Skip to content

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

model-apps 2.18.0: bundled SDK update, pages-only apps, page bindings in the spec, Custom API discovery by default, stopped-build recovery, a wider token guard (#763)

Akshay Maloo6ff5c6f3d4bb
diff --git a/evals/model-apps/genpage/EVAL_GUIDE.md b/evals/model-apps/genpage/EVAL_GUIDE.md
index 5e3357990..4f8d18557 100644
--- a/evals/model-apps/genpage/EVAL_GUIDE.md
+++ b/evals/model-apps/genpage/EVAL_GUIDE.md
@@ -76,6 +76,9 @@ Layers 1 and 2 are automated. Layer 3 is human judgment by design — visual qua
- Current upload commands use `genpage-upload.js` with file transport; the preservation fixture compares exact approved/forwarded text and before/after name, model and binding sets. `--app-id` is optional for a create — the first page of a new app has none, and no `--add-to-sitemap` — while a create that names an app includes `--add-to-sitemap`, and an update names its app and omits it (the update that completes a create that did not finish is the exception). `forwarded` records what the script hands the page backend: a flag an update leaves out forwards nothing, so the page keeps its own name, model and data sources, and a name with a straight `"`, a `%` or a `$(…)` is stored exactly
- A divergence refusal (`no-base`, `deployed-changed`, `deployed-unreadable`) stops an update before the page backend writes (`ok: false`, no write, no forwarded args). `--overwrite-deployed` needs the `Choice:` line that upload command consumes to be exactly `Choice: Overwrite the deployed changes`. Each `genpage-upload.js` line consumes the pending choice, so one approval does not cover a later upload
- Custom API discovery/gates/bindings/runtime/update stages agree; optional packaging names every deployed page and preserves failures/read-back evidence
+ When successful downloads are recorded, before-page evidence needs one identifiable producing output
+ directory. Environment/app checks use that producer, not unrelated same-ID downloads elsewhere;
+ unmatched or ambiguous producers refuse preservation rather than guessing a historical source.
- Prefix discipline holds across plan, entity-creation log, and resolved names
- Per-eval discovery, provisioning, schema and deployment expectations compare structured evidence read by `lib/expectation-evidence.js` — `list-tables`/`list-languages`/the type generator/upload flags and their recorded results, the plan's entity blocks, the entity-creation transactions, and the choice enums in the captured `RuntimeTypes.ts` — on either upload transport. The plugin's own scripts are read as data: `scripts/list-tables.js` (a table exists when `tables` holds its exact logical name; `missing` names the terms with none; a failed read confirms nothing), `scripts/apps.js list` (`apps`), `scripts/genpage.js list` (`pages`, each with its `pageId` and `name`) and `scripts/list-languages.js` (`languages`; it is the only source, so a failed read detects nothing and a `pac model list-languages` after it is not credited). The type generator is `scripts/genpage.js types` and the edit flow's download `scripts/genpage.js download`; a capture made before the scripts records the `pac model list-tables`, `pac model list`, `pac model list-languages`, `pac model genpage list | download | generate-types` forms, and those are read too. The new-app expectations (eval 8) require the plugin's order: the first page uploaded with no app and no `--add-to-sitemap`, then `apps.js create --solution --page-id --publish` (which pins the first page's tables itself, so nothing has to follow it), and every upload after it naming the app it returned — `pac model create` does not satisfy them. These recognizers read a script's verb the way the mutation checks do, so a verb after its flags (`genpage.js --env <url> types …`) counts, and a "types … SKIPPED (mock data)" expectation fails for a run that generated types that way. A listing recorded as the JSON the scripts print — one line, as a parsed result, as text, or as a log's `Result: {…}` line — is read as data (`id`/`pageId`/`appId` and `name`); JSON that does not parse lists nothing, and only output that is not JSON (a PAC table, a log's bullets) goes to the older table reader
@@ -106,6 +109,13 @@ Layers 1 and 2 are automated. Layer 3 is human judgment by design — visual qua
Plus per-eval `expectations` for **Phase 5, 5a, 5b and 5c**. `Edit Phase 5` entries remain Layer-1 expectations. The registered Phase-5b column checker now executes; its existing `column-name verification requires RuntimeTypes.ts fixture` SKIP is explicit, not silently excluded by routing. Column/schema verification itself remains unimplemented. Other unregistered/AST-dependent expectations are reported as skips, not claimed as coverage. The API request scorer supports literal request objects in named helpers and scalar annotations; it is not a TypeScript compiler or a runtime execution oracle.
+**Bounded Custom API declaration tracking (Layers 1 and 2):** Potential-write checks
+distinguish a definite plain arrow parameter declaration, including a default, from an
+unrelated outer variable with the same name. Arrow values and callers remain opaque; this
+does not prove lookup input values or relax receiver/RHS checks. Ambiguous binding patterns
+retain conservative outer-write possibilities, and actual writes to the selected input
+still refuse lookup provenance.
+
**Runner:** `evals/model-apps/genpage/run-layer-2.js`
**Library:** `lib/assertions-layer-2.js`
diff --git a/evals/model-apps/genpage/lib/custom-api-contract.js b/evals/model-apps/genpage/lib/custom-api-contract.js
index a8b1e67a2..dd5611bdc 100644
--- a/evals/model-apps/genpage/lib/custom-api-contract.js
+++ b/evals/model-apps/genpage/lib/custom-api-contract.js
@@ -6,8 +6,10 @@ const { pageStructureProblems } = require('../../../../plugins/model-apps/script
const { workflowCalls, isGeneration, isUpload, isMutation, resultObject, unassociatedCallProblems } = require('./workflow-evidence.js');
const { artifactText, artifactJson, commandInfo, fileName, isGuid, pathKey } = require('./evidence-utils.js');
const { planSection, parseMarkdownRows } = require('./plan-evidence.js');
-const { actionCalls, literalString, objectFields, receiverIsDataApi, escapeRe } = require('./source-evidence.js');
-const { desiredBindings, sameBindings } = require('./upload-contract.js');
+const { actionCalls, literalString, objectFields, receiverIsDataApi, stringRecordMemberIsInput, escapeRe } = require('./source-evidence.js');
+const {
+ desiredBindings, sameBindings, uploadResultIdentityMatches, beforePageIdentityProblems, sameRecordedEnvironment,
+} = require('./upload-contract.js');
const KINDS = new Set(Object.values(PARAMETER_KIND_BY_TYPE));
const isGate = (command) => /\bfeature-flags\.js\b[^\n]*\bcustom-api\b/.test(command);
@@ -39,16 +41,38 @@ function planBindings(fixture) {
}
function projectBinding(entry) {
- if (!entry || typeof entry.name !== 'string' || typeof entry.isFunction !== 'boolean' || !entry.displayName
- || !entry.parameterKinds || Object.values(entry.parameterKinds).some((kind) => !KINDS.has(kind))) {
+ if (!entry || typeof entry.name !== 'string' || typeof entry.isFunction !== 'boolean'
+ || typeof entry.displayName !== 'string' || !entry.displayName
+ || !entry.parameterKinds || typeof entry.parameterKinds !== 'object' || Array.isArray(entry.parameterKinds)
+ || Object.values(entry.parameterKinds).some((kind) => !KINDS.has(kind))) {
throw new Error('discovered/bound API is missing its name, kind, display name or parameter kinds');
}
if (entry.bindingType && !['Global', 'Entity'].includes(entry.bindingType)) throw new Error('collection-bound API is not a supported record binding');
if (entry.bindingType === 'Global' && entry.boundEntityLogicalName) throw new Error('global API incorrectly declares a bound entity');
+ if (entry.boundEntityLogicalName !== undefined
+ && (typeof entry.boundEntityLogicalName !== 'string' || !entry.boundEntityLogicalName)) {
+ throw new Error('bound API has an unreadable bound entity');
+ }
return { name: entry.name, isFunction: entry.isFunction, displayName: entry.displayName, parameterKinds: entry.parameterKinds,
...(entry.boundEntityLogicalName && { boundEntityLogicalName: entry.boundEntityLogicalName }) };
}
+function discoveredLookupParameters(entry) {
+ const lookups = entry.lookupParameters;
+ if (lookups === undefined) return {};
+ if (!lookups || typeof lookups !== 'object' || Array.isArray(lookups)) {
+ throw new Error(`${entry.name}: unreadable discovery-only lookup parameters`);
+ }
+ for (const [name, lookup] of Object.entries(lookups)) {
+ if (!name || Object.hasOwn(entry.parameterKinds, name) || !lookup || typeof lookup !== 'object'
+ || Array.isArray(lookup) || typeof lookup.isOptional !== 'boolean'
+ || (lookup.logicalEntityName !== undefined && (typeof lookup.logicalEntityName !== 'string' || !lookup.logicalEntityName))) {
+ throw new Error(`${entry.name}.${name}: unreadable discovery-only lookup metadata`);
+ }
+ }
+ return lookups;
+}
+
function customApiGateProblems(fixture) {
const bindings = planBindings(fixture);
const calls = workflowCalls(fixture);
@@ -88,10 +112,39 @@ function parameterMatches(value, kind, prefix) {
if (kind === 'Boolean') return /^(true|false)$/.test(value) || annotation === 'boolean';
if (kind === 'DateTime') return annotation === 'Date' || (literal !== null && /^\d{4}-\d\d-\d\dT/.test(literal));
if (kind === 'StringArray') return annotation === 'string[]';
- return value.trim().startsWith('{') || (kind === 'EntityCollection' && value.trim().startsWith('['));
+ return false;
+}
+
+function existingRecordId(value, prefix, call) {
+ if (literalString(value) !== null) return false;
+ return (/^[\w$]+$/.test(value) && parameterMatches(value, 'Guid', prefix))
+ || Boolean(call && stringRecordMemberIsInput(call.mask, call.scopes, value, call.start));
+}
+
+function lookupParameterProblems(parameters, lookups, operation, prefix, call) {
+ const problems = [];
+ for (const [name, lookup] of Object.entries(lookups)) {
+ if (!parameters.has(name)) {
+ if (!lookup.isOptional) problems.push(`${operation}.${name}: required discovered lookup input is missing`);
+ continue;
+ }
+ let fields;
+ try { fields = objectFields(parameters.get(name)); }
+ catch { problems.push(`${operation}.${name}: lookup must be the structural { entityName, id } object`); continue; }
+ const entity = literalString(fields.get('entityName') || '');
+ if (fields.size !== 2 || !entity || !fields.has('id')) {
+ problems.push(`${operation}.${name}: lookup must have exactly entityName and id`);
+ } else if (lookup.logicalEntityName && entity !== lookup.logicalEntityName) {
+ problems.push(`${operation}.${name}: lookup table disagrees with discovery`);
+ }
+ if (!existingRecordId(fields.get('id') || '', prefix, call)) {
+ problems.push(`${operation}.${name}: lookup id must come from string-typed existing page input, never an invented or numeric id`);
+ }
+ }
+ return problems;
}
-function runtimeProblems(code, bindings, declaredOutputs) {
+function runtimeProblems(code, bindings, declaredOutputs, lookupMetadata) {
const problems = pageStructureProblems(code);
const calls = actionCalls(code);
const known = new Map(bindings.map((binding) => [binding.name, binding]));
@@ -115,17 +168,25 @@ function runtimeProblems(code, bindings, declaredOutputs) {
const match = presence.exec(prefixMask);
if (!match || !/^['"]function['"]/.test(prefix.slice(match.index + match[0].length - 1))) problems.push(`${name}: method is not presence-checked on the same receiver in its helper before the call`);
const parameters = call.fields.has('parameters') ? objectFields(call.fields.get('parameters')) : new Map();
- if ([...parameters.keys()].sort().join('|') !== Object.keys(binding.parameterKinds).sort().join('|')) problems.push(`${name}: runtime parameter names differ from the declared kinds`);
+ // Sparse declared kinds do not enumerate lookup inputs. Use discovery-only metadata to allow
+ // their names and enforce required lookups without persisting structural kinds in the binding.
+ const lookups = lookupMetadata.get(name) || {};
+ const allowed = new Set([...Object.keys(binding.parameterKinds), ...Object.keys(lookups)]);
+ if ([...parameters.keys()].some((parameter) => !allowed.has(parameter))
+ || Object.keys(binding.parameterKinds).some((parameter) => !parameters.has(parameter))) {
+ problems.push(`${name}: runtime parameter names differ from the declared kinds and discovered lookups`);
+ }
for (const [parameter, kind] of Object.entries(binding.parameterKinds)) {
if (!parameterMatches(parameters.get(parameter) || '', kind, prefix)) problems.push(`${name}.${parameter}: runtime value does not match ${kind}`);
}
+ problems.push(...lookupParameterProblems(parameters, lookups, name, prefix, call));
if (binding.boundEntityLogicalName) {
if (!call.fields.has('boundTo')) problems.push(`${name}: entity-bound operation omits boundTo`);
else {
const bound = objectFields(call.fields.get('boundTo'));
if (literalString(bound.get('entityName') || '') !== binding.boundEntityLogicalName) problems.push(`${name}: boundTo uses the wrong entity`);
const id = bound.get('id') || '';
- if (literalString(id) !== null || !/^[\w$.]+$/.test(id) || !parameterMatches(id, 'Guid', prefix)) {
+ if (!existingRecordId(id, prefix)) {
problems.push(`${name}: bound record id must come from string-typed existing page input, never a hard-coded GUID or numeric value`);
}
}
@@ -163,12 +224,64 @@ function customApiProblems(fixture) {
const declared = planBindings(fixture);
const calls = workflowCalls(fixture);
const discovered = new Map();
+ const lookupMetadata = new Map();
for (const call of calls.filter((entry) => /\blist-custom-apis\.js\b/.test(entry.command))) {
const result = resultObject(call);
if (result?.ok !== true || !Array.isArray(result.customApis)) problems.push('Custom API discovery failed or returned unreadable metadata');
- else for (const entry of result.customApis) discovered.set(entry.name, projectBinding(entry));
+ else for (const entry of result.customApis) {
+ discovered.set(entry.name, projectBinding(entry));
+ lookupMetadata.set(entry.name, discoveredLookupParameters(entry));
+ }
+ }
+ const beforeByStage = new Map();
+ const verifiedBefore = new Set();
+ const producedConfigs = new Map();
+ for (const stage of contract.stages) {
+ const uploads = calls.filter((entry) => entry.id === stage.upload && isUpload(entry.command));
+ const call = uploads.length === 1 ? uploads[0] : null;
+ const flags = call ? commandInfo(call).flags : {};
+ const result = call ? resultObject(call) : null;
+ if (stage.beforeConfig) {
+ const config = artifactJson(fixture, stage.beforeConfig);
+ const before = config.actionBindings === undefined ? [] : config.actionBindings;
+ desiredBindings(before, undefined, 'name');
+ for (const binding of before) projectBinding(binding);
+ beforeByStage.set(stage, before);
+ const identityProblems = [];
+ if (!call || !flags['page-id'] || result?.ok !== true || !uploadResultIdentityMatches(flags, result)) {
+ identityProblems.push(`${stage.id}: before-config preservation requires an unambiguous existing update target`);
+ }
+ const rows = fixture.manifest?.uploads;
+ if (rows !== undefined) {
+ const associated = Array.isArray(rows) ? rows.filter((row) => row.event === stage.upload) : [];
+ if (associated.length !== 1) {
+ identityProblems.push(`${stage.id}: before-page identity evidence has no unique upload association`);
+ } else if (call) {
+ identityProblems.push(...beforePageIdentityProblems(fixture, associated[0], call, stage.beforeConfig, stage.afterConfig));
+ }
+ } else {
+ // A prior successful lifecycle stage can associate its exact read-back snapshot with its
+ // result identity. A first-stage arbitrary artifact path cannot establish page ownership.
+ const prior = producedConfigs.get(pathKey(stage.beforeConfig));
+ if (!prior || prior.pageId !== flags['page-id'] || prior.appId !== flags['app-id']) {
+ identityProblems.push(`${stage.id}: before-config lacks same-page/app identity provenance`);
+ } else if (prior.env !== undefined && !sameRecordedEnvironment(prior.env, flags.env)) {
+ identityProblems.push(`${stage.id}: before-config environment differs from the update target`);
+ }
+ }
+ problems.push(...identityProblems);
+ if (!identityProblems.length) verifiedBefore.add(stage);
+ }
+ if (call && result?.ok === true && uploadResultIdentityMatches(flags, result)) {
+ producedConfigs.set(pathKey(stage.afterConfig), { pageId: result.pageId, appId: result.appId, env: flags.env });
+ }
+ }
+ const beforeBindings = [...verifiedBefore].flatMap((stage) => beforeByStage.get(stage));
+ for (const binding of declared) {
+ const fresh = isDeepStrictEqual(discovered.get(binding.name), binding);
+ const existing = beforeBindings.some((before) => isDeepStrictEqual(projectBinding(before), binding));
+ if (!fresh && !existing) problems.push(`${binding.name}: plan kind, bound entity or parameter kinds do not match discovery or unchanged before-config evidence`);
}
- for (const binding of declared) if (!isDeepStrictEqual(discovered.get(binding.name), binding)) problems.push(`${binding.name}: plan kind, bound entity or parameter kinds do not match discovery`);
let previousId = null;
for (const stage of contract.stages) {
const uploadIndex = calls.findIndex((call) => call.id === stage.upload);
@@ -179,7 +292,7 @@ function customApiProblems(fixture) {
if (fileName(flags['code-file']) !== stage.target || result?.ok !== true) problems.push(`${stage.id}: upload target/result does not match the generated API page`);
if (previousId && (flags['page-id'] !== previousId || result.pageId !== previousId)) problems.push(`${stage.id}: update changes the API page's identity`);
previousId = result?.pageId;
- const before = stage.beforeConfig ? artifactJson(fixture, stage.beforeConfig).actionBindings || [] : declared;
+ const before = stage.beforeConfig ? beforeByStage.get(stage) : declared;
const desired = stage.beforeConfig ? desiredBindings(before, stage.change, 'name') : declared;
if (stage.beforeConfig && stage.change === undefined && flags.actions) problems.push(`${stage.id}: unchanged APIs must omit --actions`);
if (!stage.beforeConfig || stage.change !== undefined) {
@@ -189,14 +302,20 @@ function customApiProblems(fixture) {
}
const after = artifactJson(fixture, stage.afterConfig).actionBindings;
if (!sameBindings(after, desired, 'name')) problems.push(`${stage.id}: API config read-back loses preservation or explicit-clear intent`);
+ const authoredNames = new Set((stage.change?.add || []).map((binding) => binding.name));
for (const binding of desired) {
const projected = projectBinding(binding);
- if (!isDeepStrictEqual(discovered.get(binding.name), projected)) problems.push(`${binding.name}: actions file differs from discovered metadata`);
+ const fresh = isDeepStrictEqual(discovered.get(binding.name), projected);
+ // Only an exact unchanged stage-before entry has preservation provenance. An explicit
+ // addition/replacement still needs eligible discovery, even when its name already existed.
+ const preserved = verifiedBefore.has(stage) && !authoredNames.has(binding.name)
+ && before.some((entry) => isDeepStrictEqual(entry, binding));
+ if (!fresh && !preserved) problems.push(`${binding.name}: actions file differs from discovered metadata or unchanged before-config evidence`);
}
const code = artifactText(fixture, stage.source);
const write = calls.slice(0, uploadIndex).filter((entry) => /^Write\s+/.test(entry.command) && fileName(entry.command.slice(6)) === stage.target).at(-1);
if (!write || artifactText(fixture, write.artifact) !== code) problems.push(`${stage.id}: uploaded API source is not the actual preceding generated snapshot`);
- problems.push(...runtimeProblems(code, desired, contract.outputs));
+ problems.push(...runtimeProblems(code, desired, contract.outputs, lookupMetadata));
}
const last = contract.stages.at(-1);
if (artifactText(fixture, last.target) !== artifactText(fixture, last.source)) problems.push('final API TSX differs from the final lifecycle stage');
diff --git a/evals/model-apps/genpage/lib/source-evidence.js b/evals/model-apps/genpage/lib/source-evidence.js
index b01223819..16f7723a4 100644
--- a/evals/model-apps/genpage/lib/source-evidence.js
+++ b/evals/model-apps/genpage/lib/source-evidence.js
@@ -331,6 +331,7 @@ function arrowScopes(mask) {
for (const match of mask.matchAll(/=>/g)) {
const before = mask.slice(0, match.index).replace(/\s+$/, '');
let names = [];
+ let plainNames = [];
let paramsOpen = -1;
let close = before.length - 1;
if (before[close] !== ')') {
@@ -341,16 +342,20 @@ function arrowScopes(mask) {
paramsOpen = groupStart(mask, close);
if (paramsOpen < 0) continue;
names = boundNames(mask.slice(paramsOpen + 1, close));
+ plainNames = splitTopLevel(mask, paramsOpen, close)
+ .map((param) => /^([A-Za-z_$][\w$]*)(?=\s*(?:[:=]|$))/.exec(param)?.[1]).filter(Boolean);
} else {
const single = /([A-Za-z_$][\w$]*)$/.exec(before);
if (!single || /^(?:async|await|return)$/.test(single[1])) continue;
names = [single[1]];
+ plainNames = [single[1]];
paramsOpen = before.length - single[1].length;
}
let body = match.index + 2;
while (/\s/.test(mask[body] || '')) body += 1;
const bodyEnd = mask[body] === '{' ? groupEnd(mask, body) : expressionEnd(mask, body);
- scopes.push({ arrow: true, names, paramsOpen, body: match.index, end: bodyEnd });
+ const paramsEnd = before[close] === ')' ? close : before.length;
+ scopes.push({ arrow: true, names, plainNames, paramsOpen, paramsEnd, body: match.index, end: bodyEnd });
}
// `function (…) {` and `function* (…) {` with no name: a value, so its callers are untraceable too.
for (const match of mask.matchAll(/\bfunction\s*\*?\s*\(/g)) {
@@ -358,7 +363,7 @@ function arrowScopes(mask) {
const paramsEnd = groupEnd(mask, paramsOpen);
const body = mask.indexOf('{', paramsEnd);
if (body < 0) continue;
- scopes.push({ arrow: true, names: boundNames(mask.slice(paramsOpen + 1, paramsEnd)), paramsOpen, body: paramsOpen, end: groupEnd(mask, body) });
+ scopes.push({ arrow: true, names: boundNames(mask.slice(paramsOpen + 1, paramsEnd)), paramsOpen, paramsEnd, body: paramsOpen, end: groupEnd(mask, body) });
}
return scopes;
}
@@ -367,7 +372,7 @@ function arrowScopes(mask) {
// `const { … } = …`) inside an enclosing scope or outside every scope. A binding inside a scope
// that does not enclose `at` (another helper, or the component seen from a helper outside it) is
// not visible. Several bindings at the same level must all resolve.
-function bindingsOf(ctx, name, at) {
+function bindingsOf(ctx, name, at, potentialWrite = false, parameterHeader = false) {
const { mask, scopes, component } = ctx;
const found = [];
const levelOf = (index) => {
@@ -375,9 +380,15 @@ function bindingsOf(ctx, name, at) {
if (!scope) return -1;
return scope.body < at && scope.end > at ? scope.body : null;
};
- for (const scope of scopes.filter((entry) => entry.body < at && entry.end > at)) {
+ // A parameter default (`record = props.selectedAccount`) is before its body but binds
+ // that same parameter. Include it only when identifying an assignment LHS, not its RHS or
+ // ordinary value/receiver proof. Header visibility uses the list position so nested scopes win.
+ for (const scope of scopes.filter((entry) => (entry.body < at && entry.end > at)
+ || (parameterHeader && potentialWrite && !entry.isComponent && entry.paramsOpen < at && entry.paramsEnd > at))) {
+ const level = scope.body < at ? scope.body : scope.paramsOpen;
if (scope.arrow) {
- if (scope.names.includes(name)) found.push({ level: scope.body, kind: 'opaque' });
+ if (scope.names.includes(name)) found.push({ level, kind: 'opaque', at: scope.paramsOpen, scope,
+ definiteParameter: scope.plainNames?.includes(name) === true });
continue;
}
if (scope.isComponent) {
@@ -393,13 +404,13 @@ function bindingsOf(ctx, name, at) {
splitTopLevel(mask, scope.paramsOpen, scope.paramsEnd).forEach((param, index) => {
const plain = param.startsWith('...') ? null : /^([A-Za-z_$][\w$]*)/.exec(param);
if (plain) {
- if (plain[1] === name) found.push({ level: scope.body, kind: 'param', scope, index, name });
+ if (plain[1] === name) found.push({ level, kind: 'param', scope, index, name });
return;
}
const pattern = /^\{([^{}]*)\}/.exec(param);
const property = pattern ? destructuredNames(pattern[1]).get(name) : undefined;
- if (property) found.push({ level: scope.body, kind: 'param-member', scope, index, name, property });
- else if (boundNames(param).includes(name)) found.push({ level: scope.body, kind: 'opaque' });
+ if (property) found.push({ level, kind: 'param-member', scope, index, name, property });
+ else if (boundNames(param).includes(name)) found.push({ level, kind: 'opaque', scope, index });
});
}
for (const match of mask.matchAll(new RegExp(`\\b(?:const|let|var)\\s+${escapeRe(name)}\\s*(?::[^=;]+)?=`, 'g'))) {
@@ -407,20 +418,23 @@ function bindingsOf(ctx, name, at) {
if (level === null) continue;
// The whole initializer must pass the value on: `const a = dataApi && other` is not `dataApi`.
const expr = identityChain(initializerText(mask, match.index + match[0].length));
- found.push(expr ? { level, kind: 'alias', expr, at: match.index } : { level, kind: 'opaque' });
+ found.push(expr ? { level, kind: 'alias', expr, at: match.index } : { level, kind: 'opaque', at: match.index });
}
for (const match of mask.matchAll(/\b(?:const|let|var)\s*\{([^{}]*)\}\s*(?::[^=;]+)?=/g)) {
const property = destructuredNames(match[1]).get(name);
const level = property ? levelOf(match.index) : null;
if (level === null) continue;
const object = identityChain(initializerText(mask, match.index + match[0].length));
- found.push(object ? { level, kind: 'member', object, property, at: match.index } : { level, kind: 'opaque' });
+ found.push(object ? { level, kind: 'member', object, property, at: match.index } : { level, kind: 'opaque', at: match.index });
}
if (!found.length) return [];
const innermost = Math.max(...found.map((binding) => binding.level));
const visible = found.filter((binding) => binding.level === innermost);
// A name assigned again after its declaration (or a parameter overwritten in its helper) proves nothing.
- return reassigned(mask, name) ? visible.map((binding) => ({ ...binding, kind: 'opaque' })) : visible;
+ // Write tracking keeps potential identities even after a rebind: an earlier alias may still
+ // hold the original object. This over-approximation is used only to refuse member provenance;
+ // the ordinary binding/receiver proof keeps its existing fail-closed rebinding behavior.
+ return !potentialWrite && reassigned(mask, name) ? visible.map((binding) => ({ ...binding, kind: 'opaque' })) : visible;
}
// A helper parameter is what its callers pass. A recursive call that passes the same PLAIN parameter on
@@ -475,7 +489,7 @@ function isDataApi(ctx, expr, at, depth = 0) {
// where <props> is the page component's props parameter, a name destructured from those props or
// assigned from such a name (casts allowed), or a parameter of an enclosing helper that every
// outside call fills with one of those. Anything unresolvable fails.
-function receiverIsDataApi(mask, scopes, expr, at) {
+function sourceContext(mask, scopes) {
const component = pageComponent(mask, scopes);
const named = component
? [...scopes.filter((scope) => scope.paramsOpen !== component.scope.paramsOpen), component.scope]
@@ -483,6 +497,164 @@ function receiverIsDataApi(mask, scopes, expr, at) {
// The component itself may be an arrow; it is already in the list as the component scope.
const arrows = arrowScopes(mask).filter((scope) => !component || scope.paramsOpen !== component.scope.paramsOpen);
const all = [...named, ...arrows];
- return isDataApi({ mask, scopes: all, component }, expr, at);
+ return { mask, scopes: all, component };
+}
+
+function receiverIsDataApi(mask, scopes, expr, at) {
+ return isDataApi(sourceContext(mask, scopes), expr, at);
+}
+
+// Resolve only the identity-preserving forms already understood by the shared evidence reader.
+// Parameters keep a local identity and their recognized caller identities so writes through a
+// named helper or alias cannot conceal a changed member. Opaque expressions establish no identity.
+function identityPaths(ctx, expr, at, depth = 0) {
+ if (!expr || depth > 8) return [];
+ const chain = identityChain(expr);
+ if (!chain) return [];
+ const [name, ...members] = normalizeChain(chain).split('.');
+ const append = (paths, parts = []) => paths.map((entry) => ({ root: entry.root, parts: [...entry.parts, ...parts, ...members] }));
+ const bindings = bindingsOf(ctx, name, at, true);
+ const bindingKey = (binding) => JSON.stringify(binding.scope
+ ? [binding.kind, binding.scope.paramsOpen, binding.index, binding.property]
+ : [binding.kind, binding.level, binding.at, binding.property]);
+ const bindingKeys = new Set(bindings.map(bindingKey));
+ const paths = bindings.flatMap((binding) => {
+ if (binding.kind === 'props') return append([{ root: `props:${ctx.component.scope.paramsOpen}`, parts: [] }]);
+ if (binding.kind === 'prop-member') return append([{ root: `props:${ctx.component.scope.paramsOpen}`, parts: [] }], [binding.property]);
+ if (binding.kind === 'alias') return append(identityPaths(ctx, binding.expr, binding.at, depth + 1));
+ if (binding.kind === 'member') return append(identityPaths(ctx, binding.object, binding.at, depth + 1), [binding.property]);
+ if (binding.kind === 'param' || binding.kind === 'param-member') {
+ const { scope, index } = binding;
+ const local = [{ root: `param:${scope.paramsOpen}:${index}`, parts: [] }];
+ const callers = callSites(ctx.mask, scope.name).filter((site) => !(site.at > scope.body && site.at < scope.end
+ && identityChain(site.args[index] || '') === name));
+ const incoming = callers.flatMap((site) => identityPaths(ctx, site.args[index], site.at, depth + 1));
+ return append([...local, ...incoming], binding.kind === 'param-member' ? [binding.property] : []);
+ }
+ return [];
+ });
+ // A reassigned writer may acquire the input after its initializer. Union recognized RHS
+ // identities only for that resolved scope/declaration/parameter, not another scope's `record`.
+ // Even opaque bindings retain their declaration position; this adds no value or receiver proof.
+ const assignments = new RegExp(`(?<![\\w$.])${escapeRe(name)}\\s*(?:\\?\\?|\\|\\||&&)?=(?![=>])`, 'g');
+ for (const assignment of ctx.mask.matchAll(assignments)) {
+ if (/\b(?:const|let|var)\s+$/.test(ctx.mask.slice(Math.max(0, assignment.index - 12), assignment.index))) continue;
+ const assigned = bindingsOf(ctx, name, assignment.index, true, true);
+ // Opaque patterns over-approximate names: `{ other = (outer = input) }` can assign an
+ // enclosing `outer`, not declare a parameter. Keep the original body-only possibilities
+ // too; ambiguity may refuse provenance but must never silently discard a possible write.
+ // A plain arrow parameter definitely declares its own name even though value/caller
+ // evidence stays opaque. It cannot assign a same-named outer variable in its header;
+ // only genuinely ambiguous patterns need the body-only outer possibilities.
+ const opaqueHeader = assigned.some((binding) => binding.kind === 'opaque' && !binding.definiteParameter && binding.scope
+ && binding.scope.paramsOpen < assignment.index && binding.scope.paramsEnd > assignment.index);
+ const outsideHeader = opaqueHeader ? bindingsOf(ctx, name, assignment.index, true) : null;
+ const possible = outsideHeader ? [...assigned, ...outsideHeader] : assigned;
+ // Two unresolved references may still share an outer binding. Retain that potential write only
+ // for conservative refusal, never as authorization of an input value or API receiver.
+ const sameBinding = bindingKeys.size ? possible.some((binding) => bindingKeys.has(bindingKey(binding)))
+ : (outsideHeader || assigned).length === 0;
+ if (!sameBinding) continue;
+ const rhs = identityChain(initializerText(ctx.mask, assignment.index + assignment[0].length));
+ if (rhs && normalizeChain(rhs) !== name) paths.push(...append(identityPaths(ctx, rhs, assignment.index, depth + 1)));
+ }
+ return [...new Map(paths.map((entry) => [JSON.stringify(entry), entry])).values()];
+}
+
+function memberWriteTargets(mask) {
+ const candidates = [];
+ const writes = [];
+ for (const match of mask.matchAll(/(?<![\w$.])([A-Za-z_$][\w$]*)/g)) {
+ const parts = [];
+ let end = match.index + match[0].length;
+ while (end < mask.length) {
+ const member = /^\s*\.\s*([A-Za-z_$][\w$]*)/.exec(mask.slice(end));
+ if (member) { parts.push(member[1]); end += member[0].length; continue; }
+ const bracket = /^\s*\[/.exec(mask.slice(end));
+ if (!bracket) break;
+ const open = end + bracket[0].length - 1;
+ end = groupEnd(mask, open) + 1;
+ // Strings are masked, and a computed member may name the used field: refuse rather than guess.
+ parts.push('*');
+ }
+ if (!parts.length) continue;
+ const target = { expr: match[1], parts, at: match.index, end };
+ candidates.push(target);
+ const tail = mask.slice(end);
+ const prefix = mask.slice(0, match.index);
+ if (/^\s*(?:(?:\*\*|<<|>>>?|&&|\|\||\?\?|[-+*/%&|^])?=(?![=>])|\+\+|--)/.test(tail)
+ || /\bdelete\s*$|\+\+\s*$|--\s*$/.test(prefix)
+ || (/\bfor\s*\(\s*$/.test(prefix) && /^\s+(?:of|in)\b/.test(tail))) writes.push(target);
+ }
+ // Destructuring assignments can write a member without an adjacent '=': ({ id: record.id } = x).
+ for (const match of mask.matchAll(/[\]}]\s*=(?![=>])/g)) {
+ const open = groupStart(mask, match.index);
+ if (open < 0 || /\b(?:const|let|var)\s*$/.test(mask.slice(Math.max(0, open - 8), open))) continue;
+ writes.push(...candidates.filter((entry) => entry.at > open && entry.end <= match.index));
+ }
+ for (const match of mask.matchAll(/\b(?:Object\s*\.\s*(?:assign|defineProperty|defineProperties|setPrototypeOf)|Reflect\s*\.\s*(?:set|defineProperty|deleteProperty|setPrototypeOf))\s*\(/g)) {
+ const open = match.index + match[0].lastIndexOf('(');
+ const close = groupEnd(mask, open);
+ const target = splitTopLevel(mask, open, close)[0];
+ if (target) writes.push({ expr: target, parts: [], at: match.index });
+ }
+ return writes;
}
-module.exports = { groupEnd, literalString, objectFields, actionCalls, receiverIsDataApi, escapeRe };
+
+function recordValueWritten(ctx, expr, at) {
+ const roots = identityPaths(ctx, expr, at);
+ if (!roots.length) return true;
+ const writes = ctx.memberWrites || (ctx.memberWrites = memberWriteTargets(ctx.mask));
+ return writes.some((write) => identityPaths(ctx, write.expr, write.at).some((entry) => {
+ const changed = { root: entry.root, parts: [...entry.parts, ...write.parts] };
+ return roots.some((root) => root.root === changed.root
+ && root.parts.slice(0, Math.min(root.parts.length, changed.parts.length))
+ .every((part, index) => part === '*' || changed.parts[index] === '*' || part === changed.parts[index]));
+ }));
+}
+
+function recordPropInput(ctx, expr, at, depth = 0) {
+ if (!expr || depth > 8) return false;
+ const chain = identityChain(expr);
+ const name = chain ? normalizeChain(chain) : null;
+ if (!name) return false;
+ if (recordValueWritten(ctx, name, at)) return false;
+ const direct = /^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/.exec(name);
+ if (direct) return isPropsObject(ctx, direct[1], at, depth + 1);
+ if (!IDENT.test(name)) return false;
+ const bindings = bindingsOf(ctx, name, at);
+ return bindings.length > 0 && bindings.every((binding) => {
+ if (binding.kind === 'prop-member') return true;
+ if (binding.kind === 'param') return paramFilledWith(ctx, binding, depth, recordPropInput);
+ if (binding.kind === 'alias') return recordPropInput(ctx, binding.expr, binding.at, depth + 1);
+ if (binding.kind === 'member') return isPropsObject(ctx, binding.object, binding.at, depth + 1);
+ return false;
+ });
+}
+
+// The bounded member form is a named helper's explicit record input, e.g.
+// `selectedAccount: { accountid: string }` supplied from the page's props. A local fabricated
+// record, an opaque type alias or an arbitrary chain is not evidence that an ID came from an input.
+function stringRecordMemberIsInput(mask, scopes, expr, at) {
+ const member = /^([A-Za-z_$][\w$]*)\s*\.\s*([A-Za-z_$][\w$]*)$/.exec(expr.trim());
+ if (!member) return false;
+ const ctx = sourceContext(mask, scopes);
+ // Conservatively refuse recognized writes anywhere on these value paths, including aliased
+ // helpers declared later in the module. This is not an execution-order or general heap evaluator.
+ if (recordValueWritten(ctx, member[1], at)) return false;
+ const bindings = bindingsOf(ctx, member[1], at);
+ return bindings.length > 0 && bindings.every((binding) => {
+ if (binding.kind !== 'param') return false;
+ const parameter = splitTopLevel(mask, binding.scope.paramsOpen, binding.scope.paramsEnd)[binding.index];
+ const annotation = new RegExp(`^${escapeRe(member[1])}\\s*:\\s*(\\{[\\s\\S]*\\})$`).exec(parameter);
+ if (!annotation) return false;
+ try {
+ // Flat inline type members use the same literal-name grammar as request objects. TypeScript
+ // allows semicolons between members; no value/source code is evaluated to infer their types.
+ if (objectFields(annotation[1].replace(/;/g, ',')).get(member[2]) !== 'string') return false;
+ } catch { return false; }
+ return paramFilledWith(ctx, binding, 0, recordPropInput);
+ });
+}
+
+module.exports = { groupEnd, literalString, objectFields, actionCalls, receiverIsDataApi, stringRecordMemberIsInput, escapeRe };
diff --git a/evals/model-apps/genpage/lib/upload-contract.js b/evals/model-apps/genpage/lib/upload-contract.js
index 0767814d6..931805b7a 100644
--- a/evals/model-apps/genpage/lib/upload-contract.js
+++ b/evals/model-apps/genpage/lib/upload-contract.js
@@ -1,8 +1,9 @@
'use strict';
const { isDeepStrictEqual } = require('node:util');
+const path = require('node:path');
const { currentContract, workflowCalls, isUpload, isObject, resultObject, unassociatedCallProblems } = require('./workflow-evidence.js');
-const { artifactText, artifactJson, commandInfo, isGuid } = require('./evidence-utils.js');
+const { artifactText, artifactJson, commandInfo, isGuid, scriptRuns, pathKey } = require('./evidence-utils.js');
const sameJson = (left, right) => isDeepStrictEqual(JSON.parse(JSON.stringify(left)), JSON.parse(JSON.stringify(right)));
const switchOn = (value) => value === true || value === 'true';
@@ -86,6 +87,112 @@ function sameBindings(left, right, idKey) {
return sameJson(bindingSet(left, idKey), bindingSet(right, idKey));
}
+function uploadResultIdentityMatches(flags, result) {
+ return isGuid(result?.pageId) && result.appId === flags['app-id']
+ && (!flags['page-id'] || result.pageId === flags['page-id']);
+}
+
+function pageIdentityProblems(event, flags, result, beforePage, afterPage, update) {
+ const problems = [];
+ if (afterPage.pageId !== result?.pageId || afterPage.appId !== result?.appId) {
+ problems.push(`${event}: read-back identity differs from the upload result`);
+ }
+ if (update && (beforePage.pageId !== flags['page-id'] || beforePage.appId !== flags['app-id'])) {
+ problems.push(`${event}: update does not target the downloaded page in its app`);
+ }
+ return problems;
+}
+
+function sameRecordedEnvironment(left, right) {
+ try { return typeof left === 'string' && typeof right === 'string' && new URL(left).origin === new URL(right).origin; }
+ catch { return false; }
+}
+
+// A repeated page ID does not identify a snapshot's source. The recorded destination associates
+// `--output-directory before` with `before/page.json` or `before/<pageId>/page.json`, not a sibling
+// `before-other/`. These are archive paths: normalize separators/dot segments, never inspect the
+// filesystem or infer a working directory. null means the source cannot be associated safely.
+function downloadContainsSnapshot(source, downloaded, snapshot) {
+ const directory = Object.hasOwn(source, 'output-directory') ? source['output-directory'] : downloaded.outputDirectory;
+ if (typeof directory !== 'string' || !directory.trim() || typeof snapshot !== 'string' || !snapshot.trim()) return null;
+ const folder = path.posix.normalize(pathKey(directory));
+ const file = path.posix.normalize(pathKey(snapshot));
+ if (folder === '.') return file !== '.' && file !== '..' && !file.startsWith('../')
+ && !path.posix.isAbsolute(file) && !/^[A-Za-z]:/.test(file);
+ return file.startsWith(`${folder.replace(/\/+$/, '')}/`);
+}
+
+// This is the identity slice of the upload contract, not the optional full upload assertion.
+// A binding-preservation consumer must call it itself before treating a before blob as authority.
+function beforePageIdentityProblems(fixture, row, call, beforeConfig, afterConfig) {
+ const event = call.id;
+ const { flags } = commandInfo(call);
+ const result = resultObject(call);
+ const problems = [];
+ if (row.mode !== 'update' || !isGuid(flags['page-id'])) {
+ problems.push(`${event}: before-config preservation requires an existing update page target`);
+ }
+ if (row.beforeConfig !== beforeConfig || row.afterConfig !== afterConfig) {
+ problems.push(`${event}: before-config identity evidence is associated with another snapshot`);
+ }
+ if (result?.ok !== true || !uploadResultIdentityMatches(flags, result)) {
+ problems.push(`${event}: upload result does not preserve the requested page/app identity`);
+ }
+ const beforePage = artifactJson(fixture, row.beforePage);
+ const afterPage = artifactJson(fixture, row.afterPage);
+ if (!isObject(beforePage) || !isObject(afterPage)) throw new Error(`${event}: before/after page identity evidence must be objects`);
+ problems.push(...pageIdentityProblems(event, flags, result, beforePage, afterPage, true));
+ const calls = workflowCalls(fixture);
+ const earlier = calls.slice(0, calls.findIndex((entry) => entry.id === call.id));
+ let recordedDownloads = 0;
+ const producers = [];
+ for (const download of earlier) {
+ const runs = scriptRuns(download, 'genpage.js');
+ const downloaded = resultObject(download);
+ if (!runs.some((run) => run.verb === 'download') || downloaded?.ok !== true) continue;
+ recordedDownloads += 1;
+ if (runs.length !== 1) {
+ problems.push(`${event}: ambiguous download context cannot establish before-page provenance`);
+ continue;
+ }
+ const { flags: source } = commandInfo(download);
+ const ids = typeof source['page-id'] === 'string' ? source['page-id'].split(',').map((id) => id.trim()) : [];
+ if (!ids.includes(beforePage.pageId)) continue;
+ const associated = downloadContainsSnapshot(source, downloaded, row.beforePage);
+ if (associated === false) continue;
+ producers.push({ source, ids, downloaded, associated });
+ }
+ // A known different directory is unrelated history. An unknown destination is still a possible
+ // producer, not permission to borrow a better-looking download or guess the first/latest match.
+ if (recordedDownloads && (producers.length !== 1 || producers[0].associated !== true)) {
+ problems.push(`${event}: before-page identity has no unique associated recorded download source`);
+ return problems;
+ }
+ if (producers.length === 1) {
+ const { source, ids, downloaded } = producers[0];
+ const hasPages = Object.hasOwn(downloaded, 'pages');
+ // Array.from also visits unreadable holes in direct object evidence; map would skip them.
+ const returnedIds = Array.isArray(downloaded.pages)
+ ? Array.from(downloaded.pages, (page) => isObject(page) ? page.pageId : undefined) : [];
+ const establishesBeforePage = (values) => values.length > 0 && values.includes(beforePage.pageId)
+ && values.every((id) => isGuid(id) && ids.includes(id));
+ // Current downloads return pages: [{ pageId, ... }]. A present empty/malformed list
+ // contradicts the download; only genuinely absent fields retain historical shorthand.
+ // Validate a recorded scalar independently so neither shape can hide a contradiction.
+ if ((hasPages && !establishesBeforePage(returnedIds))
+ || (downloaded.pageId !== undefined && !establishesBeforePage([downloaded.pageId]))) {
+ problems.push(`${event}: recorded download result does not establish the before-page identity`);
+ }
+ if (source.env !== undefined && !sameRecordedEnvironment(source.env, flags.env)) {
+ problems.push(`${event}: before-page environment context differs from the upload target`);
+ }
+ if (source['app-id'] !== undefined && source['app-id'] !== flags['app-id']) {
+ problems.push(`${event}: before-page app context differs from the upload target`);
+ }
+ }
+ return problems;
+}
+
// The one update that is not an ordinary edit: `--page-id` naming a page that an earlier create of the SAME code file wrote and did not finish (its failure result carries the page's id;
// the publish or the placement it was asked for failed). genpage-upload.js completes it by naming it again, and then the update may carry `--add-to-sitemap` and, for a page created with no
// app, no `--app-id`. SKILL.md Phase 6, "A create that did not finish".
@@ -130,7 +237,7 @@ function uploadTransportProblems(fixture) {
if (update && (!isGuid(flags['page-id']) || (placement && !completing))) problems.push('update must name a valid page id and omit sitemap placement');
// A create that names an app places its page in it. One that names none (the first page of a new app, which apps.js create then builds the app around) has no app to place it in.
if (!update && flags['app-id'] !== undefined && !placement) problems.push('a create that names an app must include --add-to-sitemap');
- if (result?.ok && (!isGuid(result.pageId) || result.appId !== flags['app-id'] || (update && result.pageId !== flags['page-id']))) {
+ if (result?.ok && !uploadResultIdentityMatches(flags, result)) {
problems.push('upload result does not preserve the requested app/page identity');
}
// Every upload consumes its own log entry, overwriting or not, so an entry an earlier upload
@@ -205,11 +312,10 @@ function uploadProblems(fixture) {
const afterConfig = artifactJson(fixture, row.afterConfig);
const afterPage = artifactJson(fixture, row.afterPage);
if (!isObject(afterConfig) || !isObject(afterPage)) throw new Error(`${row.event}: after config/page metadata must be objects`);
- if (afterPage.pageId !== result?.pageId || afterPage.appId !== result?.appId) problems.push(`${row.event}: read-back identity differs from the upload result`);
const beforeConfig = update ? artifactJson(fixture, row.beforeConfig) : {};
const beforePage = update ? artifactJson(fixture, row.beforePage) : {};
if (!isObject(beforeConfig) || !isObject(beforePage)) throw new Error(`${row.event}: before config/page metadata must be objects`);
- if (update && (beforePage.pageId !== flags['page-id'] || beforePage.appId !== flags['app-id'])) problems.push(`${row.event}: update does not target the downloaded page in its app`);
+ problems.push(...pageIdentityProblems(row.event, flags, result, beforePage, afterPage, update));
if (update && afterPage.navigationTitle !== beforePage.navigationTitle) problems.push(`${row.event}: rename changed the untouched sitemap title`);
// The page backend stores a name exactly as it is given — a `"`, a `%` or a `$(…)` is only text — and an update that gives none keeps the page's own, so the backend is sent
@@ -268,4 +374,7 @@ function uploadPreservationProblems(fixture, mode) {
return uploadProblems(fixture);
}
-module.exports = { uploadProblems, uploadPreservationProblems, uploadTransportProblems, desiredBindings, sameBindings };
+module.exports = {
+ uploadProblems, uploadPreservationProblems, uploadTransportProblems, desiredBindings, sameBindings,
+ uploadResultIdentityMatches, pageIdentityProblems, beforePageIdentityProblems, sameRecordedEnvironment,
+};
diff --git a/evals/model-apps/genpage/tests/custom-api-lifecycle.test.js b/evals/model-apps/genpage/tests/custom-api-lifecycle.test.js
index e5c70540b..fd1bcaaa1 100644
--- a/evals/model-apps/genpage/tests/custom-api-lifecycle.test.js
+++ b/evals/model-apps/genpage/tests/custom-api-lifecycle.test.js
@@ -6,6 +6,7 @@ const path = require('node:path');
const { loadFixtures } = require('../lib/fixture-loader.js');
const { PHASE_EXPECTATIONS, WORKFLOW_ASSERTIONS } = require('../lib/assertions-layer-1.js');
const { PHASE5_EXPECTATIONS } = require('../lib/assertions-layer-2.js');
+const { actionCalls, receiverIsDataApi } = require('../lib/source-evidence.js');
const RULE = 'Phase 5: Custom API discovery, gate, bare bindings, runtime calls and update preservation or explicit clear agree';
const bindings = [
@@ -173,6 +174,71 @@ test('Custom API bindings preserve omission and only an explicit empty array cle
}
});
+function lookupFixture({ isOptional = false, supplied = true } = {}) {
+ const fixture = apiFixture();
+ event(fixture, 'discovery').result.customApis[0].lookupParameters = {
+ Ref: { isOptional, logicalEntityName: 'salesorder' },
+ };
+ fixture.genpagePlan += '\nLookup inputs (discovery-only): cnt_ApproveOrder.Ref '
+ + `is ${isOptional ? 'optional' : 'required'}; use { entityName: 'salesorder', id: recordId } `
+ + 'from the existing page record, never a declared parameter kind in actions.json.\n';
+ if (supplied) {
+ fixture.artifacts['stages/with-api.tsx'] = source.replace(
+ "parameters: { Comment: 'Approved', Amount: amount }",
+ "parameters: { Ref: { entityName: 'salesorder', id: recordId }, Comment: 'Approved', Amount: amount }"
+ );
+ }
+ return fixture;
+}
+
+test('Custom API lookup inputs are structural while authored bindings remain primitive-only', () => {
+ const fixture = lookupFixture();
+ for (const layer of [1, 2]) {
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'pass', result.reason);
+ }
+ assert.deepEqual(JSON.parse(fixture.artifacts['actions.json']), bindings);
+ for (const file of ['created/config.json', 'preserved/config.json']) {
+ assert.deepEqual(JSON.parse(fixture.artifacts[file]).actionBindings, bindings);
+ }
+});
+
+test('a required discovered lookup input cannot silently disappear from the generated call', () => {
+ const fixture = lookupFixture({ supplied: false });
+ for (const layer of [1, 2]) {
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'fail', 'the discovery-only lookup name is still a required call input');
+ assert.match(result.reason, /lookup|Ref/i);
+ }
+});
+
+test('an optional discovered lookup may be omitted or supplied in its structural shape', () => {
+ for (const supplied of [false, true]) {
+ const fixture = lookupFixture({ isOptional: true, supplied });
+ const result = score(fixture);
+ assert.equal(result.status, 'pass', result.reason);
+ }
+});
+
+test('lookup inputs must use the discovered table and an existing record rather than a primitive or invented id', () => {
+ for (const replacement of [
+ 'recordId',
+ "{ entityName: 'account', id: recordId }",
+ "{ entityName: 'salesorder' }",
+ "{ entityName: 'salesorder', id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' }",
+ "{ entityName: 'salesorder', id: amount }",
+ "{ entityName: 'salesorder', id: recordId, name: 'Invented' }",
+ 'null',
+ ]) {
+ const fixture = lookupFixture();
+ fixture.artifacts['stages/with-api.tsx'] = fixture.artifacts['stages/with-api.tsx']
+ .replace("Ref: { entityName: 'salesorder', id: recordId }", `Ref: ${replacement}`);
+ const result = score(fixture);
+ assert.equal(result.status, 'fail', replacement);
+ assert.match(result.reason, /lookup|Ref/i);
+ }
+});
+
test('disabled or unreadable Custom API gates refuse before generation, not as a no-bindings fallback', () => {
for (const result of ['disabled', 'unknown', null]) {
const stopped = apiFixture();
@@ -204,3 +270,789 @@ test('a populated plan cannot continue the audit disabled-gate probe', () => {
const enabled = { ...disabled, workflowLog: 'node feature-flags.js custom-api -> enabled\n' + captured.workflowLog };
assert.equal(check({ fixture: enabled }).status, 'pass');
});
+
+function selectedRecordLookupFixture(memberType = 'string') {
+ const fixture = lookupFixture();
+ event(fixture, 'discovery').result.customApis[0].lookupParameters.Ref.logicalEntityName = 'account';
+ fixture.genpagePlan = fixture.genpagePlan
+ .replace("entityName: 'salesorder', id: recordId", "entityName: 'account', id: selectedAccount.accountid");
+ fixture.artifacts['stages/with-api.tsx'] = fixture.artifacts['stages/with-api.tsx']
+ .replace('pending: Pending)', `pending: Pending, selectedAccount: { accountid: ${memberType} })`)
+ .replace("Ref: { entityName: 'salesorder', id: recordId }",
+ "Ref: { entityName: 'account', id: selectedAccount.accountid }")
+ .replace("approveOrder(dataApi, 'record', 1, pending)", "approveOrder(dataApi, 'record', 1, pending, props.selectedAccount)");
+ return fixture;
+}
+
+test('selected-record member lookup IDs with a proven string input pass both evaluator layers', () => {
+ const fixture = selectedRecordLookupFixture();
+ for (const layer of [1, 2]) {
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'pass', result.reason);
+ }
+});
+
+test('selected-record member lookup IDs retain type provenance table and shape refusals', async (t) => {
+ for (const [label, mutate] of [
+ ['numeric member', (fixture) => {
+ fixture.artifacts['stages/with-api.tsx'] = fixture.artifacts['stages/with-api.tsx']
+ .replace('accountid: string', 'accountid: number');
+ }],
+ ['unknown member type', (fixture) => {
+ fixture.artifacts['stages/with-api.tsx'] = fixture.artifacts['stages/with-api.tsx']
+ .replace('selectedAccount: { accountid: string }', 'selectedAccount: SelectedAccount');
+ }],
+ ['unproven member name', (fixture) => {
+ fixture.artifacts['stages/with-api.tsx'] = fixture.artifacts['stages/with-api.tsx']
+ .replace('id: selectedAccount.accountid', 'id: selectedAccount.unprovenid');
+ }],
+ ['arbitrary member chain', (fixture) => {
+ fixture.artifacts['stages/with-api.tsx'] = fixture.artifacts['stages/with-api.tsx']
+ .replace('id: selectedAccount.accountid', 'id: selectedAccount.owner.accountid');
+ }],
+ ['invented literal', (fixture) => {
+ fixture.artifacts['stages/with-api.tsx'] = fixture.artifacts['stages/with-api.tsx']
+ .replace('id: selectedAccount.accountid', "id: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'");
+ }],
+ ['invented local record', (fixture) => {
+ fixture.artifacts['stages/with-api.tsx'] = fixture.artifacts['stages/with-api.tsx']
+ .replace(', selectedAccount: { accountid: string }', '')
+ .replace(', pending, props.selectedAccount)', ', pending)')
+ .replace(" if (typeof api.executeAction", " const selectedAccount: { accountid: string } = { accountid: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' };\n if (typeof api.executeAction");
+ }],
+ ['invented caller record', (fixture) => {
+ fixture.artifacts['stages/with-api.tsx'] = fixture.artifacts['stages/with-api.tsx']
+ .replace(', pending, props.selectedAccount)', ", pending, { accountid: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' })");
+ }],
+ ['mixed record provenance across callers', (fixture) => {
+ fixture.artifacts['stages/with-api.tsx'] = fixture.artifacts['stages/with-api.tsx']
+ .replace(" void readSummary(dataApi, 'record');",
+ " void approveOrder(dataApi, 'record', 1, pending, { accountid: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' });\n void readSummary(dataApi, 'record');");
+ }],
+ ['wrong table', (fixture) => {
+ fixture.artifacts['stages/with-api.tsx'] = fixture.artifacts['stages/with-api.tsx']
+ .replace("Ref: { entityName: 'account'", "Ref: { entityName: 'contact'");
+ }],
+ ['wrong structural shape', (fixture) => {
+ fixture.artifacts['stages/with-api.tsx'] = fixture.artifacts['stages/with-api.tsx']
+ .replace("Ref: { entityName: 'account', id: selectedAccount.accountid }",
+ "Ref: { entityName: 'account', id: selectedAccount.accountid, name: 'Invented' }");
+ }],
+ ]) {
+ await t.test(`selected-record member: ${label}`, () => {
+ const fixture = selectedRecordLookupFixture();
+ mutate(fixture);
+ for (const layer of [1, 2]) {
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'fail', label);
+ assert.match(result.reason, /lookup|Ref/i, label);
+ }
+ });
+ }
+});
+
+function privateBeforePublicAddFixture() {
+ const fixture = apiFixture();
+ const existing = { ...structuredClone(bindings[0]), name: 'cnt_ExistingPrivate', displayName: 'Existing Private' };
+ const added = structuredClone(bindings[1]);
+ const desired = [existing, added];
+ const editedSource = source.replaceAll('cnt_ApproveOrder', existing.name);
+ fixture.files = [{ name: 'page.tsx', content: editedSource }];
+ fixture.artifacts = {
+ 'stages/edited.tsx': editedSource,
+ 'actions.json': JSON.stringify(desired),
+ 'before/config.json': JSON.stringify({ actionBindings: [existing] }),
+ 'after/config.json': JSON.stringify({ actionBindings: desired }),
+ 'before/page.json': JSON.stringify({
+ pageId: '99999999-9999-4999-8999-999999999999',
+ appId: '11111111-1111-4111-8111-111111111111',
+ name: 'Owned API Page', navigationTitle: 'Owned API Page',
+ }),
+ 'after/page.json': JSON.stringify({
+ pageId: '99999999-9999-4999-8999-999999999999',
+ appId: '11111111-1111-4111-8111-111111111111',
+ name: 'Owned API Page', navigationTitle: 'Owned API Page',
+ }),
+ };
+ fixture.genpagePlan = `## Custom API Bindings
+| Name | Kind | Bound Entity | Display Name | Parameters (name: kind) |
+|------|------|--------------|--------------|-------------------------|
+| ${existing.name} | Action | salesorder | Existing Private | Comment: String, Amount: Decimal |
+| ${added.name} | Function | (Global) | Summary | OrderId: Guid |
+`;
+ fixture.workflowLog = 'Edit adds a discovered public API and preserves the downloaded private binding exactly.';
+ fixture.manifest.customApi = {
+ outputs: { [existing.name]: ['NewStatus'], [added.name]: ['Total'] },
+ stages: [{
+ id: 'edit', target: 'page.tsx', source: 'stages/edited.tsx', actions: 'actions.json',
+ beforeConfig: 'before/config.json', afterConfig: 'after/config.json', upload: 'edit',
+ change: { add: [added] },
+ }],
+ };
+ // Use the shared upload identity fields to tie the before blob to this update, independently
+ // of whether its binding values happen to be equal to the desired array.
+ fixture.manifest.uploads = [{
+ event: 'edit', mode: 'update', beforeConfig: 'before/config.json', beforePage: 'before/page.json',
+ afterConfig: 'after/config.json', afterPage: 'after/page.json',
+ }];
+ fixture.events = [
+ { id: 'gate-discover', command: 'node feature-flags.js custom-api', result: 'enabled' },
+ { id: 'download', command: 'node genpage.js download --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --page-id 99999999-9999-4999-8999-999999999999 --output-directory before',
+ result: { ok: true, pages: [{ pageId: '99999999-9999-4999-8999-999999999999' }] } },
+ { id: 'discovery', command: 'node list-custom-apis.js https://contoso.crm.dynamics.com --entities salesorder',
+ result: { ok: true, customApis: [{ ...added, bindingType: 'Global' }] } },
+ { id: 'gate-generate', command: 'node feature-flags.js custom-api', result: 'enabled' },
+ { id: 'write-edit', command: 'Write page.tsx', artifact: 'stages/edited.tsx' },
+ { id: 'edit', command: 'node genpage-upload.js --env https://contoso.crm.dynamics.com --app-id 11111111-1111-4111-8111-111111111111 --page-id 99999999-9999-4999-8999-999999999999 --code-file page.tsx --actions actions.json',
+ result: { ok: true, pageId: '99999999-9999-4999-8999-999999999999', appId: '11111111-1111-4111-8111-111111111111' } },
+ ];
+ return fixture;
+}
+
+test('pre-existing private bindings are exact preservation evidence when a public API is added', () => {
+ const fixture = privateBeforePublicAddFixture();
+ for (const layer of [1, 2]) {
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'pass', result.reason);
+ }
+});
+
+test('pre-existing binding preservation never authorizes dropping changing or undiscovered additions', async (t) => {
+ for (const [label, mutate] of [
+ ['old binding dropped', (fixture) => {
+ const rows = JSON.parse(fixture.artifacts['actions.json']).slice(1);
+ fixture.artifacts['actions.json'] = JSON.stringify(rows);
+ fixture.artifacts['after/config.json'] = JSON.stringify({ actionBindings: rows });
+ }],
+ ['old primitive contract changed', (fixture) => {
+ const rows = JSON.parse(fixture.artifacts['actions.json']);
+ rows[0].parameterKinds.Amount = 'Integer';
+ fixture.artifacts['actions.json'] = JSON.stringify(rows);
+ fixture.artifacts['after/config.json'] = JSON.stringify({ actionBindings: rows });
+ }],
+ ['old method changed together with the call', (fixture) => {
+ const rows = JSON.parse(fixture.artifacts['actions.json']);
+ rows[0].isFunction = true;
+ fixture.artifacts['actions.json'] = JSON.stringify(rows);
+ fixture.artifacts['after/config.json'] = JSON.stringify({ actionBindings: rows });
+ fixture.manifest.customApi.stages[0].change.add.push(rows[0]);
+ fixture.genpagePlan = fixture.genpagePlan.replace('| cnt_ExistingPrivate | Action |', '| cnt_ExistingPrivate | Function |');
+ const nextSource = fixture.artifacts['stages/edited.tsx'].replaceAll('api.executeAction', 'api.executeFunction');
+ fixture.artifacts['stages/edited.tsx'] = nextSource;
+ fixture.files[0].content = nextSource;
+ }],
+ ['before-config provenance absent', (fixture) => {
+ delete fixture.manifest.customApi.stages[0].beforeConfig;
+ }],
+ ['explicit re-addition of the private binding', (fixture) => {
+ const existing = JSON.parse(fixture.artifacts['before/config.json']).actionBindings[0];
+ fixture.manifest.customApi.stages[0].change.add.push(existing);
+ }],
+ ...[
+ ['parameterKinds', ['String']],
+ ['isFunction', 'false'],
+ ['displayName', 7],
+ ['boundEntityLogicalName', 7],
+ ].map(([field, value]) => [`malformed before ${field}`, (fixture) => {
+ const before = JSON.parse(fixture.artifacts['before/config.json']);
+ before.actionBindings[0][field] = value;
+ fixture.artifacts['before/config.json'] = JSON.stringify(before);
+ const rows = JSON.parse(fixture.artifacts['actions.json']);
+ rows[0][field] = value;
+ fixture.artifacts['actions.json'] = JSON.stringify(rows);
+ fixture.artifacts['after/config.json'] = JSON.stringify({ actionBindings: rows });
+ }]),
+ ['new public binding not discovered', (fixture) => {
+ event(fixture, 'discovery').result.customApis = [];
+ }],
+ ['new private binding not discovered', (fixture) => {
+ const extra = { name: 'cnt_NewPrivateSummary', isFunction: true, displayName: 'New Private', parameterKinds: { OrderId: 'Guid' } };
+ fixture.manifest.customApi.stages[0].change.add.push(extra);
+ fixture.manifest.customApi.outputs[extra.name] = ['Total'];
+ const rows = JSON.parse(fixture.artifacts['actions.json']);
+ rows.push(extra);
+ fixture.artifacts['actions.json'] = JSON.stringify(rows);
+ fixture.artifacts['after/config.json'] = JSON.stringify({ actionBindings: rows });
+ fixture.genpagePlan += `| ${extra.name} | Function | (Global) | New Private | OrderId: Guid |\n`;
+ const start = source.indexOf('async function readSummary');
+ const end = source.indexOf('const GeneratedComponent');
+ const helper = source.slice(start, end)
+ .replaceAll('readSummary', 'readPrivateSummary')
+ .replaceAll('cnt_GetOrderSummary', extra.name);
+ const nextSource = fixture.artifacts['stages/edited.tsx']
+ .replace('const GeneratedComponent', helper + 'const GeneratedComponent')
+ .replace(" void readSummary(dataApi, 'record');", " void readSummary(dataApi, 'record');\n void readPrivateSummary(dataApi, 'record');");
+ fixture.artifacts['stages/edited.tsx'] = nextSource;
+ fixture.files[0].content = nextSource;
+ }],
+ ['disabled gate', (fixture) => { event(fixture, 'gate-generate').result = 'disabled'; }],
+ ['changed method on the existing operation', (fixture) => {
+ const nextSource = fixture.artifacts['stages/edited.tsx'].replace('await api.executeAction({', 'await api.executeFunction({');
+ fixture.artifacts['stages/edited.tsx'] = nextSource;
+ fixture.files[0].content = nextSource;
+ }],
+ ]) {
+ await t.test(`pre-existing binding preservation: ${label}`, () => {
+ const fixture = privateBeforePublicAddFixture();
+ mutate(fixture);
+ for (const layer of [1, 2]) {
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'fail', label);
+ if (label === 'old method changed together with the call') assert.match(result.reason, /discovery|before-config/i);
+ }
+ });
+ }
+});
+
+test('pre-existing private bindings can be removed only through an explicit clear intent', () => {
+ const fixture = privateBeforePublicAddFixture();
+ fixture.manifest.customApi.stages[0].change = { clear: true };
+ fixture.artifacts['actions.json'] = '[]';
+ fixture.artifacts['after/config.json'] = '{"actionBindings":[]}';
+ fixture.artifacts['stages/edited.tsx'] = cleared;
+ fixture.files[0].content = cleared;
+ for (const layer of [1, 2]) {
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'pass', result.reason);
+ }
+});
+
+function assertKnownApiReceivers(code) {
+ const calls = actionCalls(code);
+ assert.ok(calls.length > 0);
+ for (const call of calls) {
+ assert.equal(receiverIsDataApi(call.mask, call.scopes, call.receiver, call.start), true,
+ `${call.scope.name}: record-value evidence must not change the shared dataApi receiver proof`);
+ }
+}
+
+test('lookup member value writes and source replacements cannot retain input provenance', async (t) => {
+ const invented = "'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'";
+ const helperWrite = (text, write) => text.replace(" if (typeof api.executeAction", ` ${write}\n if (typeof api.executeAction`);
+ const callerWrite = (text, write) => text.replace(' const pending = { current: false };', ` ${write}\n const pending = { current: false };`);
+ for (const [label, mutate] of [
+ ['direct helper member write', (text) => helperWrite(text, `selectedAccount.accountid = ${invented};`)],
+ ['computed helper member write', (text) => helperWrite(text, `selectedAccount['accountid'] = ${invented};`)],
+ ['compound helper member write', (text) => helperWrite(text, "selectedAccount.accountid += 'invented';")],
+ ['helper record alias member write', (text) => helperWrite(text, `const recordAlias = selectedAccount;\n recordAlias.accountid = ${invented};`)],
+ ['explicit record mutation call', (text) => helperWrite(text, `Object.assign(selectedAccount, { accountid: ${invented} });`)],
+ ['recognized helper argument member write', (text) => helperWrite(text, 'replaceAccountId(selectedAccount);')
+ .replace('const GeneratedComponent', `function replaceAccountId(record: { accountid: string }) {\n record.accountid = ${invented};\n}\nconst GeneratedComponent`)],
+ ['captured helper alias after parameter rebinding', (text) => helperWrite(text, 'replaceAccountId(selectedAccount);')
+ .replace('const GeneratedComponent', `function replaceAccountId(record: { accountid: string }) {\n const capturedRecord = record;\n record = { accountid: 'other' };\n capturedRecord.accountid = ${invented};\n}\nconst GeneratedComponent`)],
+ ['rebound helper writer alias', (text) => helperWrite(text,
+ `let recordAlias = { accountid: 'other' };\n recordAlias = selectedAccount;\n recordAlias.accountid = ${invented};`)],
+ ['caller props record replacement', (text) => callerWrite(text, `props.selectedAccount = { accountid: ${invented} };`)],
+ ['caller computed props replacement', (text) => callerWrite(text, `props['selectedAccount'] = { accountid: ${invented} };`)],
+ ['caller props alias replacement', (text) => callerWrite(text, `const pageAlias = props;\n pageAlias.selectedAccount = { accountid: ${invented} };`)],
+ ['caller record alias member write', (text) => callerWrite(text, `const chosenAccount = props.selectedAccount;\n chosenAccount.accountid = ${invented};`)
+ .replace(', pending, props.selectedAccount)', ', pending, chosenAccount)')],
+ ['caller destructured alias member write', (text) => callerWrite(text, `const { selectedAccount: chosenAccount } = props;\n chosenAccount.accountid = ${invented};`)
+ .replace(', pending, props.selectedAccount)', ', pending, chosenAccount)')],
+ ['captured caller alias after rebinding', (text) => callerWrite(text,
+ `let record = props.selectedAccount;\n const capturedRecord = record;\n record = { accountid: 'other' };\n capturedRecord.accountid = ${invented};`)],
+ ]) {
+ await t.test(`lookup member value: ${label}`, () => {
+ const fixture = selectedRecordLookupFixture();
+ const code = mutate(fixture.artifacts['stages/with-api.tsx']);
+ fixture.artifacts['stages/with-api.tsx'] = code;
+ assertKnownApiReceivers(code);
+ for (const layer of [1, 2]) {
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'fail', `${label}, layer ${layer}`);
+ assert.match(result.reason, /lookup|Ref|provenance/i, label);
+ }
+ });
+ }
+});
+
+test('lookup member value positives retain unchanged inputs readonly aliases and receivers', async (t) => {
+ for (const [label, declaration, argument] of [
+ ['unchanged direct input', '', 'props.selectedAccount'],
+ ['record alias', 'const chosenAccount = props.selectedAccount;', 'chosenAccount'],
+ ['props alias', 'const pageAlias = props;', 'pageAlias.selectedAccount'],
+ ['destructured record alias', 'const { selectedAccount: chosenAccount } = props;', 'chosenAccount'],
+ ]) {
+ await t.test(`lookup member value positive: ${label}`, () => {
+ const fixture = selectedRecordLookupFixture();
+ const code = fixture.artifacts['stages/with-api.tsx']
+ .replace(' const pending = { current: false };', ` ${declaration}\n const pending = { current: false };`)
+ .replace(', pending, props.selectedAccount)', `, pending, ${argument})`);
+ fixture.artifacts['stages/with-api.tsx'] = code;
+ assertKnownApiReceivers(code);
+ for (const layer of [1, 2]) {
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'pass', result.reason);
+ }
+ });
+ }
+});
+
+function updateIdentityArtifact(fixture, file, changes) {
+ const value = JSON.parse(fixture.artifacts[file]);
+ fixture.artifacts[file] = JSON.stringify({ ...value, ...changes });
+}
+
+test('before-page provenance cannot authorize a different page or a successful create', async (t) => {
+ const otherPage = '22222222-2222-4222-8222-222222222222';
+ for (const associated of [false, true]) {
+ for (const mode of ['different update target', 'create']) {
+ await t.test(`before-page provenance target: ${mode}, upload association=${associated}`, () => {
+ const fixture = privateBeforePublicAddFixture();
+ if (!associated) delete fixture.manifest.uploads;
+ const upload = event(fixture, 'edit');
+ if (mode === 'create') {
+ upload.command = upload.command.replace(/ --page-id [0-9a-f-]+/, '') + ' --add-to-sitemap';
+ if (associated) fixture.manifest.uploads[0].mode = 'create';
+ } else {
+ upload.command = upload.command.replace(/ --page-id [0-9a-f-]+/, ` --page-id ${otherPage}`);
+ }
+ upload.result.pageId = otherPage;
+ updateIdentityArtifact(fixture, 'after/page.json', { pageId: otherPage });
+ for (const layer of [1, 2]) {
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'fail', `${mode}, layer ${layer}`);
+ assert.match(result.reason, /before|page|identity|provenance|target|preserv|evidence/i);
+ }
+ });
+ }
+ }
+});
+
+test('before-page provenance stays associated with recorded context and cannot be ambiguous', async (t) => {
+ const otherApp = '22222222-2222-4222-8222-222222222222';
+ for (const [label, mutate] of [
+ ['different recorded environment', (fixture) => {
+ event(fixture, 'edit').command = event(fixture, 'edit').command
+ .replace('https://contoso.crm.dynamics.com', 'https://example.crm.dynamics.com');
+ }],
+ ['different recorded app', (fixture) => {
+ const upload = event(fixture, 'edit');
+ upload.command = upload.command.replace(/ --app-id [0-9a-f-]+/, ` --app-id ${otherApp}`);
+ upload.result.appId = otherApp;
+ updateIdentityArtifact(fixture, 'after/page.json', { appId: otherApp });
+ }],
+ ['contradictory before-page identity', (fixture) => {
+ updateIdentityArtifact(fixture, 'before/page.json', { pageId: '22222222-2222-4222-8222-222222222222' });
+ }],
+ ['renamed snapshots contradict the recorded download', (fixture) => {
+ const pageId = '22222222-2222-4222-8222-222222222222';
+ const upload = event(fixture, 'edit');
+ upload.command = upload.command.replace(/ --page-id [0-9a-f-]+/, ` --page-id ${pageId}`);
+ upload.result.pageId = pageId;
+ updateIdentityArtifact(fixture, 'before/page.json', { pageId });
+ updateIdentityArtifact(fixture, 'after/page.json', { pageId });
+ }],
+ ['download result contradicts the requested page', (fixture) => {
+ event(fixture, 'download').result.pageId = '22222222-2222-4222-8222-222222222222';
+ }],
+ ['declared before-page evidence missing', (fixture) => {
+ delete fixture.artifacts['before/page.json'];
+ }],
+ ['ambiguous upload evidence association', (fixture) => {
+ fixture.manifest.uploads.push(structuredClone(fixture.manifest.uploads[0]));
+ }],
+ ['no download or upload identity association', (fixture) => {
+ fixture.events = fixture.events.filter((call) => call.id !== 'download');
+ delete fixture.manifest.uploads;
+ }],
+ ]) {
+ await t.test(`before-page provenance context: ${label}`, () => {
+ const fixture = privateBeforePublicAddFixture();
+ mutate(fixture);
+ for (const layer of [1, 2]) {
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'fail', `${label}, layer ${layer}`);
+ assert.match(result.reason, /before|page|identity|provenance|target|context|app|environment|download|evidence/i);
+ }
+ });
+ }
+});
+
+test('before-page provenance keeps same-page private adds and explicit clear positives', () => {
+ for (const clear of [false, true]) {
+ const fixture = privateBeforePublicAddFixture();
+ if (clear) {
+ fixture.manifest.customApi.stages[0].change = { clear: true };
+ fixture.artifacts['actions.json'] = '[]';
+ fixture.artifacts['after/config.json'] = '{"actionBindings":[]}';
+ fixture.artifacts['stages/edited.tsx'] = cleared;
+ fixture.files[0].content = cleared;
+ }
+ for (const layer of [1, 2]) {
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'pass', result.reason);
+ }
+ }
+});
+
+function separateRecordBindingsFixture(argument = "{ accountid: 'new draft' }") {
+ const fixture = selectedRecordLookupFixture();
+ fixture.artifacts['stages/with-api.tsx'] = fixture.artifacts['stages/with-api.tsx']
+ .replace('const GeneratedComponent', `function editDraft(record: { accountid: string }) {
+ record.accountid = 'draft';
+}
+const GeneratedComponent`)
+ .replace(' const pending = { current: false };', ` let record = props.otherAccount;
+ record = props.selectedAccount;
+ void record.accountid;
+ editDraft(${argument});
+ const pending = { current: false };`);
+ return fixture;
+}
+
+function plainArrowDefaultFixture(writesInput = false) {
+ const fixture = selectedRecordLookupFixture();
+ fixture.artifacts['stages/with-api.tsx'] = fixture.artifacts['stages/with-api.tsx']
+ .replace(' const pending = { current: false };', ` const record = { accountid: 'fresh draft' };
+ const inspectRecord = (record = props.selectedAccount) => {
+ ${writesInput ? "record.accountid = 'edited input';" : 'void record.accountid;'}
+ };
+ inspectRecord();
+ record.accountid = 'edited draft';
+ const pending = { current: false };`);
+ return fixture;
+}
+
+test('plain arrow declaration: a default parameter stays separate from a later outer write', async (t) => {
+ for (const layer of [1, 2]) {
+ await t.test(`plain arrow declaration: independent outer write, layer ${layer}`, () => {
+ const fixture = plainArrowDefaultFixture();
+ assertKnownApiReceivers(fixture.artifacts['stages/with-api.tsx']);
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'pass', result.reason);
+ });
+ }
+});
+
+test('plain arrow declaration: writing its default input still refuses lookup provenance', async (t) => {
+ for (const layer of [1, 2]) {
+ await t.test(`plain arrow declaration: default input mutation, layer ${layer}`, () => {
+ const fixture = plainArrowDefaultFixture(true);
+ assertKnownApiReceivers(fixture.artifacts['stages/with-api.tsx']);
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'fail', result.reason);
+ assert.match(result.reason, /lookup|Ref|provenance/i);
+ });
+ }
+});
+
+test('scoped assignment origin: unrelated helper parameter remains independent', async (t) => {
+ for (const layer of [1, 2]) {
+ await t.test(`scoped assignment origin: unrelated helper parameter, layer ${layer}`, () => {
+ const fixture = separateRecordBindingsFixture();
+ assertKnownApiReceivers(fixture.artifacts['stages/with-api.tsx']);
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'pass', result.reason);
+ });
+ }
+});
+
+test('scoped assignment origin: actual input mutation is refused', async (t) => {
+ for (const layer of [1, 2]) {
+ await t.test(`scoped assignment origin: actual input mutation, layer ${layer}`, () => {
+ const fixture = separateRecordBindingsFixture('props.selectedAccount');
+ assertKnownApiReceivers(fixture.artifacts['stages/with-api.tsx']);
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'fail', result.reason);
+ assert.match(result.reason, /lookup|Ref|provenance/i);
+ });
+ }
+});
+
+test('scoped assignment origin: unmodeled outer alias writes remain refusals', async (t) => {
+ for (const layer of [1, 2]) {
+ await t.test(`scoped assignment origin: unmodeled outer alias write, layer ${layer}`, () => {
+ const fixture = selectedRecordLookupFixture();
+ const code = fixture.artifacts['stages/with-api.tsx']
+ .replace('const GeneratedComponent', 'declare let writtenRecord: { accountid: string };\nconst GeneratedComponent')
+ .replace(' const pending = { current: false };', ` writtenRecord = props.selectedAccount;
+ writtenRecord.accountid = 'draft';
+ const pending = { current: false };`);
+ fixture.artifacts['stages/with-api.tsx'] = code;
+ assertKnownApiReceivers(code);
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'fail', result.reason);
+ assert.match(result.reason, /lookup|Ref|provenance/i);
+ });
+ }
+});
+
+test('scoped assignment origin: named helper defaults retain potential input writes', async (t) => {
+ for (const [label, parameter, argument, arrow = false] of [
+ ['plain parameter', 'record = props.selectedAccount', ''],
+ ['destructured member', '{ record = props.selectedAccount }', '{}'],
+ ['opaque array member', '[record = props.selectedAccount]', '[]'],
+ ['arrow parameter', 'record = props.selectedAccount', '', true],
+ ]) {
+ for (const layer of [1, 2]) {
+ await t.test(`scoped assignment origin: named helper defaults ${label}, layer ${layer}`, () => {
+ const fixture = selectedRecordLookupFixture();
+ const code = fixture.artifacts['stages/with-api.tsx']
+ .replace(' const pending = { current: false };', ` ${arrow ? 'const editDraft = ' : 'function editDraft'}(${parameter})${arrow ? ' =>' : ''} {
+ record.accountid = 'draft';
+ };
+ editDraft(${argument});
+ const pending = { current: false };`);
+ fixture.artifacts['stages/with-api.tsx'] = code;
+ assertKnownApiReceivers(code);
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'fail', result.reason);
+ assert.match(result.reason, /lookup|Ref|provenance/i);
+ });
+ }
+ }
+});
+
+test('scoped assignment origin: opaque default headers cannot hide outer writes', async (t) => {
+ for (const layer of [1, 2]) {
+ await t.test(`scoped assignment origin: opaque default headers, layer ${layer}`, () => {
+ const fixture = selectedRecordLookupFixture();
+ const code = fixture.artifacts['stages/with-api.tsx']
+ .replace(' const pending = { current: false };', ` let writtenRecord!: { accountid: string };
+ function prepareDraft({ other = (writtenRecord = props.selectedAccount) }) {
+ void other;
+ }
+ prepareDraft({});
+ writtenRecord.accountid = 'draft';
+ const pending = { current: false };`);
+ fixture.artifacts['stages/with-api.tsx'] = code;
+ assertKnownApiReceivers(code);
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'fail', result.reason);
+ assert.match(result.reason, /lookup|Ref|provenance/i);
+ });
+ }
+});
+
+test('scoped assignment origin: helper default header positives keep distinct bindings', async (t) => {
+ for (const [label, declaration] of [
+ ['unrelated component local', `let record = props.otherAccount;
+ record = props.selectedAccount;
+ void record.accountid;
+ function editDraft(record = { accountid: 'fresh' }) {
+ record.accountid = 'draft';
+ }`],
+ ['nested arrow parameter', `function editDraft(record = ((record: { accountid: string }) => {
+ record = props.selectedAccount;
+ return { accountid: 'fresh' };
+ })({ accountid: 'fresh' })) {
+ record.accountid = 'draft';
+ }`],
+ ['nested named parameter', `function editDraft(record = (function makeDraft(record: { accountid: string }) {
+ record = props.selectedAccount;
+ return { accountid: 'fresh' };
+ })({ accountid: 'fresh' })) {
+ record.accountid = 'draft';
+ }`],
+ ]) {
+ for (const layer of [1, 2]) {
+ await t.test(`scoped assignment origin: helper default header positives ${label}, layer ${layer}`, () => {
+ const fixture = selectedRecordLookupFixture();
+ const code = fixture.artifacts['stages/with-api.tsx']
+ .replace(' const pending = { current: false };', ` ${declaration}
+ editDraft({ accountid: 'fresh' });
+ const pending = { current: false };`);
+ fixture.artifacts['stages/with-api.tsx'] = code;
+ assertKnownApiReceivers(code);
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'pass', result.reason);
+ });
+ }
+ }
+});
+
+test('download result pages: empty present list cannot establish provenance', async (t) => {
+ for (const layer of [1, 2]) {
+ await t.test(`download result pages: empty present list, layer ${layer}`, () => {
+ const fixture = privateBeforePublicAddFixture();
+ event(fixture, 'download').result = { ok: true, pages: [] };
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'fail', result.reason);
+ assert.match(result.reason, /download|before|provenance|identity|evidence/i);
+ });
+ }
+});
+
+test('download result pages: unreadable list slots cannot establish provenance', async (t) => {
+ for (const layer of [1, 2]) {
+ await t.test(`download result pages: unreadable list slots, layer ${layer}`, () => {
+ const fixture = privateBeforePublicAddFixture();
+ const pages = [{ pageId: '99999999-9999-4999-8999-999999999999' }];
+ // Direct object evidence can contain holes even though a JSON capture would encode null.
+ pages.length = 2;
+ event(fixture, 'download').result = { ok: true, pages };
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'fail', result.reason);
+ assert.match(result.reason, /download|before|provenance|identity|evidence/i);
+ });
+ }
+});
+
+test('download result pages: malformed or wrong identities cannot establish provenance', async (t) => {
+ const pageId = '99999999-9999-4999-8999-999999999999';
+ const otherPage = '22222222-2222-4222-8222-222222222222';
+ for (const [label, downloaded, requested = pageId] of [
+ ['null list', { ok: true, pages: null }],
+ ['object instead of list', { ok: true, pages: {} }],
+ ['string instead of list', { ok: true, pages: 'unreadable' }],
+ ['null list entry', { ok: true, pages: [null] }],
+ ['entry without identity', { ok: true, pages: [{}] }],
+ ['entry with null identity', { ok: true, pages: [{ pageId: null }] }],
+ ['entry with malformed identity', { ok: true, pages: [{ pageId: 'not-a-page-id' }] }],
+ ['different returned page', { ok: true, pages: [{ pageId: otherPage }] }],
+ ['matching page plus malformed entry', { ok: true, pages: [{ pageId }, {}] }],
+ ['matching scalar cannot hide empty list', { ok: true, pageId, pages: [] }],
+ ['matching scalar cannot hide null list', { ok: true, pageId, pages: null }],
+ ['matching scalar cannot hide object list', { ok: true, pageId, pages: {} }],
+ ['matching scalar cannot hide wrong page', { ok: true, pageId, pages: [{ pageId: otherPage }] }],
+ ['matching scalar cannot hide missing identity', { ok: true, pageId, pages: [{}] }],
+ ['matching scalar cannot hide missing before page in batch',
+ { ok: true, pageId, pages: [{ pageId: otherPage }] }, `${pageId},${otherPage}`],
+ ['wrong scalar cannot hide behind matching list', { ok: true, pageId: otherPage, pages: [{ pageId }] }],
+ ]) {
+ for (const layer of [1, 2]) {
+ await t.test(`download result pages: ${label}, layer ${layer}`, () => {
+ const fixture = privateBeforePublicAddFixture();
+ const download = event(fixture, 'download');
+ download.result = structuredClone(downloaded);
+ download.command = download.command.replace(`--page-id ${pageId}`, `--page-id ${requested}`);
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'fail', `${label}, layer ${layer}: ${result.reason}`);
+ assert.match(result.reason, /download|before|provenance|identity|evidence/i);
+ });
+ }
+ }
+});
+
+test('download result pages: valid current and historical identities retain preservation', async (t) => {
+ const pageId = '99999999-9999-4999-8999-999999999999';
+ const otherPage = '22222222-2222-4222-8222-222222222222';
+ for (const [label, downloaded, requested] of [
+ ['current list', { ok: true, pages: [{ pageId }] }, pageId],
+ ['agreeing current list and scalar', { ok: true, pageId, pages: [{ pageId }] }, pageId],
+ ['historical scalar without list', { ok: true, pageId }, pageId],
+ ['historical omitted identity fields', { ok: true }, pageId],
+ ['current list for multiple requested pages', { ok: true, pages: [{ pageId }, { pageId: otherPage }] }, `${pageId},${otherPage}`],
+ ]) {
+ for (const layer of [1, 2]) {
+ await t.test(`download result pages: ${label}, layer ${layer}`, () => {
+ const fixture = privateBeforePublicAddFixture();
+ const download = event(fixture, 'download');
+ download.result = structuredClone(downloaded);
+ download.command = download.command.replace(`--page-id ${pageId}`, `--page-id ${requested}`);
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'pass', `${label}, layer ${layer}: ${result.reason}`);
+ });
+ }
+ }
+});
+
+function addSeparateDirectoryDownload(fixture, after = false) {
+ const producer = event(fixture, 'download');
+ const unrelated = structuredClone(producer);
+ unrelated.id = 'unrelated-download';
+ unrelated.command = unrelated.command
+ .replace('https://contoso.crm.dynamics.com', 'https://fabrikam.crm.dynamics.com')
+ .replace('--output-directory before', '--output-directory unrelated');
+ fixture.events.splice(fixture.events.indexOf(producer) + (after ? 1 : 0), 0, unrelated);
+ return unrelated;
+}
+
+test('before-page download source: unrelated earlier directory does not taint the actual snapshot', async (t) => {
+ for (const layer of [1, 2]) {
+ await t.test(`before-page download source: unrelated earlier directory, layer ${layer}`, () => {
+ const fixture = privateBeforePublicAddFixture();
+ addSeparateDirectoryDownload(fixture);
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'pass', result.reason);
+ });
+ }
+});
+
+test('before-page download source: actual producer environment and app mismatches still refuse', async (t) => {
+ for (const field of ['environment', 'app']) {
+ for (const layer of [1, 2]) {
+ await t.test(`before-page download source: actual ${field} mismatch, layer ${layer}`, () => {
+ const fixture = privateBeforePublicAddFixture();
+ addSeparateDirectoryDownload(fixture);
+ const producer = event(fixture, 'download');
+ producer.command = field === 'environment'
+ ? producer.command.replace('https://contoso.crm.dynamics.com', 'https://example.crm.dynamics.com')
+ : producer.command.replace('11111111-1111-4111-8111-111111111111', '22222222-2222-4222-8222-222222222222');
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'fail', result.reason);
+ assert.match(result.reason, /before|source|context|environment|app/i);
+ });
+ }
+ }
+});
+
+test('before-page download source: ambiguous or unassociated producers refuse instead of guessing', async (t) => {
+ for (const [label, mutate] of [
+ ['two matching destinations', (fixture) => {
+ const duplicate = structuredClone(event(fixture, 'download'));
+ duplicate.id = 'duplicate-download';
+ fixture.events.splice(fixture.events.indexOf(event(fixture, 'download')), 0, duplicate);
+ }],
+ ['one matching and one unlocated destination', (fixture) => {
+ const duplicate = structuredClone(event(fixture, 'download'));
+ duplicate.id = 'unlocated-download';
+ duplicate.command = duplicate.command.replace(' --output-directory before', '');
+ fixture.events.splice(fixture.events.indexOf(event(fixture, 'download')), 0, duplicate);
+ }],
+ ['no recorded destination', (fixture) => {
+ const producer = event(fixture, 'download');
+ producer.command = producer.command.replace(' --output-directory before', '');
+ }],
+ ['present malformed destination cannot use result fallback', (fixture) => {
+ const producer = event(fixture, 'download');
+ producer.command = producer.command.replace('--output-directory before', '--output-directory');
+ producer.result.outputDirectory = 'before';
+ }],
+ ['a sibling prefix is not the producing directory', (fixture) => {
+ fixture.artifacts['before-other/page.json'] = fixture.artifacts['before/page.json'];
+ fixture.manifest.uploads[0].beforePage = 'before-other/page.json';
+ }],
+ ]) {
+ for (const layer of [1, 2]) {
+ await t.test(`before-page download source: ${label}, layer ${layer}`, () => {
+ const fixture = privateBeforePublicAddFixture();
+ mutate(fixture);
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'fail', `${label}: ${result.reason}`);
+ assert.match(result.reason, /before|source|download|provenance|ambiguous/i);
+ });
+ }
+ }
+});
+
+test('before-page download source: recorded destination forms preserve the correct producer', async (t) => {
+ for (const [label, mutate] of [
+ ['later unrelated directory', (fixture) => { addSeparateDirectoryDownload(fixture, true); }],
+ ['Windows separators', (fixture) => {
+ event(fixture, 'download').command = event(fixture, 'download').command.replace('--output-directory before', '--output-directory before\\');
+ fixture.manifest.uploads[0].beforePage = 'before\\page.json';
+ }],
+ ['explicit result directory in abbreviated command evidence', (fixture) => {
+ const producer = event(fixture, 'download');
+ producer.command = producer.command.replace(' --output-directory before', '');
+ producer.result.outputDirectory = 'before';
+ }],
+ ['current per-page directory layout', (fixture) => {
+ const pageId = JSON.parse(fixture.artifacts['before/page.json']).pageId;
+ const file = `before/${pageId}/page.json`;
+ fixture.artifacts[file] = fixture.artifacts['before/page.json'];
+ fixture.manifest.uploads[0].beforePage = file;
+ }],
+ ]) {
+ for (const layer of [1, 2]) {
+ await t.test(`before-page download source: ${label}, layer ${layer}`, () => {
+ const fixture = privateBeforePublicAddFixture();
+ mutate(fixture);
+ const result = score(fixture, layer);
+ assert.equal(result.status, 'pass', `${label}: ${result.reason}`);
+ });
+ }
+ }
+});
diff --git a/plugins/model-apps/.claude-plugin/plugin.json b/plugins/model-apps/.claude-plugin/plugin.json
index 8b1b9192d..ada50e4ca 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.17.0",
+ "version": "2.18.0",
"description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
"author": {
"name": "Microsoft",
diff --git a/plugins/model-apps/.plugin/plugin.json b/plugins/model-apps/.plugin/plugin.json
index 8b1b9192d..ada50e4ca 100644
--- a/plugins/model-apps/.plugin/plugin.json
+++ b/plugins/model-apps/.plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "model-apps",
- "version": "2.17.0",
+ "version": "2.18.0",
"description": "Build model-driven Power Apps end to end: /app-builder authors whole apps (tables, relationships, forms, views, charts, security roles, app + sitemap) from a natural-language intent, and /genpage builds generative pages with specialist agents for planning, entity creation, and parallel code generation. Requires PAC CLI > 2.10.0 and Azure CLI (`az`). See CHANGELOG.md for v1.x -> v2.x migration.",
"author": {
"name": "Microsoft",
diff --git a/plugins/model-apps/AGENTS.md b/plugins/model-apps/AGENTS.md
index 2d72160de..241780dea 100644
--- a/plugins/model-apps/AGENTS.md
+++ b/plugins/model-apps/AGENTS.md
@@ -455,6 +455,11 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
`$batch` change set (the plugin's client has `postRaw`) and stays Active; a Draft flow as one PATCH. The
Active/Draft state is converged AFTER the edit — a state change before it would move the row's version,
and the SDK's push is conditioned on it (a 412).
+ When the customization lock refuses an Active edit's whole change set, the SDK waits and re-sends the
+ identical body for at most 180 seconds of scheduled waits. The guard keeps the original `If-Match`:
+ another maker's intervening edit fails it with 412 rather than being overwritten. The HTTP client
+ delivers each attempt once; an ambiguous 5xx envelope is not permission to replay it. These boundaries
+ are pinned over the real bundle in `bpf-stage-edits.test.js`.
- *Refused — no stage or step edit of the flow is applied, never half of them*: a stage or step the flow has
and the spec does not list (a build never removes either, and cannot tell a spec that dropped one from
a maker who added it in Maker); the same stages in another order; a different number of stages where one
@@ -518,8 +523,10 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
no published layer, so whatever it holds is saved only. That list is fail-closed like the others: a read that fails halts as
`pages-shared-check-failed`, and a never-published app whose layer, sitemap component or saved sitemap cannot be read is listed
unreadable. A never-published app whose component read **succeeds** and finds **no sitemap component** is not yet shown to have no navigation: the
- vendored SDK links an app to its sitemap **by name** — it looks the sitemap up with `sitemapnameunique eq '<the app's unique name>'` and takes one for the app only
- while that column holds the app's name, and `ensureSitemapInSolution` (sdk-build.js) resolves it the same way — so such an app may hold a sitemap, and pages in it, that no component row links to it.
+ vendored SDK prefers a type-62 sitemap component on the app's **current** `appmoduleidunique` layer, but falls back to
+ `sitemapnameunique eq '<the app's unique name>'` when that component is absent and no other live app pins the candidate. So such an app may
+ hold a sitemap, and pages in it, that no component row links to it. `ensureSitemapInSolution` (sdk-build.js) still uses the naming convention
+ of SDK-created apps for its best-effort, additive solution membership; it is not an ownership or deletion proof.
The saved-layer read the scan makes anyway (it asks for `sitemapnameunique` too — no further request) shows whether it does: a sitemap of that name is joined
like any draft app's (case-insensitively, as Dataverse compares names), several sitemaps of the name leave the app unreadable, and **none** means the app has no
navigation at all and holds no page, so it is skipped — one draft app saved with only a name must not stop every page update in the environment (a read that
@@ -927,8 +934,9 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
downloaded spec carries the app's own navigation, which can be empty, so a build of a new app used to fail at the app
step, after the solution, tables, views and forms were written. `navigationVerdict` (`scripts/lib/app-navigation.js`)
now decides from the spec alone, whenever the app-shell phase is in the run's range (never for `--stage data`, or an
- `--only` without it). A NEW app needs one table, dashboard or url entry in a group in an area, because its first push
- creates the sitemap: a navigation of pages only, or with no entry, is refused. An EXISTING app is refused for neither.
+ `--only` without it). A NEW app needs an entry its first push holds, because that push creates the sitemap: a navigation
+ with no entry is refused, and so is a navigation of pages only in a run that cannot create the pages first (below). An
+ EXISTING app is refused for neither.
Its navigation is written from the whole spec once the pages exist, so a page entry counts; and an empty navigation is
built (Dataverse accepts it on an update) with a WARNING that the app is left with no navigation entries — any it has
now are removed, which the destructive-operation gate (`lib/op-diff.js`, wired in `buildModelApp`) asks
@@ -943,10 +951,13 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
would stop the build closes with "Fix the steps marked ? above, then re-run with --apply to execute." rather than
inviting an apply that would stop; `--apply` (`checkNavigationBeforeWriting`, ahead of the view-filter pre-flight) halts
with `BuildHalt` code `app-navigation-empty` (phase `preflight`, `recoverable: false`, `transient = false`, never
- retried), saying what the platform requires and what to add — `{ entity: '<table>', title: '<label>' }` in a group, and
- for a navigation of pages only that a page entry joins the navigation only once its page exists, so a new app needs one
- other entry. A navigation that is fine for an app that exists and refused for a new one — pages only, or no entry at all
- — depends on whether the app exists, so only it reads that: one `findArtifact('app')`, the read the app step makes next.
+ retried), saying what the platform requires and what to add — `{ entity: '<table>', title: '<label>' }` in a group (or,
+ in a run that creates the pages first, an entry for one of the spec's pages), and for a navigation of pages only why this
+ run cannot create the pages first. A navigation that is fine for an app that exists and refused for a new one — pages
+ only, or no entry at all — depends on whether the app exists, so only it reads that: one `findArtifact('app')`, the read
+ the app step makes next. The read is made for a navigation of pages only in a run that creates the pages first too, where
+ both answers build, so that an app that exists makes exactly the requests it made; the app step's own read decides the
+ order.
A valid navigation adds no call, and its plan and requests are byte-identical to what they were. When that read cannot
answer (`--no-live-plan`, a failed read) the stricter rule is not applied: the build warns what it could not check and
goes on as before. A spec with no `appShell.areas` is refused whatever the answer. The destructive-operation gate in
@@ -954,12 +965,37 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
the removal is real, and the build then goes on — and it does not ask about a spec the check refuses outright:
`discoverOpDiffState` reads the deployed navigation only for a spec that declares `appShell.areas`, so a maker is never
asked to authorize the removal of entries from a navigation the build will not write.
- `lint-app-spec` warns (`appShell: …`) for a navigation a new app cannot be built from, and says whether an app that
- already exists is spared (not affected, or built with no entries). A test that builds a NEW app against a fake SDK must
- give its navigation an entry that is not a page: the fakes do not model the platform's rule.
+ `lint-app-spec` warns (`appShell: …`) for a navigation a new app cannot be built from by the whole build — which creates
+ the pages first, so a navigation of pages only is not one — and says whether an app that already exists is spared (not
+ affected, or built with no entries). A test that builds a NEW app against a fake SDK must give its navigation an entry
+ that is not a page, or run the pages phase (which then creates the pages first): the fakes do not model the platform's
+ rule (`lifecycle-pages-first-real-bundle.test.js` adds it in front of its fake).
Pinned by `app-navigation.test.js` (the rule, its agreement with `appDef`, validation, lint) and
`app-navigation-build.test.js` (dry run and apply for every shape, with every call recorded, the summary line, and the
order of the destructive gate and the check).
+ **A new app whose navigation is pages only is built by creating its pages FIRST** (`pagesFirstRule` and
+ `createAppWithPages`, `scripts/lib/sdk-build.js`). In a run that has the app step and the pages phase, is not a changed-only
+ re-upload, and builds every page an entry names, the app step does all it does before a create — the icon, the Main-form
+ list, the `app.tables` refs, its existence read, the one pre-app table publish — and, finding no app, leaves the create to
+ the pages phase: the step is reported `⊘ app "<name>" (created after its pages: its navigation holds only page entries)`,
+ never a ✓ for an app that does not exist yet. The pages phase runs as for any app, with no membership (there is no
+ sitemap to read, so an id binds only through this workspace's creation receipt — the rule that already binds a page whose
+ build stopped before its finalizer — and the removal gate has nothing of this app to protect), and in the finalizer's slot
+ it CREATES the app with `appDef(spec, result.created)` — the whole navigation, every page's id in it — through the app
+ step's own create (`createApp`: create and push, the app and its sitemap into the solution, the `app.tables` pin), reported
+ in the app-shell phase as `✓ app "<name>" (created with its pages)`. Its first sitemap holds the page entries, so no
+ navigation without them is ever sent and there is no temporary entry to remove; the pages' default views are pinned after
+ it as for any app. This is the order `apps.js create --page-id` has always used (a page made with no app, then the app
+ around it, live-verified). A stop between the pages and the app leaves the pages, their receipts and the manifest, and no
+ app: a re-run — or the CLI's own retry of a transient halt — adopts each page by its receipt (an unchanged page is neither
+ written nor published) and creates the app; a teardown deletes them by their receipts with the app absent. A build from
+ another workspace holds no receipt: it halts `pages-identity-conflict`, and its advice names that workspace rather than an
+ `add-to-app` for an app that does not exist. An app that EXISTS is not affected: the app step finds it and reuses it, and
+ its requests are byte-identical (pinned). A run that cannot create the pages first — no pages phase, a changed-only
+ re-upload, a page entry whose page it does not build — still refuses a new app of pages only, and says which. Pinned by
+ `lifecycle-pages-first-real-bundle.test.js` (over the real bundle: built from nothing, an unchanged rebuild, a stop between
+ the pages and the app then a re-run, the CLI's retry, another workspace, and a teardown after each, back to what the
+ environment held) and `app-navigation-build.test.js` (every request of the order, and the refusals).
**An existing app's sitemap is rewritten ONTO its live nodes (AB#6726727).** The App Spec describes a
node's label/title, target and icons only, and the SDK serializes a node without its fetched `bag` from
scratch (new `Id`, `ResourceId="SitemapDesigner.NewSubArea"`, broad `Client`/`Sku`,
@@ -1132,7 +1168,7 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
in one `<entities>` PublishXml, with or without `--publish` — in the data-model phase, before anything can publish
the app; a failed publish is a warning that names the tables. Nothing else in the build is sure to publish them:
its other table publishes follow from what the spec puts on a table (a form, view, chart or icon, or its enriched
- default views), and a downloaded spec carries no forms, views, charts or table icons and marks every table
+ default views), and a downloaded spec need not carry forms, views, charts or table icons and marks every table
`existing: true`, whose default views the build leaves alone. No metadata read can confirm that publish: measured
live, `RetrieveEntity` returns the new label right after the PUT even with `RetrieveAsIfPublished=false`, so a
live check of it has to trace the request. The labels are read **once per child table**
@@ -1387,13 +1423,35 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
never published answers 404 without it; measured live, the platform DELETED such a row, so the read-back is insurance against an answer it has not been seen to give.
Form-only page references are not scanned.
**An app is TWO rows** — an `appmodule` AND a `sitemaps`
- row, with no lookup between them and no server-side cascade; the only link is
- `sitemap.sitemapnameunique === appmodule.uniquename`. Deleting only the appmodule strands the sitemap
+ row, with no server-side cascade. The sitemap is linked by a type-62 `appmodulecomponent` on the app's **current**
+ `appmoduleidunique` layer, not necessarily by equal unique names (first-party and renamed sitemaps may have different names).
+ Only an app with no sitemap component permits a same-name fallback, and only when no other live app's current layer pins that candidate.
+ Deleting only the appmodule strands the sitemap
forever and, because `sitemapnameunique` is unique-constrained, permanently **burns that unique name**:
a later build of an app with the same name fails with *"The name &lt;x&gt; is already in use by an
existing site map"*, which the maker cannot act on. `deleteAppCascade` therefore resolves the sitemap
- BEFORE deleting the app, deletes both rows in **one atomic OData `$batch`**, and **fails closed** — any
- delete it cannot prove is rejected rather than guessed. Each row's delete is conditioned on its
+ BEFORE deleting the app, rechecks the current link after reading it, deletes both rows in **one atomic OData `$batch`**, and **fails closed**.
+ Missing, malformed, ambiguous or changed identity refuses as `APP_SITEMAP_UNRESOLVED`; a sitemap another live app currently pins refuses
+ deletion as `APP_SITEMAP_SHARED`. Fetch/push also refuse a shared same-name fallback rather than adopting another app's navigation, and
+ download returns the refusal with `ok:false` before writing output. A copy whose app was re-linked must be fetched again before pushing edits.
+ One `APP_SITEMAP_UNRESOLVED` refusal, and only that one, teardown gets past itself — for a published app whose teardown reaches the app step:
+ the app's SiteMap component names a sitemap that is GONE (`… sitemap '<id>' was not returned by the unpublished-aware read. … Retry.`). Before
+ 2.18.0 the teardown of one app deleted a sitemap another app shared, and the other app's component outlives the row it names (measured live).
+ 2.17.0's delete looked the sitemap up by the app's unique name and, when no sitemap had that name, deleted such an app alone; the component-aware 2.18.0 delete
+ refuses it on every run, and no retry can pass that. `scripts/lib/app-sitemap-dangling.js` reads the app's row version FIRST, then proves the
+ sitemap absent by its id in the published AND the saved layer, with no other app's current layer naming it and the link unchanged when read
+ again; then it deletes the app ALONE — one `DELETE` with `If-Match` on the version read before the proof, so a repair, relink or publish of
+ the app while the proof ran is refused (412, a final refusal), no sitemap written — reads it back gone from both layers, warns once, and
+ teardown goes on. A read that fails or is ambiguous, a sitemap a layer still holds, another app's pin, a relink, a moved version and an app with
+ no published row are each a final refusal (`transient: false`) that says what was found and asks the maker to delete the app in Power Apps and
+ run the teardown again — never "Retry". Every error of this path is `failClosed`: `deleteStep` passes it on before its not-found, dependency and
+ undeletable shortcuts, which read an error's words (an app's display name, a proxy's "not found"), so the steps that depend on the app are
+ never attempted after it. What the version cannot see — another app pinning the sitemap, or a row of its id made again, after the last read —
+ is the same snapshot limit as the SDK's reverse-owner check. Not reached: an app with live generative pages stops earlier, at the page proof
+ (its navigation is gone), as before — delete such an app in Power Apps, then run the teardown again. The SDK's sentence only chooses this path;
+ the proof decides (pinned against the real bundle in `scripts/tests/teardown-dangling-sitemap-real-bundle.test.js`).
+ The reverse-owner check is a snapshot, not a cross-app lock: another app adding a pin afterwards moves neither row token, so this does not
+ promise to prevent that race. Each row's delete is conditioned on its
**row** token from a by-id read, not the unpublished-aware read's content token, which runs ahead
of the row while a sitemap edit is unpublished (that made such an app impossible to tear down —
412 every time). This is why
@@ -1404,6 +1462,10 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
The SDK re-sends an app delete itself when the platform's search-index insert race refuses it (HTTP
400, SQL 547) — an answer this client never re-sends — so the two layers add and never multiply
(counts pinned in `scripts/tests/sdk-resend-layers.test.js`).
+ An app-create rollback preserves the SDK's distinction between **KEPT** (a whole atomic change set was refused by the customization lock
+ and deleted nothing) and **unconfirmed** (its answer cannot prove what happened). Its advice is surfaced unchanged: verify that the rows
+ are this create's own before removing them; a raw outer 429 remains unconfirmed and retains its lock error, rather than proving KEPT.
+ Neither `PublishXml` nor an unguarded rollback is re-sent.
Pinned by
`scripts/tests/app-delete-real-bundle.test.js` against the real bundle — every other teardown test
drives a mock and would stay green through a regression here. The teardown of an app that was created and never
@@ -1458,8 +1520,26 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
writes); dry-run lists every page candidate by id and stored name without writes, marking absent
rows as "not found" with their manifest names only.
Best-effort continue (a failed step is recorded, teardown proceeds). A not-found (already-gone)
- error is treated as deleted, the table delete's **not-found-on-success** is tolerated (`tolerateNotFound`),
+ error is never a failure, the table delete's **not-found-on-success** is tolerated (`tolerateNotFound`),
and system/managed artifacts that cannot be deleted are recorded as `skipped` rather than failing.
+ A step reports `(not found)` — and the closing line counts it so — only where it knows nothing was there
+ when it began (the handler's `absentOnNotFound`, or `foundNothing` for an answer): a default-view reset
+ that finds no default view, a relationship the SDK's own lookup does not find (it sends no delete), a
+ table its step's read did not list, and a global choice, whose delete is its step's only request. A
+ teardown run again therefore reads `0 deleted, N not found` (it read every one of those `(1 deleted)`),
+ and so does the relationship from a table to itself whose table this run deleted (it went with it). A
+ not-found answer after a read that SAW the artifact — a table's, which is the not-found a re-sent metadata
+ delete gets once its first send did the work, or a relationship's to its own delete — stays a deletion.
+ The deletes sent are unchanged, and so is the exit status. One case can still mislabel: a global
+ choice delete the client sent again (after a timeout or a gateway error) whose first send had removed it
+ reads "not found", since the step makes no read that could tell.
+ **A publisher is never deleted**, and no step plans one: the build reuses any publisher that carries the
+ spec's prefix (`provisionSolution`) and other solutions may share the one it made, so a teardown cannot
+ tell that this app alone uses it. Its closing summary says so in one line after the count, on a clean
+ run and a failed one alike — `▸ the publisher with prefix '<prefix>' is kept: teardown never deletes a
+ publisher, which other solutions may share — delete it in Power Apps (Solutions → Publishers) once nothing
+ uses it` — so the row a maker finds left behind is expected (`teardown-model-app.test.js`, and the
+ lifecycle matrix's teardown).
`--clear-workspace` prunes `.maker-workspace/` after a clean apply (not while another teardown of it
still holds the changed-only fence). It also refuses while any unconsumed ownership records remain,
including another app/environment. The refusal names each file and explains that teardown retires it
@@ -1500,7 +1580,8 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
A missing SDK sitemap or a mismatch is refused with publish-then-download guidance, never emitted
as hidden-table membership or lost Main restrictions. The immutable name is recovered from the
fetched `uniqueName`/`uniquename` before manifest/prefix lookup; an unresolved identity is refused.
- **Round-trip scope (be precise — do not claim "complete"):** tables, sitemap/appShell, generative pages,
+ **Round-trip scope (be precise — do not claim "complete"):** tables, sitemap/appShell, generative pages
+ (with their data sources, model and connector and Custom API bindings),
classic dashboards, icons, and solution round-trip; **forms, views, charts, and commands do NOT yet
round-trip.** (View hydration was tried and reverted — LIVE-verified that the deployed savedquery set
can't reliably tell app-builder-authored views from Dataverse's auto-generated Active/Inactive/QuickFind
@@ -1519,12 +1600,154 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
`view-related-rows-filter.test.js` and `rebuild-writes-real-bundle.test.js`).
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
+ **Portable schema is reconstructed, not only column types.** The download keeps Text format/length,
+ Memo length, Integer range/format, Decimal/Double range/precision, Money range, Boolean labels, DateTime
+ format, AutoNumber masks, and the primary name column's length/mask. Values equal to the SDK's
+ create defaults are left implicit; explicit defaults cannot be distinguished from omission on a
+ deployed column. Primary name lengths stay explicit even at 100, because the build's post-create
+ correction runs only for an asked length on environments that override the create's value.
+ Reads scale by the types present on each table, never by its column count:
+ String, Memo, Integer, Decimal, Double and DateTime each need one conditional cast; Money detail
+ rides its existing currency-twin read and Boolean labels ride the SDK projection. Money's
+ `PrecisionSource` is classified there too: the SDK always creates source 2 (transaction currency).
+ Only source 2 keeps numeric `Precision` metadata; its effective precision still depends on the
+ transaction currency's decimal places, so equal numeric metadata is not cross-environment
+ currency equivalence. Source 0 (column), source 1 (organization pricing), and missing/malformed/
+ unknown sources are diagnosed; the typed column and range remain, but precision is omitted.
+ Configure the required source in Power Apps on the target before relying on its behavior.
+ Custom unmanaged status reasons in Active/Inactive states keep their values, labels and colors
+ (stock reasons 1/2 are not re-declared; a stock table's reasons below the custom range are not
+ portable). Their single label is selected only in the resolved download authoring language
+ (flag, existing spec pin, then environment base), never the caller's UI language. A missing
+ requested translation is named and that reason omitted, not substituted from another LCID.
+ A read-time non-base-language flag must also be passed to the rebuild, or pinned in the spec.
+ One Status cast per table supplies the state the SDK's flattened choices omit.
+ Alternate keys, including names, columns and available display labels, ride the table-label read;
+ solution/global-choice display names and dashboard tile spans ride existing reads too. A
+ malformed or missing optional `Keys` array is diagnosed without losing the table, its primary
+ name, typed columns or navigation.
+ A table's `vectorIcon` is written only with a captured own-publisher, explicitly unmanaged SVG
+ that has content. The resource is `external: true`: shared table metadata is not proof this app
+ owns the file, so teardown of the downloaded spec must not delete it. Resource resolution may
+ need one set-name lookup plus one read per distinct SVG; navigation/table overlaps are deduplicated.
+ **Same-environment rebuilds do not re-send these schema writes when proven equal.** Scalar
+ key identities ride the existing table probe. Status-label comparisons run only after all
+ labelled schema creates (including deferred keys), so they cannot strip a later create's
+ non-base-language labels. A halted attempt leaves its queued existing-table status reasons for
+ the next successful attempt. A standalone Integer format is compared before its SDK update. Unknown
+ proof keeps the existing duplicate-protected create/update path; a missing reason/key or a
+ changed Integer format still writes. Table icons retain the SDK's assignment and specific-table
+ publish even when the saved name matches: a failed publish can leave that same saved name behind.
+ Existing status/key definitions are not rewritten on a
+ name/value conflict, and ordinary column lengths/ranges remain create-only, as before.
+ Missing, malformed or refused portable detail is named on stderr without dropping typed columns
+ or inventing defaults. This is not full environment cloning: script resources, raster/foreign/
+ managed table icons, `roleGrants[]`, `sampleData`, Boolean defaults, column capabilities and
+ BigInt ranges are not reconstructed. Neither are unsupported status states or managed reasons;
+ a non-primary AutoNumber's custom length/format and DateTime behavior are not authorable here.
+ Dashboard tiles still bind source view/chart ids; moving them to another environment also needs
+ those artifacts mapped, and removing a pinned source `dashboardId` when creating a new dashboard.
+ **Form/view/chart omissions are 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.
+ **A page's connector and Custom API bindings are in the spec** (`pages[].connectorBindings`,
+ `pages[].actionBindings`; the format and the rebuild rules are in `references/app-spec-schema.md` →
+ `pages[]`). The page folder always held the raw lists in its `config.json`, but the spec carried only
+ `dataSources` and `model`: a rebuild into the same environment kept a page's bindings only because it sent none
+ (the SDK leaves a list a push omits as it is), and a copy of the spec rebuilt in another environment deployed
+ the pages without them. `parseDownloadedPages` now writes a list a page holds into the spec **only WHOLE, and only
+ what is known to be safe** (`lib/page-bindings.js`, whose header holds the threat model and lists every sink).
+ Declared Custom API kinds come from the pure `lib/custom-api-kinds.js` contract shared with discovery,
+ without loading a CLI; only the ten runtime primitives are declared, never structural lookups. Each key is
+ one of the documented properties (`logicalName`, `connectorId`, `dataset`, `tables`, `tableDisplayNames`,
+ `operations` for a connector binding; `name`, `isFunction`, `boundEntityLogicalName`, `displayName`, `parameterKinds`
+ for a Custom API binding) and each value of a conservative shape positively known to be safe — an identifier, a GUID,
+ a plain name or label, or an `http(s)` URL whose PARSED form (`new URL`) has no user-info, no query and no fragment and whose text is already that canonical form (a parser removes dot-segments before any check could see them, so the text that is persisted must be the text that is checked)
+ and whose decoded path is labels — none of it shaped like a token (a known token prefix, an authorization scheme, a
+ 32+ run mixing letters and digits). **That is a security rule, not a tidiness one, and it fails closed**:
+ `genpage-upload.js` writes any JSON array into a binding, so an entry can hold a connection id or a credential as a
+ value, as a KEY, or inside a URL's user-info, query or fragment, encoded or not, and the spec is the artifact that is
+ committed and shared. A list in which any entry holds anything else is left out of the spec **whole** — nothing is
+ projected out of it, because an entry stated without its identity (or a property) would make a rebuild REPLACE the
+ page's entry with less — and reported in `pageBindings.notCarried` (stderr `WARNING:`) by the page, the list, the
+ entry's place and the vetted property, or "an unrecognized property": never a value, never an unrecognized key
+ (`bindingProblemText`). A list left out is one a rebuild does not send, so the page keeps it: no write, no publish.
+ The validator holds an authored spec to the same rule, as an ERROR in the same words, because refusing is the only
+ thing that keeps a credential out of the file. The page folder's own `config.json` is the page as the environment
+ holds it and is **not** rewritten, so it still holds everything — the `WARNING:` says so. A list that is no list of
+ objects (`pageBindingsProblem`, also the validator's) is left out whole too. An empty list and `null` (the page's
+ way of holding none) are nothing and are never written: a stated `[]` means "clear". Neither is a gate, as for a
+ model the spec cannot hold. **A rebuild must not strip what a spec does not state** (an author's list, or a page that
+ gained a property after its download), so the page backend reads a list a
+ spec states against the page's own entries (`update` and `publishedDiffers` take `specBindings: true`, the build
+ always passes it; `planEdits` → `mergeBindings`): an entry is matched by `logicalName` / `name`, the properties a
+ spec can state come from the spec, and the others stay on the entry. A page that already holds what the spec
+ states is therefore **not written and not published**, and an edit changes what it names and nothing else. Any
+ other caller of the backend keeps replacing a list with the one it gives. The build sends a list a spec page
+ states, and none it does not (`statedPageBindings`; the create that makes a page the others navigate to, and the
+ create or update of the pages loop, both pass them) — an omitted list is the deployed page's own, a stated one,
+ `[]` too, is the page's list. **The record of an earlier publish is recognised** (`lib/page-publish-records.js`):
+ it is the hash of the content the build sent, and every record made before a download stated the lists is the
+ hash of the content WITHOUT them (or without one of them, for a record made while the spec stated only the other).
+ With `specBindings`, when the page already holds what the spec states and the caller's record is the hash of that
+ content without one or both of the lists it states, `update` reads the PUBLISHED copy (read only) and, when it holds
+ the lists too, answers `publish.kind: 'skipped'` with `receiptUpgraded: true`; the build then renews the record to
+ the new hash with the versions it already holds (`rememberPublished`), so the next build reads nothing more. A
+ copy that does not hold them, or cannot be read, publishes as it always did, and a page the spec changes is
+ written and published whatever was recorded. Verify does not compare the lists, as it does not compare
+ `dataSources` or `model`. `--changed-only` reads a change to a list as a structural change to the page, so it
+ takes a full build. No `minimumPluginVersion` is set for them: an older plugin ignores the lists, which is what
+ it always did, and a floor above the running version makes `validateAppSpec` refuse the spec. **A rebuild
+ checks what the lists name before it writes anything** (`lib/page-binding-targets.js`, called from
+ `checkPageBindingsBeforeWriting` next to the navigation check, and in a dry run's plan): it reads the
+ environment's `connectionreference` rows and `customapi` rows for the names the pages it writes state —
+ the pages a changed-only run selects and the navigation targets it may have to make — and **stops**
+ (`BuildHalt`, phase `preflight`, code `pages-binding-reference-conflict`, never retried, nothing written) at a
+ connection reference of that name whose connector is another than the binding's `connectorId` (compared by the
+ connector's name, the last segment of its id). It never guesses and never makes a reference: the author gives the
+ binding another logical name, or states the connector this environment has (a custom connector made separately in
+ each environment has another id in each). It only SAYS, by name, a reference or Custom API that is not there (the
+ page is written with its binding, and a reference made afterwards makes it work without a rebuild), a reference
+ that is there with no connection (`connectionid` empty — what a solution import leaves when no settings file gives
+ one), an operation a binding lists that the custom connector of its reference does not define, a Custom API that is
+ the other kind or bound to another table (the runtime refuses that call itself), and a read that failed (the
+ bindings were not checked); a connector that is not named on both sides is never a conflict. The runner captures the
+ attempt's throttle checkpoint before these preflight reads: a wait refused by the shared budget stops preflight with
+ `throttle-budget-exhausted` before any SDK or page mutation, not just an unchecked-metadata warning. Refusals from
+ earlier attempts do not stop a new attempt unless it refuses another wait. **Missing evidence is
+ NOT CHECKED, never compatible**: a row that answers without its `connectorid`, its `connectionid`, or a GUID in
+ `_customconnectorid_value` (absent, null or invalid) — or with a value of another shape: a `connectorid` that is not
+ `/providers/Microsoft.PowerApps/apis/shared_<name>` (`referenceConnectorKey` checks the syntax before anything is
+ compared), a `connectionid` that is not a text or null — is said by name as not checked (`unchecked`, a warning): the
+ connector is not compared, the connection not judged, the operations not proven, and nothing is refused for it. The
+ conflict halt needs two VALID connector ids that differ.
+ Operations are read only for a CUSTOM connector: its definition is a row of the
+ environment (`connector.openapidefinition`, found through the reference's `_customconnectorid_value`, parsed by
+ `definedOperations` as Swagger 2.0 — every HTTP method's `operationId`, matched exactly, as the SDK matches them;
+ a definition it cannot read leaves the operations unchecked, and says so), and the copy there can be another
+ version than the page was made with. A reference whose row names no custom connector gets no definition read, and
+ its binding's operations are said as not checked: a null lookup is what a connector the platform publishes has, but
+ it is no proof of one (a reference made through the Web API can leave it unset).
+ **What a rebuild cannot bring to another environment is what the lists name,
+ and the download says so**: when any page holds a binding it prints `NOTE:` on stderr and returns
+ `pageBindings` — `pages` (each page's key, name and the connection references / Custom APIs its bindings go by),
+ `neededInTarget` (`connectionReferences`, `customApis`, and `serviceResources`: the references whose bindings
+ name a `dataset` or `tables`, which are the source environment's), `notCarried` and a
+ `note` — in the order the spec lists its pages, names sorted by `compareText`; the block is absent when no page
+ holds one and nothing was left out. The connection reference and the connection behind it (a user's sign-in, which
+ stays where it was made), the Custom API (a solution component) and the resources a connector binding points at
+ are not App Spec items; the `NOTE:` names the scripts that make each one there. The `custom-api` feature flag
+ gates what the `/genpage` agents author, not this: a download and a rebuild carry the bindings a page already
+ holds. `page-binding-contract.test.js` pins the allowlist, the projection and the merge,
+ `page-binding-targets.test.js` the reads and the judgement of the environment, `page-bindings.test.js` the
+ download, the validator, the build's write sites and its check of the environment, and
+ `page-bindings-real-bundle.test.js` what the real SDK does with the lists: a page read with them, a rebuild
+ that writes no row, a changed list that keeps what the spec could not state, a create in another environment, and
+ the record of an older publish (the build-level version, with the real pages phase, is in
+ `sdk-build-pages-deploy.test.js`).
**A download is written in a fixed order, so two downloads of one app match byte for byte** and a diff
between them shows only what changed. Dataverse promises no row order for a query without `$orderby`,
and a directory listing is in the file system's order (name order on NTFS, hash order on ext4), so
@@ -1661,11 +1884,11 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
dropped and counted in `droppedSubareas`.
- **`scripts/verify-model-app.js` → `scripts/lib/verify-spec.js`** — read-only reconcile of the App Spec
against what actually deployed; exits non-zero and lists anything missing, catching silent partial
- builds. It validates the spec first under the `deploy` profile, with two compatibility downgrades
- (`relationshipCollisions: 'warn'` and `columnValues: 'warn'`): a spec an earlier release accepted and built — a 1:N and an N:N
- that share a schema name, an AutoNumber column with no format, a `required` that is not `true`, `false` or `"recommended"` — is
- verified, with a warning that names the fix, and is never refused before anything is read (the build, the lint and the
- provisioning gate keep these as errors). **Every `WARNING:` line it prints on stderr — those findings, the spec's other warnings, and a page
+ builds. It validates the spec first under the `deploy` profile, with three compatibility downgrades
+ (`relationshipCollisions: 'warn'`, `columnValues: 'warn'` and `fieldOptionKeys: 'warn'`): a spec an earlier release accepted and built — a 1:N and an N:N
+ that share a schema name, an AutoNumber column with no format, a `required` that is not `true`, `false` or `"recommended"`, a key a form's
+ `fieldOptions` entry does not take — is verified, with a warning that names the fix, and is never refused before anything is read (the
+ build, the lint and the provisioning gate keep these as errors). **Every `WARNING:` line it prints on stderr — those findings, the spec's other warnings, and a page
workspace it could not remove — is also in the result JSON's optional `warnings` array** (the same messages, without the prefix, in the order
printed; left out when there is none, as `unverified` is), so a caller that reads only the JSON loses none of them. It is there on a failed
verification and on a refused spec (`{ ok: false, errors, warnings }`, whose warnings are printed too) as on a passed one, and changes neither
@@ -1691,8 +1914,24 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
check fails and says what the answer lacked. It is not listed `unverified`, which leaves `ok` and the exit
status as they were; a relationship nobody identified must not read as a pass. (A reader that lists plain
names, as older test doubles do, stays a name-only reader; the plugin's own reader never does.)
+ **Status reasons and alternate keys** are checked too, each declared one by its name (`lib/status-reasons-keys.js`):
+ `status-reason <table>.<label>` passes when one of the table's status reasons carries the label (in any language the spec
+ writes it in) under the state the build gives it — Active unless the spec says Inactive — and at the `value` the spec pins,
+ when it pins one. The deployed option must carry a readable integer state: a missing, null or malformed state fails with
+ an explicit unreadable-state detail, never a guessed match. `alternate-key <table>.<schemaName>` passes when the table has a key of that name over exactly the
+ declared columns, in any order (live, a key read back answers its columns in an order of its own). One that is there but
+ different says how (the other state, another value, other columns), and a missing one says when the value the build gives
+ it is another label's — a rebuild inserts the reason at that value again, which the platform refuses as already there, so a
+ reason renamed in the environment stays renamed — or when a key of another name is over the same columns. The state and
+ value are the build's own (`statusReasonTargets`, `lib/entity-provision.js`), so verify cannot hold a reason to anything the
+ build did not write. Each is ONE narrow read on the SDK's client — the Status attribute's cast read (the one the view filter's
+ label resolution makes for the column, `optionCastUrl`) and `EntityDefinitions(…)/Keys?$select=LogicalName,SchemaName,KeyAttributes`
+ — made only for a table that declares any: a spec that declares neither sends no request for them
+ (`lifecycle-scenarios-real-bundle.test.js` pins the difference to exactly those two reads). A key's index status is not read:
+ right after its create a key is `Pending` (live-measured), and a key of the declared name over the declared columns is the
+ key the spec declares. A read that fails is a failed check with its reason, never a pass.
Content checks are additive + reader-gated (they only fire when the reader supplies `layoutxml` /
- `entityRelationships` / `commandBar`), so existence-only callers are unaffected. A view filter's
+ `entityRelationships` / `commandBar` / `statusReasons` / `alternateKeys`), so existence-only callers are unaffected. A view filter's
Choice label is expected as the value the **environment** gives it, which needs the reader's
`choiceAttributes` (one memoized read per table per pass); without it the spec-only expectation
applies. A label whose option metadata could not be read is reported as **unresolved** with the
@@ -1842,7 +2081,13 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
and archival. It is **rendered, never hand-written** — the freehand version drifted from the spec
and shrank to a counts summary. Also returns `warnings[]` naming design gaps (no jobs captured, a
job with no covering surface, no generative pages, a new table no persona and no `roleGrants[]`
- entry grants a privilege on) so the orchestrator surfaces them in chat. Its Security section keeps
+ entry grants a privilege on) so the orchestrator surfaces them in chat. A `roleGrants[]` entry the
+ build refuses because it does not name exactly one role — `role` and `roleId` both, neither, or one
+ of them malformed — is named there and in the document in lint's own words: one check decides it
+ (`roleGrantIdentityErrors`, `lib/app-spec.js`), which `validateRoleGrants` reports (the gate a build
+ and `lint-app-spec.js` run) and the document reads through `roleGrantRefusals` (`lib/app-access.js`).
+ The document shows such an entry as that refusal, never as rows of privileges the build would add,
+ and does not match it against the roles the app has. Its Security section keeps
two questions apart — who can open the APP (the roles associated with it) and who can use the
TABLES the spec introduces (privileges) — and never calls the app administrator-only on the
strength of a spec with no personas alone: that is a claim about the deployed app. With `--env` it
@@ -1890,6 +2135,36 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
none, because a download never writes one and a relationship adopted with `existing: true` has the intersect
table its maker chose — the answer still has to state it. The SDK's own relationship projection
(`fetchEntityMetadata`) lists an N:N without its intersect table, so it never proves one.
+- **An "already exists" answer is also recognised by its error code, in any language.** A create the platform refuses because what it
+ asks for is already there is a skip for a status reason (its pinned value is taken), for an alternate key the build could not
+ prove from its table read, and for a column of a table whose columns could not be read; for a table and a relationship it is
+ the cue to read what exists, and only what that read finds — the declared relationship, by its whole identity — is reused.
+ The platform can word that answer in the caller's language: measured on an environment whose only language is Spanish, a key
+ created again was answered `Ya existe una clave de entidad con el nombre … en la entidad …` (HTTP 400, `0x80060893`), and a
+ rebuild that read only English words halted there (the same environment answered the other creates below in English). So each of
+ those creates also recognises the answer by the `error.code` of its body — `ALREADY_EXISTS_CODES` in `lib/entity-provision.js`, read
+ by `serviceCodeOf` (`lib/retry-policy.js`) from the SDK's `ConnectionError`: `0x80060893` for a key, `0x80044310` for a status
+ reason's value, `0x80047013` (measured, on 13 column types; not on a Customer column) and `0x80060304` for a column, `0x80044363`
+ (measured), `0x8009050d` (measured; not in the platform's reference) and `0x8004700b` for a table; for a 1:N `0x80072551`
+ (measured), the reference's name code `0x8004432B` and the column codes for its lookup column; for an N:N the name code only, as no
+ answer to the create of an existing N:N has been captured
+ ([web service error codes](https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/web-service-error-codes)).
+ Two of them speak of something another component can hold, so each is listed for one create only, where the read that follows
+ decides. `0x80044363` ("The schema name … for type Entity is not unique. An … with same name already exists.", the answer to the
+ create of an existing table) is about a schema name: a name held by anything but a table finds no table on that read, and the
+ create's own error stops the build. `0x80072551` ("NavigationPropertyName … is not unique within an entity", the answer to the
+ create of an existing 1:N — in words no English rule matched, so such a relationship stopped the build in every language) is about
+ the navigation property the create names after the relationship: the build reuses only the declared relationship that the read of
+ the name, or of the lookup column's owner, proves, and any other relationship holding it — or an answer the read cannot prove —
+ stops the build.
+ The codes only add recognition, and prove no more than the English words of the same refusal: the 409 and English-word rules are
+ unchanged, and they apply whatever code the answer carries, an unlisted one included — an English `0x80060894` answer (another key
+ over the same columns, "An entity key with the selected attributes already exists on entity.") is still a skip, as it was. A code
+ another create answers, a generic code (`0x80040216`) and a code the message only quotes do not count by themselves: such an answer
+ stops the build unless the 409 or the English words read it as an already-exists one — an answer worded in another language, which
+ the English rule does not read, stops. Pinned by
+ `already-exists-codes-real-bundle.test.js`, which runs each of those creates through the real bundle answered in English and
+ in another language, and requires the same outcome.
- **Bounded parallelism in the read-heavy and publish-heavy paths.** Each item below has tests that count
requests and prove the overlap (`verify-parallel-checks`, `verify-page-code-batch`,
`download-parallel-reads`, `teardown-publish-once`, `table-columns-in-create`, and the check-auth tests),
@@ -2032,12 +2307,12 @@ the pipeline and delegates each script's **behavioral spec** to the entries belo
columns), and a PUT of the finished column — the SDK's `updateColumn`, with `MSCRM.MergeLabels: true` — is honored
(850 → 120 → 850). So when the spec gives a length and THIS build created the table, it reads the length back with
one typed `…/Attributes(LogicalName='…')/Microsoft.Dynamics.CRM.StringAttributeMetadata?$select=MaxLength` GET and
- calls `updateColumn` only when it differs — LAST in the data-model phase, once every table, column, status reason,
+ calls `updateColumn` only when it differs — at the end of the data-model phase, once every table, column, new table's status reason,
relationship and alternate key that needs no length has been created, and in the halt path too, so that a phase that
halts after creating a table still sets that table's length (a run in a new process finds the table and leaves an
existing table's name column alone; a length that cannot be set while the phase is halting is warned about as one such
a run will not set either).
- Last, because `updateColumn` starts by reading the column WITH its labels, and a label-bearing metadata read ahead of
+ There, because `updateColumn` starts by reading the column WITH its labels, and a label-bearing metadata read ahead of
a labelled create is what strips non-base languages (measured; see `findExistingColumns`): within one attempt, nothing
labelled in more than one language is created after it, except one kind of alternate key over the name column (below): the
key labelled in several languages that cannot fit beside the name column before the step, which is made after it because it
@@ -2322,7 +2597,7 @@ scripts/
list-connections.js ← Connector discovery: the maker's connections + Dataverse connection references. The connections come from the SDK first (`listConnections`, with the Power Apps service token); `pac connection list --environment <origin>` runs only where the SDK refuses the route — and at once, with no SDK and no token read, for an environment outside the Public cloud, which the SDK has no route for (see "Connections, connector metadata and deployment settings") — and the output says which answered (`connectionsSource`, `connectionsFallback`)
connector.js ← /genpage connector builder: a connector's operations, one operation's parameters and response, a tabular connector's table columns — `operations` and `schema --operation` from the SDK first (an environment outside the Public cloud goes to `pac` at once), `schema --dataset --table` and every SDK refusal through `pac model genpage`; one pure-ASCII JSON line with `source`
create-connection-reference.js ← Creates Dataverse connectionreference rows for connector bindings
- list-custom-apis.js ← Discovers bindable Custom APIs (Global + entity-bound) + parameter kinds (custom-api gated)
+ list-custom-apis.js ← Discovers supported public Custom APIs (Global + entity-bound), primitive kinds + separate lookup inputs (custom-api gated)
list-languages.js ← /genpage planner: the environment's base language and each provisioned language (LCID, culture code, right-to-left) — the SDK's `getEnvironmentLanguages()` over the az-token client, three reads and no write, printed as one pure-ASCII JSON line. The only source: no `pac model list-languages` stands behind it, because every /genpage page operation needs the Azure CLI
apps.js ← the replacement for `pac model list` and `pac model create` that /genpage and /app-builder run (`pac-replaced-docs.test.js` pins that their text names this script, not the `pac` commands): the environment's model-driven apps and a new app that opens on generative pages, through the bundled SDK. `list` prints each app's id, name, unique name, description and two facts, apart: `published` (it has a row in the published layer: users can open it) and `unpublishedChanges` (it has a saved row that is not published) — drafts included; `pac`'s "(Saved - Not Published)" is neither of them (see the spec section) and never part of the name. `create --name --solution --page-id <guid> [--page-id …] [--unique-name] [--description] [--publish]` makes the app with one area "Main", one group "Pages" and a sub-area per page, titled with the page's stored name; the app and its sitemap join the solution (a system solution such as `Default` holds them already: `systemSolution: true`); it is published only with `--publish`. The default public view of each table the pages read (the tables come from each page's own configuration, the views from the page backend: the definition `placeInApp` pins with) joins the app's components in the create itself — `components.views` of the app the SDK creates, written by the same AddAppComponents that adds the sitemap — as `pac model genpage upload --app-id` pinned them; the output says what was pinned (`dataSources`, `pinnedViews`), a table with no default public view or a page held as raw files is named in `warnings`, and a page that cannot be read refuses the create before the first write. Every check — no page id, a page that does not exist, a solution that does not exist or is managed, a taken unique name, an unreadable base language — is a refusal printed as `{ ok: false, code, error, written: false }` before the first write; a failure after the push began reads the platform back and prints what is actually left of this create (its rows are recognised by their ids, and a row that holds the unique name under another id is named apart)
list-tables.js ← the replacement for `pac model list-tables` (the skills' and agents' text runs this script: `pac-replaced-docs.test.js`): the environment's tables — the SDK's `findTables(term)` for each comma-separated `--search` term, a few reads at a time, joined without repeats; `--exact` keeps the tables whose logical name IS a term and names the terms no table has (`missing`), from one read of every table; `--type custom|standard|all` is `pac`'s own filter, `custom` through the SDK's `customOnly` option. One pure-ASCII JSON line of `{ logicalName, displayName, schemaName, isCustom }` rows. An answer that is no list of tables — a 2xx with no `value` list: a sign-in page, `{}`, `null` — fails `TABLES_UNREADABLE` (exit 1) instead of reading as "no tables, every searched one missing" (`lib/collection-answers.js`)
@@ -2353,22 +2628,23 @@ scripts/
capture-fixture.js ← Copies /genpage working dir into an eval fixture and runs both runners
lib/
entity-provision.js ← Shared entity-provisioning core (solution + data-model + sample-data): a new table is created with only its primary name attribute and its ordinary columns follow in one atomic change set (`createColumns`), falling back to one request per column (unless the run's throttle budget refused to wait for the change set: the phase then stops, `stop`); the primary name column's length is always sent (100 unless the spec gives one), its required level is asked in the create when the spec states one (and said applied only when the SDK confirms it) and, where the platform did not keep a length the spec gave, set last in the phase — a length a failed attempt left unset is owed to the build's retry (`owedLengths`, paid only to the table that attempt created: proved by its MetadataId, and then written by requests addressed with the ids, which a table made again cannot answer to), and an alternate key over that column is made after it; `makeRunner`, whose runner stops the phase at the next step once the run's throttle budget has refused a wait (`stopIfRefused`: `run` and each item of its `mapLimit`; a step that pays the name column length a table the run created is owed is let through); and `mapLimit`, the bounded fan-out every parallel path reuses
- retry-policy.js ← when the build runs a failed phase again, decided from what the SERVICE said and never from what the maker named: `RETRY` (`NEVER` — a refusal of the spec, an identity or ownership conflict, an approval, a prerequisite, a file on the maker's machine; `SERVICE` — what the failure it wraps says), `judgeFailure(error, { declares })` (an explicit `transient: false` anywhere along the causes wins; then the HTTP status 429, 502, 503, 504; then a condition the service names by the `error.code` of its answer — `TRANSIENT_SERVICE_CODES`, a SQL deadlock victim (the generic SQL error code `0x80044150` AND the platform's `Sql Number: 1205` — the last SQL number the answer gives — in the service's own answer, `isDeadlockVictimAnswer`), and the lag of a column the spec creates (`declares`) — on any status; then a timeout or reset of the transport (by Node's own code when the error carries one, by its words only when it has none); then **any other HTTP status is final** whatever the answer's words say; then the SDK's or plugin's own type — a refusal, whatever it quotes (bar the SDK's wrapper of a failed publish, read by the status of the answer it embeds); then, only for a failure that carries no status at all, the service's own words, never a halt's message), `throttleAskOf` (what a throttled failure asks of the next send: `retryAfterMs` and `retryNotBefore`), `retryPolicyFor` / `retryFrom` (the policy a halt is raised with), `refusal` / `serviceFailure` (the errors the engine itself makes; `serviceFailure`'s `answered` records the OData error of an answer the engine read with a request of its own — its `code` and `message`, nothing else — and the rule reads that code as it reads the SDK's) and `withCause` (the failure a by-value result carries); `BuildHalt` takes `retry`, `retryText` and `statusCode`; build-model-app.js `isTransientHalt` is its one reader, and `tests/halt-retry-policy.test.js` holds every halt in the sources to a row of its table
+ retry-policy.js ← when the build runs a failed phase again, decided from what the SERVICE said and never from what the maker named: `RETRY` (`NEVER` — a refusal of the spec, an identity or ownership conflict, an approval, a prerequisite, a file on the maker's machine; `SERVICE` — what the failure it wraps says), `judgeFailure(error, { declares })` (an explicit `transient: false` anywhere along the causes wins; then the HTTP status 429, 502, 503, 504; then a condition the service names by the `error.code` of its answer — `TRANSIENT_SERVICE_CODES`, a SQL deadlock victim (the generic SQL error code `0x80044150` AND the platform's `Sql Number: 1205` — the last SQL number the answer gives — in the service's own answer, `isDeadlockVictimAnswer`), and the lag of a column the spec creates (`declares`) — on any status; then a timeout or reset of the transport (by Node's own code when the error carries one, by its words only when it has none); then **any other HTTP status is final** whatever the answer's words say; then the SDK's or plugin's own type — a refusal, whatever it quotes (bar the SDK's wrapper of a failed publish, read by the status of the answer it embeds); then, only for a failure that carries no status at all, the service's own words, never a halt's message), `throttleAskOf` (what a throttled failure asks of the next send: `retryAfterMs` and `retryNotBefore`), `retryPolicyFor` / `retryFrom` (the policy a halt is raised with), `refusal` / `serviceFailure` (the errors the engine itself makes; `serviceFailure`'s `answered` records the OData error of an answer the engine read with a request of its own — its `code` and `message`, nothing else — and the rule reads that code as it reads the SDK's) and `withCause` (the failure a by-value result carries); `BuildHalt` takes `retry`, `retryText` and `statusCode`; build-model-app.js `isTransientHalt` is its one reader, and `tests/halt-retry-policy.test.js` holds every halt in the sources to a row of its table; an error that WRAPS the failure it carries as its `cause` (`CAUSE_WRAPPER_CODES`: `WEB_RESOURCE_UNVERIFIED`) is judged by that cause, read whether or not it is enumerable, and never by its own code or words — and one that carries no cause is run again
throttle-budget.js ← the budget a run allows itself for the waiting it does when a service throttles — five minutes, shared by the HTTP client's waits before it sends a throttled read, publish, delete or column create again (`deps.throttle` of `lib/sdk-http-client.js`), the page backend's waits between the sends of a page write (a `$batch` the HTTP client never re-sends) and the build's own waits before it runs a phase again (the upload script makes one for its run) (`makeThrottleBudget({ totalMs, warn })`: `fits(ms, at)` and `spend(ms, at)`, which answers what the wait added — a wait the client PLACES on the clock (`at`) adds only what runs past the waits placed before it, because requests sent together are throttled together and wake together, while the backend's and the build's, which wait one at a time, place nothing and add whole; `announce` for a wait longer than five seconds, on the `warn` seam the build wires to stderr; `decline` / `declined`, where the client says that a wait did not fit — in the words of `refusedWait`: what the service asked and that the request was not sent again, with no advice on what to run, because a refused request can follow a write that committed — and the build's retry loop and the engine's runner read it (the loop to stop with the halt, the runner so that no step starts after it), since the answer the client hands back carries nothing of what the service asked; `note`; `waitDoesNotFit`, the sentence of the `throttle-budget-exhausted` halt: what the service asked, how much is spent, that a later run of the same command continues); it only counts, each layer waits with its own seam. What is not drawn from it is a wait that is not for a throttle — a 5xx, a reset connection, a deadlock victim's re-send — and the waits of a client given no budget
provision-input.js ← Input validation for entity provisioning (the entry gate of `/genpage` and `/app-builder`; it applies `app-spec.js`'s own `primaryNameLengthProblem`, `autoNumberFormatProblem` and `requiredValueProblem`, so a name-column length, an AutoNumber column with no format and a `required` that is not `true`, `false` or `"recommended"` are refused here exactly as in `validateAppSpec`)
dataverse-auth.js ← Shared auth + HTTP helpers (`az account get-access-token`, memoized per process and replaced on a 401 — a synchronous `az` call, which a caller running other probes beside the request opts out of with `refreshOn401: false`; responses decoded as UTF-8 once; a request that fails is reported as `{ error, code? }` — the message and, when Node gave one, Node's own error code (the failures this module words itself have none), which `lib/sdk-http-client.js` reads to decide whether the request is worth sending again; an answer that is not a success, and a transport failure's text, come back from `dataverseRequest` with every token the call sent taken out — the one `scrub` of `sdk-http-client.js`, a success untouched; every token read from the Azure CLI, and every one `dataverseRequest` sends, is noted in `lib/output-redaction.js`, which keeps it out of everything the process writes, and `emitResult` cleans its own text the same way; an environment URL is used only as a Dataverse https origin, `dataverseOrigin`; a request path must stay under `/api/data/v9.2/` as both the client and the server resolve it, `webApiUrl`), the Azure CLI token for the Power Apps service (`getPowerAppsToken`: the same read for another resource, memoized apart from the Dataverse token and asked for only by the Power Apps service client and the connectivity preflight), plus the CLI arg contract (parseArgs/validateFlags, and `readLanguageCodeFlag` — the `--language-code` / `--languageCode` flag as an LCID, which `verify-model-app.js` reads exactly as the build does) and the result printer (`emitResult`, whose `{ ascii: true }` option writes stdout JSON as pure ASCII for a script an agent reads off a console)
process-runner.js ← how every script starts az/pac/npm/npx/git: the executable is resolved to an absolute path on PATH, never the project folder, and started without a shell (a Windows batch shim runs through cmd.exe with its arguments checked — except a launcher that only forwards to the native program beside it, the Windows MSI's two-line `pac.cmd` (`@echo off` / `"%~dp0pac.launcher.exe" %*`): it is recognised by its exact lines — `@echo off` on a line of its own, then the forwarding line, as `cmd` reads lines, so a one-line `@echo off "%~dp0x.exe" %*`, which is an `echo`, is not one — and the program beside it (`forwardedProgram`) and that program is started directly, so a `%` or a double quote reaches it unchanged; every other batch file keeps the checked route and its refusal of them); `killProcessTree` ends a stalled child AND everything it started (`taskkill /T /F` on Windows, where `pac.cmd` is cmd.exe → pac.exe, looked up with the System32 folder first on PATH so a PATH without it cannot leave the tree running, and with its window hidden; SIGKILL to the descendants `ps` lists elsewhere, each only once `ps -o lstart= -p` shows its pid still has the start time the listing saw — a descendant that exited meanwhile can have its pid given to an unrelated process; best effort, since two processes can share a one-second start time and the moment between that read and the signal is not covered), through the same audited calls; a child that has already exited is only asked to die, never ended by its pid, which may be another process's by then; synchronous, and it never throws. `spawnResultTree` is `spawnResultSync`'s asynchronous twin (same result shape, never rejects) for a call that may have to be ended: one that outlasts its `timeout`, or writes past `maxBuffer`, has its whole tree ended through `killProcessTree` before the call settles (`ETIMEDOUT`, `ENOBUFS`), after a short wait for the pipes of what was ended; the error says whether they closed (`containment`: `confirmed`, or `unconfirmed` when a process that outlived the ended tree still holds them, with the `pid` the call was started as)
cli-failure.js ← how a CLI child failed (timeout / missing / failed), the Azure CLI budget (60 s, `POWER_PLATFORM_SKILLS_AZ_TIMEOUT_MS`), so a slow `az` is never reported as missing or signed out; `commandArg` writes an argument of a command a message tells you (or the agent) to paste so that, run from PowerShell (Windows PowerShell 5.1 or PowerShell 7) or a POSIX shell, the program gets it unchanged as one argument — bare when it is plain, single-quoted otherwise (a path from an untrusted checkout can hold `;`, `$(…)` or backticks) — or not at all when no spelling does that in every one of those shells: a quote or a line break, and the values Windows PowerShell changes on their way to a native program (a `"`, white space with a final `\`, the empty value) or both PowerShells read as the stop-parsing token (`--%`), all measured. `commandArgOrPlaceholder` then writes a placeholder and names the value outside the command
- nearest-name.js ← pure single-edit "did you mean" matcher for closed vocabularies (CLI flags, FetchXML operators)
+ nearest-name.js ← pure single-edit "did you mean" matcher for closed vocabularies (CLI flags, FetchXML operators, `fieldOptions` keys)
compare-text.js ← `compareText`, the text order for any list a script writes and a diff between two runs then reads: UTF-16 code units after lower-casing, the raw text breaking a tie; never `localeCompare`, whose order follows the host's ICU locale and version (the download's lists use it)
lcid-cultures.js ← pure: a Windows language id (LCID) → culture code and right-to-left, from a table of Windows' own culture data (what `pac` printed; the SDK reports numbers only, and no Intl API maps an LCID); a language id with no entry stays numeric and is reported, never guessed (`list-languages.js`)
supported-dependencies.js ← Single source of truth for runtime + dev deps versions
- feature-flags.js ← Default-OFF feature flag probe + Custom API script backstop
+ feature-flags.js ← Feature flag probe with fail-closed fallback + Custom API script backstop
sdk-build.js ← app-builder build engine (idempotent; incl. the pages phase). Every way it pushes or publishes the app is one of `appWriters`, which first awaits `publishTablesBeforeApp` (the one request that publishes, before the app, the tables whose forms or charts its publish ships)
app-components.js ← shared current/published app layers (`currentLayerRows`, and `currentLayerRow` — the authored layer wins — for a listing), component inventory (`readAppComponentInventory`: the download's read, with two opt-ins the build's pre-app proof makes — `savedLayer`, which looks the tables of the form and chart components up in the SAVED layer, and `requireIdentified`, which reads the answer strictly: a row counts for an id the list asked about, two tables for one id or a value no table has make the read incomplete, and a row of the component list that cannot be placed — no record, no GUID objectid, another component type — makes the list unreadable), hidden-table pin/proof, Main-form resolution/membership and push directives, `collectionRows`, the one reader of a paged collection, and `savedPageRows`, the one reader of the generative-page rows in the SAVED layer (RetrieveUnpublishedMultiple, 50 ids a read): a plain read of the page table answers the published layer only, so a page that was created and never published is "not found" by it — `apps.js` and teardown read pages here
solution-membership.js ← one read of a solution's components (the types the build adds, plus its tables: a table held with all its subcomponents vouches for its views, forms and charts, which have no rows of their own), so a rebuild adds just what the solution is not PROVEN to hold; every doubt reads as "add"
unsynced-edits.js ← the SDK's own dirty tracking (`diffArtifact`) as the one proof that a reconcile has nothing to push; every doubt reads as "push"
table-publish.js ← the tables a spec names (`specTables`, the wide READ-ONLY list a halted build reads), the tables the build publishes before the app (`preAppTables`: what it changed — reconciled tables, the tables of the charts it wrote — the tables whose Main forms its own write of the app adds (`appWriteTables`: the navigation's tables, from the spec and how the SDK writes the app, honouring `app.mainForms` — for a writer that sends the spec's navigation; `appPushTables` takes the Entity tables of the navigation a writer does send, the placement's and the routing-description push's, and the Main-form list that push carries), and the tables the app is PROVEN to hold a form or chart of; the spec decides nothing else, so never a table that is only declared, a lookup's target, read only by a page or only pinned in `app.tables`), the proof (`readAppFormChartTables`: the app's form and chart components on the server, looked up in the saved layer, complete and unambiguous or nothing), the ONE `PublishXml` that publishes tables by name (`publishTablesXml`: the build's pre-app publish, and the lookup-label repair's), the read of which of the spec's views, forms and charts are saved but not published (`readSavedNotPublished`, the SAVED layer through `RetrieveUnpublishedMultiple`, `componentstate` 1 and 3) with the line a halted build prints from it (`describeSavedNotPublished`), and the warnings for a refused pre-app publish and for an app whose components could not be read (`describePreAppRefusal`, `describeUnreadAppComponents`); every doubt in a read says so and names the tables, never a shorter list
+ publish-xml.js ← the plugin's OWN publishes (`postPublishXml(dataverse, parameterXml)`: the tables `table-publish.js` publishes by name, and the app `app-components.js` publishes after pinning its tables) — the one place they are sent, and the one layer that re-sends one SQL rolled back as a deadlock victim (1 s / 2 s / 4 s, four sends at most, by `sdk-http-client.js`'s own predicate): the HTTP client sends a publish once, and the SDK's publishes are re-sent by the SDK's own `publishXml`
stages.js ← stage→phase-range mapping + PHASES/STAGES constants
op-diff.js ← destructive-op diff + --allow-destructive / --non-interactive gating
artifact-intent.js ← pure App Spec → canonical SDK intent compiler (new form topology; no SDK calls)
@@ -2387,17 +2663,20 @@ scripts/
app-source-path.js ← shared lexical + realpath confinement for app source reads/uploads and hashes
page-ownership-records.js ← local CREATE receipts and pre-delete ownership records, scoped to app/key/id; and the `pending` records of a page create that was started and not acknowledged (written before the create is sent, under the id it will use, with the name and the SHA-256 of the source it sends — one per create sent under the id; intent, never ownership: `readPageOwnership` does not see it, `readPendingCreations` / `completePendingCreations` settle it, and only evidence settles it — an acknowledged create, a page proven to be the one sent, a teardown that deleted the page — never an absence from a listing)
page-publish-records.js ← `page-published.<hash>.json`, one file per app and environment in the build workspace: per page, the hash of the content (`contentFingerprint`) it was last PUBLISHED with and the version number of every one of its file rows and of its own row (the plain reads `genpage.fileVersions` and `genpage.projectVersions`), written only after a publish seen to take effect, and with versions only when they were read on both sides of a read-back of the page's published copy (`genpage.publishedDiffers`), were the same set, and the copy held the content and the compiled output the draft held when it was published (`runtimeSha256`). The build hands the hash back to `genpage.update` as `publishedFingerprint` only for a page whose rows read now are exactly the recorded set at the recorded versions (`sameFileVersions`), so an unchanged page is not published again and a page published, renamed or saved from elsewhere is; a cache, never an authority — anything missing, damaged, for other content, without versions or with a moved version reads as "not known to be published" and costs one publish, and the schema (3) is the proof's version: a record of an earlier schema is read for its hashes and skips nothing; it grants and blocks nothing (`readPublishedPages` never throws, `writePublishedPages` failing is one warning)
+ web-resource-records.js ← `web-resource-unconfirmed.<hash>.json`, one file per environment in the build workspace: the web resources this workspace's builds wrote and could not confirm were published (`WEB_RESOURCE_UNVERIFIED`), by name and id. `openUnconfirmedWebResources` is a run's view of it (`idOf`, `note`, `clear`; it never throws: a record it cannot read is "nothing recorded", said once, and a run with no workspace records nothing). A name it holds is written again by id by the next run (sdk-build.js `writeOwnedWebResource`, `persistPageManifest`) instead of being reused untouched; the entry is cleared once that write verified and the row is in the solution. Each change is made under the record's writer lease (`record-lease.js`) to the file as it is then, so builds sharing the workspace keep each other's entries: a note never replaces an entry with another row's id that another build recorded since this run read the file (said once; `note` answers false; a note of the same row is a later unconfirmed write of it and takes the entry's place with a revision of its own), and a clear removes only the entry its run knows — its id AND the revision of the note that made it (`revisions`, written beside the name-to-id map), so a later unconfirmed write of the same row that another build noted survives a clear by a build that verified an earlier one; an entry written without a revision is matched by its id, as before
+ dashboard-creation-records.js ← `dashboard-creation.<hash>.json`, one file per environment, app and solution in the build workspace: the dashboards this workspace's builds CREATED and have not yet seen join the solution, by name — the id the create was sent with (the SDK sends the workspace's own id as `systemform.formid`), noted before the push, and the id the push reported when that is another. `openDashboardCreations` is a run's view of it (`idsOf`, `note`, `observe`, `clear`, `path`; it never throws: a record it cannot read — an entry it does not write included — is "nothing recorded" and is never written over or removed, said once; a run with no workspace, environment or solution records nothing). Cleared once the row is in the solution or the build's own undo deleted it; the next run reads each recorded id in the saved layer before any name lookup and adds the row the create made to the solution — after a re-key only the reported one (sdk-build.js `recoverRecordedDashboard`) — never a namesake, never a delete, never teardown authority. Each change is made under the record's writer lease (`record-lease.js`) to the file as it is then, comparing the whole entry (both ids), so builds sharing the workspace keep each other's entries: `note` never replaces an entry another build recorded or changed since this run read the file (said once), and a note of the id the entry already holds keeps its reported id; `observe` adds only to the entry as its run noted it; `clear` removes only the entry as its run knows it, and answers null when another build has changed it since — when every id it recorded read as absent, `recoverRecordedDashboard` then stops instead of creating a dashboard on the word of the older entry (after the row joined the solution, a changed entry is left and the build goes on)
+ record-lease.js ← the writer lease of a workspace record (`withRecordLease(root, file, change)`): the change runs while `<record file>.lock` is held — the workspace lease protocol (`apply-snapshot-store.js acquireLease`: exclusive create, exclusive reclaim, owner-checked release), stamped and judged as the pages lock is (`process-owner.js`: taken over only from a build proven gone, never by age). A lock another build holds is tried `LEASE_ATTEMPTS` (10) times `LEASE_WAIT_MS` (100 ms) apart and then given up — the change is not made and its record says so once — so a build never hangs on it. Used by `web-resource-records.js` and `dashboard-creation-records.js`; reads take no lease
source-literals.js ← TSX lexer (code/comment/string/template/regex/JSX) — see "Known limits" below
sdk-teardown.js ← app-builder teardown engine (planTeardown is pure)
- sdk-http-client.js ← az-token HttpClient for the vendored SDK; a caller can name requests that are sent exactly once (`sendOnce(method, url)`: no retry on a transport failure, a 429 or 5xx, or a 401 refresh, and none of the replays special to a record delete and a `$batch` either) — `solution-settings.js` does for the three long solution actions; a caller can hand it the run's throttle budget (`deps.throttle`, lib/throttle-budget.js): every wait it takes before it sends a throttled request (HTTP 429, alone or as every operation of a `$batch`) again is then drawn from the budget — the answer's `Retry-After` whole, past the cap of a minute, or the schedule's wait when that is longer, placed on the clock so that requests throttled together are charged once — and a wait that does not fit is not taken: the 429 comes back as it came and the budget is told what the service asked (`decline`); every other wait (a 5xx, a reset connection, a deadlock victim's re-send) keeps its own schedule, and the budget is duck-typed and never loaded here, so the pcf copy, which has none, waits as it always did; an answer that is not a success comes back with the access token taken out of it (and a transport failure's text too, the error that carries Node's code included), a success untouched — the one `scrub` / `scrubAnswer` the Power Apps client uses as well; `needlesOf(token)` and `TOKEN_MARKER` are `lib/output-redaction.js`'s: the one list of texts a scrubber takes out of one token (the token and each of its parts of 24 characters or more) and the one marker, so the client's scrubber and what the process writes are kept free of a token by the same list, and each token the client sends is noted there (`noteToken`); `throttleBackoffMs(attempt, random)` is the capped, jittered schedule every throttled request waits on (1 s, 2 s, 4 s, 8 s, 8 s), exported because the page backend waits out a throttled page write on it (the client never re-sends a page's `$batch`: `lib/genpage-sdk.js` does, a push at a time); `retryAfterMs(headers, now, cap)` and `batchRetryAfterMs(res, now, cap)` cap what a response asks at a minute for the client's own retries, and a caller with a bound of its own passes `Infinity`: the page backend spends it inside the run's budget, the client itself does when it has that budget, and `solution-settings.js` inside the one budget of its import resend; `completeBatchStatus(res)` is the one status a COMPLETE multipart answer reports for every operation (the page backend reads a change set refused as a whole with it); the parser behind it, `isBatchThrottled` and `isBatchDeadlockVictim` is strict — an answer is read only when its outer boundary closes, every change set in it closes, and every part is a complete response whose first line is a status line; a part that declares a change set (`Content-Type: multipart/mixed; boundary=…`) must open and close exactly that boundary before the outer one goes on, a part with no response in it is an operation nobody answered, and a body is as long as the `Content-Length` its response gives, counted by the line breaks the answer has; a part that declares a `Transfer-Encoding` (chunked or any other) is not read at all, whole stream or not — the delimiters around it say nothing of whether its chunk stream is finished, so it never certifies a refusal or a deadlock victim; anything missing or malformed makes the WHOLE answer unproven (an answer that closes its outer boundary and is incomplete inside proves nothing); `isTransientTransportFailure(text, code)` says which failures of the transport are sent again — decided by Node's own error code when `makeRequest` reported one (`TRANSIENT_TRANSPORT_CODES`: `ECONNRESET`, `ETIMEDOUT`, `ESOCKETTIMEDOUT`, `ECONNABORTED`, `EPIPE`, `EAI_AGAIN`; any other code is final whatever the words say) and by the words only when it did not (a certificate's own phrases first): a reset, a timeout, an answer cut off, a temporary DNS failure, the same list `lib/retry-policy.js` calls a blip, and nothing else — a certificate that does not verify (whatever names it quotes), an unknown host and a message nobody recognises return at once; the error it throws carries the code beside the same message (this file is copied into the pcf plugin, so a test holds the two lists equal). Copied verbatim into `plugins/pcf` (`scripts/validate-plugin-copies.js`)
+ sdk-http-client.js ← az-token HttpClient for the vendored SDK; a caller can name requests that are sent exactly once (`sendOnce(method, url)`: no retry on a transport failure, a 429 or 5xx, or a 401 refresh, and none of the replays special to a record delete and a `$batch` either) — `solution-settings.js` does for the three long solution actions; a caller can hand it the run's throttle budget (`deps.throttle`, lib/throttle-budget.js): every wait it takes before it sends a throttled request (HTTP 429, alone or as every operation of a `$batch`) again is then drawn from the budget — the answer's `Retry-After` whole, past the cap of a minute, or the schedule's wait when that is longer, placed on the clock so that requests throttled together are charged once — and a wait that does not fit is not taken: the 429 comes back as it came and the budget is told what the service asked (`decline`); every other wait (a 5xx, a reset connection, a deadlock victim's re-send) keeps its own schedule, and the budget is duck-typed and never loaded here, so the pcf copy, which has none, waits as it always did; an answer that is not a success comes back with the access token taken out of it (and a transport failure's text too, the error that carries Node's code included), a success untouched — the one `scrub` / `scrubAnswer` the Power Apps client uses as well; `needlesOf(token)` and `TOKEN_MARKER` are `lib/output-redaction.js`'s: the one list of texts a scrubber takes out of one token (the token and each of its parts of 24 characters or more) and the one marker, so the client's scrubber and what the process writes are kept free of a token by the same list, and each token the client sends is noted there (`noteToken`); `throttleBackoffMs(attempt, random)` is the capped, jittered schedule every throttled request waits on (1 s, 2 s, 4 s, 8 s, 8 s), exported because the page backend waits out a throttled page write on it (the client never re-sends a page's `$batch`: `lib/genpage-sdk.js` does, a push at a time); `retryAfterMs(headers, now, cap)` and `batchRetryAfterMs(res, now, cap)` cap what a response asks at a minute for the client's own retries, and a caller with a bound of its own passes `Infinity`: the page backend spends it inside the run's budget, the client itself does when it has that budget, and `solution-settings.js` inside the one budget of its import resend; `completeBatchStatus(res)` is the one status a COMPLETE multipart answer reports for every operation (the page backend reads a change set refused as a whole with it); the parser behind it, `isBatchThrottled` and `isBatchDeadlockVictim` is strict — an answer is read only when its outer boundary closes, every change set in it closes, and every part is a complete response whose first line is a status line; a part that declares a change set (`Content-Type: multipart/mixed; boundary=…`) must open and close exactly that boundary before the outer one goes on, a part with no response in it is an operation nobody answered, and a body is as long as the `Content-Length` its response gives, counted by the line breaks the answer has; a part that declares a `Transfer-Encoding` (chunked or any other) is not read at all, whole stream or not — the delimiters around it say nothing of whether its chunk stream is finished, so it never certifies a refusal or a deadlock victim; anything missing or malformed makes the WHOLE answer unproven (an answer that closes its outer boundary and is incomplete inside proves nothing); `isTransientTransportFailure(text, code)` says which failures of the transport are sent again — decided by Node's own error code when `makeRequest` reported one (`TRANSIENT_TRANSPORT_CODES`: `ECONNRESET`, `ETIMEDOUT`, `ESOCKETTIMEDOUT`, `ECONNABORTED`, `EPIPE`, `EAI_AGAIN`; any other code is final whatever the words say) and by the words only when it did not (a certificate's own phrases first): a reset, a timeout, an answer cut off, a temporary DNS failure, the same list `lib/retry-policy.js` calls a blip, and nothing else — a certificate that does not verify (whatever names it quotes), an unknown host and a message nobody recognises return at once; the error it throws carries the code beside the same message (this file is copied into the pcf plugin, so a test holds the two lists equal); a publish (`PublishXml`, `PublishAllXml`) is sent ONCE but for a 401 and a 429 of the service protection limits (`isServiceProtectionRefusal`, `SERVICE_PROTECTION_CODES`: the three codes the api-limits page documents) — never for the customization lock's 429, a 5xx or a failure of the transport — and its deadlock victim is the layer above's to re-send (`isSqlDeadlockVictim` and `DEADLOCK_RESENDS` are exported for `publish-xml.js`). Copied verbatim into `plugins/pcf` (`scripts/validate-plugin-copies.js`)
maker-sdk.js ← the one way a script makes an SDK: the vendored bundle with the vendored TypeScript compiler as its page compiler, and with the client it is handed guarded by `app-header-text.js`; `connectivity: true` (opt-in) also gives the instance the Power Apps service client, so no script wires a credential-carrying client by hand; and the `httpClient` it is given is handed over with the read of the environment's TABLE LIST held to being a list (`lib/collection-answers.js` `guardTableLists`), so every script's `findTables()` meets a failure (`TABLES_UNREADABLE`, an `SdkError`, so `error.code`) where the bundle alone would read a sign-in page, `{}` or `null` as "no tables" — none can forget it; and the `workspaceStorage` it is given is handed over with every text it is asked to write taken clean of the access tokens the process obtained (`lib/output-redaction.js` `guardWorkspaceStorage`: the SDK writes every file of its workspace through `writeTextAtomic`, and the wrapper is the storage in everything else), so a token a service repeated in an answer cannot land in a workspace file. The SDK itself — its errors, its warnings, its results — is exactly what the bundle makes: what a script WRITES is what is cleaned
- output-redaction.js ← keeps every access token the process obtained out of everything it WRITES, and out of nothing the service or the SDK made: `noteToken(token)` (called where a token is read from the Azure CLI — `dataverse-auth.js`, both reads — and where `dataverseRequest` and the SDK's HTTP client send one) is the registry, and the first token noted guards the process: `guardStream` wraps `process.stdout.write` and `process.stderr.write` (every `console.*` call, every script's result and warning printer, a library's own output end there; text only, bytes pass), and `guardFatalErrors` prints — cleaned — what Node itself prints when an error ends the process, which never passes through `process.stderr.write` (only when nothing else handles the error: a test runner's own listener is left alone). `redactOutput(text)` is what the file writers call (`safe-fs.js` `writeFileSafe` and `appendFileSafe`, `apply-snapshot-store.js` `writeFileAtomic`) and `guardWorkspaceStorage` wraps the SDK's `writeTextAtomic` (`maker-sdk.js`). `redactTokens(text, tokens)` is the matcher: it reads the text as it SPELLS a token, one character at a time — the character itself or an escape of it (`\uXXXX` in either case, `\xXX`, `\/`), with a fold between any two of them (white space, `\r\n` `\t` `\b` and the like as JSON writes them, a run of backslashes before an escape: JSON inside JSON, a stray backslash, a terminal colour code, the quote-plus-line-break `util.inspect` prints between the pieces of a long string, in colours or not) and an escape that can also be a literal backslash and letters (`\n` before a signature that starts with `n`) read both ways — every needle (the token and each part of 24 characters or more: `needlesOf`) in ONE linear pass with a bounded set of readings beside it (a text that would need more is refused: the writer fails closed), the whole span from the token's first character to its last becoming `<token>`, so that JSON that was written is JSON still. It never touches an error, a warning or an answer: the SDK's errors keep every word the SDK gave them, and the strict `$batch` readers see the bytes the service sent. Not read: other encodings of a token (percent-encoding, base64, entities), a token another process obtained, bytes, a token written in two separate calls to `write`, and the end of a part a formatter cut short. `makeWritesBlocking(...streams)` makes a stream's writes blocking for the last writes of a process — `emitResult`, `guardFatalErrors`, and every printer of a script's own that ends the process after writing (a result, a usage error, a last-resort handler, a hook's message, the warnings a script prints right before its result) — because on Linux and macOS a pipe's writes are queued and `process.exit` does not wait for them, so a large result reached its reader cut short (`tests/result-whole-before-exit.test.js`, `tests/printers-whole-before-exit.test.js`: each process records the order in which it makes its streams blocking and writes to them — the check that fails on every runtime for a printer without the call — and the text a reader receives; nothing else about the stream changes, the guard included). `tests/exit-writes-inventory.test.js` is a syntactic tripwire, not a proof: it fails on a new exit with no such call before it in its block (or that is not listed with the bound that makes it safe: it writes nothing, or a constant), and on a call that comes after a write of its block or leaves out a stream written before the exit; it does not follow calls or control flow, and does not see writes made in an enclosing block, before an `await`, or through a helper. Copied verbatim into `plugins/pcf` (`scripts/validate-plugin-copies.js`), where it also cleans `pcf-push.js`'s receipt and guards the SDK workspace `makePcfSdk` makes
+ output-redaction.js ← keeps every access token the process obtained out of everything it WRITES, and out of nothing the service or the SDK made: `noteToken(token)` (called where a token is read from the Azure CLI — `dataverse-auth.js`, both reads — and where `dataverseRequest` and the SDK's HTTP client send one) is the registry, and the first token noted guards the process: `guardStream` wraps `process.stdout.write` and `process.stderr.write` (every `console.*` call, every script's result and warning printer, a library's own output end there; a text cleaned as a string, bytes — a Buffer, a Uint8Array, a string in `base64` or `hex` — masked byte for byte with as many `*` in a copy, the very bytes when they hold none), and `guardFatalErrors` prints — cleaned — what Node itself prints when an error ends the process, which never passes through `process.stderr.write` (only when nothing else handles the error: a test runner's own listener is left alone). `redactOutput(text)` is what the file writers call (`safe-fs.js` `writeFileSafe` and `appendFileSafe`, `apply-snapshot-store.js` `writeFileAtomic`) and `guardWorkspaceStorage` wraps the SDK's `writeTextAtomic` (`maker-sdk.js`). `redactTokens(text, tokens)` is the matcher: it reads the text as it SPELLS a token, one character at a time — the character itself or an escape of it (`\uXXXX` in either case, `\xXX`, `\/`), with a fold between any two of them (white space, `\r\n` `\t` `\b` and the like as JSON writes them, a run of backslashes before an escape: JSON inside JSON, a stray backslash, a terminal colour code, the quote-plus-line-break `util.inspect` prints between the pieces of a long string, in colours or not) and an escape that can also be a literal backslash and letters (`\n` before a signature that starts with `n`) read both ways — every needle (the token and each part of 24 characters or more: `needlesOf`, and its base64, percent-encoded and HTML spellings: `spellingsOf`) in ONE linear pass with a bounded set of readings beside it (a text that would need more is refused: the writer fails closed), the whole span from the token's first character to its last becoming `<token>`, so that JSON that was written is JSON still. It never touches an error, a warning or an answer: the SDK's errors keep every word the SDK gave them, and the strict `$batch` readers see the bytes the service sent. The beginning of a needle, 24 characters or more, goes too where a text says it was cut (`util.inspect`'s `... N more characters`, an ellipsis) and at the end of a whole text the process writes, and the end of a needle at its start (`redactOutput`; `redactTokens(text, tokens, { edges: true })`); `maskTokenBytes(bytes, tokens)` is the same for bytes. Not read: a token another process obtained, a piece of a token shorter than 24 characters, a piece from the middle of one, and bytes given to a file writer. `makeWritesBlocking(...streams)` makes a stream's writes blocking for the last writes of a process — `emitResult`, `guardFatalErrors`, and every printer of a script's own that ends the process after writing (a result, a usage error, a last-resort handler, a hook's message, the warnings a script prints right before its result) — because on Linux and macOS a pipe's writes are queued and `process.exit` does not wait for them, so a large result reached its reader cut short (`tests/result-whole-before-exit.test.js`, `tests/printers-whole-before-exit.test.js`: each process records the order in which it makes its streams blocking and writes to them — the check that fails on every runtime for a printer without the call — and the text a reader receives; nothing else about the stream changes, the guard included). `tests/exit-writes-inventory.test.js` is a syntactic tripwire, not a proof: it fails on a new exit with no such call before it in its block (or that is not listed with the bound that makes it safe: it writes nothing, or a constant), and on a call that comes after a write of its block or leaves out a stream written before the exit; it does not follow calls or control flow, and does not see writes made in an enclosing block, before an `await`, or through a helper. Copied verbatim into `plugins/pcf` (`scripts/validate-plugin-copies.js`), where it also cleans `pcf-push.js`'s receipt and guards the SDK workspace `makePcfSdk` makes
app-header-text.js ← an app's header texts (`name`, `description`) held to plain text at the HTTP client every SDK is made with (wired in `maker-sdk.js`): a PATCH of an app module row that carries one that is not a string is refused before any byte is sent — `APP_HEADER_NOT_PLAIN_TEXT`, an `SdkError` marked `transient: false` — whether it is the SDK's `patch`, a `patchRaw`, or a PATCH inside a raw change set (`postRaw` / `post` to `$batch`), because the SDK writes every text its workspace copy holds whenever its own comparison read of the header cannot be made (503, 403, a thrown error, an empty 200). The build takes such a text off the copy before its push, so this is the last line of defence, for a push of a copy it did not clean. A batch that names the app module table and cannot be read is refused too. A delegating Proxy: every member it does not judge runs on the client itself. Also how such a text reads in a message (`describeHeldAppText`), which the guard's refusals share
batch-request.js ← a multipart `$batch` REQUEST read the way the service reads it — `readBatchRequest(text, contentType)`: the parts of the boundary the Content-Type declares, a change set one level down, one HTTP request in each part, answered as `{ operations: [{ method, target, contentId, body }] }`, or `{ problem }` for text it cannot read with confidence (cut short, another boundary, a part that is not a request). A body is only ever text: a line in it that looks like a request is not an operation. `app-header-text.js` reads a raw change set with it
throwaway-sdk.js ← `withThrowawaySdk({ env, prefix, httpClient? }, run)`: the bundled SDK, made through `maker-sdk.js`, over a throwaway workspace folder (made by `temp-workspace.js`) that is removed whichever way the run ends (a constructor, a storage or a module that throws included); `run(make)` gets a `make(extra)` for more instances over the same folder and the one client (`make({ languageCode })` is a writer). The one copy of what `apps.js`, `list-tables.js` and `list-languages.js` each wrote out
collection-answers.js ← `requireCollectionAnswers(client, { reads, unreadable })`: the HttpClient the SDK is given, with one addition — a 2xx answer to a read `reads(url)` selects must be a collection (`{ value: [...] }`), or the read throws what `unreadable` says; `unreadableAnswer(error)` finds that error, itself or under the SDK's `ConnectionError`. `guardTableLists(client, makeError)` is its policy for the one read of the environment's table list (`/EntityDefinitions?…`, which only `findTables()` makes), and `maker-sdk.js` applies it to every SDK a script makes: the SDK's `findTables()` is `body.value ?? []`, and the bundle is not edited
temp-workspace.js ← the one maker of the plugin's throwaway workspace folders, and the sweep of the ones a KILLED run left (`makeTempWorkspace(prefix)` in place of `fs.mkdtempSync(path.join(os.tmpdir(), prefix))`, at every entry point that makes an SDK workspace — the page backend, `withThrowawaySdk`, `sdkFirst`, build, download, teardown, verify, the `provision-*` scripts, `ai-preflight`, and `solution-settings`' pac scratch folder). A run killed outright (SIGKILL, "End task", a timeout) never reaches its `finally`, and what it left held the source of every page it read and the environment's address (`solution-settings`' pac scratch folder: a settings template, an exported package or a copy of the settings file, which can hold values; the sweep's note says which a folder held, by its prefix). The folders go together in one folder of the plugin's own, `<temp>/power-platform-skills-model-apps` (`-<uid>` after it on POSIX, where the temp folder is shared). That folder is a courtesy, never a reason for a run to fail: it must be a plain folder that only this user can change — POSIX: owned by the user and writable by no one else; Windows, which tells Node no owner and no permissions: a folder this process MAKES is given an explicit access list before anything is put in it — protected, with only this user, the system and the administrators on it, full control inherited by every workspace and record made inside — and read back, and one that cannot be made so is removed and not used; an EXISTING one is judged by its access list and its owner (`windows-folder-acl.js`) and used only if NO entry of the list, an inherit-only one too, lets anyone else add to it, write to it, delete it or take it over, and the user (or the administrators, who own what an elevated process makes) owns it) — and if it cannot be used, or will not take a new folder (mode 0500, an access list that denies this user; a Windows folder that is being removed refuses a new entry — and its access list cannot be got — for a moment, so the attempt is made again after short pauses, up to six in all, and a folder that is still refusing after the last is not asked again by that process), the workspace is made in the plain temp folder exactly as before, unrecorded and never swept, and an error is reported only when that fails too. Each folder is named for the process that made it (`genpage-4242-AbC123`: the prefix, the pid, `mkdtemp`'s six characters; a prefix that does not end in a hyphen is given one, so that the pid always follows the hyphen a sweep reads it from) and holds an owner record `.owner.json` (`process-owner.js`); the first workspace a process makes sweeps that folder (`sweepDeadWorkspaces`) — only a workspace whose owner is PROVABLY gone is removed (the name's pid must have no process — on Linux a pid that runs is looked into too, since the record's start time can show it was handed out again — and the record must agree with the name; the record is read again, and judged again, just before the removal; what is inside is removed first and the record last, and the record leaves the folder only for as long as the folder itself is being removed — it is renamed out to `<folder>.removing`, which Windows allows even while another process holds it open, and moved back if the folder will not go — and if even that is refused it stays beside the folder, whole, and is never WRITTEN into the folder instead, since a write can be cut off and a damaged record beside the whole one would strand the removal; a sweep that is killed between the move and the removal leaves that file and the empty folder, and the next sweep finishes the removal when the file is a record of the folder's own — its name, a record that names the pid in it, an owner that is gone — and the folder is empty or gone, and leaves anything that does not agree as it is — so a removal that fails, half way or at the very end, leaves a folder still known to be dead and found again by the next sweep (Windows with Node 20 keeps a file that was deleted while open, listed, until the holder lets go, and the folder cannot go meanwhile); at most 100 a run, out of 500 entries looked at: the entries are taken in name order and the next run starts after the last one looked at — a cursor, `.sweep-cursor.json`, one small file in the plugin's folder, written whole and there only while the folder holds more than a run looks at — so that a folder whose first 500 entries must be kept does not hide a dead run's workspace, or a removal a kill left half done, behind them for good), and a folder whose name names a pid that RUNS is not even opened (on Linux its record alone is read, for the start time that can show the pid was handed out again; Linux lets a file another process has open be removed) — on Windows a file that is deleted while another process has it open stays in its folder until that process lets go, so a sweep that read a live run's record could make that run's own removal fail — and the run says so on stderr (`⚠ removed 1 temporary workspace left in … by a run that is no longer running`). A run that may still be going, another machine's, a folder with no readable record (a release before this one's, a damaged record), a link, a file: left as they are. **A path inside a workspace that is given to a program of another make makes the workspace LENT, when it is made** (`makeTempWorkspace(prefix, { lent: true })`, as `solution-settings`' `templateThroughPac` does for pac): on POSIX such a program outlives a run that is killed, so the record — written ONCE, whole, to a file of its own and renamed into place, and never written again — says `lent: true`, and a sweep never takes a lent workspace because its maker is gone: only when its maker is gone AND it is old, neither the folder nor its record written to for seven days (`LENT_KEEP_MS`; pac gets an hour at most). Nothing follows the program or changes the record once it has started (a record that is changed later can be unreadable at that moment), and a record that is unreadable keeps the folder. Every caller that hands a path in a workspace to another program decides that when it makes the workspace. The plugin's folder is removed when the process ends with nothing in it, so a normal run leaves the temp folder as it found it — and so does a run that is cut short by `process.exit` or an error nothing catches (the `exit` event): it first removes the workspaces it made and did not lend that are still there, by the steps of a sweep (what is inside first, the record last), since it never reached the `finally` that would have; a LENT workspace is never taken at the end of the run that lent it, and what is not its own is never touched (`rmdir` takes the folder only when it is empty, and a run that loses the folder between making it and making its workspace in it makes it again); the one caller that removes a lent workspace itself, `solution-settings`, does it in a cleanup it registers with `lib/exit-cleanup.js`, which runs after the maker's listener has found the workspace still in the folder and left the folder, so that cleanup calls `pruneWorkspaceParents()` once its workspace is gone — the same `rmdir`, so a run that is cut short while pac runs leaves no empty plugin folder behind (a signal included: it ends a POSIX process with no `exit` event, and that cleanup is what runs). A POSIX signal is NOT one of these ends — its default action ends the process with no JavaScript run, and a listener, which would, replaces that default action in every script that makes a workspace (a process blocked in a synchronous `az` or `pac` call would no longer end when signalled, and the signal would have to be raised again to keep its status) — so a run that is signalled leaves its workspace for the next run's sweep, as a killed one does; a folder that cannot be used or a record that cannot be written costs the sweep, never the run. The sweep reads only the plugin's own folder, never the temp folder, which can hold hundreds of thousands of entries
- process-owner.js ← who made a lock or a workspace, and whether that process is gone — one place for the pages lock, the temporary workspaces and the snapshot lease's liveness check (`processAlive`, as it always was). `ownerStamp()` is what a maker records (pid, time, host, platform, and on Linux the pid namespace and the process's start time from `/proc`); `ownerState(stamp)` answers `gone` only when the stamp was made on this machine, by this kind of system, in this pid namespace, and no process has the pid (ESRCH) — or, on Linux, a zombie or a process with another start time has it (the pid was handed out again) — `alive` for a process that runs (this one included) and `unknown` for anything else: another machine, a stamp that is missing, damaged or not understood. **On Linux a pid is only a name inside its pid namespace, so the stamp AND the reader must both name theirs (`pid:[…]`, readable and well formed) and name the same one: a side that cannot (a hidden `/proc`: a container, hidepid, a sandbox), or two that cannot, is `unknown`, never "the same pid space".** A recorded `start` that is not `<boot id>:<ticks>` — empty, cut short, damaged inside a record that is still valid JSON — makes the record untrusted (`isOwnerStamp`: kept), and a start read from `/proc` that is not well formed is not compared: only two well-formed starts that differ show a pid handed out again, in the self-pid branch too. `ownerState` is a fact about the maker and only that: a workspace that was handed to a program that outlives its maker is kept by its age instead (`temp-workspace.js`, `lent`). Every doubt keeps; where no start time is cheap to read (Windows, macOS) a pid given to another process makes a dead run look alive, which keeps its lock or folder (the state of things before this module)
+ process-owner.js ← who made a lock or a workspace, and whether that process is gone — one place for the pages lock, the recovery records' writer lease (`record-lease.js`), the temporary workspaces and the snapshot lease's liveness check (`processAlive`, as it always was). `ownerStamp()` is what a maker records (pid, time, host, platform, and on Linux the pid namespace and the process's start time from `/proc`); `ownerState(stamp)` answers `gone` only when the stamp was made on this machine, by this kind of system, in this pid namespace, and no process has the pid (ESRCH) — or, on Linux, a zombie or a process with another start time has it (the pid was handed out again) — `alive` for a process that runs (this one included) and `unknown` for anything else: another machine, a stamp that is missing, damaged or not understood. **On Linux a pid is only a name inside its pid namespace, so the stamp AND the reader must both name theirs (`pid:[…]`, readable and well formed) and name the same one: a side that cannot (a hidden `/proc`: a container, hidepid, a sandbox), or two that cannot, is `unknown`, never "the same pid space".** A recorded `start` that is not `<boot id>:<ticks>` — empty, cut short, damaged inside a record that is still valid JSON — makes the record untrusted (`isOwnerStamp`: kept), and a start read from `/proc` that is not well formed is not compared: only two well-formed starts that differ show a pid handed out again, in the self-pid branch too. `ownerState` is a fact about the maker and only that: a workspace that was handed to a program that outlives its maker is kept by its age instead (`temp-workspace.js`, `lent`). Every doubt keeps; where no start time is cheap to read (Windows, macOS) a pid given to another process makes a dead run look alive, which keeps its lock or folder (the state of things before this module)
windows-folder-acl.js ← who can change a folder on Windows, where Node reports no owner and no permissions, and the making of a folder that only this user can: `windowsFolderIsPrivate(folder)` saves the folder's access list with `icacls <folder> /save` (SDDL: SIDs, in every language, not names) and reads the user's SID with `whoami /user /fo csv /nh`, both started through `process-runner.js` with System32 first on PATH, and answers `{ ok, reason, owner? }` — private only when NO entry that grants a right to add to the folder, remove from it, delete it, write its attributes or extended attributes, change who may or take it over names anyone but this user, the system or the administrators (an INHERIT-ONLY entry counts too: it does not apply to the folder, but it is what every workspace and every owner record made in it is given; denials and audits grant nothing; SDDL writes the machine's own Administrator and Guest accounts as the aliases `LA` and `LG`, which are the user's own only for the user whose account that is, as a CI runner's renamed built-in Administrator is; an audit list after the access list, as Windows' own folders carry, is read and ignored) AND the folder is owned by this user or the administrators — whoever owns a folder can rewrite its list, so a list that names only the user does not make a foreign folder the user's. The owner is the one thing `icacls` cannot print (`/save` stores the list and nothing else), so it is read with PowerShell (`[IO.Directory]::GetAccessControl(folder, Owner)`, a SID; the folder goes in through the environment and the script is passed encoded) — half a second, which is why it is the last thing asked (a folder the list has refused never starts it), and PowerShell that cannot run is "not private". The administrators are accepted as owner because a process that runs elevated (a CI runner is one) owns what it makes through that group by default, and the list trusts them anyway. A list that icacls ran and could not save — Windows is removing the folder, which cannot be opened meanwhile — is `unreadable`, a "no" that `temp-workspace.js` does not keep: it asks again after a pause, and drops an answer about a folder that was replaced while it was being judged; whatever else cannot be read, run or understood is not private, and `temp-workspace.js` then makes its workspace in the plain temp folder as before. `makeWindowsFolderPrivate(folder)` is for a folder this process has just made: `icacls <folder> /inheritance:r /grant:r *<user>:(OI)(CI)F *S-1-5-18:(OI)(CI)F *S-1-5-32-544:(OI)(CI)F` replaces its list, and the list is read back and must be exactly that — protected, nothing inherited, three grants, full control for the user
power-apps-service-client.js ← the HttpClient for the SDK's connection and connector reads: GET only, https only, a host allowlist that is exactly the hosts the SDK's connectivity code calls, redirects never followed, the Azure CLI token for the Power Apps service read only for a request that passed and never in a message, a body, a header or a key the service answers with (it is scrubbed, in whole and by part)
sdk-first.js ← the rule `list-connections.js`, `connector.js` and `solution-settings.js` share: read through the SDK, and through `pac` for the SDK's typed refusals (`sdkFirst`, `CONNECTIVITY_REFUSALS`) — an error counts only when it IS the bundle's `SdkError` (an HTTP body that carries a refusal's code does not); any other failure is thrown with the SDK's own code. An environment outside the Public cloud is judged from its host first (`connectivityCloudOf`, pinned to the bundle by a table of hosts) and answered by `pac` at once, with the code the SDK would give. What the SDK could not clean up before it refused (`readCleanupWarnings`: a staged copy of the package it could not delete, with its upload id) is carried across the fallback — as `warnings` on the answer, or attached to the error `pac` throws when it fails — so `solution-settings.js` shows it for `template` and `import` alike (an import's, sanitized once)
@@ -2424,6 +2703,7 @@ scripts/
safe-fs.js ← confined output writes and deletes: the named directory's final component must not be a link or junction (readlink, not a path-text compare, so an 8.3 name and a share root stay usable); write via exclusive temp + rename, or — with `exclusive: true` — never replace a name: the content goes to a sibling file this process created exclusively and is published with a hard link to the target name (which fails if the name exists, so the file system decides and a file that appeared meanwhile is never overwritten: `IO_ERROR` with `reason: 'exists'`; where hard links do not exist the write fails closed, `reason: 'no-hard-links'`), and only that sibling is ever removed — retried, and reported (a warning after a publish, the error after a failure) when it cannot be — and a later write of a file that still has its second name is refused naming it. Every text it writes or appends has the access tokens the process obtained taken out first (`lib/output-redaction.js` `redactOutput`; bytes are written as they are): it is the one writer of the build's journal and status file, of a download's files and of a page's file and its deployed copy. Shared by genpage markers and later callers
hydrate-spec.js ← reconstruct an App Spec from a deployed app (edit flow)
verify-spec.js ← spec-vs-deployed reconciliation core (checks are ordered tasks on a pool of 4)
+ status-reasons-keys.js ← a table's status reasons (with their states) and alternate keys (with their columns), one narrow read each (`readStatusReasons`, `readAlternateKeys`: `{ state: 'ok' | 'absent' | 'error' }`, never a throw), and the checks of the declared ones against them (`statusReasonChecks`, held to the build's own `statusReasonTargets`; `alternateKeyChecks`) — verify's `status-reason` and `alternate-key` checks
build-journal.js ← durable JSONL build journal (resume diagnostics)
form-preview.js ← form wireframe renderer
app-preview.js ← whole-app design renderer (data model + sitemap + forms + page-intents + design)
@@ -2501,7 +2781,7 @@ Agents are invoked by skills via the `Task` tool — they are not user-invocable
| `genpage-page-builder` | `genpage` (create flow) **and** `app-builder` (Phase 1.5) | Generates one complete `.tsx` page from a plan document and schema; runs in parallel with other builders for multi-page requests. `/app-builder` projects its App Spec into that plan format via `scripts/write-page-plan.js` and dispatches this same agent |
| `genpage-edit-planner` | `genpage` (edit flow) | Reads downloaded artifacts as data, gathers changes, presents an edit plan and writes the same approved change list. The plan references prompt.txt without embedding it; the orchestrator applies only verified Requested Changes. |
| `genpage-connector-builder` | `genpage` orchestrator (create **and** edit flows) | Performs connector discovery (connections, connection references, datasets, tables, operations, schema), creates Dataverse connection references, and writes the `## Connector Bindings` contract + `connectors.json`. The orchestrator forwards its output into the planner or edit-planner prompt. |
-| `genpage-customapi-builder` | `genpage` orchestrator (create **and** edit flows) | **Single owner of the custom-api feature gate.** Discovers the Dataverse Custom APIs a page can bind to (Global + entity-bound Actions/Functions) plus their parameter kinds via `list-custom-apis.js`, and writes the `## Custom API Bindings` contract + `actions.json`. The orchestrator forwards its output into the planner or edit-planner prompt. |
+| `genpage-customapi-builder` | `genpage` orchestrator (create **and** edit flows) | **Single owner of the custom-api feature gate.** Discovers supported public Dataverse Custom APIs (Global + entity-bound Actions/Functions), primitive declared kinds and separate lookup inputs via `list-custom-apis.js`, and writes the `## Custom API Bindings` contract + primitive-only `actions.json`. The orchestrator forwards its output into the planner or edit-planner prompt. |
## Key Concepts
@@ -2554,11 +2834,10 @@ What the skills ran through `pac model genpage` — the listing, the download, t
## Feature Flags
-Unreleased functionality is gated behind committed, **default-OFF** feature flags so
-the skill can merge ahead of its cross-repo dependencies. With a flag OFF, the
-**deployed page behavior is identical to before the feature existed** — the guarantee
-is about runtime/deploy output, not that every authoring artifact is byte-for-byte
-unchanged. The mechanism lives in `scripts/lib/feature-flags.js` with the committed
+Unreleased functionality can ship behind committed, **default-OFF** feature flags while
+dependencies roll out. **Supported public Custom API discovery now ships ON**, with the gate
+retained as an explicit opt-out. OFF stops new discovery/authoring; unrelated edits preserve
+existing page bindings, not silently clear them. The mechanism lives in `scripts/lib/feature-flags.js` with the committed
values in `feature-flags.json` at the plugin root.
**A flag is flipped to `true` FIRST and removed in a LATER change, not both at once.**
@@ -2569,14 +2848,13 @@ a permanently-on gate is dead weight that still has to be probed, branched on an
about at every call site.
Connector authoring no longer has a feature flag (the feature itself is in public preview). The
-remaining flags are `custom-api` and `custom-telemetry`; both currently ship **OFF** while their
-dependencies finish rolling out.
+remaining flags are `custom-api` (**ON**) and `custom-telemetry` (**OFF**).
-- **Source of truth:** `feature-flags.json` (e.g. `{ "custom-api": false }`). Flip a
+- **Source of truth:** `feature-flags.json` (e.g. `{ "custom-api": true }`). Flip a
flag to `true` in a one-line PR once its dependencies are GA in PROD, then remove
it in a follow-up that deletes its gates.
- **Precedence (highest first):** env var `GENPAGE_ENABLE_<FLAG>` (e.g.
- `GENPAGE_ENABLE_CUSTOM_API=1` for a single run) → committed
+ `GENPAGE_ENABLE_CUSTOM_API=0` to opt out for a single run) → committed
`feature-flags.json` → default `false`
(fail-closed). This mirrors the telemetry opt-out env-over-config convention.
- **LLM gate:** skill/agent markdown probes a flag with
@@ -2603,14 +2881,16 @@ only the per-feature specifics are tabled below:
never gate inline.
2. **Scripts** — each entry-point script calls the shared `exitIf<Feature>Disabled()` helper (DRY —
never an inlined gate) and fails closed with exit 3 when OFF.
-3. **Deploy** — the SKILL phase **re-probes** the flag and treats an absent/malformed bindings
- section as *no bindings*, so a plan authored while the flag was ON cannot deploy after it goes OFF.
+3. **Deploy** — the SKILL phase **re-probes** the flag. A populated Custom API table under an
+ OFF probe halts before generation; a missing/malformed section halts too. Only the exact
+ `No custom API bindings.` sentinel means none, never a fallback that clears existing bindings.
4. **ALM** — solution packaging honours the flag (or documents why it needs no gate).
5. **Codegen** — `genpage-page-builder` emits feature code **only** when the plan carries an actual
binding table, never on an absent/sentinel section.
| | `custom-api` | `custom-telemetry` |
|---|---|---|
+| **Committed default** | ON (`GENPAGE_ENABLE_CUSTOM_API=0` opts out) | OFF |
| **Owner agent** | `genpage-customapi-builder` | none — codegen-only |
| **Plan section** | `## Custom API Bindings` | none — driven by the maker request, not the plan |
| **Gated scripts** | `list-custom-apis.js` | none |
@@ -2631,17 +2911,32 @@ produces the dispatch line. It also carries a second gate the other flags do not
when `enabled`, `genpage-page-builder` instruments a page **only** when the maker explicitly
asked to measure or track something. `enabled` is permission, not instruction.
-The two remaining flags currently ship **OFF**, each waiting on cross-repo dependencies:
+Feature dependencies remain separate from their committed defaults:
-- **`custom-api`** — the AIBuilder CoderAgent action prompt, the shared `pai-gen-ux-action-runtime`
+- **`custom-api` (ON)** — the AIBuilder CoderAgent action prompt, the shared `pai-gen-ux-action-runtime`
plus the UCI and Controls host runtimes, the page `actionBindings` the plugin writes into `config.json`
(through the SDK: `genpage-upload.js --actions`, and the build), and the `GenUxPluginActionAllowList` ECS setting.
Note the maker-facing name is "Custom API" while the shipped wire contract stays
`actionBindings` / `executeAction` (see `references/custom-api.md`).
-- **`custom-telemetry`** — the page telemetry facade in the UCI host runtime, the GenUX
+- **`custom-telemetry` (OFF)** — the page telemetry facade in the UCI host runtime, the GenUX
authoring control (power-platform-ux), the AIBuilder CoderAgent telemetry prompt, and the
`GenUxEnableCustomTelemetry` ECS setting (see `references/page-telemetry.md`).
+Custom API discovery selects public Global APIs and the page's entity-bound APIs in one inline
+request, including request and response types. It excludes collection-bound APIs and APIs with
+Entity/EntityCollection inputs or outputs. Missing, unreadable or incomplete required metadata is an error, not
+an empty successful result. `lookupParameters` retains exact lookup names, optionalness and an
+optional table hint for authoring; it never enters `actions.json`. Primitive declared kinds and
+structural `{ entityName, id }` lookup values remain separate. The builder/reference contract
+also requires known read semantics before automatic Function invocation; GET alone is not
+proof that an operation is harmless. See `references/custom-api.md` for the wire and call shapes.
+Single-level expanded collection links normally repeat the same related rows, so their presence
+alone is not a paging failure. Discovery validates the known relationship shape without following
+it, and refuses genuine/ambiguous paging or the 5,000-row expansion cap. Lookup names, boolean
+requiredness and supplied hint shapes must be read, not invented. The offline consumer accepts
+typed, provenance-checked record member IDs and exact unchanged before-config bindings; additions
+or replacements still need fresh eligible discovery.
+
## TSX source lexer — known limits
**`scripts/lib/source-literals.js` — known limits.** It is a hand-rolled TSX lexer, not a
@@ -3498,9 +3793,10 @@ if (flagError) { process.stderr.write(`✗ ${flagError}\n${USAGE}\n`); process.e
```
`validateFlags` (`scripts/lib/dataverse-auth.js`) rejects unknown flags with a single-edit "did you
-mean" (via `scripts/lib/nearest-name.js`, shared with the FetchXML operator lint), and rejects a
-value-bearing flag passed bare or empty. It reads flag names from `argv` rather than the parsed
-object, because `--__proto__` goes through the inherited setter and never becomes an own property.
+mean" (via `scripts/lib/nearest-name.js`, shared with the FetchXML operator lint and the spec gate's
+`fieldOptions` key check), and rejects a value-bearing flag passed bare or empty. It reads flag names
+from `argv` rather than the parsed object, because `--__proto__` goes through the inherited setter
+and never becomes an own property.
Two consequences worth knowing:
@@ -3622,7 +3918,7 @@ client sends it) out of everything the process writes, and changes nothing else
| What the process writes | How the token is kept out |
|---|---|
-| stdout and stderr — every `console.*` call, every script's result printer and warning printer, the progress lines, a library's own output, the SDK bundle's | `process.stdout.write` and `process.stderr.write` are wrapped when the first token is noted (a process that has none is untouched); text only, bytes pass. `emitResult` cleans its own text too, so a result is clean where a caller has replaced `write` |
+| stdout and stderr — every `console.*` call, every script's result printer and warning printer, the progress lines, a library's own output, the SDK bundle's | `process.stdout.write` and `process.stderr.write` are wrapped when the first token is noted (a process that has none is untouched); a text is cleaned as a string, bytes are masked byte for byte in a copy (as many `*`, so a frame keeps its length). `emitResult` cleans its own text too, so a result is clean where a caller has replaced `write` |
| what Node itself prints when an error ends the process (an uncaught exception, an unhandled rejection) — it never passes through `write` | a handler prints it, cleaned, with the same exit status, when nothing else handles the error (a test runner has its own listener and is left alone) |
| the build's journal and status file, a download's spec and pages, a page's file and its deployed copy, a plan, the settings template | `writeFileSafe` and `appendFileSafe` (`lib/safe-fs.js`) clean the text they write |
| the apply snapshot, the baseline `last-applied.json`, the page ownership and publish records | `writeFileAtomic` (`lib/apply-snapshot-store.js`) cleans the text it writes |
@@ -3632,10 +3928,14 @@ client sends it) out of everything the process writes, and changes nothing else
no token), so a new writer fails there until it is classified; it also pins that the one raw write to a descriptor is `solution-settings.js`'s own, and that no script pipes a child's output to a stream. A token is looked for as
the text SPELLS it: one character at a time, each the character itself or an escape of it, with a fold between any two (white space, `\r\n` as JSON writes it, a run of backslashes for JSON inside JSON, a stray backslash, a
terminal colour code, the quote-plus-line-break `util.inspect` prints between the pieces of a long string, in colours or not), and an escape that can also be a literal backslash and its letters (`\n` before a part that starts
-with `n`) read both ways — in one linear pass over the text, every needle (the token and each of its parts of 24 characters or more) at once, with a bounded set of the second readings beside it (a text that would need more is
-refused, and the writer fails closed: a stream writes a notice, a file is not written), the whole span becoming `<token>` so that JSON that was written is JSON still. Not read: other encodings of a token (percent-encoding,
-base64, entities), a token another process obtained, bytes (a Buffer a writer is given is written as it is), a token written in two separate calls to `write`, and the end of a part a formatter cut short (`util.inspect`
-prints at most 10,000 characters of a string). Observe the boundary at the process's descriptors and files — `output-token-boundary.test.js` runs real processes (`tests/helpers/token-boundary-child.js`), in colours too — and not by replacing `process.stderr.write` in a
+with `n`) read both ways — in one linear pass over the text, every needle (the token, each of its parts of 24 characters or more, and its other spellings: base64 at each of the three byte alignments, standard and URL-safe, and the
+percent-encoded and HTML spellings where they differ from it) at once, with a bounded set of the second readings beside it (a text that would need more is refused, and the writer fails closed: a stream writes a notice, a
+file is not written), the whole span becoming `<token>` so that JSON that was written is JSON still. Where a text says it was cut (`util.inspect` prints at most 10,000 characters of a string and then `... N more
+characters`; an ellipsis, `...` or `…`), the run before it that begins a needle — 24 characters or more — goes too; and a whole text the process writes loses such a run at its end, and the end of a needle at its start
+(a token written in two pieces: nothing is held back for the next write; an escape cut between the two writes — `\` and `/`, `\u00` and `73` — is kept whole,
+because a guarded stream remembers the few characters of it, so JSON written in two pieces is JSON together). Bytes a stream is given (a Buffer, a Uint8Array, a string in `base64` or `hex`) are read byte for byte and each hit is masked with as many `*` in
+a copy, so a test runner's frames keep their lengths; bytes that hold none are the very object. Not read: a token another process obtained, a piece of a token shorter than 24 characters (the shorter piece of a token written
+in two), a piece from the middle of one, other spellings, a cut inside bytes, and bytes given to a file writer (the module's header lists them). Observe the boundary at the process's descriptors and files — `output-token-boundary.test.js` runs real processes (`tests/helpers/token-boundary-child.js`), in colours too — and not by replacing `process.stderr.write` in a
process of your own, which replaces the guard itself. `output-redaction.test.js` holds the matcher (against an exact reference that follows every reading over random spellings, JSON validity, cost on a large text and on texts made of nothing but escapes), the registry and the guards,
`output-token-real-bundle.test.js` the real bundle and the production client (the SDK's error is the SDK's own; the answer reaches the SDK byte for byte as the service sent it; a page write whose refusal proof and sends are
those of a client that takes nothing out). `solution-settings.js` keeps its own guard on what it writes (below), which stacks with this one. The pcf plugin carries the copy of the module and notes the tokens it reads; its
@@ -3927,7 +4227,11 @@ runner names the manual reset every workspace-reset remedy shares
(`RESET_WORKSPACE` in `lib/entity-provision.js`): stop other builds and teardowns on the workspace
first — the changed-only snapshot holds their leases and a running teardown's registration — then
delete everything except `last-applied.json` (the navigation baseline), `destructive-approval.json`
-(the approved removals) and the `page-ownership.*.json` records (a page's creation receipt, a teardown's
+(the approved removals), `web-resource-unconfirmed.*.json` (the durable ids of web resources whose publication
+could not be confirmed: a later build must rewrite and verify those same rows, not create again or reuse stale
+published content), `dashboard-creation.*.json` (the ids of the dashboards an interrupted build created before
+they joined the solution: a later build adds those same rows to it, where a name lookup would miss one nobody
+published and create a second) and the `page-ownership.*.json` records (a page's creation receipt, a teardown's
record of the pages it is deleting, and the `pending` record of a page create that was started and never
answered — the only trace of a page that may still land: without it the next build creates a second page
for the spec entry), which no re-run can rebuild. The build does not reset the copy itself: the
@@ -4789,7 +5093,15 @@ real bundle, because a stub stays green through a change in the SDK's own rule.
that file (`NAMED_ROUTES`), pinned to its one call and its `if (!request.env)` guard.
- **Two layers re-send, and for a delete they add** (`scripts/tests/sdk-resend-layers.test.js` pins every
count). The HTTP client re-sends a 429 or 5xx — except a record delete and a `$batch`, which it
- re-sends only for a deadlock (SQL 1205) or a 429. The SDK re-sends a deadlock for reads, an app
+ re-sends only for a deadlock (SQL 1205) or a 429, and a publish (`PublishXml`, `PublishAllXml`), which it
+ sends ONCE but for a 401 (the token is refreshed) and a 429 of the service protection limits
+ (`0x80072322`/`21`/`26`, waited out inside the run's budget): a publish the customization lock refused
+ (429 `0x80071151`) is not shown to change nothing — measured under the lock, a later accepted publish
+ published a web resource's OLD content, and an accepted re-send answered 204 while publishing old content —
+ so it reaches the caller as it came. A publish's deadlock victim is re-sent by ONE layer: the SDK's
+ `publishXml` for its own publishes, `lib/publish-xml.js` (`postPublishXml`, 1 s / 2 s / 4 s) for the
+ plugin's raw table and app publishes — a persistent one costs four sends, not the client's six times the
+ SDK's four. The SDK re-sends a deadlock for reads, an app
create, `PublishXml`, a form create, a view create, a publisher create and each delete of a row-summary
removal (there a 400 quoting SQL's "chosen as the deadlock victim" counts too), and re-sends an app delete
that hits the platform's search-index insert race (HTTP 400, SQL 547). An app delete's two triggers are
@@ -4819,6 +5131,67 @@ real bundle, because a stub stays green through a change in the SDK's own rule.
with the kept steps, not the deleted ones, as its own step line does (`teardown-row-summary-removal.test.js` holds all
of it over the real bundle). The table delete that follows reports the dependency if the skill row is still there, and
a model left behind blocks only a later row summary for the same table, by name.
+- **A web resource whose publication the SDK cannot confirm is recorded, put in the solution, and written again by the
+ next run** (`scripts/tests/web-resource-unconfirmed.test.js`). The SDK reads a web resource's PUBLISHED content back
+ after every create and every content write it publishes — one GET per write (the lifecycle matrix's first build reads
+ four more) — and throws `WEB_RESOURCE_UNVERIFIED` when the publish failed or the read-back could not confirm the
+ content: after the row exists, with its id (`error.id`) and the failure as its non-enumerable `cause`. A second
+ create of the name is refused. Measured under the customization lock, a publish the lock refused was followed by a
+ later accepted publish of the OLD content, so the content has to be WRITTEN again, not only published. At each place
+ the build writes one — the spec's web resources, the generated app icon, the page manifest — it keeps the row's id
+ and records it in `web-resource-unconfirmed.<hash>.json`, one file per environment in the build workspace
+ (`lib/web-resource-records.js`), adds it to the solution as the success path does, and stops with the SDK's words
+ (the row, its id, why it is unconfirmed) and the build's: UNCONFIRMED, not lost — run the build again. The run that
+ follows — the build's own re-run of the halt, and a new invocation on the same workspace — writes the content again
+ by id (`updateWebResource`, which publishes and reads it back again) and clears the entry once that verified and the
+ row is in the solution — only the entry that run knows, its id and the revision of the note that made it, so a later
+ unconfirmed write of the same row that another build sharing the workspace recorded meanwhile stays for the next run;
+ a row that is gone by then is created again only if no conflicting replacement was found.
+ A receipt whose id and a live row's name disagree, or whose name now belongs to another id, stops recovery without
+ adopting or overwriting the other row. A failed solution add retains the receipt; its 404 is not a missing resource.
+ A web resource of that name the record does not
+ hold — another maker's, or one whose write was confirmed — is reused untouched, as before. The page manifest's own
+ dedup compares with its PUBLISHED copy (what `readPageManifest` reads), so an update whose publication was not
+ confirmed is written again whenever that copy is still old; the record supplies the id of a manifest created and never
+ published, which no plain read finds (assumed, not measured). The pages a halted run created are bound by their
+ creation receipts, so none is created twice. The build's retry reads the error as a wrapper of its cause
+ (`CAUSE_WRAPPER_CODES`, `lib/retry-policy.js`): a lock refusal, a 503 or a reset is run again, a 400, 401, 403, 404,
+ 412 or a typed refusal is not, and no cause (the read-back differed or carried no content) is run again. An unchanged
+ rebuild reads one local file and sends nothing more. Recovery of a recorded spec resource or icon checks its published
+ name by id first (one extra GET; 404 can also mean unpublished, so only an update's 404 proves it gone). A recorded
+ manifest whose name lookup is empty makes that same identity check before any page writes. Without a writable recovery
+ record the build still attempts the solution add, but does not automatically replay the phase; the halt requires
+ recovery by the known id. Not covered: a process killed while the SDK publishes (no error,
+ so no record — the next run reuses the row as before), and another workspace (no record, and no page receipts).
+- **A dashboard created by a build that stops before adding it to the solution is added to it by the next run**
+ (`scripts/tests/dashboard-creation-recovery-real-bundle.test.js`). A new dashboard is two requests: the push POSTs the
+ `systemforms` row, and AddSolutionComponent puts it in the app's solution — the only later proof that it is the app's.
+ A run that stopped between them (killed, the create's answer lost, or the add and its undo both refused) left the row
+ outside the solution with nothing to remember it: the next build's name lookup reads the PUBLISHED layer, where a
+ dashboard nobody published is not, so it created a second one (or, once the first had been published, reused it
+ outside the solution); teardown kept the first and a solution export left it out. The SDK sends the workspace's own
+ id as `systemform.formid`, so the build notes that id in `dashboard-creation.<hash>.json` (`lib/dashboard-creation-records.js`,
+ one file per environment, app and solution) BEFORE the push, keeps the id the push reports beside it when that is another,
+ and clears it once the add answered or its own undo's delete did (a stranded halt keeps it, and says a run again adds it).
+ The next run — the build's own re-run of a halt, or a new invocation — reads each recorded id with
+ `GET systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()` (the saved layer, which answers a never-published row;
+ a missing id is 404 `0x80040217`) BEFORE the name lookup: none there clears the record and the build goes on as before —
+ unless another build sharing the workspace has changed the entry since this run read it (recorded the id its push reported):
+ then nothing is concluded from the older entry, and the step stops with nothing created, added or deleted;
+ the row the create made — the id it was sent with, or after a re-key ONLY the id the service reported — if it is a standard
+ dashboard of the spec's name, is added to the solution (an idempotent add), reused and cleared; anything else —
+ a read that fails, another kind of row, a dashboard renamed since, both ids answering, after a re-key only the sent id
+ answering (a row the build never saw its create make, which adding would hand to teardown), an add refused now — stops the step
+ with nothing added, deleted or created and the record kept, saying what a maker can do — never asking for a dashboard to be
+ deleted that may be another app's. The record is never a reason to
+ delete, never adopts a namesake (it holds only ids the build sent or was answered with — never a downloaded `dashboardId`,
+ a name match or a solution member), and teardown never reads it. A record that cannot be read — an entry the build does not
+ write included (an id that is no id, two names Dataverse compares as one) — is never written over or removed, and
+ one that cannot be read or written is one warning — the build is then the one it was before there was a record, which is
+ also why a record that cannot be written does not stop the create. An ordinary first build and an unchanged rebuild send
+ exactly what they sent before (no recorded id, no read). Not covered: a dashboard created by another workspace, or before
+ this release; a pinned (downloaded) dashboard, which is bound by its pin first and never consults the record; and
+ `teardown-model-app.js --clear-workspace`, which deletes the record with the workspace (it keeps the dashboard as it always did).
- **Changes in the same SDK release that no plugin path reaches** — read these again before a plugin change
reaches one. (`importSolution`, which now requires `overwriteUnmanagedCustomizations`
and `publishWorkflows`, was on this list while no script called it. `solution-settings.js import` does, with
diff --git a/plugins/model-apps/CHANGELOG.md b/plugins/model-apps/CHANGELOG.md
index 64f0e4659..01906a39d 100644
--- a/plugins/model-apps/CHANGELOG.md
+++ b/plugins/model-apps/CHANGELOG.md
@@ -5,6 +5,207 @@ 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.
+## [2.18.0]
+
+The bundled SDK is updated to power-platform-ux a3443479. An app whose sitemap's unique name is not the app's — first-party apps
+such as Sales Hub have one — is now read with its navigation (#746), and a web resource write is confirmed by reading back what was
+published. A new app whose navigation holds only generative pages can now be built, a download carries each page's connector and
+Custom API bindings and much more of each table's schema into the App Spec, and verify checks declared status reasons and alternate
+keys. Supported public Custom APIs are discovered by default. The HTTP client no longer re-sends a publish the customization lock
+refused, a web resource or dashboard that a stopped build left behind is finished by the next build instead of made again, and an
+unknown key in a form's `fieldOptions` is refused instead of ignored. An access token is now also kept out of bytes, out of its
+other spellings, and out of text cut short or split between two writes.
+
+### Added
+
+- **A new app whose navigation holds only generative pages is built.** Dataverse refuses to create a sitemap with no entry, so the
+ build refused such a spec before writing anything (`app-navigation-empty`), and lint warned about it. The build now creates the
+ pages first and then the app, with the pages already in its first sitemap — the order `apps.js create --page-id` uses: the app step
+ says `created after its pages`, and the app's create is reported in the app-shell phase. A build that stops between the pages and
+ the app is finished by running it again (the pages are adopted by their creation receipts, not created twice), and a teardown
+ removes the pages it made. An app that exists is not affected, and its requests are unchanged. A run that cannot create the pages
+ first — no pages phase, a `--changed-only` re-upload, a page entry whose page the run does not build — still refuses, and says
+ which.
+- **A download writes each generative page's connector and Custom API bindings into the App Spec, and a rebuild writes them back**
+ (`pages[].connectorBindings`, `pages[].actionBindings`). A copy of a spec rebuilt in another environment used to create its pages
+ without them. A list is written into the spec only whole, and only when every property is a documented one and every value has a
+ shape known to be safe — an identifier, a GUID, a plain name or label, a canonical `http(s)` URL with no user-info, query or
+ fragment, nothing shaped like a token, and for a Custom API only the ten primitive parameter kinds the runtime binds. Any other list
+ is left out of the spec, named by page, list, entry and property (never by a value), and stays on the page; a spec that states one
+ is refused. A secret written as plain words in a label cannot be told from a label. A list the spec does not state is not sent, so
+ the page keeps its own, and `[]` clears it. When a page already holds what the spec states and this workspace has a usable record
+ of its last publish, the build neither writes nor publishes it; a record from before the spec stated the lists counts only once
+ the page's published copy is read and found to hold them, and with no usable record the page is published (not written), as an
+ unchanged page always was. Before it writes anything (and in a dry run), a build reads the target environment's connection
+ references and Custom APIs, and the definition of a custom connector whose operations a binding calls: it stops
+ (`pages-binding-reference-conflict`, never retried) at a connection reference of that name for another connector; it names a
+ reference or Custom API that is not there, a reference with no connection, an operation the custom connector there does not
+ define, and a Custom API of the other kind or bound to another table. A read that fails, a reference row that does not say — in a
+ form the build can read — its connector, its connection or its custom connector, and a definition it cannot read are reported as
+ not checked, never as compatible; a Custom API row is taken as it reads (a kind it does not state counts as an Action, a table it
+ does not state as Global). A throttle wait the run's budget refuses during these reads stops the build before it writes. The
+ download's `pageBindings` result and a `NOTE:` on stderr list what the target must already have: the connection references and
+ their connections, the Custom APIs and the service resources the bindings point at.
+- **A download keeps much more of each table's schema**: Text format and length, Memo length, Integer range and format, Decimal and
+ Double range and precision, Money range, Boolean labels, DateTime format, AutoNumber masks, and the primary name column's length
+ (written even at 100, so a fresh build corrects an environment that overrides it; a lookup to that table made before the correction
+ keeps the overridden length on its name column) and mask; custom unmanaged Active and Inactive status reasons with their values and
+ colors, labelled in the download's authoring language; alternate keys with their columns and labels; solution and global-choice
+ display names; dashboard tile sizes; and a table's own unmanaged SVG icon, carried as `external: true` so a teardown of the
+ downloaded spec never deletes it. Values equal to the build's defaults are left out. A Money column's precision is kept only when it
+ follows the transaction currency, the only kind the build creates; for another source the download says so and leaves it out. A
+ detail it cannot read is named on stderr without dropping the column or table or guessing a default, and a status reason with no
+ label in the authoring language is named and left out. It is still not a clone: Boolean defaults, column capabilities, BigInt
+ ranges, DateTime behavior, script resources, raster, foreign or managed table icons, `roleGrants[]` and `sampleData` are not
+ carried. The download reads once more per table for its status reasons, once per column type present (Text, Memo, Integer, Decimal,
+ Double, DateTime) and once per icon it captures, plus one lookup of the web-resource table's entity set name before the first icon
+ when that name is not yet known.
+- **Verification checks declared status reasons and alternate keys** — `verify-model-app.js`, and the verification a build runs (with
+ `--verify`, and on every build that applies a spec's generative pages). A status reason passes when the table holds its label
+ under the state the build gives it and at the value the spec pins, if it pins one; a state the answer does not give readably
+ fails. An alternate key passes when a key of its name is over exactly its columns, in any order. Each is one read, made only for a
+ table that declares one. A build therefore now fails its verification, as it does for any other artifact, when the environment
+ holds a declared reason or key differently — a reason renamed in Maker, say, which a rebuild does not rename back — or the read
+ fails.
+
+### Changed
+
+- **The bundled SDK is updated (power-platform-ux a3443479).** What a maker can see of it:
+ - a web resource create, and an update that writes content, read the published content back once their publish succeeds (one
+ read), and fail with `WEB_RESOURCE_UNVERIFIED`, naming the row (which exists), when the publish fails (nothing is read back then)
+ or the content read back is missing, unreadable or not what was written (see Fixed for how a build recovers);
+ - a publish is never sent again by the SDK, except when SQL rolled it back as a deadlock victim;
+ - an edit of an Active business process flow that the customization lock refuses is sent again, unchanged and with its original
+ version check, for up to three minutes of waits, where it failed at once: another maker's edit in between makes it fail rather
+ than be overwritten;
+ - an app's sitemap is found by the SiteMap component on the app's current layer, not by the app's unique name (see Fixed). The link
+ is checked when an app is read — before and after its sitemap is read — and again before the app is written; each check is two
+ reads (the app's current layer and its SiteMap component) where a read of an app made one name lookup, and deleting an app also
+ reads which apps use its sitemap;
+ - an app create whose rollback the customization lock is shown to have refused or interrupted now names the lock as the reason — the
+ partial app kept because its rollback deleted nothing, or its removal unconfirmed because the rollback may not have run — and says
+ to check, once the lock frees, that its rows exist and are the create's own before removing them; a rollback answer that does not
+ show the lock, and other rollback outcomes, read as before.
+- **The HTTP client sends a publish (`PublishXml`, `PublishAllXml`) once.** It sent one again after a 429, 500, 502, 503 or 504 or a
+ reset or timed-out connection, up to six sends; measured under the customization lock, a refused publish is no proof that nothing
+ changed, and an accepted re-send published old content. A publish is still sent again after a 401 (with a new token) and after a
+ 429 of the service protection limits, waited out as before. A deadlock victim is sent again by one layer only — the SDK for its own
+ publishes, the plugin for its table and app publishes — after 1, 2 and 4 seconds, four sends at most. pcf's copy of the client
+ changes the same way.
+- **Supported public Custom APIs are discovered by default** (`GENPAGE_ENABLE_CUSTOM_API=0` opts out for a run; a missing or
+ unreadable flag configuration still turns it off). `list-custom-apis.js` returns, in one request, the public Global APIs and the
+ public APIs bound to the page's tables; it leaves out private APIs, APIs bound to a table collection, and APIs with an Entity or
+ EntityCollection input or output. It refuses, rather than returning an empty or partial list, an API list, privacy flag, parameter
+ or response type, or lookup detail it cannot read — the metadata its eligibility checks need — and an answer or expansion whose
+ completeness it cannot prove (a continuation, or the platform's 5,000-row cap); the other fields of an API's own row are not
+ checked. This is Custom API discovery, not support for other Dataverse actions and functions. The page builders invoke a Function
+ automatically only when its read semantics are known — GET alone does not prove it harmless — and otherwise only on the user's
+ action.
+- **A rebuild no longer re-sends a status reason, an alternate key or an Integer format the environment already holds.** It reads a
+ table's status reasons once — after every labelled create, so the read cannot strip a later create's other-language labels — and
+ inserts only a reason whose value, state, label and color are not all there; it takes the keys from the table read it already
+ makes; and it reads an existing Integer column's format before updating it. Anything it cannot prove is written as before. A table
+ icon is still assigned and its table published on every build, as before: a saved name does not prove its last publish completed.
+- **Teardown says it keeps the publisher.** It never deletes the solution's publisher (the build reuses one by prefix, and other
+ solutions may share it); its closing summary now says so in one line.
+- **The design document shows a role grant the build refuses as refused.** A `roleGrants[]` entry that does not name exactly one
+ role (`role` and `roleId` both, or neither) is shown in `model-app-plan.md` and the `write-app-spec-doc.js` warnings in lint's
+ words, instead of as privileges the build would add.
+- **Lint warns on `ai.summaries.tables.<table>.prompt`**, a key the build never reads, and names the one that holds a row summary's
+ prompt (`instruction`); renaming it does not enable a summary.
+- **The genpage eval's offline Custom API check follows the new contract.** It accepts a lookup passed as `{ entityName, id }` with
+ no declared kind when its id is a string the page already holds, and refuses an invented or numeric id, a missing required lookup
+ and a parameter discovery did not return; a binding an edited page already held is accepted unchanged only for that same page, and
+ the page's earlier copy is judged by the download that saved it, not by another download of that page.
+
+### Fixed
+
+- **A download of an app whose sitemap's unique name is not the app's no longer fails on its sitemap** (#746). The SDK looked the
+ sitemap up by the app's unique name, found none, and the download failed with advice to publish the app, which did not help. The
+ sitemap is now the one the app's SiteMap component names. An app with no such component falls back to the sitemap of its name
+ only when no other live app uses that sitemap; otherwise the download returns `ok: false` and writes nothing. Deleting an app
+ whose sitemap another live app uses is refused, and so is a push of an app that was linked to another sitemap since it was read
+ (read it again). A build still adds a sitemap to the spec's solution only when it carries the app's unique name, as the sitemaps
+ the build creates do.
+- **A web resource whose publication could not be confirmed is recovered by its id on the next build**, not reused with stale
+ content or created a second time. At each place the build writes one — the spec's web resources, the generated app icon and the
+ page manifest — it records the row's id in the workspace (`web-resource-unconfirmed.*.json`), adds the row to the solution, and
+ stops saying the write is unconfirmed, not lost. The next run on that workspace — or the build's own retry — writes a spec web
+ resource's or the icon's content again by that id, publishes it and checks what was published; it writes the page manifest again
+ only when the manifest's published copy is not already what the run wants, and otherwise keeps it as it is. Either way the row
+ joins the solution and the record is cleared, and pages already created are adopted, not created twice. A row of that name the
+ record does not hold is reused as before, and a recorded id now under another name, or a recorded name now under another id,
+ stops recovery without touching the other row. When the record cannot be saved, the build does not retry on its own. The
+ workspace-reset advice keeps these records. Builds that share a workspace keep each other's entries: each change is made under a
+ short lock to the record as it is then, and a clear removes only the write its build verified, so a later unconfirmed write of the
+ same row stays for the next run. A note is not made when another build has meanwhile recorded another row under that name, or holds
+ the lock for more than about a second; that is said once, as when the record cannot be saved. Not covered: a process killed while
+ the SDK publishes, and another workspace.
+- **A dashboard a build created and then stopped before adding to the app's solution joins the solution on the next build.** A build
+ killed between the create and the add, one whose create's answer was lost, or one whose add and undo both failed left a row outside
+ the solution. The next build reused that row without adding it to the solution — or created a second dashboard if its name lookup
+ missed the row — and teardown kept it. The build now records the id it creates the dashboard with (`dashboard-creation.*.json`)
+ before the create; the next build reads that id in the saved layer and adds the same dashboard to the solution. Anything it cannot
+ prove — another kind of row, a rename, both the sent and the reported id answering, an add refused — stops the step with nothing
+ added, deleted or created, and it never asks to delete a dashboard that may be another app's. The record never adopts a namesake,
+ teardown never reads it, and the workspace-reset advice keeps it. Builds that share a workspace keep each other's entries: each
+ change is made under a short lock to the record as it is then and compares both ids. When recovery reads every recorded id as absent
+ and its clear then finds that another build changed the entry, it stops before creating a dashboard and asks for another run. A note
+ refused because another build changed the entry or held the lock for more than about a second is said once, and that build goes on
+ without the record. A first build and an unchanged rebuild send what they sent before. Not covered: a dashboard created before this
+ release or from another workspace, and an entry another build cleared after this build read it (the lock covers the record, not two
+ builds' dashboard steps).
+- **An unknown key in a form's `fieldOptions` entry is refused instead of ignored.** A misspelling such as `readOnlyy` or `colSpan`
+ passed validation and was dropped by the build, so the option was never applied. Lint, a dry run and a build now refuse it before
+ any write, naming the form, table, field and key, the option it most likely meant, and the keys an entry takes (`readOnly`,
+ `hidden`, `after`, `colspan`, `rowspan`); an entry takes no `name`, because its key names the field. A spec an earlier release
+ built with such a key can still be torn down and previewed, and `verify-model-app.js` verifies it with a warning.
+- **A Custom API with a lookup parameter is no longer bound in a way the runtime drops.** Discovery declared a lookup as
+ `EntityReference`, a kind the runtime does not take, so it dropped the whole binding. A lookup is now passed as
+ `{ entityName, id }` and kept out of the declared kinds; its name, whether it is required and its table are kept for the author in
+ a separate `lookupParameters` list, which is never written to the page.
+- **A teardown run again no longer reports what was already gone as deleted.** A default-view reset with no default view, a
+ relationship the SDK does not find, a table its read did not list and a global choice answered 404 now read `(not found)` and are
+ counted so. In any teardown, a relationship from a table to itself, which its table's delete takes with it, now reads
+ `(not found)` on its own step. The deletes sent and the exit status are unchanged.
+- **A download no longer carries the relationship a File or Image column brings** (`FileAttachment_<table>_<column>`), nor warns
+ that its name lacks the publisher prefix, nor reads the `fileattachment` table for it: the column makes it again on a rebuild.
+ Other relationships of those tables are kept.
+- **An access token the process obtained is also kept out of bytes, out of its other spellings, and out of text cut short or split
+ between two writes.** Bytes a script writes to stdout or stderr (a Buffer, or text written as base64 or hex) are read too, and a
+ token there is masked with `*` byte for byte, so framed output keeps its length. The token's base64 (standard and URL-safe),
+ percent-encoded and HTML spellings are taken out like the token itself. A piece of the token of 24 characters or more is taken out
+ where `util.inspect`'s `... N more characters` or an ellipsis cut the text, at the end of a write that begins the token, and at the
+ start of one that ends it; an escape split between two writes stays whole, so JSON written in two pieces is still JSON. Still left:
+ a piece shorter than 24 characters, the middle piece of a token written in three or more writes, a piece shorter than 24 characters
+ on the far side of an escape split between two writes, base64 of a part of the token, and bytes written to a file. pcf's copy of
+ the module changes the same way.
+- The capabilities document no longer says that a download leaves `relationships[]` out (#567).
+- **A rebuild no longer stops at something that already exists when the platform answers in another language, nor at a 1:N
+ relationship it did not see before creating it.** The build read only English words in an "already exists" answer, and the platform
+ can word that answer in the caller's language: on a Spanish environment the refusal of an alternate key the build could not prove
+ from its table read came back in Spanish, and the data-model phase stopped. A status reason, a column of a table whose columns could
+ not be read, or a table found only after its create stopped the same way wherever its refusal was worded in another language (on
+ that environment those came back in English). Each of those creates now also recognises the answer by its error code, which is the
+ same in every language (`0x80060893` key, `0x80044310` status reason, `0x80047013`/`0x80060304` column,
+ `0x80044363`/`0x8009050d`/`0x8004700b` table); a table is still reused only when it is read back. The create of an existing 1:N
+ relationship was answered `0x80072551` ("NavigationPropertyName … is not unique within an entity"), which no release recognised, so
+ a 1:N the build did not see before creating it stopped the build in every language. The build now reads that relationship and reuses
+ it only when the read proves it is the declared one; another relationship, or one the read cannot prove, still stops the build (the
+ reference's code for a taken relationship name, `0x8004432B`, leads to the same read). The codes add to the existing rules — a 409
+ and the English wording are still recognised whatever code the answer carries — and a code of another create, a generic code or a
+ code the message only quotes does not count by itself.
+- **Teardown removes a published app whose navigation names a sitemap that no longer exists, once it reaches the app.** Before 2.18.0,
+ tearing down one app could delete a sitemap another app shared, leaving that app's SiteMap component pointing at nothing. 2.17.0
+ then deleted such an app on its own (no sitemap had the app's name); the component-aware delete in 2.18.0 refused it with "… was not
+ returned by the unpublished-aware read … Retry.", which no retry could pass. Teardown now reads the app's row version, proves that
+ sitemap gone — by its id, in the published and the saved layer, with no other app's navigation naming it and the link unchanged —
+ and deletes the app on its own: the delete is conditioned on that version and touches no sitemap, and the app is then read back
+ gone. When it cannot prove that, or when the app was never published, it refuses with what it found and asks you to delete the app
+ in Power Apps and run the teardown again; when the app changed while it was proving it, it deletes nothing and asks you to run the
+ teardown again. An app with live generative pages still stops earlier, at the page check, because its pages are proven from the
+ navigation that is gone; delete such an app in Power Apps, then run the teardown again.
+
## [2.17.0]
The bundled SDK is updated to power-platform-ux d603c799. Dashboard tiles the spec does not size now show their charts and lists, a
diff --git a/plugins/model-apps/README.md b/plugins/model-apps/README.md
index 0d6c9c891..fe8e14403 100644
--- a/plugins/model-apps/README.md
+++ b/plugins/model-apps/README.md
@@ -38,18 +38,19 @@ A page write whose outcome is unknown (the connection dropped before the answer)
what it holds decides whether the write landed — the message says what to check when that cannot be told. There is no `pac` call, and so
no timeout setting, for pages.
-## Feature flags (experimental & in-progress)
+## Feature flags (defaults and overrides)
Some capabilities ship **OFF by default** while their cross-repo dependencies roll
-out to production. With a flag OFF, the skill behaves as if the feature doesn't
-exist and deployed pages are unchanged. Flags are catalogued (with lifecycle
+out to production. **Supported public Custom API discovery is ON by default**; custom
+telemetry remains OFF. An explicit Custom API opt-out stops new discovery/authoring without
+clearing existing bindings during unrelated edits. Flags are catalogued (with lifecycle
status) in `scripts/lib/feature-flags.js`; their on/off value lives in
`feature-flags.json` at the plugin root.
-| Flag | Status | Enables | Depends on |
-|---|---|---|---|
-| `custom-api` | in-progress | Calling a Dataverse Custom API Action or Function from a generated page (`executeAction` / `executeFunction` / `listBoundActions`) | the AIBuilder action prompt, the shared action runtime, the UCI and Controls host runtimes, the page `actionBindings` the plugin writes into `config.json` (through the SDK), and the `GenUxPluginActionAllowList` setting — all live in PROD |
-| `custom-telemetry` | in-progress | A generated page reporting its own events, metrics, traces and exceptions to your Application Insights resource via `props.appInsights` | the page telemetry facade in the UCI host runtime, the GenUX authoring control, the AIBuilder telemetry prompt, and the `GenUxEnableCustomTelemetry` setting — all live in PROD |
+| Flag | Status | Default | Enables | Depends on |
+|---|---|---|---|---|
+| `custom-api` | in-progress | ON | Calling a supported public Dataverse Custom API Action or Function from a generated page (`executeAction` / `executeFunction` / `listBoundActions`) | the action prompt and host runtimes, revision-bound `actionBindings`, environment governance and the signed-in user's privileges |
+| `custom-telemetry` | in-progress | OFF | A generated page reporting its own events, metrics, traces and exceptions to your Application Insights resource via `props.appInsights` | the page telemetry facade in the UCI host runtime, the GenUX authoring control, the AIBuilder telemetry prompt, and the `GenUxEnableCustomTelemetry` setting — all live in PROD |
Connector authoring is in **public preview** and no longer has a feature flag. Connector discovery, binding, deploy, and ALM packaging are always available when the required PAC and host capabilities are present.
@@ -59,31 +60,36 @@ Connector authoring is in **public preview** and no longer has a feature flag. C
node scripts/lib/feature-flags.js --list
```
-**Enable a flag for a single run** via an environment variable (highest precedence):
+**Disable Custom API discovery for a single run** via an environment variable (highest precedence):
```powershell
# Windows (PowerShell)
-$env:GENPAGE_ENABLE_CUSTOM_API = "1"
+$env:GENPAGE_ENABLE_CUSTOM_API = "0"
```
```bash
# macOS / Linux (bash)
-export GENPAGE_ENABLE_CUSTOM_API=1
+export GENPAGE_ENABLE_CUSTOM_API=0
```
-**Enable it persistently** by flipping the value in `feature-flags.json`:
+**Disable it persistently** by changing its committed value in `feature-flags.json`:
```json
-{ "custom-api": true }
+{ "custom-api": false }
```
-Precedence is **env var → `feature-flags.json` → default OFF** (fail-closed). Only
-turn a flag on once its "Depends on" items are actually available in your
-environment — otherwise the feature's commands will fail with a clear "disabled" or
-capability error. The env var name is always `GENPAGE_ENABLE_` plus the flag name in upper case, with
+Precedence is **env var → `feature-flags.json` → default OFF** for missing/unset
+configuration (fail-closed); it does not override Custom API's committed ON default.
+Use `GENPAGE_ENABLE_CUSTOM_API=1` to explicitly enable a run. Host capabilities and server
+governance still apply; enabling discovery grants no new privileges.
+The env var name is always `GENPAGE_ENABLE_` plus the flag name in upper case, with
`-` turned into `_` (`custom-api` → `GENPAGE_ENABLE_CUSTOM_API`), and unknown flags stay disabled even if
a matching env var is set.
+Discovery omits private APIs and APIs with Entity/EntityCollection inputs or outputs.
+Lookup input names stay available to the author separately from the primitive-only wire
+`parameterKinds`; see [the Custom API contract](references/custom-api.md).
+
## Skills
PCF code components ship in the separate preview [pcf plugin](../pcf/README.md).
diff --git a/plugins/model-apps/agents/genpage-customapi-builder.md b/plugins/model-apps/agents/genpage-customapi-builder.md
index 362681374..3a87be3d7 100644
--- a/plugins/model-apps/agents/genpage-customapi-builder.md
+++ b/plugins/model-apps/agents/genpage-customapi-builder.md
@@ -54,8 +54,10 @@ not repeat the reads. Full contract: `references/agent-interaction-contract.md`.
You are the Dataverse **Custom API** specialist for generative pages. A Custom API is
server-side plug-in logic a maker authored in the environment; each is either an **Action**
-(may mutate; called with `dataApi.executeAction`) or a **Function** (read-only; called with
-`dataApi.executeFunction`). You are the **single owner** of Custom API discovery and the
+(POST; called with `dataApi.executeAction`) or a **Function** (GET; called with
+`dataApi.executeFunction`). Preserve that method fidelity, but require known read semantics
+before invoking a Function automatically on mount or a filter change: GET alone does not prove
+an operation is harmless. You are the **single owner** of Custom API discovery and the
feature gate. Planners must not invoke you directly; they have no `Task` tool, and nested
`Task` calls cannot safely host your user-facing Custom API selection prompts. The top-level
`/genpage` orchestrator dispatches you from BOTH flows so the gate and the discovery logic
@@ -122,7 +124,10 @@ node "${PLUGIN_ROOT}/scripts/lib/feature-flags.js" custom-api
Record the result in `workflow-log.md` (e.g. `feature-flags.js custom-api → disabled`).
-**If it prints `disabled` (exit 1)** — Custom API support is not live in PROD:
+Custom API discovery is **enabled by default**. `GENPAGE_ENABLE_CUSTOM_API=0` explicitly
+disables it; a missing/unreadable feature config still fails closed.
+
+**If it prints `disabled` (exit 1)** — Custom API support is disabled for this run:
- Do **not** run `list-custom-apis.js` or any other discovery.
- **create:** write `custom-api-bindings.md` containing exactly `No custom API bindings.` and
@@ -132,30 +137,34 @@ Record the result in `workflow-log.md` (e.g. `feature-flags.js custom-api → di
reproduce them in `custom-api-bindings.md`. Return
`custom-api disabled — existing bindings preserved, none added`.
-Only when it prints `enabled` (exit 0) do you continue to Step 2. The flag lives in
-`plugins/model-apps/feature-flags.json`; it is flipped to `true` (or
-`GENPAGE_ENABLE_CUSTOM_API=1` for a single run) once the AIBuilder action prompt, the shared
-action runtime + UCI/Controls hosts, the `actionBindings` the upload writes into the page's
-`config.json`, and the `GenUxPluginActionAllowList` setting are all released.
+Only when it prints `enabled` (exit 0) do you continue to Step 2. The committed flag remains
+in `plugins/model-apps/feature-flags.json` as a reversible default; an explicit
+`GENPAGE_ENABLE_CUSTOM_API=1` can enable a single run. Runtime capabilities, environment
+governance and the signed-in user's privileges are still required.
## Step 2 — Discovery (enabled only)
-Enumerate the Custom APIs the page can bind to — every Global API plus those bound to the
-page's table(s). Custom API metadata lives in ordinary Dataverse tables, so this is a plain
+Enumerate supported **public** Custom APIs — Global APIs plus those bound to the
+page's table(s). Private APIs, collection-bound APIs, and APIs with Entity/EntityCollection
+request parameters or response properties are excluded. Custom API metadata lives in ordinary Dataverse tables, so this is a plain
Web API query (no pac verb needed):
```powershell
node "${PLUGIN_ROOT}/scripts/list-custom-apis.js" "<ENV_URL>" --entities "<page table logical names, comma-separated>"
```
-Omit `--entities` for a mock/global-only page to get every Global API. The script returns
+Omit `--entities` for a mock/global-only page to get supported public Global APIs. The script returns
`{ ok, customApis: [{ name, displayName, isFunction, bindingType, boundEntityLogicalName?,
-parameterKinds }] }`, already projected into the binding shape.
+parameterKinds, lookupParameters? }] }`. `parameterKinds` contains only primitive declared
+kinds. `lookupParameters` is discovery-only authoring metadata keyed by the lookup input's
+exact name, with `isOptional` and an optional `logicalEntityName` table hint.
+An unreadable required metadata answer is an error, not a successful empty discovery.
Match the maker's **intent** to the discovered APIs by `displayName` / `name`. When more than
one plausibly matches, return the choices in a `needs_input` request (show `name`, Action vs
Function, and Global vs the bound table). **Never invent** a Custom API `name`, a parameter
-name, or a parameter kind that the script did not return — a name the runtime does not find in
+name, or a parameter kind: input names must come from `parameterKinds` or `lookupParameters`.
+A name the runtime does not find in
the manifest fails closed with `not_bound`, and a wrong parameter kind corrupts the wire type.
If `list-custom-apis.js` returns no API matching the intent, do **not** fabricate one: leave it
@@ -168,6 +177,7 @@ governance the runtime enforces before dispatch (see `custom-api.md`):
- **Kind** (`isFunction`): an Action is called with `executeAction`; a Function with
`executeFunction`. A mismatch is rejected with `wrong_operation_kind`. Never "offer both".
+ Method metadata alone is not permission to auto-run an operation; require known read semantics.
- **Binding**: `bindingType: 'Global'` ⇒ omit `boundEntityLogicalName`; the page must NOT pass
`boundTo`. `bindingType: 'Entity'` ⇒ record `boundEntityLogicalName`; the page MUST pass a
`boundTo` whose `entityName` equals it. `bindingType: 'EntityCollection'` ⇒ **skip it — do not add
@@ -176,8 +186,15 @@ governance the runtime enforces before dispatch (see `custom-api.md`):
explicitly needs one, tell them it is not supported by the generated-page runtime rather than
emitting a binding that will fail. (`list-custom-apis.js` already filters these out; this is the
rule if you ever see one.)
-- **`parameterKinds`**: keep every discovered request parameter and its kind. The runtime has
- no other source for parameter types; a missing or wrong kind causes `invalid_parameter`.
+- **`parameterKinds`**: keep discovered primitive declared kinds exactly. Only the ten kinds
+ listed in `custom-api.md` belong here; EntityReference, Entity and EntityCollection are not
+ valid declared kinds. An unsupported declared kind drops the whole binding (`not_bound`).
+- **Lookups:** preserve every discovered `lookupParameters` name in the plan's authoring
+ instructions. Supply a required lookup as exactly `{ entityName, id }` from an existing
+ record, using the discovered table hint when present. With no hint, establish the table
+ from actual schema/record context; never guess. Omit an optional lookup when no record was
+ selected rather than inventing null or coercing a lookup to a primitive Guid.
+ These are call inputs, not declared kinds: never copy `lookupParameters` into `actions.json`.
## Step 4 — Edit mode reconciliation (`edit` only)
@@ -185,10 +202,13 @@ Start from the **existing bindings** you were given and apply the edit intent:
- **Preserve unchanged:** keep bindings the edit does not touch, verbatim.
- **Add:** run Steps 2–3 for the new operation and append the binding.
-- **Replace:** discover the replacement (Steps 2–3) and swap it in by `name`.
+- **Replace:** discover the supported replacement (Steps 2–3) and swap it in by `name`.
+ If discovery fails or finds no supported replacement, report it; do not silently drop the old binding.
- **Remove:** drop the named binding(s).
- Use ONLY names, kinds, bound entities, and parameter kinds you discovered this run or that
were in the existing bindings. Never fabricate.
+- New discovery eligibility is not retroactive cleanup: preserve unrelated existing bindings
+ verbatim even if they are private or no longer eligible for new discovery.
## Step 5 — Write outputs
@@ -217,6 +237,22 @@ Write the final binding set to both output files (see "Outputs"):
`boundEntityLogicalName` from its `actions.json` entry. A Function has `"isFunction": true`;
an Action has `"isFunction": false`.
+ For a selected API with lookups, append a **Lookup inputs (discovery-only)** note below
+ this table for each lookup: exact API/input name, required or optional, table hint if
+ present, and the structural `{ entityName, id }` call shape from an existing record.
+ Keep this out of the `Parameters (name: kind)` column, which lists primitive kinds only.
+ For example: `new_ResolveReference.Ref` is required, table `account`; supply the selected
+ account as `{ entityName: 'account', id: selectedAccount.accountid }`.
+ Keep the selected-record input explicitly typed in a named helper
+ (`selectedAccount: { accountid: string }`) and preserve its page-input provenance.
+ An arbitrary member chain, cast or locally invented record is not proof of an existing ID.
+ If that member form cannot be established, pass the verified ID through a typed string helper
+ input rather than guessing.
+
+ Build each new/replacement wire entry from `name`, `isFunction`, `displayName`,
+ `parameterKinds` and optional `boundEntityLogicalName` only. Do not copy the full discovery
+ entry: `bindingType` and `lookupParameters` are not `actions.json` fields.
+
- **When there are none:** `custom-api-bindings.md` contains exactly `No custom API bindings.`
and `actions.json` contains `[]`.
diff --git a/plugins/model-apps/agents/genpage-page-builder.md b/plugins/model-apps/agents/genpage-page-builder.md
index bc82a996f..30bb3d676 100644
--- a/plugins/model-apps/agents/genpage-page-builder.md
+++ b/plugins/model-apps/agents/genpage-page-builder.md
@@ -531,8 +531,12 @@ const weather = response.body as WeatherResponse;
### Custom API invocation (Dataverse Actions & Functions)
When the plan has `## Custom API Bindings`, the page may invoke Dataverse Custom APIs on the
-signed-in user's own token. Use only the `Name`, `Kind`, `Bound Entity`, and `Parameters`
-values from that section — never guess a Custom API name, parameter name, or parameter kind.
+signed-in user's own token. Use only the `Name`, `Kind`, `Bound Entity`, `Parameters` and
+separate lookup-input notes from that section — never guess a Custom API name, input name or kind.
+Primitive declared kinds belong in the binding; lookup inputs do not have a declared kind.
+Supply required lookups as exactly `{ entityName, id }` from an existing record, honor a
+discovered table hint, and omit an optional lookup with no selection. Never lose a lookup name
+because it is absent from `parameterKinds`, or copy discovery-only `lookupParameters` into a binding.
Read `${PLUGIN_ROOT}/references/custom-api.md` and emit calls with the verified patterns
there. The methods are optional at runtime, so every call must be presence-checked; guard
each **Action** against double-submit, read results from `res.outputs` (never `res.value`),
@@ -540,8 +544,10 @@ surface only the sanitized `res.error?.message`, and **never auto-retry** an `in
result (only `error.code === 'network'` is safely retryable, via a manual "Try again").
Match the call to the row's `Kind`: an **Action** row uses `executeAction`; a **Function** row
-uses `executeFunction`. Calling the wrong one is rejected with `wrong_operation_kind`. For an
-entity-bound row (a `Bound Entity` table, not `(Global)`), pass
+uses `executeFunction`. Calling the wrong one is rejected with `wrong_operation_kind`.
+Before automatic mount/filter invocation, require known read semantics; GET alone does not prove a
+Function is harmless. Otherwise require an explicit user trigger and prevent overlapping submissions.
+For an entity-bound row (a `Bound Entity` table, not `(Global)`), pass
`boundTo: { entityName: pageInput.entityName, id: pageInput.recordId }` whose `entityName`
equals that table; for a `(Global)` row, omit `boundTo` entirely.
diff --git a/plugins/model-apps/docs/app-builder-capabilities.md b/plugins/model-apps/docs/app-builder-capabilities.md
index e7c195ba9..1a8628fe5 100644
--- a/plugins/model-apps/docs/app-builder-capabilities.md
+++ b/plugins/model-apps/docs/app-builder-capabilities.md
@@ -157,10 +157,10 @@ apart deliberately.
name rules, runtime-lag limits and loss notes; the SDK serialization is covered by
`scripts/tests/app-main-forms-real-bundle.test.js`.
- Generative pages (**genpage-first**) for overview / dashboard surfaces — written through the SDK (`scripts/lib/genpage-sdk.js`); the SDK finalizes the sitemap with `GenPage` subareas.
-- Dashboards (chart / list / iframe / webresource tiles) with **sitemap placement** (auto-pinned as an app component). Tiles render in a **multi-column grid** (2-wide) rather than one stacked full-width column.
+- Dashboards (chart / list / iframe / webresource tiles) with **sitemap placement** (auto-pinned as an app component). Tiles render in a **multi-column grid** (2-wide) rather than one stacked full-width column. A dashboard a build created and then stopped before adding to the app's solution (killed, its answer lost, or the add and its undo both refused) is added by the **next build**, which recorded its id in the workspace before the create (`dashboard-creation.*.json`) and reads that exact row back — never a second dashboard, never a namesake (`scripts/tests/dashboard-creation-recovery-real-bundle.test.js`).
- **Rebuilding an existing app keeps its navigation** (AB#6726727). The build used to hand the SDK a sitemap recomputed from the spec with no trace of the live nodes, so every entry was re-created from scratch — new ids and the designer's defaults for a *new* entry — and a designer-made dashboard entry lost its launcher `Url` and with it the dashboard icon. Each entry the spec keeps is now written onto the live entry it corresponds to (`scripts/lib/sitemap-merge.js`), so everything the spec cannot describe survives, and every dashboard entry carries `Url="/workplace/home_dashboards.aspx"`, as the designer writes it. A title or icon changed in the designer since the spec's baseline (the last apply or download for that environment) is kept and reported; with no baseline the build reports each change it makes to an existing entry. A downloaded dashboard is bound by the id the download recorded, so one renamed in the designer is not recreated under its old name.
- Modern command-bar buttons — functional **JS on-click** + static hidden/disabled, incl. **flyout / split-button menus**.
-- Web resources (JS / HTML / CSS) shipped + added to the solution; idempotent (reuse by name).
+- Web resources (JS / HTML / CSS) shipped + added to the solution; idempotent (reuse by name). One whose publication the SDK could not confirm (`WEB_RESOURCE_UNVERIFIED` — its publish refused under the customization lock, say) is still added to the solution, recorded in the build workspace, and written again by id on the next run, never created twice (`lib/web-resource-records.js`; `web-resource-unconfirmed.test.js`).
### Generative-page management — three-authority, id-based — 🧪 tested
- **Three-authority page identity.** IDENTITY = durable `<app>_pagemanifest` (key→pageId map), outranked by the spec's own `pages[].pageId` for a downloaded (edit-snapshot) spec. EXISTENCE = the environment's page list through the SDK — decides create-vs-reuse for crash-safe convergence (`enumerateEnv`, no `--app-id`). MEMBERSHIP = the app's sitemap `GenPageId` set, read fail-closed via `fetchSitemap` (`scripts/lib/sitemap-pages.js`) — drives placement, download enumeration, and verify. All page matching is by id, never by display name.
@@ -279,13 +279,15 @@ apart deliberately.
test here and by a `@jest-environment node` regression upstream.
### Edit flow (download → edit → rebuild) — ✅ verified live
-- `download-model-app.js` pulls a **deployed app** back into an editable App Spec (+ page code, icons, referenced entities, and the app's **real unmanaged solution** — `recoverAppSolution` enumerates the app's solution memberships and excludes the built-in `Active`/`Default`/`Basic` system solutions, so the spec names the right container for a later clean teardown); edit the spec and re-run the idempotent build — **create and edit share one path** (reuses app/tables, updates pages in place, keeps `GenPage` subareas). The app-shell phase **re-syncs the sitemap + components of any existing app** (fetch → recompute-from-spec → push → publish), so subarea add/rename/reorder edits land for **page-less apps too** — not just generative-page apps — and `--only app-shell` can force the rewrite. **Classic DashBoard subareas are *designed* to round-trip** — the dashboard is reconstructed into `dashboards[]` with **id-passthrough tiles** (each tile carries the deployed view/chart ids), so a rebuild recreates it against the existing views/charts without re-declaring them. **This now works end to end.** It previously did not: the vendored SDK’s `fetchArtifact(‘dashboard’, …)` threw `Cannot read properties of null (reading ‘length’)` while deserializing the `<parameters>` block it had itself serialized, so no tiles were recovered and the subarea was dropped — which failed the whole download unless `--allow-lossy-download` was passed. Root cause upstream: the grammar walk descended into **text** nodes, and the bundled XML parser returns `null` for a text node’s children. Fixed in the SDK and re-vendored; measured across the re-vendor as **0/4 → 4/4** round-trips (list tile, both chart-parameter spellings, and a tile with an empty parameter value), and pinned by `scripts/tests/dashboard-roundtrip.test.js`, which feeds a serialized dashboard straight back in. ([#478](https://github.com/microsoft/power-platform-skills/issues/478)) **Round-trip scope (not yet "complete"):** tables, sitemap/appShell, generative pages (code, prompt, data sources and model; a page's connector and Custom API bindings stay on the deployed page but are not carried in the spec, so they survive a same-environment rebuild only), icons, dashboards, and solution round-trip; **forms, views, charts, and commands do NOT yet** — view hydration was tried and reverted (LIVE-verified the deployed savedquery set can't reliably distinguish author views from Dataverse's auto-generated Active/Inactive/QuickFind system views). All survive on the live app (a rebuild preserves them by discovery) but are absent from the downloaded spec, so edit them in Maker or a fresh spec. **Column types round-trip too, including Choice/MultiChoice** — their option sets are read per table, a local set becoming inline `options[]` (localizations preserved) and a shared one a `globalChoice` reference plus a `globalChoices[]` declaration; a column whose option set cannot be read is left untyped *and named*, and the App Spec cannot express option **values**, so a fresh rebuild re-bases them to `100000000 + index`. **File and Image columns** come back typed too — by their `AttributeTypeName` (FileType / ImageType), as both report `AttributeType` "Virtual", which an earlier release left out of every download without a word — with the `maxSizeKb` each was made with (left out when it is 10240 KB, the size a build gives a column that sets none) and, for an Image column the environment reports as the table's primary image, `isPrimaryImage: true` (a read of that detail that fails, or answers without a column, leaves the column typed without it, and the download says which read or column it was; the platform makes a table's first Image column its primary image whatever its create asks, so a rebuild into a fresh environment makes the spec's first Image column the primary image, whichever column carries the flag); the table's own image (`entityimage`) and the platform's companions of each column are not written, and a column of any other type the App Spec cannot express is left out *and named*. **`relationships[]` are NOT reconstructed** and their omission is not yet reported ([#567](https://github.com/microsoft/power-platform-skills/issues/567)) — a downloaded spec rebuilt into a fresh environment creates the tables without the lookups between them.
+- `download-model-app.js` pulls a **deployed app** back into an editable App Spec (+ page code, icons, referenced entities, and the app's **real unmanaged solution** — `recoverAppSolution` enumerates the app's solution memberships and excludes the built-in `Active`/`Default`/`Basic` system solutions, so the spec names the right container for a later clean teardown); edit the spec and re-run the idempotent build — **create and edit share one path** (reuses app/tables, updates pages in place, keeps `GenPage` subareas). The app-shell phase **re-syncs the sitemap + components of any existing app** (fetch → recompute-from-spec → push → publish), so subarea add/rename/reorder edits land for **page-less apps too** — not just generative-page apps — and `--only app-shell` can force the rewrite. **Classic DashBoard subareas are *designed* to round-trip** — the dashboard is reconstructed into `dashboards[]` with **id-passthrough tiles** (each tile carries the deployed view/chart ids), so a rebuild recreates it against the existing views/charts without re-declaring them. **This now works end to end.** It previously did not: the vendored SDK’s `fetchArtifact(‘dashboard’, …)` threw `Cannot read properties of null (reading ‘length’)` while deserializing the `<parameters>` block it had itself serialized, so no tiles were recovered and the subarea was dropped — which failed the whole download unless `--allow-lossy-download` was passed. Root cause upstream: the grammar walk descended into **text** nodes, and the bundled XML parser returns `null` for a text node’s children. Fixed in the SDK and re-vendored; measured across the re-vendor as **0/4 → 4/4** round-trips (list tile, both chart-parameter spellings, and a tile with an empty parameter value), and pinned by `scripts/tests/dashboard-roundtrip.test.js`, which feeds a serialized dashboard straight back in. ([#478](https://github.com/microsoft/power-platform-skills/issues/478)) **Round-trip scope (not yet "complete"):** tables, relationships, sitemap/appShell, generative pages (code, prompt, data sources, model, and connector and Custom API bindings — `pages[].connectorBindings` / `pages[].actionBindings`, stated by an allowlist of the properties the references document, each with a value of a shape known to be safe, and only whole — a list holding a connection id, a credential or anything else is left out of the spec, reported by its place and never its value, and the page keeps it — which a rebuild writes into any environment; what they name is not carried: the download lists the connection references, Custom APIs and service resources another environment must already have, and a rebuild stops, before it writes anything, at a connection reference there that is for another connector), icons, dashboards, and solution round-trip; **forms, views, charts, and commands do NOT yet** — view hydration was tried and reverted (LIVE-verified the deployed savedquery set can't reliably distinguish author views from Dataverse's auto-generated Active/Inactive/QuickFind system views). All survive on the live app (a rebuild preserves them by discovery) but are absent from the downloaded spec, so edit them in Maker or a fresh spec. **Column types round-trip too, including Choice/MultiChoice** — their option sets are read per table, a local set becoming inline `options[]` (localizations preserved) and a shared one a `globalChoice` reference plus a `globalChoices[]` declaration; a column whose option set cannot be read is left untyped *and named*, and the App Spec cannot express option **values**, so a fresh rebuild re-bases them to `100000000 + index`. **File and Image columns** come back typed too — by their `AttributeTypeName` (FileType / ImageType), as both report `AttributeType` "Virtual", which an earlier release left out of every download without a word — with the `maxSizeKb` each was made with (left out when it is 10240 KB, the size a build gives a column that sets none) and, for an Image column the environment reports as the table's primary image, `isPrimaryImage: true` (a read of that detail that fails, or answers without a column, leaves the column typed without it, and the download says which read or column it was; the platform makes a table's first Image column its primary image whatever its create asks, so a rebuild into a fresh environment makes the spec's first Image column the primary image, whichever column carries the flag); the table's own image (`entityimage`) and the platform's companions of each column are not written, nor is the relationship the platform makes with each File or Image column (`FileAttachment_<table>_<column>` to `fileattachment`, `ImageDescriptor_<table>_<column>` to `imagedescriptor`) — the column brings it back, so it is neither carried in `relationships[]` nor warned about — and a column of any other type the App Spec cannot express is left out *and named*. **`relationships[]` are reconstructed** ([#567](https://github.com/microsoft/power-platform-skills/issues/567)): every custom 1:N whose parent is one of the app's tables or a stock table, and every custom N:N between two of the app's tables, each flagged `existing: true` (a teardown of the downloaded spec keeps it), with a deployed schema name kept whenever it is not the one the prefix would generate and a lookup label kept unless it is the default. One that `relationships[]` cannot express — a polymorphic lookup, a parent that is a custom table the app does not include (or whose metadata could not be read), an N:N to a table outside the app — is left out and *named* in the download's warnings and closing note: it stays on the deployed app, so a rebuild into the same environment leaves it alone, but a rebuild into a fresh environment does not create it.
+- **Portable schema (covered by offline real-bundle round trips):** downloads keep supported column format/length/range/precision options, Boolean labels, date format and AutoNumber masks; primary name length/mask; custom unmanaged Active/Inactive status reasons and alternate keys; solution/global-choice display names; and dashboard tile dimensions. Money numeric precision is retained only for `PrecisionSource: 2`, which the SDK always creates; effective precision still depends on the target transaction currency, so numeric equality is not currency equivalence. Column/organization-controlled and unknown sources are diagnosed with precision omitted, keeping the typed Money column and range. Status labels use the resolved authoring LCID, not the caller's UI language; a missing requested translation is diagnosed rather than substituted. An unavailable optional Keys collection loses no independent table, column or navigation metadata. Values equal to the SDK's create defaults are left implicit, except primary name lengths stay explicit so a fresh build can correct an environment that overrides the table create's length. An own-publisher unmanaged SVG table icon is captured with its `vectorIcon` reference and an `external: true` resource declaration, protecting a shared icon from teardown. Proven-equal status/key definitions and standalone Integer formats send no schema write on a same-environment rebuild; missing definitions and actual format edits still take the existing create/update path. Table icons retain their assignment and specific-table publish even when the saved name matches, so a failed publish can be completed on rerun. Inconclusive or malformed metadata is reported rather than treated as a known default.
+- **Still outside that schema round trip:** script resources, raster/foreign/managed table icons, `roleGrants[]`, `sampleData`, Boolean defaults, column capabilities, BigInt ranges, DateTime behavior and unsupported/managed status reasons. Existing column length/range edits remain create-only; a downloaded dashboard still needs its source view/chart ids mapped, and its pinned `dashboardId` removed, before creating a separate dashboard in another environment. The new schema coverage is not a claim of full app cloning or new live verification.
- Live regression on the edit path found + fixed **4 bugs**, then re-verified clean.
-- `verify-model-app.js` — read-only reconcile of spec vs deployed (exits non-zero on anything missing). Sitemap checks are **element-scoped**: an area/subarea icon is matched on its own `<Area>`/`<SubArea>` element, and a **dashboard subarea** is verified by resolving the dashboard id (systemform type 0 — by a downloaded spec's pinned `dashboardId` first, else by name) and matching the sitemap's `DefaultDashboard` — so a value reused elsewhere can't produce a false pass — and that entry must carry the dashboard launcher `Url`, without which the app shows a placeholder icon for it. **Multi-area sitemaps** and the dashboard-subarea path were re-verified live (positive + negative).
+- `verify-model-app.js` — read-only reconcile of spec vs deployed (exits non-zero on anything missing). Sitemap checks are **element-scoped**: an area/subarea icon is matched on its own `<Area>`/`<SubArea>` element, and a **dashboard subarea** is verified by resolving the dashboard id (systemform type 0 — by a downloaded spec's pinned `dashboardId` first, else by name) and matching the sitemap's `DefaultDashboard` — so a value reused elsewhere can't produce a false pass — and that entry must carry the dashboard launcher `Url`, without which the app shows a placeholder icon for it. **Multi-area sitemaps** and the dashboard-subarea path were re-verified live (positive + negative). A table's **status reasons** (each by its label, under its state, at the value the spec pins) and **alternate keys** (each by its name, over exactly its columns) are checked when the table declares them — one read each, none for a table that declares neither.
### Teardown — ✅ verified live
- `teardown-model-app.js` deletes exactly what an App Spec declares, in dependency-safe order (app → dashboards → commands → business rules → business process flows → forms → **security roles** → charts → views → relationships → AI row summaries → tables [children-first] → web-resources → global choices → solution). Forms/charts/views/relationships are removed **before** tables (a table delete doesn't reliably cascade cross-references); **web resources are removed AFTER tables** (a table's icon web resource is referenced by the table). A business rule / business process flow is deactivated before it is deleted, because Dataverse refuses to delete an activated process.
-- **Classifier-safe** (every id resolved from a spec-declared name via an exact-match, entity-scoped filter), dry-run by default, best-effort continue, not-found aware, undeletable (system/managed) artifacts recorded as `skipped`. A **restricted system solution** (`Active`/`Default`/`Basic`) is skipped rather than attempted (Dataverse 400s any delete of one), so a downloaded spec that defaulted its solution to `Default` tears down cleanly. An already-gone relationship (Dataverse 400 *"…but 0 were found"*) is tolerated as deleted, like the table not-found case.
+- **Classifier-safe** (every id resolved from a spec-declared name via an exact-match, entity-scoped filter), dry-run by default, best-effort continue, not-found aware, undeletable (system/managed) artifacts recorded as `skipped`. A **restricted system solution** (`Active`/`Default`/`Basic`) is skipped rather than attempted (Dataverse 400s any delete of one), so a downloaded spec that defaulted its solution to `Default` tears down cleanly. An already-gone relationship (Dataverse 400 *"…but 0 were found"*) is tolerated as deleted, like the table not-found case. A step that finds nothing says `(not found)` and is counted so — a default-view reset with no default view, a relationship the SDK's lookup does not find, a table its read did not list, a global choice whose delete is answered 404 — so a teardown run again reads `0 deleted, N not found` instead of counting each of those as deleted; the exit status is unchanged. A **publisher is never deleted** — the build reuses one by prefix and other solutions may share it — and the closing summary says so in one line, so the publisher a maker finds left behind is expected.
- **An app whose sitemap carries an unpublished edit tears down cleanly.** A sitemap has two tokens: the unpublished-aware read returns a *content* token that runs ahead of the row while an edit is pending, and Dataverse validates `If-Match` against the *row*. The vendored SDK now conditions each delete on the row token from a by-id read. Live-verified on the same pending-edit app: the previous bundle's teardown failed with 412 on the delete `$batch`; this one deleted everything, and an independent query confirmed every row gone.
### Tooling & internals — ✅ verified live
diff --git a/plugins/model-apps/feature-flags.json b/plugins/model-apps/feature-flags.json
index b7d1f7705..61cd44768 100644
--- a/plugins/model-apps/feature-flags.json
+++ b/plugins/model-apps/feature-flags.json
@@ -1,5 +1,5 @@
{
- "_comment": "Feature flags for the /genpage skill. Unreleased features ship OFF so the skill behaves identically to production until the full cross-repo stack is live in PROD.",
- "custom-api": false,
+ "_comment": "Feature flags for the /genpage skill. Custom API discovery is enabled by default; custom telemetry remains off. Environment overrides take precedence and unknown or missing flags fail closed.",
+ "custom-api": true,
"custom-telemetry": false
}
diff --git a/plugins/model-apps/references/app-spec-schema-advanced.md b/plugins/model-apps/references/app-spec-schema-advanced.md
index ea20539d4..433aec0f4 100644
--- a/plugins/model-apps/references/app-spec-schema-advanced.md
+++ b/plugins/model-apps/references/app-spec-schema-advanced.md
@@ -43,6 +43,12 @@ Reference from a column via `"globalChoice": "new_priority"` (built before the c
resource that already exists is reused as-is, so changing `content` and rebuilding deploys nothing
and the old script keeps running. Delete the web resource (or tear down) and rebuild to change it —
note it cannot be deleted while a command or form handler still references it.
+- **An unconfirmed first write is different from an ordinary content edit.** A
+ `WEB_RESOURCE_UNVERIFIED` halt names the existing row; it does not mean the resource was lost.
+ Keep the same writable build workspace and run the full build again after resolving the cause:
+ its recovery record makes the build write the content again by that id, publish it, verify the
+ published content, and finish adding it to the solution. Do not delete or rename it to retry.
+ A conflicting name/id or an unwritable recovery record needs the explicit resolution in the halt.
- **Never hardcode Choice (option-set) values in the script.** Values like `100000003` are assigned
per publisher, so a literal that is correct in one environment silently selects nothing in another —
and a `setValue` with an unknown value fails quietly. Resolve by label instead:
@@ -283,7 +289,8 @@ works through.
than emit a spec that cannot be rebuilt: rename one in Maker and download again. Because a name can
also match **another app's** dashboard, ownership comes from the app's solution, which holds every
dashboard the build creates (one the build cannot add to it is removed again, or named in the halt
- when that fails too). When several in the
+ when that fails too; one a build created and then stopped before adding is added by the next build,
+ which finds it by the id it recorded in its workspace before the create). When several in the
environment match, the build reuses — and verify checks, its sitemap entry included — the one the
solution holds, and halts if that does not single one out; a single match is used as it is. Teardown
deletes only the ones the solution holds, never a namesake, and none when the spec has no real
diff --git a/plugins/model-apps/references/app-spec-schema.md b/plugins/model-apps/references/app-spec-schema.md
index 2b6c70519..d4426d137 100644
--- a/plugins/model-apps/references/app-spec-schema.md
+++ b/plugins/model-apps/references/app-spec-schema.md
@@ -474,7 +474,7 @@ spec with its last snapshot, not with the deployed row, so it does not notice).
Integer · BigInt · Decimal · Double · File · Image · AutoNumber · Customer`.
**Lookups are NOT columns** — declare a `OneToMany` relationship instead.
- **Per-type options** (all optional except an AutoNumber column's `autoNumberFormat`): `required: true` /
- `"recommended"` / `false`; Text → `maxLength`,
+ `"recommended"` / `false`; Text/Memo → `maxLength`; Text →
`format` (`Text`/`Email`/`Url`/`Phone`); numeric → `minValue`/`maxValue`/`precision`;
Integer → also `integerFormat` (`None`/`Duration`/`TimeZone`/`Language`/`Locale` — e.g. render a
raw minute count as a Duration picker instead of a plain number); DateTime → `dateFormat`
@@ -483,6 +483,27 @@ spec with its last snapshot, not with the deployed row, so it does not notice).
`autoNumberFormat` (**required** on an AutoNumber column, e.g. `"C-{SEQNUM:5}"` — see the
AutoNumber note below); Calculated/Rollup → `source: "Calculated"|"Rollup"` +
`formula`.
+- **Downloaded column options are canonical, not a record of which defaults the author typed.**
+ Text format/length, Memo length, Integer range/format, Decimal/Double range/precision, Money range,
+ Boolean labels, DateTime format and AutoNumber masks are reconstructed, as are the primary name
+ column's length/mask. Options equal to the bundled SDK's create defaults are omitted: Text
+ length 100/format `Text`, Memo length 2000, Integer range -2147483648..2147483647/format `None`,
+ Decimal/Double range -100000000000..100000000000/precision 2, Money range 0..1000000000/precision 2,
+ Boolean `Yes`/`No` and DateTime `DateAndTime`. A primary name length stays explicit even at 100:
+ some environments override the length in a table create, and the post-create correction runs only
+ when `primaryAttribute.maxLength` is present. A missing or malformed detail read is named on
+ stderr; the typed column remains, but a fresh build cannot recover the missing option.
+ **Money precision is not generally portable.** The SDK always creates `PrecisionSource: 2`
+ (transaction currency). Download retains numeric `Precision` metadata only for source 2, and
+ even then the effective precision depends on the transaction currency's decimal places in the
+ target; equal numeric metadata does not prove currency equivalence. Source 0 (column precision),
+ source 1 (organization pricing), and missing/malformed/unknown sources are diagnosed with
+ precision omitted, without losing the typed Money column or its range. Configure the required
+ source in Power Apps on the target rather than relying on this spec to recreate it.
+ See [Money PrecisionSource](https://learn.microsoft.com/en-us/dotnet/api/microsoft.xrm.sdk.metadata.moneyattributemetadata.precisionsource).
+ This does not reconstruct `required`, Boolean `defaultValue`, `isValidFor*`, visualization,
+ BigInt ranges or DateTime behavior. A non-primary AutoNumber's custom length/format cannot be
+ authored through this spec; its number mask is carried.
- **Write permissions** (optional, every column type **except Customer**): `isValidForCreate` /
`isValidForUpdate` / `isValidForRead` — see `isValidForCreate / isValidForUpdate /
isValidForRead` below.
@@ -512,13 +533,12 @@ spec with its last snapshot, not with the deployed row, so it does not notice).
after the answer to its create was lost, or an existing table whose columns could not be read,
warns — `false` too, since nothing shows what the column holds), and running the build again finds
the table and sets the level as it does for any existing column — it never creates the table twice.
-- **`defaultValue`, `integerFormat`, and `isValidFor*` converge differently: by re-assertion, not
- by diff.** Unlike `required` above, a rebuild does not read the column's current state first —
- it simply re-sends whichever of these fields the spec sets explicitly, on every build, for both a
- brand-new column and one that already exists. This is safe because re-sending an already-correct
- value is a no-op on the wire; it does mean (unlike `required`) there is no "leave it alone if
- omitted" behavior to rely on for a value set by hand in the portal — omit the field entirely to
- leave portal-set state untouched, exactly as for `visualization` below.
+- **`defaultValue` and `isValidFor*` converge by re-assertion.** A rebuild re-sends whichever of
+ these fields the spec sets explicitly for an existing column; an omitted field leaves portal-set
+ state untouched, exactly as for `visualization` below. **A standalone `integerFormat` is
+ compared first:** an equal scalar format skips the SDK's read-mutate-write, while a different
+ or unreadable one keeps that update path. When other capabilities are authored alongside the
+ format, the existing combined update is still re-asserted.
- **Choice / MultiChoice** need `options[]` (string labels) **or** a `globalChoice` reference
(see `globalChoices` below). **Customer** is a polymorphic account/contact lookup.
- **AutoNumber** can also be the **primary** column — put `autoNumberFormat` on `primaryAttribute`
@@ -657,6 +677,22 @@ without needing a business rule or a plug-in to enforce it.
"mainFormOrder": ["Work Item", "Work Item — Summary"] // the Main Form Set order — see forms[] → "Which form a table opens with"
```
+A download keeps unmanaged custom `statusReasons` with Active/Inactive state, label, color and
+value (omitting `value` only when the build would assign the same number by index). Stock values
+1/2, managed reasons and stock-table reasons below 100000000 are not re-declared. Other states or
+incomplete metadata are named rather than fabricated. `alternateKeys` keep their schema names,
+column sets and available display labels; managed keys are not re-declared. Status labels use only
+the resolved download language (`--language-code`, the existing spec's `languageCode`, then the
+environment base language), not the caller's UI language. A reason missing that translation is
+omitted with a diagnostic, never relabelled from another LCID. A non-base-language download flag
+is read-time only: pass the same flag on rebuild or pin `languageCode` in the spec.
+A malformed or missing optional `Keys` array is diagnosed and recovers no keys, without dropping
+the table, its primary name, typed columns or navigation. On rebuild an equal
+status value/state/label in the authoring language (and color, when authored), or an equal key
+name/column set, skips the insert. An unknown or conflicting answer keeps the existing
+duplicate-protected create path: it is not an instruction to rewrite a conflicting deployed
+definition.
+
## Conditional features — read `app-spec-schema-advanced.md` when you use one
These fields are **optional and situational**: most apps use none of them, so their full field
@@ -1344,6 +1380,13 @@ A form field can carry these per-control options. Declare them **form-level** in
(keyed by column logical name) — the only route under an `auto` layout, which has no field list —
or **inline** on an explicit layout's `fields[]` entry as `{ "name": …, "readOnly": …, "hidden": … }`.
Where both apply to one field the inline entry wins; a plain string entry keeps working unchanged.
+An entry takes only the options below — `readOnly`, `hidden`, `after`, `colspan` and `rowspan` — and
+an inline entry its `name` as well; a `fieldOptions` entry takes no `name`, because its key names the
+field. Any other key (a misspelling such as `readOnlyy` or `colSpan`) is **rejected** at author time —
+by the lint, a dry run and a build — naming the key it most likely meant, rather than accepted and
+silently ignored. A spec an earlier release built with such a `fieldOptions` key can still be read:
+`verify-model-app.js` reports the key as a warning, and teardown and `preview-form.js` accept it. The
+option stays unapplied until the key is fixed.
- **`readOnly: true`** locks the control (`disabled="true"`), leaving it visible. Use it for a value
the platform generates but does **not** make immutable — an AutoNumber column is writable through
@@ -1594,16 +1637,102 @@ custom control), but the spec validator emits a warning.
highest identity authority (outranks the manifest), confirmed against EXISTENCE — so a downloaded
app (including Maker-added pages) rebuilds against the correct existing page without duplication.
- **What a page round-trip carries — and what it does not.** A download brings back each page's
- code, prompt, `dataSources`, the id of the **model** that generated it (`pages[].model`) and its
+ code, prompt, `dataSources`, the id of the **model** that generated it (`pages[].model`), its
+ **connector and Custom API bindings** (`pages[].connectorBindings`, `pages[].actionBindings`, below) and its
identity; the build sends the model with every update, and the page's own is kept when the spec has none
- (the SDK writes only what differs). A page's **connector and Custom API bindings** have no App
- Spec field, so they are not in the spec. The build writes pages without them, and the SDK leaves a page's
- existing bindings in place when they are omitted: a rebuild in the **same environment** keeps the
- bindings working, but that is preservation, not reconstruction — the same spec rebuilt in **another
- environment** deploys the page without them (bind them there with `/genpage`).
+ (the SDK writes only what differs). What no spec can bring to **another environment** is what the bindings
+ *name* — the connection references, the Custom APIs and the service resources (below).
- **`model` (optional).** The model id a page was generated with, e.g. `"gpt-4.1"` — letters, digits and
`. _ : / @ + -`, at most 100 characters. A download writes it (an id outside that shape is left out, with
a warning); an authored spec may omit it, and then a rebuild of an existing page keeps the model that page has.
+- **`connectorBindings` and `actionBindings` (optional).** The two lists a page holds in its `config.json`, each a
+ list of objects. A spec states an entry by **the properties the references document, each with a value of a
+ conservative shape known to be safe** — an allowlist (`references/connectors.md` and `references/custom-api.md`
+ say what they mean):
+ ```jsonc
+ { "connectorBindings": [ { "logicalName": "new_msnweather", "connectorId": "/providers/Microsoft.PowerApps/apis/shared_msnweather", "dataset": "", "operations": ["CurrentWeather"] } ],
+ "actionBindings": [ { "name": "new_ApproveOrder", "isFunction": false, "boundEntityLogicalName": "salesorder", "displayName": "Approve Order", "parameterKinds": { "Comment": "String" } } ] }
+ ```
+ | List | Property | Its value |
+ |---|---|---|
+ | `connectorBindings` | `logicalName` | an identifier: a letter, then letters, digits, `_ . -` |
+ | | `connectorId` | `/providers/Microsoft.PowerApps/apis/<identifier>`, or the identifier |
+ | | `dataset` | `""`, a plain name (`server,database`, `default`), or an `http(s)` URL with no user-info, no query and no fragment, whose host is DNS labels and whose decoded path segments are labels, written in its canonical form — exactly as a URL parser gives it back: no `.` or `..` segment (plain or percent-encoded), a lower-case scheme and host, no default port |
+ | | `tables` | a list of GUIDs or plain names (`[dbo].[Orders]`) |
+ | | `tableDisplayNames` | a list of labels: letters, digits, dashes, spaces and `_ . , ; : ' ( ) & + !` — no URL, no `=` |
+ | | `operations` | a list of identifiers |
+ | `actionBindings` | `name`, `boundEntityLogicalName` | an identifier |
+ | | `displayName` | a label |
+ | | `isFunction` | `true` or `false` |
+ | | `parameterKinds` | a map from a parameter name (a letter or `_`, then letters, digits, `_`) to one of the ten declared primitive kinds the page runtime accepts (`Boolean`, `DateTime`, `Decimal`, `Float`, `Integer`, `Money`, `Picklist`, `String`, `StringArray`, `Guid`) |
+
+ `EntityReference`, `Entity` and `EntityCollection` are not declared kinds: an unsupported declared
+ kind makes the runtime drop the whole binding. Lookup inputs remain structural call values, not
+ entries in this map; lookup authoring hints are discovery-only metadata, never App Spec binding
+ properties. Sparse primitive maps are valid; a lookup-only API can state `parameterKinds: {}`.
+ To deliberately correct an existing bad map, state its verified primitive entries explicitly
+ (or `{}` for lookup-only inputs). Omitting `actionBindings` preserves the page's existing payload
+ instead of correcting it; no unsupported declaration is silently stripped or changed to `Guid`.
+
+ No text of any of them may be shaped like a token (a known token prefix such as `ghp_` or `eyJ`, an
+ authorization scheme such as `Bearer …`, or a run of 32 or more letters and digits that mixes both).
+ **Nothing else is in a spec, and a list is stated only WHOLE.** A binding a page holds can carry anything: a
+ connection id of the environment it was made in, a credential someone wrote into a `connectors.json`
+ (`genpage-upload.js` takes any JSON array) — as a value, as the NAME of a property, in a URL's user-info, query or
+ fragment — or a property a later runtime adds. The spec is what is committed and shared, so when ANY entry of a list
+ holds a key that is not on the allowlist, or a value without its shape, a download leaves the **whole list** out of
+ the spec — it never states part of an entry, because an entry stated without its identity or a property would make a
+ rebuild replace the page's entry with less — and reports it in `pageBindings.notCarried` (stderr: `WARNING:`) by the
+ page, the list, the entry's place and the vetted property, or "an unrecognized property": **never a value and never an
+ unrecognized key**. A list left out is one a rebuild does not send, so the page keeps it as it is, with no write and no
+ publish. The page folder's own `config.json` is the page as the environment holds it and is not rewritten, so it still
+ holds everything: keep that folder out of version control if a value there is a credential. A spec that states such a
+ property or value is **refused** by the validator, in the same words. A list that is not a list of objects is left out
+ whole too; neither is ever a refusal of the download.
+ A download writes the lists a page holds (an empty list, or `null`, is left out). The build writes a list a
+ spec states, and **leaves the page's own alone when the spec does not state it**; a list that is stated —
+ `[]` too — is the page's list, as `dataSources` is. It is read against the page's own entries: a page that
+ already holds what the spec states is **not written and not published**, and an entry the spec changes keeps
+ the properties the spec does not state (an entry is matched by `logicalName` / `name`). `logicalName` (a
+ connector binding) and `name` (a Custom API binding) is what the page's code finds an entry by, so an entry
+ without one draws a warning.
+ The spec carries the lists, which are text; it cannot carry what they name, and a rebuild creates none of it,
+ so each must already exist in the environment you rebuild into: the **connection reference** each connector
+ binding goes through, and the connection behind it, which holds a user's sign-in (create the reference with
+ `create-connection-reference.js`, or move it in a solution with `add-page-to-solution.js --connection-refs` and
+ `solution-settings.js`); the **Custom API** each action binding names, a solution component and not an App Spec
+ item; and, for a connector binding that names a `dataset` or `tables` (a SharePoint site and its list ids),
+ the same resources. A download names what it found, on stderr and as `pageBindings` in its JSON result.
+ **A rebuild checks them before it writes anything** (a build, and a dry run in its plan): it reads the
+ environment's connection references and Custom APIs for the names the pages it writes state, and
+ - **stops** — `pages-binding-reference-conflict`, phase `preflight`, nothing written — at a connection reference
+ of that name that is for **another connector** than the binding's `connectorId` (compared by the connector's
+ name, so `/providers/Microsoft.PowerApps/apis/shared_msnweather` and `shared_msnweather` agree): the page
+ would call that connector under that name. Give the binding the logical name of a reference that is for the
+ right connector, or, when the reference that is there is the one the page should call (a custom connector made
+ separately in each environment has another id in each), set the binding's `connectorId` to the one this
+ environment has. Nothing is guessed or made, and a connector that a binding or a reference does not name is
+ never a conflict;
+ - **says by name** (a warning, and the page is written with its binding all the same — a reference made, or given
+ its connection, later makes the page work without a rebuild) each reference and Custom API that is not there, a
+ reference that is there with **no connection** (what a solution import leaves when no settings file gives one), an
+ **operation** a binding lists that the **custom connector** of its reference there does not define, a Custom API
+ that is the other kind (Action or Function) or bound to another table, and a read that failed (the bindings were
+ then not checked);
+ - **says as NOT CHECKED**, by name, what the environment's answer did not prove — never reading it as compatible,
+ and never refusing for it: a reference row that does not say which connector it is for, or whether it has a
+ connection — or says it in a form the build cannot read (a `connectorid` that is not
+ `/providers/Microsoft.PowerApps/apis/shared_<name>`, a `connectionid` that is not text) — and the operations of a
+ binding whose reference names no custom connector. Only two valid connector ids that differ stop the build. Operations are checked
+ only through a custom connector's definition (its `connector` row), which is the environment's own and can be
+ another version than the page was made with; a reference whose custom connector lookup is absent, null or not a
+ GUID — which a connector the platform publishes also has — is not proof of which connector defines them.
+
+ `/app-builder` never authors these lists — it writes no connector or Custom API code — so they come from a page
+ a download read. A page you reset to `source.kind: "intent"` to regenerate it is generated without connector
+ code: delete its bindings from the spec too, or it keeps bindings its code no longer uses. The `custom-api`
+ feature flag gates what the `/genpage` agents author, not the download or the rebuild of bindings a page
+ already holds.
- **Safety HALTs (pages phase).** The build halts on identity/safety violations rather than
proceeding with potentially wrong state:
- `pages-identity-conflict` — spec `pageId` and manifest disagree on a key, or a duplicate id is
@@ -1649,14 +1778,18 @@ custom control), but the spec validator emits a warning.
- **The navigation needs an entry Dataverse will take — for a new app.** Dataverse refuses to **create** a sitemap with no
non-empty area holding a non-empty group (HTTP 400: "SiteMap needs to have a non-empty Area with a non-empty Group"); it
accepts the same navigation when the sitemap of an app that **already exists** is updated (measured: saved and published).
- A **new** app is created before its pages exist, so its first navigation leaves every `page` entry out and the pages phase
- writes them in afterwards: it needs **at least one `entity`, `dashboard` or `url` entry in a group in an area**, and pages
- may sit beside it. An **existing** app is refused for neither a navigation of only `page` entries (its navigation is
+ A **new** app whose navigation has an `entity`, `dashboard` or `url` entry is created before its pages exist: its first
+ navigation leaves every `page` entry out, and the pages phase writes them in afterwards. A **new** app whose navigation
+ holds **only `page` entries** is built the other way round: the build creates the pages first and then the app, with them
+ already in its first navigation (as `apps.js create --page-id` makes an app around a page). So a new app needs **at least
+ one entry in a group in an area** — a table, dashboard, url or page entry. A run that cannot create the pages first (one
+ without the pages phase, or a changed-only re-upload) still refuses a navigation of only `page` entries for a new app. An
+ **existing** app is refused for neither a navigation of only `page` entries (its navigation is
written from the whole spec once its pages are built) nor one with no entry at all: the build goes on, and for the empty
one it **warns** that the app is left with no navigation entries — any it has now are removed, which the destructive-
operation check asks `--allow-destructive` for. A spec with no `appShell.areas` is refused for every app, since there is no
- navigation to build the app's sitemap from. A spec with no `appShell`, `areas: []`, an area with no group, a group with no
- entry, or (for a new app) only `page` entries still **validates** — a data-only spec has no navigation, and a downloaded
+ navigation to build the app's sitemap from. A spec with no `appShell`, `areas: []`, an area with no group, or a group with
+ no entry still **validates** — a data-only spec has no navigation, and a downloaded
spec carries the app's own, which can be empty — but a build that includes the app-shell phase refuses what a new app
cannot be built from **before it writes anything**: the dry run marks the app step `? unknown` with the reason and counts it
among the steps that would stop the build (with a live plan or without one), `--apply` halts with `app-navigation-empty`,
@@ -1898,6 +2031,7 @@ auto-selects tables that are good row-summary candidates and skips those that ar
- **Lint warnings:**
- `incident`, `lead`, and `opportunity` are Dynamics 365 app tables (Case / Lead / Opportunity) that provide their own row summaries — configuring one as a summary table warns, because the row-summary feature is not available for them.
- A table with no descriptive columns (only lookups / system fields) warns that a row summary may not be useful.
+ - A table's entry is read for `enabled`, `instruction` and `columns` only, and validation rejects no other key — so any other key warns that it is ignored. The prompt is `instruction`: a `prompt` key warns and names it. When a summary is enabled, omitting `instruction` uses the default prompt; setting `instruction` alone does not enable a table under `default: "off"`.
## personas[] (optional — security roles)
diff --git a/plugins/model-apps/references/connectors.md b/plugins/model-apps/references/connectors.md
index c398f9df4..210758b77 100644
--- a/plugins/model-apps/references/connectors.md
+++ b/plugins/model-apps/references/connectors.md
@@ -56,6 +56,26 @@ wrapped under `connectorBindings`; the skill never writes this file directly):
- `tableDisplayNames`: user-facing names aligned by index with `tables`.
- `operations`: REST/action operation names for `executeConnectorOperation`.
+## In an App Spec
+
+An app a download reads is written with each page's `connectorBindings` in `pages[].connectorBindings`, and a
+rebuild writes that list back onto the page (a spec that states none leaves the page's own). A spec states an
+entry by the properties documented above — `logicalName`, `connectorId`, `dataset`, `tables`, `tableDisplayNames`,
+`operations` — each with a value of a conservative shape known to be safe (an identifier, a GUID, a plain name or
+label, an `http(s)` URL with no user-info, no query and no fragment, written in its canonical form), and by nothing else. A list in which any entry
+holds anything else — a connection id, a credential, a property a binding holds beyond these — is left out of the
+spec WHOLE, reported by its place and the vetted property (never a value or an unrecognized key), and stays on the
+page, which a rebuild then leaves as it is (see `references/app-spec-schema.md` → `pages[]`). Never write a
+credential or a connection id into `connectors.json`; a spec that states one is refused.
+`/genpage` itself never reads or writes the spec. The spec carries the list and not what it names: the connection
+reference — and the connection behind it — must already exist in the environment you rebuild into
+(`create-connection-reference.js`, or a solution: `add-page-to-solution.js --connection-refs`, then
+`solution-settings.js`). A rebuild reads the environment's references before it writes: one of that name for
+**another connector** than the binding's `connectorId` stops it, before anything is written; one that is not there,
+one that has no connection, and an operation in `operations` that a custom connector there does not define are
+said by name; what the environment's answer did not prove (its row's connector or connection, or which custom
+connector it is for) is said by name as not checked.
+
## Runtime requirements
- Always cast `dataApi` to an optional connector-method shape.
diff --git a/plugins/model-apps/references/custom-api.md b/plugins/model-apps/references/custom-api.md
index e16b5f198..598b0c2ef 100644
--- a/plugins/model-apps/references/custom-api.md
+++ b/plugins/model-apps/references/custom-api.md
@@ -6,15 +6,15 @@ token** (no broker, no impersonation). The `name` string a page passes to
`dataApi.executeAction` / `executeFunction` **MUST** equal an `actionBindings[].name` value
in the page `config.json`, and that Custom API must exist in the target environment.
-> **Gated behind the `custom-api` feature flag (default OFF).** This reference is only used
-> when Custom API support is enabled — see the Feature Flags section in the plugin `AGENTS.md`
-> and `feature-flags.json`. When OFF, pages are Dataverse / mock-data / connector only;
-> **no Custom API code is emitted and no `actionBindings` are
-> written**. The `genpage-customapi-builder` agent is the single owner of this gate.
+> **Custom API discovery is enabled by default**, with a retained `custom-api` feature flag.
+> Set `GENPAGE_ENABLE_CUSTOM_API=0` to opt out. Unknown flags and missing/unreadable config
+> still fail closed. When OFF, no new Custom API bindings or calls are authored; unrelated
+> edits preserve existing bindings unchanged. The `genpage-customapi-builder` agent owns this gate.
> **Vocabulary.** Makers author **Custom APIs** (the Dataverse `customapi` artifact); each is
-> either an **Action** (may mutate; call with `executeAction`) or a **Function** (read-only;
-> call with `executeFunction`). The shipped runtime contract uses the technical term
+> either an **Action** (POST; call with `executeAction`) or a **Function** (GET;
+> call with `executeFunction`). Known read semantics, not GET alone, determine whether automatic
+> invocation is appropriate. The shipped runtime contract uses the technical term
> *action*: bindings persist into `config.json.actionBindings` and the upload flag is
> `--actions`. So the maker-facing skill says "Custom API" while the wire format stays
> `actionBindings` — the two describe the same thing at different layers.
@@ -59,7 +59,7 @@ under `actionBindings`; the skill never writes this file directly):
the TSX passes as `executeAction({ name })` / `executeFunction({ name })`. **This is the
revision-bound gate — a name not in `actionBindings` is rejected client-side with
`not_bound` and is never dispatched.**
-- `isFunction`: `true` ⇒ a read-only **Function** (call with `executeFunction`; GET
+- `isFunction`: `true` ⇒ a **Function** (call with `executeFunction`; GET
semantics); `false`/absent ⇒ an **Action** (call with `executeAction`; may mutate; POST).
Calling the wrong method is rejected with `wrong_operation_kind` before dispatch.
- `boundEntityLogicalName`: present ⇒ the operation is **entity-bound** and its calls
@@ -68,11 +68,83 @@ under `actionBindings`; the skill never writes this file directly):
- `displayName`: friendly name surfaced by `listBoundActions()`; discovery/affordance only.
- `parameterKinds`: the Custom API's DECLARED request-parameter kinds, keyed by parameter
unique name (e.g. `{ "Amount": "Decimal" }`). The runtime has no other source for these,
- so record every request parameter's Dataverse type. Values are `DataverseParameterKind`
+ so record every primitive request parameter's Dataverse type. Values are `DataverseParameterKind`
strings: `String`, `Integer`, `Decimal`, `Float`, `Money`, `Boolean`, `DateTime`, `Guid`,
- `StringArray`, `EntityReference`, `Entity`, `EntityCollection`, `Picklist`.
+ `StringArray`, `Picklist`.
+ EntityReference, Entity and EntityCollection are **not** declared kinds: an unsupported kind
+ causes the runtime to drop the whole binding, so calls fail with `not_bound`.
See <https://learn.microsoft.com/power-apps/developer/data-platform/custom-api>.
+## In an App Spec
+
+An app a download reads is written with each page's `actionBindings` in `pages[].actionBindings`, and a rebuild
+writes that list back onto the page (a spec that states none leaves the page's own). A spec states an entry by the
+properties documented above — `name`, `isFunction`, `boundEntityLogicalName`, `displayName`, `parameterKinds` — and
+by nothing else, each with a value of a conservative shape known to be safe (an identifier, a label, a flag, a map of
+parameter names to the ten primitive declared kinds documented above). A list in which any entry holds anything else is left out of the spec
+WHOLE, reported by its place and the vetted property (never a value or an unrecognized key), and stays on the page;
+a spec that states one is refused (see `references/app-spec-schema.md` → `pages[]`). `/genpage`
+itself never reads or writes the spec. The spec carries the list and not the Custom APIs it names: each must
+already exist in the environment you rebuild into, deployed in a solution. A rebuild reads the environment's Custom
+APIs before it writes and says by name one that is not there, one that is the other kind (Action or Function) and
+one bound to another table; it does not stop for them. The `custom-api` flag gates what the `/genpage` agents
+author, not this.
+
+An App Spec must not declare `EntityReference`, `Entity` or `EntityCollection`. A downloaded list
+holding an unsupported declared kind is left out whole and reported by place and property, never
+by value; the raw page config and an omitted list's rebuild payload stay untouched. A sparse
+primitive map such as `{ "Note": "String" }` is valid, as is `{}` for a lookup-only API. The lookup
+still belongs in the call as `{ entityName, id }`; its authoring hints remain discovery-only,
+not App Spec binding fields (see below). A deliberate repair states the verified primitive map
+explicitly; omitting the list preserves it rather than repairing it. Do not coerce a lookup to `Guid`.
+
+## Discovery-only lookup inputs
+
+`list-custom-apis.js` discovers supported public Global APIs and APIs bound to the page's
+tables. It excludes private APIs, collection-bound APIs, and APIs with Entity/EntityCollection
+inputs **or outputs**. It reads request and response type metadata inline in one query;
+an unreadable or incomplete required metadata answer is an error, never a successful empty list.
+These discovery rules do not remove unrelated existing page bindings.
+Single-level expanded collections normally include relationship `@odata.nextLink` annotations
+that describe the same related rows, not another page. Discovery accepts those known links
+without following them; genuine/ambiguous paging and the 5,000-related-row ceiling fail explicitly.
+See <https://learn.microsoft.com/power-apps/developer/data-platform/webapi/query/join-tables#single-expand-on-collection-valued-navigation-properties>.
+Request names must be usable and unique. Lookup requiredness must be a real boolean, and a
+supplied table hint must be a valid string; missing or malformed authoring facts are errors,
+not guessed defaults. An absent/null table hint is legitimate.
+
+A lookup (request type 5) is supported **structurally**, not through a declared kind.
+Discovery retains its exact input name separately:
+
+```json
+{
+ "name": "new_ResolveReference",
+ "parameterKinds": { "Note": "String" },
+ "lookupParameters": {
+ "Ref": { "isOptional": false, "logicalEntityName": "account" },
+ "OptionalRef": { "isOptional": true }
+ }
+}
+```
+
+`lookupParameters` is **discovery-only authoring metadata**, not an `actions.json` or
+`config.json.actionBindings` field. Keep lookup names and required/optional/table information
+in the plan's separate lookup-input notes, not in its primitive kind column.
+The callable `Ref` input must not disappear just because it has no declared kind.
+
+Pass a lookup as exactly `{ entityName, id }`, for example
+`Ref: { entityName: 'account', id: selectedAccount.accountid }` from a record the page
+actually loaded or selected. For the directly checked member form, use a named helper's explicit
+record input (for example `selectedAccount: { accountid: string }`) supplied from the page's
+existing record input. Do not fabricate a local record or cast an unknown object to provide
+type/provenance evidence. For a more complex record source, pass its verified ID through an
+explicitly typed `string` helper input instead of an unproven member chain.
+Honor `logicalEntityName` when discovery supplies a table hint;
+when it is absent, establish the table from actual schema/record context rather than guessing.
+Omit an optional lookup when no record was selected. Never invent a GUID, substitute a
+primitive Guid parameter, or manufacture a null lookup value.
+See <https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/customapirequestparameter>.
+
## Runtime requirements
- Always cast `dataApi` to the optional action-method shape and **presence-check** the method
@@ -80,8 +152,9 @@ under `actionBindings`; the skill never writes this file directly):
- **Actions may mutate: guard against double-submit.** Keep an `isSubmitting` flag per
action-triggering control; disable it while a call is in flight; never fire a second
`executeAction` for the same trigger before the first resolves.
-- **Functions are read-only** — safe to call on mount / on a filter change; no double-submit
- guard needed (still avoid pointless overlapping fetches; ignore stale responses).
+- **Functions use GET, not a proof of harmless behavior.** Automatic mount/filter invocation
+ requires author-known read semantics for the selected Custom API. Otherwise require an explicit
+ user trigger and prevent overlapping submissions; still avoid pointless fetches and ignore stale responses.
- **`boundTo` rules** (checked against the manifest BEFORE dispatch; every mismatch is
`invalid_bound_to`): an entity-bound operation (`boundEntityLogicalName` present) REQUIRES
`boundTo`; `boundTo.entityName` must equal that table; a Global operation must NOT receive
@@ -161,7 +234,7 @@ try {
For a **Global** action, omit `boundTo` entirely.
-## Verified Function pattern (read-only; safe on mount)
+## Function pattern (known read semantics required before automatic invocation)
```typescript
const actionApi = dataApi as unknown as { executeFunction?: (request: { name: string; parameters?: Record<string, unknown> }) => Promise<{ ok: boolean; outputs?: Record<string, unknown>; error?: { message: string; code?: string } }>; };
diff --git a/plugins/model-apps/references/rules.md b/plugins/model-apps/references/rules.md
index 2cd6fb09b..e510feb49 100644
--- a/plugins/model-apps/references/rules.md
+++ b/plugins/model-apps/references/rules.md
@@ -645,14 +645,18 @@ required patterns and the binding contract.
When the plan's `## Custom API Bindings` contains a binding table, the page may invoke Dataverse
**Custom APIs** (server-side plug-in logic) on the signed-in user's own token. A Custom
-API of kind **Action** (may mutate) is called with `dataApi.executeAction`; a **Function**
-(read-only) with `dataApi.executeFunction`; `dataApi.listBoundActions` enumerates the
+API of kind **Action** (POST) is called with `dataApi.executeAction`; a **Function**
+(GET) with `dataApi.executeFunction`; `dataApi.listBoundActions` enumerates the
page's bound operations. These are optional runtime methods — always presence-check before
calling, guard Actions against double-submit, read results from `res.outputs` (never
`res.value`), surface only the sanitized `res.error?.message`, and never auto-retry an
`indeterminate` result. Call only the `name`s in the plan's `## Custom API Bindings`; a name
not bound to the page fails with `not_bound`. See [custom-api.md](./custom-api.md) for the
required patterns, the `boundTo` rules, and the full `error.code` contract.
+Automatic Function invocation requires known read semantics, not merely GET metadata.
+Read the plan's separate lookup-input notes: structural `{ entityName, id }` lookup values
+remain call inputs even though only primitive kinds appear in `parameterKinds`.
+Discovery-only `lookupParameters` must never be copied into a wire binding.
---
diff --git a/plugins/model-apps/scripts/build-model-app.js b/plugins/model-apps/scripts/build-model-app.js
index cb8dbac6f..2d3d80f4c 100644
--- a/plugins/model-apps/scripts/build-model-app.js
+++ b/plugins/model-apps/scripts/build-model-app.js
@@ -923,8 +923,10 @@ function isTransientHalt(err, { spec } = {}) {
if (!err) return false;
// A dashboard the build could neither add to its solution nor remove again says `transient: false`
// (sdk-build.js): its message quotes the causes verbatim — a customization lock, "try again later" —
- // but a retry would find the dashboard as a lone name match and reuse it outside the solution, the
- // state the undo exists to prevent. `never` is that, and the typed refusals, and a status that says no.
+ // but the add and its undo were both refused just now, which is a person's to look at, and a dashboard
+ // the build could not record (lib/dashboard-creation-records.js) would be found by a retry as a lone name
+ // match and reused outside the solution, the state the undo exists to prevent. One it recorded is added by
+ // the maker's next run. `never` is that, and the typed refusals, and a status that says no.
const judgement = judgeFailure(err, spec ? { declares: (table, column) => specDeclaresAttribute(spec, table, column) } : {});
if (judgement.never) return false;
if (judgement.transient) return true;
diff --git a/plugins/model-apps/scripts/download-model-app.js b/plugins/model-apps/scripts/download-model-app.js
index af634b463..8267b66a3 100644
--- a/plugins/model-apps/scripts/download-model-app.js
+++ b/plugins/model-apps/scripts/download-model-app.js
@@ -21,6 +21,13 @@
// the download stops without writing anything, `{ ok: false, code: 'navigation-language-unknown', error }`: titles read in a guessed language could overwrite the right ones on the next
// rebuild. Run it again, or pass --language-code. The flag only decides the language the titles are read in: it is not written into the spec (a pin there is the author's), and a flag that
// names another language than the spec on disk pins is refused (`navigation-language-conflict`).
+//
+// A page's connector and Custom API bindings are written into the spec (`pages[].connectorBindings`, `pages[].actionBindings`) when the spec can state a list WHOLE — every key one of the properties the
+// references document, every value of a shape known to be safe (lib/page-bindings.js, which holds the threat model and every sink) — so a rebuild keeps them in this environment and writes them into another
+// one. A list holding anything else (a connection id, a credential, a property this plugin does not know) is left out whole, named by its place and the vetted property, never a value or an unrecognized key,
+// and stays on the page. What a rebuild cannot make in another environment — the connection references and the connections behind them, the Custom APIs, the service resources a connector binding points at
+// — is said on stderr and in the JSON result as `pageBindings` (pageBindingsReport): { pages, neededInTarget, notCarried?, note }.
+// It is left out of the result when no page holds a binding and none had to be left out; a list the spec cannot state is never a refusal (see parseDownloadedPages).
const fs = require('node:fs');
const path = require('node:path');
@@ -35,12 +42,15 @@ const { reverseResolveNavIdsReport } = require('./lib/pageref-resolver.js');
const { fetchSitemap, sitemapGenPages, appNavigationMatchesSitemap } = require('./lib/sitemap-pages.js');
const { isRestrictedSolution } = require('./lib/system-solutions.js');
const { isPlatformIconRef, webResourceNameFromRef, validateAppSpec, normalizeLanguageCode, isLocalizedLabelMap, derivedPluralName, ambiguousChoiceAliases, relationshipSchemaName, manyToManySchemaName, dashboardNameKey, PAGE_MODEL_RE, sitemapEntityTables, lookupLabelFor, isOldLookupColumnLabel } = require('./lib/app-spec.js');
+const { PAGE_BINDINGS, pageBindingsProblem, statableBindings, bindingProblemText } = require('./lib/page-bindings.js');
const { labelsByLcid, sameLabel } = require('./lib/lookup-labels.js');
const { odataGuid } = require('./lib/ai-app-settings.js');
const { APP_COMPONENT_ENTITY_SOURCES, appComponentEntities, appComponentRows, currentAppLayer, readAppComponentInventory, downloadAppMainForms, setAppMembershipFloor } = require('./lib/app-components.js');
const { mapLimit, DEFAULT_MAX_SIZE_KB } = require('./lib/entity-provision.js');
const { compareText } = require('./lib/compare-text.js');
const { hostsCustomControl } = require('./lib/dashboard-tiles.js');
+const { readColumnOptions, columnOptionFields, primaryColumnOptionFields } = require('./lib/download-column-options.js');
+const { readStatusOptions, statusReasonsFromOptions, alternateKeysFromMetadata } = require('./lib/table-schema-metadata.js');
const { appUniqueName } = require('./lib/sdk-build.js');
const { makeTempWorkspace } = require('./lib/temp-workspace.js');
const { makeWritesBlocking } = require('./lib/output-redaction.js');
@@ -137,6 +147,11 @@ async function readDashboards(sdk, app, warn) {
const p = c.parameters || {};
const entity = p.TargetEntityType;
const viewId = strip(p.ViewId);
+ // The SDK already read each cell's dimensions. Keep only non-default spans: the build
+ // creates a 1-column by 12-row tile when neither is stated, including for one-row tiles.
+ const size = {};
+ if (Number.isInteger(c.colspan) && c.colspan > 0 && c.colspan !== 1) size.colspan = c.colspan;
+ if (Number.isInteger(c.rowspan) && c.rowspan > 0 && c.rowspan !== 12) size.rowspan = c.rowspan;
// A grid or chart a custom control hosts reads exactly like a native one (lib/dashboard-tiles.js, which verify shares),
// so it must be told apart BEFORE the branches below build a plain tile from its parameters. It is left out, and named —
// never emitted as the plain tile that would replace the control when a rebuild creates the dashboard. A rebuild into
@@ -168,14 +183,14 @@ async function readDashboards(sdk, app, warn) {
if (c.type === 'chart' && !visualizationId) missing.push('VisualizationId');
if (!missing.length) {
tiles.push(c.type === 'chart'
- ? { type: 'chart', name: c.name, entity, viewId, visualizationId }
- : { type: 'list', name: c.name, entity, viewId });
+ ? { type: 'chart', name: c.name, entity, viewId, visualizationId, ...size }
+ : { type: 'list', name: c.name, entity, viewId, ...size });
} else if (typeof warn === 'function') {
warn(`dashboard '${name}' ${c.type} tile '${c.name || viewId || '(unnamed)'}' carries no ${missing.join(' or ')}, so it cannot be rebuilt; it is omitted from dashboards[].`);
}
}
- else if (c.type === 'iframe' && p.Url) tiles.push({ type: 'iframe', name: c.name, url: p.Url });
- else if (c.type === 'webresource' && p.WebResourceName) tiles.push({ type: 'webresource', name: c.name, webResource: p.WebResourceName });
+ else if (c.type === 'iframe' && p.Url) tiles.push({ type: 'iframe', name: c.name, url: p.Url, ...size });
+ else if (c.type === 'webresource' && p.WebResourceName) tiles.push({ type: 'webresource', name: c.name, webResource: p.WebResourceName, ...size });
// Everything else a dashboard can hold. Reported for the same reason as the branches above: the
// dashboard-level "no recognizable tiles" warning below only fires when NOTHING survives, so a
// dashboard with one good tile would otherwise drop its siblings in silence.
@@ -253,6 +268,36 @@ function adoptDeployedName(rel, deployed, auto, publisherPrefix, prefixUnknown,
}
}
+// The relationship the platform makes WITH a File or an Image column, as a table's ManyToOneRelationships answers it (LIVE-MEASURED):
+// { "SchemaName": "FileAttachment_<table>_<file>", "ReferencedEntity": "fileattachment", "ReferencingEntity": "<table>",
+// "ReferencingAttribute": "<file>", "IsCustomRelationship": true }
+// { "SchemaName": "ImageDescriptor_<table>_<image>", "ReferencedEntity": "imagedescriptor", "ReferencingEntity": "<table>",
+// "ReferencingAttribute": "<image>id", "IsCustomRelationship": false }
+// Nothing but the column makes it, so a build that creates the column gets it back and relationships[] has nothing to say of it. The
+// Image one is not custom, so the custom filter drops it; the File one IS custom and its parent a stock table, so it was carried as an
+// `existing` relationship under a name with no publisher prefix, and warned about for that. Recognised by the column, not by the parent
+// table alone: the referencing attribute must be a File column of the table (or an Image column's `<name>id`) as this download typed it
+// (entityFromMetadata), so a relationship to either table that is no such column's reads as it always did.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/file-attributes
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/image-attributes
+const MEDIA_RELATIONSHIP_PARENT = { File: 'fileattachment', Image: 'imagedescriptor' };
+
+// `<parent>:<referencing attribute>` of every such relationship, by the table's logical name, from the downloaded tables' columns.
+function mediaRelationshipKeys(entities) {
+ const lc = (s) => String(s || '').toLowerCase();
+ const out = new Map();
+ for (const e of entities || []) {
+ if (!e || !e.schemaName) continue;
+ const keys = new Set();
+ for (const c of Array.isArray(e.columns) ? e.columns : []) {
+ if (!c || !c.schemaName || !Object.hasOwn(MEDIA_RELATIONSHIP_PARENT, c.type)) continue;
+ keys.add(`${MEDIA_RELATIONSHIP_PARENT[c.type]}:${lc(c.schemaName)}${c.type === 'Image' ? 'id' : ''}`);
+ }
+ if (keys.size) out.set(lc(e.schemaName), keys);
+ }
+ return out;
+}
+
// Per-table relationship reads overlap because they are independent network fetches, but the
// TABLE-ORDER processing that dedupes, warns and chooses the surviving N:N owner stays sequential so
// the emitted notes and winners do not depend on response timing.
@@ -261,7 +306,12 @@ function adoptDeployedName(rel, deployed, auto, publisherPrefix, prefixUnknown,
// ordered pass below words the note from it exactly as the sequential loop did — including for a
// rejection that is not an Error, where `e && e.message` reads as undefined — and never mistakes a
// falsy rejection for "no failure".
-async function readRelationshipMetadataForTable(sdk, logical) {
+//
+// `mediaKeys` is the table's entry of mediaRelationshipKeys: a File or Image column's own relationship is dropped with the platform's
+// others, before the lookup read below — which it would otherwise cost a table that has no other custom relationship.
+async function readRelationshipMetadataForTable(sdk, logical, mediaKeys) {
+ const lc = (s) => String(s || '').toLowerCase();
+ const isMediaRelationship = (r) => !!mediaKeys && mediaKeys.has(`${lc(r.ReferencedEntity)}:${lc(r.ReferencingAttribute)}`);
let rows = null;
let rowsFailure = null;
try {
@@ -270,7 +320,7 @@ async function readRelationshipMetadataForTable(sdk, logical) {
const res = await sdk.dataverse.get(`/${metadataEntityPath(logical)}/ManyToOneRelationships`
+ '?$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute,IsCustomRelationship');
if (!res || res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res && res.status}`);
- rows = ((res.body && res.body.value) || []).filter((r) => r && r.IsCustomRelationship);
+ rows = ((res.body && res.body.value) || []).filter((r) => r && r.IsCustomRelationship && !isMediaRelationship(r));
} catch (e) {
rowsFailure = { error: e };
}
@@ -368,7 +418,8 @@ async function readRelationships(sdk, logicals, publisherPrefix, warn, { prefixU
return (would.source === 'table' || would.source === 'environment') && sameLabel(lookupLabel, would.label);
};
- const captured = await mapLimit(logicals || [], concurrency, (logical) => readRelationshipMetadataForTable(sdk, logical), { firstInOrder: true });
+ const media = mediaRelationshipKeys(entities);
+ const captured = await mapLimit(logicals || [], concurrency, (logical) => readRelationshipMetadataForTable(sdk, logical, media.get(lc(logical))), { firstInOrder: true });
for (const { logical, rows, rowsFailure, lookups, manyToManyRows, manyToManyFailure } of captured) {
if (rowsFailure) {
// Report rather than swallow: "no relationships" and "the query failed" must not look alike.
@@ -931,7 +982,10 @@ async function readDescriptionInventory(sdk, appId, solutionScope, referencedGlo
//
// `unkeptModels` collects pages whose model id the App Spec cannot hold (`PAGE_MODEL_RE`): written into
// the spec it would fail validation and block a rebuild, so it is left out and reported instead.
-function parseDownloadedPages(pagesRoot, outDir, nameById, unreadable, unkeptModels) {
+//
+// `unkeptBindings` collects the pages whose config.json holds a list of connector or Custom API bindings the spec cannot state: { pageId, field, reason }. The list is not a list, or an entry is not an object
+// (`pageBindingsProblem`), or an entry holds anything a spec does not state (see the projection below). `reason` names the place and the vetted property, never a value or an unrecognized key.
+function parseDownloadedPages(pagesRoot, outDir, nameById, unreadable, unkeptModels, unkeptBindings) {
const pages = [];
if (!fs.existsSync(pagesRoot)) return pages;
// Read in the pages' own order (comparePages), not the directory's: `readdirSync` lists in the file system's order, which is
@@ -992,11 +1046,37 @@ function parseDownloadedPages(pagesRoot, outDir, nameById, unreadable, unkeptMod
const recordedModel = typeof config.model === 'string' ? config.model.trim() : '';
const model = PAGE_MODEL_RE.test(recordedModel) ? recordedModel : undefined;
if (recordedModel && !model && Array.isArray(unkeptModels)) unkeptModels.push({ pageId: entry, model: recordedModel });
+ // The page's connector and Custom API bindings, written into the spec only when the spec can state them WHOLE (page-bindings.js has the threat model and every sink): each key one of the properties the
+ // references document, each value of a conservative shape known to be safe. A binding can carry anything — a connection id, a credential written into a connectors.json (genpage-upload.js takes any JSON
+ // array) as a value, a key or part of a URL, a property a later runtime adds — and the spec is what is committed and shared, so a list with any such thing in any entry is left out of the spec WHOLE and
+ // recorded in `unkeptBindings`, with the place and the vetted property's name only. Nothing is projected out of it: an entry stated without its identity, or without a property it holds, would make a rebuild
+ // REPLACE the page's entry with less (mergeBindings matches entries by identity), while a list the spec leaves out is one a rebuild does not send, so the page keeps it as it is — no write, no publish. It
+ // stays, too, in the page folder's own config.json, which this does not rewrite.
+ // A list that has an entry is carried; an empty one is not, as it says what a page with none already says. `null` is the page's way of holding none (the backend reads it as "not given"), so there is nothing to report.
+ // A list left out is reported and not a gate — a page whose list is left out keeps it when it is rebuilt into this environment, which is what a rebuild did before the spec could state bindings — whereas the
+ // page's data sources, which a rebuild replaces, are (above).
+ const bindings = {};
+ for (const kind of Object.keys(PAGE_BINDINGS)) {
+ if (!Object.prototype.hasOwnProperty.call(config, kind) || config[kind] === null) continue;
+ const problem = pageBindingsProblem(kind, config[kind]);
+ if (problem) {
+ if (Array.isArray(unkeptBindings)) unkeptBindings.push({ pageId: entry, field: kind, reason: problem });
+ continue;
+ }
+ if (!config[kind].length) continue;
+ const projected = statableBindings(kind, config[kind]);
+ if (projected.problem) {
+ if (Array.isArray(unkeptBindings)) unkeptBindings.push({ pageId: entry, field: kind, reason: bindingProblemText(kind, projected.problem.entry, projected.problem) });
+ continue;
+ }
+ bindings[kind] = projected.stated;
+ }
pages.push({
pageId: entry,
name: nameOf(entry),
dataSources: Object.prototype.hasOwnProperty.call(config, 'dataSources') ? config.dataSources : [],
...(model ? { model } : {}),
+ ...bindings,
prompt,
codeFile: path.relative(outDir, tsx).replace(/\\/g, '/'),
});
@@ -1004,6 +1084,114 @@ function parseDownloadedPages(pagesRoot, outDir, nameById, unreadable, unkeptMod
return pages;
}
+// The names a page's bindings go by — `PAGE_BINDINGS` says which property of an entry names it — each once, in code-unit order (compareText). An entry with no name (a page can hold one; the validator warns of it)
+// is listed as `(no <property>)`, so a page that holds a binding never reads as one that holds none.
+function bindingNames(list, identity) {
+ const names = (Array.isArray(list) ? list : []).map((entry) => (entry && typeof entry[identity] === 'string' && entry[identity].trim() ? entry[identity].trim() : `(no ${identity})`));
+ return [...new Set(names)].sort(compareText);
+}
+
+// What the connector and Custom API bindings of the pages a download read come to, and what a rebuild into ANOTHER environment still cannot bring:
+// { pages: [{ key, name, connectorBindings?: [name…], actionBindings?: [name…] }], notCarried?: [{ key, name, field, reason }], neededInTarget: { connectionReferences?, customApis?, serviceResources? }, note }
+// or null when no page holds a binding or lost one. `pages` are the pages whose bindings are in the spec, in the order the spec lists its pages, each with the names its bindings go by (identifiers: a list is
+// in the spec only when every value in it has a safe shape, page-bindings.js); `notCarried` the lists a page holds that the spec cannot state (`unkept`, from parseDownloadedPages), each with the place and the
+// vetted property that kept it out, never a value — a rebuild into this environment leaves those as they are, and a rebuild into another does not carry them.
+//
+// The spec carries the binding LISTS: they are plain text in the page's config.json, so a rebuild writes them in any environment. It carries nothing of what they name, and a rebuild makes none of it:
+// - a connector binding names a CONNECTION REFERENCE by its logical name. The reference is a Dataverse row that points at a connection, and a connection holds a user's sign-in, so it stays in the environment
+// that made it; the page resolves the reference by name, which is how the page itself can travel (https://learn.microsoft.com/power-apps/maker/data-platform/create-connection-reference);
+// - a Custom API binding names a Custom API by its unique name. A Custom API is a solution component, not an App Spec item (https://learn.microsoft.com/power-apps/developer/data-platform/custom-api);
+// - what a connector binding points at inside the service — `dataset`, `tables`: a SharePoint site and its list ids, say — is written as the page holds it, and means something in another environment only if the same
+// resources are there. `serviceResources` names the connection references whose bindings carry one.
+function pageBindingsReport(pages, unkept) {
+ const held = [];
+ const references = new Set();
+ const apis = new Set();
+ const service = new Set();
+ const nonEmpty = (list) => Array.isArray(list) && list.length > 0;
+ for (const page of pages || []) {
+ if (!nonEmpty(page.connectorBindings) && !nonEmpty(page.actionBindings)) continue;
+ const entry = { key: page.key, name: page.name };
+ if (nonEmpty(page.connectorBindings)) {
+ entry.connectorBindings = bindingNames(page.connectorBindings, PAGE_BINDINGS.connectorBindings);
+ for (const binding of page.connectorBindings) {
+ const name = binding && typeof binding.logicalName === 'string' ? binding.logicalName.trim() : '';
+ if (!name) continue;
+ references.add(name);
+ if (binding.dataset || nonEmpty(binding.tables)) service.add(name);
+ }
+ }
+ if (nonEmpty(page.actionBindings)) {
+ entry.actionBindings = bindingNames(page.actionBindings, PAGE_BINDINGS.actionBindings);
+ for (const binding of page.actionBindings) {
+ const name = binding && typeof binding.name === 'string' ? binding.name.trim() : '';
+ if (name) apis.add(name);
+ }
+ }
+ held.push(entry);
+ }
+ const byId = new Map((pages || []).map((p) => [String(p.pageId).toLowerCase(), p]));
+ const notCarried = (unkept || []).map((u) => {
+ const page = byId.get(String(u.pageId).toLowerCase()) || {};
+ return { key: page.key, name: page.name === undefined ? u.pageId : page.name, field: u.field, reason: u.reason };
+ }).sort((a, b) => compareText(a.name, b.name) || compareText(a.field, b.field));
+ if (!held.length && !notCarried.length) return null;
+ const sorted = (set) => [...set].sort(compareText);
+ return {
+ pages: held,
+ ...(notCarried.length ? { notCarried } : {}),
+ neededInTarget: {
+ ...(references.size ? { connectionReferences: sorted(references) } : {}),
+ ...(apis.size ? { customApis: sorted(apis) } : {}),
+ ...(service.size ? { serviceResources: sorted(service) } : {}),
+ },
+ note: 'The spec states these bindings, so a rebuild writes them onto each page in any environment. A rebuild cannot create what they name — the connection references and the connections behind them, the Custom APIs, and the '
+ + 'service resources a connector binding points at — so each must already exist in the environment you rebuild into. A rebuild reads them there before it writes a page: it stops, before writing anything, at a connection '
+ + 'reference that is for another connector, and says by name each reference and Custom API that is not there, a reference that has no connection, and an operation a custom connector there does not define.',
+ };
+}
+
+// Render `pageBindingsReport` as the operator-facing text on stderr, kept apart from the computation (as notRoundTrippedWarning is) so the wording is testable without a download. The scripts it names are
+// the ones that make each missing piece in the target environment.
+function pageBindingsNote(report) {
+ if (!report) return '';
+ const lines = [];
+ const needed = report.neededInTarget || {};
+ const list = (names) => names.join(', ');
+ if (report.pages.length) {
+ lines.push(
+ `NOTE: ${report.pages.length} page(s) hold connector or Custom API bindings, and the spec states them (pages[].connectorBindings, pages[].actionBindings), so a rebuild writes them back onto the page — here or in another environment.`,
+ ' Rebuilding into THIS environment keeps them working. Rebuilding into a DIFFERENT environment writes them, but cannot bring what they name, which has to be there first:',
+ );
+ if (needed.connectionReferences) {
+ lines.push(` - connection reference(s) ${list(needed.connectionReferences)}, and the connection each one goes through (a connection holds a user's sign-in, so it stays where it was made): create the reference there with create-connection-reference.js, or move it with a solution (add-page-to-solution.js --connection-refs, then solution-settings.js for the connection ids)`);
+ }
+ if (needed.customApis) {
+ lines.push(` - Custom API(s) ${list(needed.customApis)}: a Custom API is a solution component, not an App Spec item — deploy it there first (list-custom-apis.js lists what an environment has); one bound to a table needs that table there too`);
+ }
+ if (needed.serviceResources) {
+ lines.push(` - what the connector bindings of ${list(needed.serviceResources)} point at inside the service (dataset, tables: a SharePoint site and list ids, for example) is written as it is here, and works there only if the same resources exist`);
+ }
+ lines.push(' Until they are, the page cannot use those bindings. A rebuild reads them in the environment it writes to: it stops, before writing anything, at a connection reference that is for another connector, and names each reference and Custom API that is not there, each reference that has no connection, and each operation a custom connector there does not define. The pages:');
+ for (const page of report.pages) {
+ const parts = [];
+ if (page.connectorBindings) parts.push(`connectorBindings: ${list(page.connectorBindings)}`);
+ if (page.actionBindings) parts.push(`actionBindings: ${list(page.actionBindings)}`);
+ lines.push(` ${page.name}${page.key ? ` [${page.key}]` : ''} — ${parts.join('; ')}`);
+ }
+ }
+ if (report.notCarried && report.notCarried.length) {
+ lines.push(
+ `WARNING: ${report.notCarried.length} list(s) of connector or Custom API bindings are NOT in the spec, because the spec cannot state them as the page holds them: ${report.notCarried.map((n) => `${JSON.stringify(n.name)} (${n.reason})`).join('; ')}.`,
+ ' Rebuilding into THIS environment leaves such a page\'s bindings as they are. Rebuilding into a DIFFERENT environment will not carry them — bind them there with /genpage (genpage-upload.js --connectors / --actions).',
+ ' A spec states a binding only by the properties the references document, each with a value of a shape known to be safe, so a list holding anything else — a connection id, a credential, a property this plugin '
+ + 'does not know — is left out whole (the values are never printed). It is still in the page folder\'s own config.json (pages/<page id>/config.json), which is the page as this environment holds it and is not '
+ + 'rewritten: keep that folder out of version control, and do not share it, if a value there is a credential.',
+ );
+ }
+ return `${lines.join('\n')}\n`;
+}
+
// The page keys an earlier download of this app left in the output folder: { keys, conflicts, problem, unidentified }, read from the app-spec.json this
// download is about to replace (the working folder of an edit session holds it). A key is a page's identity in a rebuild — a copy of that spec deployed to
// another environment binds each key to the page it created there — so a page whose id is read again keeps the key it had, whatever it is called now or
@@ -1214,13 +1402,10 @@ const SPEC_TYPE_FROM_ATTRIBUTE_TYPE = {
BigInt: 'BigInt', Decimal: 'Decimal', Double: 'Double', File: 'File', Image: 'Image',
};
-// Types whose App Spec declaration REQUIRES a companion field this hydrator cannot supply: a
-// `Choice`/`MultiChoice` column must carry `options[]` or a `globalChoice` reference, and reading
-// those needs a per-column typed-metadata expand the download does not perform. (Verified to be the
-// ONLY such dependency: every other companion rule in `validateAppSpec` / `spec-lint` — Calculated/
-// Rollup's formula, Customer's description — is a warning, not an error. An AutoNumber column's
-// format IS an error there, and cannot arise here: an auto-number column is a String attribute, so it
-// is hydrated as Text, and no AutoNumber column or format is ever emitted.)
+// Types whose App Spec declaration REQUIRES detail beyond their type: a Choice/MultiChoice needs
+// options[] or a globalChoice reference. A failed typed expand cannot supply either. AutoNumber
+// also requires a mask, but is emitted only when the String cast positively supplies one; otherwise
+// its surviving String type remains Text and the missing-detail warning explains the loss.
//
// So the column is emitted WITHOUT a type rather than with one that makes the whole spec fail
// validation ("column X: Choice needs options[] or a globalChoice reference") — which is what
@@ -1390,15 +1575,16 @@ function optionSetFromRow(row) {
// would silently re-point existing data. Refusing to type the column is the honest outcome, and it
// falls through to the untyped warning that already exists for exactly this case.
if (labels.some((l) => descriptionFromDataverse(l) === undefined)) return null;
- return { ...(name ? { name } : {}), isGlobal: os.IsGlobal === true, options: labels };
+ const displayName = descriptionFromDataverse(os.DisplayName);
+ return { ...(name ? { name } : {}), ...(displayName !== undefined ? { displayName } : {}), isGlobal: os.IsGlobal === true, options: labels };
}
-// One INLINE Choice option's App Spec label. Localization is PRESERVED here — unlike a
-// `globalChoices[]` option, which must be a plain string — because `columns[].options[]` round-trips
-// an LCID map correctly. `labelFromDataverse` reads only `LocalizedLabels`, so a Label carrying just
+// Inline Choice options and alternate-key display names can preserve LCID maps, unlike a
+// `globalChoices[]` option, which must be a plain string.
+// `labelFromDataverse` reads only `LocalizedLabels`, so a Label carrying just
// a `UserLocalizedLabel` falls back to the single-string unwrap rather than emitting `undefined`,
// which would fail validation with "options[i] must be a non-empty string".
-function choiceOptionLabel(label) {
+function localizedSpecLabel(label) {
const localized = labelFromDataverse(label);
return localized !== undefined ? localized : descriptionFromDataverse(label);
}
@@ -1410,7 +1596,7 @@ async function readOptionSets(sdk, logical) {
const byLogical = new Map();
let failed = null;
for (const { cast, type } of OPTION_SET_CASTS) {
- const url = `/${metadataEntityPath(logical)}/Attributes/${cast}?$select=LogicalName&$expand=OptionSet($select=Name,IsGlobal,Options)`;
+ const url = `/${metadataEntityPath(logical)}/Attributes/${cast}?$select=LogicalName&$expand=OptionSet($select=Name,DisplayName,IsGlobal,Options)`;
try {
const res = await sdk.dataverse.get(url);
// `dataverse.get` RESOLVES on a non-2xx rather than throwing, so the status must be checked
@@ -1454,7 +1640,11 @@ function collectGlobalChoices(meta, into) {
if (!os || !os.isGlobal || !os.name) continue;
const key = String(os.name).toLowerCase();
if (into.has(key)) continue;
- into.set(key, { name: os.name, options: os.options.map((l) => descriptionFromDataverse(l)), existing: true });
+ into.set(key, {
+ name: os.name,
+ ...(os.displayName !== undefined ? { displayName: os.displayName } : {}),
+ options: os.options.map((l) => descriptionFromDataverse(l)), existing: true,
+ });
}
return into;
}
@@ -1678,7 +1868,7 @@ function untypedColumnNames(entities) {
// nothing shows they were not authored (`{ table, column, typeName }`), so the caller can name them (see the end of the filter).
// `incomplete`, when given, is filled with the File and Image columns written without detail an answered read should have carried
// (`{ table, column, type, missing }`, missingMediaDetail), so the caller can name those too.
-function entityFromMetadata(meta, logical, { unexpressible, incomplete } = {}) {
+function entityFromMetadata(meta, logical, { unexpressible, incomplete, schemaOmissions = [], languageCode } = {}) {
const primary = meta && (meta.primaryNameAttribute || meta.primaryNameLogicalName);
const attrs = Array.isArray(meta && meta.attributes) ? meta.attributes : (Array.isArray(meta && meta.Attributes) ? meta.Attributes : []);
const primaryLower = String(primary || '').toLowerCase();
@@ -1849,7 +2039,7 @@ function entityFromMetadata(meta, logical, { unexpressible, incomplete } = {}) {
// The shared `ambiguousChoiceAliases` is reused rather than reimplemented, so this screen and
// the validator can never disagree about what "ambiguous" means.
const inlineOptions = optionSet && !(optionSet.isGlobal && optionSet.name)
- ? optionSet.options.map(choiceOptionLabel)
+ ? optionSet.options.map(localizedSpecLabel)
: null;
const inlineIsAmbiguous = inlineOptions ? ambiguousChoiceAliases(inlineOptions).some((c) => c.hidden) : false;
const usableOptionSet = inlineIsAmbiguous ? null : optionSet;
@@ -1881,6 +2071,7 @@ function entityFromMetadata(meta, logical, { unexpressible, incomplete } = {}) {
...(columnDisplayName(a) !== undefined ? { displayName: columnDisplayName(a) } : {}),
...(specType ? { type: specType } : {}),
...choice,
+ ...columnOptionFields(a, specType),
// The size (and, for an image, the primary-image flag) the column was made with, where a rebuild needs it (mediaColumnFields).
...(specType === 'File' || specType === 'Image' ? mediaColumnFields(a, specType) : {}),
}, a && (a.description !== undefined ? a.description : a.Description));
@@ -1899,6 +2090,8 @@ function entityFromMetadata(meta, logical, { unexpressible, incomplete } = {}) {
const primaryLabel = columnDisplayName(primaryAttr);
const tableSchemaName = (meta && (meta.schemaName || meta.logicalName)) || logical;
const tableLabel = displayName !== undefined ? displayName : ((meta && meta.displayName) || logical);
+ const statusReasons = statusReasonsFromOptions(meta && meta.statusOptions, { customTable: !meta || meta.isCustomEntity !== false, languageCode, omitted: schemaOmissions });
+ const alternateKeys = alternateKeysFromMetadata(meta && meta.Keys, localizedSpecLabel, schemaOmissions);
return {
schemaName: tableSchemaName,
displayName: tableLabel,
@@ -1920,8 +2113,10 @@ function entityFromMetadata(meta, logical, { unexpressible, incomplete } = {}) {
...(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: primaryLabel !== undefined ? primaryLabel : 'Name' } : null,
+ primaryAttribute: primary ? { schemaName: primary, displayName: primaryLabel !== undefined ? primaryLabel : 'Name', ...primaryColumnOptionFields(primaryAttr) } : null,
columns,
+ ...(statusReasons.length ? { statusReasons } : {}),
+ ...(alternateKeys.length ? { alternateKeys } : {}),
// 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
// deleting a customer's table/data is unrecoverable while an orphaned table is not — so fail safe.
@@ -1952,7 +2147,7 @@ async function readEntityAuxMetadata(sdk, logical, concurrency) {
const tasks = [
async () => {
try {
- const res = await sdk.dataverse.get(`${entityPath}?$select=LogicalName,Description,DisplayName,DisplayCollectionName`);
+ const res = await sdk.dataverse.get(`${entityPath}?$select=LogicalName,Description,DisplayName,DisplayCollectionName,IconVectorName&$expand=Keys($select=SchemaName,DisplayName,KeyAttributes,IsManaged)`);
if (res && res.status >= 200 && res.status < 300 && res.body) {
return { kind: 'entityLabels', body: res.body };
}
@@ -1973,10 +2168,11 @@ async function readEntityAuxMetadata(sdk, logical, concurrency) {
},
async () => {
try {
- const res = await sdk.dataverse.get(`${entityPath}/Attributes/Microsoft.Dynamics.CRM.MoneyAttributeMetadata?$select=LogicalName,IsBaseCurrency`);
+ const res = await sdk.dataverse.get(`${entityPath}/Attributes/Microsoft.Dynamics.CRM.MoneyAttributeMetadata?$select=LogicalName,IsBaseCurrency,MinValue,MaxValue,Precision,PrecisionSource`);
if (res && res.status >= 200 && res.status < 300 && res.body && Array.isArray(res.body.value)) {
return {
kind: 'moneyFlags',
+ rows: res.body.value,
baseCurrency: new Set(res.body.value
.filter((r) => r && r.LogicalName && r.IsBaseCurrency === true)
.map((r) => String(r.LogicalName).toLowerCase())),
@@ -2030,6 +2226,8 @@ async function readEntityWithDescriptions(sdk, logical, { concurrency } = {}) {
meta.Description = entityLabels.body.Description;
meta.DisplayName = entityLabels.body.DisplayName;
meta.DisplayCollectionName = entityLabels.body.DisplayCollectionName;
+ meta.IconVectorName = entityLabels.body.IconVectorName;
+ meta.Keys = entityLabels.body.Keys;
} else if (entityLabels.failed) {
// 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.
@@ -2085,6 +2283,11 @@ async function readEntityWithDescriptions(sdk, logical, { concurrency } = {}) {
return moneyFlags.baseCurrency.has(key) ? { ...a, IsBaseCurrency: true } : a;
});
}
+ const moneyByName = new Map((moneyFlags.rows || []).filter((a) => a && a.LogicalName).map((a) => [attributeLogicalName(a), a]));
+ meta.attributes = (meta.attributes || []).map((a) => {
+ const row = moneyByName.get(attributeLogicalName(a));
+ return row ? { ...a, MinValue: row.MinValue, MaxValue: row.MaxValue, Precision: row.Precision, PrecisionSource: row.PrecisionSource } : a;
+ });
// Choice / MultiChoice option sets (#564). A SEPARATE read from the attribute one above, and it
// has to be: `OptionSet` can only be `$expand`ed through a type CAST, which the heterogeneous
// `Attributes` collection cannot carry (see OPTION_SET_CASTS). Without it every Choice column
@@ -2122,6 +2325,20 @@ async function readEntityWithDescriptions(sdk, logical, { concurrency } = {}) {
// checks each of its columns against, so an answer that lacks one is said too (missingMediaDetail).
if (Object.keys(media.answered).length) meta.mediaReadsAnswered = media.answered;
if (Object.keys(media.failed).length) meta.mediaReadFailures = media.failed;
+ const columnOptions = await readColumnOptions(sdk, logical, meta.attributes, concurrency);
+ meta.attributes = (meta.attributes || []).map((a) => {
+ const row = columnOptions.rows.get(attributeLogicalName(a));
+ return row ? { ...a, ...row } : a;
+ });
+ const statuses = await readStatusOptions(sdk.dataverse, logical);
+ if (statuses.options) meta.statusOptions = statuses.options;
+ meta.schemaReadFailures = [
+ ...columnOptions.failures,
+ ...(statuses.failed ? [`status reasons: ${statuses.failed}`] : []),
+ ...(entityLabels.failed ? [`alternate keys and table icon: ${entityLabels.failed}`] : []),
+ ...(entityLabels.body && !Array.isArray(meta.Keys) ? ['alternate keys: the response carried no Keys[] array'] : []),
+ ...(!moneyFlags.rows && (meta.attributes || []).some((a) => (a.attributeType || a.AttributeType) === 'Money') ? ['Money: the column detail read did not answer'] : []),
+ ];
return meta;
}
@@ -2256,11 +2473,12 @@ const IMAGE_WR_TYPES = new Set([5, 6, 7, 10, 11]);
// any path-derived WR (an unknown non-'new' prefix would BuildHalt on a fresh env) but we PROBE every
// customRef and surface each genuine CUSTOM (unmanaged image) one as `unresolved` — a managed/OOB/absent
// ref is a system icon present in every env, so it stays silent (no false alarm).
-async function iconWebResources(sdk, icons, customRefs, ownPrefix, prefixResolved, navRefs) {
+async function iconWebResources(sdk, icons, customRefs, ownPrefix, prefixResolved, navRefs, tableRefs) {
const out = [];
const seen = new Set(); // lowercased names actually re-declared into `out`
const prefixLc = ownPrefix ? String(ownPrefix).toLowerCase() + '_' : null;
- const customRefSet = new Set((customRefs || []).map((n) => String(n).toLowerCase()));
+ const tableRefSet = new Set((tableRefs || []).map((n) => String(n).toLowerCase()));
+ const customRefSet = new Set([...(customRefs || []), ...(tableRefs || [])].map((n) => String(n).toLowerCase()));
// `navRefs` are web resources a URL SUBAREA targets (the Site Map Designer's "custom page backed by
// an HTML web resource"), as opposed to an icon. They take the SAME safety gates as a path-derived
// icon — own prefix, unmanaged, has content, `external: true` so teardown never deletes it — but
@@ -2268,17 +2486,17 @@ async function iconWebResources(sdk, icons, customRefs, ownPrefix, prefixResolve
// design. Without this distinction the page is never re-declared and a rebuild's nav entry points
// at a resource the spec cannot recreate.
const navRefSet = new Set((navRefs || []).map((n) => String(n).toLowerCase()));
- const allowedTypeFor = (key) => (navRefSet.has(key) ? null : IMAGE_WR_TYPES); // null = any type
+ const allowedTypeFor = (key) => (navRefSet.has(key) ? null : tableRefSet.has(key) ? new Set([11]) : IMAGE_WR_TYPES); // null = any type
const candidateUnresolved = new Map(); // key -> original name; a path ref we could NOT re-declare in PASS 1
const queryWr = async (name) =>
- (await sdk.queryRecords('webresource', { select: ['name', 'webresourcetype', 'content', 'ismanaged'], filter: `name eq '${String(name).replace(/'/g, "''")}'`, top: 1 }))?.[0];
+ (await sdk.queryRecords('webresource', { select: ['name', 'displayname', 'webresourcetype', 'content', 'ismanaged'], filter: `name eq '${String(name).replace(/'/g, "''")}'`, top: 1 }))?.[0];
const isCustomImage = (wr) => !!(wr && wr.content && wr.ismanaged === false && IMAGE_WR_TYPES.has(wr.webresourcetype));
// PASS 1 — path-derived custom icons (safety-gated). Done FIRST so a name referenced BOTH by a platform
// path AND by a bare name is classified by the STRICTER path rules (and flagged `external`) before the
// lenient bare pass can re-declare it as deletable — otherwise the overlap silently loses teardown
// protection and a shared nav icon gets deleted.
- for (const name of [...(customRefs || []), ...(navRefs || [])]) {
+ for (const name of [...(customRefs || []), ...(navRefs || []), ...(tableRefs || [])]) {
const key = String(name).toLowerCase();
if (seen.has(key)) continue;
const ownScoped = !!prefixLc && key.startsWith(prefixLc);
@@ -2296,9 +2514,12 @@ async function iconWebResources(sdk, icons, customRefs, ownPrefix, prefixResolve
}
if (!wr || !wr.content) { candidateUnresolved.set(key, name); continue; } // own-prefix but absent on source → will dangle
const allowed = allowedTypeFor(key);
+ // A table's vector icon can be recreated only from an SVG this publisher owns. An absent
+ // management flag is unknown, not proof of an unmanaged resource safe to copy.
+ if (tableRefSet.has(key) && wr.ismanaged !== false) continue;
if (wr.ismanaged === true || (allowed && !allowed.has(wr.webresourcetype))) continue; // managed / wrong type → leave as a bare reference
seen.add(key);
- out.push({ name, type: WR_TYPE[wr.webresourcetype] || 'png', contentBase64: wr.content, external: true });
+ out.push({ name, ...(wr.displayname ? { displayName: wr.displayname } : {}), type: WR_TYPE[wr.webresourcetype] || 'png', contentBase64: wr.content, external: true });
} catch { candidateUnresolved.set(key, name); /* read failure → candidate (surface unless a bare pass resolves it) */ }
}
@@ -2309,11 +2530,13 @@ async function iconWebResources(sdk, icons, customRefs, ownPrefix, prefixResolve
for (const name of icons || []) {
const key = String(name).toLowerCase();
if (seen.has(key)) continue;
+ // A second navigation spelling must not turn a rejected table resource into a portable SVG.
+ if (tableRefSet.has(key)) continue;
try {
const wr = await queryWr(name);
if (!wr || !wr.content) continue;
seen.add(key);
- const entry = { name, type: WR_TYPE[wr.webresourcetype] || 'png', contentBase64: wr.content };
+ const entry = { name, ...(wr.displayname ? { displayName: wr.displayname } : {}), type: WR_TYPE[wr.webresourcetype] || 'png', contentBase64: wr.content };
if (customRefSet.has(key)) entry.external = true; // also path-referenced → protect from teardown
out.push(entry);
} catch { /* a bare author icon that fails to read is skipped (unchanged) */ }
@@ -2372,7 +2595,7 @@ async function recoverAppSolution(sdk, appId) {
const comps = await sdk.queryRecords('solutioncomponent', { select: ['_solutionid_value'], filter: `objectid eq ${appId}`, paginate: true });
const solIds = [...new Set((comps || []).map((c) => c && c._solutionid_value).filter(Boolean))];
if (!solIds.length) return null;
- const sols = await rowsByIds(sdk, 'solution', 'solutionid', solIds, ['solutionid', 'uniquename', 'ismanaged', 'description'], (r) => r);
+ const sols = await rowsByIds(sdk, 'solution', 'solutionid', solIds, ['solutionid', 'uniquename', 'friendlyname', 'ismanaged', 'description'], (r) => r);
// Sorted so the candidates — and everything derived from them — are order-independent.
real = sols
.filter((s) => s && s.ismanaged === false && !isRestrictedSolution(s.uniquename))
@@ -2395,7 +2618,10 @@ async function recoverAppSolution(sdk, appId) {
}
};
if (real.length === 1) {
- const out = withDescription({ uniqueName: real[0].uniquename }, real[0].description);
+ const out = withDescription({
+ uniqueName: real[0].uniquename,
+ ...(typeof real[0].friendlyname === 'string' && real[0].friendlyname.trim() ? { displayName: real[0].friendlyname } : {}),
+ }, real[0].description);
const prefix = await prefixOf(real[0]);
if (typeof prefix === 'string') out.publisherPrefix = prefix;
else if (prefix) out.publisherUnreadable = prefix.failed;
@@ -2481,23 +2707,20 @@ async function readSitemapPages(genpage, ids, concurrency) {
return { ok: true, pages: results.map(({ id, page }) => ({ pageId: String(id).toLowerCase(), files: pageFolderFiles(page) })) };
}
-async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy = false, resetPageKeys = false, concurrency }) {
+async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy = false, resetPageKeys = false, concurrency, languageCode }) {
concurrency = validatedDownloadConcurrency(concurrency);
// The caller named this directory. A link at its final component would make every page and
// the spec land outside it. Ancestors are the caller's choice and are not inspected.
assertSafeOutputDir(outDir);
- // `fetchArtifact('app')` FAILS CLOSED when the app's sitemap cannot be resolved, read, or proven to
- // still belong to this app (SDK code `APP_SITEMAP_UNRESOLVED`) — rather than returning an app whose
- // navigation is untrustworthy. That is a LOGICAL failure of exactly the class this function's
- // contract says it returns rather than throws (the sitemap IS the download's membership oracle), so
- // translate it instead of letting a raw SDK error escape. A newly created app is the common cause:
- // an unpublished appmodule is not readable, so the caller's fix is to publish it and retry.
+ // The sitemap is the download's membership oracle. An unresolved or shared identity is a logical
+ // refusal, not a partial app: return it before reading pages or writing output. Saved-only apps are
+ // readable when the SDK can prove their current layer and sitemap; publishing is not a blanket fix.
let app;
try {
app = await sdk.fetchArtifact('app', appId);
} catch (e) {
const code = e && e.code;
- if (code === 'APP_SITEMAP_UNRESOLVED' || code === 'APP_UPDATE_NO_ETAG') {
+ if (code === 'APP_SITEMAP_UNRESOLVED' || code === 'APP_SITEMAP_SHARED' || code === 'APP_UPDATE_NO_ETAG') {
return { ok: false, error: `cannot read app ${appId}: ${(e && e.message) || code}` };
}
throw e;
@@ -2535,6 +2758,8 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy
// Ids a download left in navigation calls instead of turning them back into PAGEREF_ tokens: see the reverse resolution below.
const navIdsLeft = [];
let manifest = null;
+ // What the pages' connector and Custom API bindings come to (pageBindingsReport): in the spec, and what a rebuild into another environment still cannot bring. Null when no page holds any.
+ let pageBindings = null;
if (smPages.length) {
// Durable manifest (stable key→id bindings + v2 semantics). Best-effort: a missing or corrupt
@@ -2617,7 +2842,8 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy
const unreadableConfigs = [];
const unkeptModels = [];
- pages = parseDownloadedPages(pagesRoot, outDir, nameById, unreadableConfigs, unkeptModels);
+ const unkeptBindings = [];
+ pages = parseDownloadedPages(pagesRoot, outDir, nameById, unreadableConfigs, unkeptModels, unkeptBindings);
// Reported, not gated: a page whose model is left out rebuilds exactly as every page did before the spec carried models — an
// update leaves the model the page already has as it is (the SDK writes only what a spec names), and a page the rebuild creates
// gets none.
@@ -2632,7 +2858,7 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy
if (!allowLossy) {
return { ok: false, error: `could not read config.json for page(s): ${detail} — their data-source bindings are unknown, so refusing to write a spec that would silently rebuild them unbound. Re-run with --allow-lossy-download to accept the loss.` };
}
- process.stderr.write(`WARNING: ${unreadableConfigs.length} page config(s) unreadable; their data-source bindings are DROPPED: ${detail}\n`);
+ process.stderr.write(`WARNING: ${unreadableConfigs.length} page config(s) unreadable; their data-source bindings are DROPPED, and their connector and Custom API bindings are not in the spec either (a rebuild into this environment leaves those as they are): ${detail}\n`);
}
// Bidirectional exact equality: sitemap ids ↔ downloaded ids. A gap either way means the download
@@ -2688,6 +2914,11 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy
process.stderr.write(`WARNING: ${navIdsLeft.length} page id(s) of this app remain in the downloaded page source instead of PAGEREF_ tokens (${navIdsLeft.map((l) => `page "${l.page}" line ${l.line}, column ${l.column}: ${why(l)}`).join('; ')}) — a navigation call that keeps one is a hardcoded page id, which a rebuild refuses: write it as a double-quoted "PAGEREF_<key>" literal in a navigateTo call whose options object is written inline, before any construct this check reads by guess, then rebuild. An id that is data — a record id, text, a comment — can stay.\n`);
}
+ // The connector and Custom API bindings the pages hold. The spec states them (parseDownloadedPages), so a rebuild writes them back; what it cannot do in another environment is said here — and in the result — rather
+ // than left for the first call through a binding that cannot resolve. Silent when no page holds one.
+ pageBindings = pageBindingsReport(pages, unkeptBindings);
+ if (pageBindings) process.stderr.write(pageBindingsNote(pageBindings));
+
// Warn about manifest pages no longer in the sitemap (Maker-deleted in the live app). The
// rebuilt spec drops these pages; the warning mirrors the droppedSubareaCount WARNING below.
const liveSet = new Set(sitemapIds.map((id) => String(id).toLowerCase()));
@@ -2744,10 +2975,13 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy
// Shared option sets bound by a downloaded column, keyed by lower-cased name so a set used by
// several tables is declared once.
const globalChoiceDecls = new Map();
+ const tableVectorIcons = new Map();
+ const schemaReadFailures = new Map();
for (const logical of allLogicals) {
let e;
const leftOut = [];
const shortOf = [];
+ const schemaOmissions = [];
// A metadata READ failure is not the same as metadata that reports no primary name, and it must
// not be swallowed: a 429/503 on a sitemap table used to drop it silently, leaving its subarea
// behind so validation later complained about a "sitemap subArea references unknown entity" —
@@ -2760,7 +2994,10 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy
if (meta && meta.optionSetReadFailed) optionSetReadFailures.set(logical, meta.optionSetReadFailed);
for (const [type, reason] of Object.entries((meta && meta.mediaReadFailures) || {})) if (mediaReadFailures[type]) mediaReadFailures[type].set(logical, reason);
collectGlobalChoices(meta, globalChoiceDecls);
- e = entityFromMetadata(meta, logical, { unexpressible: leftOut, incomplete: shortOf });
+ e = entityFromMetadata(meta, logical, { unexpressible: leftOut, incomplete: shortOf, schemaOmissions, languageCode });
+ if (meta && typeof meta.IconVectorName === 'string' && meta.IconVectorName.trim()) tableVectorIcons.set(logical, meta.IconVectorName);
+ const missingSchema = [...((meta && meta.schemaReadFailures) || []), ...schemaOmissions];
+ if (missingSchema.length) schemaReadFailures.set(logical, missingSchema.join('; '));
} catch (err) {
metadataErrors.set(logical, (err && err.message) || String(err));
(sitemapSet.has(logical) ? noPrimaryName : droppedComponents).push(logical);
@@ -2805,6 +3042,9 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy
// read failing says nothing about the table. Not a gate: an English-only spec is still a usable spec, and failing a read-only
// command over it would be worse.
const failureDetail = (failures) => [...failures.entries()].sort(([a], [b]) => compareText(a, b)).map(([l, r]) => `${l} (${r})`).join(', ');
+ if (schemaReadFailures.size) {
+ process.stderr.write(`WARNING: some portable schema detail could not be captured (${failureDetail(schemaReadFailures)}). The table and its typed columns are kept, but rebuilding into a FRESH environment uses the build defaults for missing column options and cannot recreate missing status reasons, alternate keys or table icons. Re-run the download to recover unreadable detail, and resolve the stated build limits before a cross-environment rebuild.\n`);
+ }
if (tableLabelReadFailures.size) {
// The table's plural is carried by this read alone (download keeps one a rebuild would not derive), so it goes with it.
process.stderr.write(`WARNING: the table label read failed for ${tableLabelReadFailures.size} table(s) (${failureDetail(tableLabelReadFailures)}). Their display names and descriptions fall back to ONE language and their plurals are not written, so rebuilding into a FRESH environment would recreate each of those tables labelled in one language, with the plural '<display name>s'. Re-run the download to recover them before a cross-environment rebuild.\n`);
@@ -2916,6 +3156,7 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy
const trustedPrefix = solutionPrefix || (prefixUnknown ? null : appDerivedPrefix);
const solution = { uniqueName: 'Default', publisherPrefix: trustedPrefix || 'new', prefixResolved: !!trustedPrefix };
if (recovered && recovered.uniqueName) solution.uniqueName = recovered.uniqueName;
+ if (recovered && recovered.displayName) solution.displayName = recovered.displayName;
// `recoverAppSolution` already unwraps the solution's description; carry it across. This object is
// built fresh (rather than spread from `recovered`) so an unrecovered solution still gets its
// required defaults, which is why each field has to be copied deliberately — a field added to
@@ -2929,14 +3170,28 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy
// publisher (`solution.publisherPrefix`). A FOREIGN-prefix / OOB reference is left as a bare reference:
// re-declaring it would make the build try to createWebResource under an unregistered prefix on a fresh
// env → a hard BuildHalt, turning a cosmetic broken icon into a failed build.
- const { webResources, unresolved: unresolvedIcons } = await iconWebResources(sdk, icons, customRefs, solution.publisherPrefix, solution.prefixResolved, navRefs);
- if (unresolvedIcons && unresolvedIcons.length) {
+ // A table icon is shared metadata, not proof this app created the resource. Reuse the
+ // own-prefix/unmanaged gates of path-referenced navigation icons and their teardown protection.
+ const tableIconNames = entities.map((e) => tableVectorIcons.get(e.schemaName.toLowerCase())).filter(Boolean);
+ const { webResources, unresolved: unresolvedIcons } = await iconWebResources(sdk, icons, customRefs, solution.publisherPrefix, solution.prefixResolved, navRefs, tableIconNames);
+ const svgByName = new Map(webResources.filter((wr) => wr.type === 'svg').map((wr) => [wr.name.toLowerCase(), wr.name]));
+ for (const entity of entities) {
+ const name = tableVectorIcons.get(entity.schemaName.toLowerCase());
+ if (name && svgByName.has(name.toLowerCase())) entity.vectorIcon = svgByName.get(name.toLowerCase());
+ }
+ const navigationRefs = new Set([...icons, ...customRefs, ...navRefs].map((name) => String(name).toLowerCase()));
+ const unresolvedNavIcons = unresolvedIcons.filter((name) => navigationRefs.has(String(name).toLowerCase()));
+ const unresolvedTableIcons = unresolvedIcons.filter((name) => !navigationRefs.has(String(name).toLowerCase()));
+ if (unresolvedNavIcons.length) {
// A custom nav icon we couldn't safely round-trip: either an own-prefix WR that's absent on the source
// env / failed to read, OR (when the publisher prefix couldn't be verified) any custom image icon we
// can't classify as own-vs-foreign. Its sitemap reference round-trips but the WR isn't re-declared, so
// the icon will dangle on a rebuild into a fresh env. Surface it now (the build-time portability
// warning is the backstop). Without this, an unverified-prefix download would silently drop the icon.
- process.stderr.write(`WARNING: ${unresolvedIcons.length} custom nav-icon web resource(s) could not be captured (${unresolvedIcons.join(', ')}) — their sitemap reference is kept, but declare the web resource(s) in webResources[] if you rebuild into a fresh environment, or the icon will be missing there.\n`);
+ process.stderr.write(`WARNING: ${unresolvedNavIcons.length} custom nav-icon web resource(s) could not be captured (${unresolvedNavIcons.join(', ')}) — their sitemap reference is kept, but declare the web resource(s) in webResources[] if you rebuild into a fresh environment, or the icon will be missing there.\n`);
+ }
+ if (unresolvedTableIcons.length) {
+ process.stderr.write(`WARNING: ${unresolvedTableIcons.length} table-icon web resource(s) could not be captured (${unresolvedTableIcons.join(', ')}) — their vectorIcon references are omitted. Rebuilding here keeps the existing icons, but declare the SVG resources and table vectorIcon fields before rebuilding into a fresh environment.\n`);
}
// Dashboards (declared as DashBoard sitemap subareas) — reconstructed with id-passthrough tiles.
@@ -3056,7 +3311,7 @@ async function runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy
if (relationshipsSkipped.length) process.stderr.write(relationshipsSkippedWarning(relationshipsSkipped));
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, notRoundTripped, relationships, relationshipsSkipped, ...(navIdsLeft.length ? { navIdsLeft } : {}), ...(solutionCandidates ? { solutionCandidates } : {}) };
+ return { ok: true, spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped, relationships, relationshipsSkipped, ...(navIdsLeft.length ? { navIdsLeft } : {}), ...(pageBindings ? { pageBindings } : {}), ...(solutionCandidates ? { solutionCandidates } : {}) };
}
async function main(deps = {}) {
@@ -3175,12 +3430,12 @@ async function main(deps = {}) {
// The page backend reads through the download's own throwaway SDK, lent to it: nothing of its own to make or remove.
const genpage = io.makeGenpageSdk(env, { sdk });
- const result = await io.runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy: allowLossyDownload, resetPageKeys });
+ const result = await io.runDownload({ sdk, genpage, outDir, appId, appUnique, allowLossy: allowLossyDownload, resetPageKeys, languageCode: session.languageCode });
// The run's last writes: these lines, then the result and the exit, with no turn of the event loop between them — made blocking (lib/output-redaction.js).
makeWritesBlocking(process.stdout, io.stderr);
if (!result.ok) { finish(false, result); return; }
- const { spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped, solutionCandidates, navIdsLeft } = result;
+ const { spec, pages, entities, webResources, droppedSubareas, droppedSubareaDetails, dashboardReconstructionError, dashboardWarnings, notRoundTripped, solutionCandidates, navIdsLeft, pageBindings } = result;
if (droppedSubareas > 0 || dashboardReconstructionError) {
const droppedList = (droppedSubareaDetails || [])
.map((d) => `${d.type}${d.id ? `:${d.id}` : ''}${d.title ? ` (${d.title})` : ''}`)
@@ -3239,7 +3494,7 @@ async function main(deps = {}) {
}
// Each optional field is in the result only when it has something to say. `navIdsLeft` is absent in the usual case (runDownload leaves it out when no id is
// left) and could be an empty list from another producer, so it is checked for both: an empty list is no finding.
- finish(true, { ok: true, spec: specPath, pages: pages.length, entities: entities.length, webResources: webResources.length, droppedSubareas, ...(notRoundTripped ? { notRoundTripped } : {}), ...(defaulted.length ? { directEntryDefaulted: defaulted } : {}), ...(navIdsLeft && navIdsLeft.length ? { navIdsLeft } : {}), ...(solutionCandidates ? { solutionCandidates } : {}) });
+ finish(true, { ok: true, spec: specPath, pages: pages.length, entities: entities.length, webResources: webResources.length, droppedSubareas, ...(notRoundTripped ? { notRoundTripped } : {}), ...(defaulted.length ? { directEntryDefaulted: defaulted } : {}), ...(navIdsLeft && navIdsLeft.length ? { navIdsLeft } : {}), ...(pageBindings ? { pageBindings } : {}), ...(solutionCandidates ? { solutionCandidates } : {}) });
} finally {
try { if (session) session.cleanup(); } catch { /* best-effort: the result below matters more */ }
if (outcome) io.emitResult(...outcome);
@@ -3307,4 +3562,4 @@ if (require.main === module) {
main().catch((err) => emitResult(false, err));
}
-module.exports = { untypedColumnNames, collectGlobalChoices, finalizeGlobalChoices, roundTrippedAware, isRoleRestrictedFormXml, notRoundTrippedSummary, notRoundTrippedWarning, relationshipsSkippedWarning, labelFromDataverse, columnDisplayName, resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, readPreviousPageKeys, assignPageKeys, missingDownloads, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, readAppShellSettings, iconWebResources, readDashboards, readRelationships, droppedSubareaCount, recoverAppSolution, runDownload, preserveAuthoredLanguageCode, makeDownloadSdk, compareText, main };
+module.exports = { untypedColumnNames, collectGlobalChoices, finalizeGlobalChoices, roundTrippedAware, isRoleRestrictedFormXml, notRoundTrippedSummary, notRoundTrippedWarning, relationshipsSkippedWarning, labelFromDataverse, columnDisplayName, resolveAppId, collectSitemap, appComponentEntities, parseDownloadedPages, pageBindingsReport, pageBindingsNote, readPreviousPageKeys, assignPageKeys, missingDownloads, entityFromMetadata, readEntityWithDescriptions, readDescriptionInventory, readAppShellSettings, iconWebResources, readDashboards, readRelationships, droppedSubareaCount, recoverAppSolution, runDownload, preserveAuthoredLanguageCode, makeDownloadSdk, compareText, main };
diff --git a/plugins/model-apps/scripts/lib/app-access.js b/plugins/model-apps/scripts/lib/app-access.js
index b8af8514b..f16d65236 100644
--- a/plugins/model-apps/scripts/lib/app-access.js
+++ b/plugins/model-apps/scripts/lib/app-access.js
@@ -17,7 +17,7 @@
// PURE: no I/O. The lint (spec-lint.js), the design document (app-spec-doc.js) and its warnings (write-app-spec-doc.js) all read the spec through here,
// so they cannot disagree about which tables nothing grants, or which marks say an app already exists. The environment's side — the roles an app
// has — is read by lib/app-roles.js and arrives here as `appAccess`.
-const { canonicalPersonaName } = require('./app-spec.js');
+const { canonicalPersonaName, roleGrantEntryLabel, roleGrantIdentityErrors } = require('./app-spec.js');
// Every collection read here is shape-guarded: the lint and the document run on specs still being typed, and a crash kills the authoring flow.
const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
@@ -100,6 +100,24 @@ function uncoveredTables(spec) {
});
}
+/**
+ * The roleGrants[] entries the build refuses because they do not name exactly one role — `role` and `roleId` both, neither, or one of them
+ * malformed — each with the gate's own messages (app-spec.js roleGrantIdentityErrors, which validateRoleGrants reports and lint-app-spec.js
+ * prints as `schema:` errors), labelled by the entry's index as written:
+ * [ { index, messages: ["roleGrants[1] (role \"Viewer\"): set either 'role' … or 'roleId' …, not both — …"] } ]
+ * The document shows these instead of the entry's privileges, and does not match them against the roles of the app.
+ * @returns {{ index: number, messages: string[] }[]}
+ */
+function roleGrantRefusals(spec) {
+ const out = [];
+ arr(isObject(spec) ? spec.roleGrants : []).forEach((g, index) => {
+ if (!isObject(g)) return;
+ const messages = roleGrantIdentityErrors(g, roleGrantEntryLabel(g, index));
+ if (messages.length) out.push({ index, messages });
+ });
+ return out;
+}
+
// --- the personas' share of who can open the app ----------------------------------------------------------------------------------------------
/**
@@ -225,7 +243,10 @@ function appAccessModel(spec, appAccess) {
const named = arr(s.personas).filter(isObject)
.map((p) => ({ name: canonicalPersonaName(p), getsApp: p.appAccess !== false }))
.filter((p) => filled(p.name));
- const wanted = arr(s.roleGrants).filter(isObject).map((g) => {
+ // An entry the build refuses names no role it would extend (roleGrantRefusals), so it is matched to none of the app's.
+ const refused = new Set(roleGrantRefusals(s).map((r) => r.index));
+ const wanted = arr(s.roleGrants).map((g, index) => {
+ if (!isObject(g) || refused.has(index)) return null;
if (filled(g.roleId)) return { by: 'id', key: lc(g.roleId.trim()), label: g.roleId.trim() };
if (filled(g.role)) return { by: 'name', key: lc(g.role.trim()), label: g.role.trim() };
return null;
@@ -256,6 +277,7 @@ module.exports = {
introducedTables,
tablePrivileges,
uncoveredTables,
+ roleGrantRefusals,
personaAppAccess,
rolesOfPersonas,
appAccessCondition,
diff --git a/plugins/model-apps/scripts/lib/app-components.js b/plugins/model-apps/scripts/lib/app-components.js
index b368d961a..aa728853b 100644
--- a/plugins/model-apps/scripts/lib/app-components.js
+++ b/plugins/model-apps/scripts/lib/app-components.js
@@ -6,6 +6,7 @@
// references; its cached fetchEntityMetadata projection cannot supply these membership reads.
// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/appmodulecomponent
const { odataLit } = require('./odata.js');
+const { postPublishXml } = require('./publish-xml.js');
const { dashboardNameKey, FORM_GUID_RE, formIdentityKey, compareVersions, isPluginVersion, APP_MEMBERSHIP_MIN_VERSION } = require('./app-spec.js');
const { isMainForm } = require('./form-order.js');
const { compareText } = require('./compare-text.js');
@@ -254,14 +255,13 @@ async function pinAppTables(client, appId, logicalNames, { refs: resolvedRefs }
return { added, already };
}
-async function publishAppComponents(client, appId) {
+async function publishAppComponents(client, appId, { sleep } = {}) {
const id = requireGuid(appId, 'app id');
// A fresh SDK create already publishes before the plugin can pin hidden tables. Publish that
// newly proven layer too, even without --publish, or a page-less create leaves its pins pending.
+ // Sent once but for a deadlock victim (postPublishXml): a refusal halts here, as it came.
// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/publishxml
- const response = await client.post('/PublishXml', {
- ParameterXml: `<importexportxml><appmodules><appmodule>${id}</appmodule></appmodules></importexportxml>`,
- });
+ const response = await postPublishXml(client, `<importexportxml><appmodules><appmodule>${id}</appmodule></appmodules></importexportxml>`, { sleep });
if (!response || response.status < 200 || response.status >= 300) {
throw componentError('APP_TABLES_NOT_PUBLISHED', `app '${id}' tables were pinned but publishing returned HTTP ${response && response.status}; re-run the build`, response && response.status);
}
diff --git a/plugins/model-apps/scripts/lib/app-navigation.js b/plugins/model-apps/scripts/lib/app-navigation.js
index 5d633aa25..4923af9af 100644
--- a/plugins/model-apps/scripts/lib/app-navigation.js
+++ b/plugins/model-apps/scripts/lib/app-navigation.js
@@ -20,6 +20,14 @@
// published sitemap then holding no SubArea at all. So an empty navigation is refused where the platform refuses
// it, for a new app, and only said so for an app that exists, which is left with no entries (`warn`).
//
+// A NEW app whose navigation holds ONLY page entries is not refused by a build that can create its pages FIRST: one that has the
+// pages phase, and is not a changed-only re-upload, for a spec whose page entries all name pages it builds. Such a build leaves the
+// app's create to the end of the pages phase and makes the app with the pages already in its first navigation (sdk-build.js
+// `createAppWithPages`), so the sitemap it creates is not empty. That is the order `apps.js create --page-id` has always used — a page
+// made with no app, then the app around it, through the same SDK create and the same sub-area (genpage-subarea.js) — and that order
+// was live-verified. Any other run creates the app before its pages, and is still refused (`newAppPagesFirst` false; `whyNotPagesFirst`
+// says why).
+//
// The spec models no IsVisible children, so none are ignored here. A spec whose navigation is only pages, or is
// `areas: []`, or has an area with no group, or a group with no entry, is still VALID — validateAppSpec accepts
// a spec with no appShell at all, which data-only builds and downloaded specs rely on — so such a build of a new
@@ -64,27 +72,39 @@ function navigationHolds(spec) {
return holds;
}
+// Whether the navigation holds entries and every one of them is a page — the one navigation a NEW app is built from only by
+// creating its pages first (the app step decides that from this and from the run's shape: sdk-build.js, `createAppWithPages`).
+const onlyPages = (holds) => holds.declared && holds.entries > 0 && holds.entries === holds.pages.length;
+function navigationIsPagesOnly(spec) {
+ return onlyPages(navigationHolds(spec));
+}
+
// What a navigation that cannot build a NEW app holds, why that stops one, and what to add. `held` is the first of the
-// three on its own, for the warning an app that exists gets.
-function navigationAdvice(holds) {
+// three on its own, for the warning an app that exists gets. `pagesFirst` is whether the run creates a new app's pages
+// before the app (navigationVerdict's `newAppPagesFirst`): an entry for one of the spec's pages is then one the app's first
+// navigation holds, so the advice offers it. `whyNotPagesFirst` is why a run does not, for a navigation of pages only.
+function navigationAdvice(holds, { pagesFirst = false, whyNotPagesFirst } = {}) {
+ const orPage = pagesFirst ? ", or an entry for one of the spec's pages (a build that has the pages phase creates a new app's pages before the app)" : '';
+ const notAPage = pagesFirst ? '' : ' A new app needs one entry that is not a page, since a page entry joins the navigation only once its page exists.';
if (!holds.declared) {
// `appDef` throws on a spec with no appShell.areas before it asks whether the app exists, so no app, new or not, is built from it.
return {
kind: 'undeclared',
held: 'the spec has no appShell.areas',
problem: 'the spec has no appShell.areas, so there is no navigation to build the app with.',
- fix: `Add appShell.areas with a group holding an entry — for example ${ENTRY_EXAMPLE} in appShell.areas[].groups[].subAreas. A new app needs one entry that is not a page, since a page entry joins the navigation only once its page exists.`,
+ fix: `Add appShell.areas with a group holding an entry — for example ${ENTRY_EXAMPLE} in appShell.areas[].groups[].subAreas${orPage}.${notAPage}`,
};
}
if (holds.entries > 0) {
+ // Reached only for a run that does NOT create a new app's pages first (navigationVerdict): one that does builds a navigation of pages only.
const shown = holds.pages.slice(0, 5).map((page) => `'${page}'`).join(', ');
const more = holds.pages.length > 5 ? ` and ${holds.pages.length - 5} more` : '';
const held = `the navigation holds only page entries (${shown}${more})`;
return {
kind: 'pages-only',
held,
- problem: `${held}. A page entry joins the navigation only once its page exists, so a new app is created without them, and ${PLATFORM_REFUSAL}.`,
- fix: `A new app needs one entry that is not a page: add one to a group — for example ${ENTRY_EXAMPLE}; a dashboard or url entry works too — and keep the page entries beside it.`,
+ problem: `${held}. A page entry joins the navigation only once its page exists, and ${whyNotPagesFirst || 'this run does not create the pages before the app'}, so a new app would be created without them, and ${PLATFORM_REFUSAL}.`,
+ fix: `A build that has the pages phase creates such an app after its pages, with them in its first navigation: run the whole build, with every page the navigation names implemented. Or give a group one entry that is not a page — for example ${ENTRY_EXAMPLE}; a dashboard or url entry works too — and keep the page entries beside it.`,
};
}
const what = holds.areas === 0 ? 'appShell.areas is empty'
@@ -95,7 +115,7 @@ function navigationAdvice(holds) {
kind: 'empty',
held,
problem: `${held}, and ${PLATFORM_REFUSAL}.`,
- fix: `Give an area a group with an entry — for example ${ENTRY_EXAMPLE} in appShell.areas[].groups[].subAreas. A new app needs one entry that is not a page, since a page entry joins the navigation only once its page exists.`,
+ fix: `Give an area a group with an entry — for example ${ENTRY_EXAMPLE} in appShell.areas[].groups[].subAreas${orPage}.${notAPage}`,
};
}
@@ -111,27 +131,39 @@ function navigationAdvice(holds) {
// existingAppIsWritten whether this run writes the spec's navigation to an app that already exists (sdk-build.js
// existingAppSitemapIsWritten); a run that writes none asks nothing of the spec for such an app
// whyUnknown what stopped the caller reading it, for the `unknown` message
+// newAppPagesFirst whether this run creates a NEW app's pages before the app, so that the app's first navigation holds
+// its page entries (sdk-build.js pagesFirstRule: the app step and the pages phase, not a changed-only
+// re-upload, and every page entry naming a page the run builds). lint-app-spec speaks of the build
+// `--apply` runs, which does. Absent is false: the stricter rule.
+// whyNotPagesFirst why it does not, for the refusal of a navigation of pages only
//
// the navigation holds NEW app (its first push EXISTING app (its sitemap existence
// creates the sitemap) is updated) UNKNOWN
// an entry that is not a page ok ok ok
-// entries, every one a page refuse ok unknown
+// entries, every one a page, and
+// the run creates the pages first ok ok ok
+// a run that does not refuse ok unknown
// no entry at all refuse warn (ok if this run writes unknown
// no navigation to it)
// no appShell.areas refuse refuse refuse
//
// Why they differ:
-// NEW app one entry that is not a page. Its first navigation leaves the pages out, so that is all it holds, and
-// Dataverse refuses to CREATE a sitemap with no entry (the HTTP 400 quoted above).
+// NEW app an entry its first push holds, since that push creates the sitemap and Dataverse refuses to CREATE one with
+// no entry (the HTTP 400 quoted above). A run that creates the pages first creates the app after them, so its
+// first push holds the page entries; any other run creates the app before its pages and leaves them out, so it
+// needs one entry that is not a page.
// EXISTING app its navigation is written from the whole spec once the pages exist (the pages phase's finalizer), so a
// page entry counts, and Dataverse accepts an empty navigation when a sitemap is UPDATED (measured, above):
// the build goes on, with a warning that the app is left with no entries. A run that writes no navigation
// to it asks nothing of the spec.
// no appShell.areas refused for every app: `appDef` throws on it before it asks whether the app exists.
-function navigationVerdict(spec, { appExists, existingAppIsWritten = true, whyUnknown } = {}) {
+function navigationVerdict(spec, { appExists, existingAppIsWritten = true, whyUnknown, newAppPagesFirst = false, whyNotPagesFirst } = {}) {
const holds = navigationHolds(spec);
if (holds.declared && holds.entries > holds.pages.length) return { outcome: 'ok' };
- const advice = navigationAdvice(holds);
+ // Pages only, in a run that creates a new app's pages first: a new app is created with them, and an app that exists takes them as it
+ // always did — so the answer is the same whichever this is, and whether or not that could be read.
+ if (newAppPagesFirst && onlyPages(holds)) return { outcome: 'ok' };
+ const advice = navigationAdvice(holds, { pagesFirst: newAppPagesFirst, whyNotPagesFirst });
if (appExists === false || advice.kind === 'undeclared') {
return { outcome: 'refuse', kind: advice.kind, code: NAVIGATION_REFUSAL_CODE, message: `${advice.problem} ${advice.fix}` };
}
@@ -154,4 +186,4 @@ function navigationVerdict(spec, { appExists, existingAppIsWritten = true, whyUn
};
}
-module.exports = { NAVIGATION_REFUSAL_CODE, navigationEntryKind, navigationHolds, navigationVerdict };
+module.exports = { NAVIGATION_REFUSAL_CODE, navigationEntryKind, navigationHolds, navigationIsPagesOnly, navigationVerdict };
diff --git a/plugins/model-apps/scripts/lib/app-sitemap-dangling.js b/plugins/model-apps/scripts/lib/app-sitemap-dangling.js
new file mode 100644
index 000000000..306e0978b
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/app-sitemap-dangling.js
@@ -0,0 +1,244 @@
+'use strict';
+// The teardown of a published app whose SiteMap component names a sitemap that no longer exists: proving that sitemap gone, then deleting the app alone.
+//
+// WHY. An app is two rows, the appmodule and its sitemap, and the bundled SDK deletes them together (one change set) once it has resolved the sitemap
+// from the app's current layer: an app deleted on its own while its sitemap exists strands that row and keeps its unique name taken for good
+// (AGENTS.md, "An app is TWO rows"). When the sitemap row is gone, that resolution cannot finish and the SDK refuses. Refusing is right while it
+// cannot tell, but the row can be gone for good: before 2.18.0, the teardown of one app deleted a sitemap that another app shared, and — measured
+// live — the other app's SiteMap component outlives the row it names. 2.17.0's delete looked an app's sitemap up by the app's unique name and, when
+// no sitemap had that name, deleted such an app alone; the component-aware delete of the 2.18.0 SDK refuses it on every run, and its "Retry." can never get past that.
+//
+// SCOPE. This is the app step of a teardown. A teardown that stops before it never gets here: an app with live generative pages has them proven from
+// its navigation first (sdk-teardown.js, the pages' resolve), and with that navigation gone the proof stops the teardown, as it always did — the maker
+// deletes such an app in Power Apps, then runs the teardown again. So is an app that was never published refused here (step 0 below).
+//
+// THE SDK'S REFUSAL, the one this module acts on (the vendored bundle's app delete: deleteAppCascade, and the sitemap resolution it starts with):
+// SdkError {
+// code: "APP_SITEMAP_UNRESOLVED",
+// message: "Refusing to delete app '9e9aabc1-e978-4322-a0ad-f1c16d5b90ab': sitemap 'a8252d00-b5c5-4026-bfbf-090a7001cff5' was not returned by the
+// unpublished-aware read. Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique
+// name forever. Retry."
+// }
+// The SDK raises it when it found ONE SiteMap component on the app's current layer, and its read of that sitemap in the saved layer
+// GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapnameunique,sitemapxml&$filter=sitemapid eq <id>&$top=1
+// answered no row — or an answer with no list in it, which it does not tell apart. It raises the same code for every other way that resolution fails (a
+// layer or a component it cannot read, two components, a link that changes while it reads, a renamed or malformed row), and nothing in the error
+// says which, so the SENTENCE is matched: anchored on the SDK's own fixed words, both ids GUIDs, and the app the one being deleted. Every other
+// refusal stays exactly as the SDK words it. The match only CHOOSES this path; nothing is deleted on the SDK's word. What decides is the proof below,
+// made with reads of this module's own. An SDK that words the refusal otherwise leaves teardown refusing as before
+// (tests/teardown-dangling-sitemap-real-bundle.test.js has the real bundle raise it, word for word).
+//
+// THE PROOF. Every read is strict: an answer that is refused, is no list, or pages wrongly is "not proven", never "absent" (app-components.js
+// collectionRows).
+// 0. FIRST, the app's row version, from its read by id. Everything after it is proven of the app AT this version, and the delete is conditioned on
+// it: a repair, a relink or a publish of the app while the proof runs moves the version, and the platform then refuses the delete (412), which is
+// a final refusal here. A version read after the proof would carry such a change in with it — the delete would then act on an app nothing proved.
+// (The 2.17.0 SDK's own app delete reads the app's version first, for the same reason.)
+// 1. the link: the app's current layer, and exactly one SiteMap component on it, naming the sitemap the SDK named;
+// 2. that sitemap, by its id, in the PUBLISHED layer (a plain read of the collection) and in the SAVED layer (RetrieveUnpublishedMultiple): no row
+// in either;
+// 3. no OTHER app's current layer names it — the rule the SDK applies before it deletes a sitemap that two apps use (APP_SITEMAP_SHARED);
+// 4. the link again, unchanged: a relink while this module reads is caught, as the SDK's own second read of the link catches one.
+// Then ONE write: DELETE /appmodules(<id>) with If-Match on the version of step 0 — the app alone. No sitemap is written or deleted. Then the app is
+// read in both layers again: it is gone, or the step fails. Anything else refuses and says what was found and what the maker can do; a refusal is final
+// (retry-policy.js `refusal`: `transient: false`) and does not ask for a retry, which could not change what was found.
+// What the version cannot see: a change of OTHER rows after the last read — another app adding a pin to the sitemap, a sitemap of that id made
+// again — moves no version of this app. That is the snapshot the SDK's own reverse-owner check is ("not a cross-app lock").
+//
+// FAIL CLOSED. Every error that leaves this path is marked `failClosed` (sdk-teardown.js passes such an error on before any of deleteStep's
+// shortcuts): its words can be the maker's — the app's display name — or the platform's ("Resource not found …"), and read as words they could pass
+// for a row that is already gone or an artifact that cannot be deleted, and let the steps that depend on a live app run.
+// See https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/retrieveunpublishedmultiple
+// and https://learn.microsoft.com/power-apps/developer/data-platform/webapi/perform-conditional-operations-using-web-api#apply-optimistic-concurrency
+const { collectionRows, currentAppLayer, appComponentRows } = require('./app-components.js');
+const { FORM_GUID_RE } = require('./app-spec.js');
+const { refusal, serviceFailure } = require('./retry-policy.js');
+
+// componenttype 62 is a site map: https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/appmodulecomponent
+const SITEMAP_COMPONENT = 62;
+const GUID = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}';
+const SITEMAP_GONE_REFUSAL = new RegExp(`^Refusing to delete app '(${GUID})': sitemap '(${GUID})' was not returned by the unpublished-aware read\\. `);
+const guidKey = (id) => String(id || '').replace(/^\{|\}$/g, '').toLowerCase();
+const reasonOf = (error) => String((error && error.message) || error || 'read failed');
+
+// The sitemap the SDK could not find when it refused to delete the app `appId` ({ sitemapId }), or null for any other failure — see the header.
+function danglingSitemapOf(error, appId) {
+ if (!error || error.code !== 'APP_SITEMAP_UNRESOLVED' || typeof error.message !== 'string') return null;
+ const named = SITEMAP_GONE_REFUSAL.exec(error.message);
+ if (!named || guidKey(named[1]) !== guidKey(appId)) return null;
+ return { sitemapId: guidKey(named[2]) };
+}
+
+// Steps 1 and 4: the app's current layer, and the one sitemap its SiteMap component names there — { ok: true, layer, sitemapId } | { ok: false, why }. The
+// layer is the one the SDK resolves (componentstate 1 when a pending edit makes the platform answer with both layers: app-components.js currentLayerRows).
+// GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <layer> and componenttype eq 62
+// { "value": [ { "objectid": "a8252d00-b5c5-4026-bfbf-090a7001cff5", "componenttype": 62 } ] }
+async function readLink(client, appId) {
+ const current = await currentAppLayer(client, appId);
+ if (!current.ok) return { ok: false, why: `the app's current layer could not be read (${current.reason})` };
+ let rows;
+ try {
+ rows = await appComponentRows(client, current.appModuleIdUnique, SITEMAP_COMPONENT, { strict: true });
+ } catch (error) {
+ return { ok: false, why: `the app's SiteMap component could not be read (${reasonOf(error)})` };
+ }
+ if (rows.length !== 1) return { ok: false, why: `the app's current layer holds ${rows.length} SiteMap components, where an app holds one` };
+ return { ok: true, layer: current.appModuleIdUnique, sitemapId: guidKey(rows[0].objectid) };
+}
+
+// Step 2: the sitemap by its id in one layer — { state: 'absent' }, or { state: 'present' | 'unread', why }. A plain read of the collection answers the
+// PUBLISHED layer only; RetrieveUnpublishedMultiple answers the SAVED one, a never-published row included (a deleted row is in neither):
+// GET /sitemaps?$select=sitemapid&$filter=sitemapid eq <id> { "value": [] }
+// GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid&$filter=sitemapid eq <id> { "value": [] }
+// A row that is some other sitemap proves nothing either way.
+const LAYER_READS = {
+ published: (id) => `/sitemaps?$select=sitemapid&$filter=sitemapid eq ${id}`,
+ saved: (id) => `/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid&$filter=sitemapid eq ${id}`,
+};
+async function sitemapIn(client, layer, sitemapId) {
+ let rows;
+ try {
+ rows = await collectionRows(client, LAYER_READS[layer](sitemapId), `sitemap '${sitemapId}' in the ${layer} layer`);
+ } catch (error) {
+ return { state: 'unread', why: `the ${layer} layer could not be read (${reasonOf(error)})` };
+ }
+ if (!rows.length) return { state: 'absent' };
+ if (rows.every((row) => row && guidKey(row.sitemapid) === sitemapId)) return { state: 'present', why: `the ${layer} layer still holds it` };
+ return { state: 'unread', why: `the ${layer} layer answered a row that is not that sitemap` };
+}
+
+// Step 3: the apps other than `appId` whose CURRENT layer names the sitemap, found as the SDK finds them before it deletes a sitemap: a component names an
+// app LAYER, the layer names its app, and the pin counts only while that layer is the app's current one — an old layer of a re-published app does not.
+// `ownLayer` (the app's own current layer) is skipped without a read. Throws when any of it cannot be read.
+// GET /appmodulecomponents?$select=_appmoduleidunique_value&$filter=componenttype eq 62 and objectid eq <sitemap> { "value": [ { "_appmoduleidunique_value": "<layer>" } ] }
+// GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid&$filter=appmoduleidunique eq <layer> { "value": [ { "appmoduleid": "<app>" } ] }
+async function otherAppsNaming(client, sitemapId, appId, ownLayer) {
+ const rows = await collectionRows(client,
+ `/appmodulecomponents?$select=_appmoduleidunique_value&$filter=componenttype eq ${SITEMAP_COMPONENT} and objectid eq ${sitemapId}`,
+ `the apps whose navigation names sitemap '${sitemapId}'`);
+ const layers = new Set();
+ for (const row of rows) {
+ const layer = guidKey(row && row._appmoduleidunique_value);
+ if (!FORM_GUID_RE.test(layer)) throw new Error(`a SiteMap component naming sitemap '${sitemapId}' carries no app layer id`);
+ if (layer !== ownLayer) layers.add(layer);
+ }
+ const others = [];
+ for (const layer of layers) {
+ const apps = await collectionRows(client,
+ `/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid&$filter=appmoduleidunique eq ${layer}`,
+ `the app of layer '${layer}'`);
+ for (const app of apps) {
+ const id = guidKey(app && app.appmoduleid);
+ if (!FORM_GUID_RE.test(id)) throw new Error(`app layer '${layer}' answered a row with no app id`);
+ if (id === appId || others.includes(id)) continue;
+ const current = await currentAppLayer(client, id);
+ if (!current.ok) throw new Error(`the current layer of app '${id}' could not be read (${current.reason})`);
+ if (current.appModuleIdUnique === layer) others.push(id);
+ }
+ }
+ return others;
+}
+
+// Step 0: the app's row version, which its delete is conditioned on — read FIRST, before anything is proven about the app (see the header), as the SDK
+// reads it first for its own delete of an app that has no sitemap. An app's read by id is its PUBLISHED projection, so an app that was never published
+// answers 404 (measured; the download tells the maker to publish a new app first):
+// GET /appmodules(<id>)?$select=appmoduleid -> 200, ETag: W/"1234567" (the same version is the body's "@odata.etag")
+async function appRowVersion(client, appId) {
+ let answer;
+ try {
+ answer = await client.get(`/appmodules(${appId})?$select=appmoduleid`);
+ } catch (error) {
+ return { ok: false, why: `reading the app failed (${reasonOf(error)})` };
+ }
+ if (answer && answer.status === 404) return { ok: false, why: 'its read by id answered HTTP 404: it was never published, or it was deleted meanwhile' };
+ if (!answer || answer.status < 200 || answer.status >= 300) return { ok: false, why: `reading the app answered HTTP ${answer && answer.status}` };
+ const header = Object.entries(answer.headers || {}).find(([name]) => name.toLowerCase() === 'etag');
+ const version = header ? header[1] : answer.body && answer.body['@odata.etag'];
+ if (typeof version !== 'string' || !version) return { ok: false, why: 'reading the app answered no row version' };
+ return { ok: true, version };
+}
+
+// Whether the app is gone from both layers, read by its id — { ok: true, gone } | { ok: false, why }. A row of any id counts as "not gone".
+// GET /appmodules?$select=appmoduleid&$filter=appmoduleid eq <id> { "value": [] }
+// GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid&$filter=appmoduleid eq <id> { "value": [] }
+async function appGone(client, appId) {
+ try {
+ const published = await collectionRows(client, `/appmodules?$select=appmoduleid&$filter=appmoduleid eq ${appId}`, `app '${appId}' in the published layer`);
+ const saved = await collectionRows(client, `/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid&$filter=appmoduleid eq ${appId}`, `app '${appId}' in the saved layer`);
+ return { ok: true, gone: published.length === 0 && saved.length === 0 };
+ } catch (error) {
+ return { ok: false, why: reasonOf(error) };
+ }
+}
+
+// What the DELETE was answered, for a message: the status and the platform's own OData error, or why no answer came.
+// { "error": { "code": "0x80060882", "message": "The version of the existing record doesn't match the RowVersion property provided." } }
+function answerOf(answer, failure) {
+ if (failure) return `no answer: ${reasonOf(failure)}`;
+ const error = answer && answer.body && answer.body.error;
+ const words = error && typeof error.message === 'string' ? `: ${error.code ? `${error.code} ` : ''}${error.message}` : '';
+ return `HTTP ${answer && answer.status}${words}`;
+}
+
+// Deletes the app `appId` (named `appName`) on its own, once the sitemap the SDK could not find (`sitemapId`, from danglingSitemapOf) is proven gone — see the
+// header. `client` is the SDK's Dataverse client (`sdk.dataverse`), `refused` the SDK's refusal, kept as the cause of a refusal here. Resolves to { warning }
+// (what to tell the maker) once the app is deleted and read back gone from both layers; throws otherwise — every error it throws marked `failClosed`.
+// Nothing is written before the proof is complete.
+async function deleteAppWithoutSitemap(client, { appId, appName, sitemapId, refused }) {
+ const id = guidKey(appId);
+ const lead = `app "${appName}" (${id}) was not deleted: its navigation link names sitemap ${sitemapId}, which the SDK could not read.`;
+ const ask = 'If this app is yours, delete it in Power Apps (make.powerapps.com, Apps), then run the teardown again: it removes the rest.';
+ const unproven = (why) => refusal(`${lead} Teardown deletes such an app on its own only once that sitemap is proven gone, and it could not prove it: ${why}. Nothing was deleted. ${ask}`, { cause: refused, failClosed: true });
+ if (!client || typeof client.get !== 'function' || typeof client.delete !== 'function') throw unproven('there is no Dataverse client to read it with');
+
+ // Step 0, before anything is proven: the version the delete is conditioned on. Never read again after the proof — see the header.
+ const row = await appRowVersion(client, id);
+ if (!row.ok) throw refusal(`${lead} Teardown deletes such an app on its own only with a delete conditioned on the app's row version, and it could not read one: ${row.why}. Nothing was deleted. ${ask}`, { cause: refused, failClosed: true });
+ const link = await readLink(client, id);
+ if (!link.ok) throw unproven(link.why);
+ if (link.sitemapId !== sitemapId) throw unproven(`the app's SiteMap component names sitemap ${link.sitemapId} now`);
+ for (const layer of ['published', 'saved']) {
+ const found = await sitemapIn(client, layer, sitemapId);
+ if (found.state !== 'absent') throw unproven(found.why);
+ }
+ let others;
+ try {
+ others = await otherAppsNaming(client, sitemapId, id, link.layer);
+ } catch (error) {
+ throw unproven(`which apps name it could not be read (${reasonOf(error)})`);
+ }
+ if (others.length) throw unproven(`the navigation of app ${others.map((other) => `'${other}'`).join(', ')} names it too`);
+ const again = await readLink(client, id);
+ if (!again.ok) throw unproven(again.why);
+ if (again.layer !== link.layer || again.sitemapId !== sitemapId) throw unproven(`the link changed while teardown read it (sitemap ${sitemapId}, then sitemap ${again.sitemapId})`);
+
+ // The one write, conditioned on the version of step 0. A delete that gets no answer is not sent again (lib/sdk-http-client.js never re-sends a
+ // conditional write it has no answer to): the reads below say whether it ran.
+ let answer;
+ let failure = null;
+ try {
+ answer = await client.delete(`/appmodules(${id})`, { headers: { 'If-Match': row.version } });
+ } catch (error) {
+ failure = error;
+ }
+ const gone = await appGone(client, id);
+ if (!gone.ok) {
+ throw Object.assign(new Error(`app "${appName}" (${id}): its sitemap ${sitemapId} is gone and the app's delete was sent (${answerOf(answer, failure)}), but whether the app is gone could not be read (${gone.why}), so the steps that depend on it are not attempted. Run the teardown again: it finds the app gone, or proves its sitemap gone again and deletes it.`), { failClosed: true, ...(failure ? { cause: failure } : {}) });
+ }
+ if (!gone.gone) {
+ // 412: the app's version is no longer the one the proof began at — the app changed while it ran (a repair, a relink, a publish), and nothing proven
+ // holds for the app as it is now. Final, as every refusal of the proof is: the next teardown proves the app as it is then.
+ // { "error": { "code": "0x80060882", "message": "The version of the existing record doesn't match the RowVersion property provided." } }
+ if (!failure && answer && answer.status === 412) {
+ throw refusal(`app "${appName}" (${id}) was not deleted: its sitemap ${sitemapId} is gone, but the app changed while teardown was proving that, so the platform refused a delete conditioned on the version the proof began at (${answerOf(answer)}). Nothing was deleted. Run the teardown again: it proves the app as it is now before it deletes anything.`, { cause: refused, failClosed: true });
+ }
+ throw Object.assign(serviceFailure(`app "${appName}" (${id}) was not deleted: its sitemap ${sitemapId} is gone, but the delete of the app on its own did not remove it (${answerOf(answer, failure)}). Nothing else was deleted. Run the teardown again; if the app stays, and it is yours, delete it in Power Apps (make.powerapps.com, Apps), then run the teardown again: it removes the rest.`, {
+ status: answer && answer.status,
+ answered: answer && answer.body && answer.body.error,
+ cause: failure || refused,
+ }), { failClosed: true });
+ }
+ return { warning: `app "${appName}" (${id}) was deleted without its sitemap: its navigation link named sitemap ${sitemapId}, which is in neither the published nor the saved layer (the teardown of another app that shared it can leave an app so), so there was none to delete, and no sitemap was touched` };
+}
+
+module.exports = { danglingSitemapOf, deleteAppWithoutSitemap };
diff --git a/plugins/model-apps/scripts/lib/app-spec-doc.js b/plugins/model-apps/scripts/lib/app-spec-doc.js
index 6bc0d4a9f..1d4d34c53 100644
--- a/plugins/model-apps/scripts/lib/app-spec-doc.js
+++ b/plugins/model-apps/scripts/lib/app-spec-doc.js
@@ -17,7 +17,7 @@
const lc = (s) => String(s || '').toLowerCase();
const { labelText, lookupLabelFor } = require('./app-spec.js');
-const { appAccessCondition, appAccessModel, rolesOfPersonas, uncoveredTables, uncoveredTablesCallout } = require('./app-access.js');
+const { appAccessCondition, appAccessModel, rolesOfPersonas, roleGrantRefusals, uncoveredTables, uncoveredTablesCallout } = require('./app-access.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
@@ -418,22 +418,33 @@ function namedGrantNote(grant) {
// roleGrants[]: privileges ADDED to roles that already exist. Shown with the role they extend — the persona sections above show the roles this spec owns — and,
// when the environment was read, with how each grant stands to the roles the app has: a grant gives a role a table, not the app.
+//
+// An entry that does not name exactly one role is refused by the gate a build runs, and is shown as that refusal, in the gate's own words
+// (roleGrantRefusals), never as rows: listed with the rest, it read as a grant the build would make. Shape errors are otherwise validateAppSpec's to
+// report and not this document's — but this one is the document's own claim about what the build does.
function roleGrantsSection(spec, model) {
const grants = objs(spec.roleGrants);
if (!grants.length) return [];
+ const refusals = roleGrantRefusals(spec);
+ const refused = new Set(refusals.map((r) => r.index));
const rows = [];
- for (const g of grants) {
+ arr(spec.roleGrants).forEach((g, index) => {
+ if (!g || typeof g !== 'object' || Array.isArray(g) || refused.has(index)) return;
const role = typeof g.role === 'string' && g.role.trim() ? g.role.trim() : (typeof g.roleId === 'string' ? g.roleId.trim() : '');
for (const r of privilegeRows(unionPrivileges(arr(g.privileges)))) rows.push({ role, ...r });
- }
+ });
const out = ['### Roles extended by `roleGrants[]`', '', 'These roles already exist. The build ADDS the privileges below and removes none, and a grant does not associate the role with the app. After a build, `verify-model-app.js` checks that each role holds them.', ''];
if (rows.length) {
out.push('| Role | Table | Access | Scope |', '|---|---|---|---|');
for (const r of rows) out.push(`| ${cell(r.role)} | ${cell(r.entity)} | ${cell(r.access)} | ${cell(r.scope)} |`);
- } else {
- out.push('_No privileges declared._');
+ out.push('');
+ } else if (!refusals.length) {
+ out.push('_No privileges declared._', '');
}
- out.push('');
+ for (const { messages } of refusals) {
+ for (const message of messages) out.push(`> ✗ ${text(message)}`, '');
+ }
+ if (refusals.length) out.push('The build refuses this spec until each of these entries names one role, so their privileges are not listed.', '');
if (model.state === 'read') {
for (const g of model.grants) {
if (g.status === 'not-associated') out.push(`> ⚠ Role "${text(g.label)}" is not among the roles associated with the app, so its users get these privileges but may not be able to open the app.`, '');
diff --git a/plugins/model-apps/scripts/lib/app-spec.js b/plugins/model-apps/scripts/lib/app-spec.js
index d26e83da8..a3ec465d5 100644
--- a/plugins/model-apps/scripts/lib/app-spec.js
+++ b/plugins/model-apps/scripts/lib/app-spec.js
@@ -6,6 +6,8 @@ const { isAppSourcePath } = require('./app-source-path.js');
const { normalizeSpecShape } = require('./spec-shape.js');
const { isMainForm, selectDefaultForm, ordersByHand } = require('./form-order.js');
const { AUTO_TAB_NAME, AUTO_SECTION_NAME, placementOf, resolvePlacement } = require('./form-subgrid-placement.js');
+const { PAGE_BINDINGS, pageBindingsProblem, statedPageBindings, statableBinding, bindingProblemText } = require('./page-bindings.js');
+const { nearestName } = require('./nearest-name.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:`
@@ -38,6 +40,9 @@ const FORM_GUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{
// `model` in its config.json. Shared with download, which carries only a model the spec can hold.
const PAGE_MODEL_RE = /^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,99}$/;
+// A generative page's connector and Custom API bindings: what a spec states of them (an allowlist of properties, each with the kind of value it holds) and how a rebuild reads it is defined in page-bindings.js.
+// The validator below holds a page to it, and the download holds what it writes to the same rule, so a download never writes a spec this refuses. Re-exported here for the callers that take them from the spec module.
+
// 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.
@@ -1603,6 +1608,38 @@ function validateFormSecurityRoles(f, spec, errors) {
}
}
+// The per-field control options, ONE list for both routes that declare them: a form-level
+// `fieldOptions` entry takes exactly these, and an inline `fields[]` entry takes these plus its `name`
+// (FORM_FIELD_ENTRY_KEYS). A map entry takes no `name`, because its KEY names the field.
+//
+// It is also the list the compiler projects (artifact-intent.js `projectFieldOptions`), so validation
+// and the build cannot disagree about what an option is. A `fieldOptions` entry used to be checked only
+// for the values of these keys, so any other key (`readOnlyy`, `colSpan`, a subgrid's `before`)
+// validated clean and was then dropped by the projection: a green build that never applied the option.
+// Frozen, and in the order of the compiled entry.
+const FIELD_OPTION_KEYS = Object.freeze(['readOnly', 'hidden', 'after', 'colspan', 'rowspan']);
+// `readOnly?, hidden?, after?, colspan?, rowspan?`, for the messages that describe an entry's shape.
+const FIELD_OPTION_SHAPE = FIELD_OPTION_KEYS.map((k) => `${k}?`).join(', ');
+
+// What to write instead, for a key of a `fieldOptions` entry that a near spelling cannot explain.
+// Prototype-less for the reason ENTITY_KEY_HINTS is: the lookup key comes from the spec, and
+// `constructor` must not find Object's own function.
+const FIELD_OPTION_KEY_HINTS = Object.assign(Object.create(null), {
+ name: " — a fieldOptions entry is keyed by the field's logical name, so it takes no 'name'",
+ visible: " — to keep the field on the form but not show it, use 'hidden': true",
+});
+
+// The message suffix naming the option an unknown `fieldOptions` key most likely meant: a written hint
+// first, then the shared single-edit matcher, which also settles a casing slip (`colSpan` for
+// `colspan`). nearestName answers in lower case, so its match is mapped back to the spelling the spec
+// must use.
+function fieldOptionKeyHint(key) {
+ if (FIELD_OPTION_KEY_HINTS[key]) return FIELD_OPTION_KEY_HINTS[key];
+ const near = nearestName(key, FIELD_OPTION_KEYS.map((k) => k.toLowerCase()));
+ const meant = near && FIELD_OPTION_KEYS.find((k) => k.toLowerCase() === near);
+ return meant ? ` — did you mean '${meant}'?` : '';
+}
+
// Allow-listed keys for an explicit form layout, with the reason each rejection exists.
//
// `tabs[]`/`sections[]` had no allow-list at all, so an invented or misspelled key validated clean
@@ -1622,7 +1659,7 @@ function validateFormSecurityRoles(f, spec, errors) {
const FORM_TAB_KEYS = new Set(['name', 'label', 'expanded', 'visible', 'sections', 'columns']);
const FORM_TAB_COLUMN_KEYS = new Set(['width', 'sections']);
const FORM_SECTION_KEYS = new Set(['name', 'label', 'columns', 'showLabel', 'visible', 'fields']);
-const FORM_FIELD_ENTRY_KEYS = new Set(['name', 'readOnly', 'hidden', 'after', 'colspan', 'rowspan']);
+const FORM_FIELD_ENTRY_KEYS = new Set(['name', ...FIELD_OPTION_KEYS]);
// Identity of a sample-data `matchOn` value, shared by the author-time gate in `validateAppSpec` and
// the loader's own refusal in `chooseMatchOn`/`firstDuplicateNonEmpty` (entity-provision.js).
//
@@ -2225,7 +2262,7 @@ function validateFormLayoutKeys(f, errors) {
});
}
-function validateFormFieldOptions(f, entityByLower, errors, warnings) {
+function validateFormFieldOptions(f, entityByLower, errors, warnings, unknownKeyFindings = errors) {
const label = `form '${f.name || f.entity}'`;
const entity = entityByLower.get(String(f.entity || '').toLowerCase());
const columnType = (logical) => {
@@ -2263,7 +2300,7 @@ function validateFormFieldOptions(f, entityByLower, errors, warnings) {
} 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? }`);
+ errors.push(`${label}: a field entry must be a column logical name or an object { name, ${FIELD_OPTION_SHAPE} }`);
}
}
}
@@ -2276,9 +2313,18 @@ function validateFormFieldOptions(f, entityByLower, errors, warnings) {
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?, colspan? }`);
+ errors.push(`${label}: fieldOptions['${key}'] must be an object { ${FIELD_OPTION_SHAPE} }`);
continue;
}
+ // Only the entry's OWN keys (Object.keys): a key the entry does not take is reported here, worded
+ // like the inline entry's check (validateFormLayoutKeys), instead of being dropped by the compiler —
+ // as an error, or as a warning where validateAppSpec says the spec is only read (fieldOptionKeyFindings).
+ // A named form also names its table: a field belongs to a table, and two tables' forms can share
+ // a name.
+ for (const k of Object.keys(v)) {
+ if (FIELD_OPTION_KEYS.includes(k)) continue;
+ unknownKeyFindings.push(`${label}${f.name && f.entity ? ` (table ${f.entity})` : ''}: unknown key '${k}' on fieldOptions['${key}']${fieldOptionKeyHint(k)} (allowed: ${FIELD_OPTION_KEYS.join(', ')})`);
+ }
seen.push({ name: String(key).toLowerCase(), opt: v, where: `fieldOptions['${key}']`, inline: false });
}
}
@@ -2436,6 +2482,12 @@ function validateAppSpec(spec, opts = {}) {
// protect there, and the spec of an app an earlier release built from a value they refuse must still reach its deployment. The same arrangement as
// `relationshipCollisions: 'warn'` at the end of this function; every other caller keeps the error.
const columnValueFindings = opts.columnValues === 'warn' ? warnings : errors;
+ // Where an unknown key of a form's `fieldOptions` entry goes (validateFormFieldOptions). Every profile that builds or plans a build
+ // keeps it an error: the build drops such a key, so the option would never be applied. A release before that check accepted and built
+ // a spec carrying one (the key was ignored), and a spec that is only READ to act on its deployment must still be read — so the
+ // structural profile (teardown, preview) takes it as a warning in the same words, and so does read-only verification, which keeps the
+ // deploy profile and passes `fieldOptionKeys: 'warn'`, as it passes `columnValues: 'warn'`. Nothing else about the entry moves.
+ const fieldOptionKeyFindings = profile === 'structural' || opts.fieldOptionKeys === 'warn' ? warnings : errors;
if (!VALIDATION_PROFILES.includes(profile)) {
return { ok: false, errors: [`unknown validation profile '${profile}' (valid: ${VALIDATION_PROFILES.join(', ')})`], warnings };
}
@@ -2965,7 +3017,7 @@ function validateAppSpec(spec, opts = {}) {
}
}
}
- validateFormFieldOptions(f, entityByLower, errors, warnings);
+ validateFormFieldOptions(f, entityByLower, errors, warnings, fieldOptionKeyFindings);
validateFormLayoutKeys(f, errors);
validateFormSecurityRoles(f, spec, errors);
// `layout: 'explicit'` with no `tabs[]` is a spec that asks for one thing and builds another.
@@ -3473,6 +3525,25 @@ function validateAppSpec(spec, opts = {}) {
if (p.model !== undefined && (typeof p.model !== 'string' || !PAGE_MODEL_RE.test(p.model))) {
errors.push(`page '${p.key || p.name}': model must be a model id such as 'gpt-4.1' (letters, digits and . _ : / @ + -, at most 100 characters)`);
}
+ // The page's connector and Custom API bindings. That each is a list, and that none of its entries is missing, is reported above by normalizeSpecShape; an entry that is there and is no object (a string, a number) is
+ // reported here, by the rule a download holds a page's bindings to (pageBindingsProblem), so a download never writes a spec this refuses.
+ // An entry is stated by an allowlist of properties, each with a value of a shape known to be safe (page-bindings.js, which holds the threat model): a property outside it — a connection id, a credential,
+ // anything the runtime or a later version adds — or a value of another shape is an ERROR that names the vetted property or says "an unrecognized property", and never a value or an unrecognized key (a key
+ // can be the secret), because the spec is what is committed and shared, and refusing is the only thing that keeps a credential out of it.
+ // What the page finds an entry by is only a warning: an entry is written as it is given, and a page a download read the bindings of may hold one with no such property, which a refusal would leave with no spec at all.
+ for (const [kind, identity] of Object.entries(PAGE_BINDINGS)) {
+ if (!Array.isArray(p[kind])) continue;
+ const problem = pageBindingsProblem(kind, p[kind]);
+ if (problem) errors.push(`page '${p.key || p.name}': ${problem}`);
+ p[kind].forEach((entry, i) => {
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return;
+ const unstated = new Set(statableBinding(kind, entry).leftOut.map((found) => `page '${p.key || p.name}': ${bindingProblemText(kind, i, found)}`));
+ for (const text of unstated) errors.push(text);
+ if (typeof entry[identity] !== 'string' || !entry[identity].trim()) {
+ warnings.push(`page '${p.key || p.name}': ${kind}[${i}] has no ${identity} — the page's code finds a binding by it, so this one can never be used`);
+ }
+ });
+ }
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).
@@ -4210,6 +4281,39 @@ function canonicalPersonaName(persona) {
// 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']);
+// How every roleGrants[] message names its entry: `roleGrants[1] (role "Viewer")`, `roleGrants[0] (roleId <guid>)`, or `roleGrants[2]`.
+// `i` is the entry's index in the spec's roleGrants[] as written.
+function roleGrantEntryLabel(g, i) {
+ const roleName = typeof g.role === 'string' ? g.role.trim() : g.role;
+ return `roleGrants[${i}]${roleName ? ` (role "${roleName}")` : g.roleId ? ` (roleId ${g.roleId})` : ''}`;
+}
+
+// The ONE check of which role a roleGrants[] entry names: exactly one of `role` (an existing role's display name) and `roleId` (its
+// GUID). Answers the gate's messages, [] for an entry that names one role. validateRoleGrants (the gate a build and lint-app-spec.js
+// run) reports them, and the design document repeats them word for word (lib/app-access.js roleGrantRefusals → lib/app-spec-doc.js and
+// the warnings of write-app-spec-doc.js), which used to show an entry with both as a grant the build would make.
+function roleGrantIdentityErrors(g, label) {
+ const describeValue = (v) => { try { return JSON.stringify(v); } catch { return Object.prototype.toString.call(v); } };
+ const errors = [];
+ const roleName = typeof g.role === 'string' ? g.role.trim() : g.role;
+ // 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)})`);
+ }
+ return errors;
+}
+
function validateRoleGrants(spec, errors) {
const grants = spec && spec.roleGrants;
if (grants === undefined) return;
@@ -4217,7 +4321,6 @@ function validateRoleGrants(spec, errors) {
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.
@@ -4242,22 +4345,9 @@ function validateRoleGrants(spec, errors) {
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 label = roleGrantEntryLabel(g, i);
+ errors.push(...roleGrantIdentityErrors(g, label));
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`);
}
@@ -4415,6 +4505,8 @@ function migrateAppSpec(spec) {
}
module.exports = {
+ roleGrantEntryLabel,
+ roleGrantIdentityErrors,
rejectLocalizedGlobalChoice,
sampleKeyIdentity,
dashboardNameKey,
@@ -4460,10 +4552,14 @@ module.exports = {
quickCreateEnabledFor,
isPlatformIconRef,
webResourceNameFromRef,
+ FIELD_OPTION_KEYS,
FORM_TYPE_CODE,
formIdentityKey,
FORM_GUID_RE,
PAGE_MODEL_RE,
+ PAGE_BINDINGS,
+ pageBindingsProblem,
+ statedPageBindings,
ACCESS_LEVELS,
PRIVILEGE_SCOPES,
ROLE_GRANT_KEYS,
diff --git a/plugins/model-apps/scripts/lib/artifact-intent.js b/plugins/model-apps/scripts/lib/artifact-intent.js
index 2197bc525..1defdf469 100644
--- a/plugins/model-apps/scripts/lib/artifact-intent.js
+++ b/plugins/model-apps/scripts/lib/artifact-intent.js
@@ -11,7 +11,7 @@
// the SDK's generic mutation surface without hardcoding form-model logic everywhere.
const { entityByLogical } = require('./_graph.js');
-const { lookupColumnsFor, generatedTabName, generatedSectionName, formColumnsOf, authoredSectionNames, authoredTabNames } = require('./app-spec.js');
+const { lookupColumnsFor, generatedTabName, generatedSectionName, formColumnsOf, authoredSectionNames, authoredTabNames, FIELD_OPTION_KEYS } = require('./app-spec.js');
const { SDK_COLUMN_TYPE } = require('./entity-provision.js');
const { timelineCellIntent, timelineRowsIntent, wantsTimeline } = require('./form-timeline.js');
@@ -159,6 +159,36 @@ function fieldCellIntent(logical, opts) {
// custom control — but validateAppSpec emits a warning so the choice is deliberate rather than accidental.
const NON_FORM_RENDERABLE_TYPES = new Set(['BigInt']);
+// A span is `undefined` only when the author SAID NOTHING. An explicit 1 is preserved as 1: the
+// previous rule mapped every value <= 1 to undefined, which made "author asked for the default"
+// and "author said nothing" IDENTICAL — the opposite of what its comment claimed. The consequence
+// was live-reproduced: changing an authored colspan from 2 to 1 compiled to "no colspan",
+// reconcile read that as "no desired span", and the deployed cell stayed at 2 across two applies.
+function optSpan(v) {
+ if (v === undefined || v === null || v === '') return undefined; // said nothing
+ const n = Number(v);
+ return Number.isFinite(n) && n >= 1 ? Math.floor(n) : undefined; // an explicit 1 IS intent
+}
+
+// How each per-field option reaches the canonical entry, the same from both routes that declare one
+// (an inline `fields[]` entry and a form-level `fieldOptions` entry). The projection walks
+// FIELD_OPTION_KEYS (app-spec.js), the list validation accepts, so the two cannot drift apart: a key
+// added there without a projector here fails the first compile, and a key that is not there never
+// reaches a form, because the spec gate refuses it instead of this projection dropping it in silence.
+const FIELD_OPTION_PROJECTORS = {
+ readOnly: (v) => v === true,
+ hidden: (v) => v === true,
+ after: (v) => (v ? String(v).toLowerCase() : undefined),
+ colspan: optSpan,
+ rowspan: optSpan,
+};
+
+function projectFieldOptions(name, source) {
+ const entry = { name };
+ for (const key of FIELD_OPTION_KEYS) entry[key] = FIELD_OPTION_PROJECTORS[key](source[key]);
+ return entry;
+}
+
// Normalize one entry of `tabs[].sections[].fields[]`.
//
// An entry is either a bare logical name (the original and still most common shape) or an object
@@ -170,30 +200,12 @@ const NON_FORM_RENDERABLE_TYPES = new Set(['BigInt']);
// { "name": "co_description", "colspan": 2 }
// Returns a canonical { name, readOnly, hidden, after, colspan, rowspan } with `name`/`after`
// lower-cased, because every downstream comparison (form field logicals, cell pointers, Dataverse
-// attribute logical names) is lower-case.
-//
-// A span is `undefined` only when the author SAID NOTHING. An explicit 1 is preserved as 1: the
-// previous rule mapped every value <= 1 to undefined, which made "author asked for the default"
-// and "author said nothing" IDENTICAL — the opposite of what its comment claimed. The consequence
-// was live-reproduced: changing an authored colspan from 2 to 1 compiled to "no colspan",
-// reconcile read that as "no desired span", and the deployed cell stayed at 2 across two applies.
+// attribute logical names) is lower-case. Spans keep optSpan's omission-vs-value rule.
function normalizeFieldEntry(entry) {
- const span = (v) => {
- if (v === undefined || v === null || v === '') return undefined; // said nothing
- const n = Number(v);
- return Number.isFinite(n) && n >= 1 ? Math.floor(n) : undefined; // an explicit 1 IS intent
- };
if (entry && typeof entry === 'object' && !Array.isArray(entry)) {
- return {
- name: String(entry.name || '').toLowerCase(),
- readOnly: entry.readOnly === true,
- hidden: entry.hidden === true,
- after: entry.after ? String(entry.after).toLowerCase() : undefined,
- colspan: span(entry.colspan),
- rowspan: span(entry.rowspan),
- };
+ return projectFieldOptions(String(entry.name || '').toLowerCase(), entry);
}
- return { name: String(entry || '').toLowerCase(), readOnly: false, hidden: false, after: undefined, colspan: undefined, rowspan: undefined };
+ return projectFieldOptions(String(entry || '').toLowerCase(), {});
}
// Form-level per-field control options, keyed by column logical name:
@@ -202,12 +214,6 @@ function normalizeFieldEntry(entry) {
// This is the ONLY way to reach these attributes under an AUTO layout, which has no field list to
// hang an inline object off. Under an EXPLICIT layout both work and the inline entry wins, because
// the more specific declaration should not be silently overridden by a form-wide default.
-function optSpan(v) {
- if (v === undefined || v === null || v === '') return undefined;
- const n = Number(v);
- return Number.isFinite(n) && n >= 1 ? Math.floor(n) : undefined;
-}
-
function fieldOptionsMap(formSpec) {
const map = {};
const fo = formSpec && formSpec.fieldOptions;
@@ -215,15 +221,7 @@ function fieldOptionsMap(formSpec) {
for (const key of Object.keys(fo)) {
const v = fo[key];
if (!v || typeof v !== 'object' || Array.isArray(v)) continue;
- map[String(key).toLowerCase()] = {
- name: String(key).toLowerCase(),
- readOnly: v.readOnly === true,
- hidden: v.hidden === true,
- after: v.after ? String(v.after).toLowerCase() : undefined,
- // Same omission-vs-value rule as normalizeFieldEntry: an explicit 1 is a claim, absence is not.
- colspan: optSpan(v.colspan),
- rowspan: optSpan(v.rowspan),
- };
+ map[String(key).toLowerCase()] = projectFieldOptions(String(key).toLowerCase(), v);
}
return map;
}
diff --git a/plugins/model-apps/scripts/lib/custom-api-kinds.js b/plugins/model-apps/scripts/lib/custom-api-kinds.js
new file mode 100644
index 000000000..efc5f9a6a
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/custom-api-kinds.js
@@ -0,0 +1,23 @@
+'use strict';
+
+// A declared kind the page action runtime does not support drops the WHOLE binding. Discovery
+// and App Spec validation therefore share this closed vocabulary, rather than drifting apart.
+// Types 3/4 are unsupported complex values; type 5 is a structural lookup at call time, not a
+// declared kind. Numeric keys are customapirequestparameter.type option values:
+// https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/customapirequestparameter
+const PARAMETER_KIND_BY_TYPE = Object.freeze({
+ 0: 'Boolean',
+ 1: 'DateTime',
+ 2: 'Decimal',
+ 6: 'Float',
+ 7: 'Integer',
+ 8: 'Money',
+ 9: 'Picklist',
+ 10: 'String',
+ 11: 'StringArray',
+ 12: 'Guid',
+});
+
+const PARAMETER_KINDS = Object.freeze(Object.values(PARAMETER_KIND_BY_TYPE));
+
+module.exports = { PARAMETER_KIND_BY_TYPE, PARAMETER_KINDS };
diff --git a/plugins/model-apps/scripts/lib/dashboard-creation-records.js b/plugins/model-apps/scripts/lib/dashboard-creation-records.js
new file mode 100644
index 000000000..ab1b9a256
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/dashboard-creation-records.js
@@ -0,0 +1,283 @@
+'use strict';
+// The dashboards a build CREATED and has not yet seen join the app's solution, kept in the build's workspace so that the run that FOLLOWS an interrupted
+// one adds that same dashboard to the solution instead of losing it.
+//
+// The build creates a dashboard (lib/sdk-build.js, the dashboards phase) with one request — the push POSTs the systemform row — and adds it to the app's
+// solution with a second one (AddSolutionComponent). The solution is the only later proof that the dashboard is this app's: a dashboard's name is neither
+// unique nor compared exactly, and teardown deletes only the dashboards the solution holds (sdk-build.js dashboardsInSolution). A run that stops between
+// the two requests — the process is killed, the answer to the create is lost, or the membership add and the build's own undo of the create both fail —
+// leaves the row outside the solution, and nothing durable remembered it. The next build looked the dashboard up by name: a dashboard that was created and
+// never published is in no plain read (only RetrieveUnpublished answers it), so that build created a SECOND one; one that someone had published since was
+// reused as a lone namesake without being added. Either way teardown kept it and a solution export left it out.
+//
+// The bundled SDK sends the workspace's own id as the row's key on the create (`systemform.formid`, minted by the client), so the build holds the id BEFORE
+// the request. It notes it here before the push, keeps the id the push reports beside it when that is another one (the SDK prefers the id the service's
+// answer names and moves its copy there), and clears it once the row is PROVEN in the solution (the membership add answered) or proven REMOVED by the
+// build's own undo (the delete answered). A stranded dashboard — the add and the undo both failed — keeps it. The next build reads each recorded id in the
+// saved layer before it looks any dashboard up by name (sdk-build.js recoverRecordedDashboard).
+//
+// What this record is NOT: proof about any row but the one its id names, deletion authority (teardown stays solution-membership based and never reads
+// it), or a way to adopt a namesake. It is written only from the id the build minted for a create it is about to send and from the id that push
+// reported — never from a downloaded `dashboardId`, a namesake, a solution member or any id a spec supplies.
+//
+// One file per environment, app and solution, named by the hash of the three, so another app built from the same folder, or the same app into another
+// solution or environment, never sees it (an app that does not exist yet is still named: its unique name comes from the spec, not from the service):
+// dashboard-creation.<64 hex>.json
+// { "schemaVersion": 1, "environmentFingerprint": "<sha256 of the origin>", "appUniqueName": "contoso_app", "solutionUniqueName": "contososolution",
+// "dashboards": { "Ops Overview": { "id": "11111111-1111-4111-8111-111111111111" },
+// "Sales": { "id": "33333333-3333-4333-8333-333333333333", "reportedId": "44444444-4444-4444-8444-444444444444" } } }
+// `reportedId` appears only when the push reported another id than the one the build sent; both observations are kept, and they are not equal: the
+// reported id is the row the create made, the sent one was never seen to make anything, so the next build recovers only the reported row and never
+// adopts the sent one on its own (sdk-build.js recoverRecordedDashboard). Names are compared as Dataverse compares dashboard names (app-spec.js
+// dashboardNameKey); the file keeps a name as the build wrote it, sorted by that comparison, so the same dashboards are the same bytes. Written atomically.
+//
+// A file that cannot be read — damaged, a link where the file should be, a folder, too large, one written for another environment, app or solution, or
+// one holding an entry the build never writes (an id or a reported id that is no id, a reported id equal to the id, a key it does not write, two names
+// Dataverse compares as one) — is "nothing is recorded", which is what the build did before there was a record: it finds dashboards by name. An entry
+// is never skipped on its own: what it held may be the only trace of a dashboard outside its solution, and a record that went on being written would
+// lose it (a note() would replace the file, a clear() of the last good entry would delete it). The run then writes no record of its own either, so a
+// file it cannot read is never replaced or removed; the warning names it, for a person to look at and remove.
+//
+// Builds that share a workspace share this file (the same app and solution in the same environment), and each change replaces it whole. So a change
+// is never made to what a run read earlier — another build may have written its own entry since, and writing the earlier copy back dropped it (A notes
+// `a`, B notes `b`: only `b` was left; A then clears `a`: the file went, `b` with it). A change takes the record's writer lease (lib/record-lease.js),
+// reads the file as it is then, applies its one change to that, and writes it: a note adds an entry or replaces the one this run knows, an observe adds
+// a reported id to this run's entry, a clear removes this run's entry, and none of them touches another build's. A file that has become unreadable since
+// is not written over. Reads take no lease.
+//
+// An entry is compared WHOLE — the id its create was sent with AND the id the service reported for it — because the reported id is added after the entry
+// was noted: a build that read the entry before its creator recorded the reported id knows only the sent one, and removing or replacing what it knows
+// would drop the reported id, which names the row the create made. So a change that finds the entry other than this run knows it leaves it; a note of
+// the id the entry already holds keeps the reported id beside it; and a clear that finds the entry changed says so to its caller (it answers null), so
+// that the recovery of an interrupted create stops rather than create a second dashboard on the word of the older entry (sdk-build.js
+// recoverRecordedDashboard).
+const fs = require('node:fs');
+const path = require('node:path');
+const { sha256 } = require('./hash.js');
+const { writeFileAtomic } = require('./apply-snapshot-store.js');
+const { environmentFingerprint, workspaceRoot } = require('./page-ownership-records.js');
+const { dashboardNameKey } = require('./app-spec.js');
+const { withRecordLease } = require('./record-lease.js');
+
+const PREFIX = 'dashboard-creation.';
+const SCHEMA_VERSION = 1;
+const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+// A handful of names and ids: a file much larger than any spec's dashboards could need is not a record of this kind.
+const MAX_BYTES = 1 << 20;
+
+const lower = (value) => String(value == null ? '' : value).toLowerCase();
+// An id as the record keeps it: bare (no braces) and lower case, or null for anything that is not a GUID.
+function idOf(value) {
+ const id = lower(value).trim().replace(/^\{|\}$/g, '');
+ return GUID.test(id) ? id : null;
+}
+const recordFile = (root, fingerprint, app, solution) => path.join(root, `${PREFIX}${sha256(JSON.stringify([fingerprint, app, solution]))}.json`);
+const byKey = ([a], [b]) => (a < b ? -1 : a > b ? 1 : 0);
+// The same entry: the same sent id and the same reported id — none on either side is the same as none.
+const sameEntry = (a, b) => Boolean(a) && Boolean(b) && a.id === b.id && (a.reportedId || '') === (b.reportedId || '');
+// An entry's ids, for a message: "<sent>" or "<sent> (the service reported <reported>)".
+const idsText = (entry) => `${entry.id}${entry.reportedId ? ` (the service reported ${entry.reportedId})` : ''}`;
+
+// Where the record of `appUniqueName`'s dashboards in `solutionUniqueName` and `environment` is kept — for a caller that has to point at it (a message, a
+// test), never to read it.
+function dashboardCreationRecordPath(workspaceDir, environment, appUniqueName, solutionUniqueName) {
+ return recordFile(path.resolve(workspaceDir), environmentFingerprint(environment), lower(appUniqueName), lower(solutionUniqueName));
+}
+
+// The recorded dashboards, as Map<dashboardNameKey(name), { name, id, reportedId? }>. Throws what stops the file from being read (the caller decides that is
+// only a warning); a workspace or a file that does not exist is an empty map. An entry the build does not write makes the whole file unreadable.
+function readDashboardCreations(workspaceDir, environment, appUniqueName, solutionUniqueName) {
+ const known = new Map();
+ const root = workspaceRoot(workspaceDir);
+ if (!root) return known;
+ const fingerprint = environmentFingerprint(environment);
+ const app = lower(appUniqueName);
+ const solution = lower(solutionUniqueName);
+ const file = recordFile(root, fingerprint, app, solution);
+ let stat;
+ try { stat = fs.lstatSync(file); } catch (e) { if (e.code === 'ENOENT') return known; throw e; }
+ // A plain, unlinked file of a sane size, as the page and web-resource records are read: a record another location can alter, or a file that is not one,
+ // says nothing.
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink > 1 || stat.size > MAX_BYTES) throw new Error(`${file} is not a plain file of a dashboard creation record`);
+ const record = JSON.parse(fs.readFileSync(file, 'utf8'));
+ if (!record || record.schemaVersion !== SCHEMA_VERSION || record.environmentFingerprint !== fingerprint || record.appUniqueName !== app || record.solutionUniqueName !== solution
+ || !record.dashboards || typeof record.dashboards !== 'object' || Array.isArray(record.dashboards)) {
+ throw new Error(`${file} is not a dashboard creation record this build can read`);
+ }
+ for (const [name, entry] of Object.entries(record.dashboards)) {
+ // JSON.parse makes every key of the file an OWN key — a `__proto__` key included (it defines the property; it never calls the prototype setter) — and
+ // the names are only listed here, into a Map, so no name read from the file is ever taken as a prototype.
+ // Exactly what the writer writes, or the whole record is unreadable (see the header): `{ "id": "<guid>" }` or `{ "id": "<guid>", "reportedId": "<another guid>" }`
+ // under a name no other entry shares as Dataverse compares names. Reading only the id of an entry whose reported id is damaged could prove "absent" while the
+ // row the service named exists; keeping one of two entries for the same name would drop the other's id.
+ const key = dashboardNameKey(name);
+ const shaped = Boolean(entry) && typeof entry === 'object' && !Array.isArray(entry) && Object.keys(entry).every((k) => k === 'id' || k === 'reportedId');
+ const id = shaped ? idOf(entry.id) : null;
+ const reportedId = shaped && entry.reportedId !== undefined ? idOf(entry.reportedId) : undefined;
+ if (!key || !id || reportedId === null || reportedId === id || known.has(key)) {
+ throw new Error(`${file} holds an entry this build does not write (dashboard '${name}')`);
+ }
+ known.set(key, { name, id, ...(reportedId ? { reportedId } : {}) });
+ }
+ return known;
+}
+
+// Replace the record with `entries` (the Map readDashboardCreations answers); an empty map removes the file. It takes no lease: a caller that shares the
+// workspace with another build holds the record's lease across its read and this write (openDashboardCreations).
+function writeDashboardCreations(workspaceDir, environment, appUniqueName, solutionUniqueName, entries) {
+ const fingerprint = environmentFingerprint(environment);
+ const app = lower(appUniqueName);
+ const solution = lower(solutionUniqueName);
+ if (!entries.size) {
+ const root = workspaceRoot(workspaceDir);
+ if (!root) return;
+ try { fs.unlinkSync(recordFile(root, fingerprint, app, solution)); } catch (e) { if (e.code !== 'ENOENT') throw e; }
+ return;
+ }
+ const root = workspaceRoot(workspaceDir, true);
+ // A null-prototype object, so that EVERY name becomes an own key. `__proto__` is a legal dashboard name, and assigned to a plain object it calls the
+ // inherited prototype setter instead of adding an entry: JSON.stringify then left that dashboard out, with no error to warn about, and the next run
+ // could not find it. Every other name serializes exactly as before — JSON.stringify lists own keys in the same order whatever the prototype.
+ const dashboards = Object.create(null);
+ for (const [, { name, id, reportedId }] of [...entries].sort(byKey)) dashboards[name] = { id, ...(reportedId ? { reportedId } : {}) };
+ writeFileAtomic(recordFile(root, fingerprint, app, solution), `${JSON.stringify({ schemaVersion: SCHEMA_VERSION, environmentFingerprint: fingerprint, appUniqueName: app, solutionUniqueName: solution, dashboards })}\n`);
+}
+
+/**
+ * The record for one run of the build: read once, then each change made to the file as it is then, under the record's writer lease. `idsOf(name)` is
+ * every id an earlier run recorded for the dashboard — the one it sent first, then the one the service reported when that was another — or undefined (what
+ * this run read, with its own changes); `note(name, id)` records the id a create is about to be sent with, `observe(name, reportedId)` the id its push
+ * reported, and `clear(name)` removes the dashboard; each answers whether that is now on disk. Each touches only the entry as this run knows it, both ids
+ * compared: `note` does not replace an entry another build recorded or changed since this run read the record (said once; it answers false), and a note
+ * of the id the entry holds already keeps its reported id; `observe` adds only to the entry as this run noted it (said once otherwise); `clear` leaves an
+ * entry another build has changed since, and then answers null — true once this run's entry is gone, false when the change could not be made. `path()`
+ * is the file, for a message. None of them throws: a record that cannot be read or written, or a lease another build holds past the bounded wait, is said
+ * once on `warn`, and a run without a workspace, an environment or a solution (a caller that gives none; the CLI always gives all three) records nothing.
+ * `lease` is for tests: the lib/record-lease.js seams.
+ */
+function openDashboardCreations({ workspaceDir, environment, appUniqueName, solutionUniqueName, warn, lease } = {}) {
+ const usable = Boolean(workspaceDir) && Boolean(environment) && Boolean(solutionUniqueName);
+ let entries;
+ // False once the file was there and could not be read: nothing is written over it.
+ let readable = true;
+ let warned = false;
+ const say = (message) => {
+ if (warned || typeof warn !== 'function') return;
+ warned = true;
+ warn(message);
+ };
+ const where = () => {
+ try { return dashboardCreationRecordPath(workspaceDir, environment, appUniqueName, solutionUniqueName); } catch { return 'the build workspace'; }
+ };
+ const unreadable = (e) => `the record of the dashboards earlier builds created and did not see join solution '${solutionUniqueName}' (${where()}) could not be read (${(e && e.message) || e}), so this build finds dashboards by name, as before, and records none of its own: a dashboard it creates is not found again if it stops before adding it to the solution. Remove the file once you have looked at it`;
+ const notFound = `the dashboard is not found again if this build stops before adding it to solution '${solutionUniqueName}'`;
+ const load = () => {
+ if (entries) return entries;
+ entries = new Map();
+ if (!usable) return entries;
+ try { entries = readDashboardCreations(workspaceDir, environment, appUniqueName, solutionUniqueName); } catch (e) {
+ readable = false;
+ say(unreadable(e));
+ }
+ return entries;
+ };
+ // One change, made under the record's lease to the record as it is on disk now — never to this run's copy, which another build may have changed
+ // since. `apply(disk)` changes the Map it is given and answers true when there is something to write, false when there is not, null when the record
+ // holds the entry as another build changed it and this change leaves it, or the reason this run's change is refused (a string, said once). Answers
+ // true when the change is made, null when another build's entry was left, false otherwise. `create` is false for a removal: a workspace that is not
+ // there holds nothing to remove, and is not made for it.
+ const change = (apply, create = true) => {
+ if (!usable || !readable) return false;
+ let verdict;
+ try {
+ const root = workspaceRoot(workspaceDir, create);
+ if (!root) return true;
+ const file = recordFile(root, environmentFingerprint(environment), lower(appUniqueName), lower(solutionUniqueName));
+ const leased = withRecordLease(root, path.basename(file), () => {
+ let disk;
+ try { disk = readDashboardCreations(workspaceDir, environment, appUniqueName, solutionUniqueName); } catch (e) {
+ // Unreadable now, though this run read it before: from now on it is not written over, as one unreadable at the first read is not (above).
+ readable = false;
+ return unreadable(e);
+ }
+ const answer = apply(disk);
+ if (answer === true) writeDashboardCreations(workspaceDir, environment, appUniqueName, solutionUniqueName, disk);
+ return answer;
+ }, lease);
+ if (!leased.ok) throw new Error(leased.reason);
+ verdict = leased.value;
+ } catch (e) {
+ say(`the record of the dashboards this build creates (${where()}) could not be written (${(e && e.message) || e}): a dashboard it creates is not found again if it stops before adding it to solution '${solutionUniqueName}'`);
+ return false;
+ }
+ if (typeof verdict === 'string') { say(verdict); return false; }
+ return verdict === null ? null : true;
+ };
+ return {
+ idsOf: (name) => {
+ const entry = load().get(dashboardNameKey(name));
+ return entry ? [entry.id, ...(entry.reportedId ? [entry.reportedId] : [])] : undefined;
+ },
+ note: (name, id) => {
+ const sent = idOf(id);
+ if (!usable || !sent) return false;
+ const key = dashboardNameKey(name);
+ let entry = { name: String(name), id: sent };
+ const known = load().get(key);
+ const made = change((disk) => {
+ const held = disk.get(key);
+ // The record holds this create already, and with it the id the service reported for it, when it has one: that observation stays.
+ if (held && held.id === sent) { entry = held; return false; }
+ // Another build recorded or changed this dashboard's entry since this run read the record: that entry may be the only trace of a dashboard a
+ // build created outside its solution — its reported id the row the create made — and replacing it would lose it.
+ if (held && !sameEntry(held, known)) {
+ return `the record of the dashboards builds create (${where()}) already holds '${held.name}' as ${idsText(held)}, which another build recorded since this one read it; it is left as it is, and this build's create of '${entry.name}' (${sent}) is not recorded: ${notFound}`;
+ }
+ disk.set(key, entry);
+ return true;
+ });
+ if (made === true) entries.set(key, entry);
+ return made === true;
+ },
+ observe: (name, reportedId) => {
+ const reported = idOf(reportedId);
+ const key = dashboardNameKey(name);
+ const entry = load().get(key);
+ if (!entry || !reported) return false;
+ if (reported === entry.id || reported === entry.reportedId) return true;
+ const next = { ...entry, reportedId: reported };
+ const made = change((disk) => {
+ const held = disk.get(key);
+ if (sameEntry(held, next)) return false;
+ // Only to the entry as this run noted it: one another build has replaced, removed or given another reported id since is not this run's to change.
+ if (!sameEntry(held, entry)) {
+ return `the record of the dashboards builds create (${where()}) no longer holds '${entry.name}' as ${idsText(entry)} — another build has changed it since this one recorded it — so it is left as it is, and the id the service reported for this build's create (${reported}) is not recorded: ${notFound}`;
+ }
+ disk.set(key, { ...held, reportedId: reported });
+ return true;
+ });
+ if (made === true) entries.set(key, next);
+ return made === true;
+ },
+ clear: (name) => {
+ const key = dashboardNameKey(name);
+ const known = load().get(key);
+ if (!known) return false;
+ const made = change((disk) => {
+ const held = disk.get(key);
+ if (!held) return false;
+ // Only the entry as this run knows it, both ids: one another build has changed since — a reported id it recorded, another create — stays, and
+ // the caller is told (null).
+ if (!sameEntry(held, known)) return null;
+ disk.delete(key);
+ return true;
+ }, false);
+ // Removed, or left as another build changed it: either way this run's own entry is no longer in the record.
+ if (made !== false) entries.delete(key);
+ return made;
+ },
+ path: where,
+ };
+}
+
+module.exports = { PREFIX, openDashboardCreations, readDashboardCreations, writeDashboardCreations, dashboardCreationRecordPath };
diff --git a/plugins/model-apps/scripts/lib/download-column-options.js b/plugins/model-apps/scripts/lib/download-column-options.js
new file mode 100644
index 000000000..cd1f0feff
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/download-column-options.js
@@ -0,0 +1,168 @@
+'use strict';
+
+const { mapLimit } = require('./entity-provision.js');
+const { odataLit } = require('./odata.js');
+const { INTEGER_FORMATS } = require('./app-spec.js');
+
+// These are the vendored SDK's create defaults, not Maker's defaults. A download leaves them
+// implicit so an ordinary column does not acquire options its author never needed to write.
+// The real-bundle round-trip tests compare the resulting definitions, including these defaults.
+const DEFAULTS = {
+ Text: { maxLength: 100, format: 'Text' },
+ Memo: { maxLength: 2000 },
+ Integer: { minValue: -2147483648, maxValue: 2147483647, integerFormat: 'None' },
+ Decimal: { minValue: -1e11, maxValue: 1e11, precision: 2 },
+ Double: { minValue: -1e11, maxValue: 1e11, precision: 2 },
+ Money: { minValue: 0, maxValue: 1e9, precision: 2 },
+ DateTime: { dateFormat: 'DateAndTime' },
+ Boolean: { trueLabel: 'Yes', falseLabel: 'No' },
+};
+
+const TYPE_BY_NAME = {
+ StringType: 'Text', MemoType: 'Memo', IntegerType: 'Integer', DecimalType: 'Decimal',
+ DoubleType: 'Double', MoneyType: 'Money', DateTimeType: 'DateTime', BooleanType: 'Boolean',
+};
+const TYPE_BY_ATTRIBUTE = {
+ String: 'Text', Memo: 'Memo', Integer: 'Integer', Decimal: 'Decimal', Double: 'Double',
+ Money: 'Money', DateTime: 'DateTime', Boolean: 'Boolean',
+};
+const CASTS = [
+ { type: 'Text', cast: 'String', select: 'LogicalName,MaxLength,FormatName,AutoNumberFormat' },
+ { type: 'Memo', cast: 'Memo', select: 'LogicalName,MaxLength' },
+ { type: 'Integer', cast: 'Integer', select: 'LogicalName,MinValue,MaxValue,Format' },
+ { type: 'Decimal', cast: 'Decimal', select: 'LogicalName,MinValue,MaxValue,Precision' },
+ { type: 'Double', cast: 'Double', select: 'LogicalName,MinValue,MaxValue,Precision' },
+ { type: 'DateTime', cast: 'DateTime', select: 'LogicalName,Format' },
+];
+
+function columnType(attribute) {
+ const name = attribute && ((attribute.AttributeTypeName && attribute.AttributeTypeName.Value) || attribute.attributeTypeName);
+ const fallback = attribute && (attribute.attributeType || attribute.AttributeType);
+ return Object.hasOwn(TYPE_BY_NAME, name) ? TYPE_BY_NAME[name]
+ : Object.hasOwn(TYPE_BY_ATTRIBUTE, fallback) ? TYPE_BY_ATTRIBUTE[fallback] : undefined;
+}
+
+function logicalName(attribute) {
+ return String((attribute && (attribute.logicalName || attribute.LogicalName)) || '').toLowerCase();
+}
+
+// A heterogeneous Attributes collection cannot select MaxLength, FormatName, MinValue, etc.:
+// .../Attributes/Microsoft.Dynamics.CRM.IntegerAttributeMetadata?$select=LogicalName,MinValue,MaxValue,Format
+// -> { "value": [{ "LogicalName": "contoso_minutes", "MinValue": 0, "MaxValue": 60, "Format": "Duration" }] }
+// Read only types this table actually declares, never its audit columns or lookup/choice shadows.
+// Money's detail rides on the existing base-currency read; Boolean labels already ride on the
+// SDK's choices projection. BigInt's range is deliberately not read: the SDK cannot create it.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/query-metadata-web-api
+async function readColumnOptions(sdk, logical, attributes, concurrency) {
+ const authored = (attributes || []).filter((a) => a && a.isCustomAttribute !== false && a.IsCustomAttribute !== false
+ && !a.AttributeOf && !a.attributeOf && a.IsLogical !== true && a.isLogical !== true && a.IsBaseCurrency !== true);
+ const present = new Set(authored.map(columnType).filter(Boolean));
+ const results = await mapLimit(CASTS.filter((c) => present.has(c.type)), concurrency, async ({ type, cast, select }) => {
+ try {
+ const res = await sdk.dataverse.get(`/EntityDefinitions(LogicalName='${odataLit(logical)}')/Attributes/Microsoft.Dynamics.CRM.${cast}AttributeMetadata?$select=${select}`);
+ 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');
+ return { type, rows: res.body.value };
+ } catch (err) {
+ return { type, failed: (err && err.message) ? String(err.message).slice(0, 200) : 'read failed' };
+ }
+ }, { firstInOrder: true });
+ const rows = new Map();
+ const failures = [];
+ for (const r of results) {
+ if (r.failed) { failures.push(`${r.type}: ${r.failed}`); continue; }
+ const byName = new Map(r.rows.filter((a) => a && a.LogicalName).map((a) => [logicalName(a), a]));
+ for (const attribute of authored.filter((a) => columnType(a) === r.type)) {
+ const name = logicalName(attribute);
+ const row = byName.get(name);
+ if (!row) { failures.push(`${r.type} ${name}: its row was missing`); continue; }
+ rows.set(name, row);
+ const missing = [];
+ columnOptionFields(row, r.type, missing);
+ failures.push(...missing.map((detail) => `${r.type} ${name}: ${detail}`));
+ }
+ }
+ for (const attribute of authored.filter((a) => ['Money', 'Boolean'].includes(columnType(a)))) {
+ const type = columnType(attribute);
+ const missing = [];
+ columnOptionFields(attribute, type, missing);
+ failures.push(...missing.map((detail) => `${type} ${logicalName(attribute)}: ${detail}`));
+ }
+ return { rows, failures };
+}
+
+function columnOptionFields(attribute, type, omitted = []) {
+ const a = attribute || {};
+ const fields = {};
+ const defaults = DEFAULTS[type] || {};
+ const keep = (key, value) => {
+ if (value !== undefined && value !== null && value !== defaults[key]) fields[key] = value;
+ };
+ if (type === 'Text' || type === 'Memo') {
+ const length = a.MaxLength !== undefined ? a.MaxLength : a.maxLength;
+ if (Number.isInteger(length) && length > 0) keep('maxLength', length);
+ else omitted.push('maxLength was missing or not a positive whole number');
+ }
+ if (type === 'Text') {
+ const format = a.FormatName && a.FormatName.Value;
+ if (typeof a.AutoNumberFormat === 'string' && a.AutoNumberFormat.trim()) {
+ // AutoNumber is a StringAttributeMetadata with AutoNumberFormat, not a distinct API type.
+ // Its length/format cannot be authored through columnOptions, so do not pretend otherwise.
+ return { type: 'AutoNumber', autoNumberFormat: a.AutoNumberFormat };
+ }
+ if (typeof format === 'string' && format.trim()) keep('format', format);
+ else omitted.push('format was missing or not a format name');
+ if (a.AutoNumberFormat === undefined || (a.AutoNumberFormat !== null && typeof a.AutoNumberFormat !== 'string')) {
+ omitted.push('autoNumberFormat was missing or malformed');
+ }
+ }
+ if (['Integer', 'Decimal', 'Double', 'Money'].includes(type)) {
+ for (const [key, raw] of [['minValue', 'MinValue'], ['maxValue', 'MaxValue']]) {
+ if (typeof a[raw] === 'number' && Number.isFinite(a[raw]) && (type !== 'Integer' || Number.isInteger(a[raw]))) keep(key, a[raw]);
+ else omitted.push(`${key} was missing or not a finite ${type === 'Integer' ? 'whole ' : ''}number`);
+ }
+ }
+ // Money PrecisionSource selects column (0), organization pricing (1) or transaction currency
+ // (2). The SDK always creates 2, so carrying Precision alone for 0/1 would silently change
+ // what controls the column. Source 2 keeps numeric metadata, not a promise that the target's
+ // currencies have the same effective precision.
+ // See: https://learn.microsoft.com/en-us/dotnet/api/microsoft.xrm.sdk.metadata.moneyattributemetadata.precisionsource
+ if (type === 'Money' && a.PrecisionSource !== 2) {
+ const source = a.PrecisionSource === 0 ? 'PrecisionSource 0 (column precision) is unsupported'
+ : a.PrecisionSource === 1 ? 'PrecisionSource 1 (organization pricing precision) is unsupported'
+ : 'PrecisionSource was missing, malformed or unknown';
+ omitted.push(`${source}; the build always creates PrecisionSource 2 (transaction currency), so precision was omitted. Check and configure the required precision source in Power Apps on the target`);
+ } else if (['Decimal', 'Double', 'Money'].includes(type)) {
+ if (Number.isInteger(a.Precision) && a.Precision >= 0) keep('precision', a.Precision);
+ else omitted.push('precision was missing or not a non-negative whole number');
+ }
+ if (type === 'Integer') {
+ if (INTEGER_FORMATS.includes(a.Format)) keep('integerFormat', a.Format);
+ else omitted.push('integerFormat was missing or is not supported by the build');
+ }
+ if (type === 'DateTime') {
+ if (['DateOnly', 'DateAndTime'].includes(a.Format)) keep('dateFormat', a.Format);
+ else omitted.push('dateFormat was missing or is not supported by the build');
+ }
+ if (type === 'Boolean') {
+ for (const [key, value] of [['trueLabel', 1], ['falseLabel', 0]]) {
+ const option = (Array.isArray(a.choices) ? a.choices : []).find((o) => o && o.value === value);
+ if (option && typeof option.label === 'string' && option.label.trim()) keep(key, option.label);
+ else omitted.push(`${key} could not be read`);
+ }
+ }
+ return fields;
+}
+
+function primaryColumnOptionFields(attribute) {
+ const length = attribute && (attribute.MaxLength !== undefined ? attribute.MaxLength : attribute.maxLength);
+ const format = attribute && attribute.AutoNumberFormat;
+ return {
+ // A primary length must stay explicit even at 100: some environments ignore the create's
+ // length, and the post-create correction runs only when primaryAttribute.maxLength is present.
+ ...(Number.isInteger(length) && length > 0 ? { maxLength: length } : {}),
+ ...(typeof format === 'string' && format.trim() ? { autoNumberFormat: format } : {}),
+ };
+}
+
+module.exports = { readColumnOptions, columnOptionFields, primaryColumnOptionFields };
diff --git a/plugins/model-apps/scripts/lib/entity-provision.js b/plugins/model-apps/scripts/lib/entity-provision.js
index 0cc71126c..ab4276fb0 100644
--- a/plugins/model-apps/scripts/lib/entity-provision.js
+++ b/plugins/model-apps/scripts/lib/entity-provision.js
@@ -32,7 +32,7 @@ const {
maxLengthSent,
PRIMARY_NAME_MAX_LENGTH,
} = require('./app-spec.js');
-const { readColumnLabels, makeTableLabelReader, lookupKey } = require('./lookup-labels.js');
+const { readColumnLabels, makeTableLabelReader, lookupKey, labelsByLcid } = require('./lookup-labels.js');
const { topoOrderEntities, entityByLogical } = require('./_graph.js');
// OData string-literal escaping for spec-controlled values interpolated into $filter (a solution
// uniquename / publisher prefix with a `'` would otherwise break the query or inject a clause).
@@ -46,9 +46,10 @@ const { readRelationshipsOf, findRelationshipHolder, compareRelationship, descri
const { readOrgLanguageCode, readProvisionedLanguages } = require('./dataverse-auth.js');
// The build's retry policy (see the header of retry-policy.js): every halt below says what a run again may do, decided where it is raised, and every failure this engine raises itself is made by
// refusal() (deterministic) or serviceFailure() (the plugin's words around a failure of the service) — never a bare `new Error`, whose message the build's retry would read.
-const { RETRY, retryPolicyFor, refusal, serviceFailure } = require('./retry-policy.js');
+const { RETRY, retryPolicyFor, refusal, serviceFailure, serviceCodeOf } = require('./retry-policy.js');
// What the run's throttle budget says when it refuses a wait (the words of the build's own halt for it), for the step guard in makeRunner.
const { waitDoesNotFit } = require('./throttle-budget.js');
+const { readStatusOptions, alternateKeyMatches } = require('./table-schema-metadata.js');
// App Spec column type -> SDK ColumnType. Lookup is omitted (side effect of a OneToMany
// relationship); Customer is handled specially (createCustomerColumn).
@@ -526,12 +527,13 @@ async function checkOwedTable({ provision, debt, logical, primaryLogical, asked
// the one the debt was recorded for (checkOwedTable, or a request addressed by its ids that answered 404), which is left alone. A step the runner stopped before it began (`notStarted: true`, with the stop as `error`, and the column's
// id as above) is neither a length that was set nor an update that failed: nothing was sent, and the table is owed the length as it was.
//
-// It is the LAST thing the data-model phase does (provisionDataModel calls it once every table, column, status reason, alternate
-// key and relationship has been created), not the first thing after the table. The SDK's updateColumn starts by reading the column
+// This runs at the end of the phase, after tables, columns, new tables' status reasons, relationships and keys that need no length,
+// not immediately after each table. Deferred keys and existing tables' status reasons follow it. The SDK's updateColumn starts by reading the column
// WITH its labels, and a label-bearing metadata read ahead of a labelled create is what makes Dataverse keep only the base-language
// label of what is created (measured live — see findExistingColumns, which is why the reads that precede a create in this file are
-// narrow). That read is inside the SDK and cannot be narrowed, so it goes where nothing labelled is created after it — within one
-// attempt. The build runs a phase that halts on a transient answer (a 429, a lock) again (build-model-app.js): the attempt that
+// narrow). That read is inside the SDK and cannot be narrowed. Deferred keys have their own label/length ordering rules; status
+// reasons accept only a single label, with no other languages for this read to strip. The build runs a phase that halts on a
+// transient answer (a 429, a lock) again (build-model-app.js): the attempt that
// created the table sets its length by then, because this runs after a halt too. When that step fails as well — the lock that
// stopped the phase can still be held — the table is OWED its length: the halt carries a record of it (`owedLengths`, see
// runSdkBuild) the way it carries the publishes an attempt owes for the views it saved, and the retry, which finds the table, sets
@@ -987,6 +989,17 @@ async function confirmInlineColumns(provision, table, columns, { warn, sleep, at
const STATE_CODE = { Active: 0, Inactive: 1 };
+// The state and the value the build gives each of a table's declared status reasons, in the spec's order: the declared state (Active
+// unless it says Inactive; any other word has always read as Active) and the declared `value`, else 100000000 + the reason's place in the
+// list. The data-model phase inserts each at these, and verify (lib/status-reasons-keys.js) holds a deployed reason to the same two.
+function statusReasonTargets(entity) {
+ return ((entity && entity.statusReasons) || []).map((statusReason, index) => ({
+ statusReason,
+ stateCode: STATE_CODE[statusReason.state] !== undefined ? STATE_CODE[statusReason.state] : 0,
+ value: typeof statusReason.value === 'number' ? statusReason.value : 100000000 + index,
+ }));
+}
+
// A halt the build stops with. `retry` is the halt's policy for the build's own re-run (retry-policy.js), decided where it is raised: RETRY.NEVER (a run again cannot change it — marks the halt
// `transient: false`, which the retry check has always read) or RETRY.SERVICE (it wraps a failure of the service: the status and words of that failure decide, never this halt's message, which quotes
// what the maker named). `retryText` is what the halt declares as the service's own words, `statusCode` the status the service answered, when a halt has no failure to carry them as its `cause`.
@@ -1047,15 +1060,91 @@ function causeChain(err, maxDepth = 6) {
return chain;
}
+// The Dataverse error codes that say what a create asked for ALREADY EXISTS, for each create that reads such an answer (isAlreadyExists).
+// The platform words an answer in the caller's language, so its words cannot be what decides on an environment that is not in English:
+// live, on one whose only language is Spanish, an alternate key created again was answered (names replaced)
+// HTTP 400 {"error":{"code":"0x80060893","message":"Ya existe una clave de entidad con el nombre contoso_codekey en la entidad contoso_project."}}
+// and the rebuild halted, because only the English words below were read. The code is the same in every language. A code is listed only
+// for the create that answers it, and only where the platform's reference gives it an "already exists" meaning for what that create
+// makes — never a generic code such as 0x80040216 ("An unexpected error occurred."), and never a neighbouring condition: a key over the
+// same columns under another name (0x80060894, EntityKeyWithSelectedAttributesExists — the declared key is not there), a record that
+// already holds a key's values (0x80060892). Two codes are broader than the thing created — the name or the navigation property they speak
+// of can be held by something else — and each is listed for one create only, where a read that follows the refusal decides: 0x80044363
+// (SchemaNameisNotUnique) for the table create, 0x80072551 (NavigationPropertyAlreadyExists) for the 1:N relationship create. A listed
+// code is taken exactly as the English words of the same refusal are, and proves no more than they do: a status reason, a key or a column
+// is skipped on it (a column's code can name a companion the platform makes beside the column, as its words can), and for a table or a
+// relationship it is only the cue to read what exists, which alone decides what is reused. The lists only ADD recognition:
+// isAlreadyExists keeps its 409 and English-word rules unchanged, and they still read an answer whatever code it carries, an unlisted one
+// included — an English 0x80060894 answer ("An entity key with the selected attributes already exists on entity.") is still a skip, as it
+// always was. Names and messages are the platform's reference:
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/web-service-error-codes
+// Lower case, because serviceCodeOf (lib/retry-policy.js) lower-cases what it reads: the platform writes a code in either case (the
+// reference spells 0x8004432B with a capital).
+const ALREADY_EXISTS_CODES = Object.freeze({
+ // POST EntityDefinitions. Live-captured, the create of a table that exists (names replaced; the server's stack trace that follows cut):
+ // HTTP 400 {"error":{"code":"0x80044363","message":"Failed to create entity with logical name contoso_project and object type code -1.
+ // Exception: Microsoft.Crm.CrmException: The schema name contoso_project for type Entity is not unique. An contoso_project with same name
+ // already exists.\r\n at Microsoft.Crm.Metadata.SchemaNameValidator.ValidateSchemaNameIsUnique(…)…"}}
+ // SchemaNameisNotUnique speaks of a schema name, which a component of another kind can hold too. Another environment answered the same
+ // create HTTP 400 {"error":{"code":"0x8009050d","message":"Entities already exist: contoso_Project."}} — a code the reference does not list —
+ // and the reference has InvalidSchemaName, 0x8004700b, "An entity with the specified name already exists. Please specify a unique name.".
+ // None of them is a proof: the build reads the table again and takes it only when that read finds it (findExistingTable); a name held by
+ // anything but a table finds no table there, and the create's own error stops the build.
+ table: Object.freeze(new Set(['0x80044363', '0x8009050d', '0x8004700b'])),
+ // POST EntityDefinitions(…)/Attributes, and a Customer column's POST CreateCustomerRelationships: DuplicateAttributeSchemaName, 0x80047013 —
+ // live-captured, the same answer for each of 17 columns of 13 types (Text, Memo, Integer, Decimal, Double, Money, Boolean, DateTime, Choice,
+ // MultiChoice, AutoNumber, File, Image; a Customer column's answer, to CreateCustomerRelationships, was not captured):
+ // HTTP 400 {"error":{"code":"0x80047013","message":"An attribute with the specified name contoso_code already exists for entity contoso_project."}}
+ // — and DuplicateAttributePhysicalName, 0x80060304, "Attribute {0} already exists for entity {1}.".
+ column: Object.freeze(new Set(['0x80060304', '0x80047013'])),
+ // POST InsertStatusValue, which the build sends with the reason's pinned value: PicklistValueNotUnique, 0x80044310, "The picklist value already
+ // exists. Picklist values must be unique." Live-captured: HTTP 400 {"error":{"code":"0x80044310","message":"The picklist or status value 100000000
+ // is invalid for optionSet <id> because another picklist or status option for this optionSet already exists with that value"}}.
+ statusReason: Object.freeze(new Set(['0x80044310'])),
+ // POST EntityDefinitions(…)/Keys: EntityKeyNameExists, 0x80060893, "An entity key with the name {0} already exists on entity {1}." — live-captured
+ // in English and in Spanish (above).
+ alternateKey: Object.freeze(new Set(['0x80060893'])),
+ // POST RelationshipDefinitions of a 1:N. Live-captured, the create of a 1:N that exists (names replaced):
+ // HTTP 400 {"error":{"code":"0x80072551","message":"NavigationPropertyName contoso_project_contoso_task is not unique within an entity"}}
+ // NavigationPropertyAlreadyExists: the navigation property the create names after the relationship's schema name is already on the table —
+ // the declared relationship's, or another relationship's. None of the English words matched it, so such a relationship stopped the build in
+ // every language. Also the reference's EntityRelationshipSchemaNameNotUnique, 0x8004432b, "A relationship with the specified name already
+ // exists. Please specify a unique name." (not what the create of an existing 1:N was answered live), and the column codes above, for the
+ // lookup column a 1:N create makes. None of them is a proof: the build reads the relationship that holds the name, or the one that owns the
+ // lookup column, and reuses only the declared one (compareRelationship); any other stops the build.
+ oneToManyRelationship: Object.freeze(new Set(['0x80072551', '0x8004432b', '0x80060304', '0x80047013'])),
+ // POST RelationshipDefinitions of an N:N: the reference's name code only, read the same way (the whole identity of the N:N, the table that
+ // holds its links included). The answer to the create of an existing N:N has not been captured. An N:N names a navigation property on each
+ // of its tables (Entity1NavigationPropertyName, Entity2NavigationPropertyName) and makes the attributes of the table that holds its links,
+ // so 0x80072551 or a column code may answer it too; neither is listed until such an answer is seen, and an N:N refused with one stops the
+ // build unless the 409 or the English words read it.
+ // See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/manytomanyrelationshipmetadata
+ manyToManyRelationship: Object.freeze(new Set(['0x8004432b'])),
+});
+const NO_CODES = Object.freeze(new Set());
+
// A metadata create that fails because the component already exists (the classic re-run
-// case). Dataverse answers 409, or 400 with a duplicate-name message. Used to make
-// otherwise non-idempotent creates (e.g. alternate keys — the SDK has no key lister) safe
-// to re-run: the build skips instead of halting. Kept deliberately narrow so a genuine
-// failure (bad key attribute, etc.) still surfaces.
-function isAlreadyExists(err) {
+// case). Used to make otherwise non-idempotent creates (e.g. alternate keys — the SDK has no
+// key lister — and a status reason's pinned value) safe to re-run: the build skips instead of
+// halting, or, for a table and a relationship, reads what exists. Such an answer is recognised by
+// an HTTP 409, by an OData `error.code` that is one of `codes` — the create's own list in
+// ALREADY_EXISTS_CODES — or by the English words below. The SDK keeps the OData answer as the
+// `cause` of the ConnectionError it throws:
+// ConnectionError {
+// code: 'CONNECTION_ERROR', statusCode: 400, url: "https://contoso.crm.dynamics.com/api/data/v9.0/EntityDefinitions(LogicalName='contoso_project')/Keys",
+// message: 'HTTP 400 from <url>: Ya existe una clave de entidad con el nombre contoso_codekey en la entidad contoso_project.',
+// cause: { error: { code: '0x80060893', message: 'Ya existe una clave de entidad con el nombre contoso_codekey en la entidad contoso_project.' } } }
+// and serviceCodeOf reads that `error.code` of THIS error's own answer: never a code its message only quotes, and never one further
+// down a chain — an SDK error that wraps another failure (COLUMN_VISUALIZATION_BIND_FAILED around a binding that failed after the
+// column WAS made) carries a code that is not the create's. The code only ADDS recognition: the 409 and English-word rules are
+// the ones this function always had, and they apply whatever code the answer carries — a code of another create, a generic code or
+// a code the message only quotes does not count by itself, and does not stop the words from counting either. Kept deliberately
+// narrow so a genuine failure (bad key attribute, etc.) still surfaces.
+function isAlreadyExists(err, codes = NO_CODES) {
if (!err) return false;
const status = err.statusCode || err.status || (err.cause && (err.cause.statusCode || err.cause.status));
if (status === 409) return true;
+ if (codes.has(serviceCodeOf(err))) return true;
const msg = String((err && err.message) || '').toLowerCase();
// "already exist" (no trailing 's') also catches the plural table-create message
// "Entities already exist: <name>" that Dataverse returns on a transient-retry duplicate.
@@ -1381,12 +1470,19 @@ function makeRunner({ emit, total, throttle }) {
// How an operator resets a workspace by hand, where the build cannot do it itself. Most of `.maker-workspace`
// is state a re-run rebuilds — the SDK's copies are re-read from the environment, and without the
-// changed-only snapshot the next `--changed-only` run just does a full build — but three kinds of file record
+// changed-only snapshot the next `--changed-only` run just does a full build — but five kinds of file record
// things the environment cannot give back:
// - last-applied.json, what was last applied or downloaded: the baseline that keeps a nav change made in
// the designer from being reverted by a stale spec (AB#6726727);
// - destructive-approval.json, the removals a maker approved: without it the next --allow-destructive
// authorizes whatever that run finds, not what was shown;
+// - web-resource-unconfirmed.*.json, the durable ids of resources whose publication could not be
+// confirmed: without them a re-run can retry a duplicate create or silently reuse stale published
+// content instead of rewriting the known row and verifying what it publishes;
+// - dashboard-creation.*.json, the ids of the dashboards an interrupted build created and did not see join the
+// solution (lib/dashboard-creation-records.js): without them the next build cannot find a dashboard that was
+// never published, creates a second one, and the first stays outside the solution — kept by teardown, left out
+// of a solution export;
// - page-ownership.*.json, the receipts of the pages this app created, the records of pages a teardown is
// deleting, and the `pending` records of page creates that were started and never answered. A pending
// record is the only trace of a page that may still land: without it the next build creates a second page
@@ -1395,7 +1491,7 @@ function makeRunner({ emit, total, throttle }) {
// And the changed-only snapshot can hold a RUNNING teardown's registration and a build's lease, which are
// that run's guard against a concurrent one: deleting them under a live run removes it. Every remedy that
// resets the workspace says exactly this.
-const RESET_WORKSPACE = 'stop any other build or teardown using the .maker-workspace directory (or the --workspace one), then delete everything in it except last-applied.json, destructive-approval.json and the page-ownership.*.json records (the receipts and pending records of the pages the app created: nothing else can find them)';
+const RESET_WORKSPACE = 'stop any other build or teardown using the .maker-workspace directory (or the --workspace one), then delete everything in it except last-applied.json, destructive-approval.json, web-resource-unconfirmed.*.json (the durable ids needed to recover unconfirmed web-resource writes), dashboard-creation.*.json (the ids of the dashboards an interrupted build created before they joined the solution) and the page-ownership.*.json records (the receipts and pending records of the pages the app created: nothing else can find them)';
// Some SDK refusals end with the SDK call that fixes them — `fetchArtifact(...)` — which an operator of this
// plugin cannot make. Where the operator's step is known, the halt names it too.
@@ -1624,12 +1720,14 @@ async function resolveAuthoringLanguage({ envUrl, languageCode, spec, warn, read
// 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 } = {}) {
+async function findExistingTable(provision, schemaName, { hasLocalizedLabels = false, attempts = 3, includeKeys = false } = {}) {
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`;
+ // Keys' identities are scalars, so they can ride this already-required probe
+ // without a label-bearing read ahead of a localized create.
+ const url = `/EntityDefinitions(LogicalName='${escaped}')?$select=LogicalName,EntitySetName${includeKeys ? '&$expand=Keys($select=SchemaName,KeyAttributes)' : ''}`;
// 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.
@@ -1646,7 +1744,10 @@ async function findExistingTable(provision, schemaName, { hasLocalizedLabels = f
lastFailure = undefined;
try { res = await raw.get(url); } catch (err) { res = null; lastFailure = err; 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 };
+ return {
+ logicalName: String(res.body.LogicalName).toLowerCase(), entitySetName: res.body.EntitySetName,
+ ...(includeKeys && Array.isArray(res.body.Keys) ? { keys: res.body.Keys } : {}),
+ };
}
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' : ''}`; lastStatus = res.status; }
@@ -1718,18 +1819,43 @@ async function provisionDataModel(args) {
// The tables an EARLIER attempt left unset, as the phase found them: one this attempt creates again is not among them.
const carriedIn = new Set(owed.keys());
const waitingKeys = [];
+ const waitingStatuses = [];
let result;
try {
- result = await provisionDataModelSteps(args, { owed, carriedIn, waitingKeys });
+ result = await provisionDataModelSteps(args, { owed, carriedIn, waitingKeys, waitingStatuses });
} catch (err) {
await payOwedLengths(args, owed, carriedIn, { halted: true, waitingKeys });
throw err;
}
const outcomes = await payOwedLengths(args, owed, carriedIn, { halted: false, waitingKeys });
await createWaitingKeys(args, waitingKeys, outcomes);
+ // Option labels must be read only AFTER every labelled schema create (including deferred keys).
+ // Reading them inside the table loop can strip later creates' non-base-language labels.
+ for (const status of waitingStatuses) await applyStatusReasons(args, status, result, true);
return result;
}
+async function applyStatusReasons({ sdk, provision, runner, warn }, { entity, logical, languageCode }, result, checkExisting = false) {
+ const read = checkExisting ? await readStatusOptions(provision && provision.dataverse, logical) : {};
+ if (read.failed && typeof warn === 'function') {
+ warn(`could not read status reasons for ${logical} (${read.failed}); using the duplicate-protected insert instead`);
+ }
+ for (const { statusReason: sr, stateCode, value: pinned } of statusReasonTargets(entity)) {
+ (result.statusReasonValues[logical] = result.statusReasonValues[logical] || {})[sr.label] = { value: pinned, stateCode };
+ const same = (read.options || []).some((o) => o && o.Value === pinned && o.State === stateCode
+ && labelsByLcid(o.Label)[languageCode] === sr.label
+ && (sr.color === undefined || o.Color === sr.color));
+ if (same) {
+ runner.skip('data-model', `status reason ${entity.schemaName}: ${sr.label} (exists — reuse)`);
+ continue;
+ }
+ await runner.run('data-model', `status reason ${entity.schemaName}: ${sr.label}`, async () => {
+ const value = await sdk.insertStatusValue(logical, { label: sr.label, stateCode, color: sr.color, value: pinned, languageCode });
+ result.statusReasonValues[logical][sr.label] = { value: typeof value === 'number' ? value : pinned, stateCode };
+ }, { recoverable: true, skipIf: (err) => isAlreadyExists(err, ALREADY_EXISTS_CODES.statusReason) });
+ }
+}
+
// Sets the primary name column length of every table the phase owes one, in table order — the length steps are the last the phase
// takes — and answers what each came to: `Map<logical name, { ok, error?, left? }>`, for the keys that wait for them. A table whose length
// is right comes out of `owed`; so does one that turned out not to be the table the debt was recorded for (`left`: it is left alone, see
@@ -1770,7 +1896,7 @@ async function payOwedLengths({ runner, sdk, provision, spec, warn, sleep }, owe
function alternateKeyStep({ runner, sdk, entity, logical, key, languageCode }) {
return runner.run('data-model', `alt key ${entity.schemaName}.${key.schemaName}`,
() => sdk.createAlternateKey(logical, { schemaName: key.schemaName, displayName: key.displayName || key.schemaName, keyAttributes: (key.columns || []).map((x) => x.toLowerCase()), languageCode }),
- { recoverable: true, skipIf: isAlreadyExists });
+ { recoverable: true, skipIf: (err) => isAlreadyExists(err, ALREADY_EXISTS_CODES.alternateKey) });
}
// What the build can tell of an alternate key over a table's name column with that column at the length the spec asks — the one wording every
@@ -1941,7 +2067,7 @@ async function settleOwedLengths({ sdk, provision, spec, owed, warn, sleep } = {
// `owed` is the Map provisionDataModel keeps (see there): this attempt's tables whose length is to be set, and those an earlier attempt
// left unset. `carriedIn` is the set of the second kind as the phase found them; `waitingKeys` collects the alternate keys that wait for
// a length step, for createWaitingKeys to make once the steps have run.
-async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, languageCode, warn, provisionedLanguages, preResolvedLanguageCode, sleep, reconcileLookupLabels = false, inlineColumns = true }, { owed, carriedIn, waitingKeys }) {
+async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, languageCode, warn, provisionedLanguages, preResolvedLanguageCode, sleep, reconcileLookupLabels = false, inlineColumns = true }, { owed, carriedIn, waitingKeys, waitingStatuses }) {
// `lookupLabels` records the label each spec lookup column carries once this phase is done
// (`<referencing>|<lookup logical>` -> { label }), so a later phase that repairs something derived
// from it — an existing form's cell label — repairs it to what the column now says.
@@ -1961,7 +2087,6 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la
await checkLocalizedLabelLanguages(spec, provisionedLanguages);
const globalChoiceIds = result.globalChoiceIds;
- const statusReasonValues = result.statusReasonValues;
// The declared tables (lower-case logical names) this run found already in the environment, as opposed
// to the ones it created. A lookup to one that sets no displayName of its own is named by the
// environment (lookupParentNeedsEnvironment), which only the table loop below can know.
@@ -1988,7 +2113,9 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la
// 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 hits = await findExistingTable(provision, e.schemaName, {
+ hasLocalizedLabels: entityIsLocalized, includeKeys: !!(e.alternateKeys && e.alternateKeys.length),
+ });
const existingTable = hits;
// Every buildable column: all scalar types + Customer (a Lookup comes from a relationship).
const buildable = (e.columns || []).filter((c) => SDK_COLUMN_TYPE[c.type || 'Text'] || c.type === 'Customer');
@@ -2066,7 +2193,7 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la
// The SDK says of this refusal that the table WAS created. What its cause carries — a 409 from the update, a word in the platform's reason —
// is no sign that the table's name is taken, so it is never taken for an already-exists answer and "rediscovered".
if (err && err.code === 'PRIMARY_COLUMN_REQUIRED_NOT_APPLIED') throw err;
- if (!isAlreadyExists(err)) throw err;
+ if (!isAlreadyExists(err, ALREADY_EXISTS_CODES.table)) throw err;
// First POST likely succeeded server-side; a transient-network retry hit "already exists".
// 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.
@@ -2149,7 +2276,7 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la
() => inlineConfirmed.get(c) || (c.type === 'Customer'
? sdk.createCustomerColumn(logical, { schemaName: c.schemaName, displayName: c.displayName || c.schemaName, required: REQUIRED(c), languageCode: resolvedLanguageCode })
: sdk.createColumn(logical, columnOptions(c, globalChoiceIds, spec.globalChoices, resolvedLanguageCode))),
- { skipIf: isAlreadyExists }));
+ { skipIf: (err) => isAlreadyExists(err, ALREADY_EXISTS_CODES.column) }));
if (existingTable) {
const existingColMeta = new Map(existingColRows.map((c) => [String(c.logicalName || c.schemaName || '').toLowerCase(), c]));
const requiredTargets = requiredDeclared.filter((c) => existingCols.has(c.schemaName.toLowerCase()));
@@ -2202,19 +2329,17 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la
// Deliberately a SEPARATE block from the `required` reconcile above rather than folded into
// it, and with a DIFFERENT strategy: `required` reads the column's CURRENT level first so it
// can skip a no-op update and, more importantly, avoid demoting an omitted value (a maker may
- // have set Business Required by hand, and the spec staying silent must not undo that). These
- // three have no equivalent maker-authored surface to protect, and `updateColumn` performs its
- // own GET-mutate-PUT round trip per call (measured against the vendored bundle — replaying an
- // already-correct value is a harmless no-op on the wire), so they are simply RE-ASSERTED
- // whenever the spec sets them explicitly — the same no-pre-read-diff strategy already used by
- // `setColumnVisualization` below for the same reason.
+ // have set Business Required by hand, and the spec staying silent must not undo that).
+ // Capabilities are re-asserted through the SDK's GET-mutate-PUT. A standalone Integer format
+ // is the exception below: downloads now carry it, so compare that scalar without labels to
+ // avoid writing an unchanged column on every download/rebuild.
//
// Customer columns are excluded outright, not merely skipped for these three fields:
// `updateColumn` refuses ANY change to a Customer column (measured — it throws "type
// 'Customer' not supported"), because Customer has no entry in the SDK's attribute-type ->
// OData-cast table (it is created through the wholly separate createCustomerColumn instead).
const capabilityTargets = capabilityDeclared.filter((c) => existingCols.has(c.schemaName.toLowerCase()));
- await runner.mapLimit(capabilityTargets, 1, (c) => {
+ await runner.mapLimit(capabilityTargets, 1, async (c) => {
const columnLogical = c.schemaName.toLowerCase();
const opts = {};
// Same type gates as columnOptions() above (Boolean-only / Integer-only): the SDK's update
@@ -2228,6 +2353,18 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la
if (c.isValidForCreate !== undefined) opts.isValidForCreate = c.isValidForCreate;
if (c.isValidForUpdate !== undefined) opts.isValidForUpdate = c.isValidForUpdate;
if (c.isValidForRead !== undefined) opts.isValidForRead = c.isValidForRead;
+ // A downloaded Whole Number format is an instruction to preserve it, not a reason to
+ // PUT an unchanged definition on every rebuild. This scalar read replaces updateColumn's
+ // own GET on a no-op; a real edit still takes the SDK's read-mutate-write path.
+ if (Object.keys(opts).length === 1 && opts.integerFormat !== undefined && provision.dataverse && typeof provision.dataverse.get === 'function') {
+ try {
+ const current = await provision.dataverse.get(`/EntityDefinitions(LogicalName='${odataLit(logical)}')/Attributes(LogicalName='${odataLit(columnLogical)}')/Microsoft.Dynamics.CRM.IntegerAttributeMetadata?$select=Format`);
+ if (current && current.status >= 200 && current.status < 300 && current.body && current.body.Format === opts.integerFormat) {
+ runner.skip('data-model', `column capabilities ${e.schemaName}.${c.schemaName} (already ${opts.integerFormat})`);
+ return;
+ }
+ } catch { /* an inconclusive proof keeps the SDK's existing update behaviour */ }
+ }
return runBestEffort(
runner,
'data-model',
@@ -2309,20 +2446,16 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la
// (publisher range 100000000+i, matching how the engine assigns choice/global option values;
// authors may override via sr.value) and pass it explicitly: a re-run then hits an already-exists
// error that skipIf turns into a skip (no duplicate), while the value stays captured for sample
- // data. On a fresh insert we overwrite with the server-returned value (authoritative).
- let srIdx = 0;
- for (const sr of e.statusReasons || []) {
- const stateCode = STATE_CODE[sr.state] !== undefined ? STATE_CODE[sr.state] : 0;
- const pinned = typeof sr.value === 'number' ? sr.value : 100000000 + srIdx;
- srIdx += 1;
- (statusReasonValues[logical] = statusReasonValues[logical] || {})[sr.label] = { value: pinned, stateCode };
- await runner.run('data-model', `status reason ${e.schemaName}: ${sr.label}`, async () => {
- const v = await sdk.insertStatusValue(logical, { label: sr.label, stateCode, color: sr.color, value: pinned, languageCode: resolvedLanguageCode });
- statusReasonValues[logical][sr.label] = { value: typeof v === 'number' ? v : pinned, stateCode };
- }, { recoverable: true, skipIf: isAlreadyExists });
+ // data. Existing tables first prove equality after the phase's labelled creates; inconclusive
+ // proof keeps that duplicate-protected path. A fresh insert records the server-returned value.
+ // The same statusReasonTargets supply both the insert and verification state/value contract.
+ if (e.statusReasons && e.statusReasons.length) {
+ const status = { entity: e, logical, languageCode: resolvedLanguageCode };
+ if (existingTable && provision.dataverse && typeof provision.dataverse.get === 'function') waitingStatuses.push(status);
+ else await applyStatusReasons({ sdk, provision, runner, warn }, status, result);
}
- // alternate keys — idempotent: the SDK has no key lister, so a re-run that hits an
- // already-exists error is treated as a skip (not a halt) via skipIf.
+ // Alternate keys' scalar identity rides the table probe: an identical name/column set skips
+ // its POST, while unknown or different metadata keeps the duplicate-protected create path.
//
// A key over the name column of a table whose length is still to be set waits for that step when its label goes out in ONE language
// (keyWaitsForNameLength): it is made at the end of the phase, once the length is right. A key over that column whose label goes out in
@@ -2331,6 +2464,10 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la
// beside the others: the platform would refuse it here, so it waits too, whatever its label (keyMustWaitForShorterNameColumn).
// Every other key is made here, with its table, as it always was.
for (const k of e.alternateKeys || []) {
+ if (alternateKeyMatches(existingTable && existingTable.keys, k)) {
+ runner.skip('data-model', `alt key ${e.schemaName}.${k.schemaName} (exists)`);
+ continue;
+ }
if (lengthPending && keyWaitsForNameLength(e, k)) {
waitingKeys.push({ entity: e, logical, key: k, languageCode: resolvedLanguageCode });
continue;
@@ -2405,6 +2542,11 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la
const createOpts = rel.type === 'OneToMany'
? { type: 'OneToMany', schemaName: schema, referencedEntity: rel.referenced.toLowerCase(), referencingEntity: rel.referencing.toLowerCase(), lookupSchemaName: rel.lookup.schemaName, lookupDisplayName: createLabel.label, languageCode: resolvedLanguageCode }
: { type: 'ManyToMany', schemaName: schema, entity1: rel.entity1.toLowerCase(), entity2: rel.entity2.toLowerCase(), intersectEntityName: rel.intersectEntityName, languageCode: resolvedLanguageCode };
+ // The codes on which a refusal of this create is the cue to read who holds the name (ALREADY_EXISTS_CODES), by kind. A 1:N's list adds the
+ // navigation-property code its re-create was answered with live, and the codes of the lookup column it makes. An N:N names navigation
+ // properties too, and makes the attributes of the table that holds its links, but no answer to its re-create has been captured, so its list
+ // holds the name code only: those other answers are not observed for an N:N, not impossible.
+ const alreadyExistsCodes = rel.type === 'OneToMany' ? ALREADY_EXISTS_CODES.oneToManyRelationship : ALREADY_EXISTS_CODES.manyToManyRelationship;
await runner.run('data-model', label, async () => {
try {
const res = await sdk.createRelationship(createOpts);
@@ -2417,7 +2559,7 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la
result.lookupLabels[key] = { label: labelText(createLabel.label, resolvedLanguageCode) };
}
} catch (err) {
- if (!isAlreadyExists(err)) throw err;
+ if (!isAlreadyExists(err, alreadyExistsCodes)) throw err;
// What the relationship held under this name says of itself decides the step. It is the declared one only when it states its whole
// identity (compareRelationship): the create's own error is then rethrown, marked, which is how skipIf turns the step into a skip. One
// it contradicts is another relationship's, and the name has to change. One that leaves a part out is neither — it has not been shown
@@ -2482,7 +2624,7 @@ async function provisionDataModelSteps({ sdk, provision, runner, spec, apply, la
// run again can help; the create's own refusal, and the name, do not.
throw serviceFailure(`could not identify the relationship that already uses schema name '${schema}' (${holder.error || 'read failed'}); the create failed because it already exists: ${(err && err.message) || err}`, { status: holder.status, words: holder.error || '', answered: holder.answered });
}
- }, { skipIf: (e) => isAlreadyExists(e) && e.sameRelationshipExists === true });
+ }, { skipIf: (e) => isAlreadyExists(e, alreadyExistsCodes) && e.sameRelationshipExists === true });
}
// A rebuild repairs a lookup column an older build labelled with its old default (opt-in: only the app
@@ -2622,7 +2764,7 @@ async function reconcileLookupLabelsPass({ spec, sdk, provision, runner, warn, l
// with RetrieveAsIfPublished=false, so a live check of this publish has to trace the request, not read the label.
// Nothing else in the build is sure to publish the child table. Its other table publishes follow from what the spec
// puts on a table — a form, view, chart or icon, or its enriched default views — and a downloaded spec, whose lookups
-// the download leaves without a label precisely so that this pass repairs them, carries no forms, views, charts or
+// the download leaves without a label precisely so that this pass repairs them, need not carry forms, views, charts or
// table icons and marks every table existing: true, whose default views the build leaves alone. A rebuild of one would
// save the new label and leave it to whatever publishes that table next, while reporting the repair done; a re-run
// finds the label already changed. So the pass publishes the tables it relabelled itself, in ONE envelope, at once —
@@ -2902,4 +3044,4 @@ async function provisionSampleData({ sdk, provision, runner, spec, dataModel })
return { records: result.records, entitySetFor };
}
-module.exports = { makeRunner, mapLimit, runBestEffort, requireSuccessfulPush, pushFailed, reportPartialPush, errorCodeChain, RESET_WORKSPACE, makeEntitySetResolver, resolveLanguageCode, resolveAuthoringLanguage, provisionSolution, provisionDataModel, settleOwedLengths, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE, DEFAULT_MAX_SIZE_KB, isVisualizationUnsupported, localizedLabelLcidsInSpec, checkLocalizedLabelLanguages, findExistingTable, findExistingColumns, relationshipExists, lookupsWithDefaultLabel, relationshipsInCreateOrder };
+module.exports = { makeRunner, mapLimit, runBestEffort, requireSuccessfulPush, pushFailed, reportPartialPush, errorCodeChain, RESET_WORKSPACE, makeEntitySetResolver, resolveLanguageCode, resolveAuthoringLanguage, provisionSolution, provisionDataModel, settleOwedLengths, provisionSampleData, buildSeedGroup, BuildHalt, SDK_COLUMN_TYPE, DEFAULT_MAX_SIZE_KB, isVisualizationUnsupported, ALREADY_EXISTS_CODES, localizedLabelLcidsInSpec, checkLocalizedLabelLanguages, findExistingTable, findExistingColumns, relationshipExists, lookupsWithDefaultLabel, relationshipsInCreateOrder, statusReasonTargets };
diff --git a/plugins/model-apps/scripts/lib/feature-flags.js b/plugins/model-apps/scripts/lib/feature-flags.js
index b7eeac7b4..d086c5a91 100644
--- a/plugins/model-apps/scripts/lib/feature-flags.js
+++ b/plugins/model-apps/scripts/lib/feature-flags.js
@@ -7,8 +7,9 @@
// cadences — a pac CLI verb, a host/authoring runtime, and a maker/admin ECS setting.
// Until ALL of them are live in PROD, the skill must behave exactly as it did before
// the capability existed. A committed, default-OFF flag lets us merge the skill code
-// ahead of GA and flip it on in a one-line follow-up PR (or per-run via env var)
-// once the dependencies are released — instead of carrying an un-merged branch.
+// ahead of release and flip it on in a follow-up (or per-run via env var) once
+// its dependencies are available. Custom API discovery now ships ON; the retained
+// flag remains an explicit opt-out, not a change to the generic fail-closed fallback.
//
// A flag is flipped to `true` FIRST and removed in a later change, not both at once.
// Flipping is reversible in one line if the rollout turns out to be incomplete in some
@@ -42,7 +43,7 @@ const FLAGS = {
'custom-api': {
status: 'in-progress',
summary:
- 'GenPage Dataverse Custom API (plug-in) invocation — calling a Custom API Action or Function ' +
+ 'GenPage Dataverse Custom API (plug-in) invocation, enabled by default for supported public APIs — calling an Action or Function ' +
'from a generated page via dataApi.executeAction / executeFunction / listBoundActions, gated by ' +
"the page's revision-bound actionBindings manifest.",
dependencies:
@@ -183,11 +184,10 @@ function validateFlags(flags) {
function customApiDisabledMessage() {
return (
'Dataverse Custom API support is disabled (feature flag "custom-api" is OFF). ' +
- 'GenPage Custom API invocation requires the AIBuilder action prompt, the shared action ' +
- 'runtime, the UCI and Controls host runtimes, and the GenUxPluginActionAllowList setting to ' +
- 'all be live in PROD. To enable for a ' +
- 'single run set GENPAGE_ENABLE_CUSTOM_API=1, or flip "custom-api" to true in ' +
- 'plugins/model-apps/feature-flags.json once the dependencies are released.'
+ 'Discovery is enabled by default; GENPAGE_ENABLE_CUSTOM_API=0 explicitly disables it. ' +
+ 'To enable for a single run set GENPAGE_ENABLE_CUSTOM_API=1, or set "custom-api" to true in ' +
+ 'plugins/model-apps/feature-flags.json. Runtime capabilities, environment governance and ' +
+ 'the signed-in user privileges still apply.'
);
}
diff --git a/plugins/model-apps/scripts/lib/genpage-sdk.js b/plugins/model-apps/scripts/lib/genpage-sdk.js
index 09b34fa54..bb685c10c 100644
--- a/plugins/model-apps/scripts/lib/genpage-sdk.js
+++ b/plugins/model-apps/scripts/lib/genpage-sdk.js
@@ -44,6 +44,7 @@ const { makeTempWorkspace } = require('./temp-workspace.js');
const { sha256 } = require('./hash.js');
const { withCause } = require('./retry-policy.js');
const { makeThrottleBudget, waitDoesNotFit, spentNote } = require('./throttle-budget.js');
+const { mergeBindings } = require('./page-bindings.js');
const GUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
@@ -293,14 +294,19 @@ function projectionOf(page) {
// What an update has to write for `page` to hold `fields` — [{ key, value }], in the order they are applied; empty when it already does. A field left `undefined` is the
// page's own and is never an edit. The one definition of "this page already holds that content": an update plans its writes with it, and a create that finds a page
// under its id asks it whether that page holds all of what the create asked for.
-function planEdits(fields, page) {
+// `specBindings`: the binding lists given are an App Spec's. A spec states an entry by the properties it can carry and not by the ones it cannot (a connection id, a credential, a property a later runtime adds),
+// so a list it states is read against the page's own entry by entry (mergeBindings): the page "holds" the list when every entry reads the same, and an edit's value is the list as the page will hold it, each entry
+// still carrying what the spec could not state. For any other caller a list given is the page's list, as it always was.
+function planEdits(fields, page, { specBindings = false } = {}) {
const edits = [];
if (fields.source !== page.source) edits.push({ key: 'source', value: fields.source });
if (fields.name !== undefined && fields.name !== page.name) edits.push({ key: 'name', value: fields.name });
if (fields.dataSources !== undefined && !isDeepStrictEqual(fields.dataSources, page.dataSources === undefined ? [] : page.dataSources)) edits.push({ key: 'dataSources', value: fields.dataSources });
if (fields.model !== undefined && fields.model !== page.model) edits.push({ key: 'model', value: fields.model });
for (const key of ['connectorBindings', 'actionBindings']) {
- if (fields[key] !== undefined && !isDeepStrictEqual(fields[key], page[key])) edits.push({ key, value: fields[key] });
+ if (fields[key] === undefined) continue;
+ const wanted = specBindings ? mergeBindings(key, fields[key], page[key]) : fields[key];
+ if (!isDeepStrictEqual(wanted, page[key])) edits.push({ key, value: wanted });
}
return edits;
}
@@ -316,6 +322,20 @@ function contentFingerprint(fields) {
return sha256(`genpage-content/1\n${JSON.stringify(content)}`);
}
+// The hashes a record of a publish holds for `fields` when it was made before one or more of the binding lists `fields` states were stated: the content with each such set of lists left out — three for a caller
+// that states both lists (without the connector bindings, without the Custom API bindings, without either), one for a caller that states one, none for a caller that states none. `update` takes a record that is
+// one of them for this content only once it has read the published copy and found the lists there too.
+function fingerprintsBeforeListsWereStated(fields) {
+ const stated = ['connectorBindings', 'actionBindings'].filter((key) => fields[key] !== undefined);
+ const hashes = [];
+ for (let leftOut = 1; leftOut < (1 << stated.length); leftOut += 1) {
+ const earlier = { ...fields };
+ stated.forEach((key, at) => { if (leftOut & (1 << at)) earlier[key] = undefined; });
+ hashes.push(contentFingerprint(earlier));
+ }
+ return hashes;
+}
+
// The content fields of a page as `update` takes them from its arguments, normalized as the write normalizes them, so what is compared, hashed and checked afterwards is what is written. A field the caller leaves
// out (`undefined`) is the page's own. `publishedDiffers` takes its arguments through this too, so the `fingerprint` it answers is the one `update` answers for the same arguments.
function contentFieldsOf(args) {
@@ -397,6 +417,16 @@ async function readPublishedPage(sdk, id, { runtime = false } = {}) {
return page;
}
+// Whether the PUBLISHED copy of page `id` holds `fields` (planEdits, on the published layer): read only, and false for a page that has no published copy or whose copy cannot be read — "cannot be told" is never "holds it".
+async function publishedCopyHolds(sdk, id, fields, options) {
+ try {
+ const page = await readPublishedPage(sdk, id);
+ return page !== null && planEdits(fields, page, options).length === 0;
+ } catch {
+ return false;
+ }
+}
+
// The filetype of a page's COMPILED output row: the one after the text rows (TEXT_ROW_TYPE) — the bytes the runtime serves. The SDK writes it with the source, and a publish copies it to the published layer.
const COMPILED_ROW_TYPE = TEXT_ROW_TYPE + 1;
@@ -1093,7 +1123,9 @@ function makeGenpageSdk(env, deps = {}) {
},
// UPDATE: read the page, write only what differs from it, record the turn, publish, and prove the published copy.
- // args: { name, source, dataSources, model, prompt, agentMessage, connectorBindings, actionBindings, caller, appId, sourceFile, publishedFingerprint, runtimeEvidence, throttle } (`runtimeEvidence`, `throttle`: see create)
+ // args: { name, source, dataSources, model, prompt, agentMessage, connectorBindings, actionBindings, specBindings, caller, appId, sourceFile, publishedFingerprint, runtimeEvidence, throttle } (`runtimeEvidence`, `throttle`: see create)
+ // `specBindings: true` says that the binding lists given are an App Spec's: it states each entry by the properties it can carry, so they are read against the page's entries and an entry keeps what the spec could
+ // not state (planEdits, mergeBindings). Without it a list given is the page's list.
// A field the caller leaves out (`undefined`) is left alone — an omitted data-source list, model, name or binding list is the
// page's own, not an instruction to clear it; `[]` clears a list. The page's FIRST prompt is kept and the new one is recorded
// as a turn of its conversation (pac overwrote the first prompt on every upload).
@@ -1103,6 +1135,8 @@ function makeGenpageSdk(env, deps = {}) {
// is the `fingerprint` (contentFingerprint) a result gave it for a publish it saw take effect, and a page that already holds content with that very fingerprint is not
// published again (`publish.kind: 'skipped'`). It is only ever a reason not to publish a page this update has just read as already holding the content: a page that
// differs is written and published whatever the caller recorded, and a fingerprint that is missing or is another content's leaves the publish as it always was.
+ // With `specBindings`, the hash of the same content WITHOUT one or both of the binding lists it states is the record of a publish made before those lists were stated: it is taken for them too only when the
+ // published copy is read and holds them, and the result then says `receiptUpgraded: true` — its `fingerprint` is the hash to keep from now on.
// The result carries the `fingerprint` of the content the page holds now, for the caller that keeps one.
// The #722 guarantee: an update that MAY have landed is never sent again blindly. After an unknown outcome the page is read:
// what was sent is there, turn included -> it landed (publish)
@@ -1143,7 +1177,9 @@ function makeGenpageSdk(env, deps = {}) {
// `validate` and `normalize`, is only that it is a GUID — it keeps one it is given, and derives the message ids from its digits.
const turn = { ...turnOf({ prompt: args.prompt, agentMessage: args.agentMessage }, fields.name || baseline.name), id: String(newTurnId()).toLowerCase() };
const warnings = [];
- const planFor = (page) => planEdits(fields, page);
+ // The lists a caller gives as an App Spec's (see planEdits) are read against the page's entries; every other caller's replace them.
+ const specBindings = args.specBindings === true;
+ const planFor = (page) => planEdits(fields, page, { specBindings });
const fingerprint = contentFingerprint(fields);
let edits = planFor(baseline);
if (!edits.length) {
@@ -1152,6 +1188,15 @@ function makeGenpageSdk(env, deps = {}) {
if (typeof args.publishedFingerprint === 'string' && args.publishedFingerprint === fingerprint) {
return { pageId: id, unchanged: true, publish: { kind: 'skipped', detail: 'the page already holds this content, and the caller recorded that this content was published' }, fingerprint, warnings: [] };
}
+ // A record made before the caller stated a binding list is the hash of this content WITHOUT it — the build's record of every page it published before a download wrote the lists into the spec (both lists),
+ // or before a spec stated the second of them (one: a list a download could not state, or one the author took out of the spec to keep the page's own, stated again). The page holds them now (nothing is left
+ // to write), and the caller's record says that nothing has touched the page since that publish, so the lists were published with it: but the record never named them, and it is only taken for them once the
+ // PUBLISHED copy is read and found to hold them too (one read of the published layer, never a write). The answer says so (`receiptUpgraded`), so the caller keeps the hash it was given now, and a later
+ // update finds it as it is. A copy that does not hold them — or cannot be read — leaves the page to be published, as it always was.
+ if (specBindings && typeof args.publishedFingerprint === 'string' && fingerprintsBeforeListsWereStated(fields).includes(args.publishedFingerprint)
+ && await publishedCopyHolds(sdk, id, fields, { specBindings })) {
+ return { pageId: id, unchanged: true, publish: { kind: 'skipped', detail: 'the page already holds this content, the caller recorded that this content was published before its binding lists were stated, and the published copy holds them' }, fingerprint, receiptUpgraded: true, warnings: [] };
+ }
const runtimeSha256 = await runtimeEvidenceOf(sdk, id, args);
const published = await publish(sdk, 'genPage', id, { verify: true });
return { pageId: id, unchanged: true, publish: published, fingerprint, ...(runtimeSha256 ? { runtimeSha256 } : {}), warnings: warningsOf(null, published, `page ${who()}`) };
@@ -1647,7 +1692,8 @@ function makeGenpageSdk(env, deps = {}) {
},
// What the PUBLISHED copy of a page differs from `args` in: the content a caller that keeps a record of what it published (the build: lib/page-publish-records.js) needs to see held before it records a publish.
- // args: what `update` takes — only the content fields count (the source, and the name, data sources, model and bindings given); an omitted one is the page's own and cannot differ
+ // args: what `update` takes — only the content fields count (the source, and the name, data sources, model and bindings given); an omitted one is the page's own and cannot differ. `specBindings: true`
+ // reads the binding lists as an App Spec's, as `update` does, so the published copy of a page that holds more than a spec states is not reported as differing from it
// expected: `{ runtimeSha256 }` — the hash of the compiled output the DRAFT held when it was published (what `create` and `update` answer with `runtimeEvidence: true`); the published copy's compiled output must hash to it
// -> { ok: true, differing: [key…], fingerprint, runtimeSha256? } | { ok: false, error }
// `differing` names the fields whose published value is not the one asked for, in `planEdits`' own words — the one definition of "holds that content", made on the published layer where `update` makes it on the
@@ -1670,7 +1716,7 @@ function makeGenpageSdk(env, deps = {}) {
const wantsRuntime = !!expected && typeof expected.runtimeSha256 === 'string';
const page = await readPublishedPage(sdk, id, { runtime: wantsRuntime });
if (page === null) return { ok: false, error: `page ${id} has no published copy` };
- const differing = planEdits(fields, page).map((edit) => edit.key);
+ const differing = planEdits(fields, page, { specBindings: args.specBindings === true }).map((edit) => edit.key);
if (wantsRuntime && page.runtimeSha256 !== expected.runtimeSha256) differing.push('compiled output');
// Given evidence, the answer says which compiled output it read (`runtimeSha256`, null for a copy with none), so a caller can see that the comparison was made: an answer that does not carry it was not about the runtime.
return { ok: true, differing, fingerprint: contentFingerprint(fields), ...(wantsRuntime ? { runtimeSha256: page.runtimeSha256 } : {}) };
diff --git a/plugins/model-apps/scripts/lib/hydrate-spec.js b/plugins/model-apps/scripts/lib/hydrate-spec.js
index 4572c9db1..630f019e6 100644
--- a/plugins/model-apps/scripts/lib/hydrate-spec.js
+++ b/plugins/model-apps/scripts/lib/hydrate-spec.js
@@ -1,5 +1,5 @@
'use strict';
-const { isSafeHttpUrl, webResourceNameFromRef, FORM_GUID_RE } = require('./app-spec.js');
+const { isSafeHttpUrl, webResourceNameFromRef, FORM_GUID_RE, statedPageBindings } = require('./app-spec.js');
// Reconstruct a COMPLETE app-spec from a DEPLOYED app (the edit flow's "pull everything" step). Pure
// + testable: `read` supplies the deployed state — the app (sitemap JSON, via the SDK's app read
// path which surfaces entity/genPage/icon subareas), its generative pages (read through the SDK),
@@ -196,6 +196,10 @@ async function hydrateSpec(read) {
};
};
+ // A page's connector and Custom API bindings, as the download read them — written when the page has any. An empty list says nothing the page does not already say by having none, and
+ // a spec that stated one would claim the page's bindings were cleared on purpose (a rebuild writes a stated list as the page's own, `[]` clearing it), as `dataSources` is left out when empty.
+ const bindingsOf = (p) => Object.fromEntries(Object.entries(statedPageBindings(p)).filter(([, list]) => list.length));
+
const spec = {
// schemaVersion 2 only when pages carry keys (v2 shape); omitted for legacy back-compat.
...(hasKeys ? { schemaVersion: 2 } : {}),
@@ -273,6 +277,7 @@ async function hydrateSpec(read) {
...(p.purpose !== undefined ? { purpose: p.purpose } : {}),
...(p.dataSources && p.dataSources.length ? { dataSources: p.dataSources } : {}),
...(p.model ? { model: p.model } : {}),
+ ...bindingsOf(p),
...(p.navigatesTo ? { navigatesTo: p.navigatesTo } : {}),
...(p.pageInput !== undefined ? { pageInput: p.pageInput } : {}),
...directEntryOf(p),
@@ -285,6 +290,7 @@ async function hydrateSpec(read) {
name: p.name,
...(p.dataSources && p.dataSources.length ? { dataSources: p.dataSources } : {}),
...(p.model ? { model: p.model } : {}),
+ ...bindingsOf(p),
...(p.prompt !== undefined ? { prompt: p.prompt } : {}),
codeFile: p.codeFile,
})),
diff --git a/plugins/model-apps/scripts/lib/output-redaction.js b/plugins/model-apps/scripts/lib/output-redaction.js
index 04441224d..cc0572b4b 100644
--- a/plugins/model-apps/scripts/lib/output-redaction.js
+++ b/plugins/model-apps/scripts/lib/output-redaction.js
@@ -20,9 +20,12 @@
//
// EVERY OUTPUT PATH (sink), and what covers it:
// - stdout and stderr: `process.stdout.write` and `process.stderr.write` are wrapped (guardStream) the moment the first token is obtained — never before, so a process that has no token is untouched. Every `console.*` call
-// (in colours too), every script's result printer and warning printer, the build's progress lines, a library's own `console.warn` and the SDK bundle's end there. A text is cleaned as a STRING; bytes (a Buffer) are passed
-// as they are: nothing in the plugin writes bytes to a stream, and a test runner's own frames are bytes. `emitResult` (lib/dataverse-auth.js) also cleans its own text, so a result is clean where a caller has replaced the
-// stream's `write`. The writes a `process.exit` follows at once are made blocking first (makeWritesBlocking), so that what is written there is whole when the process ends — not only clean.
+// (in colours too), every script's result printer and warning printer, the build's progress lines, a library's own `console.warn` and the SDK bundle's end there. A text is cleaned as a STRING. BYTES (a Buffer, a
+// Uint8Array, or a string given with an encoding the stream decodes into bytes: `write(text, 'base64')`) are read byte for byte for every needle and spelling below, and a hit is masked in a COPY with as many `*` as
+// it has bytes — never decoded into text and encoded back, never shorter or longer: a test runner's own frames are bytes, and the length a frame declares must stay true — while bytes that hold none are the very object
+// given. Each write is read on its own, and nothing is held back to wait for the next one, so a token written in two pieces is two texts: the end of a write that BEGINS a needle and the start of one that ENDS a
+// needle are taken out too (EDGES, below) — never part of an escape cut between the two writes. `emitResult` (lib/dataverse-auth.js) also cleans its own text, so a result is clean where a caller has replaced the stream's `write`. The writes a `process.exit` follows at
+// once are made blocking first (makeWritesBlocking), so that what is written there is whole when the process ends — not only clean.
// - what Node itself prints when an error ends the process (an uncaught exception, an unhandled rejection): it never passes through `process.stderr.write`, so a handler prints it, cleaned, when nothing else handles the error
// (guardFatalErrors).
// - the files the plugin writes: `writeFileSafe` and `appendFileSafe` (lib/safe-fs.js: the build's journal and status file, a download's spec and pages, a page's file and its deployed copy, the plan, the settings template),
@@ -30,9 +33,14 @@
// `writeTextAtomic` (lib/maker-sdk.js wraps it: guardWorkspaceStorage). tests/output-token-writers.test.js lists every other write in the plugin and says why none of them can carry a token.
// - in the pcf plugin (which carries a copy of this module): its streams and its fatal errors as above (its scripts note their tokens through the same lib/dataverse-auth.js), the receipt `pcf-push.js` writes
// (`pcf-receipt.json`) and the SDK workspace `makePcfSdk` makes; pcf's tests/pcf-push-token.test.js lists every other write of pcf and says why none of them can carry a token.
-// - not covered, by design: bytes (a Buffer given to a writer is written as it is); a token another process obtained (`pac` has its own); another encoding of a token (percent-encoding, base64 of a whole header, HTML
-// entities — nothing is known to quote a token in one, and a reader that guessed at them would blank ordinary text); a token written in two separate calls to `write` (no script writes a message in pieces); a token a
-// formatter CUT SHORT (util.inspect prints at most 10,000 characters of a string, and the end of a part cut off there is not the part); a raw control character other than white space and ESC between two of its characters.
+// - not covered, by design: a token another process obtained (`pac` has its own); a piece of a token SHORTER than MIN_TOKEN_PART_LENGTH at the edge of a write or before a cut (it would be taken out of ordinary words — a
+// token written in two pieces leaves the shorter piece when it is under 24 characters; the first one is written before the second exists); a piece from the MIDDLE of a token that neither begins nor ends a needle (a
+// token written in three pieces or more, or cut at both ends); the start of a write read through an escape's letters (it is read on the first reading only: a literal backslash before its first letter leaves that letter);
+// the piece of a token that an escape cut between two writes leaves on its far side when that piece is shorter than 24 characters (the escape stays whole, so its characters count for neither piece);
+// a spelling other than those below (a partial percent-encoding, a numeric entity for every character, base64 of a part alone, hex, a token spelled backwards — a reader that guessed at them would blank ordinary data);
+// a cut other than util.inspect's, an ellipsis or the end of a text the process writes; inside BYTES only whole needles and the edges of a write are read (no cut, no fold, no escape); bytes given to a FILE writer (the
+// writers below clean text); the cuts and edges of a token searched for literally (one with white space, a backslash or an ESC of its own — no token a service issues); a raw control character other than white space
+// and ESC between two of its characters.
//
// A TOKEN AS A TEXT SPELLS IT. A token is looked for as the text spells it, one character at a time: a character is itself, or an escape of it (`\u0073` for `s`, in either case of hex; `\x73`; `\/` for `/`), and between
// two characters of the token there may be a fold — any white space, a line break and its indentation (the obsolete line folding of https://www.rfc-editor.org/rfc/rfc9112#section-5.2, a column a gateway wrapped), spelled as
@@ -42,11 +50,26 @@
// the token. The span from the token's first character to its last — the folds and escapes inside it included, an escape always whole — becomes `<token>`, and the white space before and after it stays. In JSON text the
// span is always inside one string and never leaves half of an escape, so what was JSON is still JSON (the baseline and the journal are read back by the next run).
//
-// COST. Every needle (the token, and each of its parts of 24 characters or more: needlesOf) is searched in ONE pass over the characters the text spells, as Knuth-Morris-Pratt does, in lockstep, so a text of any size takes time
-// that grows with its size and a near miss of a long needle over and over costs no more than any other text; an escape read the other way starts a reading that is followed next to the pass, and at most MAX_READINGS of them
-// per needle are alive at once — a real token keeps one or two — so no text makes the search backtrack or grow faster than the text. A text that would need more is not guessed at: the search fails, and every caller fails
-// closed (tests/output-redaction.test.js measures all of it). A text that holds no token comes back as the very string.
-const { inspect } = require('node:util');
+// OTHER SPELLINGS of a token the process obtained are needles of their own, read the same way (spellingsOf): its base64, standard and URL-safe, at each of the three byte alignments it can have inside a longer value (a
+// whole `Authorization` header, a body encoded once more), and its percent-encoded and HTML spellings where they differ from it. Exact spellings of a KNOWN token — nothing in a text is decoded to look inside it.
+//
+// A TOKEN CUT SHORT. A formatter that cuts a long text keeps its beginning, and the end of what it kept can be the beginning of a token: util.inspect prints at most 10,000 characters of a string and then says how many it
+// left out (`'Rejected bearer syntheticHeaderPartNotA'... 9876 more characters`), and a text cut to a length by hand ends with an ellipsis (`...`, `…`). Where a text says it was cut, the run before it that BEGINS a needle — 24
+// characters or more of it, read with every rule above — is taken out too, from its first character to its last (cutsHere, takePrefixes).
+//
+// EDGES. A write is read on its own and nothing is held back for the next one, so a token written in two pieces is two texts, each with a piece of it at one end. A text the process writes (redactOutput: a stream's write,
+// a file, a result) loses a run of 24 characters or more at its END that begins a needle, and one at its START that ends a needle (takeLeadingSuffix: on the first reading — an escape there is the character it stands
+// for). An escape is never cut by this: a text that ends inside one (`\`, `\u00`, `\x7`) is read up to where it begins, and a guarded stream remembers it — a few characters, not output — so that its next write, which
+// begins by finishing it, is read from after it (unfinishedEscape, finishEscape). The escape stays whole where it was written, and the pieces of the token on either side of it go each on its own: JSON written in two
+// pieces is JSON together. A text a caller only asks about (redactTokens) is read this way when it asks for `edges` (and `from`).
+//
+// COST. Every needle (the token, each of its parts of 24 characters or more: needlesOf, and each spelling: spellingsOf) is searched in ONE pass over the characters the text spells, as Knuth-Morris-Pratt does, in lockstep, so
+// a text of any size takes time that grows with its size and a near miss of a long needle over and over costs no more than any other text; an escape read the other way starts a reading that is followed next to the pass,
+// and at most MAX_READINGS of them per needle are alive at once — a real token keeps one or two — so no text makes the search backtrack or grow faster than the text. A cut is looked at where the pass already is (a quote,
+// a dot, an ellipsis, while a needle is being read), and its pieces are the alignments the pass already follows; the start of a text is read for at most the longest needle's length; bytes are read in one pass of the
+// same kind, needle by needle in lockstep. A text that would need more is not guessed at: the search fails, and every caller fails closed (tests/output-redaction.test.js and tests/output-token-forms.test.js measure
+// all of it). A text that holds no token comes back as the very string, and bytes as the very bytes.
+const { inspect, types: { isUint8Array } } = require('node:util');
// What takes the place of a token, or of a part of one, in a text.
const TOKEN_MARKER = '<token>';
@@ -63,6 +86,58 @@ function needlesOf(token) {
return [...needles].sort((a, b) => b.length - a.length);
}
+// The characters a percent-encoded text leaves as they are: the unreserved ones of https://www.rfc-editor.org/rfc/rfc3986#section-2.3 (`A-Z a-z 0-9 - . _ ~`). `encodeURIComponent` also leaves `! ' ( ) *` — none of
+// which a base64 or base64url token holds, so the two agree on every token a service issues.
+const unreserved = (byte) => (byte >= 0x41 && byte <= 0x5a) || (byte >= 0x61 && byte <= 0x7a) || (byte >= 0x30 && byte <= 0x39) || byte === 0x2d || byte === 0x2e || byte === 0x5f || byte === 0x7e;
+
+// `text` percent-encoded (https://www.rfc-editor.org/rfc/rfc3986#section-2.1): every UTF-8 byte that is not unreserved as `%` and two hex digits — upper case, which the RFC asks for, or lower case, which some encoders
+// write (`%2b`). A standard-base64 token in a query string: `abc+def/ghi=` → `abc%2Bdef%2Fghi%3D`.
+function percentSpelling(text, upper) {
+ let out = '';
+ for (const byte of Buffer.from(text, 'utf8')) {
+ if (unreserved(byte)) out += String.fromCharCode(byte);
+ else out += `%${(upper ? byte.toString(16).toUpperCase() : byte.toString(16)).padStart(2, '0')}`;
+ }
+ return out;
+}
+
+// The characters HTML text and attribute values spell as entities (https://html.spec.whatwg.org/multipage/parsing.html#escapingString, and `'` for an attribute in single quotes), as an HTML error page quotes a value.
+const HTML_ENTITIES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
+
+/**
+ * The other spellings of `token` that are taken out of what the process writes, each an exact needle read as any needle is (with folds and escapes in it):
+ * - its base64, standard and URL-safe (https://www.rfc-editor.org/rfc/rfc4648#section-4 and #section-5), as it is spelled INSIDE a longer value: base64 spells three bytes as four characters of six bits, so the token's
+ * first byte can stand at any of three places in a group and each place spells it differently. Of each, only the characters made of the token's own bits — a character that also holds bits of the byte before or
+ * after it changes with that byte, so it is left out at either end;
+ * - its percent-encoded spelling (upper- and lower-case hex) and its HTML spelling, and those of each of its parts of 24 characters or more — only where they differ from it: a JWT is base64url and dots, which
+ * neither changes, so a JWT has base64 spellings only.
+ * Each is kept only when it is MIN_TOKEN_PART_LENGTH characters or more, as a part is; a spelling that is already a needle of the token is not repeated. The longest first.
+ * @param {string} token
+ * @returns {string[]}
+ */
+function spellingsOf(token) {
+ if (typeof token !== 'string' || token === '') return [];
+ const plain = needlesOf(token);
+ const spellings = new Set();
+ const keep = (spelled) => {
+ if (spelled.length >= MIN_TOKEN_PART_LENGTH && !plain.includes(spelled)) spellings.add(spelled);
+ };
+ const bytes = Buffer.from(token, 'utf8');
+ for (let offset = 0; offset < 3; offset += 1) {
+ // With `offset` bytes before the token, its bits are bits [8 * offset, 8 * (offset + n)) of the value, and character i holds bits [6i, 6i + 6): the characters from ceil(8 * offset / 6) to floor(8 * (offset + n) / 6)
+ // hold the token's bits and nothing else.
+ const standard = Buffer.concat([Buffer.alloc(offset), bytes]).toString('base64').slice(Math.ceil((4 * offset) / 3), Math.floor((4 * (offset + bytes.length)) / 3));
+ keep(standard);
+ keep(standard.replace(/\+/g, '-').replace(/\//g, '_'));
+ }
+ for (const needle of plain) {
+ keep(percentSpelling(needle, true));
+ keep(percentSpelling(needle, false));
+ keep(needle.replace(/[&<>"']/g, (char) => HTML_ENTITIES[char]));
+ }
+ return [...spellings].sort((a, b) => b.length - a.length);
+}
+
// ---- Reading a text as it spells a token ----------------------------------------------------------------------------------------------------------------------------------------------------------
// White space as a regular expression's `\s` reads it: a fold can be made of any of it, and the plugin's own tests normalize a text with that class.
@@ -202,16 +277,32 @@ function readSpelled(text, at, skip) {
}
// The longest proper prefix of `needle.slice(0, i + 1)` that is also its suffix, for each i: where a search for the needle goes on after a mismatch, so that it never reads a character twice
-// (https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm).
-function failureTable(needle) {
- const table = new Int32Array(needle.length);
- for (let i = 1, k = 0; i < needle.length; i += 1) {
- while (k > 0 && needle.charCodeAt(i) !== needle.charCodeAt(k)) k = table[k - 1];
- if (needle.charCodeAt(i) === needle.charCodeAt(k)) k += 1;
+// (https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm). `unitAt(i)` is the needle's unit i, so that the same table is made for a needle read forwards, read backwards, or as bytes.
+function borders(size, unitAt) {
+ const table = new Int32Array(size);
+ for (let i = 1, k = 0; i < size; i += 1) {
+ const unit = unitAt(i);
+ while (k > 0 && unit !== unitAt(k)) k = table[k - 1];
+ if (unit === unitAt(k)) k += 1;
table[i] = k;
}
return table;
}
+const failureTable = (needle) => borders(needle.length, (i) => needle.charCodeAt(i));
+// The same of the needle read from its end: what the start of a text is matched against (endsAtStart).
+const reversedFailureTable = (needle) => borders(needle.length, (i) => needle.charCodeAt(needle.length - 1 - i));
+
+// How many units at the START of a sequence are the END of a needle: KMP over the needle read backwards (`reversed`, its table), fed the first `length` units of the sequence backwards, so that the state it is left in is
+// the longest end of the needle that the sequence begins with (the needle may also be found whole: then it is the needle's length). `needleUnit(i)` and `unitAt(i)` give unit i of the needle and of the sequence.
+function endsAtStart(size, needleUnit, reversed, length, unitAt) {
+ let state = 0;
+ for (let i = length - 1; i >= 0; i -= 1) {
+ const unit = unitAt(i);
+ while (state > 0 && (state === size || needleUnit(size - 1 - state) !== unit)) state = reversed[state - 1];
+ if (state < size && needleUnit(size - 1 - state) === unit) state += 1;
+ }
+ return state;
+}
// How many readings of ONE needle that took an escape's letters (and not the escape) the search follows at once. A random token keeps one or two alive on any text, and a needle that is one letter over and over keeps
// one per letter; more than this needs a text made to match the needle almost everywhere — i.e. made by someone who has the token. The bound keeps the cost linear on any text: past it the search does not guess which
@@ -219,35 +310,50 @@ function failureTable(needle) {
const MAX_READINGS = 128;
const TOO_MANY_READINGS = 'output-redaction: a text holds too many ways to read a token for it to be checked';
-// Everything the search needs of a set of tokens, made once and not for each text: the needles it can read and each one's failure table, the first character of each (a text is only looked at closely where one could start,
-// or where a needle is already being matched), what the reader skips, and the tokens that still need a literal search for a needle of their own that the reader cannot read.
+// Everything the search needs of a set of tokens, made once and not for each text: the needles it can read (the tokens, their parts and their spellings) and each one's failure tables, the first character of each (a text is
+// only looked at closely where one could start, or where a needle is already being matched), what the reader skips, and the needles that still need a literal search because the reader cannot read them — every needle
+// of a token that has one such (as before), and a spelling that is one.
function prepare(tokens) {
const live = [...new Set(tokens.filter((token) => typeof token === 'string' && token !== ''))];
if (live.length === 0) return null;
- const needles = [...new Set(live.flatMap(needlesOf))].filter((needle) => !unreadable(needle));
+ const plain = [...new Set(live.flatMap(needlesOf))];
+ const spelled = [...new Set(live.flatMap(spellingsOf))].filter((spelling) => !plain.includes(spelling));
+ const every = [...plain, ...spelled];
+ const needles = every.filter((needle) => !unreadable(needle));
const skip = new Uint8Array(128);
for (const unit of [0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x20]) skip[unit] = 1;
for (const unit of [0x22, 0x27, 0x60]) skip[unit] = 2;
skip[0x1b] = 3;
const firstUnits = new Uint8Array(65536);
+ // Every character any needle holds: a text whose first characters are not all among them cannot begin with the end of one (takeLeadingSuffix).
+ const inNeedles = new Uint8Array(65536);
for (const needle of needles) {
firstUnits[needle.charCodeAt(0)] = 1;
for (let i = 0; i < needle.length; i += 1) {
const unit = needle.charCodeAt(i);
+ inNeedles[unit] = 1;
if (unit < 128) skip[unit] = 0;
}
}
+ const longest = needles.reduce((length, needle) => Math.max(length, needle.length), 0);
return {
needles,
+ every,
tables: needles.map(failureTable),
- longest: needles.reduce((length, needle) => Math.max(length, needle.length), 0),
+ reversedTables: needles.map(reversedFailureTable),
+ longest,
firstUnits,
+ inNeedles,
skip,
- literal: live.filter((token) => needlesOf(token).some(unreadable)),
+ literal: [...live.filter((token) => needlesOf(token).some(unreadable)).flatMap(needlesOf), ...spelled.filter(unreadable)],
// The search's working memory, kept with what it is made for: a stream is written in many small pieces, and an array of the longest needle's length made for each would cost more than the search. The search
// never calls out and never starts another, so one set at a time is all there is.
- starts: new Int32Array(needles.reduce((length, needle) => Math.max(length, needle.length), 1)),
+ starts: new Int32Array(Math.max(longest, 1)),
states: new Int32Array(needles.length),
+ // The first characters a text spells, where each begins and ends: what its start is matched against (takeLeadingSuffix).
+ lead: { codes: new Int32Array(Math.max(longest, 1)), begins: new Int32Array(Math.max(longest, 1)), ends: new Int32Array(Math.max(longest, 1)) },
+ // The same needles as bytes, made the first time bytes are read (bytesOf).
+ bytes: null,
// For each needle, the readings that took an escape's letters: how far each is (`states`) and where it began (`begins`), with a second pair the next set is made in, and `slot` — for a state, 1 + its index in the next
// set — so that two readings that have come equally far are kept once, with the earlier beginning (whatever the later one would find, the earlier one finds with a span that holds it).
readings: needles.map((needle) => ({
@@ -328,25 +434,166 @@ function forkReadings(text, begin, end, prepared, read, spans) {
return alive;
}
+// The most digits of the count util.inspect prints after a cut: a string's length is below 2^53, which has 16 digits; a bound keeps the look at a cut from reading on.
+const MAX_COUNT_DIGITS = 16;
+
+// ---- An escape cut between two writes ----------------------------------------------------------------------------------------------------------------------------------------------------------------
+
+// Where an escape that a write ENDS inside begins — a run of backslashes at its end, or such a run and `u` with fewer than four hex digits after it, or `x` with fewer than two (readEscape's items, cut short) — or
+// `length` when it ends on no such thing. `unitAt(i)` is unit i of the write (a character, or a byte: an escape is ASCII either way), read from `from` on. The edges of a write stop there, and the guard on a stream
+// remembers it, so that the piece of a token before it and the one after it are each taken out and the escape is never cut in two: `{"error":"…\` and `/…"}` — a JSON `\/` written in two pieces — stay `\` and `/`.
+function unfinishedEscape(unitAt, from, length) {
+ const runStart = (at) => {
+ let start = at;
+ while (start - 1 >= from && unitAt(start - 1) === 0x5c) start -= 1;
+ return start;
+ };
+ let digitsFrom = length;
+ while (digitsFrom > from && digitsFrom > length - 3 && hexValue(unitAt(digitsFrom - 1)) >= 0) digitsFrom -= 1;
+ for (let letterAt = digitsFrom - 1; letterAt < length; letterAt += 1) {
+ if (letterAt - 1 < from) continue;
+ const letter = unitAt(letterAt);
+ const digits = length - letterAt - 1;
+ if (((letter === 0x75 && digits <= 3) || (letter === 0x78 && digits <= 1)) && unitAt(letterAt - 1) === 0x5c) return runStart(letterAt - 1);
+ }
+ if (length - 1 >= from && unitAt(length - 1) === 0x5c) return runStart(length - 1);
+ return length;
+}
+
+// The escape a write ended inside, kept as the stream's only memory of it: one backslash for its whole run (a run of any length is one item to readEscape) and what followed it — at most `\u` and three digits.
+function openEscapeOf(unitAt, start, length) {
+ let at = start;
+ while (at < length && unitAt(at) === 0x5c) at += 1;
+ let open = '\\';
+ for (let i = at; i < length; i += 1) open += String.fromCharCode(unitAt(i));
+ return open;
+}
+
+// How many units at the start of a write finish the escape the last write ended inside (`open`), and the escape still open after it when the write ends inside it too. `head` is the write's first units as a string
+// (latin1 for bytes), as many as can belong to the escape: its leading backslashes and six more.
+function finishEscape(open, head, wholeLength) {
+ const joined = open + head;
+ if (head.length === wholeLength && unfinishedEscape((i) => joined.charCodeAt(i), 0, joined.length) === 0) return { rest: wholeLength, open: openEscapeOf((i) => joined.charCodeAt(i), 0, joined.length) };
+ readEscape(joined, 0);
+ return { rest: Math.min(wholeLength, Math.max(0, spelledWidth - open.length)), open: null };
+}
+
+// Whether the text says, at `at`, that what stands before it was CUT SHORT:
+// - util.inspect prints at most `maxStringLength` (10,000) characters of a string and then, after the closing quote — in colours, after the code that ends the string's colour — how many it left out
+// (https://nodejs.org/api/util.html#utilinspectobject-options):
+// body: 'Rejected bearer syntheticHeaderPartNotA'... 9876 more characters body: \u001b[32m'Rejected bearer syntheticHe'\u001b[39m... 1 more character
+// with `"` or a backtick for the quote when the string holds a `'`;
+// - a text cut to a length by hand ends with an ellipsis: `...` (the plugin's own `briefReason`, lib/entity-provision.js, cuts a platform message to 297 characters and adds it), or `…`.
+// Only an item that can begin one of them is looked at, and only while a needle is being read; the codes after a quote are read once, by the one quote before them, so the look costs no more than the text.
+function cutsHere(text, at) {
+ const unit = text.charCodeAt(at);
+ if (unit === 0x2026) return true;
+ if (unit === 0x2e) return text.charCodeAt(at + 1) === 0x2e && text.charCodeAt(at + 2) === 0x2e;
+ if (unit !== 0x22 && unit !== 0x27 && unit !== 0x60) return false;
+ let i = at + 1;
+ while (text.charCodeAt(i) === 0x1b) {
+ const end = codeEnd(text, i);
+ if (end < 0) return false;
+ i = end;
+ }
+ if (!text.startsWith('... ', i)) return false;
+ const digits = i + 4;
+ let j = digits;
+ while (j - digits < MAX_COUNT_DIGITS && text.charCodeAt(j) >= 0x30 && text.charCodeAt(j) <= 0x39) j += 1;
+ return j > digits && text.startsWith(' more character', j);
+}
+
+// A needle CUT SHORT where the search now is (a cut, or the end of a whole write): every alignment still being read — the search's own (its state; the shorter alignments in its failure chain end where it ends and
+// begin later, so they are inside it) and every reading that took an escape's letters — that has come MIN_TOKEN_PART_LENGTH characters or more into a needle is that needle's beginning, from where it began to `end`,
+// the end of the last item that spelled a character. They all end there, so one span from the earliest of them holds them all. The readings are at most MAX_READINGS a needle, as for every other item the search reads.
+function takePrefixes(prepared, read, end, spans) {
+ const { needles, longest, starts, states, readings: all } = prepared;
+ let earliest = -1;
+ for (let n = 0; n < needles.length; n += 1) {
+ const state = states[n];
+ if (state >= MIN_TOKEN_PART_LENGTH) {
+ const begin = starts[(read - state) % longest];
+ if (earliest < 0 || begin < earliest) earliest = begin;
+ }
+ const readings = all[n];
+ for (let i = 0; i < readings.count; i += 1) {
+ if (readings.states[i] >= MIN_TOKEN_PART_LENGTH && (earliest < 0 || readings.begins[i] < earliest)) earliest = readings.begins[i];
+ }
+ }
+ if (earliest >= 0) spans.push([earliest, end]);
+}
+
+// A whole write that BEGINS with the end of a needle — what is left of a token whose first piece an earlier write took: the first characters the text spells, on the first reading (an escape is the character it stands for,
+// or nothing; its letters are not followed here), and for each needle the longest of its ends that they are (endsAtStart). One of MIN_TOKEN_PART_LENGTH characters or more is taken out, from the first character spelled
+// to the last of it: the white space before it stays. Such an end begins with MIN_TOKEN_PART_LENGTH characters that stand somewhere in its needle, so only a needle that holds the text's first ones is matched, and only
+// as many characters are read as the longest of those needles has: a write of ordinary words costs one short look.
+function takeLeadingSuffix(text, prepared, spans, from, to) {
+ const { needles, reversedTables, skip, lead } = prepared;
+ const { codes, begins, ends } = lead;
+ let count = 0;
+ let at = from;
+ const readUpTo = (limit) => {
+ while (at < to && count < limit) {
+ const begin = at;
+ let code = readSpelled(text, at, skip);
+ at += spelledWidth;
+ if (code === DUAL) code = primaryCode;
+ if (code === -1) continue;
+ codes[count] = code;
+ begins[count] = begin;
+ ends[count] = at;
+ count += 1;
+ }
+ };
+ readUpTo(MIN_TOKEN_PART_LENGTH);
+ if (count < MIN_TOKEN_PART_LENGTH) return;
+ for (let i = 0; i < MIN_TOKEN_PART_LENGTH; i += 1) if (prepared.inNeedles[codes[i]] === 0) return;
+ const first = String.fromCharCode(...codes.subarray(0, MIN_TOKEN_PART_LENGTH));
+ let reach = 0;
+ for (const needle of needles) if (needle.length > reach && needle.includes(first)) reach = needle.length;
+ if (reach === 0) return;
+ readUpTo(reach);
+ let longestEnd = 0;
+ for (let n = 0; n < needles.length; n += 1) {
+ const needle = needles[n];
+ if (!needle.includes(first)) continue;
+ const length = endsAtStart(needle.length, (i) => needle.charCodeAt(i), reversedTables[n], Math.min(count, needle.length), (i) => codes[i]);
+ if (length > longestEnd) longestEnd = length;
+ }
+ if (longestEnd >= MIN_TOKEN_PART_LENGTH) spans.push([begins[0], ends[longestEnd - 1]]);
+}
+
// Every needle searched for in ONE pass over the items the text spells, in time that grows with the text: a search that starts again at every character takes seconds on a text that is a needle's first thousand
// characters over and over. A needle's state is how many of its first characters the last items spell — on the escapes' first readings (as the character an escape stands for, or nothing), as Knuth-Morris-Pratt does it.
// An escape that can also be its letters (a literal backslash before an `n`) starts readings that the search follows next to it, a bounded set (forkReadings). A match runs from where the first of its characters is
// spelled to where its last ends — the folds and escapes between them are inside it, and the white space before and after is not. `starts` remembers where each of the last items began, in a ring as long as the longest
-// needle, which is all a match can reach back over; an item that cannot start a match while no needle is being matched is counted and not stored, because no match will ever ask for its start. The spans of all the
-// needles are then merged where they overlap (a token and its parts do) and each merged span is replaced by one marker; two spans that only touch stay two, as two tokens written one after the other are two.
-function takeOutSpelled(text, prepared) {
+// needle, which is all a match can reach back over; an item that cannot start a match while no needle is being matched is counted and not stored, because no match will ever ask for its start. Where the text says it was cut
+// (cutsHere), and — with `edges` — at its end, the alignments still being read that have come MIN_TOKEN_PART_LENGTH characters or more are a needle cut short (takePrefixes); with `edges`, a needle's end at the start of
+// the text is one too (takeLeadingSuffix). The spans of all the needles are then merged where they overlap (a token and its parts do) and each merged span is replaced by one marker; two spans that only touch stay two,
+// as two tokens written one after the other are two. With `edges`, the text is read from `from` (where an escape the last write ended inside is finished: see unfinishedEscape) up to an escape it ends inside, so that
+// no span ever takes part of an escape.
+function takeOutSpelled(text, prepared, edges, start = 0) {
const { needles, tables, longest, firstUnits, skip, starts, states, readings: all } = prepared;
const count = needles.length;
+ const stop = edges ? unfinishedEscape((i) => text.charCodeAt(i), start, text.length) : text.length;
states.fill(0);
for (const readings of all) readings.count = 0;
const spans = [];
let read = 0;
let matching = false;
- for (let at = 0; at < text.length;) {
+ // Where the last item that spells a character — or may: an escape read two ways — ends. A needle cut short ends there; the white space, colour codes and stray backslashes after it stay, as they do after a match.
+ let lastEnd = 0;
+ for (let at = start; at < stop;) {
+ if (matching) {
+ // Only a quote, a dot or an ellipsis can begin a cut: looked for here, and not in a call for every character of a token.
+ const unit = text.charCodeAt(at);
+ if ((unit === 0x27 || unit === 0x2e || unit === 0x22 || unit === 0x60 || unit === 0x2026) && cutsHere(text, at)) takePrefixes(prepared, read, lastEnd, spans);
+ }
const begin = at;
let code = readSpelled(text, at, skip);
at += spelledWidth;
if (code === -1) continue;
+ lastEnd = at;
let forked = false;
if (code === DUAL) {
code = primaryCode;
@@ -367,6 +614,8 @@ function takeOutSpelled(text, prepared) {
for (let n = 0; n < count; n += 1) {
const needle = needles[n];
const readings = all[n];
+ // A needle that is not being read and does not begin here stays as it is: nothing below would change it. The spellings make the needles of a token several, and a token's text runs this loop for each of them.
+ if (states[n] === 0 && readings.count === 0 && needle.charCodeAt(0) !== code) continue;
if (!forked && readings.count > 0) {
let kept = 0;
for (let i = 0; i < readings.count; i += 1) {
@@ -396,6 +645,10 @@ function takeOutSpelled(text, prepared) {
}
read += 1;
}
+ if (edges) {
+ if (matching) takePrefixes(prepared, read, lastEnd, spans);
+ takeLeadingSuffix(text, prepared, spans, start, stop);
+ }
if (spans.length === 0) return text;
spans.sort((a, b) => a[0] - b[0] || b[1] - a[1]);
let out = '';
@@ -414,27 +667,116 @@ function takeOutSpelled(text, prepared) {
return out + text.slice(kept);
}
-// `text` with the tokens `prepared` stands for taken out: what the reader finds, and then — only for a token that has a needle the reader cannot read (white space, a backslash or an ESC in it) — a literal search, as the Dataverse
-// client's scrubber does it. The reader first, so that a token spelled in one piece is one marker: a literal search first would take out the parts of a token whose dots are inside a fold, and leave `<token>.<token>`
-// where the reader finds the whole.
-function redactWith(prepared, text) {
+// `text` with the tokens `prepared` stands for taken out: what the reader finds, and then — only for a needle the reader cannot read (white space, a backslash or an ESC in it), with the other needles of its token — a literal
+// search, as the Dataverse client's scrubber does it. The reader first, so that a token spelled in one piece is one marker: a literal search first would take out the parts of a token whose dots are inside a fold, and leave
+// `<token>.<token>` where the reader finds the whole. `edges`: the text is a whole write (see EDGES above), read from `from`; nothing before `from` is changed, by the reader or the literal search.
+function redactWith(prepared, text, edges = false, from = 0) {
let out = text;
- if (prepared.needles.length > 0) out = takeOutSpelled(out, prepared);
- for (const token of prepared.literal) out = needlesOf(token).reduce((current, needle) => current.split(needle).join(TOKEN_MARKER), out);
- return out;
+ if (prepared.needles.length > 0) out = takeOutSpelled(out, prepared, edges, from);
+ if (prepared.literal.length === 0) return out;
+ // The reader leaves the units before `from` as they were, so they are the start of `out` too.
+ let rest = out.slice(from);
+ for (const needle of prepared.literal) rest = rest.split(needle).join(TOKEN_MARKER);
+ return from === 0 ? rest : out.slice(0, from) + rest;
+}
+
+// ---- Bytes ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+
+// What stands in the place of each byte of a token in bytes: one byte for one, so that bytes keep their length — a test runner's frames say how many bytes follow them.
+const MASK_BYTE = 0x2a;
+
+// The needles of `prepared` as the bytes they are written as (UTF-8): every one of them, read literally — bytes are not a text a formatter made, so no fold and no escape is read in them. Made the first time bytes are read.
+function bytesOf(prepared) {
+ if (prepared.bytes !== null) return prepared.bytes;
+ const needles = prepared.every.map((needle) => Buffer.from(needle, 'utf8'));
+ const firstBytes = new Uint8Array(256);
+ const inNeedles = new Uint8Array(256);
+ for (const needle of needles) {
+ firstBytes[needle[0]] = 1;
+ for (const byte of needle) inNeedles[byte] = 1;
+ }
+ prepared.bytes = {
+ needles,
+ tables: needles.map((needle) => borders(needle.length, (i) => needle[i])),
+ reversed: needles.map((needle) => borders(needle.length, (i) => needle[needle.length - 1 - i])),
+ firstBytes,
+ inNeedles,
+ states: new Int32Array(needles.length),
+ };
+ return prepared.bytes;
+}
+
+// `bytes` with every needle in them — and, with `edges`, a run of MIN_TOKEN_PART_LENGTH bytes or more at their end that begins a needle and at their start that ends one — masked, in a COPY: the bytes given are the
+// caller's (a frame it may write again, a pooled buffer). The very bytes when nothing is found. One pass, every needle in lockstep as Knuth-Morris-Pratt does it, the start read for at most each needle's length.
+function maskWith(prepared, bytes, edges, from = 0) {
+ const { needles, tables, reversed, firstBytes, inNeedles, states } = bytesOf(prepared);
+ const to = edges ? unfinishedEscape((i) => bytes[i], from, bytes.length) : bytes.length;
+ states.fill(0);
+ const spans = [];
+ let matching = false;
+ for (let i = from; i < to; i += 1) {
+ const unit = bytes[i];
+ if (!matching && firstBytes[unit] === 0) continue;
+ matching = false;
+ for (let n = 0; n < needles.length; n += 1) {
+ const needle = needles[n];
+ let state = states[n];
+ while (state > 0 && needle[state] !== unit) state = tables[n][state - 1];
+ if (needle[state] === unit) state += 1;
+ if (state === needle.length) {
+ spans.push(i + 1 - state, i + 1);
+ state = tables[n][state - 1];
+ }
+ states[n] = state;
+ if (state > 0) matching = true;
+ }
+ }
+ if (edges) {
+ // The start: an end of a needle of MIN_TOKEN_PART_LENGTH bytes or more begins with bytes that stand somewhere in that needle — each of them a byte some needle holds — so only a needle that holds the first ones
+ // is matched. The start and the end are those of the write less an escape cut at either of them (see unfinishedEscape).
+ let first = to - from >= MIN_TOKEN_PART_LENGTH ? bytes.subarray(from, from + MIN_TOKEN_PART_LENGTH) : null;
+ for (let i = 0; first !== null && i < MIN_TOKEN_PART_LENGTH; i += 1) if (inNeedles[bytes[from + i]] === 0) first = null;
+ for (let n = 0; n < needles.length; n += 1) {
+ const needle = needles[n];
+ if (states[n] >= MIN_TOKEN_PART_LENGTH) spans.push(to - states[n], to);
+ if (first === null || needle.indexOf(first) < 0) continue;
+ const length = endsAtStart(needle.length, (i) => needle[i], reversed[n], Math.min(to - from, needle.length), (i) => bytes[from + i]);
+ if (length >= MIN_TOKEN_PART_LENGTH) spans.push(from, from + length);
+ }
+ }
+ if (spans.length === 0) return bytes;
+ const copy = Buffer.from(bytes);
+ for (let i = 0; i < spans.length; i += 2) copy.fill(MASK_BYTE, spans[i], spans[i + 1]);
+ return copy;
}
/**
- * `text` with every token in `tokens` taken out of it — whole, and by each of its parts of 24 characters or more — wherever the text spells it: plainly, with a fold in it, with an escape in it (or a stray backslash), or
- * printed over several lines the way `util.inspect` prints a long string, in colours or not. A text that holds none is returned as the same string. Throws a RangeError for a text that holds too many ways to read a token
- * to be checked (MAX_READINGS): a caller must then not write the text.
+ * `text` with every token in `tokens` taken out of it — whole, by each of its parts of 24 characters or more, and by each of its other spellings (spellingsOf) — wherever the text spells it: plainly, with a fold in it, with
+ * an escape in it (or a stray backslash), or printed over several lines the way `util.inspect` prints a long string, in colours or not; and the beginning of one, 24 characters or more, where the text says it was cut.
+ * With `edges`, the text is read as a whole write is: a needle's beginning at its end, and a needle's end at its start, are taken out too. A text that holds none is returned as the same string. Throws a RangeError for a
+ * text that holds too many ways to read a token to be checked (MAX_READINGS): a caller must then not write the text. `from` (with `edges`): where an escape the last write ended inside is finished — nothing before it is read.
* @param {string} text
* @param {string[]} tokens
+ * @param {{ edges?: boolean, from?: number }} [options]
* @returns {string}
*/
-function redactTokens(text, tokens) {
+function redactTokens(text, tokens, { edges = false, from = 0 } = {}) {
const prepared = prepare(Array.isArray(tokens) ? tokens : []);
- return prepared === null || typeof text !== 'string' || text === '' ? text : redactWith(prepared, text);
+ return prepared === null || typeof text !== 'string' || text === '' ? text : redactWith(prepared, text, edges === true, edges === true ? from : 0);
+}
+
+/**
+ * `bytes` (a Buffer or a Uint8Array) with every token in `tokens` masked — each needle and spelling of it, byte for byte, with as many `*` — in a copy; with `edges`, also a needle's beginning of 24 bytes or more at their
+ * end and a needle's end at their start (from `from`, as for redactTokens). The very bytes when they hold none, and anything that is not bytes as it is.
+ * @template T
+ * @param {T} bytes
+ * @param {string[]} tokens
+ * @param {{ edges?: boolean, from?: number }} [options]
+ * @returns {T | Buffer}
+ */
+function maskTokenBytes(bytes, tokens, { edges = false, from = 0 } = {}) {
+ const prepared = prepare(Array.isArray(tokens) ? tokens : []);
+ return prepared === null || !isUint8Array(bytes) || bytes.length === 0 ? bytes : maskWith(prepared, bytes, edges === true, edges === true ? from : 0);
}
// ---- The tokens this process obtained -------------------------------------------------------------------------------------------------------------------------------------------------------------
@@ -461,17 +803,37 @@ function obtainedTokens() {
return [...obtained];
}
+// What is prepared from the tokens obtained so far, made again only when one has joined.
+function preparedNow() {
+ if (preparedFor.version !== version) preparedFor = { version, prepared: prepare([...obtained]) };
+ return preparedFor.prepared;
+}
+
/**
- * `text` with every token this process has obtained taken out of it. Anything that is not a string — bytes, a number — is returned as it is, and so is a text when no token has been obtained yet. Throws as `redactTokens`
- * does for a text that cannot be checked; every caller then fails closed (the guard on a stream writes a notice instead of the text, a file writer writes nothing and reports the failure).
+ * `text` with every token this process has obtained taken out of it, as a whole text the process writes is read (`edges`: a needle's beginning at its end and a needle's end at its start go too — a write, a file, a result).
+ * Anything that is not a string — bytes, a number — is returned as it is, and so is a text when no token has been obtained yet. Throws as `redactTokens` does for a text that cannot be checked; every caller then fails
+ * closed (the guard on a stream writes a notice instead of the text, a file writer writes nothing and reports the failure).
* @template T
* @param {T} text
* @returns {T}
*/
function redactOutput(text) {
if (typeof text !== 'string' || obtained.size === 0 || text === '') return text;
- if (preparedFor.version !== version) preparedFor = { version, prepared: prepare([...obtained]) };
- return redactWith(preparedFor.prepared, text);
+ return redactWith(preparedNow(), text, true);
+}
+
+/**
+ * What a guarded stream writes in place of `chunk`: a text as `redactOutput` makes it, and bytes with every token this process has obtained masked (maskTokenBytes, with the edges of the write) — the very bytes when they
+ * hold none. `from`: where an escape the stream's last write ended inside is finished (guardStream). Anything else is returned as it is.
+ * @template T
+ * @param {T} chunk
+ * @param {{ from?: number }} [options]
+ * @returns {T | Buffer}
+ */
+function redactWritten(chunk, { from = 0 } = {}) {
+ if (obtained.size === 0) return chunk;
+ if (typeof chunk === 'string') return chunk === '' ? chunk : redactWith(preparedNow(), chunk, true, from);
+ return isUint8Array(chunk) && chunk.length > 0 ? maskWith(preparedNow(), chunk, true, from) : chunk;
}
// ---- The streams, an error that ends the process, and the SDK's workspace --------------------------------------------------------------------------------------------------------------------------
@@ -480,29 +842,79 @@ function redactOutput(text) {
const GUARDED = Symbol.for('power-platform-skills.output-redaction.guarded');
// What is written where a text could not be cleaned (the cleaning itself failed): not the text, which may hold the token — a failure here is rare enough to be loud.
const WITHHELD = '[output withheld: it could not be checked for an access token]\n';
-// A string given with one of these encodings is not text (`write('6162', 'hex')`), so it is not read as text.
+// A string given with one of these encodings is not text (`write('6162', 'hex')`): the stream decodes it into the bytes it writes, so those bytes are what is read.
const BINARY_ENCODINGS = /^(?:hex|base64|base64url)$/i;
/**
- * Makes `stream.write` take the tokens out of every string it is given. The wrapper is the stream's own `write` property, put where the original was: whatever replaces it later replaces it whole, and a caller that wraps it
- * (`const write = stream.write; stream.write = …`) wraps it with the guard inside. Bytes are passed on as they are. Returns false for a stream that is already guarded or has no `write`.
+ * Makes `stream.write` take the tokens out of everything it is given. The wrapper is the stream's own `write` property, put where the original was: whatever replaces it later replaces it whole, and a caller that wraps it
+ * (`const write = stream.write; stream.write = …`) wraps it with the guard inside. A text is given to `redact`; so are bytes — a Buffer or a Uint8Array, and the bytes a string in a binary encoding stands for (decoded as
+ * the stream would decode it) — and where `redact` hands back other bytes, those are written in their place, with the same encoding argument (a stream ignores it for bytes): never a text made of bytes and turned back.
+ * The callback and what `write` returns are the stream's own. A write that ends inside an escape is remembered (a few characters), and the next write is read from after the units that finish it, with `{ from }` given
+ * to `redact`. Returns false for a stream that is already guarded or has no `write`.
* @param {{ write: Function }} stream
- * @param {(text: string) => string} [redact]
+ * @param {(chunk: string | Uint8Array, options: { from: number }) => (string | Uint8Array)} [redact]
* @returns {boolean}
*/
-function guardStream(stream, redact = redactOutput) {
+function guardStream(stream, redact = redactWritten) {
if (!stream || typeof stream.write !== 'function' || stream.write[GUARDED]) return false;
const write = stream.write;
+ // The escape the last write ended inside (`\`, `\u00`, …), or null: the stream's only memory of what it wrote — a few characters, no output — so that the next write, which begins by finishing it, is read from after
+ // it. Without it each write is read on its own, and a JSON `\/` written as `…\` and `/…` lost its `/` to the piece of the token after it: `\<token>`, which is no JSON (see unfinishedEscape).
+ let open = null;
+ const escapeIn = (unitAt, length, head) => {
+ let from = 0;
+ let carried = null;
+ if (open !== null) ({ rest: from, open: carried } = finishEscape(open, head, length));
+ if (carried === null) {
+ const start = unfinishedEscape(unitAt, from, length);
+ if (start < length) carried = openEscapeOf(unitAt, start, length);
+ }
+ return { from, carried };
+ };
+ // The units a finished escape can take at the start of a write: its leading backslashes and six more.
+ const headOf = (unitAt, length, slice) => {
+ let at = 0;
+ while (at < length && unitAt(at) === 0x5c) at += 1;
+ return slice(Math.min(length, at + 6));
+ };
+ // Bumped by every write, so that a write the stream refuses can tell whether a write made inside it (a callback the stream called at once) has moved the memory on since.
+ let writes = 0;
const guarded = function writeWithoutTokens(chunk, ...rest) {
+ const before = open;
let given = chunk;
- if (typeof chunk === 'string' && !(typeof rest[0] === 'string' && BINARY_ENCODINGS.test(rest[0]))) {
- try {
- given = redact(chunk);
- } catch {
- given = WITHHELD;
+ try {
+ let bytes = null;
+ if (typeof chunk === 'string' && typeof rest[0] === 'string' && BINARY_ENCODINGS.test(rest[0])) bytes = Buffer.from(chunk, rest[0]);
+ else if (isUint8Array(chunk)) bytes = chunk;
+ if (bytes !== null) {
+ const unitAt = (i) => bytes[i];
+ const { from, carried } = escapeIn(unitAt, bytes.length, headOf(unitAt, bytes.length, (end) => Buffer.from(bytes.buffer, bytes.byteOffset, end).toString('latin1')));
+ const masked = redact(bytes, { from });
+ open = carried;
+ if (masked !== bytes) given = masked;
+ } else if (typeof chunk === 'string') {
+ const unitAt = (i) => chunk.charCodeAt(i);
+ const { from, carried } = escapeIn(unitAt, chunk.length, headOf(unitAt, chunk.length, (end) => chunk.slice(0, end)));
+ given = redact(chunk, { from });
+ open = carried;
+ } else {
+ open = null;
}
+ } catch {
+ open = null;
+ given = WITHHELD;
+ }
+ // The memory is this write's before the stream takes it, so that a callback the stream calls at once, and writes from, reads on from it. A write the stream REFUSES — it throws (an encoding it does not know, a
+ // chunk that is no text and no bytes, a stream already ended) — wrote nothing, so the memory goes back to what the last written one left, unless a write made inside it has moved it on; the error is the
+ // stream's own. A write that returns false was taken (the stream asks the writer to wait): its memory stands.
+ writes += 1;
+ const mine = writes;
+ try {
+ return write.call(this, given, ...rest);
+ } catch (error) {
+ if (writes === mine) open = before;
+ throw error;
}
- return write.call(this, given, ...rest);
};
guarded[GUARDED] = true;
stream.write = guarded;
@@ -626,9 +1038,11 @@ function guardWorkspaceStorage(storage, redact = redactOutput) {
module.exports = {
TOKEN_MARKER,
needlesOf,
+ spellingsOf,
noteToken,
obtainedTokens,
redactTokens,
+ maskTokenBytes,
redactOutput,
guardStream,
makeWritesBlocking,
diff --git a/plugins/model-apps/scripts/lib/page-binding-targets.js b/plugins/model-apps/scripts/lib/page-binding-targets.js
new file mode 100644
index 000000000..3f4fe1080
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/page-binding-targets.js
@@ -0,0 +1,358 @@
+'use strict';
+// What a rebuild checks of the environment it writes a page's bindings into.
+//
+// A binding names what it goes through — a connection reference by the logical name a page calls it by, a Custom API by its unique name — and the spec can state the name and the connector the binding was made for
+// (`connectorId`) but cannot make the reference: a connection holds a user's sign-in, and a Custom API is a solution component. So before a rebuild writes a binding it reads what the environment has for the names
+// the spec states (readBindingTargets) and judges it (judgeBindingTargets):
+// - a reference that exists for ANOTHER connector is refused. The page calls a binding through the reference's logical name, so it would call that connector's operation under this name, with the signed-in user's
+// connection to it, and the name cannot tell the two apart. Nothing is guessed or made: the author gives the binding a name that is the right reference's, or states the connector this environment has;
+// - a reference or a Custom API that is not there is said by name. The page is written with its binding all the same: the page finds the reference by name when it runs, so one made afterwards makes the page work
+// without a rebuild;
+// - a Custom API of the other kind (an Action for a Function) or bound to another table is said by name: the runtime refuses such a call before it is sent, so it is a warning and never a refusal;
+// - a reference of the right connector that has NO connection is said by name — what a solution import leaves when no settings file gives one: the page's calls through it fail until it has one;
+// - an operation a binding calls that the connector there does not define is said by name, where the environment holds the connector's definition. A connector the platform publishes — every connector that is
+// not a custom one — has one definition for every environment of its cloud, the one the binding's operations were read from (connector.js), so a reference for the same connector offers them, and nothing is
+// read for it. A CUSTOM connector's definition is a row of the environment it is in (the `connector` table's `openapidefinition`, which the reference points at through `customconnectorid`), and the copy
+// there can be another version than the page was made with: that one is read, and an operation it does not define is a warning — the call fails, it does not reach another service.
+// A read that fails is said — the bindings were not checked — and never read as "nothing is there"; a row that answers without a column the check needs (successful but incomplete) is said the same way, as
+// not checked, and never read as "compatible". Nothing is refused without evidence that contradicts the binding.
+const { odataLit } = require('./odata.js');
+const { normalizePageSource } = require('./app-spec.js');
+const { PAGE_BINDINGS, statedPageBindings } = require('./page-bindings.js');
+
+// A filter is bounded: the names of a long list are read in requests of this many, not in one URL.
+const CHUNK = 25;
+// A name is quoted in a message as far as a reader needs to find it, not as far as it goes on.
+const MAX_SHOWN = 80;
+const shown = (name) => {
+ const text = String(name);
+ return text.length > MAX_SHOWN ? `${text.slice(0, MAX_SHOWN - 3)}...` : text;
+};
+const quoted = (name) => JSON.stringify(shown(name));
+
+// The name of a connector, whatever form its id is written in: the last segment of its path, lower-cased.
+// /providers/Microsoft.PowerApps/apis/shared_msnweather a connection reference's `connectorid`, and what the planner writes into a binding
+// shared_msnweather the bare name
+// Two ids name the same connector when their names are equal. A custom connector's name is `shared_<name>-5f<hash>`, and the same connector made separately in two environments has another hash in each, so a
+// binding made with one does not match the other: that is a conflict the author settles by stating the connector this environment has. null when there is no name.
+// See: https://learn.microsoft.com/power-platform/admin/connector-reference-in-the-environment
+function connectorKey(id) {
+ if (typeof id !== 'string') return null;
+ const last = id.trim().replace(/\/+$/, '').split('/').pop().toLowerCase();
+ return last || null;
+}
+
+// The connector ids that are COMPARED, each checked for its syntax first — a value of another shape is evidence of nothing, so it is never compared, and so never a conflict (it is reported as not checked).
+// a reference row's `connectorid` exactly the API id Dataverse writes: `/providers/Microsoft.PowerApps/apis/shared_<name>` — a standard connector (`shared_msnweather`) or a custom one
+// (`shared_contoso-5fwidgets-5f6a8c`, whose own identity is the `_customconnectorid_value` lookup). `***`, a bare name, a number or an object is not one.
+// a binding's `connectorId` that API id, or its bare `shared_<name>` (both are what a spec may state; references/connectors.md)
+// Each answers the lower-cased connector name, or null.
+const CONNECTOR_API_ID = /^\/providers\/Microsoft\.PowerApps\/apis\/(shared_[A-Za-z0-9_.-]{1,128})$/i;
+const CONNECTOR_NAME = /^(shared_[A-Za-z0-9_.-]{1,128})$/i;
+const referenceConnectorKey = (id) => (typeof id === 'string' && CONNECTOR_API_ID.test(id) ? id.match(CONNECTOR_API_ID)[1].toLowerCase() : null);
+const bindingConnectorKey = (id) => (typeof id === 'string' && (CONNECTOR_API_ID.test(id) || CONNECTOR_NAME.test(id)) ? connectorKey(id) : null);
+
+// The pages a build writes that state a binding: [{ key, name, connectorBindings?, actionBindings? }], with the lists as the spec states them, in the spec's order. A page with no source the build can deploy is not
+// written, and a page that states no entry has nothing to check. A changed-only run writes the pages it selected and any page another one navigates to (the build makes an absent target first, from its own
+// spec entry, so it may have to write it), and no other.
+function pagesStatingBindings(spec, { changedOnly } = {}) {
+ const pages = Array.isArray(spec && spec.pages) ? spec.pages : [];
+ const selected = changedOnly && Array.isArray(changedOnly.selectedKeys) ? new Set(changedOnly.selectedKeys) : null;
+ const navigatedTo = new Set(pages.flatMap((page) => ((page && page.navigatesTo) || []).map((target) => target && target.targetKey)));
+ const out = [];
+ for (const page of pages) {
+ const source = normalizePageSource(page);
+ if (!(source && source.kind === 'tsx' && source.codeFile)) continue;
+ const key = page.key || page.name;
+ if (selected && !selected.has(key) && !navigatedTo.has(key)) continue;
+ const lists = statedPageBindings(page);
+ if (!Object.values(lists).some((list) => list.length)) continue;
+ out.push({ key, name: page.name, ...lists });
+ }
+ return out;
+}
+
+// The names the pages state for one kind of binding: each once, as the first page spells it (the service compares them without regard to case, and the match here is made in lower case).
+function namesOf(pages, kind) {
+ const identity = PAGE_BINDINGS[kind];
+ const names = new Map();
+ for (const page of pages) {
+ for (const entry of page[kind] || []) {
+ const name = entry && typeof entry[identity] === 'string' ? entry[identity].trim() : '';
+ if (name && !names.has(name.toLowerCase())) names.set(name.toLowerCase(), name);
+ }
+ }
+ return [...names.values()];
+}
+
+async function readNamed(provision, entity, select, column, names) {
+ const rows = [];
+ for (let at = 0; at < names.length; at += CHUNK) {
+ const filter = names.slice(at, at + CHUNK).map((name) => `${column} eq '${odataLit(name)}'`).join(' or ');
+ rows.push(...((await provision.queryRecords(entity, { select, filter, paginate: true })) || []));
+ }
+ return rows;
+}
+
+const text = (value) => (typeof value === 'string' && value.trim() ? value : undefined);
+
+const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+// The operations a binding calls (`operations`, the operation ids `executeConnectorOperation` is given), each once, in its order.
+function operationsOf(entry) {
+ const listed = entry && Array.isArray(entry.operations) ? entry.operations : [];
+ return [...new Set(listed.filter((operation) => typeof operation === 'string' && operation !== ''))];
+}
+
+// The HTTP methods under which a Swagger 2.0 path item holds an operation. Its other members — `parameters` (shared by its operations), `$ref`, an `x-ms-…` extension — are not operations.
+// See: https://swagger.io/specification/v2/#path-item-object
+const HTTP_METHODS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch'];
+
+// The operation ids a custom connector's definition declares — its `openapidefinition`, the Swagger 2.0 document the connector was made from, as text:
+// { "swagger": "2.0", "info": { … }, "host": "widgets.contoso.example",
+// "paths": { "/widgets": { "parameters": [ … ], "get": { "operationId": "ListWidgets", … }, "post": { "operationId": "AddWidget", … } }, "/widgets/{id}": { "get": { "operationId": "GetWidget", … } } } }
+// as a Set, matched exactly — case included — as the bundled SDK matches a connector's operation ids (projectConnectorOperations, which is how connector.js lists the ids a binding's `operations` hold).
+// null when the text is not such a document, or holds a path item it cannot see into (a `$ref` to one elsewhere): its operations are then NOT checked, which is never "it defines none".
+function definedOperations(definition) {
+ let document;
+ try {
+ document = typeof definition === 'string' ? JSON.parse(definition.replace(/^\uFEFF/, '')) : null;
+ } catch {
+ return null;
+ }
+ const paths = document && typeof document === 'object' && !Array.isArray(document) ? document.paths : null;
+ if (!paths || typeof paths !== 'object' || Array.isArray(paths)) return null;
+ const ids = new Set();
+ for (const item of Object.values(paths)) {
+ if (!item || typeof item !== 'object' || Array.isArray(item) || Object.prototype.hasOwnProperty.call(item, '$ref')) return null;
+ for (const method of HTTP_METHODS) {
+ const operation = item[method];
+ if (operation && typeof operation === 'object' && typeof operation.operationId === 'string' && operation.operationId !== '') ids.add(operation.operationId);
+ }
+ }
+ return ids;
+}
+
+// The definitions of the custom connectors `ids` names (lower-cased `connector` ids): Map<id, Set<operation id> | { problem }>. A connector the read does not return, a definition that is not a document
+// this reads (definedOperations), and a read that fails are each a `problem` of the connectors it concerns — never an empty definition.
+// A `connector` row as the Web API answers it (https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/connector):
+// { "connectorid": "c0000000-0000-4000-8000-0000000000a1", "openapidefinition": "{\"swagger\":\"2.0\",\"paths\":{…}}" }
+async function readDefinitions(reader, ids) {
+ const definitions = new Map();
+ try {
+ if (!reader) throw new Error('the rows cannot be read here');
+ for (let at = 0; at < ids.length; at += CHUNK) {
+ const filter = ids.slice(at, at + CHUNK).map((id) => `connectorid eq ${id}`).join(' or ');
+ for (const row of (await reader.queryRecords('connector', { select: ['connectorid', 'openapidefinition'], filter, paginate: true })) || []) {
+ const id = row && typeof row.connectorid === 'string' ? row.connectorid.toLowerCase() : '';
+ if (!ids.includes(id) || definitions.has(id)) continue;
+ const defined = definedOperations(row.openapidefinition);
+ definitions.set(id, defined || { problem: 'its definition is not a Swagger document this build can read' });
+ }
+ }
+ for (const id of ids) if (!definitions.has(id)) definitions.set(id, { problem: 'no connector row of that id was found' });
+ } catch (error) {
+ for (const id of ids) definitions.set(id, { problem: String((error && error.message) || error) });
+ }
+ return definitions;
+}
+
+// What the environment has for the names `pages` state: { references, apis, definitions, problems }.
+// references Map<lower-cased logical name, { connectorId, connected?, customConnectorId? }> of the connection references (`connectionreference` rows) — or null when no page states a connector binding, or
+// the read failed. Each piece is kept only as the row PROVES it, and anything else is left out — which judgeBindingTargets reads as "not known", never as "fine":
+// connectorId the row's `connectorid` when it is a connector's API id (referenceConnectorKey); absent, null, blank or of any other shape leaves it out (the connector is then not compared)
+// connected true or false when the row's `connectionid` is a text or null (null or blank: no connection); absent, or a value of another type, leaves it out (whether it has one is then
+// not checked)
+// customConnectorId the lower-cased GUID in `_customconnectorid_value`; absent, null or not a GUID leaves it out. A null lookup is NOT proof that the connector is not a custom one — a reference
+// made through the Web API can leave it unset — so the operations through such a reference are reported as not checked, not as defined
+// SUCCESSFUL BUT INCOMPLETE: a read that answers 200 with a row that lacks a column is as much "not known" as a read that fails. Nothing here infers compatibility from a value that is not there.
+// apis Map<lower-cased unique name, { isFunction, boundEntity? }> of the Custom APIs (`customapi` rows) — or null likewise
+// definitions Map<custom connector id, Set<operation id> | { problem }> (readDefinitions) of the custom connectors a binding that calls operations goes through — or null when there is none
+// problems { references?, apis? }: why a read failed, as the service said it. A failed read does not stop the other, and is never an empty answer.
+// Only the rows of the names asked for are kept, whatever the service answered.
+// A connection reference row as the Web API answers it (https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/connectionreference); `connectionid` is null while it has no
+// connection, and `_customconnectorid_value` null when no custom connector is recorded for it:
+// { "connectionreferencelogicalname": "contoso_msnweather", "connectorid": "/providers/Microsoft.PowerApps/apis/shared_msnweather", "connectionid": "shared-msnweather-…", "_customconnectorid_value": null }
+// and a Custom API row (https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/customapi), `bindingtype` 0 Global, 1 Entity, 2 EntityCollection:
+// { "uniquename": "contoso_ApproveOrder", "isfunction": false, "bindingtype": 1, "boundentitylogicalname": "contoso_item" }
+async function readBindingTargets(provision, pages) {
+ const targets = { references: null, apis: null, definitions: null, problems: {} };
+ const reader = provision && typeof provision.queryRecords === 'function' ? provision : null;
+ const read = async (kind, entity, select, column, keyOf, valueOf, target) => {
+ const names = namesOf(pages, kind);
+ if (!names.length) return;
+ try {
+ if (!reader) throw new Error('the rows cannot be read here');
+ const wanted = new Set(names.map((name) => name.toLowerCase()));
+ const found = new Map();
+ for (const row of await readNamed(reader, entity, select, column, names)) {
+ const key = row && typeof keyOf(row) === 'string' ? keyOf(row).trim().toLowerCase() : '';
+ if (key && wanted.has(key) && !found.has(key)) found.set(key, valueOf(row));
+ }
+ targets[target] = found;
+ } catch (error) {
+ targets.problems[target] = String((error && error.message) || error);
+ }
+ };
+ await read('connectorBindings', 'connectionreference', ['connectionreferencelogicalname', 'connectorid', 'connectionid', '_customconnectorid_value'], 'connectionreferencelogicalname',
+ (row) => row.connectionreferencelogicalname,
+ (row) => ({
+ // Only a connector id of the shape Dataverse writes is kept (referenceConnectorKey): a malformed one is left out, and so read as not known — never as a connector to refuse a binding over.
+ ...(referenceConnectorKey(row.connectorid) ? { connectorId: row.connectorid } : {}),
+ // A text is the connection (blank: none), and null is none; any other value — a number, an object — says nothing, and is left out like an absent column.
+ ...(row.connectionid === null || typeof row.connectionid === 'string' ? { connected: Boolean(text(row.connectionid)) } : {}),
+ ...(typeof row._customconnectorid_value === 'string' && GUID.test(row._customconnectorid_value) ? { customConnectorId: row._customconnectorid_value.toLowerCase() } : {}),
+ }), 'references');
+ // The definitions of the custom connectors the bindings that call operations go through — each once, by id. A binding that calls none needs none, and one whose reference names no custom connector cannot
+ // be given one: its operations are reported as not checked (judgeBindingTargets).
+ if (targets.references instanceof Map) {
+ const ids = [];
+ for (const page of pages) {
+ for (const entry of page.connectorBindings || []) {
+ const name = entry && typeof entry[PAGE_BINDINGS.connectorBindings] === 'string' ? entry[PAGE_BINDINGS.connectorBindings].trim().toLowerCase() : '';
+ const reference = name ? targets.references.get(name) : undefined;
+ if (reference && reference.customConnectorId && operationsOf(entry).length && !ids.includes(reference.customConnectorId)) ids.push(reference.customConnectorId);
+ }
+ }
+ if (ids.length) targets.definitions = await readDefinitions(reader, ids);
+ }
+ await read('actionBindings', 'customapi', ['uniquename', 'isfunction', 'bindingtype', 'boundentitylogicalname'], 'uniquename',
+ (row) => row.uniquename,
+ (row) => ({ isFunction: row.isfunction === true, ...(text(row.boundentitylogicalname) && Number(row.bindingtype) !== 0 ? { boundEntity: row.boundentitylogicalname } : {}) }), 'apis');
+ return targets;
+}
+
+const joined = (names) => names.map(shown).join(', ');
+const plural = (names, one, many) => (names.length === 1 ? one : many);
+const pagesWords = (pages) => `${plural(pages, 'page', 'pages')} ${pages.map((page) => quoted(page.name)).join(', ')}`;
+
+// What `targets` says of the bindings `pages` state: { findings, unchecked }.
+// findings [{ severity: 'refuse' | 'warn', kind, page: { key, name }, text, … }], a page at a time, in the order a page lists its bindings: its connector conflicts, the references it has none of, the references it
+// has with no connection, the operations a custom connector there does not define, the Custom APIs it has none of, the Custom APIs that are not as the binding says. `refuse` is a connector conflict
+// and nothing else: a binding that is refused is not judged further.
+// unchecked [{ what, text }] for what could not be checked, and why: a page at a time, what its references' rows did not say (their connector, whether they have a connection, which custom connector they
+// are for), then the operations of a binding whose custom connector's definition could not be read; then each read that failed. Missing evidence is never a finding and never "compatible".
+function judgeBindingTargets(pages, targets) {
+ const findings = [];
+ const unchecked = [];
+ const nameOf = (entry, identity) => (entry && typeof entry[identity] === 'string' && entry[identity].trim() ? entry[identity].trim() : undefined);
+ const sameName = (names, name) => names.some((seen) => seen.toLowerCase() === name.toLowerCase());
+ for (const page of pages) {
+ const at = { key: page.key, name: page.name };
+ const connectors = (page.connectorBindings || []).filter((entry) => nameOf(entry, PAGE_BINDINGS.connectorBindings));
+ const actions = (page.actionBindings || []).filter((entry) => nameOf(entry, PAGE_BINDINGS.actionBindings));
+ const missingReferences = [];
+ const disconnected = [];
+ const undefinedOperations = [];
+ // What the rows did not say (readBindingTargets keeps a piece only as a row proves it): kept apart from what they said, and reported as not checked.
+ const connectorUnknown = [];
+ const connectionUnknown = [];
+ const customUnknown = [];
+ const missingApis = [];
+ const mismatches = [];
+ if (targets.references instanceof Map) {
+ for (const entry of connectors) {
+ const name = nameOf(entry, PAGE_BINDINGS.connectorBindings);
+ const reference = targets.references.get(name.toLowerCase());
+ if (!reference) {
+ if (!sameName(missingReferences, name)) missingReferences.push(name);
+ continue;
+ }
+ // A conflict is only ever PROVEN: both sides name a connector, and they are not the same one.
+ const expected = bindingConnectorKey(entry.connectorId);
+ const found = referenceConnectorKey(reference.connectorId);
+ if (expected && found && expected !== found) {
+ findings.push({
+ severity: 'refuse', kind: 'connector-conflict', page: at, binding: name, expected, found,
+ text: `page ${quoted(page.name)}: connector binding ${quoted(name)} is for connector ${shown(expected)}, but the connection reference of that name in this environment is for connector ${shown(found)}`,
+ });
+ continue;
+ }
+ // The binding names a connector and the row did not say which one the reference is for: nothing contradicts the binding, and nothing proves it either.
+ if (expected && !found && !sameName(connectorUnknown, name)) connectorUnknown.push(name);
+ // Only a row that says it has no connection is one with none; a row that does not carry the column says nothing (readBindingTargets).
+ if (reference.connected === false && !sameName(disconnected, name)) disconnected.push(name);
+ if (reference.connected === undefined && !sameName(connectionUnknown, name)) connectionUnknown.push(name);
+ // The operations of a custom connector, whose definition is the environment's own (see the header). A reference that names no custom connector — the lookup absent, null or not a GUID — is not
+ // proven to be for a connector the platform publishes, so its operations are not checked, and that is said.
+ const operations = operationsOf(entry);
+ if (!operations.length) continue;
+ if (!reference.customConnectorId) {
+ if (!sameName(customUnknown, name)) customUnknown.push(name);
+ continue;
+ }
+ const defined = targets.definitions instanceof Map ? targets.definitions.get(reference.customConnectorId) : undefined;
+ if (!(defined instanceof Set)) {
+ const why = defined && defined.problem ? defined.problem : 'its definition was not read';
+ const said = `could not read the definition of the custom connector that connection reference ${shown(name)} is for in this environment (${shown(why)}), so the operations connector binding ${quoted(name)} of page ${quoted(page.name)} calls were not checked against it`;
+ if (!unchecked.some((u) => u.text === said)) unchecked.push({ what: 'custom connector definitions', text: said });
+ continue;
+ }
+ const absent = operations.filter((operation) => !defined.has(operation));
+ if (!absent.length) continue;
+ const said = `page ${quoted(page.name)}: connector binding ${quoted(name)} calls ${plural(absent, 'operation', 'operations')} ${joined(absent)}, which the custom connector that connection reference is for in this environment does not define, so the page's ${plural(absent, 'call to it fails', 'calls to them fail')} there until it does (import the solution that holds the connector as the page was made with it)`;
+ if (!undefinedOperations.some((u) => u.text === said)) undefinedOperations.push({ binding: name, operations: absent, text: said });
+ }
+ }
+ if (missingReferences.length) {
+ findings.push({
+ severity: 'warn', kind: 'reference-missing', page: at, names: missingReferences,
+ text: `page ${quoted(page.name)}: ${plural(missingReferences, 'connection reference', 'connection references')} ${joined(missingReferences)} ${plural(missingReferences, 'is', 'are')} not in this environment, so the page is written with ${plural(missingReferences, 'a binding', 'bindings')} it cannot resolve yet. A page finds its connector by the ${plural(missingReferences, "reference's logical name", "references' logical names")}: create the ${plural(missingReferences, 'reference', 'references')} here (create-connection-reference.js, or import the solution that holds ${plural(missingReferences, 'it', 'them')}) and the page works without a rebuild`,
+ });
+ }
+ if (disconnected.length) {
+ const them = plural(disconnected, 'it', 'them');
+ findings.push({
+ severity: 'warn', kind: 'connection-missing', page: at, names: disconnected,
+ text: `page ${quoted(page.name)}: ${plural(disconnected, 'connection reference', 'connection references')} ${joined(disconnected)} ${plural(disconnected, 'is', 'are')} in this environment but ${plural(disconnected, 'has', 'have')} no connection, so the page's calls through ${them} fail until ${plural(disconnected, 'it has', 'they have')} one. Give ${them} a connection (import the solution that holds ${them} with a settings file that does: solution-settings.js, or set ${them} in Power Apps, in the solution's connection references) and the page works without a rebuild`,
+ });
+ }
+ for (const missing of undefinedOperations) findings.push({ severity: 'warn', kind: 'operation-missing', page: at, binding: missing.binding, operations: missing.operations, text: missing.text });
+ // What the rows did not say, a page at a time and by name: never "fine", never a refusal.
+ const bindingsWords = (names) => `${plural(names, 'connector binding', 'connector bindings')} ${names.map(quoted).join(', ')} of page ${quoted(page.name)}`;
+ if (connectorUnknown.length) unchecked.push({ what: 'reference connectors', text: `this environment's ${plural(connectorUnknown, 'row', 'rows')} for connection ${plural(connectorUnknown, 'reference', 'references')} ${joined(connectorUnknown)} did not give a connector id this build can read (absent, or not of the form /providers/Microsoft.PowerApps/apis/shared_<name>), so whether ${bindingsWords(connectorUnknown)} ${plural(connectorUnknown, 'goes', 'go')} through the connector ${plural(connectorUnknown, 'it was', 'they were')} made for was not checked` });
+ if (connectionUnknown.length) unchecked.push({ what: 'reference connections', text: `this environment's ${plural(connectionUnknown, 'row', 'rows')} for connection ${plural(connectionUnknown, 'reference', 'references')} ${joined(connectionUnknown)} did not say, in a form this build can read, whether ${plural(connectionUnknown, 'it has', 'they have')} a connection, so that was not checked for page ${quoted(page.name)}` });
+ if (customUnknown.length) unchecked.push({ what: 'custom connector definitions', text: `the operations that ${bindingsWords(customUnknown)} call were not checked: this environment does not name a custom connector for ${plural(customUnknown, 'its connection reference', 'their connection references')}, and only a custom connector's definition is read here (a connector the platform publishes defines the same operations in every environment of its cloud)` });
+ if (targets.apis instanceof Map) {
+ for (const entry of actions) {
+ const name = nameOf(entry, PAGE_BINDINGS.actionBindings);
+ const api = targets.apis.get(name.toLowerCase());
+ if (!api) {
+ if (!sameName(missingApis, name)) missingApis.push(name);
+ continue;
+ }
+ // `isFunction` that is not stated is an Action, as references/custom-api.md says; `boundEntityLogicalName` that is not stated is a Global operation.
+ const refused = (what) => `the runtime refuses the call (${what})`;
+ if (Boolean(entry.isFunction) !== api.isFunction) {
+ mismatches.push({
+ binding: name,
+ text: `page ${quoted(page.name)}: Custom API binding ${quoted(name)} says it is ${entry.isFunction ? 'a Function' : 'an Action'}, but the Custom API of that name in this environment is ${api.isFunction ? 'a Function' : 'an Action'} — ${refused('wrong_operation_kind')}`,
+ });
+ }
+ const wantsTable = text(entry.boundEntityLogicalName);
+ if ((wantsTable || '').toLowerCase() !== (api.boundEntity || '').toLowerCase()) {
+ const says = wantsTable ? `is bound to table ${shown(wantsTable)}` : 'is for a Global operation';
+ const finds = api.boundEntity ? `is bound to table ${shown(api.boundEntity)}` : 'is Global';
+ mismatches.push({ binding: name, text: `page ${quoted(page.name)}: Custom API binding ${quoted(name)} ${says}, but the Custom API of that name in this environment ${finds} — ${refused('invalid_bound_to')}` });
+ }
+ }
+ }
+ if (missingApis.length) {
+ findings.push({
+ severity: 'warn', kind: 'api-missing', page: at, names: missingApis,
+ text: `page ${quoted(page.name)}: ${plural(missingApis, 'Custom API', 'Custom APIs')} ${joined(missingApis)} ${plural(missingApis, 'is', 'are')} not in this environment (list-custom-apis.js lists what it has), so a call through ${plural(missingApis, 'the binding is', 'a binding is')} refused until ${plural(missingApis, 'it is', 'they are')} deployed here`,
+ });
+ }
+ for (const mismatch of mismatches) findings.push({ severity: 'warn', kind: 'api-mismatch', page: at, binding: mismatch.binding, text: mismatch.text });
+ }
+ const unread = (what, kind, problem, listed) => {
+ if (!problem) return;
+ const affected = pages.filter((page) => (page[kind] || []).some((entry) => nameOf(entry, PAGE_BINDINGS[kind])));
+ if (affected.length) unchecked.push({ what, text: `could not read this environment's ${what} (${shown(problem)}), so the ${listed} of ${pagesWords(affected)} were not checked against them` });
+ };
+ unread('connection references', 'connectorBindings', targets.problems && targets.problems.references, 'connector bindings');
+ unread('Custom APIs', 'actionBindings', targets.problems && targets.problems.apis, 'Custom API bindings');
+ return { findings, unchecked };
+}
+
+module.exports = { connectorKey, pagesStatingBindings, readBindingTargets, judgeBindingTargets, definedOperations };
diff --git a/plugins/model-apps/scripts/lib/page-bindings.js b/plugins/model-apps/scripts/lib/page-bindings.js
new file mode 100644
index 000000000..75360ddb6
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/page-bindings.js
@@ -0,0 +1,257 @@
+'use strict';
+// A generative page's connector and Custom API bindings: what an App Spec states of them, and how a rebuild reads what it states against a page that holds more.
+//
+// A page holds two lists in its config.json beside its data sources and its model — `connectorBindings` (each entry goes through a connection reference, found by its logical name) and `actionBindings` (each
+// names a Custom API by its unique name). As a page holds them (references/connectors.md and references/custom-api.md say what each property means):
+// { "connectorBindings": [ { "logicalName": "new_msnweather", "connectorId": "/providers/Microsoft.PowerApps/apis/shared_msnweather", "dataset": "", "operations": ["CurrentWeather"] } ],
+// "actionBindings": [ { "name": "new_ApproveOrder", "isFunction": false, "boundEntityLogicalName": "salesorder", "displayName": "Approve Order", "parameterKinds": { "Comment": "String" } } ] }
+//
+// THREAT MODEL. An entry can hold more than that, and anything at all in it: genpage-upload.js writes any JSON array it is given into the list, so an entry can carry a connection id of the environment it was
+// made in, a credential someone put in a connectors.json — as a property, as the NAME of a property, inside a URL's user-info, query or fragment, percent-encoded, in a map's keys — or a property a later runtime
+// adds. The App Spec is what is committed, reviewed and shared, and a download's stderr and JSON result go to a terminal, a log and an agent's context. So nothing of a binding reaches any of them unless it is
+// KNOWN to be safe, and the rule fails closed:
+// - a key is stated only when it is one of the properties the two references document (FIELDS), and a key of `parameterKinds` only when it is shaped like a request parameter's unique name and not like a token;
+// - a value is stated only when it has a conservative shape that is positively known (SHAPES): an identifier, a GUID, a plain name or label, or a URL whose PARSED form (`new URL`) has no user-info, no query and
+// no fragment and whose decoded path is plain names, and whose text is ALREADY that parsed form (no dot-segment the parser would remove — the text that is persisted is the text that is checked). A value
+// that merely does not look like a credential is not enough — a credential has more forms than any list of them (a token alone in a URL's
+// user-info, `api%5Fkey=` in a query, `#access_token=` in a fragment, a bare token as a key);
+// - a list in which ANY entry holds anything else is left out of the spec WHOLE. Nothing is projected out of it, because an entry stated without what it was found by (`logicalName`, `name`) or without a
+// property it held would make a rebuild REPLACE the page's entry with less (mergeBindings matches entries by that identity). A list that is left out is a list a rebuild does not send, and the page keeps
+// its own as it is: no write and no publish.
+// SINKS — every place a binding's text can go, and what goes there:
+// app-spec.json (download-model-app.js, through hydrateSpec) only a list every entry of which is stated whole (statableBindings);
+// the download's stderr and JSON result (pageBindingsNote, pageBindingsReport: `pages`, `neededInTarget`, `notCarried`) the names of the bindings of a list that is stated (identifiers, by SHAPES), and for a list
+// left out its kind, the place of the entry and the vetted name of the property — or "an unrecognized property" — never a value and never an unrecognized key (listProblemText);
+// validateAppSpec's errors and warnings (lib/app-spec.js) the same words (bindingProblemText);
+// the build's warnings and halt (lib/page-binding-targets.js, lib/sdk-build.js) binding names of a spec that passed validateAppSpec, so of the shapes above.
+// The page folder's own config.json is the page as the environment holds it, written before the spec and not by these rules: it holds everything, and the download's note says so.
+//
+// That is why `mergeBindings` still matters. A spec that states an entry says nothing of the properties it does not state (an author who writes a list by hand, or a page that gains a property after it was
+// downloaded), so a rebuild into the environment the page is in must not take them away: it reads the entries a spec states as "what the page holds of these properties", writes a list only when that differs,
+// and when it writes, keeps on each entry what the spec does not state.
+const { compareText } = require('./compare-text.js');
+const { PARAMETER_KINDS } = require('./custom-api-kinds.js');
+
+// Each list of a page, with the property its entries are found by: a connector binding by the logical name of the connection reference it goes through, a Custom API binding by the API's unique name.
+const PAGE_BINDINGS = { connectorBindings: 'logicalName', actionBindings: 'name' };
+
+const MAX_LIST = 1000;
+
+// A text that is shaped like a token, wherever it stands — a name, a label, a key, a path segment. A conservative shape alone would let a token through when it happens to fit one (`ghp_` + 36 letters is an
+// identifier), so every shape below is also held to this:
+// - the prefixes of the token formats that announce themselves: `ghp_`/`gho_`/`ghu_`/`ghs_`/`ghr_`/`github_pat_` (GitHub), `xoxb-`… (Slack), `sk-`/`sk_live_`/`pk_live_`/`rk_live_` (API keys),
+// `AKIA`/`ASIA` (AWS access keys), `AIza` (Google), `ya29.` (OAuth), `eyJ` (the base64 of `{"`, which opens every JSON Web Token), an `npm_` token;
+// - an authorization scheme followed by a credential: `Bearer …`, `Basic …`;
+// - a run of 32 or more letters and digits that holds both — a hex digest, a key, a GUID written without its dashes. A connector's or reference's own random suffix is far shorter (`-5f6a8c`), and a
+// word of 32 letters has no digit.
+// A label that is flagged leaves its list out of the spec: a false positive costs the page's list its portability, and the page keeps it.
+const TOKEN_PREFIX = /(?:^|[^A-Za-z0-9])(?:gh[pousr]_|github_pat_|xox[abposr]-|sk-|sk_(?:live|test)_|pk_(?:live|test)_|rk_(?:live|test)_|AKIA|ASIA|AIza|ya29\.|eyJ|npm_)/;
+const AUTH_SCHEME = /(?:^|\s)(?:bearer|basic|negotiate|digest)\s+\S/i;
+const tokenLike = (text) => TOKEN_PREFIX.test(text) || AUTH_SCHEME.test(text) || (text.match(/[A-Za-z0-9]{32,}/g) || []).some((run) => /[0-9]/.test(run) && /[A-Za-z]/.test(run));
+
+// The conservative shapes a value may have. Each is a positive description of what the value IS; anything outside it is not stated.
+// identifier a connection reference's logical name, a table's logical name, a Custom API's unique name, an operation id: a letter, then letters, digits, `_`, `.` and `-` (up to 128)
+// guid a SharePoint list id, a table id: 8-4-4-4-12 hex digits
+// name a SQL dataset (`server,database`), a table name (`[dbo].[Orders]`), a dataset key (`default`): letters, digits, space and `_ . , : - [ ] ( )` (up to 256), opening with a letter, a digit or `[`
+// label what a person reads — a display name: letters (any script), marks, digits, dashes, space and `_ . , ; : ' ( ) & + !` (up to 256). No `/`, `@`, `=`, `?`, `#`, `%` or quote, so no URL and no key=value
+// url a SharePoint site and the like: `new URL` parses it as http(s), with no user-info (`user@`, `user:pass@`), no query and no fragment — the raw text holds no `?`, `#` or `@` at all — a host of DNS
+// labels, an optional port, and a path whose segments, decoded, are labels — written exactly as `new URL` gives it back (isSafeUrl)
+// An empty text is a value only where the reference documents one: a connector binding's `dataset` is `""` for a REST connector.
+const IDENTIFIER = /^[A-Za-z][A-Za-z0-9_.-]{0,127}$/;
+const GUID = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
+const NAME = /^[A-Za-z0-9[][A-Za-z0-9 _.,:\-[\]()]{0,255}$/;
+const LABEL = /^[\p{L}\p{M}\p{N}\p{Pd} _.,;:'()&+!]{1,256}$/u;
+const DNS_HOST = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/;
+const isIdentifier = (value) => typeof value === 'string' && IDENTIFIER.test(value) && !tokenLike(value);
+const isGuid = (value) => typeof value === 'string' && GUID.test(value);
+const isName = (value) => typeof value === 'string' && NAME.test(value) && !tokenLike(value);
+const isLabel = (value) => typeof value === 'string' && LABEL.test(value) && !tokenLike(value);
+// The `new URL` of a WHATWG parser is what decides, not a pattern: it is what a browser and the runtime read the text as. The raw text is held to having no `?`, `#` and `@` first, because a parser that drops an
+// empty query (`https://x/?`) or reads a `@` in the path as data would hide one.
+// The text a spec KEEPS is the text that is checked. The parser NORMALIZES what it reads — it removes dot-segments (`/<x>/../`, `/%2e%2e/`, `/./`), lower-cases the scheme and the host, drops a default port —
+// so a check of the parsed form alone would certify a text whose dropped segment it never saw: `https://contoso.example/<token>/../site` parses as `https://contoso.example/site`, and the spec would keep the
+// token. A URL is therefore a value only when the text is ALREADY canonical — `new URL(text).href` is the text itself, or the text and the `/` an origin with no path is given — so that every segment of the
+// text is a segment of the parsed path, and each one is checked below.
+// See: https://url.spec.whatwg.org/#double-dot-path-segment
+function isSafeUrl(value) {
+ if (typeof value !== 'string' || value.length > 2048 || /[?#@\\\s]/.test(value)) return false;
+ let url;
+ try {
+ url = new URL(value);
+ } catch {
+ return false;
+ }
+ if (url.href !== value && !(url.pathname === '/' && url.href === `${value}/`)) return false;
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') return false;
+ if (url.username || url.password || url.search || url.hash || !DNS_HOST.test(url.hostname)) return false;
+ for (const segment of url.pathname.split('/').filter(Boolean)) {
+ let decoded;
+ try {
+ decoded = decodeURIComponent(segment);
+ } catch {
+ return false;
+ }
+ // A canonical text holds no dot-segment; said again here, where a segment is read, so that this loop never certifies one whatever the parser does.
+ if (decoded === '.' || decoded === '..' || !LABEL.test(decoded) || tokenLike(decoded)) return false;
+ }
+ return !tokenLike(url.hostname);
+}
+// A connector's id as a binding and a reference write it — `/providers/Microsoft.PowerApps/apis/<connector name>` — or the bare name.
+const CONNECTOR_PATH = /^\/providers\/Microsoft\.PowerApps\/apis\//i;
+const isConnectorId = (value) => typeof value === 'string' && isIdentifier(value.replace(CONNECTOR_PATH, ''));
+const isDataset = (value) => value === '' || isName(value) || isSafeUrl(value);
+const isTableId = (value) => isGuid(value) || isName(value);
+const listOf = (check) => (value) => Array.isArray(value) && value.length <= MAX_LIST && value.every(check);
+const isBoolean = (value) => typeof value === 'boolean';
+// A Custom API request parameter's unique name: a letter or `_`, then letters, digits and `_` — and never a token-shaped one: a key is as free as a value.
+const PARAMETER_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
+function isParameterKinds(value) {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
+ const names = Object.keys(value);
+ return names.length <= MAX_LIST && names.every((name) => PARAMETER_NAME.test(name) && !tokenLike(name) && PARAMETER_KINDS.includes(value[name]));
+}
+
+// The properties a spec states of each kind of entry, each with the shape its value must have, and the words that say what that shape is. This is the allowlist: a key that is not here is not stated, and a
+// value that does not have its shape is not stated either.
+const FIELDS = {
+ connectorBindings: {
+ logicalName: [isIdentifier, 'identifier'],
+ connectorId: [isConnectorId, 'connector-id'],
+ dataset: [isDataset, 'dataset'],
+ tables: [listOf(isTableId), 'table-ids'],
+ tableDisplayNames: [listOf(isLabel), 'labels'],
+ operations: [listOf(isIdentifier), 'identifiers'],
+ },
+ actionBindings: {
+ name: [isIdentifier, 'identifier'],
+ isFunction: [isBoolean, 'boolean'],
+ boundEntityLogicalName: [isIdentifier, 'identifier'],
+ displayName: [isLabel, 'label'],
+ parameterKinds: [isParameterKinds, 'parameter-kinds'],
+ },
+};
+const BINDING_PROPERTIES = Object.fromEntries(Object.entries(FIELDS).map(([kind, fields]) => [kind, Object.keys(fields)]));
+
+// What a message says instead of a key that is not one of FIELDS: the key itself can be the secret (a token used as a property name), so it is never echoed.
+const UNUSUAL_NAME = 'an unrecognized property';
+
+const hasOwn = (object, property) => Object.prototype.hasOwnProperty.call(object, property);
+// Own-property writes that never run a setter: a config.json is parsed JSON, and `__proto__` in it is an own property like any other.
+const put = (object, property, value) => Object.defineProperty(object, property, { value, enumerable: true, writable: true, configurable: true });
+const copyOf = (value) => (Array.isArray(value) ? [...value] : (value && typeof value === 'object' ? Object.fromEntries(Object.entries(value)) : value));
+const isEntry = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
+
+// Why `value` cannot be a page's `<kind>` in an App Spec — it is not a list, or one entry is not an object — or null when it can. validateAppSpec holds a spec to the same rule, so a download that asks before it
+// writes a page's bindings into a spec never writes what the spec's own validation refuses.
+function pageBindingsProblem(kind, value) {
+ if (!Array.isArray(value)) return `${kind} is present but is not an array`;
+ const at = value.findIndex((entry) => !isEntry(entry));
+ return at === -1 ? null : `${kind}[${at}] is not an object`;
+}
+
+// The binding lists a spec page states, as the page backend takes them: { connectorBindings?, actionBindings? }. A list the page does not state is left out — the backend writes only what it
+// is given, so the page keeps the bindings it holds — and a list it states, `[]` too, is the page's own from then on, as its `dataSources` are.
+function statedPageBindings(page) {
+ const out = {};
+ for (const kind of Object.keys(PAGE_BINDINGS)) if (page && Array.isArray(page[kind])) out[kind] = page[kind];
+ return out;
+}
+
+// What a spec states of ONE entry (an object): { stated, leftOut }. `stated` holds the properties of FIELDS whose value has its shape, copied, in the entry's own order. `leftOut` says what is not stated —
+// [{ property, why }], the vetted properties first by code-unit order, then the unrecognized ones — where `property` is the vetted name, or UNUSUAL_NAME for a key that is not one (never the key), and `why` is 'not-stated' for such a key or the shape the value
+// lacks ('identifier', 'connector-id', 'dataset', 'table-ids', 'labels', 'identifiers', 'boolean', 'label', 'parameter-kinds'). It is never the value.
+function statableBinding(kind, entry) {
+ const fields = FIELDS[kind] || {};
+ const stated = {};
+ const leftOut = [];
+ for (const property of Object.keys(entry)) {
+ if (!hasOwn(fields, property)) {
+ leftOut.push({ property: UNUSUAL_NAME, why: 'not-stated' });
+ continue;
+ }
+ const [holds, shape] = fields[property];
+ if (holds(entry[property])) put(stated, property, copyOf(entry[property]));
+ else leftOut.push({ property, why: shape });
+ }
+ // A vetted property first, by name — its words say more (a list left out because of its identity says so) — then the unrecognized ones, which all read alike.
+ leftOut.sort((a, b) => Number(a.why === 'not-stated') - Number(b.why === 'not-stated') || compareText(a.property, b.property) || compareText(a.why, b.why));
+ return { stated, leftOut };
+}
+
+// What a spec states of a whole list (one `pageBindingsProblem` finds no fault with): { stated, problem }. `stated` is the list as the spec states it — every entry whole — and `problem` null; or `stated` is null
+// and `problem` is { entry, property, why } for the FIRST entry that holds anything a spec does not state (statableBinding): the list is then left out of the spec whole, because a spec that stated part of
+// it would make a rebuild replace the page's entries with less (see the header). `property` is a vetted name or UNUSUAL_NAME, never the key or the value.
+function statableBindings(kind, list) {
+ const stated = [];
+ for (let index = 0; index < list.length; index += 1) {
+ const one = statableBinding(kind, list[index]);
+ if (one.leftOut.length) return { stated: null, problem: { entry: index, property: one.leftOut[0].property, why: one.leftOut[0].why } };
+ stated.push(one.stated);
+ }
+ return { stated, problem: null };
+}
+
+const WHY_WORDS = {
+ identifier: 'must be an identifier (a letter, then letters, digits, _ . -)',
+ 'connector-id': "must be a connector's id (/providers/Microsoft.PowerApps/apis/<name>, or the name)",
+ dataset: 'must be empty, a plain name, or an http(s) URL with no user-info, no query and no fragment',
+ 'table-ids': 'must be a list of GUIDs or plain names',
+ labels: 'must be a list of plain labels',
+ identifiers: 'must be a list of identifiers',
+ boolean: 'must be true or false',
+ label: 'must be a plain label (letters, digits, spaces and simple punctuation; no URL)',
+ 'parameter-kinds': `must map safe parameter names to the ten declared primitive kinds (${PARAMETER_KINDS.join(', ')}); lookup inputs stay in the call as structural values, with discovery-only hints kept out of this map`,
+};
+
+// The words for one property of entry `index` of a list that is not stated (statableBinding's `leftOut`, statableBindings' `problem`): the vetted property's name and the shape its value lacks, or — for a key
+// that is not one of FIELDS — that the entry holds an unrecognized property. Never the value, never the key.
+function bindingProblemText(kind, index, { property, why }) {
+ const at = `${kind}[${index}]`;
+ if (why === 'not-stated') return `${at} holds ${UNUSUAL_NAME}, which an App Spec does not state (a binding states only ${BINDING_PROPERTIES[kind].join(', ')})`;
+ return `${at}.${property} ${WHY_WORDS[why] || 'does not have the shape an App Spec states'}`;
+}
+
+// The list a rebuild writes for a spec that states `stated`, onto a page that holds `held`: each stated entry on the held entry of the same name (matched in order when a name is repeated; by place when neither side
+// has one), with the properties the held entry has and the spec could not state — a connection id, a credential, a property a later runtime adds — kept, and every property a spec CAN state taken from the spec,
+// including the removal of one it no longer states. An entry the page does not hold is as the spec states it, and a held entry the spec does not state is not in the result. The order is the spec's.
+//
+// So a spec that states the entries as the page holds them (a download writes exactly that) merges into the page's own list, and a rebuild that finds it equal writes nothing; and an edit changes what it names and
+// nothing else. `held` that is no list (the page holds none) gives `stated` as it is.
+function mergeBindings(kind, stated, held) {
+ if (!Array.isArray(stated) || !Array.isArray(held)) return stated;
+ const identity = PAGE_BINDINGS[kind];
+ const taken = new Set();
+ return stated.map((entry, index) => {
+ if (!isEntry(entry)) return entry;
+ const name = entry[identity];
+ const at = typeof name === 'string'
+ ? held.findIndex((own, i) => !taken.has(i) && isEntry(own) && own[identity] === name)
+ : (isEntry(held[index]) && !taken.has(index) && typeof held[index][identity] !== 'string' ? index : -1);
+ if (at === -1) return entry;
+ taken.add(at);
+ const own = held[at];
+ const stateable = statableBinding(kind, own).stated;
+ // The held entry's own order first, so an entry the edit left as it was is written as it was; then what the spec adds.
+ const merged = {};
+ for (const property of Object.keys(own)) {
+ if (hasOwn(entry, property)) put(merged, property, entry[property]);
+ else if (!hasOwn(stateable, property)) put(merged, property, own[property]);
+ }
+ for (const property of Object.keys(entry)) if (!hasOwn(merged, property)) put(merged, property, entry[property]);
+ return merged;
+ });
+}
+
+module.exports = {
+ PAGE_BINDINGS,
+ BINDING_PROPERTIES,
+ PARAMETER_KINDS,
+ UNUSUAL_NAME,
+ WHY_WORDS,
+ pageBindingsProblem,
+ statedPageBindings,
+ statableBinding,
+ statableBindings,
+ bindingProblemText,
+ mergeBindings,
+};
diff --git a/plugins/model-apps/scripts/lib/process-owner.js b/plugins/model-apps/scripts/lib/process-owner.js
index 845e0a1b1..23074a975 100644
--- a/plugins/model-apps/scripts/lib/process-owner.js
+++ b/plugins/model-apps/scripts/lib/process-owner.js
@@ -2,9 +2,10 @@
// Who made a lock or a temporary workspace, and whether that process is gone.
//
// WHY. A run that is killed outright — SIGKILL, "End task", an agent's timeout, a power cut — cannot clean up after itself, so it leaves what it
-// held: the pages lock a build takes on an app's workspace (lib/sdk-build.js), and the throwaway workspaces it made in the temp folder
-// (lib/temp-workspace.js), which hold the page source it read and the environment's address. A later run may take such a thing over ONLY when it can
-// prove that its maker is gone; everything else is left exactly as it was. That proof is made here, once, for both. It is deliberately one-sided:
+// held: the pages lock a build takes on an app's workspace (lib/sdk-build.js), the writer lease of a recovery record in it (lib/record-lease.js), and
+// the throwaway workspaces it made in the temp folder (lib/temp-workspace.js), which hold the page source it read and the environment's address. A later
+// run may take such a thing over ONLY when it can prove that its maker is gone; everything else is left exactly as it was. That proof is made here, once,
+// for all of them. It is deliberately one-sided:
// every doubt answers "keep" — a lock that stays costs a person one delete, and a lock or a workspace taken from a run that is still going costs it
// its work.
//
diff --git a/plugins/model-apps/scripts/lib/publish-xml.js b/plugins/model-apps/scripts/lib/publish-xml.js
new file mode 100644
index 000000000..81fcc3988
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/publish-xml.js
@@ -0,0 +1,30 @@
+'use strict';
+// The plugin's OWN publishes — the `PublishXml` requests it sends itself, beside the ones the SDK sends — go out through here, and only here.
+//
+// The HTTP client sends a publish once (lib/sdk-http-client.js, `publishOnce`): a publish the customization lock refused is not shown to have
+// changed nothing, and an accepted re-send of one was measured publishing old content. What IS re-sent is a publish SQL chose as a deadlock
+// victim — its transaction was rolled back, so it did nothing — and exactly ONE layer re-sends it on each path, so that the layers never
+// multiply: the SDK's own publishXml (its resendDeadlockVictim) for every publish the SDK makes, and this function for the plugin's. Both wait
+// 1 s, 2 s and 4 s, at most three re-sends.
+//
+// The request (https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/publishxml):
+// POST /PublishXml { "ParameterXml": "<importexportxml><entities><entity>contoso_task</entity></entities></importexportxml>" }
+// `dataverse` is the SDK's Dataverse client (an SDK's `dataverse`), whose `post` answers `{ status, headers, body }` with the body parsed and
+// throws only for a failure of the transport — which is not re-sent here either: a publish that got no answer may still be running.
+// A deadlock victim is HTTP 500 whose answer ENDS in the platform's signature (SQL_DEADLOCK_VICTIM: the last SQL number it gives is 1205):
+// {"error":{"code":"0x80044150","message":" Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205"}}
+const { DEADLOCK_RESENDS, isSqlDeadlockVictim } = require('./sdk-http-client.js');
+
+const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/** Send `{ ParameterXml: parameterXml }` to PublishXml, again while SQL rolls it back as a deadlock victim. Answers the last answer, as it came. */
+async function postPublishXml(dataverse, parameterXml, { sleep = wait } = {}) {
+ for (let attempt = 0; ; attempt += 1) {
+ const answer = await dataverse.post('/PublishXml', { ParameterXml: parameterXml });
+ const lost = Boolean(answer) && isSqlDeadlockVictim({ statusCode: answer.status, body: answer.body });
+ if (!lost || attempt >= DEADLOCK_RESENDS) return answer;
+ await sleep(1000 * 2 ** attempt);
+ }
+}
+
+module.exports = { postPublishXml };
diff --git a/plugins/model-apps/scripts/lib/record-lease.js b/plugins/model-apps/scripts/lib/record-lease.js
new file mode 100644
index 000000000..36b2486c5
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/record-lease.js
@@ -0,0 +1,69 @@
+'use strict';
+// The writer lease of a workspace record: the lock that builds sharing a workspace take, one at a time, to change one record file.
+//
+// WHY. The build keeps small recovery records in its workspace — the web resources it wrote and could not confirm were published
+// (lib/web-resource-records.js), the dashboards it created and has not yet seen join the app's solution (lib/dashboard-creation-records.js) —
+// each ONE file that holds every entry of its kind, replaced whole on each change. Two builds sharing a workspace each read the file and later
+// wrote their own copy of it: with both reading before either wrote, A noting `a` and then B noting `b` both answered "recorded", and only `b`
+// was on disk; A clearing `a` afterwards deleted the file, `b` with it — the id the next build needed. Replacing the file atomically does not
+// prevent that: every write is whole, and the later one still wins.
+//
+// THE LEASE. A change takes the record's own lock, reads the record from disk as it is NOW, applies its one change to that, writes it, and lets
+// the lock go — so each change starts from every change made before it. The lock is the workspace's lease protocol
+// (lib/apply-snapshot-store.js acquireLease: an exclusive create picks one holder, a claim file makes exactly one of several reclaimers win, a
+// release removes only a lock that still holds its own token) on a file of the record's own, `<record file>.lock`, stamped and judged as the
+// pages lock is (lib/sdk-build.js acquireAppPagesLease, lib/process-owner.js): it is taken over only from a build PROVEN gone — never by age,
+// since a live build can be paused for as long as a laptop sleeps.
+//
+// THE WAIT. A change reads and writes one small file, so a lock is held for milliseconds, and one that another build holds is waited for — but
+// for a BOUNDED time: LEASE_ATTEMPTS tries, LEASE_WAIT_MS apart, about a second in all. A lock still held after that (a build paused, or one
+// that crashed on another machine, whose death this one cannot prove) is not waited for any longer: the change is not made, and the record's
+// caller says so as it says a record it cannot write — one warning, and the build goes on. Reads take no lock: a record is replaced
+// atomically, so a read sees one whole version of it.
+const path = require('node:path');
+const { acquireLease, releaseLease } = require('./apply-snapshot-store.js');
+const { ownerStamp, ownerState } = require('./process-owner.js');
+
+const LEASE_ATTEMPTS = 10;
+const LEASE_WAIT_MS = 100;
+// A synchronous pause, as the snapshot store's release waits for its lease (apply-snapshot-store.js releaseTombstone): a record is written
+// synchronously from inside a build step, and that step waits for it whatever else the process could do meanwhile.
+function sleepSync(ms) { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); }
+
+/**
+ * Runs `change()` while holding the lease of the record file named `file` in the workspace folder `root` (one that exists and that
+ * page-ownership-records.js workspaceRoot has checked). Answers { ok: true, value } with what `change` answered, or { ok: false, reason } when
+ * the lease was not taken — `reason` names the lock, for a warning. What `change` throws is thrown, after the lease is released.
+ * `deps`, for tests: `attempts`, `sleep(ms)`, and `owner` (the lib/process-owner.js seams).
+ */
+function withRecordLease(root, file, change, deps = {}) {
+ const attempts = deps.attempts != null ? deps.attempts : LEASE_ATTEMPTS;
+ const sleep = typeof deps.sleep === 'function' ? deps.sleep : sleepSync;
+ const owner = deps.owner || {};
+ const lockFile = `${file}.lock`;
+ let lease;
+ for (let attempt = 1; ; attempt += 1) {
+ lease = acquireLease(root, { file: lockFile, stamp: ownerStamp(owner), isStale: (held) => ownerState(held, owner).state === 'gone' });
+ // Every refusal is tried again within the bound, not only "held": a lock another build has just let go can refuse a create for a moment too
+ // (on Windows a file that is being deleted while a reader still has it open cannot be created again until that reader closes it — EPERM), and
+ // a folder that cannot be written at all fails within the same bound.
+ if (lease.ok || attempt >= attempts) break;
+ sleep(LEASE_WAIT_MS);
+ }
+ if (!lease.ok) {
+ const lock = path.join(root, lockFile);
+ return {
+ ok: false,
+ reason: lease.error
+ ? `its lock ${lock} could not be created (${(lease.error && lease.error.message) || lease.error})`
+ : `its lock ${lock} is held by another build of this workspace (${lease.reason})`,
+ };
+ }
+ try {
+ return { ok: true, value: change() };
+ } finally {
+ releaseLease(lease);
+ }
+}
+
+module.exports = { withRecordLease, LEASE_ATTEMPTS, LEASE_WAIT_MS };
diff --git a/plugins/model-apps/scripts/lib/retry-policy.js b/plugins/model-apps/scripts/lib/retry-policy.js
index d8e95047c..542f15953 100644
--- a/plugins/model-apps/scripts/lib/retry-policy.js
+++ b/plugins/model-apps/scripts/lib/retry-policy.js
@@ -86,6 +86,16 @@ const WRAPPED_SERVICE_CODES = Object.freeze(new Set(['ENRICH_DEFAULT_VIEWS_PUBLI
const WRAPPER_SENTENCE = /^enrichDefaultViews: \d+ view\(s\) on '[^'\s]*' were saved but the publish FAILED, so none of them is live \(([\s\S]+)\)\. Re-publish the entity to make them visible; the saves themselves are unaffected\.$/;
const EMBEDDED_ANSWER = /^(?:HTTP (\d{3}) from|Transport failure reaching) (\S+): ([\s\S]*)$/;
+// The errors that are typed and WRAP a failure they carry as their `cause` — attached NOT enumerably (the SDK's attachCause, a native Error's `cause`), which
+// causeChain reads all the same — so what decides is that failure, never the wrapper's code or its words (which name what the maker named). One today:
+// WEB_RESOURCE_UNVERIFIED, the SDK's error for a web resource it wrote whose PUBLISHED content it could not confirm, and the build's own error around it
+// (lib/sdk-build.js, unconfirmedWebResource). The row exists; a run again writes its content again by id. So:
+// - it carries a failure — its publish's, or that of the read-back of what was published: that failure is judged by the rule above, a lock refusal (429
+// `0x80071151`), a 503 or a reset is run again, a 400, 401, 403, 404, a 412 (the SDK's typed VERSION_CONFLICT) or another typed refusal is not;
+// - it carries none: the read-back answered content that is not what was written, or no content — the write did not apply, or whether it did is
+// unknown, and nothing in it is a verdict on the request. It is run again (`unconfirmed`, below).
+const CAUSE_WRAPPER_CODES = Object.freeze(new Set(['WEB_RESOURCE_UNVERIFIED']));
+
// How far down the chain of causes the decision looks. Deeper than any failure the build raises (a halt, a step's wrapper, the SDK's error, the system error under it).
const MAX_CHAIN = 8;
@@ -138,6 +148,8 @@ const messageOf = (error) => (typeof error.message === 'string' ? error.message
// An SDK error that carries a failed request's answer in its message (WRAPPED_SERVICE_CODES) — the code alone says nothing of whether that answer can be read.
const wrapsServiceFailure = (error) => WRAPPED_SERVICE_CODES.has(typedCode(error));
+// An error that carries the failure it is about as its cause (CAUSE_WRAPPER_CODES): judged by that cause, and by nothing of its own.
+const wrapsCause = (error) => CAUSE_WRAPPER_CODES.has(typedCode(error));
// What such an error embeds, as { status, answer }: the status the service answered (0 for a failure of the transport) and the words after the url — or null when the sentence is not the one the SDK words (see
// WRAPPED_SERVICE_CODES), and then nothing of it is read.
function embeddedFailure(error) {
@@ -193,7 +205,7 @@ function isTransportBlip(error) {
// An error the SDK or the plugin has typed: its code says what it is, and what it is is not a service hiccup. The one exception is an SDK error that wraps a failed publish in a sentence this code can take apart
// (embeddedFailure): it is the service's answer, and is judged as such. One it cannot take apart is a refusal like any other.
-const isTypedRefusal = (error) => !isHalt(error) && typedCode(error) !== null && !isConnectionError(error) && !TRANSPORT_CODES.has(typedCode(error)) && embeddedFailure(error) === null;
+const isTypedRefusal = (error) => !isHalt(error) && typedCode(error) !== null && !isConnectionError(error) && !TRANSPORT_CODES.has(typedCode(error)) && embeddedFailure(error) === null && !wrapsCause(error);
// The OData `error.code` of the answer an SDK ConnectionError carries — its `cause` is the response body, `{ "error": { "code": "0x80044151", "message": "SQL timeout expired." } }` — lower-cased (the platform writes
// them with either case: 0x8004F064, 0x80071151), or null when the error has no such body. Only the SDK's own ConnectionError for an answer (a status above 0) is read, and only the `code` field of the body's `error`:
@@ -298,11 +310,13 @@ function judgeFailure(error, { declares } = {}) {
const transientStatus = statuses.some(isTransientStatus);
const transport = chain.some(isTransportBlip);
const transientCode = chain.some((e) => isTransientServiceAnswer(e, declares));
- const transient = transientStatus || transport || transientCode;
+ // A wrapper that carries no failure (CAUSE_WRAPPER_CODES): the write's outcome is not confirmed, and nothing says no.
+ const unconfirmed = chain.some((e) => wrapsCause(e) && !isObject(e.cause));
+ const transient = transientStatus || transport || transientCode || unconfirmed;
const typed = chain.some(isTypedRefusal);
// A status the service answered that is not transient is a verdict: no word in its answer can undo it (rule 5).
const refused = statuses.length > 0 && !transientStatus;
- const found = { transient, transientStatus, transport, transientCode };
+ const found = { transient, transientStatus, transport, transientCode, unconfirmed };
if (explicit || (!transient && typed)) return { never: true, ...found, text: '' };
if (!transient && refused) {
// The one verdict that depends on what only the CALLER knows: the answer that says a column is missing, which is the lag of a column the spec creates or an authoring error according to the spec (MISSING_ATTRIBUTE_CODES).
@@ -312,8 +326,8 @@ function judgeFailure(error, { declares } = {}) {
}
if (typed) return { never: false, ...found, text: '' };
const declared = chain.find((e) => typeof e.retryText === 'string');
- // A failure of the transport has no words to read (rule 4 decided it), and a halt's own message is never read.
- const words = declared ? declared.retryText : chain.filter((e) => !isHalt(e) && !isTransportFailure(e)).map(answerOf).join(' ');
+ // A failure of the transport has no words to read (rule 4 decided it), a halt's own message is never read, and neither is a wrapper's: it names what the maker named.
+ const words = declared ? declared.retryText : chain.filter((e) => !isHalt(e) && !isTransportFailure(e) && !wrapsCause(e)).map(answerOf).join(' ');
return { never: false, ...found, text: words };
}
@@ -352,4 +366,6 @@ function throttleAskOf(error) {
module.exports = {
RETRY, TRANSIENT_STATUSES, TRANSIENT_SERVICE_CODES, TRANSPORT_CODES, isTransientStatus, refusal, neverRetry, serviceFailure, withCause, judgeFailure, retryPolicyFor, retryFrom, throttleAskOf,
+ // Also the reader of an answer's code for lib/entity-provision.js, which recognises an "already exists" refusal by it (isAlreadyExists).
+ serviceCodeOf,
};
diff --git a/plugins/model-apps/scripts/lib/sdk-build.js b/plugins/model-apps/scripts/lib/sdk-build.js
index 16f02022f..529edba9f 100644
--- a/plugins/model-apps/scripts/lib/sdk-build.js
+++ b/plugins/model-apps/scripts/lib/sdk-build.js
@@ -55,8 +55,10 @@ const {
subgridRelationshipName,
lookupLabelFor,
lookupParentNeedsEnvironment,
+ statedPageBindings,
} = require('./app-spec.js');
const { PHASES } = require('./stages.js');
+const { pagesStatingBindings, readBindingTargets, judgeBindingTargets } = require('./page-binding-targets.js');
const { topoOrderEntities, entityByLogical } = require('./_graph.js');
const {
isMainForm,
@@ -140,7 +142,9 @@ const { tableRefs, pinAppTables, publishAppComponents, resolveMainForms, appComp
const { appWriteTables, appPushTables, preAppTables, publishTablesXml, readSavedNotPublished, describeSavedNotPublished, readAppFormChartTables, describePreAppRefusal, describeUnreadAppComponents } = require('./table-publish.js');
const { hasUnsyncedEdits } = require('./unsynced-edits.js');
const { createSolutionMembership, ensureSolutionComponent } = require('./solution-membership.js');
-const { navigationEntryKind, navigationVerdict } = require('./app-navigation.js');
+const { openUnconfirmedWebResources } = require('./web-resource-records.js');
+const { openDashboardCreations } = require('./dashboard-creation-records.js');
+const { navigationEntryKind, navigationHolds, navigationIsPagesOnly, navigationVerdict } = require('./app-navigation.js');
const { isAppTextMap, appTextKind, localizedAppText } = require('./app-header-text.js');
// The build's retry policy (retry-policy.js): every halt below is raised with what a run again may do — RETRY.NEVER, or a policy decided from the failure it wraps — and every failure the engine
// raises itself is made by refusal() (deterministic) or serviceFailure() (the plugin's words around a failure of the service), because the build's retry reads a failure's STRUCTURE and the
@@ -243,6 +247,111 @@ async function findPinnedDashboard(sdk, pin) {
return { id: String(row.formid), name: String(row.name === undefined || row.name === null ? '' : row.name) };
}
+// One systemform row read by its id in the SAVED layer, through the SDK's own client:
+// GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,name,type
+// 200 { "@odata.etag": "W/\"1234567\"", "formid": "11111111-1111-4111-8111-111111111111", "name": "Ops Overview", "type": 0 }
+// 404 { "error": { "code": "0x80040217", "message": "systemform With Id = 11111111-… Does Not Exist" } }
+// The saved layer answers for a row whether or not it was ever published — MEASURED by the bundled SDK, whose readSystemFormType reads the same function:
+// a never-published form, a new dashboard and an out-of-box form all answer with their type, and a missing id answers 404 0x80040217. A plain read
+// (`$filter=formid eq <id>`, or the name lookup) answers the PUBLISHED layer only, where a dashboard an interrupted build created is not, so a miss there
+// proves nothing. It is not read through the build workspace either: a fetch into it can hand back the local copy the interrupted run left there, which
+// is not the service's word. `dataverse.get` answers a non-2xx as a response (it throws only when no answer came), so the status is read here, and only
+// the documented "Does Not Exist" proves the row absent — any other answer, a 404 without that code included, proves nothing either way.
+// Answers { state: 'present', id, name, type } | { state: 'absent', id } | { state: 'unreadable', id, why, status?, answered?, error? }.
+// See: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/retrieveunpublished
+async function readSavedSystemForm(provision, id) {
+ const client = provision && provision.dataverse;
+ if (!client || typeof client.get !== 'function') return { state: 'unreadable', id, why: 'the SDK has no reader of the saved layer' };
+ let response;
+ try {
+ response = await client.get(`/systemforms(${id})/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,name,type`);
+ } catch (error) {
+ return { state: 'unreadable', id, why: (error && error.message) || String(error), error };
+ }
+ const status = response && response.status;
+ const body = response && response.body;
+ const answered = body && typeof body === 'object' && body.error && typeof body.error === 'object' ? body.error : undefined;
+ if (status === 404 && answered && answered.code === '0x80040217') return { state: 'absent', id };
+ if (status >= 200 && status < 300 && body && typeof body === 'object' && String(body.formid || '').replace(/[{}]/g, '').toLowerCase() === id) {
+ return { state: 'present', id, name: typeof body.name === 'string' ? body.name : '', type: body.type };
+ }
+ return { state: 'unreadable', id, status, answered, why: `HTTP ${status}${answered && typeof answered.message === 'string' ? `: ${answered.message}` : ' with no row the build can read'}` };
+}
+
+// A systemform `type` as the integer it is, strictly (the platform answers a number; a text of digits is read as one). Anything else is NaN, never 0 —
+// 0 is a real type, the standard dashboard the build creates.
+function systemFormType(raw) {
+ if (typeof raw === 'number') return Number.isInteger(raw) ? raw : NaN;
+ return typeof raw === 'string' && /^\s*\d+\s*$/.test(raw) ? Number(raw) : NaN;
+}
+
+// The dashboard an earlier, interrupted run of this build created for `dash` and never saw join the solution (lib/dashboard-creation-records.js), settled
+// before any dashboard is looked up by name. `ids` are what the record holds: `sent`, the id the create was sent with, then `reported`, the one its push
+// reported when that was another. The two are not equal evidence: after such a re-key the reported row is the one the create made, and the sent id was
+// never seen to make anything. Each is read in the saved layer (readSavedSystemForm):
+// - none is there: the create never committed, or the row was deleted since — the record is cleared and the build goes on as it always did, looking the
+// dashboard up by name (answers undefined). Unless another build sharing the workspace has changed the entry since this build read it — recorded the
+// id its push reported, say, which names the row its create made: then the absence of the ids THIS build read proves nothing, the entry is left, and
+// the step stops without creating a dashboard;
+// - the row the create made is (the sent one, or the reported one after a re-key), a standard dashboard with this name: THAT row is added to the
+// solution — idempotent: a component the solution already holds is not added twice — and reused, and the record cleared (answers its id). Its tiles
+// are what the interrupted run pushed, and are not repaired;
+// - anything else — a read that fails, a row of another kind, a dashboard renamed since, both ids answering, or, after a re-key, only the SENT id
+// answering (a row the build never saw its create make: another maker can have made it since, and adding it would give teardown the authority to
+// delete it): nothing is added and nothing deleted, no dashboard is created, the record is kept, and the step stops with what a maker can do —
+// never asking for a row to be deleted that may be another app's. Creating a dashboard there could make the second one this record exists to
+// prevent, and adding the row could adopt what the build does not know to be its own.
+// Never deletes anything: the record proves which ids the build sent and was answered with, not that a row which answers to one now is used by nobody else.
+async function recoverRecordedDashboard(provision, { dash, ids, sol, runner, creations }) {
+ const [sent, reported] = ids;
+ const reads = [];
+ for (const id of ids) reads.push(await readSavedSystemForm(provision, id));
+ const label = `dashboard "${dash.name}"`;
+ const created = reported ? `${sent} (the service reported ${reported})` : sent;
+ const stop = (error) => runner.run('dashboards', label, async () => { throw error; });
+ const unreadable = reads.find((r) => r.state === 'unreadable');
+ if (unreadable) {
+ // A run again may settle it: whether it does follows what the service answered (its status and its own error), never the dashboard's name.
+ return stop(serviceFailure(`dashboard "${dash.name}": an earlier build created it as ${created} and stopped before adding it to solution '${sol.uniqueName}', and whether it still exists could not be read (${unreadable.why}). Nothing was added to the solution or deleted, and no second dashboard was created; run the build again.`, { status: unreadable.status, answered: unreadable.answered, cause: unreadable.error }));
+ }
+ const present = reads.filter((r) => r.state === 'present');
+ if (!present.length) {
+ // Absent — but only by the ids this build READ. Another build sharing the workspace may have changed the entry since (recorded the id its own push
+ // reported, which names the row its create made): the clear then leaves the entry (it answers null), and nothing is created on the older word.
+ if (creations.clear(dash.name) === null) {
+ return stop(refusal(`dashboard "${dash.name}": the record this build read named ${created} for it — a create an earlier build had not seen join solution '${sol.uniqueName}' — and no row has ${reported ? 'either id' : 'that id'} now, but another build sharing this workspace has changed that entry of ${creations.path()} since this build read it. Nothing was added to the solution or deleted, and no dashboard was created: this build does not act on what it read. Run the build again once the other build has finished; it then reads the record as it is.`));
+ }
+ return undefined;
+ }
+ // The way out names the row the service reported and asks for no delete: either row may be another app's, and this record is no authority over it.
+ if (present.length > 1) {
+ return stop(refusal(`dashboard "${dash.name}": an earlier build stopped after creating it, and both ids it recorded for it name a row now — ${sent}, the id its create was sent with, and ${reported}, the id the service reported for the dashboard it made — so it cannot tell on its own which one is this app's. Nothing was added to the solution or deleted. Do not delete either dashboard to settle this: the other one may be another app's. Check in Maker which one this app's build made (the service reported ${reported}), add that one to solution '${sol.uniqueName}' and publish it there, then remove the entry '${dash.name}' from ${creations.path()} and run the build again: it then reuses the dashboard the solution holds and leaves the other as it is.`));
+ }
+ const [row] = present;
+ if (reported && row.id !== reported) {
+ return stop(refusal(`dashboard "${dash.name}": an earlier build stopped after creating it. Its create was sent as ${sent}, but the service reported the dashboard it made as ${reported}, which is gone now, and ${sent} names a row this build never saw its create make. Nothing was added to the solution or deleted, and no dashboard was created. That row is not known to be this app's: do not delete or change it on this build's account. Find out whose it is, then remove the entry '${dash.name}' from ${creations.path()} and run the build again: it then finds the dashboard by name, as it does when nothing is recorded.`));
+ }
+ const type = systemFormType(row.type);
+ if (type !== 0) {
+ return stop(refusal(`dashboard "${dash.name}": an earlier build recorded ${row.id} for it before it stopped, and that id now names ${Number.isNaN(type) ? 'a systemform whose type could not be read' : `a systemform of type ${type}`}, not a dashboard of the kind the build creates (type 0). Nothing was added to the solution or deleted. Check the id, then remove the entry '${dash.name}' from ${creations.path()} and run the build again.`));
+ }
+ if (dashboardNameKey(row.name) !== dashboardNameKey(dash.name)) {
+ return stop(refusal(`dashboard "${dash.name}": an earlier build created it as ${row.id} and stopped before adding it to solution '${sol.uniqueName}', and that dashboard is now named '${row.name}'. Nothing was added to the solution or deleted. If it is this app's, rename it back to '${dash.name}' in Maker and run the build again: it is then added to the solution and reused. If it is not wanted, delete it in Maker and run the build again: '${dash.name}' is then created afresh.`));
+ }
+ await runner.run('dashboards', `${label} (created by an interrupted build as ${row.id} — added to the solution, and reused)`, async () => {
+ try {
+ await provision.addSolutionComponent({ componentId: row.id, componentType: COMPONENT_TYPE.dashboard, solutionUniqueName: sol.uniqueName });
+ } catch (err) {
+ // Kept, and not undone: deleting the row on this record's word is what it must never do. A run again tries the add again.
+ throw serviceFailure(`dashboard "${dash.name}" (${row.id}), which an earlier build created and stopped before adding to solution '${sol.uniqueName}', could not be added to it now (${(err && err.message) || err}). Nothing was deleted, and the record of it is kept: run the build again to add it.`, {
+ status: err && (err.statusCode || err.status), words: judgeFailure(err).text, cause: err,
+ });
+ }
+ creations.clear(dash.name);
+ });
+ return row.id;
+}
+
// Web-resource kinds (App Spec `type`) -> SDK createWebResource `type` token. The SDK maps
// the token to the Dataverse webresourcetype code (js=3, html=1, css=2, …).
const WEB_RESOURCE_KINDS = new Set(['js', 'html', 'css', 'xml', 'png', 'jpg', 'gif', 'xsl', 'ico', 'svg', 'resx']);
@@ -1046,12 +1155,124 @@ function defaultAppIconSvg(appName) {
`</svg>`;
}
+// --- web resources whose publication the SDK could not confirm ---------------------------------------------------------------------------------------------
+// The bundled SDK reads a web resource's PUBLISHED content back after every create and every write of content it publishes, and throws
+// WEB_RESOURCE_UNVERIFIED when its publish failed or the read-back could not confirm the content — AFTER the row exists, with its id:
+// { code: 'WEB_RESOURCE_UNVERIFIED', id: '<guid>', webResourceName: '<name>' (after a create), message: "Web resource '<name>' (<id>) was written,
+// but publishing it failed, so whether its published content is what was sent is unconfirmed (<the failure>). …", cause: <the failure, not enumerable> }
+// The row is therefore never created again (a second create of the name is refused), and its content may be what was written, the old content, or
+// none. What the build does about it is the same at every site that writes one (the spec's web resources, the generated app icon, the page manifest):
+// it records the row — in the run's result, and in the workspace (lib/web-resource-records.js), so that the run that follows writes its content again
+// by id instead of reusing it untouched — adds it to the solution as the success path does, and stops with what a run again does.
+const isUnconfirmedWrite = (e) => Boolean(e) && e.code === 'WEB_RESOURCE_UNVERIFIED' && typeof e.id === 'string' && e.id.length > 0;
+// The SDK's answer to a write by an id whose row is gone: HTTP 404 (`ensureSuccess` throws it as a ConnectionError).
+const isGoneRow = (e) => Boolean(e) && e.code === 'CONNECTION_ERROR' && e.statusCode === 404;
+const contentOf = (options) => (options.contentBase64 !== undefined ? { contentBase64: options.contentBase64 } : { content: options.content });
+
+// The error a step stops with for such a row: the SDK's own words (which name the row, its id, why its publication is unconfirmed, and the SDK call
+// that recovers it), then the plugin's — what this build did with the row and what a run again does, which makes that call. Its code is the SDK's, so the
+// runner's halt carries it, and the SDK's error is its cause: the build's retry reads that as the wrapper it is (lib/retry-policy.js, CAUSE_WRAPPER_CODES),
+// judged by the failure the SDK's error carries, and run again when it carries none.
+function unconfirmedWebResource(error, { name, recorded, inSolution }) {
+ const solution = inSolution === true ? 'added it to the solution' : `could not add it to the solution (${(inSolution && inSolution.message) || inSolution}; a run again adds it)`;
+ const remedy = recorded
+ ? `this build recorded the row as its own and ${solution}. Its publication is UNCONFIRMED, not lost: run the build again — it writes the content again by that id, publishes it and reads it back (the call the message names is made for you).`
+ : `this build ${solution}, but could not save its local recovery record. Its publication is UNCONFIRMED, not lost: this build will not automatically retry it without that record. Write its content again by the id above in Power Apps once the cause is resolved; keep the same writable build workspace for automatic recovery.`;
+ // SDK updates report only the id; the build also knows the authored name, which is what a maker needs to find the resource.
+ const detail = error.webResourceName ? error.message : `Web resource '${name}' (${error.id}): ${error.message}`;
+ const failure = Object.assign(serviceFailure(`${detail} — ${remedy}`, { cause: error }), { code: 'WEB_RESOURCE_UNVERIFIED', id: error.id });
+ // A phase replay without a saved identity could create the name again when the row has no published layer. Likewise, a permanent
+ // solution-add refusal must be resolved first even when the publish itself was transient.
+ if (!recorded || (inSolution !== true && retryPolicyFor(inSolution) === RETRY.NEVER)) failure.transient = false;
+ return failure;
+}
+
+// Records a row the SDK wrote and could not confirm, puts it in the solution, and answers the error to stop the step with (unconfirmedWebResource).
+// The record is written FIRST: it is local, and it is what the next run needs whatever happens to the add.
+async function keepUnconfirmedWebResource(error, { name, unconfirmed, addToSolution }) {
+ const recorded = unconfirmed.note(name, error.id);
+ let inSolution = true;
+ try { await addToSolution(error.id); } catch (e) { inSolution = e; }
+ return unconfirmedWebResource(error, { name, recorded, inSolution });
+}
+
+// A receipt authorizes only its original id, never a different row that came to hold the same name after it. This check costs nothing
+// on an ordinary rebuild: the manifest already reads by name; spec resources/icons check only after an update proves their recorded row gone.
+function assertUnconfirmedWebResourceIdentity(name, recordedId, foundId) {
+ if (!recordedId || !foundId || String(recordedId).toLowerCase() === String(foundId).toLowerCase()) return;
+ throw Object.assign(refusal(`Web resource '${name}' was recorded as ${recordedId}, but its name now belongs to ${foundId}. Refusing to overwrite or adopt that replacement; inspect both ids and resolve the local recovery record before rebuilding.`), { code: 'WEB_RESOURCE_IDENTITY_CONFLICT' });
+}
+
+async function checkRecordedWebResourceName(provision, name, id) {
+ let row;
+ try { row = await provision.getWebResource(id); } catch (e) {
+ // A plain GET can miss a never-published row; the receipt still proves which id this build wrote. Unpublished content
+ // is not ownership evidence, and a later publish may still serve old content. Only the subsequent PATCH's 404 proves the row gone.
+ if (isGoneRow(e)) return;
+ throw e;
+ }
+ if (row && typeof row.name === 'string' && row.name.toLowerCase() === String(name).toLowerCase()) return;
+ throw Object.assign(refusal(`Web resource '${name}' was recorded as ${id}, but that id now reads as ${row && typeof row.name === 'string' ? `'${row.name}'` : 'a row with no verifiable name'}. Refusing to overwrite it; inspect the row and resolve the local recovery record before rebuilding.`), { code: 'WEB_RESOURCE_IDENTITY_CONFLICT' });
+}
+
+// Write a web resource the build OWNS by name — the spec's, or the generated app icon — and add it to the solution: create it, or, when an earlier run
+// of this build wrote it and could not confirm its publication (`recordedId`, from the record), write its content again by that id, which publishes and
+// verifies it again. The entry is cleared only once that write verified and the row is in the solution. A row that is gone by then (404) is created as on
+// a first build. Answers the row's id. A web resource of that name that the record does not hold is the caller's to reuse untouched, as before.
+async function writeOwnedWebResource(provision, unconfirmed, sol, options, recordedId) {
+ const addToSolution = (componentId) => provision.addSolutionComponent({ componentId, componentType: COMPONENT_TYPE.webResource, solutionUniqueName: sol.uniqueName });
+ if (recordedId) {
+ await checkRecordedWebResourceName(provision, options.name, recordedId);
+ let gone = false;
+ try {
+ await provision.updateWebResource(recordedId, contentOf(options));
+ } catch (e) {
+ if (isUnconfirmedWrite(e)) throw await keepUnconfirmedWebResource(e, { name: options.name, unconfirmed, addToSolution });
+ if (!isGoneRow(e)) throw e;
+ gone = true;
+ }
+ if (!gone) {
+ // Keep the receipt when only the solution add fails. Its 404 is not proof that the web-resource row is gone.
+ await addToSolution(recordedId);
+ unconfirmed.clear(options.name);
+ return recordedId;
+ }
+ const rows = await provision.queryRecords('webresource', { select: ['webresourceid'], filter: `name eq '${odataLit(options.name)}'`, top: 1 });
+ assertUnconfirmedWebResourceIdentity(options.name, recordedId, rows && rows[0] && rows[0].webresourceid);
+ unconfirmed.clear(options.name);
+ }
+ let created;
+ try {
+ created = await provision.createWebResource(options);
+ } catch (e) {
+ if (isUnconfirmedWrite(e)) throw await keepUnconfirmedWebResource(e, { name: options.name, unconfirmed, addToSolution });
+ throw e;
+ }
+ await addToSolution(created.id);
+ return created.id;
+}
+
+// Runs a write of a web resource and hands the id of the row it leaves to `keep` — when the write stops the step because the row's publication
+// could not be confirmed too (isUnconfirmedWrite: the row exists, under `error.id`), so the run's result names the row either way.
+async function keepRowOf(write, keep) {
+ try {
+ const id = await write();
+ keep(id);
+ return id;
+ } catch (e) {
+ if (isUnconfirmedWrite(e)) keep(e.id);
+ throw e;
+ }
+}
+
// Resolve the app's tile-icon web resource id, ensuring it lives IN this solution. Uses
// spec.app.icon (a declared web resource) when set; otherwise generates a default SVG icon named
// `<appUniqueName>_icon` and adds it to the solution (idempotent — reused by name on a re-run).
// Returns the web-resource id, or undefined if it can't be resolved (the SDK then falls back).
+// A generated icon an earlier run created and could not confirm the publication of is written again by id
+// (writeOwnedWebResource), and is not looked up by name.
async function ensureAppIcon(spec, created, deps) {
- const { provision, sol, runner } = deps;
+ const { provision, sol, runner, unconfirmed = openUnconfirmedWebResources() } = deps;
const findByName = async (name) => {
const rows = await provision.queryRecords('webresource', { select: ['webresourceid'], filter: `name eq '${odataLit(name)}'`, top: 1 });
return rows && rows[0] && rows[0].webresourceid;
@@ -1061,18 +1282,19 @@ async function ensureAppIcon(spec, created, deps) {
return (created.webResources && created.webResources[spec.app.icon]) || (await findByName(spec.app.icon)) || undefined;
}
const name = `${appUniqueName(spec)}_icon`;
- const existing = await findByName(name);
+ const recordedId = unconfirmed.idOf(name);
+ const existing = recordedId ? undefined : await findByName(name);
if (existing) {
created.webResources[name] = existing;
runner.skip('app-shell', `app icon (generated) ${name} (exists — reuse)`);
return existing;
}
let id;
- await runner.run('app-shell', `app icon (generated) ${name}`, async () => {
- const r = await provision.createWebResource({ name, displayName: `${spec.app.name} Icon`, type: 'svg', content: defaultAppIconSvg(spec.app.name) });
- id = r.id;
- created.webResources[name] = r.id;
- await provision.addSolutionComponent({ componentId: r.id, componentType: COMPONENT_TYPE.webResource, solutionUniqueName: sol.uniqueName });
+ await runner.run('app-shell', `app icon (generated) ${name}${recordedId ? ' (written again: its publication was not confirmed)' : ''}`, async () => {
+ await keepRowOf(() => writeOwnedWebResource(provision, unconfirmed, sol, { name, displayName: `${spec.app.name} Icon`, type: 'svg', content: defaultAppIconSvg(spec.app.name) }, recordedId), (row) => {
+ id = row;
+ created.webResources[name] = row;
+ });
return name;
});
return id;
@@ -1109,21 +1331,49 @@ async function readPageManifest(provision, appUnique) {
// optional eighth that only spares the add when the solution is proven to hold the manifest already (see
// solution-membership.js). Every call goes through it, including the one that creates the manifest, which is
// why a first build that deploys pages makes the membership read.
-async function persistPageManifest(provision, spec, keyToId, sol, appUnique, existingId, lastContent, solutionMembers) {
+// `unconfirmed` (optional ninth) is the run's record of the web resources whose publication could not be confirmed (lib/web-resource-records.js). A write
+// the SDK could not confirm (WEB_RESOURCE_UNVERIFIED) is recorded and stops the step (keepUnconfirmedWebResource). The next run writes the manifest again
+// whenever its PUBLISHED copy — what readPageManifest reads, and `lastContent` is — is not what the run wants, by the id that read finds or, when no plain
+// read finds the row (a manifest created and never published), by the id the record holds; the name is never created again while the record holds it.
+async function persistPageManifest(provision, spec, keyToId, sol, appUnique, existingId, lastContent, solutionMembers, unconfirmed = openUnconfirmedWebResources()) {
const name = manifestResourceName(appUnique);
const content = serializeManifest(buildManifest(spec, keyToId));
- let id = existingId;
+ const recordedId = unconfirmed.idOf(name);
+ assertUnconfirmedWebResourceIdentity(name, recordedId, existingId);
+ let id = existingId || recordedId;
+ const addToSolution = (componentId) => ensureSolutionComponent(provision, solutionMembers, { componentId, componentType: COMPONENT_TYPE.webResource, solutionUniqueName: sol.uniqueName });
+ const write = async (writeId) => {
+ try {
+ if (writeId) {
+ await provision.updateWebResource(writeId, { content });
+ return writeId;
+ }
+ return (await provision.createWebResource({ name, displayName: `${spec.app.name} Page Manifest`, type: 'js', content })).id;
+ } catch (e) {
+ if (isUnconfirmedWrite(e)) throw await keepUnconfirmedWebResource(e, { name, unconfirmed, addToSolution });
+ throw e;
+ }
+ };
if (content !== lastContent) {
- if (id) await provision.updateWebResource(id, { content });
- else { const r = await provision.createWebResource({ name, displayName: `${spec.app.name} Page Manifest`, type: 'js', content }); id = r.id; }
+ try {
+ id = await write(id);
+ } catch (e) {
+ // The row the record names, which no plain read found, is gone: the manifest is created again, as on a first build.
+ if (!(recordedId && id === recordedId && isGoneRow(e))) throw e;
+ unconfirmed.clear(name);
+ id = await write(undefined);
+ }
}
- if (id) await ensureSolutionComponent(provision, solutionMembers, { componentId: id, componentType: COMPONENT_TYPE.webResource, solutionUniqueName: sol.uniqueName });
+ if (id) await addToSolution(id);
+ // Written and verified now, or its published copy already holds what this run wants: either way it is confirmed.
+ unconfirmed.clear(name);
return { id, content };
}
// Add the app's sitemap (componenttype 62) to the solution. Adding the app module alone leaves the
// sitemap only in the Default solution, so the app's own solution is incomplete on export. Resolve
-// the sitemap by its unique name (== the app's unique name) and add it. Best-effort + idempotent:
+// it by the naming convention of SDK-created apps (the app's unique name). This additive lookup is
+// not an ownership proof for a renamed or externally created sitemap. Best-effort + idempotent:
// a re-add of an already-present component is tolerated so this never fails an otherwise-good build.
async function ensureSitemapInSolution(provision, sol, appUnique, solutionMembers) {
try {
@@ -1164,6 +1414,30 @@ function existingAppSitemapIsWritten(spec, phases, changedOnly) {
return !appHasPageSubareas(spec);
}
+// Whether this run creates a NEW app's pages BEFORE the app, so that the app's first navigation already holds its page entries — the one
+// way a new app whose navigation holds only pages can be built, since Dataverse refuses to CREATE a sitemap with no entry (app-navigation.js).
+// It mirrors what runSdkBuildPhases does for such an app, and the tests that drive the engine pin that it does:
+// * the app step and the pages phase are both in the run: the app step leaves the create to the pages phase, which makes the app once
+// the pages exist (`createAppWithPages`);
+// * it is not a changed-only re-upload (`skipSitemapFinalize`), which uploads the changed pages of an app that exists and creates no app;
+// * every page entry names a page of `pages[]` the run builds — a tsx source with a codeFile, the pages phase's `implemented` — because the
+// app's first navigation is made from the pages the run created. Validation's deploy profile, which `--apply` uses, already demands that
+// (a page entry names a declared page, and every page is implemented), so this guards a caller that did not validate.
+// Returns { newAppPagesFirst: true }, or { newAppPagesFirst: false, whyNotPagesFirst } — the rule navigationVerdict takes, with the words of
+// its refusal.
+function pagesFirstRule(spec, phases, changedOnly) {
+ if (!phases.includes('app-shell')) return { newAppPagesFirst: false, whyNotPagesFirst: 'this run has no app step' };
+ if (!phases.includes('pages')) return { newAppPagesFirst: false, whyNotPagesFirst: 'this run does not have the pages phase, which would create them first' };
+ if (changedOnly && changedOnly.skipSitemapFinalize) return { newAppPagesFirst: false, whyNotPagesFirst: 'this run only re-uploads changed pages, and creates no app' };
+ const built = new Set((spec.pages || []).filter((p) => {
+ const src = normalizePageSource(p);
+ return src && src.kind === 'tsx' && src.codeFile;
+ }).map((p) => p.key || p.name));
+ const unbuilt = navigationHolds(spec).pages.filter((key) => !built.has(key));
+ if (unbuilt.length) return { newAppPagesFirst: false, whyNotPagesFirst: `this run builds no page for ${unbuilt.map((key) => `'${key}'`).join(', ')} (a page of pages[] with source.kind 'tsx' and a codeFile)` };
+ return { newAppPagesFirst: true };
+}
+
// The dry run's share of the navigation check: say, on the app step's own line, that an apply would stop there, and why.
// The line is marked as a view the build would refuse is (annotateLivePlan): `? unknown` with the reason, and `wouldHalt` so
// the summary counts it among the steps that would stop the build and not among those it could not read. Whether the app
@@ -1176,6 +1450,7 @@ function checkNavigationInPlan(plan, spec, { phases, changedOnly, warn }) {
const verdict = navigationVerdict(spec, {
appExists: item.state === 'create' ? false : item.state === 'reuse' ? true : undefined,
existingAppIsWritten: existingAppSitemapIsWritten(spec, phases, changedOnly),
+ ...pagesFirstRule(spec, phases, changedOnly),
whyUnknown: item.state === 'unknown' ? (item.stateWhy || 'the app could not be read') : 'this dry run did not read the environment',
});
if (verdict.outcome === 'refuse') {
@@ -1193,19 +1468,23 @@ function checkNavigationInPlan(plan, spec, { phases, changedOnly, warn }) {
// exists, refused for a new one — which pays for one read of that, the very read the app step makes next. A read that fails
// leaves the answer unknown: the build goes on as it always did and says what it could not check. Halts as the view-filter
// pre-flight does (phase `preflight`, never retried).
+// A navigation of pages only, in a run that creates a new app's pages first (pagesFirstRule), builds whichever the answer is, and
+// the read is made all the same: so that a build of an app that exists makes exactly the requests it always made. What decides
+// whether the pages come first is the app step's own read, right before the create, never this one.
async function checkNavigationBeforeWriting(spec, { provision, phases, changedOnly, warn }) {
- const rule = { existingAppIsWritten: existingAppSitemapIsWritten(spec, phases, changedOnly) };
- let verdict = navigationVerdict(spec, rule);
- if (verdict.outcome === 'unknown') {
- let appExists;
- let whyUnknown;
+ const written = { existingAppIsWritten: existingAppSitemapIsWritten(spec, phases, changedOnly) };
+ const rule = { ...written, ...pagesFirstRule(spec, phases, changedOnly) };
+ const readsExistence = navigationVerdict(spec, written).outcome === 'unknown';
+ let appExists;
+ let whyUnknown;
+ if (readsExistence) {
try {
appExists = !!(await provision.findArtifact('app', { uniqueName: appUniqueName(spec) }));
} catch (err) {
whyUnknown = (err && err.message) || String(err);
}
- verdict = navigationVerdict(spec, { ...rule, appExists, whyUnknown });
}
+ const verdict = navigationVerdict(spec, readsExistence ? { ...rule, appExists, whyUnknown } : rule);
if (verdict.outcome === 'refuse') {
// The message quotes the author's own page keys, so it must never be read as one of the texts the CLI retries on (isTransientHalt), and a re-run reads the same spec.
throw new BuildHalt(`app "${spec.app.name}" cannot be built: ${verdict.message} The build stopped before writing anything.`, { phase: 'preflight', code: verdict.code, recoverable: false, retry: RETRY.NEVER });
@@ -1213,6 +1492,55 @@ async function checkNavigationBeforeWriting(spec, { provision, phases, changedOn
if ((verdict.outcome === 'unknown' || verdict.outcome === 'warn') && typeof warn === 'function') warn(`app "${spec.app.name}": ${verdict.message}`);
}
+// A page's bindings are written as the spec states them, and the spec cannot make what they name: a connection reference, which a page calls its connector through by its logical name, or a Custom API. So the
+// build reads what the environment has for the names the pages it writes state (lib/page-binding-targets.js) and judges it, before it writes anything:
+// - a reference that is there for ANOTHER connector stops the build (phase `preflight`, never retried: a run again reads the same reference). The page would call that connector under this name, with the
+// signed-in user's connection to it, and nothing in the name tells the two apart — so it is refused, and nothing is guessed or made: the author gives the binding the name of the right reference, or states
+// the connector this environment has. Left to the pages phase it would stop after the solution, the tables, the views, the forms and the app were written, as the navigation check used to;
+// - a reference or a Custom API that is not there, a reference that has no connection, an operation a binding calls that the custom connector there does not define, a Custom API of the other kind or bound
+// to another table, and a read that failed are SAID, by name, and the build goes on: the page is written with its binding (a reference made, or given its connection, later makes the page work without a
+// rebuild), and an ordinary read failure says only that the bindings were not checked. A refused throttle wait is still the attempt's budget stop, checked by its runner before any mutation.
+// Only a run that has the pages phase writes a binding, and a changed-only run writes the pages it selected (pagesStatingBindings). A spec that states none reads nothing.
+async function readPageBindingVerdict(spec, { provision, phases, changedOnly }) {
+ if (!phases.includes('pages')) return null;
+ const pages = pagesStatingBindings(spec, { changedOnly });
+ if (!pages.length) return null;
+ return judgeBindingTargets(pages, await readBindingTargets(provision, pages));
+}
+
+async function checkPageBindingsBeforeWriting(spec, { provision, phases, changedOnly, warn }) {
+ const verdict = await readPageBindingVerdict(spec, { provision, phases, changedOnly });
+ if (!verdict) return;
+ const refused = verdict.findings.filter((finding) => finding.severity === 'refuse');
+ if (refused.length) {
+ // The message quotes the author's own page and binding names, so it must never be read as one of the texts the CLI retries on (isTransientHalt); `retry: RETRY.NEVER` marks it outright.
+ throw new BuildHalt(
+ `${refused.length} connector binding(s) name a connection reference this environment already has for ANOTHER connector: ${refused.map((finding) => finding.text).join('; ')}. The build stopped before writing anything. `
+ + 'A page calls a binding through its reference\'s logical name, so each of these pages would call the other connector. Either give the binding the logical name of a reference that is for the right connector '
+ + '(create-connection-reference.js makes one), or, if the reference that is here is the one the page should call (a custom connector made separately in each environment has another id in each), set the binding\'s connectorId in the spec to the connector this environment has.',
+ { phase: 'preflight', code: 'pages-binding-reference-conflict', recoverable: false, retry: RETRY.NEVER },
+ );
+ }
+ if (typeof warn === 'function') for (const text of [...verdict.unchecked.map((u) => u.text), ...verdict.findings.map((finding) => finding.text)]) warn(text);
+}
+
+// The dry run's share: say on the page's own line that an apply would stop there, and why. The line is marked as a view the build would refuse is (annotateLivePlan): `? unknown` with the reason, and `wouldHalt` so
+// the summary counts it among the steps that would stop the build. What an apply would only say is said the same way.
+async function checkPageBindingsInPlan(plan, spec, { provision, phases, changedOnly, warn }) {
+ const verdict = await readPageBindingVerdict(spec, { provision, phases, changedOnly });
+ if (!verdict) return;
+ const refusedBy = new Map();
+ for (const finding of verdict.findings.filter((f) => f.severity === 'refuse')) refusedBy.set(finding.page.name, [...(refusedBy.get(finding.page.name) || []), finding.text]);
+ for (const [name, texts] of refusedBy) {
+ const item = plan.find((p) => p.phase === 'pages' && p.label === `page "${name}"`);
+ if (!item) continue;
+ item.state = 'unknown';
+ item.stateWhy = `the build would stop before writing anything: ${texts.join('; ')}`;
+ item.wouldHalt = true;
+ }
+ if (typeof warn === 'function') for (const text of [...verdict.unchecked.map((u) => u.text), ...verdict.findings.filter((f) => f.severity !== 'refuse').map((f) => f.text)]) warn(text);
+}
+
// SINGLE-MACHINE advisory lockfile over the pages protocol (design §9, DESCOPED from a cross-machine guarantee).
// A courtesy to stop two LOCAL builds of the same app racing to CREATE duplicate pages; correctness does
// NOT depend on it — the convergence spine (fail-closed enumeration + create-absent-first + persist-after-
@@ -2654,6 +2982,14 @@ async function runSdkBuildPhases(spec, opts, owed) {
}
}
if (has('app-shell')) checkNavigationInPlan(plan, spec, { phases, changedOnly: opts.changedOnly, warn: opts.warn });
+ // What the environment has for the names the pages' bindings state (checkPageBindingsInPlan): it reads, so it is a part of the live plan and is left out of one that is asked not to read the environment.
+ if (canProbe && has('pages')) {
+ try {
+ await checkPageBindingsInPlan(plan, spec, { provision, phases, changedOnly: opts.changedOnly, warn: opts.warn });
+ } catch (err) {
+ if (typeof opts.warn === 'function') opts.warn(`could not check the bindings of the pages against this environment (${(err && err.message) || err})`);
+ }
+ }
plan.forEach((p, i) => emit({ phase: p.phase, status: p.state === 'reuse' ? 'skip' : 'skip', label: p.label, state: p.state, stateWhy: p.stateWhy, n: i + 1, total: plan.length }));
return {
ok: true,
@@ -2664,9 +3000,14 @@ async function runSdkBuildPhases(spec, opts, owed) {
};
}
+ // Capture the attempt's checkpoint before best-effort preflight reads can swallow a refused throttle wait as unchecked metadata. The same runner then stops before any mutation, without counting refusals from earlier attempts.
+ const runner = makeRunner({ emit, total: plan.length, throttle: opts.throttle });
// A navigation Dataverse will refuse stops the build here, before anything is written, rather than at the app step
// after the solution, tables, columns, views and forms have been (app-navigation.js). Only a run that has the app step.
if (has('app-shell')) await checkNavigationBeforeWriting(spec, { provision, phases, changedOnly: opts.changedOnly, warn: opts.warn });
+ // A binding whose connection reference is another connector's stops the build here too, before anything is written, for the same reason (checkPageBindingsBeforeWriting).
+ await checkPageBindingsBeforeWriting(spec, { provision, phases, changedOnly: opts.changedOnly, warn: opts.warn });
+ runner.stopIfRefused('preflight');
const createdFormsThisRun = new Set();
const result = { ok: true, created: { entities: {}, relationships: {}, records: {}, webResources: {}, views: {}, charts: {}, forms: {}, formIds: {}, businessRules: {}, businessProcessFlows: {}, bpfBackingTables: {}, commands: {}, dashboards: {}, pages: {}, pageDeployedShas: {}, pageSourceShas: {}, ai: { appFeatures: null, summaries: {} }, roles: {}, roleGrants: {}, bpfRoleGrants: {}, app: null }, skipped: { businessRules: [], aiSummaries: [], layout: [], unauthorizedRemovals: [] } };
@@ -2675,9 +3016,11 @@ async function runSdkBuildPhases(spec, opts, owed) {
// The full-build path never sets opts.changedOnly, so result.created.app stays null and app-shell
// creates/updates it exactly as before — this branch is a no-op (byte-identical) on the normal path.
if (opts.changedOnly && opts.changedOnly.resolvedAppId) result.created.app = opts.changedOnly.resolvedAppId;
- // The runner stops the run at the next step once the budget has refused a wait (entity-provision.js, makeRunner): the build's retry loop does not run the phases again to meet the same answer.
- const runner = makeRunner({ emit, total: plan.length, throttle: opts.throttle });
const sol = spec.solution;
+ // The web resources an earlier run of this build wrote and could not confirm were published (lib/web-resource-records.js), read at first use: the
+ // spec's web resources, the generated app icon and the page manifest are written again by id when they are in it. One per run of the phases, so the
+ // build's own re-run of a halt reads what the attempt before it recorded.
+ const unconfirmedWebResources = openUnconfirmedWebResources({ workspaceDir: opts.workspaceDir, environment: opts.env, warn: opts.warn });
// ADO 6691114: a view-filter label the environment already shows to be wrong stops the build here, before it
// writes anything — in any apply that writes the solution or the data model, whether or not it also builds the
@@ -2959,8 +3302,17 @@ async function runSdkBuildPhases(spec, opts, owed) {
// 3b. Web resources (opt-in via spec.webResources) — JS/HTML/CSS shipped for form logic.
// Idempotent: an existing web resource of the same name is reused (and assumed already
// in the solution). Built before forms so a form event handler can bind its library.
+ // One that an earlier run of this build created or wrote and could not confirm was published (WEB_RESOURCE_UNVERIFIED,
+ // recorded in the workspace) is not reused: its content is written again by id (writeOwnedWebResource).
if (has('web-resources')) {
for (const wr of spec.webResources || []) {
+ const recordedId = unconfirmedWebResources.idOf(wr.name);
+ if (recordedId) {
+ await runner.run('web-resources', `web resource ${wr.name} (${wr.type || 'js'}) (written again: its publication was not confirmed)`, async () => {
+ await keepRowOf(() => writeOwnedWebResource(provision, unconfirmedWebResources, sol, webResourceOpts(wr, opts.appDir), recordedId), (id) => { result.created.webResources[wr.name] = id; });
+ });
+ continue;
+ }
const existing = await provision.queryRecords('webresource', { select: ['webresourceid'], filter: `name eq '${odataLit(wr.name)}'`, top: 1 });
if (existing && existing[0] && existing[0].webresourceid) {
result.created.webResources[wr.name] = existing[0].webresourceid;
@@ -2968,9 +3320,7 @@ async function runSdkBuildPhases(spec, opts, owed) {
continue;
}
await runner.run('web-resources', `web resource ${wr.name} (${wr.type || 'js'})`, async () => {
- const r = await provision.createWebResource(webResourceOpts(wr, opts.appDir));
- result.created.webResources[wr.name] = r.id;
- await provision.addSolutionComponent({ componentId: r.id, componentType: COMPONENT_TYPE.webResource, solutionUniqueName: sol.uniqueName });
+ await keepRowOf(() => writeOwnedWebResource(provision, unconfirmedWebResources, sol, webResourceOpts(wr, opts.appDir)), (id) => { result.created.webResources[wr.name] = id; });
});
}
// 3c. Table icons — set each entity's OWN icon to a declared web resource (SVG -> IconVectorName
@@ -2991,6 +3341,8 @@ async function runSdkBuildPhases(spec, opts, owed) {
runner.skip('web-resources', `table icon for ${logical} (web resource ${missing.join(', ')} not built this run)`);
continue;
}
+ // A failed publish can leave this name in saved metadata already. Keep the SDK's
+ // specific-table publish on rerun; metadata equality is not publication proof.
await runner.run('web-resources', `table icon for ${logical}`, async () => {
await provision.setEntityIcon(logical, { vector: e.vectorIcon || undefined, medium: e.icon || undefined });
return `${[e.vectorIcon && `vector=${e.vectorIcon}`, e.icon && `raster=${e.icon}`].filter(Boolean).join(', ')}`;
@@ -5861,6 +6213,10 @@ async function runSdkBuildPhases(spec, opts, owed) {
// views/charts already built), then push + add to the solution (systemform, component type 60).
// Global (no entity); placement in the app sitemap is manual for now.
if (has('dashboards')) {
+ // The dashboards an earlier run of this build created and did not see join the solution (lib/dashboard-creation-records.js), read at first use. One
+ // per run of the phases, so the build's own re-run of a halt reads what the attempt before it recorded. Bound to this app and solution as the spec
+ // names them: a new app has no id yet, and its unique name is the spec's.
+ const creations = openDashboardCreations({ workspaceDir: opts.workspaceDir, environment: opts.env, appUniqueName: spec.app ? appUniqueName(spec) : '', solutionUniqueName: sol && sol.uniqueName, warn: opts.warn });
for (const dash of spec.dashboards || []) {
// AB#6726727: a DOWNLOADED dashboard is bound by the id it was read from before anything is tried
// by name. Renamed in the designer since, its spec name finds nothing — and the name path below
@@ -5874,6 +6230,17 @@ async function runSdkBuildPhases(spec, opts, owed) {
result.created.dashboards[dash.name] = pinned.id;
continue;
}
+ // A dashboard an earlier run created and stopped before adding to the solution is settled by the id that run recorded, BEFORE the name lookup
+ // below: a row created and never published is in no plain read, so the lookup would create a second one, and a published one it would reuse
+ // outside the solution (recoverRecordedDashboard). With nothing recorded for the name this costs nothing — no request.
+ const recordedIds = creations.idsOf(dash.name);
+ if (recordedIds) {
+ const recovered = await recoverRecordedDashboard(provision, { dash, ids: recordedIds, sol, runner, creations });
+ if (recovered) {
+ result.created.dashboards[dash.name] = recovered;
+ continue;
+ }
+ }
// Additive discover-reconcile (design §14): a dashboard is global (identity = name), so a rebuild
// or retry must REUSE the existing one instead of createArtifact-ing a duplicate every run (the old
// behavior). Discovery is `resolveArtifact('dashboard', { name })` — findArtifact does NOT support
@@ -5936,7 +6303,17 @@ async function runSdkBuildPhases(spec, opts, owed) {
for (let ti = 0; ti < tiles.length; ti++) {
await provision.addElement('dashboard', art.id, '/components', dashboardComponent(dashboardTileOpts(spec, tiles[ti], result), ti));
}
+ // Recorded BEFORE the push: the SDK sends this id as the row's key (`systemform.formid`), so if the run stops anywhere after the create is
+ // sent — killed, its answer lost, the add below and its undo both failing — the next run still knows which row it made, which no name and no
+ // plain read can tell it (lib/dashboard-creation-records.js). A record that cannot be written is one warning, and the build goes on as it did
+ // before there was a record: refusing to create the dashboard would turn a local bookkeeping failure into a failed build for every dashboard,
+ // to guard against a crash in the moment between two requests.
+ creations.note(dash.name, art.id);
const pushed = requireSuccessfulPush(await provision.pushArtifact('dashboard', art.id), `dashboard ${dash.name}`, opts.warn);
+ // The SDK prefers the id the service's answer names over the one it sent, and moves its copy there. When they differ, both are kept: the next
+ // run reads both, and neither is confirmed on the other's word.
+ const bareId = (id) => String(id).replace(/[{}]/g, '').toLowerCase();
+ if (bareId(pushed.id) !== bareId(art.id)) creations.observe(dash.name, pushed.id);
try {
await provision.addSolutionComponent({ componentId: pushed.id, componentType: COMPONENT_TYPE.dashboard, solutionUniqueName: sol.uniqueName });
} catch (err) {
@@ -5952,6 +6329,10 @@ async function runSdkBuildPhases(spec, opts, owed) {
} catch (e) {
undoErr = e;
}
+ // Proven removed only when the delete answered: the record goes with the row. When it did not, the record stays whatever the read below
+ // finds — that read answers the PUBLISHED layer, where a dashboard nobody has published is not, so it cannot prove the row gone; the next run
+ // reads the saved layer (recoverRecordedDashboard).
+ if (!undoErr) creations.clear(dash.name);
// deleteRemoteArtifact removes the row and THEN the local workspace copy, so a failure can come
// from either half. Only a row that is still there is left outside the solution; when that
// cannot be read either, assume it is.
@@ -5964,9 +6345,14 @@ async function runSdkBuildPhases(spec, opts, owed) {
} catch { /* cannot tell — keep assuming it is still there */ }
}
if (stranded) {
- // Never auto-retried (isTransientHalt, build-model-app.js): a retry would reuse it as a lone
- // name match without adding it, whatever transient text the causes quoted above carry.
- throw refusal(`dashboard "${dash.name}" was created (${pushed.id}) but could not be added to solution '${sol.uniqueName}' (${why}), and removing it again failed (${(undoErr && undoErr.message) || undoErr}) — add it to the solution or delete it in Maker before re-running, or teardown will not recognise it as this app's`, { cause: err });
+ // Never auto-retried (isTransientHalt, build-model-app.js): the add and its undo were both refused just now, which is a person's to look
+ // at, whatever transient text the causes quoted above carry — and a dashboard the record does not hold would be reused by a retry as a lone
+ // name match without being added. One the record holds is added by the next run, so the halt says that instead of asking for Maker.
+ const recorded = (creations.idsOf(dash.name) || []).includes(bareId(pushed.id));
+ const remedy = recorded
+ ? 'this build recorded it, so running the build again adds it to the solution and reuses it; or delete it in Maker before running it again, and it is created afresh'
+ : "add it to the solution or delete it in Maker before re-running, or teardown will not recognise it as this app's";
+ throw refusal(`dashboard "${dash.name}" was created (${pushed.id}) but could not be added to solution '${sol.uniqueName}' (${why}), and removing it again failed (${(undoErr && undoErr.message) || undoErr}) — ${remedy}`, { cause: err });
}
// Nothing is left behind, so a retry is safe — when the SERVICE said it may be: the cause's HTTP
// status (a 429/503 is still auto-retried as it was before the undo existed) and its own words
@@ -5975,6 +6361,8 @@ async function runSdkBuildPhases(spec, opts, owed) {
status: err && (err.statusCode || err.status), words: judgeFailure(err).text, cause: err,
});
}
+ // Proven in the solution: nothing is left to recover.
+ creations.clear(dash.name);
result.created.dashboards[dash.name] = pushed.id;
});
}
@@ -5988,9 +6376,15 @@ async function runSdkBuildPhases(spec, opts, owed) {
let appWasExisting = false;
let mainFormsP;
const resolvedMainForms = () => mainFormsP || (mainFormsP = resolveMainForms(provision.dataverse, spec, result.created.formIds));
+ // Set by the app step when it leaves the create of a NEW app to the pages phase, because the app's navigation holds only page entries
+ // (pagesFirstRule): the pages are created first, and this makes the app with them already in its first navigation.
+ let createAppWithPages = null;
// 7. App module + sitemap. When the app has generative-page subareas, create it WITHOUT them
// (they can't resolve until pages upload); the pages phase then rewrites the sitemap.
+ // A NEW app whose navigation holds ONLY page entries cannot be created that way — its first sitemap would hold no
+ // entry, which Dataverse refuses to create — so its create is left to the pages phase, which makes it once the pages
+ // exist (`createAppWithPages`), with the pages in its first navigation.
// For an app that ALREADY exists (edit flow / retry), its sitemap + components are write-once
// on create, so a plain reuse would silently drop requested subarea add/rename/reorder edits.
// Fetch it into this session's workspace (also required before push/publish on a cross-session
@@ -6010,8 +6404,39 @@ async function runSdkBuildPhases(spec, opts, owed) {
// author's spec.app.icon). Resolved BEFORE appDef so the id is embedded at create time — the
// reliable path (an appmodule's webresourceid is effectively write-once). This replaces the
// SDK's arbitrary external/managed icon fallback that broke import into a fresh environment.
- const iconWebResourceId = await ensureAppIcon(spec, result.created, { provision, sol, runner });
+ const iconWebResourceId = await ensureAppIcon(spec, result.created, { provision, sol, runner, unconfirmed: unconfirmedWebResources });
const def = appDef(spec, result.created, { omitUnbuiltPages: true, iconWebResourceId, mainFormsByTable });
+ // The create of a NEW app, made below — or, for a navigation of pages only, at the end of the pages phase (createAppWithPages): the
+ // same writes in the same order either way.
+ // Create: the full def (siteMap + explicit components + iconWebResourceId) serializes unchanged
+ // through createArtifact, and push emits appmodule -> sitemap -> AddAppComponents -> publish.
+ // The def leaves `published` unset on purpose, so that push publishes the app. The SDK can
+ // create a never-published draft (`published: false`) for the final publish to cover — one publish
+ // round trip less — but a draft answers 404 by id and is missing from the PUBLISHED projection that
+ // every probe here reads (findArtifact('app'), the collision gate, the sitemap/navigation reads of
+ // the pages phase that follows, verify, download). A failed first build would leave an app its own
+ // re-run cannot see (it would POST the same unique name again), the pages phase would find no sitemap
+ // and halt, and a build without --publish would never publish it. Pinned in sdk-opt-ins.test.js.
+ const createApp = async (createDef) => {
+ const pushed = requireSuccessfulPush(await explainAppPushWarnings(provision.dataverse, await appWriters.create(createDef), createDef.name), `app ${createDef.name}`, opts.warn);
+ // Join the solution straight after the push, before the hidden-table pin, its read-back and the
+ // publish that follows it can fail. A re-run finds the app and takes this step's reuse branch, which
+ // re-asserts the membership too, so a create interrupted here never leaves a solution without its app.
+ await provision.addSolutionComponent({ componentId: pushed.id, componentType: COMPONENT_TYPE.app, solutionUniqueName: sol.uniqueName });
+ // The app module and its sitemap are DISTINCT solution components — adding the appmodule does
+ // NOT pull the sitemap in (it lands only in the Default solution), so export/import from the
+ // app's own solution would be incomplete. Add the sitemap (componenttype 62) explicitly.
+ await ensureSitemapInSolution(provision, sol, createDef.uniqueName);
+ await pinTables(pushed.id, true);
+ return pushed.id;
+ };
+ // Whether a NEW app is created after its pages: decided from the spec and the run here, and from whether the app exists by the read
+ // the step makes next — the same read that decides create or reuse for every app, right before the write.
+ const pagesFirst = navigationIsPagesOnly(spec) && pagesFirstRule(spec, phases, opts.changedOnly).newAppPagesFirst;
+ // What the step throws to hand the create on. The runner then reports the step as SKIPPED, with the reason, rather than done (makeRunner
+ // `skipIf`, entity-provision.js): an app that does not exist yet is not one this step made, and a ✓ would say it was. It is taken back by
+ // identity and never leaves the step; it is a refusal (retry-policy.js) so that, were it ever to, it would say a run again changes nothing.
+ const createdAfterItsPages = refusal('the app is created after its pages, by the pages phase');
result.created.app = await runner.run('app-shell', `app "${def.name}"`, async () => {
// Whether the app exists says whether its components can be read to prove which tables it holds forms or charts of (publishTablesBeforeApp), so it is looked up first.
const existingId = await provision.findArtifact('app', { uniqueName: def.uniqueName });
@@ -6111,40 +6536,35 @@ async function runSdkBuildPhases(spec, opts, owed) {
await warnAppIconNotApplied(provision, spec, iconWebResourceId, opts.warn);
return existingId;
}
- // Create: the full def (siteMap + explicit components + iconWebResourceId) serializes unchanged
- // through createArtifact, and push emits appmodule -> sitemap -> AddAppComponents -> publish.
- // The def leaves `published` unset on purpose, so the push above publishes the app. The SDK can
- // create a never-published draft (`published: false`) for the final publish to cover — one publish
- // round trip less — but a draft answers 404 by id and is missing from the PUBLISHED projection that
- // every probe here reads (findArtifact('app'), the collision gate, the sitemap/navigation reads of
- // the pages phase that follows, verify, download). A failed first build would leave an app its own
- // re-run cannot see (it would POST the same unique name again), the pages phase would find no sitemap
- // and halt, and a build without --publish would never publish it. Pinned in sdk-opt-ins.test.js.
- const pushed = requireSuccessfulPush(await explainAppPushWarnings(provision.dataverse, await appWriters.create(def), def.name), `app ${def.name}`, opts.warn);
- // Join the solution straight after the push, before the hidden-table pin, its read-back and the
- // publish that follows it can fail. A re-run finds the app and takes the reuse branch above, which
- // re-asserts the membership too, so a create interrupted here never leaves a solution without its app.
- await provision.addSolutionComponent({ componentId: pushed.id, componentType: COMPONENT_TYPE.app, solutionUniqueName: sol.uniqueName });
- // The app module and its sitemap are DISTINCT solution components — adding the appmodule does
- // NOT pull the sitemap in (it lands only in the Default solution), so export/import from the
- // app's own solution would be incomplete. Add the sitemap (componenttype 62) explicitly.
- await ensureSitemapInSolution(provision, sol, def.uniqueName);
- await pinTables(pushed.id, true);
- return pushed.id;
- });
+ if (pagesFirst) {
+ // A NEW app whose navigation holds only page entries: created with `def` it would have no entry at all (its pages do not
+ // exist yet), and Dataverse refuses to create such a sitemap. So the pages phase creates the pages first and then the app,
+ // through this, with the WHOLE navigation — appDef without `omitUnbuiltPages`, over `result.created.pages`, which by then
+ // holds every page's id. Everything this step does before a create has been done above: the icon, the Main-form list, the
+ // `app.tables` refs and the one request that publishes the tables before the app, which nothing in the pages phase undoes
+ // (it writes pages and the manifest, no table, view or form).
+ createAppWithPages = async () => {
+ result.created.app = await createApp(appDef(spec, result.created, { iconWebResourceId, mainFormsByTable }));
+ return result.created.app;
+ };
+ throw createdAfterItsPages;
+ }
+ return createApp(def);
+ }, { skipIf: (err) => err === createdAfterItsPages && 'created after its pages: its navigation holds only page entries' });
}
- // 7b. Pages (generative pages). The app now exists; implement the full §9 protocol: structural scan/parity
+ // 7b. Pages (generative pages). The app now exists — or, for a NEW app whose navigation holds only page entries, it is created at the
+ // end of this phase, once its pages exist (`createAppWithPages`); implement the full §9 protocol: structural scan/parity
// BEFORE any write (fail-closed) → create-absent-first for nav targets (persist manifest after EVERY
// create, crash-safety) → resolve nav pagerefs into run-scoped staging (never mutate canonical source)
// → upload-once with UPDATE-identity guard → sitemap finalize. All under a single-machine advisory
// lockfile (courtesy, not a correctness guarantee — convergence spine is the safety guarantee).
// Run the pages phase when the phase is enabled AND there is page work to do: the spec declares pages,
// OR the app already existed (an existing app may still reference live pages the new spec dropped;
- // the destructive-removal gate below must run even when spec.pages is now empty). A FRESH app with no
- // spec pages has nothing to build and no pre-existing pages to remove, so it is correctly skipped (this
- // also avoids spinning up genpage enumeration for every page-less app build).
- if (has('pages') && ((spec.pages || []).length || appWasExisting)) {
+ // the destructive-removal gate below must run even when spec.pages is now empty), OR the app is still to be
+ // created here. A FRESH app with no spec pages has nothing to build and no pre-existing pages to remove, so it
+ // is correctly skipped (this also avoids spinning up genpage enumeration for every page-less app build).
+ if (has('pages') && ((spec.pages || []).length || appWasExisting || createAppWithPages)) {
// The page backend: the SDK on a throwaway workspace of its own, removed in the finally below (never the app folder's, whose copies of a
// page would be stale the moment anyone saved it). `opts.genpage` is a seam for the tests, and is the caller's to dispose. The run's throttle budget
// (`opts.throttle`) is handed to it, so the HTTP client it makes draws its waits for a throttled read or publish from the same five minutes as the page writes do.
@@ -6152,8 +6572,9 @@ async function runSdkBuildPhases(spec, opts, owed) {
const genpage = opts.genpage || makeGenpageSdk(opts.env, { throttle: opts.throttle });
const appUnique = appUniqueName(spec);
// Recovery guard: the app id is only populated by app-shell (this run). If pages runs without it
- // (e.g. --from pages), there is nothing to upload against — HALT and require a FULL rerun.
- if (!result.created.app) throw new BuildHalt('pages phase requires the app (app-shell) in the same run — the app id is not carried across invocations. Re-run a FULL build (do not use --from pages).', { phase: 'pages', code: 'pages-requires-app', recoverable: false, retry: RETRY.NEVER });
+ // (e.g. --from pages), there is nothing to upload against — HALT and require a FULL rerun. An app the app step left to this
+ // phase to create has no id yet, by design: it is made below, once the pages exist.
+ if (!result.created.app && !createAppWithPages) throw new BuildHalt('pages phase requires the app (app-shell) in the same run — the app id is not carried across invocations. Re-run a FULL build (do not use --from pages).', { phase: 'pages', code: 'pages-requires-app', recoverable: false, retry: RETRY.NEVER });
const wsDir = opts.workspaceDir || path.join(path.resolve(opts.appDir || '.'), '.maker-workspace');
// Advisory lease: acquired OUTSIDE the try so a failed acquire (pages-locked HALT) never triggers the
// finally that would release a lease we never held. Correctness rests on the convergence spine, not this.
@@ -6174,14 +6595,22 @@ async function runSdkBuildPhases(spec, opts, owed) {
// only when it is a proven member of THIS app). A page-bearing build has just created or is editing
// the app, so the sitemap MUST be readable; ok:false is a real failure, never "empty". A fresh app's
// sitemap is validly empty of genpages here → ids:[] (correct). Reused below for the removal gate.
- const membership = await fetchSitemap(provision, appUnique);
- if (!membership.ok) throw new BuildHalt(`could not read the app sitemap (${membership.reason}) — refusing to proceed without verifying the app's page set`, { phase: 'pages', code: 'pages-sitemap-read-failed', recoverable: true, ...retryFrom(membership.cause, membership.detail) });
- const sitemapIds = membership.ids;
+ // An app this phase is still to create (`createAppWithPages`) has no sitemap: the app step's read found no app a moment ago, so
+ // nothing is a member of it and nothing is read. Its answer is the one fetchSitemap gives for an app that does not exist, which the
+ // conflict advice below (navigationProof) reads the same way. That proves no page: an id binds only through the creation receipt
+ // a build of this app wrote for it (reconcilePageIds) — the rule that already binds a page made by a build that stopped before its
+ // finalizer — and the removal gate has no live page of this app to protect.
+ const membership = createAppWithPages ? { ok: false, reason: 'app-not-found' } : await fetchSitemap(provision, appUnique);
+ if (!membership.ok && !createAppWithPages) throw new BuildHalt(`could not read the app sitemap (${membership.reason}) — refusing to proceed without verifying the app's page set`, { phase: 'pages', code: 'pages-sitemap-read-failed', recoverable: true, ...retryFrom(membership.cause, membership.detail) });
+ const sitemapIds = membership.ok ? membership.ids : [];
// IDENTITY (the durable manifest, discriminated read). A PRESENT-but-unparseable manifest is CORRUPT
// and must HALT fail-closed BEFORE reconcile — reconciling it as "no identity" would recreate the
// app's existing pages as orphans. An ABSENT manifest (present:false) is normal for a fresh app.
const { id: readId, manifest, text, present } = await readPageManifest(provision, appUnique);
+ const recordedManifestId = unconfirmedWebResources.idOf(manifestResourceName(appUnique));
+ assertUnconfirmedWebResourceIdentity(manifestResourceName(appUnique), recordedManifestId, readId);
+ if (recordedManifestId && !readId) await checkRecordedWebResourceName(provision, manifestResourceName(appUnique), recordedManifestId);
if (present && !manifest) throw new BuildHalt(`the page manifest ${manifestResourceName(appUnique)} exists but is corrupt/unparseable — refusing to proceed (would risk recreating existing pages as orphans). Fix or delete the web resource and rebuild.`, { phase: 'pages', code: 'pages-manifest-corrupt', recoverable: false, retry: RETRY.NEVER });
let manifestId = readId;
let lastManifestContent = text;
@@ -6320,7 +6749,8 @@ async function runSdkBuildPhases(spec, opts, owed) {
: '';
const recovery = unproven.map((c) => {
const name = JSON.stringify(c.storedName || c.requestedName || '(unreadable name)');
- // The page verbs of scripts/genpage.js, ready to run: this app's id is known by now (the pages phase halts without the app), and the environment is the one the build runs in.
+ // The page verbs of scripts/genpage.js, ready to run: this app's id is known by now (the pages phase halts without the app — but for an app this
+ // phase is still to create, whose advice is its own, below), and the environment is the one the build runs in.
const place = genpageCommand('add-to-app', { env: opts.env, pageId: c.manifestId, app: { id: result.created.app, note: "this app's id" } });
if (inSavedNav.has(String(c.manifestId).toLowerCase())) {
return `page ${c.manifestId} (${name}) is only in this app's saved but unpublished navigation: publish the app — ${place} publishes it, since the page is already in its saved navigation — then re-run. The build updates a page only when the app's published navigation or a local creation record proves it is this app's, so that other apps' navigation is checked before an update`;
@@ -6329,6 +6759,11 @@ async function runSdkBuildPhases(spec, opts, owed) {
? 'its local creation record does not corroborate the stored name'
: 'this workspace holds no record that this app created it in this environment';
const removal = genpageCommand('delete', { env: opts.env, pageId: c.manifestId, flags: ' --allow-destructive' });
+ // An app this phase is still to create has no navigation to add the page to, so the record is the only proof there can be: the
+ // workspace that created the page holds it (a build run from there adopts the page and creates the app with it).
+ if (createAppWithPages) {
+ return `page ${c.manifestId} (${name}) is in no navigation of this app — the app does not exist yet: its navigation holds only page entries, so the build creates it once its pages exist — and ${proofText}: if it is this app's page, run the build from the workspace that created it, which holds that record; if not, remove the stale id from the manifest/spec (or delete the page, after asking the user — it is permanent: ${removal}) and re-run`;
+ }
return `page ${c.manifestId} (${name}) is not in this app's navigation${unreadDraft} and ${proofText}: if it is this app's page, add it to the app's navigation with ${place} (it publishes the app and proves the page in what runs) and re-run; if not, remove the stale id from the manifest/spec (or delete the page, after asking the user — it is permanent: ${removal}) and re-run`;
});
throw new BuildHalt(`generative-page identity conflict(s): ${JSON.stringify(conflicts)}${nameReadErrors.length ? `; stored-name reads failed: ${nameReadErrors.join('; ')}` : ''} — refusing to overwrite/misbind a page. ${recovery.length ? recovery.join('; ') : 'Resolve the duplicate/mismatched id(s) in the spec/manifest and rebuild.'}`, { phase: 'pages', code: 'pages-identity-conflict', recoverable: false, retry: RETRY.NEVER });
@@ -6444,7 +6879,17 @@ async function runSdkBuildPhases(spec, opts, owed) {
}
}
- const persistNow = async () => { const pr = await persistPageManifest(provision, spec, keyToId, sol, appUnique, manifestId, lastManifestContent, solutionMembers); manifestId = pr.id; lastManifestContent = pr.content; };
+ // A write the SDK could not confirm leaves the manifest's row under the error's id: kept, so that this run's next persist — and the record, the next
+ // run's — writes it again by id rather than creating the name a second time (persistPageManifest).
+ const persistNow = async () => {
+ let pr;
+ try { pr = await persistPageManifest(provision, spec, keyToId, sol, appUnique, manifestId, lastManifestContent, solutionMembers, unconfirmedWebResources); } catch (e) {
+ if (isUnconfirmedWrite(e)) manifestId = e.id;
+ throw e;
+ }
+ manifestId = pr.id;
+ lastManifestContent = pr.content;
+ };
const recordCreate = (p, id) => {
// No workspace means no durable creation authority. Normal CLI builds always supply one.
if (!opts.workspaceDir) {
@@ -6676,7 +7121,7 @@ async function runSdkBuildPhases(spec, opts, owed) {
const first = await readRowVersions([pageId]);
const before = first.ok ? first.versions.get(pageId) : null;
if (!before) return null;
- const copy = await genpage.publishedDiffers(pageId, fields, { runtimeSha256 });
+ const copy = await genpage.publishedDiffers(pageId, { ...fields, specBindings: true }, { runtimeSha256 });
// `fingerprint` is the hash of the content the copy was compared with: it must be the hash the record keeps, or the answer is about other content.
if (!copy.ok || copy.fingerprint !== fingerprint) return null;
if (copy.differing.length) {
@@ -6690,10 +7135,19 @@ async function runSdkBuildPhases(spec, opts, owed) {
} catch { return null; }
};
const rememberPublished = async (written, p, fields) => {
- if (!opts.workspaceDir || !written.publish || written.publish.kind !== 'verified' || typeof written.fingerprint !== 'string') return;
+ if (!opts.workspaceDir || typeof written.fingerprint !== 'string') return;
const pageId = String(written.pageId).toLowerCase();
- const files = await provedVersions(p, pageId, fields, written.fingerprint, written.runtimeSha256);
- publishedPages.set(pageId, { fingerprint: written.fingerprint, files });
+ if (written.receiptUpgraded) {
+ // The record of an earlier publish was made before the spec stated the page's binding lists, and the update found that it stands for them too (it read the published copy and it holds them): the page was not written
+ // and not published, so there is nothing new to prove — the record is renewed to the hash of what the spec states now, with the versions it already holds, which `publishesStillStanding` has just found to be the page's.
+ const standing = publishedPages.get(pageId);
+ if (!standing || !standing.files) return;
+ publishedPages.set(pageId, { fingerprint: written.fingerprint, files: standing.files });
+ } else {
+ if (!written.publish || written.publish.kind !== 'verified') return;
+ const files = await provedVersions(p, pageId, fields, written.fingerprint, written.runtimeSha256);
+ publishedPages.set(pageId, { fingerprint: written.fingerprint, files });
+ }
const bound = new Set(Array.from(keyToId.values(), (id) => String(id).toLowerCase()));
try {
writePublishedPages(opts.workspaceDir, appUnique, opts.env, new Map([...publishedPages].filter(([id]) => bound.has(id))));
@@ -6738,7 +7192,7 @@ async function runSdkBuildPhases(spec, opts, owed) {
for (const p of implemented) {
const key = keyOf(p);
if (keyToId.has(key) || !navTargets.has(key)) continue; // only ABSENT targets need pre-minting
- const fields = { name: p.name, source: sourceByKey.get(key), prompt: p.prompt, agentMessage: p.agentMessage, dataSources: p.dataSources || [], model: p.model };
+ const fields = { name: p.name, source: sourceByKey.get(key), prompt: p.prompt, agentMessage: p.agentMessage, dataSources: p.dataSources || [], model: p.model, ...statedPageBindings(p) };
const up = await createPage(p, fields);
recordCreate(p, up.pageId);
keyToId.set(key, up.pageId);
@@ -6835,11 +7289,14 @@ async function runSdkBuildPhases(spec, opts, owed) {
// The spec's data sources are authoritative, as they always were: a page that lists none is bound to none. The model and name ride along
// too, but the page's own are kept when the spec has none (the SDK writes only what differs; pac stored whatever `--model` it was
// sent, so a re-upload without one used to wipe a deployed page's model id to ""). A downloaded spec carries the model (pages[].model).
+ // The connector and Custom API bindings go the same way, and only when the page states them: one it leaves out is the deployed page's own, and a list it states — `[]` too — replaces it. They are the spec's, which
+ // states each entry by the properties it can carry (lib/page-bindings.js), so the update reads them against the page's own entries (`specBindings`): a page that already holds what the spec states is not
+ // written, and an entry that is changed keeps what the spec could not state of it.
// `caller: 'build'` words the advice for an UPDATE that may have landed: the build keeps no base marker, and reads every page again when it runs.
- const fields = { name: p.name, source: deployedBytes, prompt: p.prompt, agentMessage: p.agentMessage, dataSources: p.dataSources || [], model: p.model };
+ const fields = { name: p.name, source: deployedBytes, prompt: p.prompt, agentMessage: p.agentMessage, dataSources: p.dataSources || [], model: p.model, ...statedPageBindings(p) };
// `publishedFingerprint` is what this workspace recorded about the page's last publish, handed over only while the page's files still read as they did right after it (`publishesStillStanding`):
// a page that already holds this very content, and was not touched from elsewhere since, is not published again.
- const up = requestedId ? await genpage.update(requestedId, { ...fields, caller: 'build', runtimeEvidence: true, publishedFingerprint: standingPublishes.get(String(requestedId).toLowerCase()), ...(opts.throttle ? { throttle: opts.throttle } : {}) }) : await createPage(p, fields);
+ const up = requestedId ? await genpage.update(requestedId, { ...fields, caller: 'build', runtimeEvidence: true, specBindings: true, publishedFingerprint: standingPublishes.get(String(requestedId).toLowerCase()), ...(opts.throttle ? { throttle: opts.throttle } : {}) }) : await createPage(p, fields);
if (!requestedId) recordCreate(p, up.pageId);
// An UPDATE (requestedId set) must return the SAME id, else a resolved sibling could point at
// a stale target. Case-insensitive (Dataverse may echo a differently-cased GUID).
@@ -6880,8 +7337,14 @@ async function runSdkBuildPhases(spec, opts, owed) {
// empty) and STRIP the app's form/view/chart component registrations (:635). A pure content re-upload
// leaves the key→pageId map unchanged, so the sitemap needs no rewrite — skip the finalize in that
// submode. Any sitemap-changing apply (and every full build) still finalizes.
+ // A NEW app whose navigation holds only page entries does not exist yet: the app step left its create to this step, so the step
+ // CREATES it, with the whole navigation — every page now has its id — in its first sitemap (createAppWithPages). There is no live
+ // sitemap to fence or rewrite and no header to compare: the create writes the spec's name, description and routing description
+ // itself, as the app step's create does. It is the app step's work, so it is reported, and fails, in that phase.
const skipSitemapFinalize = !!(opts.changedOnly && opts.changedOnly.skipSitemapFinalize);
- if (!skipSitemapFinalize && (appHasPageSubareas(spec) || appWasExisting)) {
+ if (createAppWithPages) {
+ await runner.run('app-shell', `app "${spec.app.name}" (created with its pages)`, () => createAppWithPages());
+ } else if (!skipSitemapFinalize && (appHasPageSubareas(spec) || appWasExisting)) {
await runner.run('pages', 'finalize sitemap (genpage subareas)', async () => {
await provision.fetchArtifact('app', result.created.app);
const mainFormsByTable = await resolvedMainForms();
@@ -7726,4 +8189,4 @@ async function runSdkBuildPhases(spec, opts, owed) {
return result;
}
-module.exports = { runSdkBuild, publishTargets, partialEnrichment, settleOwedPublishes, collectOwedPublishes, settleOwedLengths, normalizeFormId, planFor, annotateLivePlan, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, findPinnedDashboard, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, applyAppAiDescription, haltOnUnpublishedAppHeader, pushAppHeader, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, bpfDef, bpfFilter, webResourceOpts, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause, roleGrantLabel, resolveRoleGrantTarget, existingAppSitemapIsWritten, applyAppHeader, applyAppHeaderText, warnAppIconNotApplied, inspectBpfStages, applyBpfStages, refuseUnpushedAppCopy, assertAuthorizedSitemapRewrite, reconciledPublishHalt };
+module.exports = { runSdkBuild, publishTargets, partialEnrichment, settleOwedPublishes, collectOwedPublishes, settleOwedLengths, normalizeFormId, planFor, annotateLivePlan, resolvePhases, PHASES, BuildHalt, SDK_COLUMN_TYPE, viewDef, defaultViewColumns, subgridLabel, enrichesDefaultViews, dashboardsInSolution, findDashboardsByName, findPinnedDashboard, artifactIdentityQuery, resolveExistingFormId, FORM_TYPE_CODE, chartDef, dashboardTileOpts, dashboardComponent, compileFormIntent, formFieldLogicals, appDef, appUniqueName, applyAppAiDescription, haltOnUnpublishedAppHeader, pushAppHeader, commandsByEntity, commandDef, businessRuleDef, businessRuleFilter, bpfDef, bpfFilter, webResourceOpts, WEB_RESOURCE_KINDS, FORM_EVENTS, acquireAppPagesLease, personaRoleSpecFor, resolveRoleBusinessUnit, roleBuClause, roleGrantLabel, resolveRoleGrantTarget, existingAppSitemapIsWritten, pagesFirstRule, applyAppHeader, applyAppHeaderText, warnAppIconNotApplied, inspectBpfStages, applyBpfStages, refuseUnpushedAppCopy, assertAuthorizedSitemapRewrite, reconciledPublishHalt };
diff --git a/plugins/model-apps/scripts/lib/sdk-http-client.js b/plugins/model-apps/scripts/lib/sdk-http-client.js
index f7d57df3e..2d14267f5 100644
--- a/plugins/model-apps/scripts/lib/sdk-http-client.js
+++ b/plugins/model-apps/scripts/lib/sdk-http-client.js
@@ -29,7 +29,7 @@ const { needlesOf, noteToken, TOKEN_MARKER } = require('./output-redaction.js');
// as the next number, so a message that repeats the marker tens of thousands of times is read in linear time, not quadratic.
// The vendored SDK matches the marker anywhere in a 500's body for its own re-send (1 s / 2 s / 4 s) of reads, an app create,
// PublishXml, a form create, a view create and a publisher create — requests this client has already re-sent by
-// then, because it re-sends every 5xx that is not a record delete or a $batch (TRANSIENT, below). So a deadlock the
+// then (all but PublishXml, below), because it re-sends every 5xx that is not a record delete, a $batch or a publish (TRANSIENT, below). So a deadlock the
// client clears costs one re-send in all and the SDK's never fires; one that never clears is attempted up to the
// client's six times per SDK attempt (24 in all, measured on a form create and on a view create), a ceiling on a
// pathological case. A record DELETE and a conditional-delete $batch are the exception: this client re-sends their
@@ -40,6 +40,11 @@ const { needlesOf, noteToken, TOKEN_MARKER } = require('./output-redaction.js');
// one re-send in all and one that never clears at most 16 attempts (this client's four per SDK attempt). All of it
// is pinned against the real bundle in sdk-resend-layers.test.js.
//
+// A PUBLISH (`POST …/PublishXml`, or `PublishAllXml` should anything send it) is the other exception, the other way round: this client
+// sends it ONCE and leaves a deadlock victim to the one layer above it that re-sends one — the SDK's publishXml (its resendDeadlockVictim)
+// for a publish the SDK makes, and postPublishXml (lib/publish-xml.js) for the plugin's own — so no publish is sent again by two layers
+// at once. See `publishOnce` in `call` for what it is never sent again for, and why.
+//
// The one other `$batch` this client sends again is a change set that only CREATES columns (a new table's ordinary columns, see
// isColumnCreateBatch), and only after a 429: the platform refused to start it, so nothing in it committed (a change set is
// atomic) and it goes out again on the throttle schedule. After any other answer, a deadlock included, it is sent once, because a
@@ -48,6 +53,24 @@ const { needlesOf, noteToken, TOKEN_MARKER } = require('./output-redaction.js');
const SQL_DEADLOCK_VICTIM = /\bSql Number:\s*1205\b(?:(?!\bSql Number:\s*\d)[\s\S])*$/i;
// At most this many re-sends of a deadlock victim, 1 s / 2 s / 4 s apart — the SDK's own schedule.
const DEADLOCK_RESENDS = 3;
+
+// A publish, addressed by the action's name as the last segment of the path, bare or with its namespace — an unbound action of the Web API:
+// POST https://contoso.crm.dynamics.com/api/data/v9.2/PublishXml { "ParameterXml": "<importexportxml>…</importexportxml>" }
+// POST https://contoso.crm.dynamics.com/api/data/v9.2/Microsoft.Dynamics.CRM.PublishAllXml {}
+// A custom action whose name merely ends the same way (`new_PublishXml`) is another segment, and not a publish.
+// See https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/publishxml and …/reference/publishallxml
+const PUBLISH_ACTION = /\/(?:Microsoft\.Dynamics\.CRM\.)?Publish(?:All)?Xml$/i;
+const isPublishRequest = (method, url) => method === 'POST' && PUBLISH_ACTION.test(new URL(url).pathname);
+
+// The error codes of Dataverse's SERVICE PROTECTION limits — the only 429s the platform documents as a refusal to START a request,
+// which asks the caller to wait for `Retry-After` and send it again (https://learn.microsoft.com/power-apps/developer/data-platform/api-limits):
+// 0x80072322 Number of requests "Number of requests exceeded the limit of 6000 over time window of 300 seconds."
+// 0x80072321 Execution time "Combined execution time of incoming requests exceeded limit of 1,200,000 milliseconds over time window of 300 seconds. …"
+// 0x80072326 Concurrent requests "Number of concurrent requests exceeded the limit of 52."
+// Read from the `error.code` of the answer, never from its words. A 429 with any other code — the customization lock (`0x80071151`
+// "Cannot start the requested operation [Publish] because there is another [WorkflowSetState] running…", and the other lock codes
+// lib/retry-policy.js lists) — or with none is not one of these.
+const SERVICE_PROTECTION_CODES = Object.freeze(new Set(['0x80072322', '0x80072321', '0x80072326']));
// The longest `Retry-After` honoured in full. Dataverse's service protection limits answer 429 with
// `Retry-After` in seconds and ask the caller to wait that long; a request sent sooner is refused again
// and spends one of the few attempts. The cap keeps a large value from stalling a build or a teardown
@@ -104,6 +127,21 @@ function isSqlDeadlockVictim(res) {
return SQL_DEADLOCK_VICTIM.test(typeof res.body === 'string' ? res.body : JSON.stringify(res.body));
}
+/**
+ * True when a raw transport response is a refusal by the service protection limits: HTTP 429 whose OData error code — the answer is
+ * `{"error":{"code":"0x80072322","message":"Number of requests exceeded the limit of 6000 over time window of 300 seconds."}}` — is one of
+ * SERVICE_PROTECTION_CODES. A body that is not that JSON (an HTML page from a gateway, a code that is not a string) is not one.
+ */
+function isServiceProtectionRefusal(res) {
+ if (!res || res.statusCode !== 429) return false;
+ let body = res.body;
+ if (typeof body === 'string') {
+ try { body = JSON.parse(body); } catch { return false; }
+ }
+ const code = body && typeof body === 'object' && body.error && typeof body.error === 'object' ? body.error.code : undefined;
+ return typeof code === 'string' && SERVICE_PROTECTION_CODES.has(code.toLowerCase());
+}
+
/**
* The operations a `$batch` REQUEST carries, as `{ method, url, ifMatch }` in the order sent, read from the request lines
* (`<METHOD> <url> HTTP/1.1`) the SDK renders — see isConditionalDeleteBatch and isColumnCreateBatch for the shapes. `ifMatch` is the
@@ -602,7 +640,7 @@ function createAzHttpClient(orgUrl, deps = {}) {
const random = deps.random || Math.random;
const now = deps.now || Date.now;
// Transient HTTP statuses worth retrying with backoff — throttling, gateway hiccups, and
- // SQL deadlocks (Dataverse surfaces deadlock 1205 as a 500 from PublishXml under load).
+ // SQL deadlocks (Dataverse surfaces deadlock 1205 as a 500 under load). A publish is the exception (`publishOnce`, in `call`).
//
// ⚠ 502/503/504 come from an INTERMEDIARY, so the write behind them may have COMMITTED — and this
// retry then re-sends it. For a CONDITIONAL write (every SDK form, view, chart, dashboard and app
@@ -617,8 +655,12 @@ function createAzHttpClient(orgUrl, deps = {}) {
// policy stays.
// It is NOT safe for a write whose failure path must know whether the first attempt landed: the
// SDK's business-process-flow `update`/`delete` settle an ambiguous deactivate by re-reading the
- // row, and this retry pre-empts that. Nothing in this plugin issues those today; exempt such
- // writes from the retry before anything does.
+ // row, and this retry pre-empts that. The plugin reaches neither cycle: its stage edits of a flow it
+ // reuses (applyBpfStages, lib/sdk-build.js) are the SDK's in-place writes — an Active flow's ONE
+ // `$batch` change set of PATCHes on `/workflows(<id>)` under `If-Match`, which this client sends once
+ // (a `$batch`, below) and the SDK re-sends itself while the customization lock refuses it, bound by
+ // the same `If-Match`; a Draft flow's one PATCH under `If-Match` — and teardown deactivates and deletes a
+ // flow's row through the record surface (lib/sdk-teardown.js). Exempt such writes from the retry before anything issues them.
const TRANSIENT = new Set([429, 500, 502, 503, 504]);
// How long to wait for an answer before giving up. A WRITE gets far longer than a read, because a
// write we stop waiting for is not a failed write — the server may still be executing it, so its
@@ -739,6 +781,20 @@ function createAzHttpClient(orgUrl, deps = {}) {
// the caller's to look up. The exceptions of a record DELETE and a `$batch` stay what they were for every request the caller does not name.
const once = sendOnce(method_, url) === true;
const noRetry = recordDelete || isBatch || once;
+ // A PUBLISH (`POST …/PublishXml`, `…/PublishAllXml`) is sent ONCE on a 5xx, on a transport failure and on a 429 — but for the two answers that prove
+ // the platform never started it: a 401 (refused before it ran: the token is refreshed and the publish sent again, as any request is) and a 429 of the
+ // service protection limits (isServiceProtectionRefusal: waited out like any throttled request, inside the run's budget when the client has one).
+ // MEASURED on a test environment (four probe runs, 2026-10-20, the customization lock held by six concurrent business-process-flow activations): a
+ // publish the lock refused — HTTP 429 `0x80071151` "Cannot start the requested operation [Publish] because there is another [WorkflowSetState] running…",
+ // answered after 33-66 s — is NOT shown to change nothing. Of 7 web-resource writes whose publish it refused at least once, a later ACCEPTED publish
+ // published the OLD content in 4; an accepted re-send answered 204 while publishing the old content; and an app was seen published right after its
+ // publish was refused. So a re-send turns a loud refusal into a quiet stale publish — which the SDK reads back for a web resource (WEB_RESOURCE_UNVERIFIED)
+ // and for an app, form, view or dashboard nothing does — and it is the SDK's rule that a publish is never re-sent but as a SQL deadlock victim, which
+ // this client's re-send underneath it defeated. A deadlock victim (rolled back) is re-sent by the layer above: see SQL_DEADLOCK_VICTIM. A 5xx from a
+ // gateway (502, 503, 504) may sit in front of a publish that ran, and a transport failure in front of one that is still running: neither is re-sent.
+ // In 15 live builds, no-op rebuilds and teardowns of the release before this one, the plugin sent 30 publishes and none was answered 429 or 5xx: this
+ // bites only under real contention.
+ const publishOnce = !once && isPublishRequest(method_, url);
const isWrite = method_ !== 'GET';
// A CONDITIONAL write that got NO answer (a timeout or a dropped connection) is never re-sent.
// It may still commit — and if it does, the re-send carries a token the first attempt already
@@ -808,7 +864,7 @@ function createAzHttpClient(orgUrl, deps = {}) {
if (res.incompleteResponse && method_ === 'POST') {
throw transportError(res, `Request failed: ${scrubText(res.error)} — the server had already answered ${res.statusCode}, so this POST may have been applied; it was not re-sent. Re-run to reconcile.`);
}
- if (last || noRetry || !isTransientTransportFailure(res.error, res.code)) throw transportError(res, `Request failed: ${scrubText(res.error)}`);
+ if (last || noRetry || publishOnce || !isTransientTransportFailure(res.error, res.code)) throw transportError(res, `Request failed: ${scrubText(res.error)}`);
await sleep(backoffMs(attempt));
continue;
}
@@ -822,7 +878,7 @@ function createAzHttpClient(orgUrl, deps = {}) {
}
continue;
}
- if (TRANSIENT.has(res.statusCode) && !last && !noRetry) {
+ if (TRANSIENT.has(res.statusCode) && !last && !noRetry && (!publishOnce || isServiceProtectionRefusal(res))) {
// A throttle (HTTP 429) is waited out inside the run's budget when the client has one, and handed back as it came when the wait does not fit (waitOutThrottle). What else is re-sent here — a customization lock or a deadlock
// victim (500), a gateway (502, 503, 504) — is not throttling, and keeps its own schedule.
if (throttle && res.statusCode === 429) {
@@ -908,4 +964,4 @@ function createAzHttpClient(orgUrl, deps = {}) {
};
}
-module.exports = { createAzHttpClient, SQL_DEADLOCK_VICTIM, isBatchDeadlockVictim, isBatchThrottled, completeBatchStatus, batchRetryAfterMs, isConditionalDeleteBatch, isColumnCreateBatch, isTransientTransportFailure, TRANSIENT_TRANSPORT_CODES, retryAfterMs, throttleBackoffMs, RETRY_AFTER_CAP_MS, scrub, scrubAnswer, scrubBearer, MIN_SCRUBBED_TOKEN_LENGTH };
+module.exports = { createAzHttpClient, SQL_DEADLOCK_VICTIM, DEADLOCK_RESENDS, isSqlDeadlockVictim, isBatchDeadlockVictim, isBatchThrottled, completeBatchStatus, batchRetryAfterMs, isConditionalDeleteBatch, isColumnCreateBatch, isTransientTransportFailure, TRANSIENT_TRANSPORT_CODES, SERVICE_PROTECTION_CODES, isServiceProtectionRefusal, retryAfterMs, throttleBackoffMs, RETRY_AFTER_CAP_MS, scrub, scrubAnswer, scrubBearer, MIN_SCRUBBED_TOKEN_LENGTH };
diff --git a/plugins/model-apps/scripts/lib/sdk-teardown.js b/plugins/model-apps/scripts/lib/sdk-teardown.js
index 91517d420..8cc39c8ee 100644
--- a/plugins/model-apps/scripts/lib/sdk-teardown.js
+++ b/plugins/model-apps/scripts/lib/sdk-teardown.js
@@ -74,6 +74,7 @@ const { unreadableAnswer } = require('./collection-answers.js');
const { fetchSitemap, navigationProof } = require('./sitemap-pages.js');
const { unescapePacName } = require('./genpage-sdk.js');
const { readPageOwnership, readPendingCreations, recordPageTeardown, completePageDeletions, completePendingCreations } = require('./page-ownership-records.js');
+const { danglingSitemapOf, deleteAppWithoutSitemap } = require('./app-sitemap-dangling.js');
// OData v4 string-literal escaping lives in ./odata.js. `odataStr` is kept as a backward-compatible
// alias because it is part of this module's exported (and unit-tested) surface.
@@ -87,12 +88,17 @@ function errMsg(err) {
return String(err);
}
+// The HTTP status of the answer an SDK error carries (its ConnectionError keeps it as `statusCode`), or 0 when the error is no
+// answer of the platform's — an SDK check that failed before any request was sent, such as a lookup that found nothing.
+function httpStatus(err) {
+ return (err && (err.statusCode || err.status || (err.cause && (err.cause.statusCode || err.cause.status)))) || 0;
+}
+
// Detect if an SDK error is a "not found" (404-like) — used to treat already-gone artifacts
// as skips rather than failures. The SDK throws typed errors with status codes.
function isNotFound(err) {
if (!err) return false;
- const status = err.statusCode || err.status || (err.cause && (err.cause.statusCode || err.cause.status));
- if (status === 404) return true;
+ if (httpStatus(err) === 404) return true;
const msg = String((err && err.message) || '').toLowerCase();
// "...but 0 were found" is Dataverse's signal that the record targeted for delete (e.g. a
// RelationshipDefinitions metadata id that no longer resolves — already cascaded away) does not
@@ -123,6 +129,18 @@ function isUndeletable(err) {
return /system-defined|system managed|system-managed/.test(msg);
}
+// Marks an error FAIL-CLOSED: what the step could not prove is itself the failure, so deleteStep passes it on before any of its shortcuts. Those read
+// an error's WORDS and status — "not found", "referenced by", "system-managed", a 404 — and the words of such an error can be a maker's (an app named
+// "System Managed Ops") or a proxy's ("Resource not found for the segment …"): read as a shortcut, it turned the refusal of a live app into an
+// undeletable skip or a confirmed delete, and the steps that depend on the app ran. The resolve step honours the same marker.
+function failClosed(err) {
+ if (err && typeof err === 'object') {
+ err.failClosed = true;
+ return err;
+ }
+ return Object.assign(new Error(String(err)), { failClosed: true });
+}
+
// Solution component type codes used when reporting what still references a relationship.
// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/dependency
const DEPENDENT_COMPONENT_LABELS = { 1: 'table', 2: 'column', 10: 'relationship', 26: 'view', 59: 'chart', 60: 'form' };
@@ -281,6 +299,8 @@ async function restoreStockMainForm(sdk, entityLogical, formIdToDelete) {
// never built). `del` deletes one. A not-found error on delete is tolerated as "already gone"
// (e.g. a flyout appaction cascade removes its child buttons) — except for tables, whose
// deleteTable throws a not-found error even on success, so we use isNotFound to treat it as gone.
+// Whether such a tolerated not-found is reported as a deletion or as "not found" is the handler's
+// `absentOnNotFound(err, item)` (see deleteStep): only a kind that knows nothing was there says so.
const KIND_HANDLERS = {
app: {
async resolve(sdk, target) {
@@ -314,11 +334,27 @@ const KIND_HANDLERS = {
// delete. Surface any GENUINE failure so the run reports ok=false with the exact leftovers. A
// not-found failure means the row already cascaded away (not a leftover), so it is tolerated —
// the same best-effort spirit as the step-level isNotFound handling in deleteStep.
- async del(sdk, item) {
+ async del(sdk, item, ctx) {
let result;
try {
result = await sdk.deleteAppCascade(item.id, item.appModuleIdUnique);
} catch (err) {
+ // The one refusal a run again can never get past: the app's SiteMap component names a sitemap that is gone (a teardown, before 2.18.0, of another
+ // app that shared it can leave an app so). The app is deleted on its own only once lib/app-sitemap-dangling.js has proven that sitemap gone with
+ // reads of its own; otherwise it refuses, finally and without asking for a retry. Whatever it throws is fail-closed, so deleteStep can never read
+ // it as a row that is already gone or an artifact that cannot be deleted. Its note — the app went without its sitemap — is a warning, said once.
+ const dangling = danglingSitemapOf(err, item.id);
+ if (dangling) {
+ let outcome;
+ try {
+ outcome = await deleteAppWithoutSitemap(sdk.dataverse, { appId: item.id, appName: item.name, sitemapId: dangling.sitemapId, refused: err });
+ } catch (refusedHere) {
+ throw failClosed(refusedHere);
+ }
+ if (ctx && Array.isArray(ctx.warnings)) ctx.warnings.push(outcome.warning);
+ if (ctx && typeof ctx.warn === 'function') ctx.warn(outcome.warning);
+ return;
+ }
// A rejection does not mean the app survived. The SDK's deleteAppCascade runs the remote
// cascade and THEN tidies its local workspace copy (`workspace.readArtifact`/`deleteArtifact`),
// so a failure in that local step arrives after the app is already gone — and reading it as
@@ -1006,6 +1042,13 @@ const KIND_HANDLERS = {
}
},
tolerateNotFound: true, // a relationship already removed (e.g. by a prior table delete) is "gone"
+ // The SDK's deleteRelationship looks the relationship up by schema name before it deletes anything:
+ // GET /RelationshipDefinitions?$filter=SchemaName eq '<schema>'&$select=MetadataId
+ // and, finding none, throws its InvalidArgumentError "relationship '<schema>' not found" — no HTTP status, because no delete was
+ // sent. That is the one not-found that says nothing was there: a re-run, or a relationship to itself its table's delete took with
+ // it. A not-found that IS an answer to the delete (a 404, or the 400 "…but 0 were found") came after the lookup found the
+ // relationship, so it stays the deletion it always was.
+ absentOnNotFound: (err) => !httpStatus(err),
},
// Gap 6: the build adds parent lookups to the built-in Active/Inactive default views, which can't be
// deleted — a lookup column on them references the relationship and blocks its delete. Before the
@@ -1015,21 +1058,35 @@ const KIND_HANDLERS = {
async resolve(sdk, target) {
return [{ id: target.entityLogical, cols: target.cols }];
},
+ // Answers `{ noView: true }` when the SDK found no default view of the table to reset — a table that is gone, as on a teardown run
+ // again — which `foundNothing` turns into a "not found" step. It can tell only on the deferred path, which the bundled SDK takes:
+ // `enrichDefaultViews(…, { publish: false })` answers `results`, one per view it found, e.g.
+ // { updated: [], results: [], pendingPublish: [] } (no default view)
+ // { updated: ['<viewid>'], results: [{ saved: true, … }], pendingPublish: [ … ] } (a view reset)
+ // or throws before it has found any (no partial record attached — see partialEnrichment) when its read of the table's views is
+ // answered not-found. The other path answers only `{ updated }`, which cannot tell "no view" from "nothing to change", so it reads
+ // as it always did.
async del(sdk, item, ctx) {
if (typeof sdk.enrichDefaultViews === 'function') {
if (!ctx || !ctx.deferPublish) {
try { await sdk.enrichDefaultViews(item.id, item.cols); } catch { /* best-effort — a reset that fails just leaves the surfacing lookup, which the delete will then report */ }
- return;
+ return undefined;
}
try {
- recordDeferredResetPublish(ctx, item.id, await sdk.enrichDefaultViews(item.id, item.cols, { publish: false }));
+ const outcome = await sdk.enrichDefaultViews(item.id, item.cols, { publish: false });
+ recordDeferredResetPublish(ctx, item.id, outcome);
+ return { noView: Boolean(outcome) && Array.isArray(outcome.results) && outcome.results.length === 0 && !(outcome.updated || []).length };
} catch (err) {
- recordDeferredResetPublish(ctx, item.id, partialEnrichment(err));
+ const partial = partialEnrichment(err);
+ recordDeferredResetPublish(ctx, item.id, partial);
// Best-effort exactly as before: a reset failure is swallowed, because the relationship
// delete that follows is what reports the actionable leftover.
+ return { noView: isNotFound(err) && !partial };
}
}
+ return undefined;
},
+ foundNothing: (outcome) => Boolean(outcome) && outcome.noView === true,
},
webResource: {
async resolve(sdk, target) {
@@ -1089,9 +1146,15 @@ const KIND_HANDLERS = {
return { items: [], skipReason: 'reused table (existing: true) — not created by this build' };
}
let table = null;
+ // Whether the read said if the table was there before its delete: `true` it listed it, `false` it answered and listed no such
+ // table, `undefined` it could not tell — it failed, or its matches were cut at `top` (findTables reads every table and keeps the
+ // first 50 whose names contain the query, so a list of 50 may have left the table out).
+ let seen;
try {
const hits = await sdk.findTables(target.logical, { top: 50 });
table = (hits || []).find((t) => String(t.logicalName).toLowerCase() === target.logical) || null;
+ if (table) seen = true;
+ else if ((hits || []).length < 50) seen = false;
} catch (err) {
const unreadable = unreadableAnswer(err);
if (unreadable) {
@@ -1102,11 +1165,16 @@ const KIND_HANDLERS = {
if (table && table.isCustom === false) {
return { items: [], skipReason: 'system table — not created by this build' };
}
- return [{ id: target.logical, logical: target.logical }];
+ return [{ id: target.logical, logical: target.logical, ...(seen === undefined ? {} : { seen }) }];
},
del: (sdk, item) => sdk.deleteTable(item.logical),
// deleteTable throws a not-found error even on success; treat any not-found as gone.
tolerateNotFound: true,
+ // ...and which of the two it is, the step's own read says. The delete is sent whatever the read found (a table it cannot see is
+ // still asked for by name), and it is a METADATA delete, which the client sends again after a timeout or a gateway error
+ // (sdk-http-client.js): once the first send did the work, the next one is answered 404. So a not-found is "not found" only when the
+ // read had listed no such table; after a read that saw the table, or could not tell, it is the deletion it always was.
+ absentOnNotFound: (err, item) => item.seen === false,
},
globalChoice: {
// Deleted by name (the SDK has no id lister); a synthetic item drives deleteStep, mirroring
@@ -1119,6 +1187,12 @@ const KIND_HANDLERS = {
},
del: (sdk, item) => sdk.deleteGlobalOptionSet(item.name),
tolerateNotFound: true, // absent, or a shared choice already removed, is "gone"
+ // The delete, `DELETE /GlobalOptionSetDefinitions(Name='<name>')`, is the step's only request, so its not-found is the platform
+ // saying there is no choice of that name: "not found", as on a teardown run again. It can mislabel one case only: a delete the
+ // client sent again (a metadata delete is re-sent after a timeout or a gateway error) whose first send had already removed the
+ // choice. That reads "not found" for a choice this run deleted — the step succeeds either way, and telling the two apart would
+ // take a read this step does not make.
+ absentOnNotFound: () => true,
},
aiSummary: {
// AI row-summary records reference the table and would block its delete; remove them first.
@@ -1507,10 +1581,12 @@ function planTeardown(spec) {
// Reporting both as "undeletable" would send an operator hunting a platform problem that isn't
// there. `skippedIds` is retained as the union of both for callers that only need the count.
// A third reason, `failed` (with a `detail`), is a removal the handler tolerates (`tolerateFailure`).
-// A not-found error counts as already-gone. Throws only on a genuine failure.
+// A not-found error counts as already-gone. Throws only on a genuine failure — and on any error marked `failClosed`, before reading it at all.
//
// A removal that looks for its artifact itself answers whether there was one: the handler's `foundNothing(outcome)` says so (aiSummary: the SDK's `{ removed: false }`), and that id is
// answered in `absentIds`. It is neither deleted nor skipped — nothing was there — and runTeardown reports it as a step that found nothing, like one whose resolver finds none.
+// So is a tolerated not-found the handler's `absentOnNotFound(err, item)` reads as "nothing was there" (a relationship the SDK's lookup did not find, a table its read did not list,
+// a global choice): a teardown run again used to report each of those `(1 deleted)`.
async function deleteStep(sdk, handler, items, ctx) {
const deletedIds = [];
const absentIds = [];
@@ -1521,9 +1597,16 @@ async function deleteStep(sdk, handler, items, ctx) {
if (typeof handler.foundNothing === 'function' && handler.foundNothing(outcome)) absentIds.push(item.id);
else deletedIds.push(item.id);
} catch (err) {
+ // A fail-closed error (failClosed, above) is passed on before every shortcut below: it says what could not be proven, and its words — a
+ // maker's names, a proxy's "not found" — are not a verdict of the platform's on this row. For the app step, passing it on is what stops the
+ // teardown before the steps that depend on the app (runTeardown).
+ if (err && err.failClosed === true) throw err;
if (handler.tolerateNotFound && isNotFound(err)) {
- // Table delete throws not-found even on success; treat as deleted
- deletedIds.push(item.id);
+ // Table delete throws not-found even on success; treat as deleted — unless the handler can
+ // tell that nothing was there when the step began (`absentOnNotFound`): then it is a step
+ // that found nothing, reported "not found" and not counted as a deletion. Still a success.
+ if (typeof handler.absentOnNotFound === 'function' && handler.absentOnNotFound(err, item)) absentIds.push(item.id);
+ else deletedIds.push(item.id);
continue;
}
if (isNotFound(err)) {
@@ -1780,7 +1863,7 @@ async function runTeardownSteps(spec, opts, deps, deferredResetPublishes) {
emit({ phase: step.phase, status: 'skip', skip: 'kept', label: why, n: myN, total });
continue;
}
- const { deletedIds, absentIds, skipped } = await deleteStep(sdk, handler, items, step.kind === 'resetDefaultViews' || step.kind === 'genpage' ? deferredResetPublishes : undefined);
+ const { deletedIds, absentIds, skipped } = await deleteStep(sdk, handler, items, step.kind === 'resetDefaultViews' || step.kind === 'genpage' || step.kind === 'app' ? deferredResetPublishes : undefined);
// A removal that looked for its artifact itself and found none is a step that found nothing — the line and the counts a resolver that finds none gets — and not a deletion.
if (!deletedIds.length && !skipped.length && absentIds.length) {
result.skipped.push(step.label);
diff --git a/plugins/model-apps/scripts/lib/spec-lint.js b/plugins/model-apps/scripts/lib/spec-lint.js
index 44e0bccd3..12a057bba 100644
--- a/plugins/model-apps/scripts/lib/spec-lint.js
+++ b/plugins/model-apps/scripts/lib/spec-lint.js
@@ -442,9 +442,12 @@ function lintAppSpec(spec) {
// A navigation a NEW app cannot be built from. validateAppSpec accepts it (data-only specs have no navigation, and a downloaded spec carries
// the app's own, which can be empty), but a build that includes the app step refuses it for a new app before it writes anything. Whether the
// app exists is not known here, so this is a warning, and it says who is spared by asking the same rule again for an app that exists.
- const navigation = navigationVerdict(spec, { appExists: false });
+ // It speaks of the build `--apply` runs — the whole build, which creates a new app's pages before the app (sdk-build.js pagesFirstRule) — so a
+ // navigation of pages only is one a new app is built from, and is not warned about; whether each page is implemented yet is validation's to say
+ // (the deploy profile), since a spec being authored may still hold intent pages.
+ const navigation = navigationVerdict(spec, { appExists: false, newAppPagesFirst: true });
if (navigation.outcome === 'refuse') {
- const forExisting = navigationVerdict(spec, { appExists: true }).outcome;
+ const forExisting = navigationVerdict(spec, { appExists: true, newAppPagesFirst: true }).outcome;
const spared = forExisting === 'ok' ? ' An app that already exists is not affected.'
: forExisting === 'warn' ? ' An app that already exists is built with no navigation entries, and the build says so.' : '';
W(`appShell: ${navigation.message}${spared}`);
@@ -561,11 +564,26 @@ function lintAppSpec(spec) {
// ai block — row-summary guardrails.
const D365_OWNED_SUMMARY_TABLES = new Set(['incident', 'lead', 'opportunity']);
const DESCRIPTIVE_TYPES = new Set(['Text', 'Memo', 'Choice', 'MultiChoice', 'DateTime', 'Money', 'Integer', 'Decimal', 'Double', 'Boolean']);
+ // The keys the build reads from a table's entry: `enabled` (ai-candidates.js), `instruction` — the table's row-summary prompt — and
+ // `columns` (ai-prompt.js buildPromptSpec). validateAppSpec rejects no other key, so a misnamed one validated, built green and did
+ // nothing; seen live: `prompt` for the prompt, under `default: "off"`, planned no summary at all. A warning, as the schema accepts it.
+ const SUMMARY_TABLE_KEYS = ['enabled', 'instruction', 'columns'];
if (spec.ai && spec.ai.summaries && spec.ai.summaries.tables && typeof spec.ai.summaries.tables === 'object') {
for (const [k, v] of Object.entries(spec.ai.summaries.tables)) {
if (D365_OWNED_SUMMARY_TABLES.has(lc(k))) {
W(`Summary table '${k}' is a Dynamics 365 app table (Case/Lead/Opportunity) — it provides its own summaries; the row-summary feature isn't available for it`);
}
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
+ for (const key of Object.keys(v)) {
+ if (SUMMARY_TABLE_KEYS.includes(key)) continue;
+ if (key === 'prompt') {
+ W(`ai.summaries.tables['${k}'].prompt is ignored — a table's row-summary prompt is its instruction: rename the key to ai.summaries.tables['${k}'].instruction (when a summary is enabled, omitting instruction uses the default prompt)`);
+ continue;
+ }
+ const near = nearestName(key, SUMMARY_TABLE_KEYS);
+ W(`ai.summaries.tables['${k}']: unknown key '${key}' is ignored${near ? ` — did you mean '${near}'?` : ''} (a table's entry reads only enabled, instruction and columns)`);
+ }
+ }
const ent = (spec.entities || []).find((e) => lc(e.schemaName) === lc(k));
if (ent) {
const descriptiveCols = (ent.columns || []).filter((c) => DESCRIPTIVE_TYPES.has(c.type));
diff --git a/plugins/model-apps/scripts/lib/spec-shape.js b/plugins/model-apps/scripts/lib/spec-shape.js
index ba8575947..261c1ee02 100644
--- a/plugins/model-apps/scripts/lib/spec-shape.js
+++ b/plugins/model-apps/scripts/lib/spec-shape.js
@@ -56,7 +56,8 @@ const COLLECTIONS = {
// stage-by-stage while a process is being designed, so a mid-edit object here is realistic.
businessProcessFlows: { children: { stages: { children: { steps: {} } } } },
dashboards: { children: { tiles: {} } },
- pages: { children: { navigatesTo: {}, dataSources: { scalar: true } } },
+ // A page's connector and Custom API bindings are lists of objects, carried onto its config.json as they are written.
+ pages: { children: { navigatesTo: {}, dataSources: { scalar: true }, connectorBindings: {}, actionBindings: {} } },
personas: { children: { jobs: { children: { privileges: {} } }, additionalPrivileges: {} } },
};
diff --git a/plugins/model-apps/scripts/lib/status-reasons-keys.js b/plugins/model-apps/scripts/lib/status-reasons-keys.js
new file mode 100644
index 000000000..0ad63dffe
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/status-reasons-keys.js
@@ -0,0 +1,128 @@
+'use strict';
+// A table's STATUS REASONS and ALTERNATE KEYS as the environment holds them, and how the ones a spec declares
+// (`entities[].statusReasons[]`, `entities[].alternateKeys[]`) compare with them — what verify checks (verify-spec.js, each declared one a
+// check of its own), with one read of each made only for a table that declares any.
+//
+// Both reads are narrow ones on the SDK's own client (`sdk.dataverse`), as lookup-labels.js and view-filter-labels.js read, and for their
+// reasons: the SDK's whole-table read (`fetchEntityMetadata`) costs about eleven requests, writes the table into the workspace, and
+// carries neither a status reason's state nor any key; and the SDK has no read of a table's keys at all (its key surface is create and
+// delete). Neither read throws: like readChoiceAttributes, each answers `{ state: 'ok', … }`, `{ state: 'absent' }` (the table answered
+// 404) or `{ state: 'error', why }`, so a read that failed is reported as one, never as "nothing there".
+
+const { odataLit } = require('./odata.js');
+const { labelText, labelAliases } = require('./app-spec.js');
+const { readMetadata } = require('./lookup-labels.js');
+const { optionCastUrl, parseOptions } = require('./view-filter-labels.js');
+const { statusReasonTargets } = require('./entity-provision.js');
+
+const lc = (s) => String(s == null ? '' : s).toLowerCase();
+
+// The two states a status reason of a table the App Spec builds can belong to (statecode 0 and 1). Another number — a system table's third
+// state — is named by its number.
+const STATE_NAME = { 0: 'Active', 1: 'Inactive' };
+const stateName = (state) => STATE_NAME[state] || `state ${state}`;
+
+// The status reasons of a table: the options of its Status attribute (`statuscode`), each with its value, the state it belongs to and its
+// label in every language. ONE read, the cast read the view filter's label resolution makes for the same column (optionCastUrl):
+// GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)
+// -> { "value": [ { "LogicalName": "statuscode", "MetadataId": "<guid>", "OptionSet": { "Options": [
+// { "Value": 1, "State": 0, "Label": { "LocalizedLabels": [ { "Label": "Active", "LanguageCode": 1033 } ], … } },
+// { "Value": 2, "State": 1, "Label": { … "Inactive" … } },
+// { "Value": 100000000, "State": 0, "Label": { … "In Review" … } } ] } } ] }
+// A table has one Status attribute, so the list holds one row. Answers { state: 'ok', options: [{ value, state, labels, shown }] }.
+// A metadata read answers the SAVED definition: measured live for a column's label, which a read returned right after its PUT, before any
+// publish (entity-provision.js, publishRelabelledTables). So a reason a build inserted without --publish is expected to be found here,
+// as the build's own views phase finds it to resolve a view filter's label; whether the app shows it yet is a publish's business.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/statusattributemetadata
+async function readStatusReasons(client, entityLogical, { languageCode } = {}) {
+ const got = await readMetadata(client, optionCastUrl(entityLogical, 'Status'));
+ if (got.state !== 'ok') return got;
+ if (!Array.isArray(got.body.value)) return { state: 'error', why: 'the answer carried no list of status columns' };
+ const row = got.body.value.find((r) => r && lc(r.LogicalName) === 'statuscode');
+ const options = row && row.OptionSet && Array.isArray(row.OptionSet.Options) ? row.OptionSet.Options : null;
+ if (!options) return { state: 'error', why: 'the answer carried no status reasons' };
+ return { state: 'ok', options: parseOptions(options, languageCode) };
+}
+
+// The alternate keys of a table, each with its name and its columns. ONE read:
+// GET /EntityDefinitions(LogicalName='contoso_project')/Keys?$select=LogicalName,SchemaName,KeyAttributes
+// -> { "value": [ { "LogicalName": "contoso_emailkey", "SchemaName": "contoso_emailkey", "KeyAttributes": [ "contoso_email" ], "MetadataId": "<guid>" } ] }
+// Live, a key read back answered its columns in an order of its own (a key made over a name and a code column answered code, name), so the
+// columns are compared as a set. Right after its create a key's index is still being built (`EntityKeyIndexStatus` "Pending", measured
+// live), which is why the index status is not read: a key of the declared name over the declared columns is the key the spec declares.
+// A row without its columns cannot be compared, so the whole answer is not used. Answers { state: 'ok', keys: [{ logicalName, schemaName, columns }] }.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/entitykeymetadata
+async function readAlternateKeys(client, entityLogical) {
+ const got = await readMetadata(client, `/EntityDefinitions(LogicalName='${odataLit(lc(entityLogical))}')/Keys?$select=LogicalName,SchemaName,KeyAttributes`);
+ if (got.state !== 'ok') return got;
+ if (!Array.isArray(got.body.value)) return { state: 'error', why: 'the answer carried no list of keys' };
+ const keys = [];
+ for (const row of got.body.value) {
+ const name = row && (row.LogicalName || row.SchemaName);
+ if (typeof name !== 'string' || !name) continue;
+ if (!Array.isArray(row.KeyAttributes)) return { state: 'error', why: `the key '${name}' was answered without its columns` };
+ keys.push({ logicalName: lc(name), schemaName: String(row.SchemaName || name), columns: row.KeyAttributes.map(lc) });
+ }
+ return { state: 'ok', keys };
+}
+
+// What a reader answered, made into one of the three answers above: a reader that throws, or answers nothing a check can use, is a read that
+// failed — reported on each check it was for, with the reason, and never the end of the verification pass.
+async function answerOf(read) {
+ try {
+ const answer = await read();
+ return answer && typeof answer === 'object' && typeof answer.state === 'string' ? answer : { state: 'error', why: 'no answer' };
+ } catch (err) {
+ return { state: 'error', why: (err && err.message) || String(err) };
+ }
+}
+const unreadable = (answer) => `could not be read: ${answer.state === 'absent' ? 'the environment answered that the table is not there' : answer.why || 'no answer'}`;
+
+// The checks of a table's declared status reasons against what readStatusReasons answered — one per reason, in the spec's order, each
+// named `<table>.<label>` (its label in the spec's language) and held to what the build gives it (statusReasonTargets, entity-provision.js):
+// present one of the table's status reasons carries the label, in any language it is written in, under that state — and at the value
+// the spec pins, when it pins one
+// different the label is there, under the other state or at another value than the pinned one: said, with both
+// missing no status reason carries the label. When the value the build gives it is another label's, that is said too: a rebuild inserts
+// the reason at that value again, which the platform refuses as already there, so a reason renamed in the environment stays so
+// An option's missing/non-integer state is not proof of the requested state: report it as unreadable rather than guessing a match.
+function statusReasonChecks(entity, answer, { languageCode } = {}) {
+ return statusReasonTargets(entity).map(({ statusReason, stateCode, value }) => {
+ const name = `${entity.schemaName}.${labelText(statusReason.label, languageCode)}`;
+ if (answer.state !== 'ok') return { name, present: false, detail: unreadable(answer) };
+ const aliases = labelAliases(statusReason.label);
+ const named = answer.options.filter((o) => o.labels.some((l) => aliases.includes(l)));
+ const pinned = typeof statusReason.value === 'number';
+ const atValue = (o) => !pinned || o.value === value;
+ const inState = (o) => Number.isInteger(o.state) && o.state === stateCode;
+ if (named.some((o) => atValue(o) && inState(o))) return { name, present: true, detail: '' };
+ if (named.some((o) => atValue(o) && !Number.isInteger(o.state))) return { name, present: false, detail: `its state could not be read; the spec declares it under ${stateName(stateCode)}` };
+ const otherState = named.find(atValue);
+ if (otherState) return { name, present: false, detail: `a status reason of the ${stateName(otherState.state)} state; the spec declares it under ${stateName(stateCode)}` };
+ if (named.length) return { name, present: false, detail: `its value is ${named[0].value}; the spec pins ${value}` };
+ const holder = answer.options.find((o) => o.value === value);
+ return { name, present: false, detail: holder ? `its value, ${value}, is the status reason '${holder.shown}' in the environment, and a build does not rename one` : '' };
+ });
+}
+
+// The checks of a table's declared alternate keys against what readAlternateKeys answered — one per key, in the spec's order, each named
+// `<table>.<schemaName>`:
+// present the table has a key of that name (the platform's logical name is the schema name in lower case) over exactly the declared
+// columns, in any order
+// different the key is there over other columns: said, with both
+// missing no key has the name — and when a key of another name is over exactly those columns, that is said too
+function alternateKeyChecks(entity, answer) {
+ const columnsOf = (list) => [...new Set((list || []).map(lc))].sort();
+ return ((entity && entity.alternateKeys) || []).map((key) => {
+ const name = `${entity.schemaName}.${key.schemaName}`;
+ if (answer.state !== 'ok') return { name, present: false, detail: unreadable(answer) };
+ const want = columnsOf(key.columns);
+ const same = (k) => columnsOf(k.columns).join('\n') === want.join('\n');
+ const found = answer.keys.find((k) => k.logicalName === lc(key.schemaName));
+ if (found) return same(found) ? { name, present: true, detail: '' } : { name, present: false, detail: `its columns are ${columnsOf(found.columns).join(', ')}; the spec declares ${want.join(', ')}` };
+ const twin = answer.keys.find(same);
+ return { name, present: false, detail: twin ? `a key over the same columns is there as '${twin.schemaName}'` : '' };
+ });
+}
+
+module.exports = { readStatusReasons, readAlternateKeys, answerOf, statusReasonChecks, alternateKeyChecks };
diff --git a/plugins/model-apps/scripts/lib/table-publish.js b/plugins/model-apps/scripts/lib/table-publish.js
index b16ea04ee..ad76b91b4 100644
--- a/plugins/model-apps/scripts/lib/table-publish.js
+++ b/plugins/model-apps/scripts/lib/table-publish.js
@@ -14,6 +14,7 @@
const { collectionRows, readAppComponentInventory, TABLE_NAME } = require('./app-components.js');
const { sitemapEntityTables } = require('./app-spec.js');
const { odataLit } = require('./odata.js');
+const { postPublishXml } = require('./publish-xml.js');
// Lower-case logical names, each once, in the order given; a name that cannot be a table's is left out. `add` and `list` of one collection.
function namesCollector() {
@@ -122,16 +123,15 @@ const xmlText = (value) => String(value).replace(/&/g, '&amp;').replace(/</g, '&
// naming a table publishes what anyone saved on it, not only what the build did.
//
// Reported by value, never thrown: the callers publish what a maker saved or what a label repair changed, none of which may stop a build. The
-// client answers `{ status, body }` and does not throw on an HTTP error (lib/sdk-http-client.js); a transport failure, after its own resends,
-// does throw. A refusal's platform text, when it gives one, is kept: `{ "error": { "code": "0x80040217", "message": "..." } }`.
-async function publishTablesXml(client, tables) {
+// client answers `{ status, body }` and does not throw on an HTTP error (lib/sdk-http-client.js); a transport failure does throw. The client
+// sends a publish once, so a refusal — the customization lock's 429 included — is reported as it came; a deadlock victim is sent again by
+// postPublishXml (lib/publish-xml.js). A refusal's platform text, when it gives one, is kept: `{ "error": { "code": "0x80040217", "message": "..." } }`.
+async function publishTablesXml(client, tables, { sleep } = {}) {
const names = Array.isArray(tables) ? tables : [];
if (!names.length) return { ok: true };
if (!client || typeof client.post !== 'function') return { ok: false, reason: 'no client to publish with' };
try {
- const response = await client.post('/PublishXml', {
- ParameterXml: `<importexportxml><entities>${names.map((t) => `<entity>${xmlText(t)}</entity>`).join('')}</entities></importexportxml>`,
- });
+ const response = await postPublishXml(client, `<importexportxml><entities>${names.map((t) => `<entity>${xmlText(t)}</entity>`).join('')}</entities></importexportxml>`, { sleep });
if (response && response.status >= 200 && response.status < 300) return { ok: true };
const said = response && response.body && response.body.error && response.body.error.message;
return { ok: false, reason: `PublishXml answered HTTP ${response && response.status}${typeof said === 'string' && said ? `: ${said}` : ''}` };
diff --git a/plugins/model-apps/scripts/lib/table-schema-metadata.js b/plugins/model-apps/scripts/lib/table-schema-metadata.js
new file mode 100644
index 000000000..3e6c99628
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/table-schema-metadata.js
@@ -0,0 +1,91 @@
+'use strict';
+
+const { odataLit } = require('./odata.js');
+const { compareText } = require('./compare-text.js');
+const { labelsByLcid } = require('./lookup-labels.js');
+
+// StatusOptionMetadata carries the State as well as Value, Label and Color. The SDK's choices
+// projection drops State, so it cannot tell an inactive reason from an active one.
+// .../StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)
+// -> { "value": [{ "LogicalName": "statuscode", "OptionSet": { "Options": [
+// { "Value": 100000042, "State": 1, "Label": { "LocalizedLabels": [...] }, "Color": "#336699" }
+// ] } }] }
+// A failed/incomplete answer is unknown, never proof of an empty list.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/statusoptionmetadata
+async function readStatusOptions(client, logical) {
+ try {
+ if (!client || typeof client.get !== 'function') return { failed: 'no metadata client' };
+ const res = await client.get(`/EntityDefinitions(LogicalName='${odataLit(logical)}')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)`);
+ if (!res || res.status < 200 || res.status >= 300) throw new Error(`HTTP ${res && res.status}`);
+ const rows = res.body && res.body.value;
+ const status = Array.isArray(rows) && rows.find((a) => a && String(a.LogicalName).toLowerCase() === 'statuscode');
+ if (!status || !status.OptionSet || !Array.isArray(status.OptionSet.Options)) throw new Error('the response carried no statuscode options');
+ return { options: status.OptionSet.Options };
+ } catch (err) {
+ return { failed: (err && err.message) ? String(err.message).slice(0, 200) : 'read failed' };
+ }
+}
+
+function statusReasonsFromOptions(options, { customTable = true, languageCode, omitted = [] } = {}) {
+ const usable = [];
+ for (const option of options || []) {
+ if (!option || option.IsManaged === true || option.Value === 1 || option.Value === 2) continue;
+ // Stock tables have other built-in reasons; only the publisher range identifies an addition.
+ if (!customTable && option.Value < 100000000) continue;
+ if (!Number.isInteger(option.Value) || ![0, 1].includes(option.State)) {
+ omitted.push(`status reason ${option.Value}: its value, Active/Inactive state or label cannot be expressed`);
+ continue;
+ }
+ // A string status label is rebuilt in the resolved authoring LCID, not the caller's UI
+ // language. Another LCID (even UserLocalizedLabel) cannot prove that label round-trips.
+ const label = labelsByLcid(option.Label)[languageCode];
+ if (!label) {
+ omitted.push(`status reason ${option.Value}: its label in authoring language ${languageCode || '(unresolved)'} could not be read`);
+ continue;
+ }
+ usable.push({ option, label });
+ }
+ usable.sort((a, b) => a.option.Value - b.option.Value);
+ return usable.map(({ option, label }, index) => ({
+ label, state: option.State === 0 ? 'Active' : 'Inactive',
+ // The build assigns this range by index. Keep any other number explicitly so a download
+ // never reassigns rows to another reason when reasons were inserted or reordered in Maker.
+ ...(option.Value !== 100000000 + index ? { value: option.Value } : {}),
+ ...(typeof option.Color === 'string' && option.Color.trim() ? { color: option.Color } : {}),
+ }));
+}
+
+function alternateKeysFromMetadata(keys, labelOf, omitted = []) {
+ const out = [];
+ // A malformed optional expansion (e.g. Keys: {}) is already diagnosed by the reader.
+ // It says nothing about the table's independently recovered primary name or typed columns.
+ for (const key of Array.isArray(keys) ? keys : []) {
+ if (!key || key.IsManaged === true) continue;
+ if (typeof key.SchemaName !== 'string' || !key.SchemaName.trim()
+ || !Array.isArray(key.KeyAttributes) || !key.KeyAttributes.length
+ || key.KeyAttributes.some((name) => typeof name !== 'string' || !name.trim())) {
+ omitted.push(`alternate key ${key && key.SchemaName || '(unnamed)'}: its name or columns could not be read`);
+ continue;
+ }
+ const displayName = labelOf(key.DisplayName);
+ out.push({
+ schemaName: key.SchemaName,
+ ...(displayName !== undefined ? { displayName } : {}),
+ columns: [...key.KeyAttributes],
+ });
+ }
+ return out.sort((a, b) => compareText(a.schemaName, b.schemaName));
+}
+
+function alternateKeyMatches(keys, key) {
+ const names = (values) => Array.isArray(values) && values.every((v) => typeof v === 'string' && v)
+ ? values.map((v) => v.toLowerCase()).sort(compareText) : null;
+ const wanted = names(key.columns);
+ return !!wanted && wanted.length > 0 && Array.isArray(keys) && keys.some((candidate) => {
+ if (!candidate || String(candidate.SchemaName).toLowerCase() !== String(key.schemaName).toLowerCase()) return false;
+ const found = names(candidate.KeyAttributes);
+ return found && found.length === wanted.length && found.every((v, i) => v === wanted[i]);
+ });
+}
+
+module.exports = { readStatusOptions, statusReasonsFromOptions, alternateKeysFromMetadata, alternateKeyMatches };
diff --git a/plugins/model-apps/scripts/lib/verify-spec.js b/plugins/model-apps/scripts/lib/verify-spec.js
index 6a9931825..73812e271 100644
--- a/plugins/model-apps/scripts/lib/verify-spec.js
+++ b/plugins/model-apps/scripts/lib/verify-spec.js
@@ -34,6 +34,7 @@ const { placementOf, resolvePlacement, columnSequence, neighbourOf, tokenLabel,
const { isMainForm, selectDefaultForm, plannedMainFormSequence, displayConditionsOrder, compareServedOrder } = require('./form-order.js');
const { hasLabelUses, resolveViewFilterLabels, memoizeChoiceReader, describeProblem } = require('./view-filter-labels.js');
const { hostsCustomControl } = require('./dashboard-tiles.js');
+const { answerOf, statusReasonChecks, alternateKeyChecks } = require('./status-reasons-keys.js');
// How many verification reads may be in flight at once. A verify pass is nothing but reads, but each is a
// Dataverse request that already retries on its own 429s (lib/sdk-http-client.js), so the bound is small:
@@ -249,6 +250,18 @@ async function verifySpec(spec, read, opts = {}) {
deployed === c.visualization ? '' : `expected '${c.visualization}', deployed '${deployed}'`);
}
}
+ // Status reasons and alternate keys, each declared one by its name (lib/status-reasons-keys.js): what the build gives a reason (its
+ // state, and the value the spec pins) and a key (its columns) is what is held to. Reader-gated like the rest, and read once for the
+ // table, only for a table that declares any — a spec that declares neither sends no request for them. A read that fails is reported on
+ // each check it was for, with the reason, and the pass goes on.
+ if (Array.isArray(e.statusReasons) && e.statusReasons.length && typeof read.statusReasons === 'function') {
+ const answer = await answerOf(() => read.statusReasons(logical));
+ for (const c of statusReasonChecks(e, answer, { languageCode: spec.languageCode })) add('status-reason', c.name, c.present, c.detail);
+ }
+ if (Array.isArray(e.alternateKeys) && e.alternateKeys.length && typeof read.alternateKeys === 'function') {
+ const answer = await answerOf(() => read.alternateKeys(logical));
+ for (const c of alternateKeyChecks(e, answer)) add('alternate-key', c.name, c.present, c.detail);
+ }
}
}
});
diff --git a/plugins/model-apps/scripts/lib/view-filter-labels.js b/plugins/model-apps/scripts/lib/view-filter-labels.js
index 5bb19bad7..f3f9e191f 100644
--- a/plugins/model-apps/scripts/lib/view-filter-labels.js
+++ b/plugins/model-apps/scripts/lib/view-filter-labels.js
@@ -125,6 +125,9 @@ const hasLabelUses = (spec, view) => labelUses(spec, view).length > 0;
// read: it is populated for a LOCAL set too, and then carries only the set's name. `Label` is read by
// language code rather than through `UserLocalizedLabel`, which is only the calling user's language — a
// filter may name a label in any.
+// A status reason (an option of a table's Status attribute, `statuscode`) also carries the state it belongs to,
+// `"State": 0`, which is kept as `state`; no other kind of option has one, and its options are answered as before.
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/statusoptionmetadata
function parseOptions(rawOptions, languageCode) {
const options = [];
for (const raw of Array.isArray(rawOptions) ? rawOptions : []) {
@@ -133,7 +136,7 @@ function parseOptions(rawOptions, languageCode) {
const labels = Object.values(byLcid);
const user = raw.Label && raw.Label.UserLocalizedLabel && raw.Label.UserLocalizedLabel.Label;
if (typeof user === 'string' && user.trim() && !labels.includes(user)) labels.push(user);
- options.push({ value: Number(raw.Value), labels, shown: labelText(byLcid, languageCode) || labels[0] || String(raw.Value) });
+ options.push({ value: Number(raw.Value), labels, shown: labelText(byLcid, languageCode) || labels[0] || String(raw.Value), ...(Number.isInteger(raw.State) ? { state: raw.State } : {}) });
}
return options;
}
@@ -146,8 +149,13 @@ function parseOptions(rawOptions, languageCode) {
// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/reference/enumattributemetadata
const OPTION_CASTS = ['Picklist', 'MultiSelectPicklist', 'State', 'Status'];
+// The read of one kind of a table's choice attributes, with every option and every language of its labels:
+// /EntityDefinitions(LogicalName='new_customer')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)
+// Shared with the status reason read verify makes (lib/status-reasons-keys.js), so the two cannot ask differently.
+const optionCastUrl = (entityLogical, cast) => `/EntityDefinitions(LogicalName='${odataLit(lc(entityLogical))}')/Attributes/Microsoft.Dynamics.CRM.${cast}AttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)`;
+
// The choice attributes of one table, with every option and every language of its label:
-// { state: 'ok', attributes: Map(logicalName -> { kind, options: [{ value, labels, shown }] }), complete, why? }
+// { state: 'ok', attributes: Map(logicalName -> { kind, options: [{ value, labels, shown, state? }] }), complete, why? }
// { state: 'absent' } — the table is not in the environment (every cast answered 404)
// { state: 'error', why } — nothing could be read
// `complete` is false when a cast failed: what the others returned is usable, but an attribute missing from
@@ -162,10 +170,9 @@ const OPTION_CASTS = ['Picklist', 'MultiSelectPicklist', 'State', 'Status'];
// "nothing there". Remove this when the SDK offers a read of a column's options that neither writes the
// workspace nor drops languages.
async function readChoiceAttributes(client, entityLogical, { languageCode } = {}) {
- const base = `/EntityDefinitions(LogicalName='${odataLit(lc(entityLogical))}')/Attributes/Microsoft.Dynamics.CRM.`;
const reads = await Promise.all(OPTION_CASTS.map(async (cast) => {
try {
- const res = await client.get(`${base}${cast}AttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)`);
+ const res = await client.get(optionCastUrl(entityLogical, cast));
return { cast, res };
} catch (err) {
return { cast, why: (err && err.message) || String(err) };
@@ -623,6 +630,8 @@ module.exports = {
labelLintWarnings,
readChoiceAttributes,
readGlobalChoiceOptions,
+ optionCastUrl,
+ parseOptions,
makeChoiceReader,
makeGlobalChoiceReader,
memoizeChoiceReader,
diff --git a/plugins/model-apps/scripts/lib/web-resource-records.js b/plugins/model-apps/scripts/lib/web-resource-records.js
new file mode 100644
index 000000000..9d8a201fd
--- /dev/null
+++ b/plugins/model-apps/scripts/lib/web-resource-records.js
@@ -0,0 +1,211 @@
+'use strict';
+// The web resources a build WROTE and could not confirm were published, kept in the build's workspace so that the next run writes them again.
+//
+// The bundled SDK writes a web resource, publishes it, and reads its PUBLISHED content back (a plain GET by id); when the publish fails or the
+// read-back cannot confirm what was written, it throws WEB_RESOURCE_UNVERIFIED — after the row exists, with the row's id (`error.id`). What the
+// build does with the error is in lib/sdk-build.js (writeOwnedWebResource, persistPageManifest). What it needs from a run that FOLLOWS — the
+// build's own re-run of a transient halt, and a new invocation — is to know that the row of that name is one this plugin wrote and could not
+// confirm, so that it writes the content again by id (`updateWebResource(id, { content })`, which publishes and verifies again) instead of
+// reusing it untouched as it reuses any web resource that exists. The server holds nothing that says so: a same-named row can be another
+// maker's; its name alone grants no right to overwrite it. So the build keeps the id of its own write rather than inferring ownership from content or a name.
+//
+// Under the customization lock, a later accepted publish was observed publishing the OLD content after earlier lock-refused publishes,
+// although the content PATCH had answered 204.
+// Publishing again alone therefore may not recover the write: the content is written again once the lock frees. This does not claim every failure lost content.
+//
+// One file per environment, named by the hash of the environment's fingerprint (a web resource's name is unique in an environment, so the name
+// is the identity and no app is part of the key):
+// web-resource-unconfirmed.<64 hex>.json
+// { "schemaVersion": 1, "environmentFingerprint": "<sha256 of the origin>",
+// "webResources": { "contoso_/scripts/form.js": "11111111-1111-4111-8111-111111111111", … },
+// "revisions": { "contoso_/scripts/form.js": "0f1e2d3c4b5a6978", … } }
+// An entry is written BEFORE anything else the build does about the error (the add to the solution, the halt), and removed only once a write by
+// that id was verified and the row is in the solution again. A file that cannot be read — damaged, a link where the file should be, too large —
+// is "nothing is recorded", which is what the build did before there was a record: the rows are reused as they are. Written atomically.
+//
+// Builds that share a workspace and an environment share this file, and each change replaces it whole. So a change is never made to what a run
+// read earlier — another build may have written its own entry since, and writing the earlier copy back dropped it (A notes `a`, B notes `b`: only
+// `b` was left; A then clears `a`: the file went, `b` with it). A change takes the record's writer lease (lib/record-lease.js), reads the file as it
+// is then, applies its one change to that, and writes it: a note adds or replaces one entry, a clear removes one, and neither touches another
+// build's. Reads take no lease.
+//
+// An id alone does not tell one build's entry from another's: the row is the same row, so a build that writes it again and cannot confirm that
+// write either records the SAME id. A clear by a build that verified an EARLIER write of it would then remove the newer entry — the only trace of a
+// write nothing has confirmed — and the next build would reuse the row untouched. So each note also records a revision, minted for that note
+// (`revisions`, 16 hex characters, beside `webResources` so that the name-to-id map keeps its shape), and a clear removes an entry only while it
+// holds the id AND the revision this build knows; an entry noted since by another build is left for that build, or for the next run, to write
+// again. An entry with no revision — one written before there were revisions — is matched by its id alone, as it always was.
+const fs = require('node:fs');
+const path = require('node:path');
+const crypto = require('node:crypto');
+const { sha256 } = require('./hash.js');
+const { writeFileAtomic } = require('./apply-snapshot-store.js');
+const { environmentFingerprint, workspaceRoot } = require('./page-ownership-records.js');
+const { withRecordLease } = require('./record-lease.js');
+
+const PREFIX = 'web-resource-unconfirmed.';
+const SCHEMA_VERSION = 1;
+const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+const REVISION = /^[0-9a-f]{16}$/;
+// A handful of names and ids: a file much larger than any spec's web resources could need is not a record of this kind.
+const MAX_BYTES = 1 << 20;
+
+const recordFile = (root, fingerprint) => path.join(root, `${PREFIX}${sha256(fingerprint)}.json`);
+// Names are compared as Dataverse compares them, without regard to case; the record keeps the name as the build wrote it.
+const keyOf = (name) => String(name).toLowerCase();
+const mintRevision = () => crypto.randomBytes(8).toString('hex');
+// The same entry: the same id and the same revision — none on either side is the same as none.
+const sameEntry = (a, b) => Boolean(a) && Boolean(b) && a.id === b.id && (a.rev || '') === (b.rev || '');
+
+// Where the record of `environment` is kept — for a caller that has to point at it (a message, a test), never to read it.
+function unconfirmedRecordPath(workspaceDir, environment) {
+ return recordFile(path.resolve(workspaceDir), environmentFingerprint(environment));
+}
+
+// The recorded web resources of `environment`, as Map<lower-cased name, { name, id, rev? }>. Throws what stops the file from being read (the caller
+// decides that is only a warning); a workspace or a file that does not exist is an empty map. A revision that is missing or not one the build
+// writes is no revision: the entry is then matched by its id alone.
+function readUnconfirmedWebResources(workspaceDir, environment) {
+ const known = new Map();
+ const root = workspaceRoot(workspaceDir);
+ if (!root) return known;
+ const fingerprint = environmentFingerprint(environment);
+ const file = recordFile(root, fingerprint);
+ let stat;
+ try { stat = fs.lstatSync(file); } catch (e) { if (e.code === 'ENOENT') return known; throw e; }
+ // A plain, unlinked file of a sane size, as the page records are read: a record another location can alter, or a file that is not one, says nothing.
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink > 1 || stat.size > MAX_BYTES) throw new Error(`${file} is not a plain file of a web-resource record`);
+ const record = JSON.parse(fs.readFileSync(file, 'utf8'));
+ if (!record || record.schemaVersion !== SCHEMA_VERSION || record.environmentFingerprint !== fingerprint
+ || !record.webResources || typeof record.webResources !== 'object' || Array.isArray(record.webResources)) {
+ throw new Error(`${file} is not a web-resource record this build can read`);
+ }
+ const revisions = record.revisions && typeof record.revisions === 'object' && !Array.isArray(record.revisions) ? record.revisions : {};
+ for (const [name, id] of Object.entries(record.webResources)) {
+ if (!(name && typeof id === 'string' && GUID.test(id))) continue;
+ const rev = Object.prototype.hasOwnProperty.call(revisions, name) && typeof revisions[name] === 'string' && REVISION.test(revisions[name]) ? revisions[name] : undefined;
+ known.set(keyOf(name), { name, id, ...(rev ? { rev } : {}) });
+ }
+ return known;
+}
+
+// Replace the record of `environment` with `entries` (the Map readUnconfirmedWebResources answers); an empty map removes the file. It takes no lease:
+// a caller that shares the workspace with another build holds the record's lease across its read and this write (openUnconfirmedWebResources).
+function writeUnconfirmedWebResources(workspaceDir, environment, entries) {
+ const fingerprint = environmentFingerprint(environment);
+ if (!entries.size) {
+ const root = workspaceRoot(workspaceDir);
+ if (!root) return;
+ try { fs.unlinkSync(recordFile(root, fingerprint)); } catch (e) { if (e.code !== 'ENOENT') throw e; }
+ return;
+ }
+ const root = workspaceRoot(workspaceDir, true);
+ const webResources = {};
+ const revisions = {};
+ // Sorted, so the entries are written in the same order whatever order they were recorded in.
+ for (const { name, id, rev } of [...entries.values()].sort((a, b) => (keyOf(a.name) < keyOf(b.name) ? -1 : 1))) {
+ webResources[name] = id;
+ if (rev) revisions[name] = rev;
+ }
+ // No revision, no key: a record of entries without one is written exactly as before there were revisions.
+ const record = { schemaVersion: SCHEMA_VERSION, environmentFingerprint: fingerprint, webResources, ...(Object.keys(revisions).length ? { revisions } : {}) };
+ writeFileAtomic(recordFile(root, fingerprint), `${JSON.stringify(record)}\n`);
+}
+
+/**
+ * The record for one run of the build: read once, then each change made to the file as it is then, under the record's writer lease. `idOf(name)`
+ * is the id an earlier run recorded for the name (what this run read, with its own changes); `note(name, id)` records one, under a revision minted
+ * for that note, and answers whether that is now on disk; `clear(name)` removes the entry this run knows — the same id and revision — and leaves
+ * one another build has noted since, the same id included. `note` does not replace an entry another build recorded since this run read the record,
+ * under another id: that is said once, and it answers false. None of them throws: a workspace that cannot be written, or a lease another build holds
+ * past the bounded wait, is said once on `warn`, and a run without a workspace or an environment (a caller that gives neither; the CLI always gives
+ * both) records nothing — `note` then answers false. `lease` is for tests: the lib/record-lease.js seams.
+ */
+function openUnconfirmedWebResources({ workspaceDir, environment, warn, lease } = {}) {
+ const usable = Boolean(workspaceDir) && Boolean(environment);
+ let entries;
+ let warned = false;
+ const say = (message) => {
+ if (warned || typeof warn !== 'function') return;
+ warned = true;
+ warn(message);
+ };
+ const unreadable = (e) => `the record of the web resources an earlier build could not confirm were published could not be read (${(e && e.message) || e}), so this build reuses every web resource that exists as it is`;
+ const load = () => {
+ if (entries) return entries;
+ entries = new Map();
+ if (!usable) return entries;
+ try { entries = readUnconfirmedWebResources(workspaceDir, environment); } catch (e) { say(unreadable(e)); }
+ return entries;
+ };
+ // One change, made under the record's lease to the record as it is on disk now — never to this run's copy, which another build may have changed
+ // since. `apply(disk, file)` changes the Map it is given and answers true when there is something to write, false when there is not, null when the
+ // record holds another build's newer entry that this change leaves as it is, or the reason this run's change is refused (a string, said once).
+ // Answers true when the change is made, null when another build's entry was left, false otherwise. `create` is false for a removal: a workspace
+ // that is not there holds nothing to remove, and is not made for it.
+ const change = (apply, create = true) => {
+ if (!usable) return false;
+ let verdict;
+ try {
+ const root = workspaceRoot(workspaceDir, create);
+ if (!root) return true;
+ const file = recordFile(root, environmentFingerprint(environment));
+ const leased = withRecordLease(root, path.basename(file), () => {
+ let disk;
+ // Unreadable now, as a first read can be (load, above): nothing is recorded, and a change replaces the file — what a note always did.
+ try { disk = readUnconfirmedWebResources(workspaceDir, environment); } catch (e) { say(unreadable(e)); disk = new Map(); }
+ const answer = apply(disk, file);
+ if (answer === true) writeUnconfirmedWebResources(workspaceDir, environment, disk);
+ return answer;
+ }, lease);
+ if (!leased.ok) throw new Error(leased.reason);
+ verdict = leased.value;
+ } catch (e) {
+ say(`the record of the web resources this build could not confirm were published could not be written (${(e && e.message) || e})`);
+ return false;
+ }
+ if (typeof verdict === 'string') { say(verdict); return false; }
+ return verdict === null ? null : true;
+ };
+ return {
+ idOf: (name) => { const entry = load().get(keyOf(name)); return entry ? entry.id : undefined; },
+ note: (name, id) => {
+ if (!usable || !GUID.test(String(id).toLowerCase())) return false;
+ const key = keyOf(name);
+ // A revision of its own, even for an id the record holds already: this note is another write nothing has confirmed, and a clear by a build that
+ // verified an earlier write must not take it (see the header).
+ const entry = { name: String(name), id: String(id).toLowerCase(), rev: mintRevision() };
+ const known = load().get(key);
+ const made = change((disk, file) => {
+ const held = disk.get(key);
+ // Another build recorded this name since this run read the record, under another id: that entry is the other build's way back to the row it
+ // wrote, and replacing it would lose it. Under the same id it is the same row, and this note — a later write of it — takes its place.
+ if (held && held.id !== entry.id && !sameEntry(held, known)) {
+ return `the record of the web resources builds could not confirm were published (${file}) already holds '${held.name}' as ${held.id}, which another build recorded since this one read it; it is left as it is, and this build's write of '${entry.name}' (${entry.id}) is not recorded`;
+ }
+ disk.set(key, entry);
+ return true;
+ });
+ if (made === true) entries.set(key, entry);
+ return made === true;
+ },
+ clear: (name) => {
+ const key = keyOf(name);
+ const known = load().get(key);
+ if (!known) return;
+ const made = change((disk) => {
+ const held = disk.get(key);
+ if (!held) return false;
+ // Only the entry this run knows — its id AND its revision. One another build has noted since, the same row's id included, is a write that this
+ // run's verification came before: it stays, for that build or the next run to write again.
+ if (!sameEntry(held, known)) return null;
+ disk.delete(key);
+ return true;
+ }, false);
+ // Removed, or left for the build that noted it since: either way this run's own entry is no longer in the record.
+ if (made !== false) entries.delete(key);
+ },
+ };
+}
+
+module.exports = { PREFIX, openUnconfirmedWebResources, readUnconfirmedWebResources, writeUnconfirmedWebResources, unconfirmedRecordPath };
diff --git a/plugins/model-apps/scripts/list-custom-apis.js b/plugins/model-apps/scripts/list-custom-apis.js
index 07f497bef..7cd42fc2d 100644
--- a/plugins/model-apps/scripts/list-custom-apis.js
+++ b/plugins/model-apps/scripts/list-custom-apis.js
@@ -1,15 +1,18 @@
#!/usr/bin/env node
// Lists the Dataverse Custom APIs a GenPage can bind to — Global ones plus those bound to the
-// page's table(s) — with each API's declared request-parameter kinds. The genpage-customapi-builder
+// page's table(s) — with primitive declared kinds and separate lookup-authoring metadata. The genpage-customapi-builder
// agent turns this into actions.json entries ({ name, isFunction, boundEntityLogicalName?,
-// displayName, parameterKinds }) that pac persists into the page config.json under `actionBindings`.
+// displayName, parameterKinds }) that the SDK persists into config.json under `actionBindings`.
+// `lookupParameters` is discovery-only: it keeps lookup input names available to the author without
+// declaring a kind the runtime would reject or copying authoring hints into the wire binding.
//
// Unlike connectors (whose metadata lives outside Dataverse and needs pac verbs), Custom API metadata
// IS in ordinary Dataverse tables, so discovery is a plain Web API query — no new pac verb needed.
// customapi — the API definitions (uniquename, isfunction, bindingtype, bound entity)
// customapirequestparameter — each API's request parameters and their declared `type` (pulled inline
// via $expand so discovery stays a single request — see main())
+// customapiresponseproperty — response types, used to exclude unsupported Entity/EntityCollection outputs
// See: https://learn.microsoft.com/power-apps/developer/data-platform/custom-api
//
// Usage:
@@ -17,11 +20,11 @@
// --entities Restrict entity-bound results to these table logical names (the page's tables).
// When omitted, ONLY Global APIs are returned (a page that needs entity-bound
// operations knows its own table(s) and passes them here); this keeps the result set
-// and the follow-up parameter query bounded.
+// bounded without per-API follow-up queries.
//
// Output:
// { "ok": true, "customApis": [ { name, displayName, isFunction, bindingType,
-// boundEntityLogicalName?, parameterKinds } ] }
+// boundEntityLogicalName?, parameterKinds, lookupParameters? } ] }
const {
dataverseRequest,
@@ -39,26 +42,14 @@ const { makeWritesBlocking } = require('./lib/output-redaction.js');
// See: https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/customapi
const BINDING_TYPE = { 0: 'Global', 1: 'Entity', 2: 'EntityCollection' };
-// customapirequestparameter.type is a Dataverse option set whose integer values map to the runtime's
-// DataverseParameterKind strings. The runtime reads these from the page manifest (`parameterKinds`)
+// Only primitive customapirequestparameter.type values map to declared DataverseParameterKind strings.
+// Types 3/4 (Entity/EntityCollection) are not supported; type 5 is recognized structurally at call time
+// as { entityName, id }, never declared as EntityReference. An unsupported declared kind drops the
+// WHOLE binding. The runtime reads primitive kinds from the page manifest (`parameterKinds`)
// and has no other source, so record them exactly — an Integer mis-recorded as Decimal (or a Guid as
// String) changes how the value is serialized on the wire.
// See: https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/customapirequestparameter
-const PARAMETER_KIND_BY_TYPE = {
- 0: 'Boolean',
- 1: 'DateTime',
- 2: 'Decimal',
- 3: 'Entity',
- 4: 'EntityCollection',
- 5: 'EntityReference',
- 6: 'Float',
- 7: 'Integer',
- 8: 'Money',
- 9: 'Picklist',
- 10: 'String',
- 11: 'StringArray',
- 12: 'Guid',
-};
+const { PARAMETER_KIND_BY_TYPE } = require('./lib/custom-api-kinds.js');
function bindingTypeLabel(bindingtype) {
return BINDING_TYPE[bindingtype] || 'Global';
@@ -70,7 +61,7 @@ function mapParameterKind(typeValue) {
return PARAMETER_KIND_BY_TYPE[typeValue];
}
-// Builds the $filter for the customapi query: every Global API (bindingtype 0), plus the entity-bound
+// Builds the $filter for public customapis: Global APIs (bindingtype 0), plus the entity-bound
// APIs for the page's tables when `entities` is non-empty. When NO tables are supplied, return ONLY
// Global APIs — returning every entity-bound API in the environment can explode the result set (and
// make the follow-up request-parameter query URL, an OR of per-API ids, too long). A page that wants
@@ -80,12 +71,13 @@ function buildCustomApiFilter(entities) {
if (list.length === 0) {
// No page tables supplied: Global only (see above). This matches the genpage-customapi-builder
// contract — omit --entities for a mock/global-only page.
- return 'bindingtype eq 0';
+ return 'isprivate eq false and (bindingtype eq 0)';
}
const bound = list
.map((e) => `boundentitylogicalname eq '${odataLit(e)}'`)
.join(' or ');
- return `bindingtype eq 0 or (${bound})`;
+ // Parenthesize the whole scope: otherwise the OR branch would admit private entity-bound APIs.
+ return `isprivate eq false and (bindingtype eq 0 or (${bound}))`;
}
// Maps one API's request-parameter rows (returned inline via $expand of CustomAPIRequestParameters)
@@ -103,8 +95,25 @@ function parameterKindsFromRows(rows) {
return kinds;
}
-// Projects one customapi row (+ its parameter kinds) into the discovery shape the builder writes to
-// actions.json. `boundEntityLogicalName` is included only for a truly entity-bound API with a table.
+// Lookup rows arrive as { uniquename: 'Ref', type: 5, isoptional: false, logicalentityname: 'account' }.
+// The table hint is optional (a lookup can be unrestricted); never invent it. Keep optionalness and
+// names outside parameterKinds so a required lookup does not disappear when its kind is omitted.
+// See: https://learn.microsoft.com/power-apps/developer/data-platform/reference/entities/customapirequestparameter
+function lookupParametersFromRows(rows) {
+ const lookups = {};
+ for (const row of rows || []) {
+ if (Number(row.type) !== 5 || !row.uniquename) continue;
+ const lookup = { isOptional: row.isoptional === true };
+ if (typeof row.logicalentityname === 'string' && row.logicalentityname) {
+ lookup.logicalEntityName = row.logicalentityname;
+ }
+ lookups[row.uniquename] = lookup;
+ }
+ return lookups;
+}
+
+// Projects discovery metadata, NOT an actions.json entry: the builder must explicitly omit
+// bindingType and lookupParameters when writing the bare wire binding.
function toCustomApiEntry(api, parameterKinds) {
const bindingType = bindingTypeLabel(api.bindingtype);
const entry = {
@@ -117,9 +126,90 @@ function toCustomApiEntry(api, parameterKinds) {
if (bindingType !== 'Global' && api.boundentitylogicalname) {
entry.boundEntityLogicalName = api.boundentitylogicalname;
}
+ const lookups = lookupParametersFromRows(api.CustomAPIRequestParameters);
+ if (Object.keys(lookups).length) entry.lookupParameters = lookups;
return entry;
}
+function requireCompleteExpansion(api, property, rows, envUrl) {
+ const context = `Custom API '${api.uniquename}' ${property} metadata`;
+ // These are single-level expansions: their ordinary relationship links repeat the same related
+ // rows, not a next page. At the documented 5,000-row cap, however, completeness is ambiguous even
+ // without an annotation. Never follow a link or mistake token absence for a complete capped set.
+ // See: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/query/join-tables#single-expand-on-collection-valued-navigation-properties
+ if (rows.length >= 5000) {
+ throw new Error(`${context} reaches the 5000-row expansion limit; completeness is ambiguous.`);
+ }
+ const annotation = api[`${property}@odata.nextLink`];
+ if (annotation === undefined) return;
+ let link;
+ try {
+ if (typeof annotation !== 'string') throw new Error();
+ link = new URL(annotation);
+ } catch {
+ throw new Error(`${context} has an unreadable relationship link; completeness is ambiguous.`);
+ }
+ const origin = new URL(envUrl).origin;
+ const expectedPath = `/api/data/v9.2/customapis(${api.customapiid})/${property}`;
+ const expectedFields = property === 'CustomAPIRequestParameters'
+ ? ['uniquename', 'type', 'isoptional', 'logicalentityname']
+ : ['type'];
+ const options = [...link.searchParams.keys()];
+ const fields = (link.searchParams.get('$select') || '').split(',').map((field) => field.trim()).sort();
+ // Accept only the same related collection and the options in our known single-level query.
+ // Paging, limiting, foreign-resource and otherwise unexplained links fail explicitly, without
+ // sending another request or echoing a potentially sensitive URL into diagnostics.
+ if (link.origin !== origin || link.username || link.password || link.hash
+ || link.pathname.toLowerCase() !== expectedPath.toLowerCase()
+ || options.length !== 1 || options[0] !== '$select'
+ || fields.join(',') !== expectedFields.sort().join(',')) {
+ throw new Error(`${context} has an incomplete or ambiguous relationship link.`);
+ }
+}
+
+function requireRequestMetadata(api, rows) {
+ const names = new Set();
+ for (const [index, row] of rows.entries()) {
+ const context = `Custom API '${api.uniquename}' request parameter ${index + 1}`;
+ const name = row.uniquename;
+ // The existing projection maps use ordinary objects: __proto__ would invoke a setter instead
+ // of retaining an own input name. Refuse it explicitly rather than lose a required parameter.
+ if (typeof name !== 'string' || !name.trim() || name === '__proto__') {
+ throw new Error(`${context} metadata is unreadable: uniquename must be a safely representable nonempty string.`);
+ }
+ if (names.has(name)) throw new Error(`${context} '${name}' has a duplicate uniquename.`);
+ names.add(name);
+ if (row.type !== 5) continue;
+ // The projection helpers keep their permissive compatibility shape; the CLI must establish
+ // lookup authoring facts first, rather than invent requiredness or drop a malformed table hint.
+ if (typeof row.isoptional !== 'boolean') {
+ throw new Error(`${context} '${name}' metadata is unreadable: lookup isoptional must be boolean.`);
+ }
+ if (row.logicalentityname != null && (typeof row.logicalentityname !== 'string'
+ || !row.logicalentityname.trim() || row.logicalentityname !== row.logicalentityname.trim())) {
+ throw new Error(`${context} '${name}' metadata is unreadable: logicalentityname must be a table hint string or absent.`);
+ }
+ }
+}
+
+function supportsApiParameters(api, envUrl) {
+ const collections = ['CustomAPIRequestParameters', 'CustomAPIResponseProperties'];
+ for (const property of collections) {
+ const rows = api[property];
+ // An omitted expansion is not an empty collection. Calling it supported would conceal an
+ // unreadable type-3/4 parameter or output; fail explicitly instead of emitting unsafe bindings.
+ if (!Array.isArray(rows) || rows.some((row) => !row || !Number.isInteger(row.type) || row.type < 0 || row.type > 12)) {
+ throw new Error('Custom API request/response type metadata is unreadable or unsupported.');
+ }
+ requireCompleteExpansion(api, property, rows, envUrl);
+ }
+ // Match authoring eligibility for both directions. A primitive input does not make an API whose
+ // output is Entity/EntityCollection callable, and collection-bound APIs are excluded separately.
+ if (collections.some((property) => api[property].some((row) => row.type === 3 || row.type === 4))) return false;
+ requireRequestMetadata(api, api.CustomAPIRequestParameters);
+ return true;
+}
+
async function main() {
// Feature gate first (fail closed) — see lib/feature-flags.js. Exit 3 = "feature off", distinct
// from 1 = runtime/usage error, so a caller can tell "not released" from "it broke".
@@ -150,22 +240,37 @@ async function main() {
// every matched API id into one $filter. A real environment has hundreds of Global Custom APIs
// (system + custom — 800+ is normal), and an OR-of-ids filter over that many rows overruns the
// server's URL-length limit (HTTP 414). $expand keeps discovery to a single request whose URL
- // length is independent of how many APIs match; request parameters per API are few, so the nested
- // collection is never truncated.
- const expand = encodeURIComponent('CustomAPIRequestParameters($select=uniquename,type,isoptional)');
+ // length is independent of how many APIs match. Expand response types too: unsupported outputs
+ // must exclude an API just as unsupported inputs do.
+ const expand = encodeURIComponent(
+ 'CustomAPIRequestParameters($select=uniquename,type,isoptional,logicalentityname),CustomAPIResponseProperties($select=type)'
+ );
const apisRes = await dataverseRequest(
envUrl,
'GET',
- 'customapis?$select=customapiid,uniquename,name,displayname,isfunction,bindingtype,boundentitylogicalname' +
+ 'customapis?$select=customapiid,uniquename,name,displayname,isfunction,bindingtype,boundentitylogicalname,isprivate' +
`&$filter=${filter}&$expand=${expand}`
);
ensureOk(apisRes, 'List custom APIs');
- const apis = (apisRes.data?.value || [])
+ if (!Array.isArray(apisRes.data?.value)) {
+ throw new Error('Custom API metadata is unreadable: expected an API value array.');
+ }
+ // Never claim a complete inventory or eligibility from a paged-away portion. Keep discovery's
+ // bounded single-query contract explicit rather than following an unchecked continuation URL.
+ if (apisRes.data['@odata.nextLink'] !== undefined) {
+ throw new Error('Custom API metadata is incomplete; the API query returned a continuation.');
+ }
+ const apis = apisRes.data.value
.filter((a) => a.uniquename)
+ .filter((a) => {
+ if (typeof a.isprivate !== 'boolean') throw new Error('Custom API privacy metadata is unreadable.');
+ return !a.isprivate;
+ })
// Exclude EntityCollection-bound APIs (bindingtype 2). The generated-page runtime's boundTo is a
// single record ({ entityName, id }); there is no collection-bound invocation shape, so surfacing
// one would only let the builder emit a binding that fails. See genpage-customapi-builder.md.
- .filter((a) => Number(a.bindingtype) !== 2);
+ .filter((a) => Number(a.bindingtype) !== 2)
+ .filter((api) => supportsApiParameters(api, envUrl));
const customApis = apis
.map((api) => toCustomApiEntry(api, parameterKindsFromRows(api.CustomAPIRequestParameters)))
diff --git a/plugins/model-apps/scripts/teardown-model-app.js b/plugins/model-apps/scripts/teardown-model-app.js
index 631111aa1..b684312da 100644
--- a/plugins/model-apps/scripts/teardown-model-app.js
+++ b/plugins/model-apps/scripts/teardown-model-app.js
@@ -17,7 +17,8 @@
// global choices -> solution. Forms/charts/views/relationships are deleted explicitly BEFORE
// tables (a table delete does not reliably cascade cross-references). Command teardown removes
// the whole command bar for an entity the spec authored commands on (the SDK models a command bar
-// per entity, not per button).
+// per entity, not per button). The solution's PUBLISHER is never deleted (it may be shared); the
+// closing summary says so in one line.
const fs = require('node:fs');
const path = require('node:path');
const { validateAppSpec, migrateAppSpec } = require('./lib/app-spec.js');
@@ -177,6 +178,12 @@ async function teardownModelApp(spec, opts, deps) {
const notAttempted = counts['not-attempted'] || 0;
const extra = `${kept ? `, ${kept} kept` : ''}${notAttempted ? `, ${notAttempted} not attempted` : ''}`;
log(`\n${r.ok ? '✓' : '✗'} teardown ${r.ok ? 'complete' : 'finished with errors'} — ${counts.ok} deleted, ${notFound} not found, ${counts.error} failed${extra} (${counts.ok + counts.skip + counts.error} steps)`);
+ // A publisher is never deleted, and no step plans one: the build reuses any publisher with the spec's prefix
+ // (lib/entity-provision.js provisionSolution), and other solutions may share the one it made, so nothing here can
+ // tell that this app alone uses it. Said once, after the count, so the row a maker finds left behind is expected.
+ // The structural profile requires solution.publisherPrefix; the guard only keeps a log line from ever throwing.
+ const publisherPrefix = spec.solution && spec.solution.publisherPrefix;
+ if (publisherPrefix) log(`▸ the publisher with prefix '${publisherPrefix}' is kept: teardown never deletes a publisher, which other solutions may share — delete it in Power Apps (Solutions → Publishers) once nothing uses it`);
}
return r;
}
diff --git a/plugins/model-apps/scripts/tests/already-exists-codes-real-bundle.test.js b/plugins/model-apps/scripts/tests/already-exists-codes-real-bundle.test.js
new file mode 100644
index 000000000..84da85580
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/already-exists-codes-real-bundle.test.js
@@ -0,0 +1,533 @@
+'use strict';
+// A create that Dataverse refuses because what it asks for already exists is a skip — or, for a table and a relationship, the cue to
+// read what exists — and that answer is recognised by its error CODE, which is the same in every language, as well as by its English
+// words. The words alone halted a rebuild on an environment whose language is Spanish: the platform words its refusals in the caller's
+// language, and an alternate key the build had to create again (it could not prove the key from its table read) was answered
+// HTTP 400 {"error":{"code":"0x80060893","message":"Ya existe una clave de entidad con el nombre contoso_codekey en la entidad contoso_project."}}
+// (live-captured, with the names replaced), which the English words cannot read.
+//
+// Each create that reads such an answer is run here twice through the real vendored SDK, over a transport that answers only what a test
+// models: once answered in English and once in another language, with the same code. The other language must come to the same outcome
+// — the same steps, warnings, requests and result. Of the non-English texts only the key's Spanish one is the platform's own (the same
+// environment answered the other creates in English, and those English texts are its own too where a test says so); the others are
+// written for these tests, to be words the English rule cannot read. The codes are the ones lib/entity-provision.js documents
+// (ALREADY_EXISTS_CODES). What must not move: a code of ANOTHER create, a generic code, and a code that the words only quote do not by
+// themselves make an answer an already-exists one — given words the English rule cannot read, such an answer stops the build (the 409
+// and English-word rules are unchanged and still apply whatever code an answer carries); and the reads that decide a table and a
+// relationship are made as before.
+//
+// Two codes are broader than the create they are listed for, and are pinned on both sides of the read that decides: the table create's
+// 0x80044363 (a schema name that is not unique — what an existing table's create was answered, live, but a name another kind of
+// component can hold too), and the 1:N create's 0x80072551 (a navigation property that is not unique — what an existing 1:N's create was
+// answered, live, in words no English rule matched, so such a relationship stopped the build in every language; but another
+// relationship can hold that navigation property too).
+// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/web-service-error-codes
+const { test } = require('node:test');
+const assert = require('node:assert');
+const path = require('node:path');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { makeRunner, provisionDataModel, BuildHalt, ALREADY_EXISTS_CODES } = require('../lib/entity-provision.js');
+
+const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
+const ORG = 'https://contoso.crm.dynamics.com';
+
+const ok = (body) => ({ status: 200, body });
+// The platform's OData error envelope, as the SDK receives it.
+const answer = (status, code, message) => ({ status, body: { error: { code, message } } });
+const refused = (code, message) => answer(400, code, message);
+// What the platform answers a read of something it does not hold.
+const absent = (message) => answer(404, '0x80060888', message);
+// The generic code, documented as "An unexpected error occurred." — it says nothing about what failed.
+const GENERIC = '0x80040216';
+
+// The real SDK over a transport that answers only the requests a test models. Every request is recorded; one that no test models is a
+// failure of the test (`unmodelled`), never an answer the build could read as a success or as the refusal under test.
+async function realSdk(route) {
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const requests = [];
+ const unmodelled = [];
+ const send = async (method, url, body) => {
+ const asked = decodeURIComponent(String(url)).replace(/^https:\/\/contoso\.crm\.dynamics\.com\/api\/data\/v9\.\d+/, '');
+ requests.push(`${method} ${asked}`);
+ const reply = route(method, asked, body);
+ if (!reply) {
+ unmodelled.push(`${method} ${asked}`);
+ throw new Error(`the test does not model ${method} ${asked}`);
+ }
+ return { status: reply.status, headers: {}, body: reply.body };
+ };
+ const httpClient = {
+ get: (url) => send('GET', url),
+ post: (url, body) => send('POST', url, body),
+ put: (url, body) => send('PUT', url, body),
+ patch: (url, body) => send('PATCH', url, body),
+ delete: (url) => send('DELETE', url),
+ };
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(makeTempDir('already-exists-codes-')), instanceUrl: ORG, httpClient });
+ await sdk.initWorkspace();
+ return { sdk, requests, unmodelled };
+}
+
+// The data-model phase of a build in an environment whose only language is Spanish (3082), over the routes given.
+async function build(spec, route) {
+ const { sdk, requests, unmodelled } = await realSdk(route);
+ const events = [];
+ const warnings = [];
+ let result;
+ let error;
+ try {
+ result = await provisionDataModel({
+ sdk, provision: sdk, runner: makeRunner({ emit: (event) => events.push(event), total: 20 }), spec, apply: true,
+ preResolvedLanguageCode: 3082, provisionedLanguages: async () => [3082], sleep: async () => {}, warn: (message) => warnings.push(message),
+ });
+ } catch (err) { error = err; }
+ const steps = events.filter((event) => event.status !== 'start').map((event) => `${event.status} ${event.label}`);
+ return { result, error, steps, warnings, requests, unmodelled };
+}
+
+// What two runs must share to have come to the same outcome.
+const outcomeOf = (run) => ({ steps: run.steps, warnings: run.warnings, requests: run.requests, result: run.result });
+
+// The build stops at `step` — the create under test, which is not skipped — with the platform's own words.
+function assertStopsAt(run, step, words, what) {
+ assert.deepStrictEqual(run.unmodelled, [], `${what}: every request was one the test models`);
+ assert.ok(run.error instanceof BuildHalt, `${what}: the build stops — ${run.error && run.error.message}`);
+ assert.strictEqual(run.error.phase, 'data-model', what);
+ assert.ok(run.error.message.includes(words), `${what}: with the platform's own words — ${run.error.message}`);
+ assert.strictEqual(run.steps[run.steps.length - 1], `error ${step}`, `${what}: at that step — ${run.steps.join(' | ')}`);
+}
+
+const SOLUTION = { uniqueName: 'Proyectos', publisherPrefix: 'contoso' };
+const project = (more) => ({ schemaName: 'contoso_Project', displayName: 'Proyecto', pluralName: 'Proyectos', primaryAttribute: { schemaName: 'contoso_Name' }, columns: [], ...more });
+const PROJECT_COLUMNS = ok({ value: [{ LogicalName: 'contoso_name', RequiredLevel: { Value: 'None' } }, { LogicalName: 'contoso_code', RequiredLevel: { Value: 'None' } }] });
+const PROBE = "/EntityDefinitions(LogicalName='contoso_project')?$select=LogicalName,EntitySetName";
+const COLUMN_LIST = "/EntityDefinitions(LogicalName='contoso_project')/Attributes?$select=LogicalName,RequiredLevel";
+
+// --- an alternate key the build cannot prove from its table read -------------------------------------------------------------------
+// The keys ride the read that finds the table (`$expand=Keys`), and a key that read shows over the same columns is not sent again. When
+// that read fails, the table is found by the list of tables, which carries no keys: the key cannot be proven, so it is created, and the
+// platform answers that it exists — the path a rebuild on the Spanish environment halted on, live.
+const KEYED = { solution: SOLUTION, relationships: [], entities: [project({
+ columns: [{ schemaName: 'contoso_Code', type: 'Text' }],
+ alternateKeys: [{ schemaName: 'contoso_CodeKey', displayName: 'Clave de codigo', columns: ['contoso_code'] }],
+})] };
+const KEYS = "/EntityDefinitions(LogicalName='contoso_project')/Keys";
+const keyRefusedWith = (keyAnswer) => (method, asked) => {
+ if (method === 'GET' && asked === `${PROBE}&$expand=Keys($select=SchemaName,KeyAttributes)`) return answer(500, GENERIC, 'An unexpected error occurred.');
+ if (method === 'GET' && asked === '/EntityDefinitions?$select=LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity') {
+ return ok({ value: [{ LogicalName: 'contoso_project', SchemaName: 'contoso_Project', EntitySetName: 'contoso_projects', IsCustomEntity: true }] });
+ }
+ if (method === 'GET' && asked === COLUMN_LIST) return PROJECT_COLUMNS;
+ if (method === 'POST' && asked === KEYS) return keyAnswer;
+ return undefined;
+};
+const KEY_IN_ENGLISH = refused('0x80060893', 'An entity key with the name contoso_codekey already exists on entity contoso_project.');
+
+test('an alternate key the build cannot prove, refused in Spanish because it exists (0x80060893), is skipped exactly as the English refusal is', async () => {
+ const english = await build(KEYED, keyRefusedWith(KEY_IN_ENGLISH));
+ assert.deepStrictEqual(english.unmodelled, []);
+ assert.strictEqual(english.error, undefined, english.error && english.error.message);
+ assert.ok(english.steps.includes('skip alt key contoso_Project.contoso_CodeKey (exists)'), english.steps.join(' | '));
+ assert.strictEqual(english.requests.filter((request) => request === `POST ${KEYS}`).length, 1, 'the key could not be proven, so it was asked for once');
+ for (const [language, words] of [
+ // The platform's own Spanish text (live-captured, names replaced).
+ ['Spanish', 'Ya existe una clave de entidad con el nombre contoso_codekey en la entidad contoso_project.'],
+ // Any other language is read the same way: the code decides, not the words.
+ ['German', 'Ein Entitaetsschluessel mit dem Namen contoso_codekey ist fuer die Entitaet contoso_project bereits vorhanden.'],
+ ]) {
+ const run = await build(KEYED, keyRefusedWith(refused('0x80060893', words)));
+ assert.strictEqual(run.error, undefined, `${language}: ${run.error && run.error.message}`);
+ assert.deepStrictEqual(outcomeOf(run), outcomeOf(english), `${language}: the same steps, warnings, requests and result as the English answer`);
+ }
+});
+
+test('an alternate key refused in another language with a code that does not say the key exists stops the build, as before', async () => {
+ for (const [what, keyAnswer] of [
+ // Another create's code: a column of that name exists — nothing about this key.
+ ['the code of a column that exists', refused('0x80060304', 'Ya existe el atributo contoso_code para la entidad contoso_project.')],
+ // A record already holds the key's values: the code of a data write, not of a key create.
+ ['the code of a record that holds the key\'s values', refused('0x80060892', 'Ya existe un registro con el mismo valor para contoso_code.')],
+ ['the generic code', refused(GENERIC, 'Ya existe una clave de entidad con el nombre contoso_codekey en la entidad contoso_project.')],
+ // The code is read from the answer's `error.code`, never from its words.
+ ['a code the words only quote', refused(GENERIC, 'Error 0x80060893: ya existe una clave de entidad con el nombre contoso_codekey.')],
+ // The two codes that are broader than their create count for that create only: a schema name (a table's) and a navigation property (a 1:N's).
+ ['the code of a schema name that is not unique, a table create\'s', refused('0x80044363', 'El nombre de esquema contoso_codekey para el tipo EntityKey no es unico.')],
+ ['the code of a navigation property that is not unique, a 1:N create\'s', refused('0x80072551', 'NavigationPropertyName contoso_codekey no es unico dentro de una entidad')],
+ ]) {
+ const run = await build(KEYED, keyRefusedWith(keyAnswer));
+ assertStopsAt(run, 'alt key contoso_Project.contoso_CodeKey', keyAnswer.body.error.message, what);
+ }
+});
+
+// --- a status reason whose value is already taken ---------------------------------------------------------------------------------
+// The build pins each status reason's value, so a second insert of it is refused because an option already holds that value. A table
+// that exists has its reasons read first, and only a reason the read does not show is inserted; when the read fails, every reason is
+// inserted and the refusal is what keeps the build from making one twice.
+const STATUSED = { solution: SOLUTION, relationships: [], entities: [project({ statusReasons: [{ label: 'En revision', state: 'Active' }] })] };
+const statusRefusedWith = (statusAnswer) => (method, asked) => {
+ if (method === 'GET' && asked === PROBE) return ok({ LogicalName: 'contoso_project', EntitySetName: 'contoso_projects' });
+ if (method === 'GET' && asked === COLUMN_LIST) return PROJECT_COLUMNS;
+ if (method === 'GET' && asked === "/EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)") {
+ return answer(500, GENERIC, 'An unexpected error occurred.');
+ }
+ if (method === 'POST' && asked === '/InsertStatusValue') return statusAnswer;
+ return undefined;
+};
+
+test('a status reason refused in Spanish because its value is taken (0x80044310) is skipped exactly as the English refusal is', async () => {
+ // The English text is the platform's own (live-captured, the option set's id replaced).
+ const english = await build(STATUSED, statusRefusedWith(refused('0x80044310', 'The picklist or status value 100000000 is invalid for optionSet 00000000-0000-0000-0000-000000000001 because another picklist or status option for this optionSet already exists with that value')));
+ assert.deepStrictEqual(english.unmodelled, []);
+ assert.strictEqual(english.error, undefined, english.error && english.error.message);
+ assert.ok(english.steps.includes('skip status reason contoso_Project: En revision (exists)'), english.steps.join(' | '));
+ assert.deepStrictEqual(english.result.statusReasonValues, { contoso_project: { 'En revision': { value: 100000000, stateCode: 0 } } }, 'the pinned value is kept for the sample data');
+ const spanish = await build(STATUSED, statusRefusedWith(refused('0x80044310', 'El valor de estado 100000000 no es valido para el conjunto de opciones 00000000-0000-0000-0000-000000000001 porque ya existe otra opcion con ese valor')));
+ assert.strictEqual(spanish.error, undefined, spanish.error && spanish.error.message);
+ assert.deepStrictEqual(outcomeOf(spanish), outcomeOf(english), 'the same steps, warnings, requests and result as the English answer');
+});
+
+test('a status reason refused in another language with a code that does not say its value is taken stops the build, as before', async () => {
+ for (const [what, statusAnswer] of [
+ ['the code of an alternate key that exists', refused('0x80060893', 'Ya existe una clave de entidad con el nombre contoso_codekey en la entidad contoso_project.')],
+ ['the generic code', refused(GENERIC, 'Ya existe otra opcion con ese valor.')],
+ ]) {
+ const run = await build(STATUSED, statusRefusedWith(statusAnswer));
+ assertStopsAt(run, 'status reason contoso_Project: En revision', statusAnswer.body.error.message, what);
+ }
+});
+
+// --- a table the probe did not find, and that exists when it is created --------------------------------------------------------------
+// The read that looks for the table answers that it is not there, the create answers that it is (a create whose earlier answer was lost,
+// or another maker's), and the build reads the table again: found, it is reused; not found, the create's own error stops the build.
+const TABLE = { solution: SOLUTION, relationships: [], entities: [project()] };
+const tableRefusedWith = (tableAnswer, { foundAfter = true } = {}) => {
+ let probes = 0;
+ return (method, asked) => {
+ if (method === 'GET' && asked === PROBE) {
+ probes += 1;
+ return probes > 1 && foundAfter ? ok({ LogicalName: 'contoso_project', EntitySetName: 'contoso_projects' }) : absent("EntityMetadata With Id = LogicalName='contoso_project' does not exist.");
+ }
+ if (method === 'POST' && asked === '/EntityDefinitions') return tableAnswer;
+ return undefined;
+ };
+};
+
+test('a table create refused in Spanish because the table exists (0x8009050d, 0x8004700b) is followed by the read that finds it, exactly as the English refusal is', async () => {
+ // The English text and its code are the platform's own (live-captured, the table's name replaced); 0x8004700b is the documented
+ // "An entity with the specified name already exists".
+ const english = await build(TABLE, tableRefusedWith(refused('0x8009050d', 'Entities already exist: contoso_Project.')));
+ assert.deepStrictEqual(english.unmodelled, []);
+ assert.strictEqual(english.error, undefined, english.error && english.error.message);
+ assert.deepStrictEqual(english.steps, ['ok table contoso_Project'], 'the table is taken as it is found, and nothing else is made');
+ assert.deepStrictEqual(english.requests, [`GET ${PROBE}`, 'POST /EntityDefinitions', `GET ${PROBE}`]);
+ assert.deepStrictEqual(english.result.entities, { contoso_Project: { logicalName: 'contoso_project', entitySetName: 'contoso_projects' } });
+ for (const tableAnswer of [refused('0x8009050d', 'Ya existen las entidades: contoso_Project.'), refused('0x8004700b', 'Ya existe una entidad con el nombre especificado. Especifique un nombre unico.')]) {
+ const run = await build(TABLE, tableRefusedWith(tableAnswer));
+ const code = tableAnswer.body.error.code;
+ assert.strictEqual(run.error, undefined, `${code}: ${run.error && run.error.message}`);
+ assert.deepStrictEqual(outcomeOf(run), outcomeOf(english), `${code}: the same steps, warnings, requests and result as the English answer`);
+ }
+});
+
+test('a table create refused in Spanish as existing, whose table the next read does not find, stops the build with the create\'s own error, as the English one does', async () => {
+ for (const [language, words] of [['English', 'Entities already exist: contoso_Project.'], ['Spanish', 'Ya existen las entidades: contoso_Project.']]) {
+ const run = await build(TABLE, tableRefusedWith(refused('0x8009050d', words), { foundAfter: false }));
+ assertStopsAt(run, 'table contoso_Project', words, language);
+ assert.deepStrictEqual(run.requests, [`GET ${PROBE}`, 'POST /EntityDefinitions', `GET ${PROBE}`], `${language}: the table was looked for again, and only once`);
+ }
+});
+
+// What an environment answered the create of a table that exists (live-captured: the names replaced, and the server's stack trace that
+// follows the message cut to its first line), and the same refusal in words the English rule cannot read.
+const TABLE_NAME_NOT_UNIQUE = 'Failed to create entity with logical name contoso_project and object type code -1. Exception: Microsoft.Crm.CrmException: The schema name contoso_project for type Entity is not unique. An contoso_project with same name already exists.\r\n at Microsoft.Crm.Metadata.SchemaNameValidator.ValidateSchemaNameIsUnique(String metadataEntityName, String attributeName, ISqlExecutionContext sqlContext)';
+const TABLE_NAME_NOT_UNIQUE_ES = 'No se pudo crear la entidad con el nombre logico contoso_project. El nombre de esquema contoso_project para el tipo Entity no es unico. Ya existe un contoso_project con el mismo nombre.';
+
+test('a table create refused because its schema name is not unique (0x80044363, the answer to an existing table\'s create, live) is followed by the read that finds the table, in Spanish exactly as in English', async () => {
+ const english = await build(TABLE, tableRefusedWith(refused('0x80044363', TABLE_NAME_NOT_UNIQUE)));
+ assert.deepStrictEqual(english.unmodelled, []);
+ assert.strictEqual(english.error, undefined, english.error && english.error.message);
+ assert.deepStrictEqual(english.steps, ['ok table contoso_Project'], 'the table is taken as it is found, and nothing else is made');
+ assert.deepStrictEqual(english.requests, [`GET ${PROBE}`, 'POST /EntityDefinitions', `GET ${PROBE}`]);
+ assert.deepStrictEqual(english.result.entities, { contoso_Project: { logicalName: 'contoso_project', entitySetName: 'contoso_projects' } });
+ const spanish = await build(TABLE, tableRefusedWith(refused('0x80044363', TABLE_NAME_NOT_UNIQUE_ES)));
+ assert.strictEqual(spanish.error, undefined, spanish.error && spanish.error.message);
+ assert.deepStrictEqual(outcomeOf(spanish), outcomeOf(english), 'the same steps, warnings, requests and result as the English answer');
+});
+
+test('a table create refused with 0x80044363 for a name that something other than a table holds finds no table when it reads again, and stops the build with the create\'s own error — in Spanish as in English', async () => {
+ // SchemaNameisNotUnique is about a schema name, not a table: a component of another kind can hold the name. It is only the cue for the
+ // read that follows, and that read finds no table.
+ for (const [language, words] of [['English', 'The schema name contoso_project for type Entity is not unique. An contoso_project with same name already exists.'], ['Spanish', TABLE_NAME_NOT_UNIQUE_ES]]) {
+ const run = await build(TABLE, tableRefusedWith(refused('0x80044363', words), { foundAfter: false }));
+ assertStopsAt(run, 'table contoso_Project', words, language);
+ assert.deepStrictEqual(run.requests, [`GET ${PROBE}`, 'POST /EntityDefinitions', `GET ${PROBE}`], `${language}: the table was looked for again, once, and not found`);
+ }
+});
+
+test('a table create refused in another language with a code that does not say the table exists stops the build, as before', async () => {
+ for (const [what, tableAnswer] of [
+ ['the code of a relationship that exists', refused('0x8004432b', 'Ya existe una relacion con el nombre especificado.')],
+ ['the code of a column that exists', refused('0x80047013', 'Ya existe un atributo con el nombre especificado.')],
+ ['the code of a navigation property that is not unique, a 1:N create\'s', refused('0x80072551', 'NavigationPropertyName contoso_project no es unico dentro de una entidad')],
+ ['the generic code', refused(GENERIC, 'Ya existen las entidades: contoso_Project.')],
+ ]) {
+ const run = await build(TABLE, tableRefusedWith(tableAnswer));
+ assertStopsAt(run, 'table contoso_Project', tableAnswer.body.error.message, what);
+ assert.deepStrictEqual(run.requests, [`GET ${PROBE}`, 'POST /EntityDefinitions'], `${what}: the table is not looked for again`);
+ }
+});
+
+// --- a column of a table whose columns could not be read ---------------------------------------------------------------------------
+// When the read of an existing table's columns fails, every declared column is taken for new, and the create of one that exists is
+// refused: that refusal is the skip that keeps the column from being made twice. A Customer column is made by its own request.
+const COLUMNED = { solution: SOLUTION, relationships: [], entities: [project({
+ columns: [{ schemaName: 'contoso_Code', type: 'Text' }, { schemaName: 'contoso_Customer', type: 'Customer', displayName: 'Cliente' }],
+})] };
+const ATTRIBUTES = "/EntityDefinitions(LogicalName='contoso_project')/Attributes";
+const columnsRefusedWith = (columnAnswer, customerAnswer) => (method, asked) => {
+ if (method === 'GET' && asked === PROBE) return ok({ LogicalName: 'contoso_project', EntitySetName: 'contoso_projects' });
+ if (method === 'GET' && asked === COLUMN_LIST) return answer(500, GENERIC, 'An unexpected error occurred.');
+ if (method === 'POST' && asked === ATTRIBUTES) return columnAnswer;
+ if (method === 'POST' && asked === '/CreateCustomerRelationships') return customerAnswer;
+ return undefined;
+};
+
+test('columns refused in Spanish because they exist (0x80060304, 0x80047013) are skipped exactly as the English refusals are', async () => {
+ // The 0x80047013 English text is the platform's own, as the live census answered it for each of the 13 column types it exercised (names
+ // replaced). A Customer column's answer, to CreateCustomerRelationships, was not captured: here that text is adapted to the Customer column.
+ const english = await build(COLUMNED, columnsRefusedWith(
+ refused('0x80060304', 'Attribute contoso_code already exists for entity contoso_project.'),
+ refused('0x80047013', 'An attribute with the specified name contoso_customer already exists for entity contoso_project.'),
+ ));
+ assert.deepStrictEqual(english.unmodelled, []);
+ assert.strictEqual(english.error, undefined, english.error && english.error.message);
+ assert.ok(english.steps.includes('skip column contoso_Project.contoso_Code (Text) (exists)'), english.steps.join(' | '));
+ assert.ok(english.steps.includes('skip column contoso_Project.contoso_Customer (Customer) (exists)'), english.steps.join(' | '));
+ assert.strictEqual(english.warnings.length, 1, 'the failed read of the columns is said, once');
+ const spanish = await build(COLUMNED, columnsRefusedWith(
+ refused('0x80060304', 'El atributo contoso_code ya existe para la entidad contoso_project.'),
+ refused('0x80047013', 'Ya existe un atributo con el nombre especificado contoso_customer.'),
+ ));
+ assert.strictEqual(spanish.error, undefined, spanish.error && spanish.error.message);
+ assert.deepStrictEqual(outcomeOf(spanish), outcomeOf(english), 'the same steps, warnings, requests and result as the English answers');
+});
+
+test('a column refused in another language with a code that does not say the column exists stops the build, as before', async () => {
+ const created = ok({});
+ for (const [what, columnAnswer] of [
+ // A choice whose values repeat is refused with the code of a taken option value: the column was NOT made.
+ ['the code of a taken option value', refused('0x80044310', 'Ya existe el valor de la lista desplegable. Los valores deben ser unicos.')],
+ ['the code of an alternate key that exists', refused('0x80060893', 'Ya existe una clave de entidad con el nombre contoso_code en la entidad contoso_project.')],
+ ['the code of a relationship that exists', refused('0x8004432b', 'Ya existe una relacion con el nombre especificado.')],
+ ['the code of a schema name that is not unique, a table create\'s', refused('0x80044363', 'El nombre de esquema contoso_code para el tipo Attribute no es unico.')],
+ ['the code of a navigation property that is not unique, a 1:N create\'s', refused('0x80072551', 'NavigationPropertyName contoso_code no es unico dentro de una entidad')],
+ ['the generic code', refused(GENERIC, 'El atributo contoso_code ya existe para la entidad contoso_project.')],
+ ]) {
+ const run = await build(COLUMNED, columnsRefusedWith(columnAnswer, created));
+ assertStopsAt(run, 'column contoso_Project.contoso_Code (Text)', columnAnswer.body.error.message, what);
+ }
+});
+
+// --- a relationship the probe did not see -----------------------------------------------------------------------------------------
+// The probe reads the referenced table's relationships and does not list it (a read that lags), the create answers that the name is
+// taken, and the build reads the relationship that holds the name: the declared one is reused, another one stops the build. The lookup
+// column is part of what a 1:N create makes, and the build looks for the relationship that owns it when the name is free.
+const SCHEMA = 'contoso_project_contoso_task';
+const RELATED = { solution: SOLUTION, entities: [], relationships: [{
+ type: 'OneToMany', schemaName: SCHEMA, referenced: 'contoso_project', referencing: 'contoso_task', lookup: { schemaName: 'contoso_ProjectId', displayName: 'Proyecto' },
+}] };
+const HELD = { SchemaName: SCHEMA, ReferencedEntity: 'contoso_project', ReferencingEntity: 'contoso_task', ReferencingAttribute: 'contoso_projectid' };
+// `holder` is what the read of the name answers (none: the name is free), `owners` the relationships the referencing table lists as its
+// many-to-one, `listed` the ones the referenced table lists as its one-to-many (the probe's read, and the search for the name);
+// `nameReadFails` answers the read of the name with a server error.
+const relationshipRefusedWith = (relationshipAnswer, { holder = HELD, owners = [], listed = [], nameReadFails = false } = {}) => (method, asked) => {
+ let m;
+ if (method === 'GET' && (m = /^\/EntityDefinitions\(LogicalName='(contoso_project|contoso_task)'\)\/(OneToMany|ManyToOne|ManyToMany)Relationships\?\$select=[\w,]+$/.exec(asked))) {
+ if (m[1] === 'contoso_task' && m[2] === 'ManyToOne') return ok({ value: owners });
+ if (m[1] === 'contoso_project' && m[2] === 'OneToMany') return ok({ value: listed });
+ return ok({ value: [] });
+ }
+ if (method === 'GET' && asked === `/RelationshipDefinitions(SchemaName='${SCHEMA}')?$select=SchemaName,RelationshipType`) {
+ if (nameReadFails) return answer(500, GENERIC, 'An unexpected error occurred.');
+ return holder ? ok({ SchemaName: SCHEMA, RelationshipType: 'OneToManyRelationship' }) : absent(`RelationshipMetadataBase With Id = SchemaName='${SCHEMA}' does not exist.`);
+ }
+ if (method === 'GET' && holder && asked === `/RelationshipDefinitions(SchemaName='${SCHEMA}')/Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata?$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute`) {
+ return ok(holder);
+ }
+ if (method === 'POST' && asked === '/RelationshipDefinitions') return relationshipAnswer;
+ return undefined;
+};
+
+test('a relationship create refused in Spanish because the name is taken (0x8004432B) reuses the declared relationship, exactly as the English refusal does', async () => {
+ const english = await build(RELATED, relationshipRefusedWith(refused('0x8004432B', 'A relationship with the specified name already exists. Please specify a unique name.')));
+ assert.deepStrictEqual(english.unmodelled, []);
+ assert.strictEqual(english.error, undefined, english.error && english.error.message);
+ assert.deepStrictEqual(english.steps, ['skip relationship 1:N contoso_project->contoso_task (exists)'], 'the relationship that holds the name is the declared one');
+ // The platform's reference spells the code with a capital B; an answer may spell it either way.
+ for (const code of ['0x8004432B', '0x8004432b']) {
+ const run = await build(RELATED, relationshipRefusedWith(refused(code, 'Ya existe una relacion con el nombre especificado. Especifique un nombre unico.')));
+ assert.strictEqual(run.error, undefined, `${code}: ${run.error && run.error.message}`);
+ assert.deepStrictEqual(outcomeOf(run), outcomeOf(english), `${code}: the same steps, warnings, requests and result as the English answer`);
+ }
+});
+
+test('a relationship refused in Spanish because the name is taken by ANOTHER relationship stops the build and names it, as the English refusal does: the code is not a proof', async () => {
+ const other = { ...HELD, ReferencingAttribute: 'contoso_ownerid' };
+ const english = await build(RELATED, relationshipRefusedWith(refused('0x8004432B', 'A relationship with the specified name already exists. Please specify a unique name.'), { holder: other }));
+ const spanish = await build(RELATED, relationshipRefusedWith(refused('0x8004432B', 'Ya existe una relacion con el nombre especificado. Especifique un nombre unico.'), { holder: other }));
+ for (const [language, run] of [['English', english], ['Spanish', spanish]]) {
+ assert.deepStrictEqual(run.unmodelled, [], language);
+ assert.ok(run.error instanceof BuildHalt, `${language}: ${run.error && run.error.message}`);
+ assert.match(run.error.message, /relationship schema name 'contoso_project_contoso_task' is already used by 1:N contoso_project -> contoso_task \(lookup contoso_ownerid\)/, language);
+ assert.deepStrictEqual(run.steps, ['error relationship 1:N contoso_project->contoso_task'], language);
+ }
+ assert.deepStrictEqual(spanish.requests, english.requests, 'the same reads identify the relationship');
+});
+
+test('a relationship refused in Spanish because its lookup column exists (0x80060304) looks for the relationship that owns the column, as the English refusal does', async () => {
+ // The name is free; the lookup column belongs to a relationship of another name, which the build names so the spec can reuse it.
+ const owners = [{ SchemaName: 'contoso_task_project', ReferencedEntity: 'contoso_project', ReferencingAttribute: 'contoso_projectid' }];
+ const english = await build(RELATED, relationshipRefusedWith(refused('0x80060304', 'Attribute contoso_projectid already exists for entity contoso_task.'), { holder: null, owners }));
+ const spanish = await build(RELATED, relationshipRefusedWith(refused('0x80060304', 'El atributo contoso_projectid ya existe para la entidad contoso_task.'), { holder: null, owners }));
+ for (const [language, run] of [['English', english], ['Spanish', spanish]]) {
+ assert.deepStrictEqual(run.unmodelled, [], language);
+ assert.ok(run.error instanceof BuildHalt, `${language}: ${run.error && run.error.message}`);
+ assert.match(run.error.message, /lookup 'contoso_projectid' on 'contoso_task' already belongs to relationship 'contoso_task_project' .*set relationships\[0\]\.schemaName to 'contoso_task_project' to reuse it/, language);
+ assert.deepStrictEqual(run.steps, ['error relationship 1:N contoso_project->contoso_task'], language);
+ }
+ assert.deepStrictEqual(spanish.requests, english.requests, 'the same reads look for the owner');
+});
+
+test('a relationship refused in another language with a code that does not say the relationship or its lookup exists stops the build at once, as before', async () => {
+ for (const [what, relationshipAnswer] of [
+ // An N:N makes a table for its links; the build does not look for a relationship behind a table that exists.
+ ['the code of a table that exists', refused('0x8009050d', 'Ya existen las entidades: contoso_project_contoso_task.')],
+ ['the code of a schema name that is not unique, a table create\'s', refused('0x80044363', 'El nombre de esquema contoso_project_contoso_task para el tipo EntityRelationship no es unico.')],
+ ['the code of an alternate key that exists', refused('0x80060893', 'Ya existe una clave de entidad con el nombre contoso_projectid en la entidad contoso_task.')],
+ ['the generic code', refused(GENERIC, 'Ya existe una relacion con el nombre especificado.')],
+ ]) {
+ const run = await build(RELATED, relationshipRefusedWith(relationshipAnswer));
+ assertStopsAt(run, 'relationship 1:N contoso_project->contoso_task', relationshipAnswer.body.error.message, what);
+ assert.ok(!run.requests.some((request) => request.startsWith('GET /RelationshipDefinitions(')), `${what}: the holder of the name is not read — ${run.requests.join(' | ')}`);
+ }
+});
+
+// What an environment answered the create of a 1:N that exists (live-captured, names replaced): the navigation property the create names
+// after the relationship's schema name is not unique on the table. No English words of the rule match it, so such a relationship stopped
+// the build in every language. And the same refusal in words of another language.
+const NAVIGATION_NOT_UNIQUE = `NavigationPropertyName ${SCHEMA} is not unique within an entity`;
+const NAVIGATION_NOT_UNIQUE_ES = `NavigationPropertyName ${SCHEMA} no es unico dentro de una entidad`;
+
+test('a 1:N create refused because its navigation property is not unique (0x80072551, the answer to an existing 1:N\'s create, live) reuses the declared relationship once the read of its name proves it — in English and in Spanish alike', async () => {
+ const english = await build(RELATED, relationshipRefusedWith(refused('0x80072551', NAVIGATION_NOT_UNIQUE)));
+ assert.deepStrictEqual(english.unmodelled, []);
+ assert.strictEqual(english.error, undefined, english.error && english.error.message);
+ assert.deepStrictEqual(english.steps, ['skip relationship 1:N contoso_project->contoso_task (exists)'], 'the relationship that holds the name is the declared one');
+ // The same reads prove it as for a refusal of the name: the read of the relationship of that name, and its typed read.
+ const byName = await build(RELATED, relationshipRefusedWith(refused('0x8004432B', 'A relationship with the specified name already exists. Please specify a unique name.')));
+ assert.deepStrictEqual(outcomeOf(english), outcomeOf(byName), 'the same steps, warnings, requests and result as a refusal of the name');
+ const spanish = await build(RELATED, relationshipRefusedWith(refused('0x80072551', NAVIGATION_NOT_UNIQUE_ES)));
+ assert.strictEqual(spanish.error, undefined, spanish.error && spanish.error.message);
+ assert.deepStrictEqual(outcomeOf(spanish), outcomeOf(english), 'the same steps, warnings, requests and result as the English answer');
+});
+
+test('a 1:N refused with 0x80072551 whose name is held by ANOTHER relationship stops the build and names it, in English and in Spanish: the code is not a proof', async () => {
+ const other = { ...HELD, ReferencingAttribute: 'contoso_ownerid' };
+ for (const [language, words] of [['English', NAVIGATION_NOT_UNIQUE], ['Spanish', NAVIGATION_NOT_UNIQUE_ES]]) {
+ const run = await build(RELATED, relationshipRefusedWith(refused('0x80072551', words), { holder: other }));
+ assert.deepStrictEqual(run.unmodelled, [], language);
+ assert.ok(run.error instanceof BuildHalt, `${language}: ${run.error && run.error.message}`);
+ assert.match(run.error.message, /relationship schema name 'contoso_project_contoso_task' is already used by 1:N contoso_project -> contoso_task \(lookup contoso_ownerid\)/, language);
+ assert.deepStrictEqual(run.steps, ['error relationship 1:N contoso_project->contoso_task'], language);
+ }
+});
+
+test('a 1:N refused with 0x80072551 whose navigation property a relationship of ANOTHER name holds, the name itself being free, stops the build in English and in Spanish: nothing is reused on the code', async () => {
+ // The referenced table lists a relationship of another name over another lookup — the one in the way. The read of the declared name finds
+ // nothing, no relationship owns the declared lookup column, the name is read twice more, and the build stops.
+ const old = { SchemaName: 'contoso_project_tasks_old', ReferencingEntity: 'contoso_task', ReferencingAttribute: 'contoso_oldprojectid' };
+ const owners = [{ SchemaName: 'contoso_project_tasks_old', ReferencedEntity: 'contoso_project', ReferencingAttribute: 'contoso_oldprojectid' }];
+ const nameRead = `GET /RelationshipDefinitions(SchemaName='${SCHEMA}')?$select=SchemaName,RelationshipType`;
+ for (const [language, words] of [['English', NAVIGATION_NOT_UNIQUE], ['Spanish', NAVIGATION_NOT_UNIQUE_ES]]) {
+ const run = await build(RELATED, relationshipRefusedWith(refused('0x80072551', words), { holder: null, listed: [old], owners }));
+ assert.deepStrictEqual(run.unmodelled, [], language);
+ assert.ok(run.error instanceof BuildHalt, `${language}: ${run.error && run.error.message}`);
+ assert.match(run.error.message, /relationship schema name 'contoso_project_contoso_task' is already used by a relationship the build could not identify\. Give it an explicit "schemaName"\./, language);
+ assert.deepStrictEqual(run.steps, ['error relationship 1:N contoso_project->contoso_task'], language);
+ assert.strictEqual(run.requests.filter((request) => request === nameRead).length, 3, `${language}: the name was read, and read twice again`);
+ }
+});
+
+test('a 1:N refused with 0x80072551 is not skipped when the read of its name cannot prove the declared relationship — an incomplete answer, a read that fails — in English and in Spanish', async () => {
+ // Only the declared relationship, proven by the read, is a skip (`sameRelationshipExists`). The build's own words for these two stops say
+ // "already exists", which the English rule would read: the proof, not the words, is what the skip is held to.
+ for (const [what, options, stop] of [
+ ['an answer that leaves out the referencing table and the lookup', { holder: { SchemaName: SCHEMA, ReferencedEntity: 'contoso_project' } },
+ /relationship schema name 'contoso_project_contoso_task' already exists, but the environment's answer for it is incomplete/],
+ ['a read of the name that fails', { nameReadFails: true },
+ /could not identify the relationship that already uses schema name 'contoso_project_contoso_task'/],
+ ]) {
+ for (const [language, words] of [['English', NAVIGATION_NOT_UNIQUE], ['Spanish', NAVIGATION_NOT_UNIQUE_ES]]) {
+ const run = await build(RELATED, relationshipRefusedWith(refused('0x80072551', words), options));
+ assert.deepStrictEqual(run.unmodelled, [], `${what}, ${language}`);
+ assert.ok(run.error instanceof BuildHalt, `${what}, ${language}: ${run.error && run.error.message}`);
+ assert.match(run.error.message, stop, `${what}, ${language}`);
+ assert.deepStrictEqual(run.steps, ['error relationship 1:N contoso_project->contoso_task'], `${what}, ${language}`);
+ }
+ }
+});
+
+// --- an N:N the probe did not see -------------------------------------------------------------------------------------------------
+// An N:N's identity includes the table that holds its links. Its create reads the holder of its name on the reference's code for a taken
+// name; the 1:N's navigation-property code is not listed for it — an N:N names navigation properties too, but the answer to an existing
+// N:N's create has not been captured — and the test below pins that boundary, not a fact about the platform.
+const INTERSECT = 'contoso_project_task_links';
+const RELATED_NN = { solution: SOLUTION, entities: [], relationships: [{ type: 'ManyToMany', schemaName: SCHEMA, entity1: 'contoso_project', entity2: 'contoso_task', intersectEntityName: INTERSECT }] };
+const NN_SELECT = 'SchemaName,Entity1LogicalName,Entity2LogicalName,IntersectEntityName,Entity1IntersectAttribute,Entity2IntersectAttribute';
+const HELD_NN = { SchemaName: SCHEMA, Entity1LogicalName: 'contoso_project', Entity2LogicalName: 'contoso_task', IntersectEntityName: INTERSECT, Entity1IntersectAttribute: 'contoso_projectid', Entity2IntersectAttribute: 'contoso_taskid' };
+const manyToManyRefusedWith = (relationshipAnswer) => (method, asked) => {
+ if (method === 'GET' && asked === `/EntityDefinitions(LogicalName='contoso_project')/ManyToManyRelationships?$select=${NN_SELECT}`) return ok({ value: [] });
+ if (method === 'GET' && asked === `/RelationshipDefinitions(SchemaName='${SCHEMA}')?$select=SchemaName,RelationshipType`) return ok({ SchemaName: SCHEMA, RelationshipType: 'ManyToManyRelationship' });
+ if (method === 'GET' && asked === `/RelationshipDefinitions(SchemaName='${SCHEMA}')/Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata?$select=${NN_SELECT}`) return ok(HELD_NN);
+ if (method === 'POST' && asked === '/RelationshipDefinitions') return relationshipAnswer;
+ return undefined;
+};
+
+test('an N:N create refused in Spanish because its name is taken (0x8004432B) reuses the declared N:N once the read proves it, exactly as the English refusal does', async () => {
+ const english = await build(RELATED_NN, manyToManyRefusedWith(refused('0x8004432B', 'A relationship with the specified name already exists. Please specify a unique name.')));
+ assert.deepStrictEqual(english.unmodelled, []);
+ assert.strictEqual(english.error, undefined, english.error && english.error.message);
+ assert.deepStrictEqual(english.steps, ['skip relationship N:N contoso_project<->contoso_task (exists)'], 'the N:N that holds the name is the declared one');
+ const spanish = await build(RELATED_NN, manyToManyRefusedWith(refused('0x8004432B', 'Ya existe una relacion con el nombre especificado. Especifique un nombre unico.')));
+ assert.strictEqual(spanish.error, undefined, spanish.error && spanish.error.message);
+ assert.deepStrictEqual(outcomeOf(spanish), outcomeOf(english), 'the same steps, warnings, requests and result as the English answer');
+});
+
+test('an N:N create refused with 0x80072551, the 1:N create\'s navigation-property code, stops the build at once in English and in Spanish: the holder of the name is not read', async () => {
+ for (const [language, words] of [['English', NAVIGATION_NOT_UNIQUE], ['Spanish', NAVIGATION_NOT_UNIQUE_ES]]) {
+ const run = await build(RELATED_NN, manyToManyRefusedWith(refused('0x80072551', words)));
+ assertStopsAt(run, 'relationship N:N contoso_project<->contoso_task', words, language);
+ assert.ok(!run.requests.some((request) => request.startsWith('GET /RelationshipDefinitions(')), `${language}: the holder of the name is not read — ${run.requests.join(' | ')}`);
+ }
+});
+
+// The codes are compared as the plugin reads them from an answer — lower case (the platform writes them in either case) — so a code
+// written in capitals here would never match. Each create that reads an already-exists answer has its own list, and the two codes that are
+// broader than a create are listed for one create each: where a read that follows the refusal decides.
+test('each create\'s already-exists codes are written as the plugin reads them: lower-case 0x and eight hex digits, none listed for a create it does not answer', () => {
+ assert.deepStrictEqual(Object.keys(ALREADY_EXISTS_CODES).sort(), ['alternateKey', 'column', 'manyToManyRelationship', 'oneToManyRelationship', 'statusReason', 'table']);
+ for (const [create, codes] of Object.entries(ALREADY_EXISTS_CODES)) {
+ assert.ok(codes.size > 0, create);
+ for (const code of codes) assert.match(code, /^0x[0-9a-f]{8}$/, `${create}: ${code}`);
+ assert.ok(!codes.has(GENERIC), `${create}: the generic code says nothing about what failed`);
+ }
+ assert.deepStrictEqual([...ALREADY_EXISTS_CODES.alternateKey], ['0x80060893']);
+ assert.deepStrictEqual([...ALREADY_EXISTS_CODES.statusReason], ['0x80044310']);
+ assert.deepStrictEqual([...ALREADY_EXISTS_CODES.table].sort(), ['0x80044363', '0x8004700b', '0x8009050d']);
+ assert.deepStrictEqual([...ALREADY_EXISTS_CODES.column].sort(), ['0x80047013', '0x80060304']);
+ assert.deepStrictEqual([...ALREADY_EXISTS_CODES.oneToManyRelationship].sort(), ['0x8004432b', '0x80047013', '0x80060304', '0x80072551']);
+ assert.deepStrictEqual([...ALREADY_EXISTS_CODES.manyToManyRelationship], ['0x8004432b']);
+ for (const [code, only] of [['0x80044363', 'table'], ['0x80072551', 'oneToManyRelationship']]) {
+ assert.deepStrictEqual(Object.keys(ALREADY_EXISTS_CODES).filter((create) => ALREADY_EXISTS_CODES[create].has(code)), [only], `${code} is listed for one create only`);
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/app-ai-description-real-bundle.test.js b/plugins/model-apps/scripts/tests/app-ai-description-real-bundle.test.js
index 33ffa68b8..8728754d8 100644
--- a/plugins/model-apps/scripts/tests/app-ai-description-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/app-ai-description-real-bundle.test.js
@@ -92,10 +92,11 @@ async function freshSdk({ ai, componentstate = 0, headerStatus = 204, sitemapSta
return { status: 200, headers: { etag: state.etag }, body: multi ? { value: [sitemapRow()] } : sitemapRow() };
}
if (/\/appmodules/.test(url)) {
- if (state.headerReadFails && /RetrieveUnpublished/i.test(url)) return { status: 500, headers: {}, body: { error: { message: 'transient failure' } } };
- // The halt's own draft read. While a draft exists, put the PUBLISHED row first, so the test proves
- // the unpublished layer is found wherever it sits: the live platform returned only the draft row,
- // but does not document that. The SDK's own reads never select componentstate, so they are unaffected.
+ const select = (new URL(url).searchParams.get('$select') || '').split(',');
+ // Fault only the push's header comparison, not its independent current-layer ownership proof.
+ if (state.headerReadFails && /RetrieveUnpublished/i.test(url) && select.includes('name')) return { status: 500, headers: {}, body: { error: { message: 'transient failure' } } };
+ // While a draft exists, put the PUBLISHED row first: the SDK must choose componentstate 1
+ // for its current-layer proof regardless of row order.
if (/componentstate/.test(decodeURIComponent(url)) && state.componentstate === 1) {
return { status: 200, headers: {}, body: { value: [{ ...appRow(), componentstate: 0 }, appRow()] } };
}
@@ -257,7 +258,8 @@ test('REAL BUNDLE: a header row moved after the fetch is a concurrent edit: refu
assert.strictEqual(res.saved, false);
assert.strictEqual(res.error && res.error.code, 'VERSION_CONFLICT');
assert.throws(() => requireSuccessfulPush(res, 'app Probe'), (e) => e.code === 'version-conflict');
- assert.ok(!reads.slice(readsBefore).some((u) => /componentstate/.test(decodeURIComponent(u))), 'not re-diagnosed as a pending draft');
+ assert.deepStrictEqual(reads.slice(readsBefore).map((u) => new URL(u).searchParams.get('$select')).filter((s) => s && s.includes('componentstate')),
+ ['appmoduleid,appmoduleidunique,componentstate'], 'only the SDK current-layer proof, never a wrapper pending-draft re-diagnosis');
assert.strictEqual(state.ai, 'Route Q1', 'nothing written');
// The copy keeps this run's edit. The app is a composite artifact whose stored token is the sitemap's, and a
// header-only change does not move the sitemap, so a plain re-fetch keeps the copy as it is; the next run
@@ -280,7 +282,8 @@ test('REAL BUNDLE: a sitemap 412 after the header committed is a concurrent edit
assert.strictEqual(res.saved, false);
assert.match(String(res.error && res.error.detail), /^Version conflict \(412\) from https:\/\/contoso\.crm\.dynamics\.com\/api\/data\/v[\d.]+\/sitemaps\(55555555-5555-5555-5555-555555555555\)$/);
assert.throws(() => requireSuccessfulPush(res, 'app Probe'), (e) => e.code === 'version-conflict');
- assert.ok(!reads.slice(readsBefore).some((u) => /componentstate/.test(decodeURIComponent(u))), 'not re-diagnosed as a pending draft');
+ assert.deepStrictEqual(reads.slice(readsBefore).map((u) => new URL(u).searchParams.get('$select')).filter((s) => s && s.includes('componentstate')),
+ ['appmoduleid,appmoduleidunique,componentstate'], 'only the SDK current-layer proof, never a wrapper pending-draft re-diagnosis');
// Someone saved the sitemap: the server has moved, and the kept copy stops the re-run's plain fetch.
state.etag = 'W/"9"';
await assert.rejects(sdk.fetchArtifact('app', APP_ID), (e) => e && e.code === 'LOCAL_EDITS_WOULD_BE_LOST');
diff --git a/plugins/model-apps/scripts/tests/app-delete-real-bundle.test.js b/plugins/model-apps/scripts/tests/app-delete-real-bundle.test.js
index d28094a95..40c7ac1ba 100644
--- a/plugins/model-apps/scripts/tests/app-delete-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/app-delete-real-bundle.test.js
@@ -1,8 +1,9 @@
'use strict';
// REAL-BUNDLE contract tests for app deletion (teardown's primary destructive step).
//
-// An app is TWO rows: an `appmodule` and a `sitemaps` row, with NO lookup between them and no
-// server-side cascade — the only link is `sitemap.sitemapnameunique === appmodule.uniquename`.
+// An app is TWO rows: an `appmodule` and a `sitemaps` row, with no server-side cascade. Its CURRENT
+// appmoduleidunique layer links type-62 appmodulecomponents to the sitemap; only an absent component
+// permits a safe same-name fallback. A component-linked sitemap may legitimately have another name.
// Deleting just the appmodule strands the sitemap forever AND, because `sitemapnameunique` is
// unique-constrained, permanently BURNS that unique name: a later build of an app with the same
// name fails with "The name <x> is already in use by an existing site map", which the user cannot
@@ -13,9 +14,8 @@
// The SDK now deletes both rows in ONE atomic OData `$batch` change set, so it requires an
// `HttpClient.postRaw` and refuses (APP_DELETE_NOT_ATOMIC) without one. It also fails closed on
// every read it cannot trust: the app must carry an ETag and the sitemap's by-id read must return its
-// ROW token (so each DELETE can be conditional on the row actually inspected), and the sitemap must
-// still carry the app's `sitemapnameunique` (so a row re-pointed between read and delete is not
-// destroyed).
+// ROW token (so each DELETE can be conditional on the row actually inspected). Shared or changed links
+// are refused; a name-fallback candidate must still carry the app's name.
const test = require('node:test');
const assert = require('node:assert');
const os = require('node:os');
@@ -24,6 +24,7 @@ const fs = require('node:fs');
const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
const { createAzHttpClient } = require('../lib/sdk-http-client.js');
+const { appSitemapLinkRows } = require('./helpers/app-sitemap-link-rows.js');
const APP_ID = '11111111-1111-1111-1111-111111111111';
const APP_UNIQUE_ID = '22222222-2222-2222-2222-222222222222';
@@ -73,7 +74,7 @@ function batchResponseFor(requestBody, statusFor = () => 204) {
/** The rows a fake Dataverse hands back, shared by the injected-client and real-transport fakes. */
function appRow(opts = {}) {
- const row = { appmoduleid: APP_ID, appmoduleidunique: APP_UNIQUE_ID, uniquename: APP_UNIQUE, name: 'Support Desk' };
+ const row = { appmoduleid: APP_ID, appmoduleidunique: APP_UNIQUE_ID, componentstate: 0, uniquename: APP_UNIQUE, name: 'Support Desk' };
if (!opts.noAppEtag) row['@odata.etag'] = 'W/"1001"';
return row;
}
@@ -104,6 +105,15 @@ function sitemapByIdResponse(opts = {}) {
}
const SITEMAP_BY_ID = /\/sitemaps\([^)]+\)/;
+function linkRows(url, opts = {}) {
+ return appSitemapLinkRows(url, {
+ apps: [appRow(opts)],
+ components: opts.noSitemap || opts.foreignSitemap ? [] : [{
+ _appmoduleidunique_value: APP_UNIQUE_ID, objectid: SITEMAP_ID, componenttype: 62,
+ }],
+ });
+}
+
/**
* A real SDK over a fake Dataverse that models the two-row app. `opts`:
* appReadStatus - HTTP status for GET /appmodules(<id>) (models a transient read failure)
@@ -129,8 +139,9 @@ async function freshSdk(opts = {}) {
// argument. e.g. /EntityDefinitions(LogicalName='appmodulecomponent')?$select=EntitySetName
const meta = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);
if (meta) return { status: 200, headers: {}, body: { LogicalName: meta[1], EntitySetName: `${meta[1]}s` } };
- // By-id app retrieve — the source of the `uniquename` the sitemap is linked by, and of the
- // ETag the conditional delete is issued against.
+ const linked = linkRows(url, opts);
+ if (linked !== undefined) return { status: 200, headers: {}, body: { value: linked } };
+ // By-id app retrieve supplies the name-fallback identity and the conditional delete's ETag.
if (/\/appmodules\([^)]+\)/.test(url)) {
const status = opts.appReadStatus || 200;
if (status !== 200) return { status, headers: {}, body: null };
@@ -209,8 +220,7 @@ test('REAL BUNDLE: both rows are deleted in ONE atomic $batch change set, never
});
test('REAL BUNDLE: the sitemap is resolved BEFORE the app delete, never after', async () => {
- // Afterwards the `uniquename` -> sitemap link is unrecoverable, so ordering is the whole
- // guarantee: read first, then destroy.
+ // Afterwards the app's layer/component link is unrecoverable: read first, then destroy.
const { sdk, calls } = await freshSdk();
await sdk.deleteAppCascade(APP_ID, APP_UNIQUE_ID);
const sitemapLookup = calls.findIndex((c) => c.method === 'GET' && c.url.includes('/sitemaps'));
@@ -235,9 +245,9 @@ test('REAL BUNDLE: an INCONCLUSIVE sitemap lookup refuses to delete the app (fai
}
});
-test("REAL BUNDLE: a sitemap that no longer carries this app's unique name is NOT deleted", async () => {
- // Ownership is name equality only. If the row was re-pointed between the read and the delete it
- // belongs to a different app now, and destroying it would be cross-app data loss.
+test("REAL BUNDLE: a NAME-FALLBACK candidate renamed after lookup is NOT deleted", async () => {
+ // No component links this fixture, so the fallback name must survive the subsequent by-id read.
+ // A valid type-62 link with a different name is a separate, supported identity.
const { sdk, calls } = await freshSdk({ foreignSitemap: true });
await assert.rejects(() => sdk.deleteAppCascade(APP_ID, APP_UNIQUE_ID), /no longer this app|APP_SITEMAP_UNRESOLVED/);
assert.strictEqual(deletedPaths(calls).length, 0, 'nothing may be deleted when ownership cannot be proven');
@@ -326,6 +336,8 @@ test('REAL BUNDLE + REAL TRANSPORT: the plugin HttpClient satisfies the SDK atom
wire.push({ url, method, body, headers });
const meta = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);
if (meta) return { statusCode: 200, headers: {}, body: JSON.stringify({ LogicalName: meta[1], EntitySetName: `${meta[1]}s` }) };
+ const linked = linkRows(url);
+ if (linked !== undefined) return { statusCode: 200, headers: {}, body: JSON.stringify({ value: linked }) };
if (/\/\$batch$/.test(url)) return { statusCode: 200, headers: {}, body: batchResponseFor(body) };
if (/\/appmodules\([^)]+\)/.test(url)) return { statusCode: 200, headers: {}, body: JSON.stringify(appRow()) };
// The row token travels ONLY in the response header here (real Dataverse also puts it in the
@@ -371,6 +383,8 @@ test('REAL BUNDLE + REAL TRANSPORT: an app delete whose change set lost a SQL de
const request = async ({ url, body }) => {
const meta = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);
if (meta) return { statusCode: 200, headers: {}, body: JSON.stringify({ LogicalName: meta[1], EntitySetName: `${meta[1]}s` }) };
+ const linked = linkRows(url);
+ if (linked !== undefined) return { statusCode: 200, headers: {}, body: JSON.stringify({ value: linked }) };
if (/\/\$batch$/.test(url)) {
batches.push(body);
return batches.length === 1 ? { statusCode: 500, headers: {}, body: deadlocked } : { statusCode: 200, headers: {}, body: batchResponseFor(body) };
@@ -414,6 +428,8 @@ for (const [shape, refusal] of [
const request = async ({ url, body }) => {
const meta = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(url);
if (meta) return { statusCode: 200, headers: {}, body: JSON.stringify({ LogicalName: meta[1], EntitySetName: `${meta[1]}s` }) };
+ const linked = linkRows(url);
+ if (linked !== undefined) return { statusCode: 200, headers: {}, body: JSON.stringify({ value: linked }) };
if (/\/\$batch$/.test(url)) {
batches.push(body);
return batches.length === 1 ? refusal : { statusCode: 200, headers: {}, body: batchResponseFor(body) };
diff --git a/plugins/model-apps/scripts/tests/app-header-text-real-bundle.test.js b/plugins/model-apps/scripts/tests/app-header-text-real-bundle.test.js
index f5a55ea3b..56f2a6fc4 100644
--- a/plugins/model-apps/scripts/tests/app-header-text-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/app-header-text-real-bundle.test.js
@@ -43,6 +43,7 @@ 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';
+const ICON_ID = '77777777-7777-4777-8777-777777777777';
const SITEMAP_XML = '<SiteMap IntroducedVersion="7.0.0.0"><Area Id="area_0" ShowGroups="true"><Titles><Title LCID="1033" Title="Main" /></Titles>'
+ '<Group Id="group_0_0"><Titles><Title LCID="1033" Title="Main" /></Titles>'
+ '<SubArea Id="sub_0_0_0" Entity="new_torder" Client="All" Sku="All"><Titles><Title LCID="1033" Title="Orders" /></Titles></SubArea>'
@@ -65,8 +66,19 @@ async function freshSdk({ name = 'Probe', description = 'Tickets', headerStatus
const state = { name, description, headerStatus, etag: 'W/"1"', ai: undefined, refused: [], fault: null };
const appRow = () => ({ appmoduleid: APP_ID, appmoduleidunique: APP_IDUNIQUE, name: state.name, uniquename: APP_UNIQUE, description: state.description, componentstate: 0, ...(state.ai !== undefined ? { aiappdescription: state.ai } : {}), '@odata.etag': state.etag });
const sitemapRow = () => ({ sitemapid: SITEMAP_ID, sitemapnameunique: APP_UNIQUE, sitemapxml: SITEMAP_XML, '@odata.etag': state.etag });
+ // The web resource a first build creates (the generated app icon) is held in two layers, as the platform holds it: the POST writes the
+ // SAVED content, a PublishXml that names the row (`<webresources><webresource>{id}</webresource></webresources>`) copies it to the
+ // PUBLISHED layer, and the plain read by id — the read-back the SDK makes after its publish, `GET /webresourceset({id})?$select=content`
+ // — answers the published content. A row no publish has named answers 404 here (assumed: the plain read of a never-published web resource
+ // is not measured; the build's own create always publishes).
+ const webResources = new Map();
const httpClient = {
get: async (url) => {
+ const wr = /\/webresourceset\(([0-9a-f-]{36})\)\?\$select=content$/i.exec(String(url));
+ if (wr) {
+ const row = webResources.get(wr[1].toLowerCase());
+ return row && row.published !== undefined ? { status: 200, headers: {}, body: { webresourceid: wr[1], content: row.published } } : { status: 404, headers: {}, body: { error: { message: 'Does Not Exist' } } };
+ }
// The SDK's own comparison read of the header: the one read of the app module row that selects the routing description, made inside its push of an app.
const fault = state.fault;
if (fault && fault.armed && fault.reads.length === 0 && /\/appmodules\/Microsoft\.Dynamics\.CRM\.RetrieveUnpublishedMultiple\(\)/i.test(url) && /aiappdescription/.test(url)) {
@@ -93,7 +105,20 @@ async function freshSdk({ name = 'Probe', description = 'Tickets', headerStatus
}
return { status: 200, headers: {}, body: { value: [] } };
},
- post: async (url, body) => { writes.push({ verb: 'post', url: String(url), body }); return { status: 204, headers: { 'odata-entityid': `https://x/y(${APP_ID})` }, body: {} }; },
+ post: async (url, body) => {
+ writes.push({ verb: 'post', url: String(url), body });
+ if (/\/webresourceset$/.test(String(url))) {
+ webResources.set(ICON_ID, { saved: body.content });
+ return { status: 204, headers: { 'odata-entityid': `https://contoso.crm.dynamics.com/api/data/v9.2/webresourceset(${ICON_ID})` }, body: {} };
+ }
+ if (/\/PublishXml$/.test(String(url))) {
+ for (const [, id] of String((body && body.ParameterXml) || '').matchAll(/<webresource>([^<]+)<\/webresource>/g)) {
+ const row = webResources.get(id.toLowerCase());
+ if (row) row.published = row.saved;
+ }
+ }
+ return { status: 204, headers: { 'odata-entityid': `https://x/y(${APP_ID})` }, body: {} };
+ },
patch: async (url, body, options) => {
const ifMatch = (options && options.headers && options.headers['If-Match']) || null;
writes.push({ verb: 'patch', url: String(url), body, ifMatch });
diff --git a/plugins/model-apps/scripts/tests/app-header-text-transport.test.js b/plugins/model-apps/scripts/tests/app-header-text-transport.test.js
index 8b410a234..e466b05fe 100644
--- a/plugins/model-apps/scripts/tests/app-header-text-transport.test.js
+++ b/plugins/model-apps/scripts/tests/app-header-text-transport.test.js
@@ -174,17 +174,23 @@ test('REAL BUNDLE + REAL CLIENT: the change set the SDK itself renders (createCo
const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
const DELETE_APP_UNIQUE_ID = '22222222-2222-2222-2222-222222222222';
const DELETE_SITEMAP_ID = '33333333-3333-3333-3333-333333333333';
+const { appSitemapLinkRows } = require('./helpers/app-sitemap-link-rows.js');
async function deleteAppOver(sdkModule) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'app-header-transport-'));
tempDirs.push(dir);
const wire = [];
- const appRow = { appmoduleid: APP, appmoduleidunique: DELETE_APP_UNIQUE_ID, uniquename: 'co_supportdesk', name: 'Support Desk', '@odata.etag': 'W/"1001"' };
+ const appRow = { appmoduleid: APP, appmoduleidunique: DELETE_APP_UNIQUE_ID, componentstate: 0, uniquename: 'co_supportdesk', name: 'Support Desk', '@odata.etag': 'W/"1001"' };
const sitemapRow = { '@odata.etag': 'W/"2003"', sitemapid: DELETE_SITEMAP_ID, sitemapnameunique: 'co_supportdesk', sitemapxml: '<SiteMap></SiteMap>' };
const ok = (body, headers = {}) => ({ statusCode: 200, headers, body: JSON.stringify(body) });
const request = async (req) => {
wire.push(req);
const meta = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(req.url);
if (meta) return ok({ LogicalName: meta[1], EntitySetName: `${meta[1]}s` });
+ const linked = appSitemapLinkRows(req.url, {
+ apps: [appRow],
+ components: [{ _appmoduleidunique_value: DELETE_APP_UNIQUE_ID, objectid: DELETE_SITEMAP_ID, componenttype: 62 }],
+ });
+ if (linked !== undefined) return ok({ value: linked });
if (/\/\$batch$/.test(req.url)) return changeSetAnswer(req);
if (/\/appmodules\([^)]+\)/.test(req.url)) return ok(appRow);
if (/\/sitemaps\([^)]+\)/.test(req.url)) return ok({ sitemapid: DELETE_SITEMAP_ID }, { etag: 'W/"2002"' });
diff --git a/plugins/model-apps/scripts/tests/app-navigation-build.test.js b/plugins/model-apps/scripts/tests/app-navigation-build.test.js
index b1f08a4c2..b4a982bdf 100644
--- a/plugins/model-apps/scripts/tests/app-navigation-build.test.js
+++ b/plugins/model-apps/scripts/tests/app-navigation-build.test.js
@@ -7,11 +7,14 @@
// all, validates, so the build of a new app used to fail at the app step AFTER the solution, tables, views and forms
// were written. These tests drive the real engine (and the real CLI wrapper) with fakes that record EVERY call, and pin:
// * each refused shape, in the dry run and on --apply, and that --apply wrote nothing before it halted;
+// * a NEW app whose navigation is pages only is built by the whole build, which creates its pages first and then the app
+// with them in its first navigation; a run that cannot create the pages first (no pages phase, a changed-only
+// re-upload, a page entry whose page the run does not build) still refuses it, and says why;
// * an existing app is spared the pages-only half, because its navigation is written once the pages exist, and the
// empty half: it is built, with a warning that it is left with no navigation entries, in a run that writes one;
// * a spec with no appShell.areas is refused for every app, since there is nothing to build the sitemap from;
// * a run without the app step is not checked, and an app whose existence cannot be read warns and goes on;
-// * a valid navigation's plan and every request it makes are exactly what they were;
+// * a valid navigation's plan and every request it makes are exactly what they were, and so are an existing app's of pages only;
// * existingAppSitemapIsWritten says what the engine does: the check never refuses a build that would have worked;
// * a dry run that would stop says so in its summary line, with a live plan and without one;
// * the order of the destructive gate and the navigation check for an app that exists.
@@ -22,23 +25,29 @@ const assert = require('node:assert');
const crypto = require('node:crypto');
const fs = require('node:fs');
-const { runSdkBuild, existingAppSitemapIsWritten, planFor, PHASES, BuildHalt } = require('../lib/sdk-build.js');
+const { runSdkBuild, existingAppSitemapIsWritten, pagesFirstRule, planFor, PHASES, BuildHalt } = require('../lib/sdk-build.js');
const { STAGES } = require('../lib/stages.js');
const { buildModelApp, isTransientHalt, discoverOpDiffState } = require('../build-model-app.js');
const { SHAPES, specFor } = require('./helpers/navigation-shapes.js');
const { writesIn, environment, pagesEnvironment, pageBackend, appFolder } = require('./helpers/navigation-fakes.js');
const shapeNamed = (name) => SHAPES.find((s) => s.name === name);
+// Refused for a new app by a run that does not create its pages first (`forNew`), and by the whole build, which does (`forNewPagesFirst`):
+// they differ by the navigation of pages only, which only the whole build builds.
const refusedForNew = SHAPES.filter((s) => s.forNew === 'refuse');
+const refusedInWholeBuild = SHAPES.filter((s) => s.forNewPagesFirst === 'refuse');
// No appShell.areas: appDef throws on it before the app step asks whether the app exists, so no app of any kind is built from it.
const undeclared = SHAPES.filter((s) => s.kind === 'undeclared');
const onlyPages = SHAPES.filter((s) => s.kind === 'pages-only');
// A navigation with no entry: refused for a new app, built for one that exists. Whether the run writes the navigation to that app decides whether
// there is anything to say, so these are the shapes the run's phases matter to.
const emptyNavigations = SHAPES.filter((s) => s.kind === 'empty');
-// Every shape the verdict depends on the app's existence for.
+// Every shape the verdict depends on the app's existence for: in a run that does not create a new app's pages first, and in the whole build, which does.
const dependsOnExistence = SHAPES.filter((s) => s.forUnknown === 'unknown');
+const dependsOnExistenceInWholeBuild = SHAPES.filter((s) => s.forUnknownPagesFirst === 'unknown');
const withPages = ['solution', 'data-model', 'app-shell', 'pages'];
+// The app step without the pages phase: a run that cannot create a new app's pages first.
+const withoutPages = ['solution', 'data-model', 'app-shell'];
const APP_LABEL = 'app module "Support Desk" + sitemap';
const appStep = (items) => items.find((p) => p.label === APP_LABEL);
const navigationWarnings = (warnings) => warnings.filter((w) => /could not be checked/.test(w));
@@ -64,7 +73,7 @@ function assertSaysWhatTheAppIsLeftWith(message, shape) {
}
// ── The dry run ──────────────────────────────────────────────────────────────────────────────────────────────────
-for (const shape of refusedForNew) {
+for (const shape of refusedInWholeBuild) {
test(`dry run, new app — ${shape.name}: the app step is the one that would stop the build, and says why`, async () => {
const spec = specFor(shape);
const env = environment({ app: 'absent' });
@@ -89,6 +98,33 @@ for (const shape of refusedForNew) {
});
}
+// A navigation of pages only, for a NEW app: the whole build creates the pages first and then the app with them, so nothing would stop it.
+for (const shape of onlyPages) {
+ test(`dry run, new app, the whole build — ${shape.name}: nothing stops the build — the pages are created first, then the app with them`, async () => {
+ const spec = specFor(shape);
+ const env = environment({ app: 'absent' });
+ const warnings = [];
+ const result = await runSdkBuild(spec, { sdk: env.sdk, apply: false, warn: (m) => warnings.push(m) });
+ const step = appStep(result.planItems);
+ assert.strictEqual(step.state, 'create', 'the app step is the plain create line');
+ assert.strictEqual(step.wouldHalt, undefined);
+ assert.strictEqual(step.stateWhy, undefined);
+ assert.deepStrictEqual(result.planItems.filter((p) => p.wouldHalt), []);
+ assert.deepStrictEqual(result.planItems.map((p) => p.label), planFor(spec, { phases: PHASES, sampleData: false, publish: false }).map((p) => p.label), 'the plan is the one planFor lists: the same steps, the same total');
+ assert.deepStrictEqual(warnings, [], 'nothing to warn of');
+ assert.deepStrictEqual(writesIn(env.calls), [], 'a dry run writes nothing');
+ });
+ // A run that cannot create the pages first — the app step without the pages phase — still would stop, and says why.
+ test(`dry run, new app, the app step without the pages phase — ${shape.name}: would stop the build, and says it is the pages phase this run lacks`, async () => {
+ const env = environment({ app: 'absent' });
+ const result = await runSdkBuild(specFor(shape), { sdk: env.sdk, apply: false, phases: withoutPages });
+ const step = appStep(result.planItems);
+ assert.strictEqual(step.wouldHalt, true);
+ assertSaysWhatIsWrong(step.stateWhy, shape);
+ assert.match(step.stateWhy, /A page entry joins the navigation only once its page exists, and this run does not have the pages phase, which would create them first, so a new app would be created without them/);
+ });
+}
+
for (const shape of onlyPages) {
test(`dry run, existing app — ${shape.name}: nothing stops the build, the pages are written once they exist`, async () => {
const env = environment({ app: 'present' });
@@ -174,7 +210,7 @@ for (const shape of undeclared) {
// What the unknown answer says first is what the navigation holds, which differs by kind; the rest is the same.
const unknownAnswerStarts = (shape) => (shape.kind === 'pages-only' ? /^app "Support Desk": the navigation holds only page entries/ : /^app "Support Desk": the navigation has no entry/);
-for (const shape of dependsOnExistence) {
+for (const shape of dependsOnExistenceInWholeBuild) {
test(`dry run, existence unknown — ${shape.name}: not refused on the stricter rule; says what could not be checked`, async () => {
const spec = specFor(shape);
const warnings = [];
@@ -196,6 +232,27 @@ for (const shape of dependsOnExistence) {
});
}
+// A navigation of pages only depends on the app's existence only in a run that cannot create a new app's pages first: the whole build builds
+// it whichever the answer is, so it has nothing to say when the answer is missing; the app step without the pages phase says what it could not check.
+for (const shape of onlyPages) {
+ test(`dry run, existence unknown — ${shape.name}: the whole build has nothing to check or say; a run without the pages phase says what it could not check`, async () => {
+ const spec = specFor(shape);
+ const warnings = [];
+ const noLivePlan = await runSdkBuild(spec, { sdk: environment().sdk, apply: false, livePlan: false, warn: (m) => warnings.push(m) });
+ assert.strictEqual(appStep(noLivePlan.planItems).wouldHalt, undefined);
+ const unreadable = await runSdkBuild(spec, { sdk: environment({ app: 'unreadable' }).sdk, apply: false, warn: (m) => warnings.push(m) });
+ assert.strictEqual(appStep(unreadable.planItems).state, 'unknown', 'the live plan could not read the app');
+ assert.strictEqual(appStep(unreadable.planItems).wouldHalt, undefined);
+ assert.deepStrictEqual(warnings, [], 'nothing to say: a new app and an existing one are both built');
+
+ const partial = await runSdkBuild(spec, { sdk: environment().sdk, apply: false, livePlan: false, phases: withoutPages, warn: (m) => warnings.push(m) });
+ assert.strictEqual(appStep(partial.planItems).wouldHalt, undefined, 'an unread app is not one that would stop the build');
+ assert.strictEqual(navigationWarnings(warnings).length, 1, JSON.stringify(warnings));
+ assert.match(warnings[0], unknownAnswerStarts(shape));
+ assert.match(warnings[0], /this run does not have the pages phase, which would create them first/);
+ });
+}
+
test('dry run — a run without the app step is not checked: no line is marked, nothing is warned of, the app is not read', async () => {
for (const phases of [STAGES.data, STAGES.ui, STAGES.publish, ['views', 'forms'], ['pages']]) {
for (const shape of refusedForNew) {
@@ -212,13 +269,13 @@ test('dry run — a run without the app step is not checked: no line is marked,
// What the CLI prints for the dry run: the summary counts the step among those that would stop the build, and does not then tell the maker to run it.
test('buildModelApp prints the plan line with its reason, and the summary counts it as one that would stop the build', async () => {
- const shape = shapeNamed('a navigation of pages only');
- const appDir = appFolder(shape.pages);
+ const shape = shapeNamed('areas: []');
+ const appDir = appFolder([]);
try {
const logs = [];
const result = await buildModelApp(specFor(shape), { apply: false, env: 'https://contoso.example', appDir, livePlan: true }, { sdk: environment({ app: 'absent' }).sdk, log: (m) => logs.push(m) });
assert.strictEqual(result.dryRun, true);
- assert.ok(logs.some((l) => /\? unknown app module "Support Desk" \+ sitemap — the build would stop before writing anything: the navigation holds only page entries/.test(l)), logs.join('\n'));
+ assert.ok(logs.some((l) => /\? unknown app module "Support Desk" \+ sitemap — the build would stop before writing anything: the navigation has no entry \(appShell\.areas is empty\)/.test(l)), logs.join('\n'));
assert.ok(logs.some((l) => /▢ dry run — .*\b1 would stop the build\b.*\(\d+ steps\)\. Fix the steps marked \? above, then re-run with --apply to execute\./.test(l)), logs.join('\n'));
assert.ok(!logs.some((l) => /Re-run with --apply to execute/.test(l)), 'a dry run that would stop the build does not say to run it');
@@ -227,6 +284,16 @@ test('buildModelApp prints the plan line with its reason, and the summary counts
assert.ok(!fine.some((l) => /would stop the build/.test(l)), 'a valid navigation is not counted');
assert.ok(fine.some((l) => /▢ dry run — .*\(\d+ steps\)\. Re-run with --apply to execute\./.test(l)), 'and its summary is the one it always was');
} finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+ // A navigation of pages only, for a new app: the whole build builds it, so the dry run counts nothing and invites the apply.
+ const pagesOnly = shapeNamed('a navigation of pages only');
+ const pagesDir = appFolder(pagesOnly.pages);
+ try {
+ const logs = [];
+ await buildModelApp(specFor(pagesOnly), { apply: false, env: 'https://contoso.example', appDir: pagesDir, livePlan: true }, { sdk: environment({ app: 'absent' }).sdk, log: (m) => logs.push(m) });
+ assert.ok(logs.some((l) => /\+ create app module "Support Desk" \+ sitemap$/.test(l)), logs.join('\n'));
+ assert.ok(!logs.some((l) => /would stop the build/.test(l)), logs.join('\n'));
+ assert.ok(logs.some((l) => /▢ dry run — .*\(\d+ steps\)\. Re-run with --apply to execute\./.test(l)), logs.join('\n'));
+ } finally { fs.rmSync(pagesDir, { recursive: true, force: true }); }
});
// With --no-live-plan nothing is read, but the check can still refuse a spec on its own (no appShell.areas): it marks the app step as one that would stop
@@ -250,12 +317,15 @@ test('buildModelApp --no-live-plan: a step marked as one that would stop the bui
});
// ── --apply: refused before anything is written ─────────────────────────────────────────────────────────────────
+// Every shape the whole build refuses for a new app, in the whole build; and a navigation of pages only — which the whole build builds, by
+// creating the pages first — in the app step without the pages phase, a run that cannot create them first.
for (const shape of refusedForNew) {
- test(`apply, new app — ${shape.name}: halts before the first write`, async () => {
+ const wholeBuild = shape.forNewPagesFirst === 'refuse';
+ test(`apply, new app — ${shape.name}${wholeBuild ? '' : ', the app step without the pages phase'}: halts before the first write`, async () => {
const env = environment({ app: 'absent' });
const warnings = [];
let halt;
- await assert.rejects(runSdkBuild(specFor(shape), { sdk: env.sdk, apply: true, warn: (m) => warnings.push(m) }), (e) => { halt = e; return true; });
+ await assert.rejects(runSdkBuild(specFor(shape), { sdk: env.sdk, apply: true, ...(wholeBuild ? {} : { phases: withoutPages }), warn: (m) => warnings.push(m) }), (e) => { halt = e; return true; });
assert.ok(halt instanceof BuildHalt);
assert.strictEqual(halt.code, 'app-navigation-empty');
assert.strictEqual(halt.phase, 'preflight', 'before the first phase, as the view-filter pre-flight halts');
@@ -266,10 +336,12 @@ for (const shape of refusedForNew) {
assert.match(halt.message, /The build stopped before writing anything\.$/);
assertSaysWhatIsWrong(halt.message, shape);
if (shape.kind === 'pages-only') {
- assert.match(halt.message, /A page entry joins the navigation only once its page exists, so a new app is created without them/);
- assert.match(halt.message, /A new app needs one entry that is not a page: add one to a group/);
+ assert.match(halt.message, /A page entry joins the navigation only once its page exists, and this run does not have the pages phase, which would create them first, so a new app would be created without them/);
+ assert.match(halt.message, /run the whole build, with every page the navigation names implemented\. Or give a group one entry that is not a page/);
} else {
- assert.match(halt.message, /A new app needs one entry that is not a page/);
+ // The whole build creates a new app's pages first, so an entry for one of the spec's pages is offered beside a table, dashboard or url entry.
+ assert.match(halt.message, /or an entry for one of the spec's pages \(a build that has the pages phase creates a new app's pages before the app\)\./);
+ assert.doesNotMatch(halt.message, /needs one entry that is not a page/);
}
// Nothing was written, and the only thing read is the one fact the verdict needed: whether the app exists. A spec with no appShell.areas is refused
// from the spec alone, since no answer could change that.
@@ -357,6 +429,111 @@ for (const shape of onlyPages) {
});
}
+// A NEW app whose navigation holds only pages, in the whole build: the pages are created FIRST and then the app, whose first push holds every page entry
+// and nothing else — so no navigation without them is ever sent, there is no temporary entry, and the finalizer has nothing to rewrite.
+for (const shape of onlyPages) {
+ test(`apply, new app, the whole build — ${shape.name}: the pages are created first, then the app with them in its first navigation`, async () => {
+ const appDir = appFolder(shape.pages);
+ try {
+ const env = pagesEnvironment({ existing: false });
+ const uploads = pageBackend();
+ // The page backend's creates, recorded among the SDK's calls in the order they were made.
+ const create = uploads.create.bind(uploads);
+ uploads.create = async (args) => { env.calls.push(['genpage.create', args.name]); return create(args); };
+ const events = [];
+ const result = await runSdkBuild(specFor(shape), { sdk: env.sdk, apply: true, env: 'https://contoso.example', appDir, genpage: uploads, phases: withPages, emit: (e) => events.push(e) });
+ assert.strictEqual(result.ok, true);
+ // The check's read of whether the app exists comes first, as it does for an app that exists; the app step makes its own, which decides.
+ assert.deepStrictEqual(env.calls[0], ['findArtifact', 'app', { uniqueName: 'new_supportdesk' }]);
+ assert.strictEqual(env.calls.filter((c) => c[0] === 'findArtifact').length, 2);
+ const appCreate = env.calls.findIndex((c) => c[0] === 'createArtifact' && c[1] === 'app');
+ const pageCreates = env.calls.map((c, i) => (c[0] === 'genpage.create' ? i : -1)).filter((i) => i >= 0);
+ assert.strictEqual(pageCreates.length, shape.pages.length, 'every page is created');
+ assert.ok(appCreate > Math.max(...pageCreates), 'and only then the app');
+ assert.strictEqual(env.calls.filter((c) => c[0] === 'createArtifact' && c[1] === 'app').length, 1, 'once');
+ const created = env.calls[appCreate][2];
+ const entries = created.siteMap.areas.flatMap((a) => a.groups.flatMap((g) => g.subAreas));
+ assert.deepStrictEqual(entries.map((s) => s.type), shape.pages.map(() => 'GenPage'), 'its first navigation holds the page entries, and nothing else');
+ assert.deepStrictEqual(entries.map((s) => s.genPageId), shape.pages.map((key) => result.created.pages[key]), 'each naming the page the run created');
+ assert.ok(created.iconWebResourceId, 'with the icon the app step resolved');
+ assert.deepStrictEqual(navigationWrites(env.calls), [], 'and nothing rewrites it: it was right when it was made');
+ // The create's own writes, in the order the app step makes them: the push, the app and its sitemap into the solution.
+ assert.deepStrictEqual(env.calls.slice(appCreate, appCreate + 3).map((c) => c[0]), ['createArtifact', 'pushArtifact', 'addSolutionComponent']);
+ assert.strictEqual(env.calls[appCreate + 2][1].componentType, 80);
+ assert.strictEqual(result.created.app, env.calls[appCreate + 2][1].componentId, 'the app the later phases act on is the one created');
+ // The app step says it left the create to the pages phase — never a ✓ for an app that does not exist yet — and the create is reported in its phase.
+ const appEvents = events.filter((e) => e.status !== 'start' && /^app "Support Desk"/.test(e.label)).map((e) => [e.phase, e.status, e.label]);
+ assert.deepStrictEqual(appEvents, [
+ ['app-shell', 'skip', 'app "Support Desk" (created after its pages: its navigation holds only page entries)'],
+ ['app-shell', 'ok', 'app "Support Desk" (created with its pages)'],
+ ]);
+ // Every step the plan budgets is reported once, in order: the create takes the finalizer's slot.
+ const done = events.filter((e) => e.status !== 'start');
+ assert.deepStrictEqual(done.map((e) => e.n), done.map((_, i) => i + 1));
+ assert.ok(done.every((e) => e.total === done.length), JSON.stringify(done.map((e) => [e.n, e.total, e.label])));
+ assert.ok(!done.some((e) => /finalize sitemap/.test(e.label)), 'there is no sitemap to finalize');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+ });
+}
+
+// What creates the pages first is the whole build's shape (pagesFirstRule): a run that cannot do it still refuses a new app of pages only, before it writes
+// anything, and says which shape it lacks.
+test('apply, new app — a navigation of pages only in a changed-only re-upload, or naming a page the run does not build, halts before the first write and says why', async () => {
+ const shape = shapeNamed('a navigation of pages only');
+ const appDir = appFolder(shape.pages);
+ try {
+ const reupload = pagesEnvironment({ existing: false });
+ let halt;
+ await assert.rejects(runSdkBuild(specFor(shape), { sdk: reupload.sdk, apply: true, env: 'https://contoso.example', appDir, genpage: pageBackend(), phases: withPages, changedOnly: { selectedKeys: ['overview'], skipSitemapFinalize: true } }), (e) => { halt = e; return true; });
+ assert.strictEqual(halt.code, 'app-navigation-empty');
+ assert.match(halt.message, /and this run only re-uploads changed pages, and creates no app, so a new app would be created without them/);
+ assert.deepStrictEqual(writesIn(reupload.calls), []);
+
+ // A page still an intent: validation's deploy profile refuses it on --apply, and the engine refuses the navigation on its own.
+ const intent = specFor(shape);
+ intent.pages[1].source = { kind: 'intent' };
+ const unbuilt = pagesEnvironment({ existing: false });
+ await assert.rejects(runSdkBuild(intent, { sdk: unbuilt.sdk, apply: true, env: 'https://contoso.example', appDir, genpage: pageBackend(), phases: withPages }), (e) => { halt = e; return true; });
+ assert.strictEqual(halt.code, 'app-navigation-empty');
+ assert.match(halt.message, /and this run builds no page for 'detail' \(a page of pages\[\] with source\.kind 'tsx' and a codeFile\), so a new app would be created without them/);
+ assert.deepStrictEqual(writesIn(unbuilt.calls), []);
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+test('pagesFirstRule: the whole build creates a new app\'s pages first; a run without the app step or the pages phase, a changed-only re-upload, or a page entry whose page the run does not build does not', () => {
+ const spec = specFor(shapeNamed('a navigation of pages only'));
+ for (const phases of [PHASES, withPages, STAGES.app]) assert.deepStrictEqual(pagesFirstRule(spec, phases), { newAppPagesFirst: true }, phases.join(','));
+ assert.deepStrictEqual(pagesFirstRule(spec, withoutPages), { newAppPagesFirst: false, whyNotPagesFirst: 'this run does not have the pages phase, which would create them first' });
+ assert.deepStrictEqual(pagesFirstRule(spec, ['pages']), { newAppPagesFirst: false, whyNotPagesFirst: 'this run has no app step' });
+ assert.deepStrictEqual(pagesFirstRule(spec, PHASES, { selectedKeys: ['overview'], skipSitemapFinalize: true }), { newAppPagesFirst: false, whyNotPagesFirst: 'this run only re-uploads changed pages, and creates no app' });
+ assert.deepStrictEqual(pagesFirstRule(spec, PHASES, { selectedKeys: ['overview'] }), { newAppPagesFirst: true }, 'a changed-only run that writes the navigation is not a re-upload of pages alone');
+ const unbuilt = specFor(shapeNamed('a navigation of pages only'));
+ unbuilt.pages[0].source = { kind: 'tsx' };
+ delete unbuilt.pages[1];
+ unbuilt.pages = unbuilt.pages.filter(Boolean);
+ assert.deepStrictEqual(pagesFirstRule(unbuilt, PHASES), { newAppPagesFirst: false, whyNotPagesFirst: "this run builds no page for 'overview', 'detail' (a page of pages[] with source.kind 'tsx' and a codeFile)" }, 'one with no codeFile, one not declared');
+ // A legacy spec names its pages by name, and so does its navigation.
+ const legacy = { app: { name: 'Legacy' }, pages: [{ name: 'Overview', codeFile: 'overview.tsx' }], appShell: { areas: [{ label: 'Main', groups: [{ label: 'G', subAreas: [{ page: 'Overview', title: 'Overview' }] }] }] } };
+ assert.deepStrictEqual(pagesFirstRule(legacy, PHASES), { newAppPagesFirst: true });
+});
+
+// An app that EXISTS and whose navigation is pages only makes exactly the requests 2.17.0 made: the app step finds it, so nothing of the new app's order applies.
+test('an existing app whose navigation is pages only is built — and dry-run — with exactly the requests it always was', async () => {
+ for (const [name, golden] of [['a navigation of pages only', GOLDEN.applyExistingPagesOnly], ['pages in two areas', GOLDEN.applyExistingPagesInTwoAreas], ['pages beside nothing but empty groups and areas', GOLDEN.applyExistingPagesBesideEmpty]]) {
+ const shape = shapeNamed(name);
+ const appDir = appFolder(shape.pages);
+ try {
+ const env = pagesEnvironment({ existing: true });
+ const result = await runSdkBuild(specFor(shape), { sdk: env.sdk, apply: true, env: 'https://contoso.example', appDir, genpage: pageBackend(), phases: withPages });
+ assert.strictEqual(result.ok, true, name);
+ calledSameAs(env.calls, golden, name);
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+ }
+ const dry = environment({ app: 'present' });
+ await runSdkBuild(specFor(shapeNamed('a navigation of pages only')), { sdk: dry.sdk, apply: false });
+ calledSameAs(dry.calls, GOLDEN.dryExistingPagesOnly, 'dry run, existing app');
+});
+
for (const shape of onlyPages) {
test(`apply, new app — ${shape.name}: with a table entry beside the pages the same navigation builds, and the first push leaves the pages out`, async () => {
const appDir = appFolder(shape.pages);
@@ -376,7 +553,7 @@ for (const shape of onlyPages) {
// The CLI wrapper reads the environment first (its own pre-flight), then hands the build to the engine.
test('buildModelApp --apply: the halt is raised once, not retried, journaled, and nothing is written', async () => {
- for (const shape of refusedForNew) {
+ for (const shape of refusedInWholeBuild) {
const appDir = appFolder(shape.pages || []);
try {
const env = environment({ app: 'absent' });
@@ -463,6 +640,14 @@ const GOLDEN = {
applyExistingBesidePages: { calls: 29, sha: '789bf9a2cdcc1c653fe49a6ff3f363ce73e7d9c255e916a5d810b74f57dd25e3' },
// The same one added read (see above), here before the app step's own push of its sitemap and header.
applyExistingAppStep: { calls: 24, sha: 'c57951fa58f2709965565258ed26693f6567e067b3b0099f36f4e8a59a237749' },
+ // An EXISTING app whose navigation is pages only — the whole build of it, and its dry run — captured on 2.17.0 with these fakes, before a NEW
+ // app of pages only could be built: that build's order (pages first) must leave every request of an app that exists as it was.
+ applyExistingPagesOnly: { calls: 32, sha: '6ea352b91cba2f7af9d8f4ee784e9bf36cad729705a3965424c0b24f14029cfb' },
+ applyExistingPagesInTwoAreas: { calls: 32, sha: '130729c40df45020333dbc83b2d1b25244797a218276aa4dc8ef7ebf9c362515' },
+ applyExistingPagesBesideEmpty: { calls: 30, sha: '5948d0defa335ed58e1a54c498e9a92687663cbc35ae3bf60b65f187192589a5' },
+ dryExistingPagesOnly: { calls: 2, sha: '4234a3bee2b8281a5346821c9eae1218743fae1213c841574d43e43b08e23698' },
+ // A NEW app whose navigation is pages only, built by creating its pages first (no earlier release built one): every request of that order.
+ applyNewPagesOnly: { calls: 23, sha: '6a994ff4984da4a8d32c695a547ec037279af8c2d6ba0713b00bbf06dd0eecb1' },
};
const calledSameAs = (calls, golden, what) => {
@@ -504,6 +689,25 @@ test('a valid navigation — with pages beside the entry, a new app and an exist
calledSameAs(appStepOnly.calls, GOLDEN.applyExistingAppStep, 'existing app, app step only');
});
+// The order a NEW app of pages only is built in, request by request: the check's read and the app step's (no app), the icon, the pages — each create
+// recorded in the manifest, which joins the solution — and then the app, ONE create whose push carries the whole navigation, joining the solution with
+// its sitemap. No navigation is rewritten afterwards. (The page backend's own requests are its fake's, not the SDK's: they are not among these.)
+test('a new app whose navigation is pages only is built with exactly these requests: the pages first, then one create of the app', async () => {
+ const shape = shapeNamed('a navigation of pages only');
+ const appDir = appFolder(shape.pages);
+ try {
+ const env = pagesEnvironment({ existing: false });
+ await runSdkBuild(specFor(shape), { sdk: env.sdk, apply: true, env: 'https://contoso.example', appDir, genpage: pageBackend(), phases: withPages });
+ assert.deepStrictEqual(env.calls.map(([name, kind]) => (name === 'queryRecords' || name === 'findArtifact' || name === 'createArtifact' || name === 'pushArtifact' ? `${name}(${kind})` : name)), [
+ 'findArtifact(app)', 'queryRecords(solution)', 'queryRecords(publisher)', 'createSolution', 'queryRecords(organization)', 'dataverse.get', 'createTable',
+ 'queryRecords(webresource)', 'createWebResource', 'addSolutionComponent', 'findArtifact(app)',
+ 'queryRecords(webresource)', 'createWebResource', 'queryRecords(solution)', 'addSolutionComponent', 'updateWebResource', 'addSolutionComponent', 'addSolutionComponent',
+ 'createArtifact(app)', 'pushArtifact(app)', 'addSolutionComponent', 'queryRecords(sitemap)', 'addSolutionComponent',
+ ]);
+ calledSameAs(env.calls, GOLDEN.applyNewPagesOnly, 'new app, pages only');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
test('a valid navigation — the dry run plans, reads and prints exactly what it always did', async () => {
const table = specFor(shapeNamed('a table entry'));
const warnings = [];
diff --git a/plugins/model-apps/scripts/tests/app-navigation.test.js b/plugins/model-apps/scripts/tests/app-navigation.test.js
index 4e51d0e5d..ffd40b068 100644
--- a/plugins/model-apps/scripts/tests/app-navigation.test.js
+++ b/plugins/model-apps/scripts/tests/app-navigation.test.js
@@ -5,9 +5,11 @@
// sitemap with no non-empty area holding a non-empty group (HTTP 400, measured). It accepts the same navigation when
// the sitemap of an app that already exists is UPDATED (measured: saved and published), so only a new app is refused.
// A spec whose navigation is only pages, or has no entry at all, still VALIDATES, so a build of a new app used to fail
-// at the app step after the solution, tables, views and forms had been written. This file pins the rule itself, its
-// agreement with what appDef pushes, that validation is unchanged, and the lint warning. The build, the dry run and
-// the writes are pinned in app-navigation-build.test.js.
+// at the app step after the solution, tables, views and forms had been written. A run that creates a new app's pages
+// FIRST (the whole build) creates the app once they exist, with them in its first navigation, so it builds a navigation
+// of pages only for a new app too; both rules are pinned. This file pins the rule itself, its agreement with what appDef
+// pushes, that validation is unchanged, and the lint warning. The build, the dry run and the writes are pinned in
+// app-navigation-build.test.js.
const { test } = require('node:test');
const assert = require('node:assert');
const fs = require('node:fs');
@@ -15,7 +17,7 @@ const os = require('node:os');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
-const { NAVIGATION_REFUSAL_CODE, navigationEntryKind, navigationHolds, navigationVerdict } = require('../lib/app-navigation.js');
+const { NAVIGATION_REFUSAL_CODE, navigationEntryKind, navigationHolds, navigationIsPagesOnly, navigationVerdict } = require('../lib/app-navigation.js');
const { appDef } = require('../lib/sdk-build.js');
const { validateAppSpec } = require('../lib/app-spec.js');
const { lintAppSpec } = require('../lib/spec-lint.js');
@@ -78,8 +80,25 @@ for (const shape of SHAPES) {
else assert.strictEqual(verdict.code, undefined, 'a navigation the build goes on with carries no refusal code');
}
});
+ // A run that creates a new app's pages before the app (sdk-build.js pagesFirstRule): the whole build --apply runs.
+ test(`verdict, a run that creates the pages first — ${shape.name}: new ${shape.forNewPagesFirst}, existing ${shape.forExisting}, unknown ${shape.forUnknownPagesFirst}`, () => {
+ const spec = specFor(shape);
+ for (const [appExists, expected] of [[false, shape.forNewPagesFirst], [true, shape.forExisting], [undefined, shape.forUnknownPagesFirst]]) {
+ const verdict = navigationVerdict(spec, { appExists, newAppPagesFirst: true });
+ assert.strictEqual(verdict.outcome, expected, `${exists[appExists]}: ${JSON.stringify(verdict)}`);
+ if (expected === 'ok') assert.deepStrictEqual(verdict, { outcome: 'ok' });
+ else assert.strictEqual(verdict.kind, shape.kind);
+ }
+ });
}
+test('navigationIsPagesOnly: a navigation that holds entries, every one a page — the one a new app is built from only by creating its pages first', () => {
+ for (const shape of SHAPES) assert.strictEqual(navigationIsPagesOnly(specFor(shape)), shape.kind === 'pages-only', shape.name);
+ assert.strictEqual(navigationIsPagesOnly({}), false);
+ assert.strictEqual(navigationIsPagesOnly({ appShell: oneGroup(page('overview'), { dashboard: 'Ops', title: 'Ops' }) }), false, 'a dashboard entry is not a page');
+ assert.strictEqual(navigationIsPagesOnly({ appShell: oneGroup(page('overview'), { url: 'https://contoso.example', title: 'u' }) }), false, 'nor is a url');
+});
+
test('the refusal code is the one the build halts with', () => {
assert.strictEqual(NAVIGATION_REFUSAL_CODE, 'app-navigation-empty');
});
@@ -108,22 +127,29 @@ test('an existing app is warned of an empty navigation only when the run writes
});
test('a refusal says what the navigation holds, what Dataverse requires, and what to add', () => {
- const pagesOnly = navigationVerdict(specFor(SHAPES.find((s) => s.name === 'a navigation of pages only')), { appExists: false });
+ // A navigation of pages only is refused only by a run that does not create a new app's pages first, and says why it does not.
+ const pagesOnly = navigationVerdict(specFor(SHAPES.find((s) => s.name === 'a navigation of pages only')), { appExists: false, whyNotPagesFirst: 'this run does not have the pages phase, which would create them first' });
assert.match(pagesOnly.message, /holds only page entries \('overview', 'detail'\)/);
- assert.match(pagesOnly.message, /A page entry joins the navigation only once its page exists, so a new app is created without them/);
+ assert.match(pagesOnly.message, /A page entry joins the navigation only once its page exists, and this run does not have the pages phase, which would create them first, so a new app would be created without them/);
assert.match(pagesOnly.message, /Dataverse refuses to create a sitemap with no non-empty area holding a non-empty group/);
assert.match(pagesOnly.message, /HTTP 400: "SiteMap needs to have a non-empty Area with a non-empty Group"/);
+ assert.match(pagesOnly.message, /A build that has the pages phase creates such an app after its pages, with them in its first navigation: run the whole build, with every page the navigation names implemented\./);
assert.ok(pagesOnly.message.includes("{ entity: '<table>', title: '<label>' }"), 'an entry to add');
- assert.match(pagesOnly.message, /A new app needs one entry that is not a page: add one to a group/);
+ assert.match(pagesOnly.message, /Or give a group one entry that is not a page/);
assert.match(pagesOnly.message, /dashboard or url entry/);
assert.match(pagesOnly.message, /keep the page entries beside it/);
+ assert.match(navigationVerdict(specFor(SHAPES.find((s) => s.name === 'a navigation of pages only')), { appExists: false }).message, /and this run does not create the pages before the app, so/, 'without a reason it still says what the run does not do');
for (const shape of SHAPES.filter((s) => s.kind === 'empty')) {
const { message } = navigationVerdict(specFor(shape), { appExists: false });
assert.ok(message.includes(`the navigation has no entry (${shape.said})`), `${shape.name}: ${message}`);
assert.match(message, /Dataverse refuses to create a sitemap with no non-empty area holding a non-empty group \(HTTP 400: "SiteMap needs to have a non-empty Area with a non-empty Group"\)/);
- assert.ok(message.includes("{ entity: '<table>', title: '<label>' } in appShell.areas[].groups[].subAreas"), shape.name);
- assert.match(message, /A new app needs one entry that is not a page/);
+ assert.ok(message.includes("{ entity: '<table>', title: '<label>' } in appShell.areas[].groups[].subAreas."), shape.name);
+ assert.match(message, /A new app needs one entry that is not a page/, 'a run that does not create the pages first needs one');
+ // In a run that does, an entry for one of the spec's pages is as good, and the advice says so instead.
+ const pagesFirst = navigationVerdict(specFor(shape), { appExists: false, newAppPagesFirst: true }).message;
+ assert.ok(pagesFirst.includes("{ entity: '<table>', title: '<label>' } in appShell.areas[].groups[].subAreas, or an entry for one of the spec's pages (a build that has the pages phase creates a new app's pages before the app)."), `${shape.name}: ${pagesFirst}`);
+ assert.doesNotMatch(pagesFirst, /needs one entry that is not a page/);
}
});
@@ -136,6 +162,10 @@ test('a spec with no appShell.areas says there is no navigation to build the app
assert.ok(message.startsWith('the spec has no appShell.areas, so there is no navigation to build the app with.'), `${shape.name}, ${exists[appExists]}: ${message}`);
assert.ok(message.includes("{ entity: '<table>', title: '<label>' } in appShell.areas[].groups[].subAreas"), shape.name);
assert.ok(!/HTTP 400/.test(message), 'Dataverse is not involved: nothing would be sent');
+ // In a run that creates a new app's pages first, an entry for one of the spec's pages is offered too.
+ const pagesFirst = navigationVerdict(specFor(shape), { appExists, newAppPagesFirst: true });
+ assert.strictEqual(pagesFirst.outcome, 'refuse', 'still refused: there is no navigation at all');
+ assert.ok(pagesFirst.message.includes("in appShell.areas[].groups[].subAreas, or an entry for one of the spec's pages"), pagesFirst.message);
}
}
});
@@ -188,10 +218,10 @@ test('an unknown answer for an empty navigation says what an app that exists wou
// The agreement the whole check rests on: what the build pushes for a NEW app is appDef with `omitUnbuiltPages`, and
// the check must call a navigation fine exactly when that holds an entry in a group in an area.
-function firstPushHoldsAnEntry(spec, created = { dashboards: {}, pages: {} }) {
+function firstPushHoldsAnEntry(spec, created = { dashboards: {}, pages: {} }, options = { omitUnbuiltPages: true }) {
let pushed;
try {
- pushed = appDef(spec, created, { omitUnbuiltPages: true });
+ pushed = appDef(spec, created, options);
} catch {
return false; // no appShell.areas: appDef has nothing to build a sitemap from
}
@@ -205,6 +235,18 @@ test('the check agrees with the navigation appDef pushes for a new app, for ever
}
});
+// The same agreement in a run that creates a new app's pages first. For a navigation of pages only the app's first push is made once the
+// pages exist — appDef over every page's id, nothing left out (sdk-build.js createAppWithPages); for any other it is the app step's, the
+// pages left out, as before.
+test('the check agrees with the navigation appDef pushes for a new app in a run that creates the pages first, for every shape', () => {
+ for (const shape of SHAPES) {
+ const spec = specFor(shape);
+ const built = { dashboards: {}, pages: Object.fromEntries((shape.pages || []).map((key, i) => [key, `gp-${i}`])) };
+ const pushed = navigationIsPagesOnly(spec) ? firstPushHoldsAnEntry(spec, built, {}) : firstPushHoldsAnEntry(spec);
+ assert.strictEqual(navigationVerdict(spec, { appExists: false, newAppPagesFirst: true }).outcome === 'ok', pushed, shape.name);
+ }
+});
+
test('the check agrees with appDef for a dashboard entry, which is built before the app and is not left out', () => {
const spec = specFor({ appShell: oneGroup({ dashboard: 'Operations', title: 'Overview' }) });
assert.strictEqual(firstPushHoldsAnEntry(spec, { dashboards: { Operations: 'dash-1' }, pages: {} }), true);
@@ -232,11 +274,13 @@ for (const profile of ['plan', 'deploy']) {
const appShellWarnings = (spec) => lintAppSpec(spec).warnings.filter((w) => w.startsWith('appShell: '));
+// Lint speaks of the build --apply runs: the whole build, which creates a new app's pages before the app. So it warns for exactly the
+// navigations that build refuses for a new app (`forNewPagesFirst`) — a navigation of pages only is not one of them.
test('lint warns, once, for exactly the navigations a new app cannot be built from — and never errors on them', () => {
for (const shape of SHAPES) {
const spec = specFor(shape);
const warnings = appShellWarnings(spec);
- assert.strictEqual(warnings.length, shape.forNew === 'refuse' ? 1 : 0, `${shape.name}: ${JSON.stringify(warnings)}`);
+ assert.strictEqual(warnings.length, shape.forNewPagesFirst === 'refuse' ? 1 : 0, `${shape.name}: ${JSON.stringify(warnings)}`);
const lint = lintAppSpec(spec);
assert.deepStrictEqual(lint.errors, [], `${shape.name}: a warning, not an error`);
assert.strictEqual(lint.ok, true, shape.name);
@@ -244,13 +288,11 @@ test('lint warns, once, for exactly the navigations a new app cannot be built fr
});
test('the lint warning carries what the build would say', () => {
- const [pagesOnly] = appShellWarnings(specFor(SHAPES.find((s) => s.name === 'a navigation of pages only')));
- assert.match(pagesOnly, /^appShell: the navigation holds only page entries \('overview', 'detail'\)/);
- assert.match(pagesOnly, /HTTP 400: "SiteMap needs to have a non-empty Area with a non-empty Group"/);
- assert.ok(pagesOnly.includes("{ entity: '<table>', title: '<label>' }"));
- assert.ok(pagesOnly.endsWith(' An app that already exists is not affected.'), 'lint cannot know whether the app exists, so it says who is spared');
+ assert.deepStrictEqual(appShellWarnings(specFor(SHAPES.find((s) => s.name === 'a navigation of pages only'))), [], 'a navigation of pages only builds: the whole build creates the pages first');
const [empty] = appShellWarnings(specFor(SHAPES.find((s) => s.name === 'areas: []')));
assert.match(empty, /^appShell: the navigation has no entry \(appShell\.areas is empty\)/);
+ assert.match(empty, /HTTP 400: "SiteMap needs to have a non-empty Area with a non-empty Group"/);
+ assert.ok(empty.includes("{ entity: '<table>', title: '<label>' } in appShell.areas[].groups[].subAreas, or an entry for one of the spec's pages"), 'what to add, a page entry included');
assert.ok(empty.endsWith(' An app that already exists is built with no navigation entries, and the build says so.'), 'an app that exists is not refused an empty navigation, and lint says what it gets instead');
const [undeclared] = appShellWarnings(specFor(SHAPES.find((s) => s.name === 'a spec with no appShell')));
assert.match(undeclared, /^appShell: the spec has no appShell\.areas, so there is no navigation to build the app with\./);
@@ -259,13 +301,18 @@ test('the lint warning carries what the build would say', () => {
// The authoring flow runs lint-app-spec at the default `plan` profile, where a page may still be an intent.
test('lint-app-spec (plan profile) reports the warning with its source tag, and the exit code stays 0 without --strict', () => {
- const spec = specFor(SHAPES.find((s) => s.name === 'a navigation of pages only'));
- for (const p of spec.pages) p.source = { kind: 'intent' };
- const report = lintSpec(spec);
+ const report = lintSpec(specFor(SHAPES.find((s) => s.name === 'areas: []')));
assert.strictEqual(report.profile, 'plan');
assert.strictEqual(report.ok, true, JSON.stringify(report.errors));
assert.strictEqual(report.warnings.filter((w) => w.startsWith('lint: appShell: ')).length, 1, JSON.stringify(report.warnings));
assert.strictEqual(lintSpec(specFor(SHAPES.find((s) => s.name === 'a table entry'))).warnings.filter((w) => /appShell:/.test(w)).length, 0);
+ // A navigation of pages only whose pages are still intents: the build that deploys them implements them first (validation's deploy
+ // profile demands it), and then creates them before the app — so lint has nothing to say of the navigation.
+ const intents = specFor(SHAPES.find((s) => s.name === 'a navigation of pages only'));
+ for (const p of intents.pages) p.source = { kind: 'intent' };
+ const pagesOnly = lintSpec(intents);
+ assert.strictEqual(pagesOnly.ok, true, JSON.stringify(pagesOnly.errors));
+ assert.deepStrictEqual(pagesOnly.warnings.filter((w) => /appShell:/.test(w)), []);
});
function runCli(spec, extraArgs = []) {
diff --git a/plugins/model-apps/scripts/tests/app-sitemap-link-real-bundle.test.js b/plugins/model-apps/scripts/tests/app-sitemap-link-real-bundle.test.js
new file mode 100644
index 000000000..667eeed39
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/app-sitemap-link-real-bundle.test.js
@@ -0,0 +1,272 @@
+'use strict';
+
+// Exercise identity through the real SDK and HTTP client over the strict, stateful lifecycle backend.
+// A matching name is deliberately a decoy: it must never override a current-layer type-62 component.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');
+const { appSitemapLinkRows } = require('./helpers/app-sitemap-link-rows.js');
+const { createAzHttpClient } = require('../lib/sdk-http-client.js');
+const { createMakerSdk, createNodeWorkspaceStorage } = require('../lib/maker-sdk.js');
+const { runDownload } = require('../download-model-app.js');
+
+const APP = '11111111-1111-4111-8111-111111111111';
+const LAYER = '22222222-2222-4222-8222-222222222222';
+const SITEMAP = '33333333-3333-4333-8333-333333333333';
+const DECOY = '44444444-4444-4444-8444-444444444444';
+const COMPONENT = '55555555-5555-4555-8555-555555555555';
+const OTHER_APP = '66666666-6666-4666-8666-666666666666';
+const OTHER_LAYER = '77777777-7777-4777-8777-777777777777';
+const OLD_LAYER = '88888888-8888-4888-8888-888888888888';
+const MISSING = '99999999-9999-4999-8999-999999999999';
+const UNIQUE = 'contoso_linked';
+const xml = (target) => `<SiteMap><Area Id="work"><Group Id="main"><SubArea Id="nav" Url="https://contoso.example/${target}" /></Group></Area></SiteMap>`;
+const isForwardLink = (req) => {
+ const u = new URL(req.url);
+ const filter = u.searchParams.get('$filter') || '';
+ return req.method === 'GET' && u.pathname.endsWith('/appmodulecomponents')
+ && filter.includes(`_appmoduleidunique_value eq ${LAYER}`) && filter.includes('componenttype eq 62');
+};
+const navigationUrl = (app) => app.siteMap.areas[0].groups[0].subAreas[0].url;
+
+async function fixture({ savedOnly = false, component = true, sameName = false } = {}) {
+ const org = createLifecycleOrg();
+ const root = makeTempDir('app-sitemap-link-');
+ const wire = [];
+ const faults = { answer: null };
+ async function send(method, resource, body) {
+ const result = await org.request({
+ method, url: `${org.API}/${resource}`, headers: { 'content-type': 'application/json' },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ assert.ok(result.statusCode >= 200 && result.statusCode < 300, `${method} ${resource}: ${result.body}`);
+ return result;
+ }
+ const app = (id, layer, uniqueName) => send('POST', 'appmodules', {
+ appmoduleid: id, appmoduleidunique: layer, uniquename: uniqueName, name: uniqueName, description: 'Original', clienttype: 4,
+ });
+ const pin = (layer, sitemap, id) => send('POST', 'appmodulecomponents', {
+ ...(id ? { appmodulecomponentid: id } : {}), _appmoduleidunique_value: layer, objectid: sitemap, componenttype: 62, rootcomponentbehavior: 0,
+ });
+ await app(APP, LAYER, UNIQUE);
+ await send('POST', 'sitemaps', { sitemapid: SITEMAP, sitemapname: 'Owned Navigation', sitemapnameunique: sameName ? UNIQUE : 'contoso_navigation', sitemapxml: xml('owned') });
+ if (!sameName) await send('POST', 'sitemaps', { sitemapid: DECOY, sitemapname: 'Decoy', sitemapnameunique: UNIQUE, sitemapxml: xml('decoy') });
+ if (component) await pin(LAYER, SITEMAP, COMPONENT);
+ if (!savedOnly) {
+ await send('POST', 'PublishXml', { ParameterXml: `<importexportxml><appmodules><appmodule>${APP}</appmodule></appmodules><sitemaps><sitemap>${SITEMAP}</sitemap>${sameName ? '' : `<sitemap>${DECOY}</sitemap>`}</sitemaps></importexportxml>` });
+ }
+ const httpClient = createAzHttpClient(org.origin, {
+ getToken: () => 'offline-sitemap-link-token', sleep: async () => {},
+ request: async (req) => {
+ wire.push(req);
+ const answer = faults.answer ? await faults.answer(req) : undefined;
+ return answer === undefined ? org.request(req) : answer;
+ },
+ });
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(path.join(root, 'workspace')), instanceUrl: org.origin, httpClient });
+ await sdk.initWorkspace();
+ async function share({ stale = false } = {}) {
+ await app(OTHER_APP, OTHER_LAYER, 'contoso_other');
+ await pin(stale ? OLD_LAYER : OTHER_LAYER, SITEMAP);
+ }
+ return { sdk, org, root, wire, faults, send, pin, share };
+}
+
+function noWrites(f, mark, before) {
+ assert.deepEqual(f.org.writes(mark), [], 'no header, sitemap, component, publish or delete was sent');
+ assert.deepEqual(f.org.contents(), before, 'every saved and published row is unchanged');
+ assert.deepEqual(f.org.unexpected, [], 'the backend understood every actual request');
+}
+
+test('link-row fixtures filter by both layer and sitemap and project the actual selected columns', () => {
+ const apps = [{ appmoduleid: APP, appmoduleidunique: LAYER, componentstate: 1 }];
+ const components = [
+ { _appmoduleidunique_value: LAYER, objectid: SITEMAP, componenttype: 62 },
+ { _appmoduleidunique_value: OTHER_LAYER, objectid: DECOY, componenttype: 62 },
+ { _appmoduleidunique_value: LAYER, objectid: DECOY, componenttype: 1 },
+ ];
+ const get = (query) => appSitemapLinkRows(`https://contoso.crm.dynamics.com/api/data/v9.0/${query}`, { apps, components });
+ assert.deepEqual(get(`appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq ${LAYER} and componenttype eq 62`), [{ objectid: SITEMAP }]);
+ assert.deepEqual(get(`appmodulecomponents?$select=_appmoduleidunique_value&$filter=componenttype eq 62 and objectid eq ${DECOY}`), [{ _appmoduleidunique_value: OTHER_LAYER }]);
+ assert.deepEqual(get(`appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid&$filter=appmoduleidunique eq ${OTHER_LAYER}`), []);
+ assert.equal(get('appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,uniquename,componentstate'), undefined, 'the plugin-wide draft scan is not a per-app identity lookup');
+ assert.equal(get('roles?$select=roleid'), undefined, 'unrelated reads are not invented');
+ assert.throws(() => get(`appmodulecomponents?$select=unknown&$filter=componenttype eq 62 and objectid eq ${SITEMAP}`), /Unmodeled/);
+});
+
+test('REAL BUNDLE: current-layer type-62 navigation wins over a same-name decoy and an old layer', async () => {
+ const f = await fixture();
+ await f.pin(OLD_LAYER, DECOY);
+ const mark = f.org.mark();
+ const before = f.org.contents();
+ assert.equal(navigationUrl(await f.sdk.fetchArtifact('app', APP)), 'https://contoso.example/owned');
+ noWrites(f, mark, before);
+ assert.ok(f.wire.some(isForwardLink), 'the current layer, not the matching sitemap name, was resolved');
+});
+
+test('REAL BUNDLE: saved-only and renamed navigation is fetched without publishing or borrowing the decoy', async () => {
+ const f = await fixture({ savedOnly: true });
+ await f.send('PATCH', `sitemaps(${SITEMAP})`, { sitemapnameunique: 'contoso_renamed_navigation', sitemapxml: xml('saved-only') });
+ const mark = f.org.mark();
+ const before = f.org.contents();
+ assert.equal(navigationUrl(await f.sdk.fetchArtifact('app', APP)), 'https://contoso.example/saved-only');
+ noWrites(f, mark, before);
+ assert.equal(f.org.rowsOf('appmodules').get(APP).published, null);
+});
+
+test('REAL BUNDLE: a pending current layer wins even when the published app row is returned first', async () => {
+ const f = await fixture();
+ await f.pin(OLD_LAYER, DECOY);
+ f.faults.answer = (req) => {
+ const u = new URL(req.url);
+ if (u.pathname.includes('/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()')
+ && (u.searchParams.get('$select') || '').includes('componentstate')) {
+ return { statusCode: 200, headers: {}, body: JSON.stringify({ value: [
+ { appmoduleid: APP, appmoduleidunique: OLD_LAYER, componentstate: 0 },
+ { appmoduleid: APP, appmoduleidunique: LAYER, componentstate: 1 },
+ ] }) };
+ }
+ return undefined;
+ };
+ const mark = f.org.mark();
+ const before = f.org.contents();
+ assert.equal(navigationUrl(await f.sdk.fetchArtifact('app', APP)), 'https://contoso.example/owned');
+ noWrites(f, mark, before);
+});
+
+const identityFaults = ['missing-layer', 'ambiguous-current-layer', 'missing-sitemap', 'ambiguous-component', 'failed-component'];
+for (const [fault, operation] of identityFaults.flatMap((fault) => ['fetch', 'delete'].map((operation) => [fault, operation]))) {
+ test(`REAL BUNDLE: ${fault} refuses ${operation} instead of using the same-name decoy`, async () => {
+ const f = await fixture();
+ if (fault === 'missing-sitemap') await f.send('PATCH', `appmodulecomponents(${COMPONENT})`, { objectid: MISSING });
+ if (fault === 'ambiguous-component') await f.pin(LAYER, DECOY);
+ f.faults.answer = (req) => {
+ const u = new URL(req.url);
+ if (['missing-layer', 'ambiguous-current-layer'].includes(fault) && u.pathname.includes('/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()')
+ && (u.searchParams.get('$select') || '').includes('componentstate')) {
+ const rows = fault === 'missing-layer' ? [{ appmoduleid: APP, componentstate: 0 }] : [
+ { appmoduleid: APP, appmoduleidunique: LAYER, componentstate: 1 },
+ { appmoduleid: APP, appmoduleidunique: OTHER_LAYER, componentstate: 1 },
+ ];
+ return { statusCode: 200, headers: {}, body: JSON.stringify({ value: rows }) };
+ }
+ if (fault === 'failed-component' && isForwardLink(req)) return { statusCode: 503, headers: {}, body: '{"error":{"message":"injected read failure"}}' };
+ return undefined;
+ };
+ const mark = f.org.mark();
+ const before = f.org.contents();
+ await assert.rejects(operation === 'fetch' ? f.sdk.fetchArtifact('app', APP) : f.sdk.deleteAppCascade(APP, LAYER),
+ (e) => e.code === 'APP_SITEMAP_UNRESOLVED');
+ await assert.rejects(async () => await f.sdk.getArtifact('app', APP), (e) => e.code === 'ARTIFACT_NOT_FOUND', 'no partial app is persisted');
+ noWrites(f, mark, before);
+ });
+}
+
+test('REAL BUNDLE: a same-name fallback pinned by another live app is a graceful failed download with no output', async () => {
+ const f = await fixture({ component: false, sameName: true });
+ await f.share();
+ const outDir = path.join(f.root, 'download');
+ fs.mkdirSync(outDir);
+ const genpage = { read: async () => { throw new Error('page reads must not start'); } };
+ const mark = f.org.mark();
+ const before = f.org.contents();
+ const result = await runDownload({ sdk: f.sdk, genpage, outDir, appId: APP, appUnique: UNIQUE });
+ assert.equal(result.ok, false);
+ assert.match(result.error, /cannot read app /);
+ assert.match(result.error, /navigation of app .*not this app's/);
+ assert.deepEqual(fs.readdirSync(outDir), [], 'no success-shaped partial spec or page folders');
+ noWrites(f, mark, before);
+});
+
+test('REAL BUNDLE: a same-name fallback shared after fetch refuses the push before any write', async () => {
+ const f = await fixture({ component: false, sameName: true });
+ await f.sdk.fetchArtifact('app', APP);
+ await f.sdk.updateElement('app', APP, '/description', 'My edit');
+ await f.share();
+ const mark = f.org.mark();
+ const before = f.org.contents();
+ await assert.rejects(f.sdk.pushArtifact('app', APP), (e) => e.code === 'APP_SITEMAP_SHARED');
+ noWrites(f, mark, before);
+});
+
+for (const method of ['deleteRemoteArtifact', 'deleteAppCascade']) {
+ test(`REAL BUNDLE: ${method} refuses a component-linked sitemap another current app pins`, async () => {
+ const f = await fixture();
+ await f.share();
+ assert.equal(navigationUrl(await f.sdk.fetchArtifact('app', APP)), 'https://contoso.example/owned', 'a component-linked shared sitemap remains readable');
+ const mark = f.org.mark();
+ const before = f.org.contents();
+ await assert.rejects(f.sdk[method](...(method === 'deleteAppCascade' ? [APP, LAYER] : ['app', APP])), (e) => e.code === 'APP_SITEMAP_SHARED');
+ noWrites(f, mark, before);
+ });
+}
+
+test('REAL BUNDLE: an inconclusive reverse-owner read refuses delete before either row is touched', async () => {
+ const f = await fixture();
+ f.faults.answer = (req) => {
+ const u = new URL(req.url);
+ if (u.pathname.endsWith('/appmodulecomponents') && (u.searchParams.get('$filter') || '').includes(`objectid eq ${SITEMAP}`)) {
+ return { statusCode: 503, headers: {}, body: '{"error":{"message":"injected owner read failure"}}' };
+ }
+ return undefined;
+ };
+ const mark = f.org.mark();
+ const before = f.org.contents();
+ await assert.rejects(f.sdk.deleteAppCascade(APP, LAYER), (e) => e.code === 'APP_SITEMAP_UNRESOLVED');
+ noWrites(f, mark, before);
+});
+
+test('REAL BUNDLE: an old-layer pin is not mistaken for another app currently sharing the sitemap', async () => {
+ const f = await fixture();
+ await f.share({ stale: true });
+ const otherBefore = structuredClone(f.org.rowsOf('appmodules').get(OTHER_APP));
+ const decoyBefore = structuredClone(f.org.rowsOf('sitemaps').get(DECOY));
+ const result = await f.sdk.deleteAppCascade(APP, LAYER);
+ assert.equal(result.success, true, JSON.stringify(result.failures));
+ assert.equal(f.org.rowsOf('appmodules').has(APP), false);
+ assert.equal(f.org.rowsOf('sitemaps').has(SITEMAP), false);
+ assert.deepEqual(f.org.rowsOf('appmodules').get(OTHER_APP), otherBefore);
+ assert.deepEqual(f.org.rowsOf('sitemaps').get(DECOY), decoyBefore);
+ assert.deepEqual(f.org.unexpected, []);
+});
+
+test('REAL BUNDLE: a relink after fetch refuses the held copy before its header or old sitemap is written', async () => {
+ const f = await fixture();
+ await f.sdk.fetchArtifact('app', APP);
+ await f.sdk.updateElement('app', APP, '/description', 'My edit');
+ await f.send('PATCH', `appmodulecomponents(${COMPONENT})`, { objectid: DECOY });
+ const mark = f.org.mark();
+ const before = f.org.contents();
+ await assert.rejects(f.sdk.pushArtifact('app', APP), (e) => e.code === 'APP_SITEMAP_UNRESOLVED' && /no longer|now/.test(e.message));
+ noWrites(f, mark, before);
+});
+
+for (const operation of ['fetch', 'delete']) {
+ test(`REAL BUNDLE: a relink during ${operation}'s final identity proof refuses before persisting or deleting`, async () => {
+ const f = await fixture();
+ let reads = 0;
+ f.faults.answer = (req) => {
+ if (isForwardLink(req) && ++reads === 2) {
+ // Another writer relinks this owned fixture between the two proof reads. Only this component
+ // changes; the SDK must neither persist a partial app nor write either candidate sitemap.
+ f.org.rowsOf('appmodulecomponents').get(COMPONENT).data.objectid = DECOY;
+ }
+ return undefined;
+ };
+ const mark = f.org.mark();
+ const before = f.org.contents();
+ await assert.rejects(operation === 'fetch' ? f.sdk.fetchArtifact('app', APP) : f.sdk.deleteAppCascade(APP, LAYER),
+ (e) => e.code === 'APP_SITEMAP_UNRESOLVED');
+ assert.equal(reads, 2, 'the link is re-read after the sitemap, not trusted from its first snapshot');
+ assert.deepEqual(f.org.writes(mark), []);
+ await assert.rejects(async () => await f.sdk.getArtifact('app', APP), (e) => e.code === 'ARTIFACT_NOT_FOUND');
+ const after = f.org.contents();
+ delete before[`row appmodulecomponents ${COMPONENT}`];
+ delete after[`row appmodulecomponents ${COMPONENT}`];
+ assert.deepEqual(after, before, 'the injected relink is the only change');
+ assert.deepEqual(f.org.unexpected, []);
+ });
+}
diff --git a/plugins/model-apps/scripts/tests/app-spec-doc-access.test.js b/plugins/model-apps/scripts/tests/app-spec-doc-access.test.js
index c0e97af5d..026d7e893 100644
--- a/plugins/model-apps/scripts/tests/app-spec-doc-access.test.js
+++ b/plugins/model-apps/scripts/tests/app-spec-doc-access.test.js
@@ -406,6 +406,59 @@ test('a malformed discovery answer or spec renders instead of throwing', () => {
}
});
+// --- a roleGrants[] entry the build refuses -------------------------------------------------------------------------------------------
+
+// An entry that names its role twice (`role` and `roleId`), or not at all, is refused by the gate a build and lint-app-spec.js run. The
+// document used to show it as a grant the build would make; it now says what lint says, in lint's words, and lists none of its privileges.
+test('a roleGrants[] entry the build refuses is refused in the document and its warnings in the words lint uses, and nothing of it is shown as granted', () => {
+ const { lintSpec } = require('../lint-app-spec.js');
+ const spec = extensionSpec();
+ spec.roleGrants = [
+ grant('Contoso PM - Viewer', 'contoso_baseline'),
+ { role: 'Contoso PM - Project Manager', roleId: '33333333-3333-3333-3333-333333333333', privileges: [{ entity: 'contoso_baseline', access: ['write'], scope: 'organization' }] },
+ { privileges: [{ entity: 'contoso_baseline', access: ['delete'], scope: 'organization' }] },
+ ];
+ const refusals = lintSpec(spec).errors.filter((e) => /^schema: roleGrants\[[12]\]/.test(e)).map((e) => e.replace(/^schema: /, ''));
+ assert.deepEqual(refusals, [
+ "roleGrants[1] (role \"Contoso PM - Project Manager\"): set either 'role' (the existing role's display name) or 'roleId' (its GUID), not both — they can disagree and only one can be honoured",
+ "roleGrants[2]: name the existing role to extend — set 'role' (display name) or 'roleId' (GUID)",
+ ]);
+
+ const gaps = designGaps(spec);
+ for (const refusal of refusals) assert.ok(gaps.includes(refusal), `the warnings say what lint says: ${refusal}\n${JSON.stringify(gaps)}`);
+
+ const extended = section(renderAppSpecDoc(spec), '### Roles extended by `roleGrants[]`');
+ for (const refusal of refusals) assert.ok(extended.includes(`> ✗ ${refusal}`), `the document says what lint says: ${refusal}\n${extended}`);
+ assert.match(extended, /\| Contoso PM - Viewer \| contoso_baseline \| read \| organization \|/, 'the entry the build makes is listed as before');
+ assert.doesNotMatch(extended, /\| (Contoso PM - Project Manager|33333333-3333-3333-3333-333333333333|) \| contoso_baseline \|/, 'no row of a refused entry');
+ assert.doesNotMatch(extended, /\| (write|delete) \|/);
+
+ // Read against the environment, a refused entry names no role a build would extend: it is not matched to the app's roles either.
+ const appAccess = appWithRoles('Contoso PM - Viewer');
+ const read = section(renderAppSpecDoc(spec, { envUrl: ENV, appAccess }), '### Roles extended by `roleGrants[]`');
+ assert.doesNotMatch(read, /Role "(Contoso PM - Project Manager|33333333-3333-3333-3333-333333333333)"/);
+ assert.deepEqual(designGaps(spec, { envUrl: ENV, appAccess }).filter((g) => /is not among the roles/.test(g)), []);
+
+ // A spec whose every entry names one role says nothing of the kind.
+ const valid = extensionSpec();
+ valid.roleGrants = [grant('Contoso PM - Viewer', 'contoso_baseline')];
+ assert.doesNotMatch(renderAppSpecDoc(valid), /> ✗ /);
+ assert.deepEqual(designGaps(valid).filter((g) => /^roleGrants\[/.test(g)), []);
+
+ // The command still writes the document and exits 0 — the lint gate is what refuses the spec — and echoes the refusals.
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'appdoc-refused-grant-'));
+ try {
+ const specPath = path.join(dir, 'app-spec.json');
+ fs.writeFileSync(specPath, JSON.stringify(spec), 'utf8');
+ const out = JSON.parse(execFileSync(process.execPath, [CLI, '--spec', `@${specPath}`], { encoding: 'utf8' }));
+ assert.equal(out.ok, true);
+ for (const refusal of refusals) assert.ok(out.warnings.includes(refusal), JSON.stringify(out.warnings));
+ assert.ok(fs.readFileSync(out.docPath, 'utf8').includes(`> ✗ ${refusals[0]}`));
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
// --- the command, offline ---------------------------------------------------------------------------------------------------------------
test('the command with no --env makes the same findings and reads no environment', () => {
diff --git a/plugins/model-apps/scripts/tests/apps-real-bundle.test.js b/plugins/model-apps/scripts/tests/apps-real-bundle.test.js
index 5261acab0..6421b59f1 100644
--- a/plugins/model-apps/scripts/tests/apps-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/apps-real-bundle.test.js
@@ -568,6 +568,49 @@ test('REAL BUNDLE: a rollback the platform refuses keeps both rows, and the outp
assert.deepStrictEqual([result.published, result.unpublishedChanges, result.addedToSolution, result.inSolution], [false, true, false, []]);
});
+for (const wholeChangeSet of [true, false]) {
+ test(`REAL BUNDLE: a customization lock ${wholeChangeSet ? 'refusing the rollback whole' : 'interrupting its answer'} keeps the SDK's honest advice, without replay`, async () => {
+ const lock = { code: '0x80071151', message: 'Cannot start the requested operation because there is another EntityCustomization running at this moment.' };
+ const org = orgWithPages({
+ answer: (req) => {
+ if (req.path === '/AddAppComponents') return json(400, { error: { message: 'component refused' } });
+ if (req.path !== '/$batch') return undefined;
+ if (!wholeChangeSet) return json(429, { error: lock });
+ // Only a failed operation is returned when an atomic change set is refused. The lock code
+ // must be on that operation, not just in the outer envelope, to prove nothing was deleted.
+ return {
+ statusCode: 200, headers: { 'content-type': 'multipart/mixed; boundary=br' },
+ body: [
+ '--br', 'Content-Type: multipart/mixed; boundary=csr', '',
+ '--csr', 'Content-Type: application/http', 'Content-ID: 1', '',
+ 'HTTP/1.1 429 Too Many Requests', 'Content-Type: application/json', '',
+ JSON.stringify({ error: lock }), '--csr--', '--br--', '',
+ ].join('\r\n'),
+ };
+ },
+ });
+ const result = await createApp(args({ publish: true }), client(org), seams);
+ assert.deepStrictEqual([result.ok, result.stage, result.written, result.left, result.published, result.unpublishedChanges],
+ [false, 'create', true, { app: true, sitemap: true }, false, true]);
+ if (wholeChangeSet) {
+ assert.match(result.error, /KEPT — its rollback deleted nothing, because the environment's customization lock refused it/);
+ assert.match(result.error, /Once the lock frees .*check that the rows exist and are this create's own before removing them/);
+ } else {
+ // postRaw preserves response TEXT, including a JSON error outside a change set. The SDK cannot
+ // prove that answer refused an atomic rollback: keep its unknown verdict and cause, not KEPT.
+ assert.match(result.error, /could not be confirmed, because its delete was sent but its outcome is unknown/);
+ assert.match(result.error, /0x80071151.*EntityCustomization/);
+ assert.match(result.error, /once you have confirmed the rows are this create's own/);
+ assert.doesNotMatch(result.error, /KEPT|rollback deleted nothing/);
+ }
+ assert.strictEqual(result.appId, org.state.apps[0].appmoduleid);
+ assert.strictEqual(result.sitemapId, org.state.sitemaps[0].sitemapid);
+ assert.strictEqual(org.requests.filter((r) => r.path === '/PublishXml').length, 0, 'the component failure happened before publication');
+ assert.strictEqual(org.requests.filter((r) => r.path === '/$batch').length, 1, 'rollback has an unguarded app delete, so neither layer may replay it');
+ assert.deepStrictEqual(org.unexpected, []);
+ });
+}
+
// The SDK cannot tell whether a change set whose answer it never read was applied, and says so. The output does not have to guess: it reads the platform.
test('REAL BUNDLE: a rollback whose answer is lost is "unconfirmed" to the SDK, and the output reads which it was — rows gone, or rows kept', async () => {
for (const applied of [true, false]) {
diff --git a/plugins/model-apps/scripts/tests/bpf-stage-edits.test.js b/plugins/model-apps/scripts/tests/bpf-stage-edits.test.js
index 92e1f1399..5c2c5a1d2 100644
--- a/plugins/model-apps/scripts/tests/bpf-stage-edits.test.js
+++ b/plugins/model-apps/scripts/tests/bpf-stage-edits.test.js
@@ -912,3 +912,158 @@ test('REAL BUNDLE: a stale local copy is replaced by the environment\'s — the
assert.strictEqual(inspected.kind, 'same', 'the interrupted build\'s local rename does not count: only the deployed flow does');
assert.strictEqual((await sdk.getArtifact('bpf', id)).stages[0].name, 'Triage');
});
+
+// An Active flow's change set the customization lock refuses. The platform answers the whole `$batch` 429 with ONE part, the guard's,
+// and nothing written (measured: etag, state, name and definition unchanged):
+// --batchresponse_<id>
+// Content-Type: multipart/mixed; boundary=changesetresponse_<id>
+//
+// --changesetresponse_<id>
+// Content-Type: application/http
+// Content-ID: 1
+//
+// HTTP/1.1 429 Too Many Requests
+// {"error":{"code":"0x80071151","message":"Cannot start the requested operation [EntityCustomization] because there is another [WorkflowSetState] running…"}}
+// --changesetresponse_<id>--
+// --batchresponse_<id>--
+// The plugin's HTTP client delivers it once — a `$batch` it never sends again but for the two kinds lib/sdk-http-client.js names — and the
+// SDK sends the IDENTICAL change set again after its first wait (2 s), the guard still under the caller's If-Match, so a flow edited in the
+// meantime would fail it 412 with nothing written. This is the one BPF write the plugin makes that the SDK's lock re-send reaches: a Draft
+// flow's edit is one PATCH, and the plugin never takes the deactivate, edit and activate cycle (its client has postRaw).
+function lockRefusedChangeSet(contentId) {
+ return ['--batchresponse_l', 'Content-Type: multipart/mixed; boundary=changesetresponse_l', '', '--changesetresponse_l', 'Content-Type: application/http', 'Content-Transfer-Encoding: binary', `Content-ID: ${contentId}`, '',
+ 'HTTP/1.1 429 Too Many Requests', 'Content-Type: application/json; odata.metadata=minimal', '',
+ JSON.stringify({ error: { code: '0x80071151', message: 'Cannot start the requested operation [EntityCustomization] because there is another [WorkflowSetState] running at this moment.' } }),
+ '--changesetresponse_l--', '--batchresponse_l--', ''].join('\r\n');
+}
+
+// SDK waits use setTimeout; advance those waits without speeding up the asynchronous workspace writes. The wall-clock bound
+// catches a hung call even if a loaded machine needs many event-loop turns to finish one write.
+async function settleBpfWaits(t, promise) {
+ let settled = false;
+ let value;
+ let failure;
+ promise.then((result) => { settled = true; value = result; }, (error) => { settled = true; failure = error; });
+ const deadline = Date.now() + 20000;
+ while (!settled && Date.now() < deadline) {
+ await new Promise((resolve) => setImmediate(resolve));
+ t.mock.timers.tick(5000);
+ }
+ assert.ok(settled, 'the SDK call settled within the wall-clock bound');
+ if (failure) throw failure;
+ return value;
+}
+
+test('REAL BUNDLE: an Active flow\'s change set the customization lock refuses is delivered ONCE by the plugin\'s HTTP client and sent again by the SDK — the edit lands under the same If-Match, and the flow stays Active', async () => {
+ const { createAzHttpClient } = require('../lib/sdk-http-client.js');
+ const { createMakerSdk, createNodeWorkspaceStorage } = require(BUNDLE);
+ const { fake, id, row } = await realBpf();
+ const batches = [];
+ let refusals = 1;
+ // The transport under the plugin's real client, onto the fake: what Node's client hands it — the status, the headers and the body as text.
+ const asTransport = async (answer) => ({ statusCode: answer.status, headers: answer.headers, body: typeof answer.body === 'string' ? answer.body : JSON.stringify(answer.body) });
+ async function request({ url, method, headers, body }) {
+ if (method === 'POST' && /\/\$batch$/.test(new URL(url).pathname)) {
+ batches.push(String(body));
+ if (refusals > 0) {
+ refusals -= 1;
+ return { statusCode: 429, headers: { 'content-type': 'multipart/mixed; boundary=batchresponse_l' }, body: lockRefusedChangeSet(/Content-ID:\s*(\S+)/i.exec(String(body))[1]) };
+ }
+ return asTransport(await fake.client.postRaw(url, body));
+ }
+ if (method === 'GET') return asTransport(await fake.client.get(url));
+ if (method === 'PATCH') return asTransport(await fake.client.patch(url, JSON.parse(body), { headers }));
+ return asTransport(await fake.client[method.toLowerCase()](url, body === null ? undefined : JSON.parse(body), { headers }));
+ }
+ const clientSleeps = [];
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bpf-stages-lock-'));
+ tempDirs.push(dir);
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: 'https://contoso.crm.dynamics.com', httpClient: createAzHttpClient('https://contoso.crm.dynamics.com', { getToken: () => 'token', request, sleep: async (ms) => { clientSleeps.push(ms); } }) });
+ await sdk.initWorkspace();
+ const d = DEPLOYED();
+ const want = flowOf([{ ...d.stages[0], name: 'Intake' }, d.stages[1], d.stages[2]]);
+ const inspected = await inspectBpfStages(sdk, want, id);
+ assert.strictEqual(inspected.kind, 'edit', JSON.stringify(inspected));
+ const pushed = await applyBpfStages(sdk, want, id, inspected.plan, {});
+ assert.strictEqual(pushed.saved, true);
+ assert.strictEqual(batches.length, 2, 'the refused change set and the SDK\u2019s one re-send of it');
+ assert.strictEqual(batches[1], batches[0], 'the same body: the guard under the same If-Match, the definition on the same row');
+ assert.deepStrictEqual(clientSleeps, [], 'the client sent the change set once: it waited for nothing');
+ assert.deepStrictEqual(fake.log.map((l) => l.verb), ['BATCH-PATCH', 'BATCH-PATCH'], 'only the accepted change set wrote anything');
+ assert.deepStrictEqual(xamlStages(row()), ['Intake', 'Resolve', 'Close']);
+ assert.strictEqual(row().statecode, 1, 'the flow is still Active');
+});
+
+test('REAL BUNDLE: an Active edit refused by the lock then edited by another maker fails its identical guarded resend without writing', async (t) => {
+ const { sdk, fake, id, row } = await realBpf();
+ const bodies = [];
+ fake.client.postRaw = async (url, body) => {
+ bodies.push(String(body));
+ const contentId = /Content-ID:\s*(\S+)/i.exec(String(body))[1];
+ if (bodies.length === 1) {
+ row().name = 'Another maker';
+ row()['@odata.etag'] = 'W/"99"';
+ return { status: 429, headers: { 'content-type': 'multipart/mixed; boundary=batchresponse_l' }, body: lockRefusedChangeSet(contentId) };
+ }
+ const validator = /^If-Match:\s*(.+)$/im.exec(String(body))[1].trim();
+ assert.notStrictEqual(validator, row()['@odata.etag'], 'the resend keeps the old guard, never a newly read token');
+ return { status: 200, headers: { 'content-type': 'multipart/mixed; boundary=batchresponse_l' }, body: lockRefusedChangeSet(contentId).replace('429 Too Many Requests', '412 Precondition Failed') };
+ };
+ const d = DEPLOYED();
+ const want = flowOf([{ ...d.stages[0], name: 'Intake' }, d.stages[1], d.stages[2]]);
+ const inspected = await inspectBpfStages(sdk, want, id);
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ await assert.rejects(settleBpfWaits(t, applyBpfStages(sdk, want, id, inspected.plan)), { code: 'version-conflict' });
+ assert.strictEqual(bodies.length, 2);
+ assert.strictEqual(bodies[1], bodies[0]);
+ assert.deepStrictEqual(fake.log, []);
+ assert.deepStrictEqual(xamlStages(row()), ['Triage', 'Resolve', 'Close']);
+ assert.strictEqual(row().name, 'Another maker');
+ assert.strictEqual(row().statecode, 1);
+});
+
+test('REAL BUNDLE: an ambiguous 503 envelope carrying a lock-refused part never authorizes an Active edit resend', async () => {
+ const { sdk, fake, id, row } = await realBpf();
+ let sends = 0;
+ fake.client.postRaw = async (url, body) => {
+ sends += 1;
+ return { status: 503, headers: { 'content-type': 'multipart/mixed; boundary=batchresponse_l' }, body: lockRefusedChangeSet(/Content-ID:\s*(\S+)/i.exec(String(body))[1]) };
+ };
+ const d = DEPLOYED();
+ const want = flowOf([{ ...d.stages[0], name: 'Intake' }, d.stages[1], d.stages[2]]);
+ const inspected = await inspectBpfStages(sdk, want, id);
+ await assert.rejects(applyBpfStages(sdk, want, id, inspected.plan), { code: 'CONNECTION_ERROR' });
+ assert.strictEqual(sends, 1);
+ assert.deepStrictEqual(fake.log, []);
+ assert.deepStrictEqual(xamlStages(row()), ['Triage', 'Resolve', 'Close']);
+});
+
+test('REAL BUNDLE: a fallback edit whose activation exhausts the lock waits succeeds when its bound compensation is acknowledged, keeping that write\'s token', async (t) => {
+ // The production client has postRaw and takes the in-place path above. This explicitly non-batch client pins the SDK's
+ // fallback contract too: a late, acknowledged activation is success, not a stale 429 that would make the builder replay it.
+ const { sdk, fake, id, row } = await realBpf({ atomic: false });
+ const patch = fake.client.patch;
+ const activationGuards = [];
+ fake.client.patch = async (url, body, options) => {
+ assert.strictEqual(options.headers['If-Match'], row()['@odata.etag'], 'every fallback write remains bound to its last acknowledged predecessor');
+ if (body.statecode === 1) {
+ activationGuards.push(options.headers['If-Match']);
+ if (activationGuards.length <= 38) return { status: 429, headers: {}, body: { error: { code: '0x80071151', message: 'Cannot start the requested operation [WorkflowSetState] because another customization is running.' } } };
+ }
+ return patch(url, body, options);
+ };
+ const d = DEPLOYED();
+ const want = flowOf([{ ...d.stages[0], name: 'Intake' }, d.stages[1], d.stages[2]]);
+ const inspected = await inspectBpfStages(sdk, want, id);
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const pushed = await settleBpfWaits(t, applyBpfStages(sdk, want, id, inspected.plan));
+ assert.strictEqual(pushed.saved, true);
+ assert.strictEqual(activationGuards.length, 39, '38 forward refusals, then the acknowledged bound compensation');
+ assert.strictEqual(new Set(activationGuards).size, 1, 'the compensation writes the same version, never another maker\'s edit');
+ assert.strictEqual(row().statecode, 1);
+ assert.deepStrictEqual(xamlStages(row()), ['Intake', 'Resolve', 'Close']);
+ // No fetch between the pushes: only the compensation's returned token can authorize this next edit.
+ await sdk.updateElement('bpf', id, '/stages/0/name', 'Screen');
+ assert.strictEqual((await settleBpfWaits(t, sdk.pushArtifact('bpf', id))).saved, true);
+ assert.deepStrictEqual(xamlStages(row()), ['Screen', 'Resolve', 'Close']);
+});
diff --git a/plugins/model-apps/scripts/tests/column-autonumber-gate.test.js b/plugins/model-apps/scripts/tests/column-autonumber-gate.test.js
index 4bd8f6676..ebc541d4b 100644
--- a/plugins/model-apps/scripts/tests/column-autonumber-gate.test.js
+++ b/plugins/model-apps/scripts/tests/column-autonumber-gate.test.js
@@ -121,10 +121,10 @@ test('an input whose AutoNumber column has a format is provisioned as before', a
});
// --- a downloaded spec passes the gate ----------------------------------------------------------------------------------------------
-// An auto-number column is a String attribute (formally a text column with a format), so the download reads it as Text and states no format: the spec it
-// makes never carries an AutoNumber column, with or without a format.
+// A positive mask distinguishes an AutoNumber from an ordinary String attribute. Both the column
+// and primary-name masks must survive so a fresh build cannot silently turn either into plain text.
-test('a downloaded auto-number column is declared Text with no autoNumberFormat, and the spec it makes passes the gate', () => {
+test('a downloaded auto-number column keeps its type and mask, and the spec it makes passes the gate', () => {
const attribute = (logicalName, extra) => ({ logicalName, displayName: logicalName, attributeType: 'String', isCustomAttribute: true, ...extra });
const meta = {
logicalName: 'new_ticket', schemaName: 'new_ticket', displayName: 'Ticket', primaryNameAttribute: 'new_name',
@@ -135,9 +135,10 @@ test('a downloaded auto-number column is declared Text with no autoNumberFormat,
],
};
const entity = entityFromMetadata(meta, 'new_ticket');
- assert.deepStrictEqual(entity.columns.map((c) => [c.schemaName, c.type]), [['new_ref', 'Text'], ['new_plain', 'Text']]);
- for (const c of entity.columns) assert.ok(!('autoNumberFormat' in c), `${c.schemaName} states no format`);
- assert.ok(!('autoNumberFormat' in entity.primaryAttribute), 'and neither does the name column');
+ assert.deepStrictEqual(entity.columns.map((c) => [c.schemaName, c.type]), [['new_ref', 'AutoNumber'], ['new_plain', 'Text']]);
+ assert.strictEqual(entity.columns[0].autoNumberFormat, 'C-{SEQNUM:5}');
+ assert.ok(!('autoNumberFormat' in entity.columns[1]), 'ordinary text gains no mask');
+ assert.strictEqual(entity.primaryAttribute.autoNumberFormat, 'WO-{SEQNUM:5}');
for (const profile of ['plan', 'deploy']) {
const result = validateAppSpec({ schemaVersion: 2, solution: { uniqueName: 'S', publisherPrefix: 'new' }, app: { name: 'A' }, entities: [entity], appShell: { areas: [] } }, { profile });
assert.deepStrictEqual(result.errors, [], profile);
diff --git a/plugins/model-apps/scripts/tests/dashboard-creation-recovery-real-bundle.test.js b/plugins/model-apps/scripts/tests/dashboard-creation-recovery-real-bundle.test.js
new file mode 100644
index 000000000..c2611b21f
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/dashboard-creation-recovery-real-bundle.test.js
@@ -0,0 +1,844 @@
+'use strict';
+// A dashboard the build CREATES joins the app's solution in a second request (AddSolutionComponent, component type 60), and the solution is
+// the only later proof that the dashboard is the app's: a name is neither unique nor compared exactly. When the run stops between the two —
+// the process is killed, the answer to the create is lost, or the membership add and the undo of the create both fail — the row is left
+// outside the solution. Nothing durable remembered it: the next build looked the dashboard up by name, and a dashboard that was created and
+// never published is in no plain read, so it made a SECOND one (or, once someone had published the first, reused it as a lone namesake
+// without adding it); teardown then kept the first, and a solution export left it out.
+//
+// The bundled SDK sends the workspace's own id as `systemform.formid` on the create, so the build knows the id before the request. It records
+// it in the workspace (lib/dashboard-creation-records.js) before the push, and clears it once the row is in the solution or the build's own
+// undo removed it. A later build reads that exact id in the SAVED layer before it looks anything up by name, and adds that row to the
+// solution — never another row, never on a name alone — and deletes nothing on the record's word.
+//
+// Over the REAL vendored SDK, the plugin's own HTTP client and the strict stateful fake of helpers/fake-lifecycle-org.js: a row created and
+// never published is in no plain collection read, RetrieveUnpublished answers it, and a missing id answers 404 0x80040217 (the SDK's
+// readSystemFormType records the last two as measured). A failure is provoked in front of the fake, for this test's own requests only, so the
+// environment holds what it would after a real one. A process that dies is a build whose request never answers, left unsettled — nothing of
+// it runs after that moment — and the next build is a new SDK on the same workspace, as a new process is.
+//
+// 1. the record itself (lib/dashboard-creation-records.js)
+// 2. a build stopped between the create and the membership add — killed, stranded, its create lost before or after it committed, the id
+// reported back changed — and the next build
+// 3. what the record never does: adopt a namesake, add a row that is no longer the one it recorded, delete anything, decide a teardown
+// 4. a record the build cannot read or write: the build is the one it was before there was a record, and says so once
+// 5. what is unchanged: an ordinary first build and an unchanged rebuild send exactly what they sent before
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');
+const { createLifecycleHarness } = require('./helpers/lifecycle-harness.js');
+const { createMakerSdk, createNodeWorkspaceStorage } = require('../lib/maker-sdk.js');
+const { isTransientHalt } = require('../build-model-app.js');
+const { sha256 } = require('../lib/hash.js');
+const { environmentFingerprint } = require('../lib/page-ownership-records.js');
+
+// Loaded where it is used, so that every test below fails on its own assertion when the module is not there.
+const records = () => require('../lib/dashboard-creation-records.js');
+
+const ENV = 'https://contoso.crm.dynamics.com';
+const ID_A = '11111111-aaaa-4aaa-8aaa-111111111111';
+const ID_B = '22222222-bbbb-4bbb-8bbb-222222222222';
+const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+const BOARD = 'Ops Overview';
+const SOLUTION = 'ContosoBoards';
+const APP = 'contoso_boards';
+
+// The smallest app that holds a dashboard the way a maker's does: built by the build, in its solution, in its navigation.
+const spec = () => ({
+ schemaVersion: 2,
+ solution: { uniqueName: SOLUTION, displayName: 'Contoso Boards', publisherPrefix: 'contoso' },
+ app: { name: 'Boards', uniqueName: APP },
+ entities: [{ schemaName: 'contact', displayName: 'Contact', existing: true, primaryAttribute: { schemaName: 'fullname', displayName: 'Full Name' }, columns: [] }],
+ dashboards: [{ name: BOARD, tiles: [{ type: 'iframe', url: 'https://contoso.example/status', name: 'Status' }] }],
+ appShell: { areas: [{ label: 'Work', groups: [{ label: 'Boards', subAreas: [{ dashboard: BOARD, title: 'Overview' }] }] }] },
+});
+
+// --- 1. the record -----------------------------------------------------------------------------------------------------------------------------------------
+
+const scratch = (prefix = 'dash-record-') => makeTempDir(prefix);
+const open = (dir, extra = {}) => records().openDashboardCreations({ workspaceDir: dir, environment: ENV, appUniqueName: APP, solutionUniqueName: SOLUTION, ...extra });
+
+test('the record: an id noted before the push is read back under any spelling Dataverse treats as the same name, by the next run too; a reported id is kept beside it; cleared, the file goes with its last entry', () => {
+ const dir = scratch();
+ const run = open(dir);
+ assert.equal(run.idsOf(BOARD), undefined, 'nothing recorded yet, and no file');
+ assert.equal(run.note(BOARD, ID_A.toUpperCase()), true, 'on disk');
+ assert.deepEqual(run.idsOf('OPS OVERVIEW '), [ID_A], 'a name is compared as Dataverse compares dashboard names; the id is kept in lower case');
+ assert.equal(run.observe(BOARD, ID_B), true, 'the id the push reported, when it is another one');
+ assert.deepEqual(open(dir).idsOf(BOARD), [ID_A, ID_B], 'the next run reads both observations, the one the build sent first');
+ const file = records().dashboardCreationRecordPath(dir, ENV, APP, SOLUTION);
+ assert.match(path.basename(file), /^dashboard-creation\.[0-9a-f]{64}\.json$/);
+ assert.deepEqual(JSON.parse(fs.readFileSync(file, 'utf8')).dashboards, { [BOARD]: { id: ID_A, reportedId: ID_B } });
+ assert.equal(run.clear(BOARD), true);
+ assert.equal(open(dir).idsOf(BOARD), undefined);
+ assert.equal(fs.existsSync(file), false, 'an empty record is no file');
+});
+
+test('the record is one file per environment, app and solution: another app, solution or environment in the same folder does not see it, the same origin written another way does', () => {
+ const dir = scratch();
+ open(dir).note(BOARD, ID_A);
+ assert.equal(open(dir, { appUniqueName: 'contoso_other' }).idsOf(BOARD), undefined, 'another app');
+ assert.equal(open(dir, { solutionUniqueName: 'ContosoOther' }).idsOf(BOARD), undefined, 'another solution');
+ assert.equal(open(dir, { environment: 'https://fabrikam.crm.dynamics.com' }).idsOf(BOARD), undefined, 'another environment');
+ assert.deepEqual(open(dir, { environment: `${ENV}/`, appUniqueName: APP.toUpperCase(), solutionUniqueName: SOLUTION.toLowerCase() }).idsOf(BOARD), [ID_A], 'the same origin, app and solution, spelt another way');
+});
+
+test('the record is the same bytes for the same dashboards, whatever order they were noted in', () => {
+ const [one, two] = [scratch(), scratch()];
+ const a = open(one);
+ a.note('Zeta', ID_A); a.note('alpha', ID_B);
+ const b = open(two);
+ b.note('alpha', ID_B); b.note('Zeta', ID_A);
+ const bytes = (dir) => fs.readFileSync(records().dashboardCreationRecordPath(dir, ENV, APP, SOLUTION));
+ assert.deepEqual(bytes(one), bytes(two));
+ assert.deepEqual(Object.keys(JSON.parse(bytes(one)).dashboards), ['alpha', 'Zeta'], 'sorted as Dataverse compares names');
+});
+
+// The exact bytes an ordinary record is written as — names that look like an index included, which JSON lists first in any object — so a change to
+// how the names are serialized cannot move one byte of a record the build already writes.
+test('ordinary names are written byte for byte as they always were', () => {
+ const dir = scratch();
+ const run = open(dir);
+ const ID_D = '44444444-dddd-4ddd-8ddd-444444444444';
+ assert.equal(run.note('Zeta', ID_A), true);
+ assert.equal(run.note('alpha', ID_B), true);
+ assert.equal(run.observe('alpha', ID_C), true);
+ assert.equal(run.note('2026', ID_D), true);
+ const expected = `{"schemaVersion":1,"environmentFingerprint":"${environmentFingerprint(ENV)}","appUniqueName":"${APP}","solutionUniqueName":"${SOLUTION.toLowerCase()}",`
+ + `"dashboards":{"2026":{"id":"${ID_D}"},"alpha":{"id":"${ID_B}","reportedId":"${ID_C}"},"Zeta":{"id":"${ID_A}"}}}\n`;
+ assert.equal(fs.readFileSync(records().dashboardCreationRecordPath(dir, ENV, APP, SOLUTION), 'utf8'), expected);
+});
+
+// `__proto__` is a legal dashboard name. Assigned to a plain object, it calls the inherited prototype setter instead of adding an entry, so the
+// record's JSON left the dashboard out — with no warning, since the write itself succeeded — and the next build could not find a create that
+// was interrupted before it joined the solution.
+test('a dashboard named __proto__ is recorded like any other name: written as an own key, read back by a fresh open, kept when another entry is cleared', () => {
+ const dir = scratch();
+ const run = open(dir);
+ assert.equal(run.note('__proto__', ID_A), true);
+ assert.equal(run.note(BOARD, ID_B), true);
+ const file = records().dashboardCreationRecordPath(dir, ENV, APP, SOLUTION);
+ const written = JSON.parse(fs.readFileSync(file, 'utf8')).dashboards;
+ assert.deepEqual(Object.keys(written), ['__proto__', BOARD], 'an own key of the file, sorted as Dataverse compares names');
+ assert.deepEqual(Object.getOwnPropertyDescriptor(written, '__proto__').value, { id: ID_A }, 'holding its id');
+ assert.deepEqual(open(dir).idsOf('__proto__'), [ID_A], 'a fresh open reads it back');
+ assert.deepEqual(open(dir).idsOf(BOARD), [ID_B]);
+ const next = open(dir);
+ assert.equal(next.observe('__proto__', ID_C), true, 'a reported id is kept beside it');
+ assert.equal(next.clear(BOARD), true);
+ assert.deepEqual(open(dir).idsOf('__proto__'), [ID_A, ID_C], 'clearing another entry keeps it');
+ assert.equal(open(dir).clear('__proto__'), true);
+ assert.equal(fs.existsSync(file), false, 'and clearing it is what removes the file');
+});
+
+// The reader takes what JSON.parse makes, and JSON.parse makes a `__proto__` key an OWN key (CreateDataProperty, never the setter); the reader
+// only lists those keys (Object.entries) into a Map, so nothing it reads is ever taken as a prototype.
+test('the reader takes a __proto__ key of the file as an ordinary entry: an own key, and no prototype changed', () => {
+ const dir = scratch();
+ const file = records().dashboardCreationRecordPath(dir, ENV, APP, SOLUTION);
+ const text = `{"schemaVersion":1,"environmentFingerprint":"${environmentFingerprint(ENV)}","appUniqueName":"${APP}","solutionUniqueName":"${SOLUTION.toLowerCase()}",`
+ + `"dashboards":{"__proto__":{"id":"${ID_A}"},"${BOARD}":{"id":"${ID_B}"}}}\n`;
+ fs.writeFileSync(file, text);
+ const parsed = JSON.parse(text).dashboards;
+ assert.equal(Object.prototype.hasOwnProperty.call(parsed, '__proto__'), true, 'JSON.parse makes it an own key');
+ assert.equal(Object.getPrototypeOf(parsed), Object.prototype, 'and changes no prototype');
+ const read = records().readDashboardCreations(dir, ENV, APP, SOLUTION);
+ assert.deepEqual([...read.entries()], [['__proto__', { name: '__proto__', id: ID_A }], ['ops overview', { name: BOARD, id: ID_B }]]);
+ assert.deepEqual(open(dir).idsOf('__proto__'), [ID_A]);
+ assert.equal(Object.prototype.hasOwnProperty.call(Object.prototype, 'id'), false, 'no object gained an id through a prototype');
+ assert.equal(fs.readFileSync(file, 'utf8'), text, 'and the file is as it was');
+});
+
+test('the record never stops a build: one it cannot read is "nothing recorded", said once, and is left exactly as it was — never overwritten; with no workspace or environment, or an id that is no id, nothing is recorded', () => {
+ const dir = scratch();
+ const file = records().dashboardCreationRecordPath(dir, ENV, APP, SOLUTION);
+ fs.writeFileSync(file, '{ not json');
+ const warnings = [];
+ const run = open(dir, { warn: (w) => warnings.push(w) });
+ assert.equal(run.idsOf(BOARD), undefined);
+ assert.equal(run.note(BOARD, ID_A), false, 'a file this build cannot read is not replaced by one that would lose what it held');
+ assert.equal(run.clear(BOARD), false);
+ assert.equal(warnings.length, 1, JSON.stringify(warnings));
+ assert.match(warnings[0], /could not be read .*so this build finds dashboards by name, as before, and records none of its own/);
+ assert.ok(warnings[0].includes(file), 'the warning names the file');
+ assert.equal(fs.readFileSync(file, 'utf8'), '{ not json', 'left exactly as it was');
+ for (const options of [{ workspaceDir: undefined }, { environment: undefined }, { solutionUniqueName: undefined }]) {
+ const none = open(dir, options);
+ assert.equal(none.note(BOARD, ID_A), false, JSON.stringify(options));
+ assert.equal(none.idsOf(BOARD), undefined);
+ }
+ assert.equal(open(scratch()).note(BOARD, 'not-a-guid'), false, 'an id that is no id is not recorded');
+});
+
+// An entry the build never writes — an id or a reported id that is no id, or two names Dataverse compares as one — is not skipped: what it
+// held may be the only trace of a dashboard outside its solution, and a record that went on being written would lose it (a note() replaced
+// the file, a clear() of the last good entry deleted it). The whole record is unreadable for the run, as a damaged file is.
+const ID_C = '33333333-cccc-4ccc-8ccc-333333333333';
+const MALFORMED_ENTRIES = [
+ ['a reported id that is no id', (dashboards) => { dashboards[BOARD].reportedId = 'damaged'; }],
+ ['an id that is no id', (dashboards) => { dashboards[BOARD].id = 'damaged'; }],
+ ['two names Dataverse compares as one', (dashboards) => { dashboards['OPS OVERVIEW '] = { id: ID_C }; }],
+];
+
+for (const [what, damage] of MALFORMED_ENTRIES) {
+ test(`an entry this build never writes — ${what} — makes the whole record unreadable: said once, nothing is read from it, not even a good sibling, and neither note() nor clear() writes or deletes it`, () => {
+ const dir = scratch();
+ const first = open(dir);
+ assert.equal(first.note(BOARD, ID_A), true);
+ assert.equal(first.note('Sibling', ID_B), true, 'a good sibling');
+ const file = records().dashboardCreationRecordPath(dir, ENV, APP, SOLUTION);
+ const record = JSON.parse(fs.readFileSync(file, 'utf8'));
+ damage(record.dashboards);
+ const bytes = Buffer.from(`${JSON.stringify(record)}\n`);
+ fs.writeFileSync(file, bytes);
+ const warnings = [];
+ const run = open(dir, { warn: (w) => warnings.push(w) });
+ assert.equal(run.idsOf(BOARD), undefined, 'nothing is read from it');
+ assert.equal(run.idsOf('Sibling'), undefined, 'not even the good sibling');
+ assert.equal(run.note('Another', ID_C), false, 'note() does not write over it');
+ assert.equal(run.observe('Sibling', ID_C), false, 'observe() does not either');
+ assert.equal(run.clear('Sibling'), false, 'clear() does not delete it');
+ assert.deepEqual(fs.readFileSync(file), bytes, 'its bytes are left intact');
+ assert.equal(warnings.length, 1, `said once: ${JSON.stringify(warnings)}`);
+ assert.match(warnings[0], /could not be read .*so this build finds dashboards by name, as before, and records none of its own/);
+ });
+}
+
+// --- the environment ---------------------------------------------------------------------------------------------------------------------------------------
+
+// A fake environment, and a seam in front of its transport that answers what a test's faults name instead of the fake. A refused request
+// never reaches the fake, so the environment holds what it would after a real refusal. A Dataverse refusal is an OData error:
+// { "error": { "code": "0x80040216", "message": "An unexpected error occurred." } }
+// See: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/compose-http-requests-handle-errors#parse-errors-from-the-response
+function environment() {
+ const org = createLifecycleOrg();
+ const faults = [];
+ const request = async (req) => {
+ const url = new URL(req.url);
+ const where = decodeURIComponent(url.pathname + url.search).replace(/^\/api\/data\/v9\.\d/, '');
+ let body = {};
+ try { body = typeof req.body === 'string' && req.body ? JSON.parse(req.body) : {}; } catch { /* a $batch or bytes: no JSON to match on */ }
+ const fault = faults.find((f) => f.method === req.method && f.matches(where, body));
+ if (!fault) return org.request(req);
+ fault.hits += 1;
+ return fault.answer(req, body);
+ };
+ const add = (method, matches, answer) => {
+ const fault = { method, matches, answer, hits: 0 };
+ faults.push(fault);
+ return { lift: () => { faults.splice(faults.indexOf(fault), 1); return fault.hits; } };
+ };
+ const harness = createLifecycleHarness({ ...org, request }, makeTempDir('dash-recovery-'));
+ return { org, harness, add };
+}
+
+const refusedWith = (statusCode, code, message) => () => ({ statusCode, headers: { 'content-type': 'application/json; odata.metadata=minimal' }, body: JSON.stringify({ error: { code, message } }) });
+// What lib/dataverse-auth.js makeRequest answers when the connection is reset before an answer arrives.
+const resetConnection = () => ({ error: 'read ECONNRESET', code: 'ECONNRESET' });
+
+const isDashboardMembership = (where, body) => where === '/AddSolutionComponent' && Number(body.ComponentType) === 60;
+const isDashboardCreate = (where, body) => /^\/systemforms(\?|$)/.test(where) && String(body.type) === '0';
+// GET /systemforms(<id>)/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,name,type — the build's read of a recorded id.
+const isRecordRead = (id) => (where) => where === `/systemforms(${id})/Microsoft.Dynamics.CRM.RetrieveUnpublished()?$select=formid,name,type`;
+
+// What a maker does in Maker, sent to the fake as the Web API call Maker makes — around the seam, which only the build's requests pass.
+async function inMaker(org, method, where, body) {
+ const res = await org.request({ url: `${org.API}${where}`, method, headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
+ assert.ok(res.statusCode < 300, `${method} ${where} answered ${res.statusCode}: ${res.body}`);
+}
+const publishDashboard = (org, id) => inMaker(org, 'POST', '/PublishXml', { ParameterXml: `<importexportxml><dashboards><dashboard>${id}</dashboard></dashboards></importexportxml>` });
+
+// The dashboards named BOARD the environment holds, saved layer (published or not), and the ones the app's solution holds.
+const boards = (org) => org.find('systemforms', (f) => Number(f.type) === 0 && f.name === BOARD).map((f) => String(f.formid).toLowerCase());
+const allDashboards = (org) => org.find('systemforms', (f) => Number(f.type) === 0).map((f) => String(f.formid).toLowerCase());
+function members(org) {
+ const [solution] = org.find('solutions', (s) => s.uniquename === SOLUTION);
+ if (!solution) return [];
+ return org.solutionComponents().filter((c) => Number(c.componenttype) === 60 && String(c._solutionid_value).toLowerCase() === String(solution.solutionid).toLowerCase()).map((c) => String(c.objectid).toLowerCase());
+}
+// What a step sent, from the fake's own record of the requests that reached it.
+const creates = (org, mark) => org.since(mark).filter((r) => r.method === 'POST' && isDashboardCreate(r.path, r.body || {})).map((r) => String(r.body.formid).toLowerCase());
+const memberships = (org, mark, id) => org.since(mark).filter((r) => r.method === 'POST' && isDashboardMembership(r.path, r.body || {}) && (!id || String(r.body.ComponentId).toLowerCase() === id));
+const formDeletes = (org, mark) => org.since(mark).filter((r) => r.method === 'DELETE' && /^\/systemforms\(/.test(r.path)).map((r) => r.path);
+const recordReads = (org, mark, id) => org.since(mark).filter((r) => r.method === 'GET' && isRecordRead(id)(r.path));
+
+// The record, as the file the build keeps for this app's dashboards in this environment:
+// dashboard-creation.<sha256 of [environment fingerprint, app unique name, solution unique name]>.json
+// computed here and not by the module, so a test fails on what the build did when the module is missing.
+const recordFile = (env) => path.join(env.harness.workspaceDir, `dashboard-creation.${sha256(JSON.stringify([environmentFingerprint(env.org.origin), APP, SOLUTION.toLowerCase()]))}.json`);
+function recorded(env) {
+ try { return JSON.parse(fs.readFileSync(recordFile(env), 'utf8')).dashboards; } catch (e) { if (e.code === 'ENOENT') return null; throw e; }
+}
+// A record of the shape the build writes, for this environment, app and solution, holding `dashboards` as given.
+function plantRecord(file, env, dashboards) {
+ fs.writeFileSync(file, `${JSON.stringify({ schemaVersion: 1, environmentFingerprint: environmentFingerprint(env.org.origin), appUniqueName: APP, solutionUniqueName: SOLUTION.toLowerCase(), dashboards })}\n`);
+}
+const recordFiles = (env) => fs.readdirSync(env.harness.workspaceDir).filter((name) => name.startsWith('dashboard-creation.'));
+
+// A measured step ran: it did not throw, and every request it sent is one the fake models.
+function ran(step, label) {
+ assert.ok(step, `${label} ran`);
+ if (step.error) throw step.error;
+ assert.deepEqual(step.unexpected, [], `every request ${label} sent is one the fake models`);
+ return step;
+}
+
+// The build is killed the moment it sends the new dashboard's membership add: that request never answers, and nothing of the run happens after
+// it — no undo, no record cleared, no app. Answers the id the add named, which is the row the create committed. `buildSpec` is the spec it builds.
+async function dieAtMembership(env, buildSpec = spec) {
+ let named;
+ const reached = new Promise((resolve) => { named = resolve; });
+ const fault = env.add('POST', isDashboardMembership, (req, body) => { named(String(body.ComponentId).toLowerCase()); return new Promise(() => {}); });
+ let settled = false;
+ env.harness.build(buildSpec()).then(() => { settled = true; }, () => { settled = true; });
+ const id = await reached;
+ fault.lift();
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(settled, false, 'the killed build never finishes');
+ return id;
+}
+
+// --- 2. a build stopped between the create and the membership add, and the next build -----------------------------------------------------------------------
+
+// What a maker may do in Maker between the killed build and the next one: nothing, publish the dashboard (it is then in the plain reads the name lookup
+// makes), or add it to the solution by hand (the add the next build makes is then a no-op: the solution never holds a component twice).
+const IN_BETWEEN = [
+ ['', async () => {}],
+ [' (a maker published it in between)', (env, id) => publishDashboard(env.org, id)],
+ [' (a maker added it to the solution in between)', (env, id) => inMaker(env.org, 'POST', '/AddSolutionComponent', { ComponentId: id, ComponentType: 60, SolutionUniqueName: SOLUTION, AddRequiredComponents: false })],
+];
+for (const [inBetween, makerDoes] of IN_BETWEEN) {
+ test(`a build killed between creating a dashboard and adding it to the solution: the next build — a new process on the same workspace — adds that same dashboard to the solution and reuses it, creates none, and teardown then removes it${inBetween}`, async () => {
+ const env = environment();
+ const id = await dieAtMembership(env);
+ assert.deepEqual(boards(env.org), [id], 'the create committed: one dashboard, under the id the build sent');
+ assert.deepEqual(members(env.org), [], 'outside the solution');
+ const left = recorded(env);
+ await makerDoes(env, id);
+
+ const rerun = ran(await env.harness.measure(() => env.harness.build(spec())), 'the next build');
+ assert.equal(rerun.value.result.ok, true, JSON.stringify(rerun.value.result.errors));
+ assert.deepEqual(creates(env.org, rerun.mark), [], 'no second dashboard is created');
+ assert.equal(memberships(env.org, rerun.mark, id).length, 1, 'the dashboard the killed build created is added to the solution');
+ assert.deepEqual(boards(env.org), [id], 'exactly one dashboard of that name');
+ assert.deepEqual(members(env.org), [id], 'and the solution holds it');
+ assert.equal(rerun.value.result.created.dashboards[BOARD], id, 'reused: the navigation points at it');
+ assert.deepEqual(env.org.since(rerun.mark).filter((r) => ['PATCH', 'PUT'].includes(r.method) && r.path.startsWith(`/systemforms(${id})`)).map((r) => `${r.method} ${r.path}`), [], 'its tiles are not rewritten: it is reused as the killed build pushed it');
+ assert.ok(!rerun.value.warnings.some((w) => /not in this app's solution/.test(w)), `no namesake warning: it is in the solution now. ${JSON.stringify(rerun.value.warnings)}`);
+
+ assert.deepEqual(left, { [BOARD]: { id } }, 'the killed build had recorded the id before it pushed');
+ assert.deepEqual(recordReads(env.org, rerun.mark, id).map((r) => r.status), [200], 'the next build read that id once, in the saved layer');
+ assert.ok(rerun.value.log.some((line) => line.includes(`dashboard "${BOARD}" (created by an interrupted build as ${id} — added to the solution, and reused)`)), 'and says what it did');
+ assert.equal(recorded(env), null, 'the record is cleared once the row is in the solution');
+
+ const teardown = ran(await env.harness.measure(() => env.harness.teardown(spec())), 'the teardown');
+ assert.equal(teardown.value.result.ok, true, JSON.stringify(teardown.value.result.errors));
+ assert.deepEqual(allDashboards(env.org), [], 'ALL ABSENT: teardown deletes it as a member of the solution — no orphan is left');
+ });
+}
+
+// A legal name that a plain JavaScript object cannot hold as a key: `__proto__`. The dashboard is built beside ordinary navigation (a table), as a
+// spec can declare a dashboard its sitemap does not open.
+const PROTO = '__proto__';
+const protoSpec = () => ({
+ ...spec(),
+ dashboards: [{ name: PROTO, tiles: [{ type: 'iframe', url: 'https://contoso.example/status', name: 'Status' }] }],
+ appShell: { areas: [{ label: 'Work', groups: [{ label: 'Records', subAreas: [{ entity: 'contact', title: 'Contacts' }] }] }] },
+});
+const named = (org, name) => org.find('systemforms', (f) => Number(f.type) === 0 && f.name === name).map((f) => String(f.formid).toLowerCase());
+
+test('a build killed before adding a dashboard named __proto__ to the solution: the record keeps its id as it keeps any name, and the next build adds that same dashboard and creates none', async () => {
+ const env = environment();
+ const id = await dieAtMembership(env, protoSpec);
+ assert.deepEqual(named(env.org, PROTO), [id], 'the create committed');
+ assert.deepEqual(members(env.org), [], 'outside the solution');
+ const left = recorded(env);
+ const rerun = ran(await env.harness.measure(() => env.harness.build(protoSpec())), 'the next build');
+ assert.equal(rerun.value.result.ok, true, JSON.stringify(rerun.value.result.errors));
+ assert.deepEqual(creates(env.org, rerun.mark), [], 'no second dashboard is created');
+ assert.equal(memberships(env.org, rerun.mark, id).length, 1, 'the dashboard the killed build created is added to the solution');
+ assert.deepEqual(named(env.org, PROTO), [id]);
+ assert.deepEqual(members(env.org), [id]);
+ assert.deepEqual(left, { [PROTO]: { id } }, 'the killed build had recorded it, under its own name');
+ assert.deepEqual(recordReads(env.org, rerun.mark, id).map((r) => r.status), [200], 'and the next build read that id in the saved layer');
+ assert.equal(recorded(env), null, 'the record is cleared once the row is in the solution');
+});
+
+test('a dashboard the build could neither add to its solution nor remove again: the halt says a run again adds it, and the next run adds that same dashboard', async () => {
+ const env = environment();
+ let id;
+ const lifts = [
+ env.add('POST', isDashboardMembership, (req, body) => { id = String(body.ComponentId).toLowerCase(); return refusedWith(400, '0x80040216', 'An unexpected error occurred.')(); }),
+ env.add('DELETE', (where) => /^\/systemforms\([0-9a-f-]{36}\)$/.test(where), refusedWith(400, '0x80040216', 'The dashboard could not be deleted.')),
+ // The undo's plain read of the row, which cannot be read either: the build assumes it is still there (it is).
+ env.add('GET', (where) => /^\/systemforms\?\$select=formid&\$filter=formid eq [0-9a-f-]{36}&\$top=1$/.test(where), refusedWith(400, '0x80040216', 'An unexpected error occurred.')),
+ ];
+ const failed = await env.harness.measure(() => env.harness.build(spec()));
+ for (const fault of lifts) fault.lift();
+ assert.ok(failed.error, 'the build stops');
+ assert.match(failed.error.message, new RegExp(`dashboard "${BOARD}" was created \\(${id}\\) but could not be added to solution '${SOLUTION}' \\(.*An unexpected error occurred.*\\), and removing it again failed \\(.*could not be deleted.*\\)`));
+ assert.equal(isTransientHalt(failed.error), false, 'never run again on its own');
+ assert.deepEqual(boards(env.org), [id], 'stranded: the row is there');
+ const left = recorded(env);
+
+ const rerun = ran(await env.harness.measure(() => env.harness.build(spec())), 'the next build');
+ assert.equal(rerun.value.result.ok, true, JSON.stringify(rerun.value.result.errors));
+ assert.deepEqual(creates(env.org, rerun.mark), [], 'no second dashboard is created');
+ assert.equal(memberships(env.org, rerun.mark, id).length, 1, 'the stranded dashboard is added to the solution');
+ assert.deepEqual(boards(env.org), [id]);
+ assert.deepEqual(members(env.org), [id]);
+
+ assert.deepEqual(left, { [BOARD]: { id } }, 'the stranded halt keeps the record');
+ assert.match(failed.error.message, /— this build recorded it, so running the build again adds it to the solution and reuses it; or delete it in Maker before running it again, and it is created afresh/);
+ assert.equal(recorded(env), null);
+});
+
+test('the undo fails at the row and its plain read misses the never-published row: the record is kept all the same, and the build\'s own run again adds that same dashboard', async () => {
+ const env = environment();
+ let id;
+ let refusals = 1;
+ // The customization lock refuses the membership add once — a refusal a run again rides out (lib/retry-policy.js) — and the row cannot be
+ // deleted. The undo's plain read answers the PUBLISHED layer, where a dashboard nobody published is not: the build reports it removed.
+ const lifts = [
+ env.add('POST', (where, body) => isDashboardMembership(where, body) && refusals > 0 && (refusals -= 1, true), (req, body) => {
+ id = String(body.ComponentId).toLowerCase();
+ return refusedWith(400, '0x80071151', 'Cannot start the requested operation [AddSolutionComponent] because there is another [Import] running at this moment.')();
+ }),
+ env.add('DELETE', (where) => /^\/systemforms\([0-9a-f-]{36}\)$/.test(where), refusedWith(400, '0x80040216', 'The dashboard could not be deleted.')),
+ ];
+ const built = await env.harness.measure(() => env.harness.build(spec()));
+ for (const fault of lifts) fault.lift();
+ ran(built, 'the build and its own run again');
+ assert.equal(built.value.result.ok, true, JSON.stringify(built.value.result.errors));
+ assert.equal(creates(env.org, built.mark).length, 1, 'one create in both attempts: the run again made no second dashboard');
+ assert.deepEqual(boards(env.org), [id]);
+ assert.deepEqual(members(env.org), [id], 'the dashboard the first attempt created is in the solution');
+ assert.equal(built.value.result.created.dashboards[BOARD], id);
+ assert.equal(recorded(env), null);
+});
+
+test('a dashboard create that never reached the service: the record names an id no row has, and the next run reads it, clears it and creates exactly one', async () => {
+ const env = environment();
+ const lose = env.add('POST', isDashboardCreate, resetConnection);
+ const failed = await env.harness.measure(() => env.harness.build(spec()));
+ assert.ok(lose.lift() > 0, 'the create was sent');
+ assert.ok(failed.error, 'the build stops');
+ assert.deepEqual(allDashboards(env.org), [], 'no row was created');
+ const left = recorded(env);
+
+ const rerun = ran(await env.harness.measure(() => env.harness.build(spec())), 'the next build');
+ assert.equal(rerun.value.result.ok, true, JSON.stringify(rerun.value.result.errors));
+ assert.equal(creates(env.org, rerun.mark).length, 1, 'exactly one dashboard is created');
+ const [only] = boards(env.org);
+ assert.deepEqual(members(env.org), [only]);
+ assert.equal(recorded(env), null);
+
+ assert.ok(left && left[BOARD] && GUID.test(left[BOARD].id), `the create was recorded before it was sent: ${JSON.stringify(left)}`);
+ assert.notEqual(only, left[BOARD].id, 'the new dashboard has an id of its own');
+ assert.deepEqual(recordReads(env.org, rerun.mark, left[BOARD].id).map((r) => r.status), [404], 'the recorded id was read in the saved layer, and no row has it');
+});
+
+// Following a halt's workspace reset: everything goes but the files the advice names — read from the advice itself, so a record the
+// advice forgets is deleted here as an operator would delete it.
+function followResetAdvice(dir, advice) {
+ assert.match(advice, /then delete everything in it except /);
+ const keep = [...advice.matchAll(/\b[a-z][a-z0-9-]*(?:\.[a-z0-9*-]+)*\.json\b/g)].map(([name]) => new RegExp(`^${name.split('*').map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('.*')}$`));
+ for (const name of fs.readdirSync(dir)) if (!keep.some((pattern) => pattern.test(name))) fs.rmSync(path.join(dir, name), { recursive: true, force: true });
+}
+
+test('a dashboard create whose answer was lost after it committed: the halt asks for a workspace reset, the reset keeps the record, and the next run adds that dashboard to the solution', async () => {
+ const env = environment();
+ let lostOne = false;
+ // The first create reaches the service and commits; its answer is lost. The client sends it again, and the service refuses the id it holds.
+ const lose = env.add('POST', (where, body) => isDashboardCreate(where, body) && !lostOne, async (req) => { lostOne = true; await env.org.request(req); return resetConnection(); });
+ const failed = await env.harness.measure(() => env.harness.build(spec()));
+ lose.lift();
+ assert.ok(failed.error, 'the build stops');
+ assert.equal(failed.error.code, 'already-exists', failed.error.message);
+ const [id] = boards(env.org);
+ assert.deepEqual(boards(env.org), [id], 'one row: the one the lost answer was for');
+ const left = recorded(env);
+ followResetAdvice(env.harness.workspaceDir, failed.error.message);
+
+ const rerun = ran(await env.harness.measure(() => env.harness.build(spec())), 'the next build');
+ assert.equal(rerun.value.result.ok, true, JSON.stringify(rerun.value.result.errors));
+ assert.deepEqual(creates(env.org, rerun.mark), [], 'no second dashboard is created');
+ assert.equal(memberships(env.org, rerun.mark, id).length, 1, 'that dashboard is added to the solution');
+ assert.deepEqual(boards(env.org), [id]);
+ assert.deepEqual(members(env.org), [id]);
+
+ assert.deepEqual(left, { [BOARD]: { id } }, 'the create was recorded before it was sent');
+ assert.match(failed.error.message, /dashboard-creation\.\*\.json/, 'the reset advice keeps the record');
+ assert.equal(recorded(env), null);
+});
+
+test('the push reports another id than the one the build sent: both are recorded, and the next run adds the one that exists — not the one it sent', async () => {
+ const env = environment();
+ const reported = '0d0d0d0d-0000-4000-8000-00000000000d';
+ // A service that keeps another id than the client-minted one it was sent: the create's own answer (`Prefer: return=representation`) names it.
+ const rekey = env.add('POST', isDashboardCreate, (req, body) => env.org.request({ ...req, body: JSON.stringify({ ...body, formid: reported }) }));
+ const id = await dieAtMembership(env);
+ rekey.lift();
+ assert.equal(id, reported, 'the build went on with the id the service reported');
+ const left = recorded(env);
+
+ const rerun = ran(await env.harness.measure(() => env.harness.build(spec())), 'the next build');
+ assert.deepEqual(creates(env.org, rerun.mark), [], 'no second dashboard is created');
+ assert.equal(memberships(env.org, rerun.mark, reported).length, 1, 'the row that exists is added');
+ assert.deepEqual(boards(env.org), [reported]);
+ assert.deepEqual(members(env.org), [reported]);
+
+ assert.ok(left && left[BOARD] && GUID.test(left[BOARD].id) && left[BOARD].id !== reported, `the id the build sent is kept: ${JSON.stringify(left)}`);
+ assert.equal(left[BOARD].reportedId, reported, 'beside the id the service reported');
+ assert.deepEqual(recordReads(env.org, rerun.mark, left[BOARD].id).map((r) => r.status), [404], 'each was read: the one sent names no row');
+ assert.deepEqual(recordReads(env.org, rerun.mark, reported).map((r) => r.status), [200]);
+});
+
+// Two builds that share the workspace, one of them creating the dashboard. A has noted the id it sends its create with; B reads that entry and, settling
+// it, reads the id in the saved layer — and no row has it, because the service gave A's create another id. Before B's read is answered, A's push is,
+// and A records the id the service reported. B's conclusion "absent" is about the older entry only: its clear must leave the newer one, and B must not
+// create a second dashboard on that older word.
+test('a build settling an entry that another build changed after it read it — recording the id its push reported — stops: nothing created, added or deleted, and the record keeps both ids', async () => {
+ const env = environment();
+ const sent = '0a0a0a0a-1111-4111-8111-00000000000a';
+ const reported = '0b0b0b0b-1111-4111-8111-00000000000b';
+ const A = records().openDashboardCreations({ workspaceDir: env.harness.workspaceDir, environment: env.org.origin, appUniqueName: APP, solutionUniqueName: SOLUTION });
+ assert.equal(A.note(BOARD, sent), true, 'A notes the id it sends its create with');
+ // The row A's create made, under the id the service gave it: never published, outside the solution.
+ await inMaker(env.org, 'POST', '/systemforms', { formid: reported, name: BOARD, type: 0, formxml: '<form><tabs /></form>' });
+ const answered = env.add('GET', isRecordRead(sent), (req) => {
+ assert.equal(A.observe(BOARD, reported), true, 'A records the id its push reported');
+ return env.org.request(req);
+ });
+ const halted = await env.harness.measure(() => env.harness.build(spec()));
+ assert.equal(answered.lift(), 1, 'B read the id it read from the record');
+ assert.deepEqual(creates(env.org, halted.mark), [], 'no second dashboard is created');
+ assert.deepEqual(memberships(env.org, halted.mark), [], 'nothing is added to the solution');
+ assert.deepEqual(formDeletes(env.org, halted.mark), [], 'nothing is deleted');
+ assert.ok(halted.error, 'B stops');
+ assert.match(halted.error.message, new RegExp(`dashboard "${BOARD}": the record this build read named ${sent} for it — a create an earlier build had not seen join solution '${SOLUTION}' — and no row has that id now, but another build sharing this workspace has changed that entry of .*dashboard-creation\\.[0-9a-f]{64}\\.json since this build read it\\. Nothing was added to the solution or deleted, and no dashboard was created: this build does not act on what it read\\. Run the build again once the other build has finished; it then reads the record as it is\\.`));
+ assert.doesNotMatch(halted.error.message, /(?<!not )\bdelete\b/i, 'it asks for no dashboard to be deleted');
+ assert.deepEqual(recorded(env), { [BOARD]: { id: sent, reportedId: reported } }, 'the record keeps both ids');
+ assert.deepEqual(boards(env.org), [reported]);
+ assert.deepEqual(halted.unexpected, []);
+ // Once A has stopped, the next build reads the record as it is now and adds the row A's create made.
+ const rerun = ran(await env.harness.measure(() => env.harness.build(spec())), 'the next build');
+ assert.deepEqual(creates(env.org, rerun.mark), [], 'still no dashboard is created');
+ assert.equal(memberships(env.org, rerun.mark, reported).length, 1, 'the row A\'s create made is added');
+ assert.deepEqual(members(env.org), [reported]);
+ assert.equal(recorded(env), null);
+});
+
+// --- 3. what the record never does ---------------------------------------------------------------------------------------------------------------------------
+
+// Another maker's dashboard of the same name, made and published in Maker, in no solution of this app.
+async function foreignDashboard(env) {
+ const other = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(makeTempDir('dash-foreign-')), instanceUrl: env.org.origin, httpClient: env.harness.client });
+ await other.initWorkspace();
+ const art = await other.createArtifact('dashboard', { name: BOARD });
+ const pushed = await other.pushArtifact('dashboard', art.id);
+ await publishDashboard(env.org, pushed.id);
+ return String(pushed.id).toLowerCase();
+}
+
+test('the record names a dashboard deleted since, and another maker has made one of that name: the record is cleared, the other one is NOT added to the solution, and it is reused with the warning it always had', async () => {
+ const env = environment();
+ const id = await dieAtMembership(env);
+ await inMaker(env.org, 'DELETE', `/systemforms(${id})`);
+ const foreign = await foreignDashboard(env);
+ const before = env.org.contents()[`row systemforms ${foreign}`];
+
+ const rerun = ran(await env.harness.measure(() => env.harness.build(spec())), 'the next build');
+ assert.equal(rerun.value.result.ok, true, JSON.stringify(rerun.value.result.errors));
+ assert.deepEqual(memberships(env.org, rerun.mark, foreign), [], 'another maker\'s dashboard is never added to this app\'s solution');
+ assert.deepEqual(members(env.org), []);
+ assert.deepEqual(creates(env.org, rerun.mark), [], 'a lone namesake is reused, as before');
+ assert.equal(rerun.value.result.created.dashboards[BOARD], foreign);
+ assert.ok(rerun.value.warnings.some((w) => w.includes(`dashboard "${BOARD}": the one dashboard with this name is not in this app's solution '${SOLUTION}', so nothing proves it is this app's`)), JSON.stringify(rerun.value.warnings));
+ assert.deepEqual(formDeletes(env.org, rerun.mark), [], 'nothing is deleted');
+ assert.deepEqual(env.org.contents()[`row systemforms ${foreign}`].content.saved.formxml, before.content.saved.formxml, 'and the other dashboard is as it was');
+ assert.equal(recorded(env), null, 'the record of a row that is gone is cleared');
+});
+
+// What a later build does when the recorded id answers, but not as the dashboard the killed build created: nothing is added or deleted, no
+// second dashboard is made, the record stays, and the build stops with what a maker can do.
+const DISAGREEMENTS = [
+ {
+ what: 'renamed in Maker since',
+ change: (env, id) => inMaker(env.org, 'PATCH', `/systemforms(${id})`, { name: 'Ops Overview (old)' }),
+ message: (id) => new RegExp(`dashboard "${BOARD}": an earlier build created it as ${id} and stopped before adding it to solution '${SOLUTION}', and that dashboard is now named 'Ops Overview \\(old\\)'\\. Nothing was added to the solution or deleted\\. If it is this app's, rename it back to '${BOARD}' in Maker and run the build again: it is then added to the solution and reused\\. If it is not wanted, delete it in Maker and run the build again: '${BOARD}' is then created afresh\\.`),
+ restore: (env, id) => inMaker(env.org, 'PATCH', `/systemforms(${id})`, { name: BOARD }),
+ },
+ {
+ what: 'no longer a dashboard (the id names a Main form now)',
+ change: async (env, id) => {
+ await inMaker(env.org, 'DELETE', `/systemforms(${id})`);
+ await inMaker(env.org, 'POST', '/systemforms', { formid: id, name: BOARD, type: 2, objecttypecode: 'contact', formxml: '<form><tabs /></form>' });
+ },
+ message: (id) => new RegExp(`dashboard "${BOARD}": an earlier build recorded ${id} for it before it stopped, and that id now names a systemform of type 2, not a dashboard of the kind the build creates \\(type 0\\)\\. Nothing was added to the solution or deleted\\. Check the id, then remove the entry '${BOARD}' from .*dashboard-creation\\.[0-9a-f]{64}\\.json and run the build again\\.`),
+ },
+ {
+ what: 'unreadable (the read of the id is refused)',
+ change: (env, id) => { env.unreadable = env.add('GET', isRecordRead(id), refusedWith(403, '0x80040220', 'Principal user is missing prvReadSystemForm privilege.')); },
+ message: (id) => new RegExp(`dashboard "${BOARD}": an earlier build created it as ${id} and stopped before adding it to solution '${SOLUTION}', and whether it still exists could not be read \\(.*prvReadSystemForm.*\\)\\. Nothing was added to the solution or deleted, and no second dashboard was created; run the build again\\.`),
+ restore: (env) => env.unreadable.lift(),
+ },
+];
+
+for (const { what, change, message, restore } of DISAGREEMENTS) {
+ test(`the record names a dashboard ${what}: the next build adds nothing, deletes nothing, creates no second dashboard, keeps the record and stops with what to do${restore ? ' — and once that is done, it adds the dashboard' : ''}`, async () => {
+ const env = environment();
+ const id = await dieAtMembership(env);
+ await change(env, id);
+ const halted = await env.harness.measure(() => env.harness.build(spec()));
+ assert.deepEqual(creates(env.org, halted.mark), [], 'no second dashboard is created');
+ assert.deepEqual(memberships(env.org, halted.mark), [], 'nothing is added to the solution');
+ assert.deepEqual(formDeletes(env.org, halted.mark), [], 'nothing is deleted');
+ assert.ok(halted.error, 'the build stops');
+ assert.match(halted.error.message, message(id));
+ assert.deepEqual(recorded(env), { [BOARD]: { id } }, 'the record is kept');
+ assert.deepEqual(halted.unexpected, []);
+ assert.equal(isTransientHalt(halted.error), false, 'a person decides; the build does not run again on its own');
+ if (!restore) return;
+ await restore(env, id);
+ const rerun = ran(await env.harness.measure(() => env.harness.build(spec())), 'the build once it is settled');
+ assert.equal(memberships(env.org, rerun.mark, id).length, 1);
+ assert.deepEqual(boards(env.org), [id]);
+ assert.deepEqual(members(env.org), [id]);
+ assert.equal(recorded(env), null);
+ });
+}
+
+test('the record names a dashboard the service still answers to, but its add to the solution is refused now: the build stops, deletes nothing, keeps the record — and the next run adds it', async () => {
+ const env = environment();
+ const id = await dieAtMembership(env);
+ const refuse = env.add('POST', isDashboardMembership, refusedWith(403, '0x80040220', 'Principal user is missing prvWriteSolution privilege.'));
+ const halted = await env.harness.measure(() => env.harness.build(spec()));
+ refuse.lift();
+ assert.ok(halted.error, 'the build stops');
+ assert.deepEqual(creates(env.org, halted.mark), [], 'no second dashboard is created');
+ assert.deepEqual(formDeletes(env.org, halted.mark), [], 'nothing is deleted: not on the record\'s word');
+ assert.match(halted.error.message, new RegExp(`dashboard "${BOARD}" \\(${id}\\), which an earlier build created and stopped before adding to solution '${SOLUTION}', could not be added to it now \\(.*prvWriteSolution.*\\)\\. Nothing was deleted, and the record of it is kept: run the build again to add it\\.`));
+ assert.equal(isTransientHalt(halted.error), false, 'a 403 is final: the build does not run again on its own');
+ assert.deepEqual(boards(env.org), [id]);
+ assert.deepEqual(recorded(env), { [BOARD]: { id } });
+ const rerun = ran(await env.harness.measure(() => env.harness.build(spec())), 'the next build');
+ assert.equal(memberships(env.org, rerun.mark, id).length, 1);
+ assert.deepEqual(members(env.org), [id]);
+ assert.equal(recorded(env), null);
+});
+
+test('both ids the record holds answer — the one the build sent and the one the service reported: the build cannot tell which it created, adds neither, deletes neither, and stops with a way out that deletes nothing', async () => {
+ const env = environment();
+ const reported = '0e0e0e0e-0000-4000-8000-00000000000e';
+ const rekey = env.add('POST', isDashboardCreate, (req, body) => env.org.request({ ...req, body: JSON.stringify({ ...body, formid: reported }) }));
+ await dieAtMembership(env);
+ rekey.lift();
+ const left = recorded(env);
+ assert.ok(left && left[BOARD] && left[BOARD].reportedId === reported, JSON.stringify(left));
+ const sent = left[BOARD].id;
+ // A dashboard of that name under the id the build sent, made in Maker since.
+ await inMaker(env.org, 'POST', '/systemforms', { formid: sent, name: BOARD, type: 0, formxml: '<form><tabs /></form>' });
+ const halted = await env.harness.measure(() => env.harness.build(spec()));
+ assert.ok(halted.error, 'the build stops');
+ assert.deepEqual(creates(env.org, halted.mark), []);
+ assert.deepEqual(memberships(env.org, halted.mark), []);
+ assert.deepEqual(formDeletes(env.org, halted.mark), []);
+ assert.match(halted.error.message, new RegExp(`dashboard "${BOARD}": an earlier build stopped after creating it, and both ids it recorded for it name a row now — ${sent}, the id its create was sent with, and ${reported}, the id the service reported for the dashboard it made — so it cannot tell on its own which one is this app's\\. Nothing was added to the solution or deleted\\. Do not delete either dashboard to settle this: the other one may be another app's\\. Check in Maker which one this app's build made \\(the service reported ${reported}\\), add that one to solution '${SOLUTION}' and publish it there, then remove the entry '${BOARD}' from .*dashboard-creation\\.[0-9a-f]{64}\\.json and run the build again: it then reuses the dashboard the solution holds and leaves the other as it is\\.`));
+ assert.doesNotMatch(halted.error.message, /(?<!not )\bdelete\b/i, 'the way out asks for no dashboard to be deleted');
+ assert.equal(isTransientHalt(halted.error), false);
+ assert.deepEqual(recorded(env), left, 'the record is kept');
+ assert.deepEqual(boards(env.org).sort(), [sent, reported].sort(), 'both rows are left as they are');
+});
+
+// After a re-keyed create, the id the SERVICE reported is the row the create made; the id the build sent was never seen to make anything. When
+// the reported row is gone and only the sent id answers, that row's being there is no evidence it is this app's — another maker can have made it
+// since — and adding it to the solution would give teardown the authority to delete it.
+test('after a re-keyed create, only the id the service reported is the row the create made: when that row is gone and only the id the build sent answers, the next build adds nothing, deletes nothing, creates nothing, keeps the record and stops', async () => {
+ const env = environment();
+ const reported = '0f0f0f0f-0000-4000-8000-00000000000f';
+ const rekey = env.add('POST', isDashboardCreate, (req, body) => env.org.request({ ...req, body: JSON.stringify({ ...body, formid: reported }) }));
+ await dieAtMembership(env);
+ rekey.lift();
+ const left = recorded(env);
+ assert.ok(left && left[BOARD] && left[BOARD].reportedId === reported, JSON.stringify(left));
+ const sent = left[BOARD].id;
+ // Another maker's dashboard of the same name at the id the build sent, made in Maker since; and the dashboard the create made, deleted since.
+ await inMaker(env.org, 'POST', '/systemforms', { formid: sent, name: BOARD, type: 0, formxml: '<form><tabs /></form>' });
+ await inMaker(env.org, 'DELETE', `/systemforms(${reported})`);
+ const before = env.org.contents()[`row systemforms ${sent}`];
+ const halted = await env.harness.measure(() => env.harness.build(spec()));
+ assert.deepEqual(memberships(env.org, halted.mark), [], 'the row at the id the build sent is never added to the solution');
+ assert.deepEqual(creates(env.org, halted.mark), [], 'no dashboard is created');
+ assert.deepEqual(formDeletes(env.org, halted.mark), [], 'nothing is deleted');
+ assert.ok(halted.error, 'the build stops');
+ assert.match(halted.error.message, new RegExp(`dashboard "${BOARD}": an earlier build stopped after creating it\\. Its create was sent as ${sent}, but the service reported the dashboard it made as ${reported}, which is gone now, and ${sent} names a row this build never saw its create make\\. Nothing was added to the solution or deleted, and no dashboard was created\\. That row is not known to be this app's: do not delete or change it on this build's account\\. Find out whose it is, then remove the entry '${BOARD}' from .*dashboard-creation\\.[0-9a-f]{64}\\.json and run the build again: it then finds the dashboard by name, as it does when nothing is recorded\\.`));
+ assert.doesNotMatch(halted.error.message, /(?<!not )\bdelete\b/i, 'it asks for no dashboard to be deleted');
+ assert.equal(isTransientHalt(halted.error), false, 'conflicting evidence is a person\'s to settle: the build does not run again on its own');
+ assert.deepEqual(recorded(env), left, 'the record is kept');
+ assert.deepEqual(members(env.org), []);
+ assert.deepEqual(env.org.contents()[`row systemforms ${sent}`], before, 'the other row is as it was');
+ assert.deepEqual(halted.unexpected, []);
+});
+
+test('the record is never teardown authority: a teardown while it names a dashboard outside the solution deletes only what the solution holds, and leaves the record as it was', async () => {
+ const env = environment();
+ const id = await dieAtMembership(env);
+ const before = fs.readFileSync(recordFile(env));
+ const teardown = ran(await env.harness.measure(() => env.harness.teardown(spec())), 'the teardown');
+ assert.equal(teardown.value.result.ok, true, JSON.stringify(teardown.value.result.errors));
+ assert.deepEqual(formDeletes(env.org, teardown.mark), [], 'the dashboard outside the solution is not deleted on the record\'s word');
+ assert.deepEqual(boards(env.org), [id]);
+ assert.deepEqual(fs.readFileSync(recordFile(env)), before, 'and the record is untouched');
+});
+
+// --- 4. a record the build cannot read or write ------------------------------------------------------------------------------------------------------------
+
+// What an ordinary first build of the spec writes and reads (section 5 pins it): a build with a record it cannot use sends exactly this.
+const FIRST_BUILD_WRITES = {
+ 'POST publishers': 1, 'POST solutions': 1,
+ 'POST systemforms': 1, // the dashboard
+ 'POST AddSolutionComponent': 4, // the dashboard, the app icon, the app and its site map
+ 'POST webresourceset': 1, // the generated app icon
+ 'POST PublishXml': 3,
+ 'POST appmodules': 1, 'POST sitemaps': 1, 'POST AddAppComponents': 1, 'POST appmodules/appmoduleroles_association/$ref': 1, 'POST appsettings': 1,
+};
+const FIRST_BUILD_READS = 41;
+const UNCHANGED_REBUILD_WRITES = { 'PATCH sitemaps': 1, 'POST AddAppComponents': 1, 'POST PublishXml': 2 };
+const UNCHANGED_REBUILD_READS = 92;
+
+const BAD_RECORDS = [
+ ['damaged', (file) => fs.writeFileSync(file, '{ "schemaVersion": 1, "dashboards": '), /could not be read/],
+ ['a folder', (file) => fs.mkdirSync(file), /could not be read/],
+ ['too large', (file) => fs.writeFileSync(file, JSON.stringify({ padding: 'x'.repeat((1 << 20) + 1) })), /could not be read/],
+ ['linked from elsewhere (a hard link)', (file, env) => {
+ const elsewhere = path.join(makeTempDir('dash-record-link-'), 'record.json');
+ fs.writeFileSync(elsewhere, '{}');
+ fs.linkSync(elsewhere, file);
+ }, /could not be read/],
+ ['unwritable', (file, env, t) => {
+ const rename = fs.renameSync;
+ t.mock.method(fs, 'renameSync', function renameSync(from, to, ...rest) {
+ if (path.resolve(String(to)) === path.resolve(file)) throw Object.assign(new Error(`EACCES: permission denied, rename '${from}' -> '${to}'`), { code: 'EACCES' });
+ return rename.call(fs, from, to, ...rest);
+ });
+ }, /could not be written/],
+ // A record of the right shape, for this environment, app and solution, holding an entry the build never writes.
+ ['holding an entry whose reported id is no id, beside a good one', (file, env) => plantRecord(file, env, { [BOARD]: { id: ID_A, reportedId: 'damaged' }, Sibling: { id: ID_B } }), /could not be read/],
+ ['holding two entries Dataverse compares as one name', (file, env) => plantRecord(file, env, { [BOARD]: { id: ID_A }, 'OPS OVERVIEW ': { id: ID_B } }), /could not be read/],
+];
+
+for (const [what, plant, said] of BAD_RECORDS) {
+ test(`a record that is ${what}: an ordinary first build is the one it was before there was a record, says so once, and leaves the file as it found it`, async (t) => {
+ const env = environment();
+ const file = recordFile(env);
+ plant(file, env, t);
+ const kind = fs.existsSync(file) ? (fs.lstatSync(file).isDirectory() ? 'folder' : fs.readFileSync(file)) : null;
+ const built = ran(await env.harness.measure(() => env.harness.build(spec())), 'the build');
+ assert.equal(built.value.result.ok, true, JSON.stringify(built.value.result.errors));
+ assert.deepEqual(built.writes, FIRST_BUILD_WRITES, 'what a first build always writes');
+ assert.equal(built.reads, FIRST_BUILD_READS, 'and reads');
+ const [only] = boards(env.org);
+ assert.deepEqual(members(env.org), [only]);
+ if (kind === 'folder') assert.ok(fs.lstatSync(file).isDirectory(), 'the folder is left where it was');
+ else if (kind) {
+ assert.equal(fs.existsSync(file), true, 'the file is left where it was');
+ assert.deepEqual(fs.readFileSync(file), kind, 'the file is left exactly as it was');
+ } else assert.equal(fs.existsSync(file), false, 'no record is left half-written');
+ const about = built.value.warnings.filter((w) => /dashboard/i.test(w) && /record/i.test(w));
+ assert.equal(about.length, 1, `one warning about the record: ${JSON.stringify(built.value.warnings)}`);
+ assert.match(about[0], said);
+ assert.ok(about[0].includes(file), 'it names the file');
+ });
+}
+
+// The two shapes the writer never makes that look most like a record it does: a reported id equal to the id (observe() records only another
+// id), and an entry with a key of its own (the writer writes `id` and `reportedId` only). Each makes the whole record unreadable, as a damaged
+// file does: read directly, and under a first build over the real bundle, which is then the build it was with no record.
+const UNWRITTEN_SHAPES = [
+ ['a reported id equal to its id', (entry) => ({ ...entry, reportedId: entry.id })],
+ ['a key the build does not write', (entry) => ({ ...entry, keptByHand: true })],
+];
+
+for (const [what, reshape] of UNWRITTEN_SHAPES) {
+ test(`an entry with ${what} makes the whole record unreadable: said once, nothing read from it, note() and clear() leave its bytes intact, and a first build is the one it is with no record`, async () => {
+ // Read directly, beside a good sibling.
+ const dir = scratch();
+ const first = open(dir);
+ assert.equal(first.note(BOARD, ID_A), true);
+ assert.equal(first.note('Sibling', ID_B), true, 'a good sibling');
+ const file = records().dashboardCreationRecordPath(dir, ENV, APP, SOLUTION);
+ const record = JSON.parse(fs.readFileSync(file, 'utf8'));
+ record.dashboards[BOARD] = reshape(record.dashboards[BOARD]);
+ const bytes = Buffer.from(`${JSON.stringify(record)}\n`);
+ fs.writeFileSync(file, bytes);
+ const warnings = [];
+ const run = open(dir, { warn: (w) => warnings.push(w) });
+ assert.equal(run.idsOf(BOARD), undefined, 'nothing is read from it');
+ assert.equal(run.idsOf('Sibling'), undefined, 'not even the good sibling');
+ assert.equal(run.note('Another', ID_C), false, 'note() does not write over it');
+ assert.equal(run.observe('Sibling', ID_C), false, 'observe() does not either');
+ assert.equal(run.clear('Sibling'), false, 'clear() does not delete it');
+ assert.deepEqual(fs.readFileSync(file), bytes, 'its bytes are left intact');
+ assert.equal(warnings.length, 1, `said once: ${JSON.stringify(warnings)}`);
+ assert.match(warnings[0], /could not be read .*so this build finds dashboards by name, as before, and records none of its own/);
+
+ // Under a first build: what a first build with no record sends — no read of a recorded id — one warning, and the file as it was.
+ const env = environment();
+ const planted = recordFile(env);
+ plantRecord(planted, env, { [BOARD]: reshape({ id: ID_A }), Sibling: { id: ID_B } });
+ const plantedBytes = fs.readFileSync(planted);
+ const built = ran(await env.harness.measure(() => env.harness.build(spec())), 'the build');
+ assert.equal(built.value.result.ok, true, JSON.stringify(built.value.result.errors));
+ assert.deepEqual(built.writes, FIRST_BUILD_WRITES, 'what a first build always writes');
+ assert.equal(built.reads, FIRST_BUILD_READS, 'and reads: no recorded id is read');
+ assert.deepEqual(recordReads(env.org, built.mark, ID_A), [], 'the id the entry names is not read');
+ const [only] = boards(env.org);
+ assert.deepEqual(members(env.org), [only]);
+ assert.equal(fs.existsSync(planted), true, 'the file is left where it was');
+ assert.deepEqual(fs.readFileSync(planted), plantedBytes, 'the file is left exactly as it was');
+ const about = built.value.warnings.filter((w) => /dashboard/i.test(w) && /record/i.test(w));
+ assert.equal(about.length, 1, `one warning about the record: ${JSON.stringify(built.value.warnings)}`);
+ assert.match(about[0], /could not be read/);
+ });
+}
+
+// --- 5. what is unchanged --------------------------------------------------------------------------------------------------------------------------------------
+
+test('an ordinary first build and an unchanged rebuild send exactly what they sent before, read no recorded id, and leave no record behind', async () => {
+ const env = environment();
+ const first = ran(await env.harness.measure(() => env.harness.build(spec())), 'the first build');
+ assert.equal(first.value.result.ok, true, JSON.stringify(first.value.result.errors));
+ assert.deepEqual(first.writes, FIRST_BUILD_WRITES);
+ assert.equal(first.reads, FIRST_BUILD_READS);
+ const [id] = boards(env.org);
+ assert.deepEqual(members(env.org), [id]);
+ assert.deepEqual(recordFiles(env), [], 'a dashboard proven in its solution leaves no record');
+ const again = ran(await env.harness.measure(() => env.harness.build(spec())), 'the rebuild');
+ assert.equal(again.value.result.ok, true, JSON.stringify(again.value.result.errors));
+ assert.deepEqual(again.writes, UNCHANGED_REBUILD_WRITES);
+ assert.equal(again.reads, UNCHANGED_REBUILD_READS);
+ assert.deepEqual(recordReads(env.org, again.mark, id), [], 'no recorded id is read');
+ assert.deepEqual(recordFiles(env), []);
+});
+
+test('a dashboard the build cannot add to its solution and removes again: the halt is as it was, the record goes with the row, and the next run creates exactly one', async () => {
+ const env = environment();
+ let id;
+ const refuse = env.add('POST', isDashboardMembership, (req, body) => { id = String(body.ComponentId).toLowerCase(); return refusedWith(400, '0x80040216', 'An unexpected error occurred.')(); });
+ const failed = await env.harness.measure(() => env.harness.build(spec()));
+ refuse.lift();
+ assert.ok(failed.error, 'the build stops');
+ assert.match(failed.error.message, new RegExp(`dashboard "${BOARD}" could not be added to solution '${SOLUTION}' \\(.*An unexpected error occurred.*\\), so it was removed again — re-run to create it afresh`));
+ assert.deepEqual(formDeletes(env.org, failed.mark), [`/systemforms(${id})`], 'the undo deletes the row it created, and only that');
+ assert.deepEqual(allDashboards(env.org), []);
+ assert.deepEqual(recordFiles(env), [], 'proven removed by the undo: nothing to recover');
+ const rerun = ran(await env.harness.measure(() => env.harness.build(spec())), 'the next build');
+ assert.equal(creates(env.org, rerun.mark).length, 1);
+ assert.deepEqual(recordReads(env.org, rerun.mark, id), [], 'and nothing recorded is read');
+ const [only] = boards(env.org);
+ assert.deepEqual(members(env.org), [only]);
+});
diff --git a/plugins/model-apps/scripts/tests/download-dashboard-custom-control.test.js b/plugins/model-apps/scripts/tests/download-dashboard-custom-control.test.js
index f3a26fd4e..5f7a37c27 100644
--- a/plugins/model-apps/scripts/tests/download-dashboard-custom-control.test.js
+++ b/plugins/model-apps/scripts/tests/download-dashboard-custom-control.test.js
@@ -47,8 +47,8 @@ async function dashboardOver(formxml) {
}
const ordinaryTiles = [
- { type: 'list', name: 'Open cases', entity: 'incident', viewId: OPEN_VIEW },
- { type: 'chart', name: 'Cases by status', entity: 'incident', viewId: CHART_VIEW, visualizationId: CHART },
+ { type: 'list', name: 'Open cases', entity: 'incident', viewId: OPEN_VIEW, colspan: 2, rowspan: 8 },
+ { type: 'chart', name: 'Cases by status', entity: 'incident', viewId: CHART_VIEW, visualizationId: CHART, colspan: 2, rowspan: 8 },
];
test('a dashboard of native tiles downloads as it always did: a list, a chart, an iframe and a web resource, with nothing said', async () => {
@@ -61,8 +61,8 @@ test('a dashboard of native tiles downloads as it always did: a list, a chart, a
assert.deepStrictEqual(dashboards.map((d) => [d.id, d.name]), [[DASHBOARD_ID, 'Support board']]);
assert.deepStrictEqual(dashboards[0].tiles, [
...ordinaryTiles,
- { type: 'iframe', name: 'Knowledge', url: 'https://contoso.example/help' },
- { type: 'webresource', name: 'Welcome', webResource: 'new_welcome.htm' },
+ { type: 'iframe', name: 'Knowledge', url: 'https://contoso.example/help', colspan: 4, rowspan: 6 },
+ { type: 'webresource', name: 'Welcome', webResource: 'new_welcome.htm', colspan: 4, rowspan: 6 },
]);
assert.deepStrictEqual(warnings, []);
});
diff --git a/plugins/model-apps/scripts/tests/download-file-image-columns-real-bundle.test.js b/plugins/model-apps/scripts/tests/download-file-image-columns-real-bundle.test.js
index 841c6bcac..7c6b0bd05 100644
--- a/plugins/model-apps/scripts/tests/download-file-image-columns-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/download-file-image-columns-real-bundle.test.js
@@ -561,16 +561,20 @@ async function downloadWith(name, rules) {
}
}
-const TABLE_LABEL_READ = { select: 'LogicalName,Description,DisplayName,DisplayCollectionName' };
+const TABLE_LABEL_READ = { select: 'LogicalName,Description,DisplayName,DisplayCollectionName,IconVectorName' };
-test('a download the environment refuses only the table label read of says so of the table\'s labels alone, and still names what it cannot express', async () => {
+test('a refused table detail read names its label and portable-schema losses, and still names unexpressible columns', async () => {
const { spec: downloaded, stderr } = await downloadWith('download-no-table-labels', ({ refuse }) => [
refuse('GET', /^\/api\/data\/v9\.\d\/EntityDefinitions\(LogicalName='contoso_asset'\)$/, TABLE_LABEL_READ),
]);
assert.deepEqual(mediaOf(downloaded), HEALTHY_MEDIA);
// The table's label comes from the SDK's own read; its plural, which only the refused read carries, is not written.
assert.deepEqual({ displayName: downloaded.entities[0].displayName, plural: 'pluralName' in downloaded.entities[0] }, { displayName: 'Asset', plural: false });
- assert.deepEqual(warningsOf(stderr), [TABLE_LABEL_READ_FAILED, SENSOR_NAMED]);
+ assert.deepEqual(warningsOf(stderr), [
+ 'WARNING: some portable schema detail could not be captured (contoso_asset (alternate keys and table icon: HTTP 400)). The table and its typed columns are kept, but rebuilding into a FRESH environment uses the build defaults for missing column options and cannot recreate missing status reasons, alternate keys or table icons. Re-run the download to recover unreadable detail, and resolve the stated build limits before a cross-environment rebuild.',
+ TABLE_LABEL_READ_FAILED,
+ SENSOR_NAMED,
+ ]);
});
test('a download the environment refuses the column read of still keeps each File and Image column and none of their companions, and says what that read carries', async () => {
diff --git a/plugins/model-apps/scripts/tests/download-model-app.test.js b/plugins/model-apps/scripts/tests/download-model-app.test.js
index b1ef2a950..e1f9ac0ad 100644
--- a/plugins/model-apps/scripts/tests/download-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/download-model-app.test.js
@@ -250,7 +250,7 @@ test('readEntityWithDescriptions reads descriptions through the RAW dataverse cl
// 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) => u === "/EntityDefinitions(LogicalName='new_order')?$select=LogicalName,Description,DisplayName,DisplayCollectionName,IconVectorName&$expand=Keys($select=SchemaName,DisplayName,KeyAttributes,IsManaged)"), `table read URL wrong: ${gets.join(' | ')}`);
assert.ok(gets.some((u) => /^\/EntityDefinitions\(LogicalName='new_order'\)\/Attributes\?\$select=LogicalName,Description,DisplayName,IsLogical,AttributeOf,AttributeTypeName$/.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');
@@ -466,7 +466,7 @@ test('#564 a LOCAL option set downloads as a real Choice with inline options[],
// The cast segment is required: Attributes is a heterogeneous collection, so OptionSet can only be
// expanded through it. Pin the exact URL so a silent shape change is caught here, not live.
assert.ok(
- urls.some((u) => u === "/EntityDefinitions(LogicalName='new_ticket')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Name,IsGlobal,Options)"),
+ urls.some((u) => u === "/EntityDefinitions(LogicalName='new_ticket')/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Name,DisplayName,IsGlobal,Options)"),
'picklist read URL wrong: ' + urls.join(' | ')
);
});
@@ -1103,11 +1103,9 @@ const { resolvePageRefs, reverseResolveNavIds } = require('../lib/pageref-resolv
const { OBJECT_DIVISION_PAGE, LONG_KEY, lookBehindPage } = require('./helpers/misread-page.js');
test('runDownload translates a fail-closed app read into a graceful error, not a raw SDK throw', async () => {
- // `fetchArtifact('app')` fails closed (`APP_SITEMAP_UNRESOLVED`) rather than hand back an app whose
- // navigation is untrustworthy. The sitemap IS this function's membership oracle, so that is a
- // LOGICAL failure of the class its contract says it RETURNS rather than throws — otherwise the CLI
- // surfaces an opaque SDK error for the very ordinary case of an unpublished app.
- for (const code of ['APP_SITEMAP_UNRESOLVED', 'APP_UPDATE_NO_ETAG']) {
+ // An unresolved or shared sitemap is not a partial download: none of its navigation can be trusted
+ // as this app's membership. Preserve that refusal as a logical error before reading or writing pages.
+ for (const code of ['APP_SITEMAP_UNRESOLVED', 'APP_SITEMAP_SHARED', 'APP_UPDATE_NO_ETAG']) {
const err = new Error('app sitemap could not be resolved');
err.code = code;
const sdk = { fetchArtifact: async () => { throw err; } };
@@ -1120,7 +1118,7 @@ test('runDownload translates a fail-closed app read into a graceful error, not a
});
test('runDownload still propagates a genuinely unexpected error (no blanket swallow)', async () => {
- // Only the two fail-closed read codes are translated. An unexpected I/O error must keep propagating
+ // Only the fail-closed read codes are translated. An unexpected I/O error must keep propagating
// to main().catch, or a real defect would be reported as an ordinary "download failed".
const err = new Error('EACCES: permission denied');
err.code = 'EACCES';
diff --git a/plugins/model-apps/scripts/tests/download-parallel-reads.test.js b/plugins/model-apps/scripts/tests/download-parallel-reads.test.js
index eeebf7ce7..bc497d935 100644
--- a/plugins/model-apps/scripts/tests/download-parallel-reads.test.js
+++ b/plugins/model-apps/scripts/tests/download-parallel-reads.test.js
@@ -111,11 +111,11 @@ function normalizedUrl(url) {
function matchAuxRoute(url) {
const text = normalizedUrl(url);
- if (/\?\$select=LogicalName,Description,DisplayName,DisplayCollectionName$/.test(text)) return 'entity-labels';
+ if (/\?\$select=LogicalName,Description,DisplayName,DisplayCollectionName,IconVectorName&\$expand=Keys\(\$select=SchemaName,DisplayName,KeyAttributes,IsManaged\)$/.test(text)) return 'entity-labels';
if (/\/Attributes\?\$select=LogicalName,Description,DisplayName,IsLogical,AttributeOf,AttributeTypeName$/.test(text)) return 'attribute-labels';
- if (/MoneyAttributeMetadata\?\$select=LogicalName,IsBaseCurrency$/.test(text)) return 'money';
- if (/PicklistAttributeMetadata\?\$select=LogicalName&\$expand=OptionSet\(\$select=Name,IsGlobal,Options\)/.test(text)) return 'picklist';
- if (/MultiSelectPicklistAttributeMetadata\?\$select=LogicalName&\$expand=OptionSet\(\$select=Name,IsGlobal,Options\)/.test(text)) return 'multiselect';
+ if (/MoneyAttributeMetadata\?\$select=LogicalName,IsBaseCurrency,MinValue,MaxValue,Precision,PrecisionSource$/.test(text)) return 'money';
+ if (/PicklistAttributeMetadata\?\$select=LogicalName&\$expand=OptionSet\(\$select=Name,DisplayName,IsGlobal,Options\)/.test(text)) return 'picklist';
+ if (/MultiSelectPicklistAttributeMetadata\?\$select=LogicalName&\$expand=OptionSet\(\$select=Name,DisplayName,IsGlobal,Options\)/.test(text)) return 'multiselect';
return null;
}
diff --git a/plugins/model-apps/scripts/tests/download-portable-detail-real-bundle.test.js b/plugins/model-apps/scripts/tests/download-portable-detail-real-bundle.test.js
new file mode 100644
index 000000000..cbaf39716
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/download-portable-detail-real-bundle.test.js
@@ -0,0 +1,249 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');
+const { createLifecycleHarness, appUniqueName } = require('./helpers/lifecycle-harness.js');
+const { validateAppSpec } = require('../lib/app-spec.js');
+
+// Current-layer and sitemap-component proofs add four GETs and replace one name lookup.
+// Pin their request shape too, so an unrelated fallback cannot hide inside the total.
+// Component type 62 is Site Map:
+// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/appmodulecomponent
+const DOWNLOAD_READS = 83;
+
+const reason = { label: 'Review', state: 'Active', value: 100000042, color: '#336699' };
+const key = { schemaName: 'contoso_emailkey', displayName: 'Email Key', columns: ['contoso_email'] };
+const spec = {
+ schemaVersion: 2,
+ solution: { uniqueName: 'ContosoDetail', displayName: 'Portable Detail', publisherPrefix: 'contoso' },
+ app: { name: 'Portable Detail', tables: ['contoso_hidden'] },
+ entities: [
+ {
+ schemaName: 'contoso_item', displayName: 'Item',
+ primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name', maxLength: 100 },
+ columns: [
+ { schemaName: 'contoso_email', displayName: 'Email', type: 'Text', format: 'Email', maxLength: 160 },
+ { schemaName: 'contoso_cost', displayName: 'Cost', type: 'Money', minValue: 5, maxValue: 900, precision: 3 },
+ ],
+ statusReasons: [reason], alternateKeys: [key],
+ },
+ {
+ schemaName: 'contoso_hidden', displayName: 'Hidden',
+ primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name', maxLength: 100 },
+ columns: [{ schemaName: 'contoso_count', displayName: 'Count', type: 'Integer', minValue: 0, maxValue: 17, integerFormat: 'Duration' }],
+ },
+ ],
+ appShell: { areas: [{ label: 'Work', groups: [{ label: 'Items', subAreas: [{ entity: 'contoso_item', title: 'Items' }] }] }] },
+};
+
+function ran(stage, what) {
+ if (stage.error) throw stage.error;
+ assert.deepEqual(stage.unexpected, [], `every request ${what} sent is modelled by the strict transport`);
+ return stage;
+}
+
+async function environment() {
+ const org = createLifecycleOrg({ baseLanguage: 1033, provisionedLanguages: [1033, 1036] });
+ const root = makeTempDir('portable-detail-');
+ const edits = [];
+ // Fault only a successfully validated response. The strict fake still checks every requested
+ // property and expansion before an optional metadata property is removed or malformed.
+ const request = async (req) => {
+ const res = await org.request(req);
+ if (req.method !== 'GET' || res.statusCode < 200 || res.statusCode >= 300) return res;
+ const url = new URL(req.url);
+ const body = JSON.parse(res.body);
+ for (const edit of edits) edit(url, body);
+ return { ...res, body: JSON.stringify(body) };
+ };
+ const harness = createLifecycleHarness({ ...org, request }, root);
+ const built = ran(await harness.measure(() => harness.build(spec)), 'the source build');
+ assert.equal(built.value.result.ok, true, JSON.stringify(built.value.result));
+ return { org, root, harness, edits };
+}
+
+async function download(env, options = {}, name = 'download') {
+ const stage = ran(await env.harness.measure(() =>
+ env.harness.download(appUniqueName(spec), path.join(env.root, name), options)), 'the download');
+ assert.equal(stage.value.emitted.ok, true, JSON.stringify(stage.value.emitted));
+ assert.deepEqual(stage.writes, {}, 'download is read-only even when optional detail is unavailable');
+ const reads = env.org.requests.slice(stage.mark, stage.end).filter((r) => r.method === 'GET')
+ .map((r) => new URL(r.path, env.org.origin));
+ assert.equal(reads.filter((url) => url.pathname === '/appmodulecomponents'
+ && url.searchParams.get('$select') === 'objectid'
+ && (url.searchParams.get('$filter') || '').endsWith(' and componenttype eq 62')).length, 2, 'sitemap identity uses actual components');
+ assert.equal(reads.filter((url) => url.pathname === '/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()'
+ && url.searchParams.get('$select') === 'appmoduleid,appmoduleidunique,componentstate'
+ && (url.searchParams.get('$filter') || '').startsWith('appmoduleid eq ')).length, 3, 'app identity uses the current layer');
+ assert.equal(reads.filter((url) => url.pathname === '/sitemaps'
+ && (url.searchParams.get('$filter') || '').startsWith('sitemapnameunique eq ')).length, 0, 'a matching name is not sitemap identity');
+ assert.deepEqual(validateAppSpec(stage.value.spec, { profile: 'plan', reconstructed: true }).errors, []);
+ return stage;
+}
+
+function moneyDefinition(org) {
+ const column = org.metadata.tables.get('contoso_item').Attributes.get('contoso_cost');
+ return Object.fromEntries(['MinValue', 'MaxValue', 'Precision', 'PrecisionSource'].map((k) => [k, column[k]]));
+}
+
+for (const [name, source] of [
+ ['column precision', 0], ['organization pricing precision', 1], ['transaction currency precision', 2],
+ ['missing source', undefined], ['null source', null], ['string source', '2'],
+ ['unknown source', 3], ['object source', {}],
+]) {
+ test(`Money download classifies ${name} without losing the typed column`, async (t) => {
+ const env = await environment();
+ const raw = env.org.metadata.tables.get('contoso_item').Attributes.get('contoso_cost');
+ if (source !== undefined) raw.PrecisionSource = source;
+ else env.edits.push((url, body) => {
+ if (url.pathname.endsWith('/Microsoft.Dynamics.CRM.MoneyAttributeMetadata')) {
+ for (const row of body.value) delete row.PrecisionSource;
+ }
+ });
+ const got = await download(env);
+ assert.equal(got.reads, DOWNLOAD_READS, 'classifying Money adds a selected property, not another request');
+ const money = got.value.spec.entities.find((e) => e.schemaName === 'contoso_item').columns.find((c) => c.schemaName === 'contoso_cost');
+ assert.equal(money.type, 'Money');
+ assert.equal(money.minValue, 5);
+ assert.equal(money.maxValue, 900);
+ if (source === 2) {
+ assert.equal(money.precision, 3, 'numeric metadata is retained only for the source the SDK can create');
+ assert.doesNotMatch(got.value.stderr, /PrecisionSource.*(?:unsupported|unknown|missing|malformed)/i);
+ } else {
+ assert.equal(money.precision, undefined, 'a numeric Precision must not masquerade as unsupported source semantics');
+ assert.match(got.value.stderr, /Money contoso_cost:.*PrecisionSource/);
+ assert.match(got.value.stderr, /build.*(?:always|only).*PrecisionSource 2/i);
+ if (source === 0 || source === 1) assert.match(got.value.stderr, new RegExp(`PrecisionSource ${source}`));
+ else assert.match(got.value.stderr, /PrecisionSource.*(?:unknown|missing|malformed)/i);
+ }
+ // Inspect the actual source AND target source selector, not numeric Precision alone.
+ if ([0, 1, 2].includes(source)) {
+ const original = moneyDefinition(env.org);
+ const dir = path.join(env.root, 'download');
+ const rebuilt = ran(await env.harness.measure(() => env.harness.build(got.value.spec, {
+ appFolder: dir, workspace: path.join(dir, '.maker-workspace'),
+ })), 'the source rebuild');
+ assert.equal(rebuilt.value.result.ok, true, JSON.stringify(rebuilt.value.result));
+ assert.equal(rebuilt.writes['PUT EntityDefinitions/Attributes'] || 0, 0);
+ assert.deepEqual(moneyDefinition(env.org), original, 'a rebuild keeps an existing Money column and its precision source');
+ const fresh = createLifecycleOrg();
+ const target = createLifecycleHarness(fresh, path.join(env.root, 'fresh'));
+ const created = ran(await target.measure(() => target.build(got.value.spec)), 'the fresh build');
+ assert.equal(created.value.result.ok, true, JSON.stringify(created.value.result));
+ const recreated = moneyDefinition(fresh);
+ assert.equal(original.PrecisionSource, source);
+ assert.equal(recreated.PrecisionSource, 2, 'the real SDK always creates a currency-controlled Money column');
+ if (source === 2) assert.deepEqual(recreated, original);
+ else assert.notDeepEqual(recreated, original, 'an unsupported source is a diagnosed gap, never exact reconstruction');
+ }
+ t.diagnostic(`Money ${name}: ${got.reads} GETs, zero writes`);
+ });
+}
+
+function statusLabels(org, texts, userLanguage) {
+ const option = org.metadata.tables.get('contoso_item').Attributes.get('statuscode').OptionSet.Options.find((o) => o.Value === reason.value);
+ option.Label = org.metadata.label({ LocalizedLabels: Object.entries(texts).map(([lcid, Label]) => ({ LanguageCode: Number(lcid), Label })) });
+ // A user's UI language need not be the build/base language. Keep the raw Dataverse label shape,
+ // including its explicit caller projection, while the strict fake serves both translations.
+ option.Label.UserLocalizedLabel = structuredClone(option.Label.LocalizedLabels.find((l) => l.LanguageCode === userLanguage));
+}
+
+for (const [name, options, pinned, userLanguage, expected] of [
+ ['environment base language', {}, undefined, 1036, 'Review'],
+ ['explicit --language-code', { languageCode: 1036 }, undefined, 1033, 'Revue'],
+ ['authored language pin', {}, 1036, 1033, 'Revue'],
+]) {
+ test(`status download uses the ${name}, not the caller UI language`, async (t) => {
+ const env = await environment();
+ statusLabels(env.org, { 1033: 'Review', 1036: 'Revue' }, userLanguage);
+ const dir = path.join(env.root, 'download');
+ if (pinned) {
+ fs.mkdirSync(dir);
+ fs.writeFileSync(path.join(dir, 'app-spec.json'), JSON.stringify({ languageCode: pinned }));
+ }
+ const got = await download(env, options);
+ assert.equal(got.reads, pinned || options.languageCode ? DOWNLOAD_READS - 1 : DOWNLOAD_READS, 'an explicit or pinned LCID reuses the existing no-org-read path');
+ const entity = got.value.spec.entities.find((e) => e.schemaName === 'contoso_item');
+ assert.deepEqual(entity.statusReasons, [{ ...reason, label: expected }], 'the requested translation, non-default value and color survive');
+ const languageCode = options.languageCode || pinned || 1033;
+ const rebuilt = ran(await env.harness.measure(() => env.harness.build(got.value.spec, {
+ appFolder: dir, workspace: path.join(dir, '.maker-workspace'), languageCode,
+ })), 'the unchanged rebuild');
+ assert.equal(rebuilt.value.result.ok, true, JSON.stringify(rebuilt.value.result));
+ assert.equal(rebuilt.writes['POST InsertStatusValue'] || 0, 0, 'an unchanged valid round trip sends zero status inserts');
+ t.diagnostic(`${name}: ${got.reads} download GETs, ${rebuilt.reads} rebuild GETs, zero status inserts`);
+ });
+}
+
+for (const [name, options, texts, userLanguage, wanted] of [
+ ['default translation', {}, { 1036: 'Revue' }, 1036, 1033],
+ ['explicit translation', { languageCode: 1036 }, { 1033: 'Review' }, 1033, 1036],
+]) {
+ test(`status download diagnoses a missing ${name} instead of substituting another LCID`, async () => {
+ const env = await environment();
+ statusLabels(env.org, texts, userLanguage);
+ const got = await download(env, options);
+ assert.equal(got.reads, options.languageCode ? DOWNLOAD_READS - 1 : DOWNLOAD_READS, 'a missing translation does not trigger a fallback read');
+ assert.equal(got.value.spec.entities.find((e) => e.schemaName === 'contoso_item').statusReasons, undefined);
+ assert.match(got.value.stderr, new RegExp(`status reason ${reason.value}:.*label.*${wanted}`));
+ assert.doesNotMatch(got.value.stderr, /primary-name column.*could not/);
+ });
+}
+
+function assertIndependentTableMetadata(got) {
+ const entities = got.value.spec.entities;
+ assert.deepEqual(entities.map((e) => e.schemaName), ['contoso_item', 'contoso_hidden']);
+ for (const e of entities) {
+ assert.deepEqual(e.primaryAttribute, { schemaName: 'contoso_name', displayName: 'Name', maxLength: 100 });
+ assert.equal(e.existing, true, 'optional key failures do not change teardown ownership');
+ }
+ assert.deepEqual(entities[0].columns, [
+ spec.entities[0].columns[1], spec.entities[0].columns[0],
+ ]);
+ assert.deepEqual(entities[1].columns, spec.entities[1].columns);
+ assert.deepEqual(entities[0].statusReasons, [reason]);
+ assert.deepEqual(got.value.spec.app.tables, ['contoso_hidden']);
+ assert.deepEqual(got.value.spec.appShell.areas[0].groups[0].subAreas, [{ entity: 'contoso_item', title: 'Items' }]);
+ assert.doesNotMatch(got.value.stderr, /primary-name column|table\(s\) were DROPPED|app component table\(s\) were omitted/);
+}
+
+for (const [name, keys] of [['object', {}], ['number', 7], ['null', null], ['missing', undefined]]) {
+ test(`an unavailable ${name} Keys collection preserves sitemap and component-only table metadata`, async (t) => {
+ const env = await environment();
+ env.edits.push((url, body) => {
+ if (url.searchParams.get('$select') === 'LogicalName,Description,DisplayName,DisplayCollectionName,IconVectorName') {
+ if (keys === undefined) delete body.Keys;
+ else body.Keys = keys;
+ }
+ });
+ const got = await download(env);
+ assert.equal(got.reads, DOWNLOAD_READS, 'an unavailable Keys collection does not add fallback requests');
+ assertIndependentTableMetadata(got);
+ assert.ok(got.value.spec.entities.every((e) => e.alternateKeys === undefined));
+ for (const name of ['contoso_item', 'contoso_hidden']) {
+ assert.match(got.value.stderr, new RegExp(`${name}.*alternate keys: the response carried no Keys\\[\\] array`));
+ }
+ t.diagnostic(`${name} Keys: ${got.reads} GETs, both tables and navigation retained`);
+ });
+}
+
+for (const malformed of [false, true]) {
+ test(`${malformed ? 'a malformed row beside a valid' : 'a valid'} Keys array keeps its independent valid key`, async () => {
+ const env = await environment();
+ if (malformed) env.edits.push((url, body) => {
+ if (url.searchParams.get('$select') === 'LogicalName,Description,DisplayName,DisplayCollectionName,IconVectorName'
+ && decodeURIComponent(url.pathname).includes("LogicalName='contoso_item'")) {
+ body.Keys.push(null, { SchemaName: 'contoso_broken', KeyAttributes: [] });
+ }
+ });
+ const got = await download(env);
+ assertIndependentTableMetadata(got);
+ assert.deepEqual(got.value.spec.entities[0].alternateKeys, [key]);
+ if (malformed) assert.match(got.value.stderr, /alternate key contoso_broken:.*name or columns could not be read/);
+ else assert.doesNotMatch(got.value.stderr, /alternate key/);
+ });
+}
diff --git a/plugins/model-apps/scripts/tests/download-relationships.test.js b/plugins/model-apps/scripts/tests/download-relationships.test.js
index 61c7f9855..4666ef205 100644
--- a/plugins/model-apps/scripts/tests/download-relationships.test.js
+++ b/plugins/model-apps/scripts/tests/download-relationships.test.js
@@ -61,6 +61,60 @@ test('drops platform relationships rather than declaring them as app relationshi
assert.deepStrictEqual(skipped, []); // not app relationships at all, so nothing to report as lost
});
+// The platform's own relationship of a File and of an Image column, as a table's ManyToOneRelationships answers them (LIVE-MEASURED):
+// { "SchemaName": "FileAttachment_<table>_<file>", "ReferencedEntity": "fileattachment", "ReferencingAttribute": "<file>", "IsCustomRelationship": true }
+// { "SchemaName": "ImageDescriptor_<table>_<image>", "ReferencedEntity": "imagedescriptor", "ReferencingAttribute": "<image>id", "IsCustomRelationship": false }
+// and fileattachment is a stock table. The File one was carried as an `existing` relationship, warned about for a name without the
+// publisher prefix, though nothing but the column makes it: a build that creates the column gets it back.
+const mediaRows = (table, file, image) => [
+ rel({ SchemaName: `FileAttachment_${table}_${file}`, ReferencedEntity: 'fileattachment', ReferencingEntity: table, ReferencingAttribute: file }),
+ { IsCustomRelationship: false, SchemaName: `ImageDescriptor_${table}_${image}`, ReferencedEntity: 'imagedescriptor', ReferencingEntity: table, ReferencingAttribute: `${image}id` },
+];
+const mediaTable = (table, file, image) => ({ schemaName: table, columns: [{ schemaName: file, type: 'File' }, { schemaName: image, type: 'Image' }] });
+const recordingReads = (sdk) => {
+ const reads = [];
+ const get = sdk.dataverse.get;
+ sdk.dataverse.get = async (p) => { reads.push(p); return get(p); };
+ return reads;
+};
+
+test('the platform relationship of a File or an Image column is not carried, not warned about and not reported as lost', async () => {
+ const sdk = makeSdk({ m2o: { contoso_card: mediaRows('contoso_card', 'contoso_contract', 'contoso_photo') }, custom: { fileattachment: false, imagedescriptor: false } });
+ const reads = recordingReads(sdk);
+ const warnings = [];
+ const { relationships, skipped } = await readRelationships(sdk, ['contoso_card'], 'contoso', (m) => warnings.push(m), { entities: [mediaTable('contoso_card', 'contoso_contract', 'contoso_photo')] });
+ assert.deepStrictEqual(relationships, []);
+ assert.deepStrictEqual(skipped, [], 'nothing is lost: the column brings it back');
+ assert.deepStrictEqual(warnings, []);
+ // ...and nothing is read for it: no lookup labels for a table it was the only custom relationship of, no parent table.
+ assert.deepStrictEqual(reads.filter((p) => /LookupAttributeMetadata|fileattachment|imagedescriptor/.test(p)), []);
+});
+
+test('beside the platform relationship of a File column, the table\'s own relationships are carried exactly as before', async () => {
+ const sdk = makeSdk({
+ m2o: { contoso_card: [
+ ...mediaRows('contoso_card', 'contoso_contract', 'contoso_photo'),
+ rel({ SchemaName: 'contoso_deck_contoso_card', ReferencedEntity: 'contoso_deck', ReferencingEntity: 'contoso_card', ReferencingAttribute: 'contoso_deckid' }),
+ ] },
+ lookups: { contoso_card: [{ LogicalName: 'contoso_deckid', SchemaName: 'contoso_DeckId', DisplayName: label('Deck'), Targets: ['contoso_deck'] }] },
+ custom: { fileattachment: false, imagedescriptor: false },
+ });
+ const warnings = [];
+ const { relationships, skipped } = await readRelationships(sdk, ['contoso_deck', 'contoso_card'], 'contoso', (m) => warnings.push(m), { entities: [mediaTable('contoso_card', 'contoso_contract', 'contoso_photo')] });
+ assert.deepStrictEqual(skipped, []);
+ assert.deepStrictEqual(warnings, []);
+ assert.deepStrictEqual(relationships, [{ type: 'OneToMany', referenced: 'contoso_deck', referencing: 'contoso_card', lookup: { schemaName: 'contoso_DeckId', displayName: 'Deck' }, existing: true }]);
+});
+
+test('a relationship to fileattachment that is no File column\'s of the table is not taken for the platform\'s, and reads as before', async () => {
+ // The rule is the column's, not the parent's: here the download typed no File column named by the relationship (a read that failed, say).
+ const sdk = makeSdk({ m2o: { contoso_card: mediaRows('contoso_card', 'contoso_contract', 'contoso_photo') }, custom: { fileattachment: false, imagedescriptor: false } });
+ const warnings = [];
+ const { relationships } = await readRelationships(sdk, ['contoso_card'], 'contoso', (m) => warnings.push(m), { entities: [{ schemaName: 'contoso_card', columns: [] }] });
+ assert.deepStrictEqual(relationships.map((r) => r.schemaName), ['FileAttachment_contoso_card_contoso_contract']);
+ assert.ok(warnings.some((w) => /FileAttachment_contoso_card_contoso_contract/.test(w) && /publisher prefix/.test(w)), JSON.stringify(warnings));
+});
+
test('skips AND reports a polymorphic lookup, which relationships[] cannot express (#567)', async () => {
// LIVE-MEASURED: `cfo_billto` targeting account+contact produced TWO relationships sharing ONE
// ReferencingAttribute. Emitting both would declare the same lookup schema name twice.
@@ -329,3 +383,12 @@ test('a single foreign 1:N keeps its deployed name and a same-environment rebuil
assert.strictEqual(created, 0);
assert.ok(events.some((e) => e.status === 'skip' && /legacy_ProjectTask/.test(e.label) && /\(exists\)/.test(e.label)), JSON.stringify(events));
});
+
+// The capabilities doc says what a download does with relationships[], as the tests above show it: they are reconstructed, flagged
+// `existing: true`, and what relationships[] cannot express is named. It said they were not reconstructed at all.
+test('the capabilities doc says a download reconstructs relationships[] and names the ones it leaves out (#567)', () => {
+ const doc = require('node:fs').readFileSync(require('node:path').join(__dirname, '..', '..', 'docs', 'app-builder-capabilities.md'), 'utf8');
+ assert.doesNotMatch(doc, /`relationships\[\]` are NOT reconstructed/);
+ assert.match(doc, /\*\*`relationships\[\]` are reconstructed\*\*/);
+ assert.match(doc, /Round-trip scope \(not yet "complete"\):\*\* tables, relationships, sitemap\/appShell/);
+});
diff --git a/plugins/model-apps/scripts/tests/download-schema-metadata.test.js b/plugins/model-apps/scripts/tests/download-schema-metadata.test.js
new file mode 100644
index 000000000..cbc729d73
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/download-schema-metadata.test.js
@@ -0,0 +1,282 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { readColumnOptions, columnOptionFields, primaryColumnOptionFields } = require('../lib/download-column-options.js');
+const { readStatusOptions, statusReasonsFromOptions, alternateKeysFromMetadata, alternateKeyMatches } = require('../lib/table-schema-metadata.js');
+const { iconWebResources, labelFromDataverse, entityFromMetadata } = require('../download-model-app.js');
+const { makeRunner, provisionDataModel } = require('../lib/entity-provision.js');
+
+const label = (text, lcid = 1033) => ({ LocalizedLabels: [{ Label: text, LanguageCode: lcid }] });
+const attr = (name, type, extra = {}) => ({ logicalName: name, attributeType: type, isCustomAttribute: true, ...extra });
+
+test('a primary AutoNumber keeps both its independently authored length and its number mask', () => {
+ assert.deepEqual(primaryColumnOptionFields({
+ MaxLength: 120, FormatName: { Value: 'Text' }, AutoNumberFormat: 'I-{SEQNUM:6}',
+ }), { maxLength: 120, autoNumberFormat: 'I-{SEQNUM:6}' });
+});
+
+test('typed detail reads scale by declared type, not by columns, and ignore synthetic and system attributes', async () => {
+ const calls = [];
+ const attrs = [
+ attr('contoso_a', 'String'), attr('contoso_b', 'String'),
+ attr('contoso_shadow', 'Integer', { AttributeOf: 'contoso_parent' }),
+ attr('createdon', 'DateTime', { isCustomAttribute: false }),
+ attr('contoso_logical', 'Memo', { IsLogical: true }),
+ ];
+ const got = await readColumnOptions({ dataverse: { get: async (url) => {
+ calls.push(url);
+ return { status: 200, body: { value: ['contoso_a', 'contoso_b'].map((LogicalName) => ({
+ LogicalName, MaxLength: 100, FormatName: { Value: 'Text' }, AutoNumberFormat: null,
+ })) } };
+ } } }, "contoso_o'brien", attrs, 3);
+ assert.equal(calls.length, 1);
+ assert.match(calls[0], /LogicalName='contoso_o''brien'/);
+ assert.match(calls[0], /StringAttributeMetadata/);
+ assert.equal(got.rows.size, 2);
+ assert.deepEqual(got.failures, []);
+});
+
+test('an absent row and a malformed selected property are named, never represented as known defaults', async () => {
+ const sdk = { dataverse: { get: async () => ({ status: 200, body: { value: [
+ { LogicalName: 'contoso_a', MaxLength: '160', FormatName: { Value: 'Email' }, AutoNumberFormat: null },
+ ] } }) } };
+ const got = await readColumnOptions(sdk, 'contoso_item', [attr('contoso_a', 'String'), attr('contoso_b', 'String')], 2);
+ assert.ok(got.failures.some((f) => /contoso_a.*maxLength/i.test(f)), JSON.stringify(got.failures));
+ assert.ok(got.failures.some((f) => /contoso_b.*missing/i.test(f)));
+ assert.deepEqual(columnOptionFields(got.rows.get('contoso_a'), 'Text'), { format: 'Email' });
+});
+
+test('a missing selected property and an unsupported Whole Number format are reported without making the spec invalid', async () => {
+ const sdk = { dataverse: { get: async () => ({ status: 200, body: { value: [
+ { LogicalName: 'contoso_count', MinValue: 0, Format: 'NotAnSdkFormat' },
+ ] } }) } };
+ const got = await readColumnOptions(sdk, 'contoso_item', [attr('contoso_count', 'Integer')], 2);
+ assert.ok(got.failures.some((f) => /maxValue/.test(f)), JSON.stringify(got.failures));
+ assert.ok(got.failures.some((f) => /integerFormat/.test(f)), JSON.stringify(got.failures));
+ assert.deepEqual(columnOptionFields(got.rows.get('contoso_count'), 'Integer'), { minValue: 0 });
+});
+
+test('fractional precision and a non-array Boolean projection cannot invent options or abort a download', () => {
+ assert.deepEqual(columnOptionFields({ MinValue: 0, MaxValue: 500, Precision: 0.25 }, 'Decimal'), { minValue: 0, maxValue: 500 });
+ assert.deepEqual(columnOptionFields({ choices: {} }, 'Boolean'), {});
+});
+
+test('currency-controlled Money keeps numeric precision metadata, including zero, and canonical defaults', () => {
+ for (const precision of [0, 2, 3]) {
+ const omitted = [];
+ assert.deepEqual(columnOptionFields({ MinValue: 0, MaxValue: 1e9, Precision: precision, PrecisionSource: 2 }, 'Money', omitted),
+ precision === 2 ? {} : { precision });
+ assert.deepEqual(omitted, []);
+ }
+});
+
+test('missing Money detail and incomplete Boolean labels are reported even though neither needs a new cast', async () => {
+ const got = await readColumnOptions({ dataverse: { get: async () => { throw new Error('must not query'); } } }, 'contoso_item', [
+ attr('contoso_cost', 'Money'),
+ attr('contoso_cost_base', 'Money', { IsBaseCurrency: true }),
+ attr('contoso_flag', 'Boolean', { choices: [{ value: 1, label: 'Chargeable' }] }),
+ ], 2);
+ assert.ok(got.failures.some((f) => /Money contoso_cost/.test(f)), JSON.stringify(got.failures));
+ assert.ok(got.failures.some((f) => /Boolean contoso_flag.*falseLabel/.test(f)), JSON.stringify(got.failures));
+ assert.ok(got.failures.every((f) => !f.includes('contoso_cost_base')));
+});
+
+for (const [name, answer] of [
+ ['HTTP failure', async () => ({ status: 403, body: {} })],
+ ['transport failure', async () => { throw new Error('connection closed'); }],
+ ['malformed collection', async () => ({ status: 200, body: { value: {} } })],
+]) {
+ test(`a column ${name} is unknown, not an empty successful snapshot`, async () => {
+ const got = await readColumnOptions({ dataverse: { get: answer } }, 'contoso_item', [attr('contoso_text', 'String')], 2);
+ assert.equal(got.rows.size, 0);
+ assert.equal(got.failures.length, 1);
+ assert.match(got.failures[0], /^Text:/);
+ });
+}
+
+for (const [name, body] of [
+ ['missing statuscode', { value: [] }],
+ ['missing options', { value: [{ LogicalName: 'statuscode', OptionSet: {} }] }],
+ ['malformed options', { value: [{ LogicalName: 'statuscode', OptionSet: { Options: {} } }] }],
+]) {
+ test(`status reasons with ${name} are unknown, not proof of absence`, async () => {
+ const got = await readStatusOptions({ get: async () => ({ status: 200, body }) }, 'contoso_item');
+ assert.equal(got.options, undefined);
+ assert.match(got.failed, /no statuscode options/);
+ });
+}
+
+test('status hydration excludes stock and managed reasons, keeps explicit values and reports unexpressible states', () => {
+ const omitted = [];
+ const got = statusReasonsFromOptions([
+ { Value: 1, State: 0, Label: label('Active') },
+ { Value: 2, State: 1, Label: label('Inactive') },
+ { Value: 100000000, State: 0, Label: label('Review') },
+ { Value: 100000042, State: 1, Label: label('Archived'), Color: '#336699' },
+ { Value: 100000010, State: 0, Label: label('From a managed solution'), IsManaged: true },
+ { Value: 100000011, State: 3, Label: label('Cannot express this state') },
+ ], { omitted, languageCode: 1033 });
+ assert.deepEqual(got, [
+ { label: 'Review', state: 'Active' },
+ { label: 'Archived', state: 'Inactive', value: 100000042, color: '#336699' },
+ ]);
+ assert.equal(omitted.length, 1);
+ assert.match(omitted[0], /100000011.*state/);
+ assert.deepEqual(statusReasonsFromOptions([{ Value: 5, State: 0, Label: label('A stock reason') }], { customTable: false }), []);
+});
+
+test('status hydration with an unresolved language or user-only label cannot claim authoring-language fidelity', () => {
+ for (const [languageCode, Label, expected] of [
+ [undefined, label('Review'), /\(unresolved\)/],
+ [1033, { UserLocalizedLabel: { Label: 'Review', LanguageCode: 1033 } }, /1033/],
+ ]) {
+ const omitted = [];
+ assert.deepEqual(statusReasonsFromOptions([{ Value: 100000042, State: 0, Label }], { languageCode, omitted }), []);
+ assert.equal(omitted.length, 1);
+ assert.match(omitted[0], expected);
+ }
+});
+
+test('non-array alternate-key collections recover no keys without throwing or reading a label', () => {
+ for (const keys of [{}, 7, null, undefined, 'not an array']) {
+ assert.deepEqual(alternateKeysFromMetadata(keys, () => assert.fail('no key label is read')), []);
+ }
+});
+
+test('alternate keys keep all read languages, exclude managed keys and name malformed ones', () => {
+ const omitted = [];
+ const got = alternateKeysFromMetadata([
+ { SchemaName: 'contoso_email', KeyAttributes: ['contoso_email'], DisplayName: { LocalizedLabels: [
+ { Label: 'Email', LanguageCode: 1033 }, { Label: 'Courriel', LanguageCode: 1036 },
+ ] } },
+ { SchemaName: 'contoso_managed', KeyAttributes: ['contoso_name'], IsManaged: true },
+ { SchemaName: 'contoso_broken', KeyAttributes: [] },
+ ], labelFromDataverse, omitted);
+ assert.deepEqual(got, [{ schemaName: 'contoso_email', displayName: { 1033: 'Email', 1036: 'Courriel' }, columns: ['contoso_email'] }]);
+ assert.equal(omitted.length, 1);
+ assert.match(omitted[0], /contoso_broken/);
+});
+
+test('an alternate key with only a UserLocalizedLabel keeps its deployed display name', () => {
+ const entity = entityFromMetadata({
+ schemaName: 'contoso_item', attributes: [],
+ Keys: [{
+ SchemaName: 'contoso_email', KeyAttributes: ['contoso_email'],
+ DisplayName: { UserLocalizedLabel: { Label: 'Email', LanguageCode: 1033 } },
+ }],
+ }, 'contoso_item');
+ assert.deepEqual(entity.alternateKeys, [{
+ schemaName: 'contoso_email', columns: ['contoso_email'], displayName: 'Email',
+ }]);
+});
+
+test('only a conclusive alternate-key identity skips its write, ignoring case and column order', () => {
+ const key = { schemaName: 'contoso_nameemail', columns: ['contoso_name', 'contoso_email'] };
+ assert.equal(alternateKeyMatches([{ SchemaName: 'Contoso_NameEmail', KeyAttributes: ['CONTOSO_EMAIL', 'contoso_name'] }], key), true);
+ for (const keys of [undefined, [], [{ SchemaName: key.schemaName }], [{ SchemaName: 'contoso_other', KeyAttributes: key.columns }],
+ [{ SchemaName: key.schemaName, KeyAttributes: ['contoso_name'] }]]) {
+ assert.equal(alternateKeyMatches(keys, key), false);
+ }
+});
+
+for (const [name, row, queried] of [
+ ['another publisher', { name: 'fabrikam_icon.svg', webresourcetype: 11, content: 'c3Zn', ismanaged: false }, false],
+ ['a managed SVG', { name: 'contoso_icon.svg', webresourcetype: 11, content: 'c3Zn', ismanaged: true }, true],
+ ['unknown management', { name: 'contoso_icon.svg', webresourcetype: 11, content: 'c3Zn' }, true],
+ ['a non-SVG resource', { name: 'contoso_icon.svg', webresourcetype: 5, content: 'cG5n', ismanaged: false }, true],
+ ['missing content', { name: 'contoso_icon.svg', webresourcetype: 11, ismanaged: false }, true],
+]) {
+ test(`a table vector icon does not capture ${name}`, async () => {
+ const calls = [];
+ const sdk = { queryRecords: async (...args) => { calls.push(args); return [row]; } };
+ const got = await iconWebResources(sdk, [], [], 'contoso', true, [], [row.name]);
+ assert.deepEqual(got.webResources, []);
+ assert.equal(calls.length, queried ? 1 : 0);
+ });
+}
+
+test('a table icon shared by navigation is captured once, with teardown protection and no type broadening', async () => {
+ const calls = [];
+ const sdk = { queryRecords: async (...args) => {
+ calls.push(args);
+ return [{ name: 'contoso_icon.svg', displayname: 'Item Icon', webresourcetype: 11, content: 'c3Zn', ismanaged: false }];
+ } };
+ const got = await iconWebResources(sdk, [], ['contoso_icon.svg'], 'contoso', true, [], ['contoso_icon.svg']);
+ assert.deepEqual(got.webResources, [{ name: 'contoso_icon.svg', displayName: 'Item Icon', type: 'svg', contentBase64: 'c3Zn', external: true }]);
+ assert.equal(calls.length, 1);
+});
+
+test('a table icon also named as a bare nav icon cannot bypass the unmanaged SVG gates', async () => {
+ const sdk = { queryRecords: async () => [
+ { name: 'contoso_icon.svg', webresourcetype: 11, content: 'c3Zn', ismanaged: true },
+ ] };
+ const got = await iconWebResources(sdk, ['contoso_icon.svg'], [], 'contoso', true, [], ['contoso_icon.svg']);
+ assert.deepEqual(got.webResources, []);
+});
+
+async function provisionWithProof({ statusAnswer, keys, laterTable = false }) {
+ const calls = [];
+ const warnings = [];
+ const sdk = {
+ insertStatusValue: async (name, options) => { calls.push(['insert-status', name, options]); return options.value; },
+ createAlternateKey: async (...args) => { calls.push(['create-key', ...args]); return {}; },
+ createTable: async (options) => { calls.push(['create-table', options.schemaName]); return { logicalName: options.schemaName, entitySetName: `${options.schemaName}s` }; },
+ createColumn: async (name, options) => { calls.push(['create-column', name, options.schemaName]); return { logicalName: options.schemaName }; },
+ };
+ const provision = { dataverse: { get: async (url) => {
+ if (url.includes('StatusAttributeMetadata')) { calls.push(['read-status']); return statusAnswer; }
+ if (url.includes('/Attributes?')) return { status: 200, body: { value: [{ LogicalName: 'contoso_name' }] } };
+ if (url.includes("LogicalName='contoso_later'")) return { status: 404 };
+ return { status: 200, body: { LogicalName: 'contoso_item', EntitySetName: 'contoso_items', Keys: keys } };
+ } } };
+ const entities = [{
+ schemaName: 'contoso_item', primaryAttribute: { schemaName: 'contoso_name' }, columns: [],
+ statusReasons: [{ label: 'Review', state: 'Active' }],
+ alternateKeys: [{ schemaName: 'contoso_namekey', columns: ['contoso_name'] }],
+ }];
+ if (laterTable) entities.push({
+ schemaName: 'contoso_later', displayName: { 1033: 'Later', 1036: 'Suivant' },
+ primaryAttribute: { schemaName: 'contoso_name' }, columns: [{ schemaName: 'contoso_text', type: 'Text' }],
+ });
+ const result = await provisionDataModel({
+ sdk, provision, spec: { solution: { uniqueName: 'ContosoSchema', publisherPrefix: 'contoso' }, entities },
+ runner: makeRunner({ emit: () => {}, total: 20 }), apply: true, preResolvedLanguageCode: 1033,
+ inlineColumns: false, warn: (m) => warnings.push(m),
+ });
+ return { calls, warnings, result };
+}
+
+test('unknown status and key proof keeps the existing duplicate-protected insert path', async () => {
+ const { calls, warnings, result } = await provisionWithProof({ statusAnswer: { status: 403, body: {} } });
+ assert.equal(calls.filter(([name]) => name === 'insert-status').length, 1);
+ assert.equal(calls.filter(([name]) => name === 'create-key').length, 1);
+ assert.ok(warnings.some((w) => /could not read status reasons.*HTTP 403/.test(w)));
+ assert.deepEqual(result.statusReasonValues.contoso_item.Review, { value: 100000000, stateCode: 0 });
+});
+
+test('a matching status label in the wrong language is not a no-op proof', async () => {
+ const { calls } = await provisionWithProof({
+ statusAnswer: { status: 200, body: { value: [{ LogicalName: 'statuscode', OptionSet: { Options: [
+ { Value: 100000000, State: 0, Label: label('Review', 1036) },
+ ] } }] } },
+ keys: [{ SchemaName: 'contoso_namekey', KeyAttributes: ['contoso_name'] }],
+ });
+ assert.equal(calls.filter(([name]) => name === 'insert-status').length, 1);
+ assert.equal(calls.filter(([name]) => name === 'create-key').length, 0);
+});
+
+test('label-bearing status proofs run after every table and column create, preserving later localized labels', async () => {
+ const { calls } = await provisionWithProof({
+ statusAnswer: { status: 200, body: { value: [{ LogicalName: 'statuscode', OptionSet: { Options: [
+ { Value: 100000000, State: 0, Label: label('Review') },
+ ] } }] } },
+ keys: [{ SchemaName: 'contoso_namekey', KeyAttributes: ['contoso_name'] }], laterTable: true,
+ });
+ const read = calls.findIndex(([name]) => name === 'read-status');
+ for (const name of ['create-table', 'create-column']) {
+ const create = calls.findIndex(([kind]) => kind === name);
+ assert.ok(create >= 0 && read > create, `${name} must precede a status-label read: ${JSON.stringify(calls)}`);
+ }
+ assert.equal(calls.filter(([name]) => name === 'insert-status').length, 0);
+});
diff --git a/plugins/model-apps/scripts/tests/download-schema-options-real-bundle.test.js b/plugins/model-apps/scripts/tests/download-schema-options-real-bundle.test.js
new file mode 100644
index 000000000..35731ce3d
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/download-schema-options-real-bundle.test.js
@@ -0,0 +1,327 @@
+'use strict';
+// The download's portable schema, over the real bundle and the strict lifecycle fake: values a second
+// environment cannot infer must survive, while proven schema reuse avoids redundant writes.
+// Table icons retain their assignment/publish pair because saved names do not prove publication.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');
+const { createLifecycleHarness, appUniqueName } = require('./helpers/lifecycle-harness.js');
+const { readDashboards, entityFromMetadata } = require('../download-model-app.js');
+const { validateAppSpec } = require('../lib/app-spec.js');
+
+const ICON = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M2 2h12v12H2z"/></svg>';
+const spec = {
+ schemaVersion: 2,
+ solution: { uniqueName: 'ContosoSchema', displayName: 'Portable Schema', publisherPrefix: 'contoso' },
+ app: { name: 'Schema Options', description: 'A portable schema.' },
+ globalChoices: [{ name: 'contoso_workstage', displayName: 'Work Stage', options: ['Planned', 'Done'] }],
+ entities: [{
+ schemaName: 'contoso_item', displayName: 'Item',
+ primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name', maxLength: 120 },
+ vectorIcon: 'contoso_item.svg',
+ statusReasons: [
+ { label: 'In Review', state: 'Active' },
+ { label: 'Archived', state: 'Inactive', value: 100000042, color: '#336699' },
+ ],
+ alternateKeys: [{ schemaName: 'contoso_itememail', displayName: 'Item Email', columns: ['contoso_email'] }],
+ columns: [
+ { schemaName: 'contoso_email', displayName: 'Email', type: 'Text', format: 'Email', maxLength: 160 },
+ { schemaName: 'contoso_notes', displayName: 'Notes', type: 'Memo', maxLength: 9000 },
+ { schemaName: 'contoso_minutes', displayName: 'Minutes', type: 'Integer', minValue: 0, maxValue: 17, integerFormat: 'Duration' },
+ { schemaName: 'contoso_rate', displayName: 'Rate', type: 'Decimal', precision: 4, minValue: 0, maxValue: 500 },
+ { schemaName: 'contoso_score', displayName: 'Score', type: 'Double', precision: 3, minValue: -2.5, maxValue: 10.5 },
+ { schemaName: 'contoso_cost', displayName: 'Cost', type: 'Money', precision: 3, minValue: 5, maxValue: 900 },
+ { schemaName: 'contoso_billable', displayName: 'Billable', type: 'Boolean', trueLabel: 'Chargeable', falseLabel: 'No charge' },
+ { schemaName: 'contoso_due', displayName: 'Due', type: 'DateTime', dateFormat: 'DateOnly' },
+ { schemaName: 'contoso_reference', displayName: 'Reference', type: 'AutoNumber', autoNumberFormat: 'I-{SEQNUM:6}' },
+ { schemaName: 'contoso_stage', displayName: 'Stage', type: 'Choice', globalChoice: 'contoso_workstage' },
+ ],
+ }],
+ webResources: [{ name: 'contoso_item.svg', displayName: 'Item Icon', type: 'svg', content: ICON }],
+ dashboards: [{
+ name: 'Item Overview', tiles: [
+ { type: 'iframe', name: 'Status', url: 'https://contoso.example/status', colspan: 2, rowspan: 8 },
+ { type: 'iframe', name: 'Thin', url: 'https://contoso.example/thin', rowspan: 1 },
+ { type: 'iframe', name: 'Default', url: 'https://contoso.example/default' },
+ ],
+ }],
+ appShell: { areas: [{ label: 'Work', groups: [{ label: 'Items', subAreas: [
+ { entity: 'contoso_item', title: 'Items' }, { dashboard: 'Item Overview', title: 'Overview' },
+ ] }] }] },
+};
+
+const ran = (stage, name) => {
+ if (stage.error) throw stage.error;
+ assert.deepEqual(stage.unexpected, [], `every request ${name} sent is modelled`);
+ return stage;
+};
+let walkPromise;
+const walk = () => walkPromise || (walkPromise = (async () => {
+ const root = makeTempDir('download-schema-options-');
+ const org = createLifecycleOrg();
+ const harness = createLifecycleHarness(org, root);
+ const build = ran(await harness.measure(() => harness.build(spec)), 'the build');
+ assert.equal(build.value.result.ok, true, JSON.stringify(build.value.result));
+ const downloaded = ran(await harness.measure(() => harness.download(appUniqueName(spec), path.join(root, 'download'))), 'the download');
+ assert.equal(downloaded.value.emitted.ok, true, JSON.stringify(downloaded.value.emitted));
+ assert.deepEqual(downloaded.writes, {}, 'download is read-only');
+ return { root, org, harness, downloaded, built: schemaOf(org) };
+})());
+
+function schemaOf(org) {
+ const table = org.metadata.tables.get('contoso_item');
+ const fields = ['AttributeTypeName', 'FormatName', 'Format', 'MaxLength', 'MinValue', 'MaxValue', 'Precision', 'PrecisionSource', 'AutoNumberFormat'];
+ return {
+ columns: Object.fromEntries([...table.Attributes]
+ .filter(([name, a]) => a.AttributeOf === null && a.IsBaseCurrency !== true && spec.entities[0].columns.some((c) => c.schemaName === name))
+ .map(([name, a]) => [name, Object.fromEntries(fields.filter((k) => a[k] !== undefined).map((k) => [k, a[k]]))])),
+ primaryLength: table.Attributes.get('contoso_name').MaxLength,
+ booleanLabels: ['TrueOption', 'FalseOption'].map((k) => org.metadata.textOf(table.Attributes.get('contoso_billable').OptionSet[k].Label)),
+ statusReasons: table.Attributes.get('statuscode').OptionSet.Options.map((o) => ({
+ value: o.Value, label: org.metadata.textOf(o.Label), state: o.State, color: o.Color,
+ })),
+ keys: [...table.Keys.values()].map((k) => ({ schemaName: k.SchemaName, displayName: org.metadata.textOf(k.DisplayName), columns: k.KeyAttributes })),
+ vectorIcon: table.IconVectorName,
+ solution: org.find('solutions', (s) => s.uniquename === spec.solution.uniqueName).map((s) => s.friendlyname),
+ globalChoice: org.metadata.textOf(org.metadata.optionSets.get('contoso_workstage').DisplayName),
+ };
+}
+
+test('download keeps the authored column formats, lengths, ranges, precision, labels and date format', async () => {
+ const { downloaded } = await walk();
+ const entity = downloaded.value.spec.entities[0];
+ const byName = (a, b) => a.schemaName < b.schemaName ? -1 : a.schemaName > b.schemaName ? 1 : 0;
+ assert.deepEqual(entity.columns, [...spec.entities[0].columns].sort(byName));
+ assert.deepEqual(entity.primaryAttribute, spec.entities[0].primaryAttribute);
+});
+
+test('download keeps custom status reasons with their states, values and colors, without adding stock reasons', async () => {
+ const { downloaded } = await walk();
+ assert.deepEqual(downloaded.value.spec.entities[0].statusReasons, spec.entities[0].statusReasons);
+});
+
+test('download keeps an alternate key name, display name and column list', async () => {
+ const { downloaded } = await walk();
+ assert.deepEqual(downloaded.value.spec.entities[0].alternateKeys, spec.entities[0].alternateKeys);
+});
+
+test('download keeps the solution and referenced global choice display names', async () => {
+ const { downloaded } = await walk();
+ assert.equal(downloaded.value.spec.solution.displayName, spec.solution.displayName);
+ assert.deepEqual(downloaded.value.spec.globalChoices, spec.globalChoices.map((g) => ({ ...g, existing: true })));
+});
+
+test('portable schema reads cost one per present column type and status table, not one per column', async (t) => {
+ const { org, downloaded } = await walk();
+ const requests = org.requests.slice(downloaded.mark, downloaded.end);
+ const casts = {
+ String: 'LogicalName,MaxLength,FormatName,AutoNumberFormat', Memo: 'LogicalName,MaxLength',
+ Integer: 'LogicalName,MinValue,MaxValue,Format', Decimal: 'LogicalName,MinValue,MaxValue,Precision',
+ Double: 'LogicalName,MinValue,MaxValue,Precision', DateTime: 'LogicalName,Format',
+ };
+ for (const [type, select] of Object.entries(casts)) {
+ const reads = requests.filter((r) => r.method === 'GET' && r.path.endsWith(`/Microsoft.Dynamics.CRM.${type}AttributeMetadata?$select=${select}`));
+ assert.equal(reads.length, 1, `${type} options take exactly one conditional cast`);
+ }
+ assert.equal(requests.filter((r) => /StatusAttributeMetadata\?\$select=LogicalName&/.test(r.path)).length, 2,
+ 'one SDK choices projection plus one portable-state read');
+ assert.equal(requests.filter((r) => /MoneyAttributeMetadata\?\$select=LogicalName,IsBaseCurrency,MinValue,MaxValue,Precision,PrecisionSource$/.test(r.path)).length, 1,
+ 'Money options reuse the already-required currency-twin read');
+ assert.equal(requests.filter((r) => /webresourceset\?.*name eq 'contoso_item\.svg'/.test(r.path)).length, 1);
+ t.diagnostic(`portable download ${requests.length} GETs: 6 conditional column casts, 1 status cast; key/icon names, Money/Boolean options, display names and tile sizes reuse existing projections`);
+});
+
+test('download keeps a table vector icon only with its own unmanaged SVG resource, protected from teardown', async () => {
+ const { downloaded } = await walk();
+ assert.equal(downloaded.value.spec.entities[0].vectorIcon, 'contoso_item.svg');
+ assert.deepEqual(downloaded.value.spec.webResources, [{
+ name: 'contoso_item.svg', displayName: 'Item Icon', type: 'svg',
+ contentBase64: Buffer.from(ICON).toString('base64'), external: true,
+ }]);
+});
+
+test('download keeps dashboard tile sizes and omits exactly the dimensions a rebuild defaults', async () => {
+ const { downloaded } = await walk();
+ assert.deepEqual(downloaded.value.spec.dashboards[0].tiles, spec.dashboards[0].tiles);
+});
+
+test('all four supported dashboard tile types keep their size without any additional read', async () => {
+ const calls = [];
+ const id = '11111111-2222-4333-8444-555555555555';
+ const viewId = '22222222-2222-4333-8444-555555555555';
+ const chartId = '33333333-2222-4333-8444-555555555555';
+ const sdk = {
+ fetchArtifact: async (...args) => {
+ calls.push(['fetchArtifact', ...args]);
+ return { components: [
+ { type: 'chart', name: 'Chart', colspan: 2, rowspan: 9, parameters: { TargetEntityType: 'contoso_item', ViewId: viewId, VisualizationId: chartId } },
+ { type: 'list', name: 'List', colspan: 2, rowspan: 15, parameters: { TargetEntityType: 'contoso_item', ViewId: viewId } },
+ { type: 'iframe', name: 'Frame', colspan: 1, rowspan: 1, parameters: { Url: 'https://contoso.example/frame' } },
+ { type: 'webresource', name: 'Resource', colspan: 2, rowspan: 7, parameters: { WebResourceName: 'contoso_panel.html' } },
+ ] };
+ },
+ queryRecords: async (...args) => { calls.push(['queryRecords', ...args]); return [{ name: 'Overview' }]; },
+ };
+ const result = await readDashboards(sdk, { siteMap: { areas: [{ groups: [{ subAreas: [{ type: 'DashBoard', dashboardId: id }] }] }] } });
+ assert.deepEqual(result[0].tiles.map(({ colspan, rowspan }) => ({ colspan, rowspan })), [
+ { colspan: 2, rowspan: 9 }, { colspan: 2, rowspan: 15 }, { colspan: undefined, rowspan: 1 }, { colspan: 2, rowspan: 7 },
+ ]);
+ assert.equal(calls.length, 2);
+});
+
+test('a column at the build defaults gains no invented type options on download', () => {
+ const entity = entityFromMetadata({
+ schemaName: 'contoso_item', primaryNameAttribute: 'contoso_name',
+ attributes: [
+ { logicalName: 'contoso_name', displayName: 'Name', attributeType: 'String', maxLength: 100 },
+ { logicalName: 'contoso_text', displayName: 'Text', attributeType: 'String', maxLength: 100, FormatName: { Value: 'Text' } },
+ { logicalName: 'contoso_flag', displayName: 'Flag', attributeType: 'Boolean', choices: [{ value: 0, label: 'No' }, { value: 1, label: 'Yes' }] },
+ ],
+ }, 'contoso_item');
+ assert.deepEqual(entity.primaryAttribute, { schemaName: 'contoso_name', displayName: 'Name', maxLength: 100 });
+ assert.deepEqual(entity.columns, [
+ { schemaName: 'contoso_text', displayName: 'Text', type: 'Text' },
+ { schemaName: 'contoso_flag', displayName: 'Flag', type: 'Boolean' },
+ ]);
+});
+
+test('rebuilding the downloaded spec reuses columns, status reasons and keys while publishing its icon assignment', async () => {
+ const { root, org, harness, downloaded, built } = await walk();
+ const dir = path.join(root, 'download');
+ const rebuild = ran(await harness.measure(() => harness.build(downloaded.value.spec, {
+ appFolder: dir, workspace: path.join(dir, '.maker-workspace'),
+ })), 'the same-environment rebuild');
+ assert.equal(rebuild.value.result.ok, true, JSON.stringify(rebuild.value.result));
+ const schemaWrites = Object.fromEntries(Object.entries(rebuild.writes).filter(([key]) =>
+ /EntityDefinitions|InsertStatusValue|GlobalOptionSetDefinitions|webresourceset/.test(key)));
+ assert.deepEqual(schemaWrites, { 'PUT EntityDefinitions': 1 }, 'only the table-icon assignment is reasserted');
+ assert.deepEqual(schemaOf(org), built, 'every schema option stays unchanged');
+ assert.deepEqual(validateAppSpec(downloaded.value.spec, { profile: 'plan', reconstructed: true }).errors, []);
+});
+
+test('building the downloaded spec in another environment recreates the same schema options', async () => {
+ const { root, downloaded, built } = await walk();
+ const fresh = createLifecycleOrg();
+ const freshHarness = createLifecycleHarness(fresh, path.join(root, 'fresh'));
+ const portable = structuredClone(downloaded.value.spec);
+ // Dashboard ids pin an edit in the source environment, not an artifact to create in another one.
+ for (const d of portable.dashboards) delete d.dashboardId;
+ const create = ran(await freshHarness.measure(() => freshHarness.build(portable, { appFolder: path.join(root, 'download') })), 'the cross-environment build');
+ assert.equal(create.value.result.ok, true, JSON.stringify(create.value.result));
+ assert.deepEqual(schemaOf(fresh), built);
+ assert.equal(fresh.find('webresourceset', (w) => w.name === 'contoso_item.svg')[0].content, Buffer.from(ICON).toString('base64'));
+ const dashboard = fresh.find('systemforms', (f) => f.name === 'Item Overview')[0];
+ assert.match(dashboard.formxml, /colspan="2" rowspan="8"|rowspan="8" colspan="2"/);
+});
+
+test('no-op proofs do not suppress a missing status, key, icon or a real Whole Number format edit', async () => {
+ const { org, root, harness, downloaded, built } = await walk();
+ const table = org.metadata.tables.get('contoso_item');
+ table.Keys.delete('contoso_itememail');
+ table.IconVectorName = null;
+ table.Attributes.get('contoso_minutes').Format = 'None';
+ const status = table.Attributes.get('statuscode').OptionSet;
+ status.Options = status.Options.filter((o) => o.Value !== 100000042);
+ const dir = path.join(root, 'download');
+ const rebuild = ran(await harness.measure(() => harness.build(downloaded.value.spec, {
+ appFolder: dir, workspace: path.join(dir, '.maker-workspace'),
+ })), 'the repair rebuild');
+ assert.equal(rebuild.value.result.ok, true, JSON.stringify(rebuild.value.result));
+ assert.equal(rebuild.writes['POST InsertStatusValue'], 1);
+ assert.equal(rebuild.writes['POST EntityDefinitions/Keys'], 1);
+ assert.equal(rebuild.writes['PUT EntityDefinitions'], 1);
+ assert.equal(rebuild.writes['PUT EntityDefinitions/Attributes'], 1);
+ assert.deepEqual(schemaOf(org), built);
+});
+
+test('a full-build rerun completes an icon publish after its table assignment was saved', async () => {
+ const logical = 'contoso_icononly';
+ const resource = 'contoso_icononly.svg';
+ const org = createLifecycleOrg();
+ const root = makeTempDir('table-icon-recovery-');
+ const observed = [];
+ let refuseIconPublish = false;
+ let assigned = false;
+ let refused = 0;
+ // The SDK's own table publish carries ParameterXml, e.g.
+ // <importexportxml><entities><entity>contoso_icononly</entity></entities></importexportxml>.
+ // Select only this one-table request, never an app/resource publish or another table.
+ const isIconPublish = (call) => {
+ if (call.method !== 'POST' || !call.path.endsWith('/PublishXml') || !call.body) return false;
+ const xml = call.body.ParameterXml;
+ if (typeof xml !== 'string' || /<(?:appmodule|webresource)>/.test(xml)) return false;
+ const names = [...xml.matchAll(/<entity>([^<]+)<\/entity>/g)].map((m) => m[1]);
+ return names.length === 1 && names[0] === logical;
+ };
+ const request = async (req) => {
+ const url = new URL(req.url);
+ const isDefinitionPut = req.method === 'PUT' && /\/EntityDefinitions\(/.test(url.pathname);
+ const isPublish = req.method === 'POST' && url.pathname.endsWith('/PublishXml');
+ const call = { method: req.method, path: url.pathname, body: isDefinitionPut || isPublish ? JSON.parse(String(req.body)) : undefined };
+ observed.push(call);
+ if (refuseIconPublish && assigned && isIconPublish(call)) {
+ refused += 1;
+ call.status = 403;
+ return { statusCode: 403, headers: { 'content-type': 'application/json' }, body: JSON.stringify({
+ error: { code: '0x80040220', message: 'Owned fixture table-icon publish refused' },
+ }) };
+ }
+ const response = await org.request(req);
+ call.status = response.statusCode;
+ if (isDefinitionPut && call.body.IconVectorName === resource && response.statusCode >= 200 && response.statusCode < 300) assigned = true;
+ return response;
+ };
+ const harness = createLifecycleHarness({ ...org, request }, root);
+ const seed = {
+ schemaVersion: 2,
+ solution: { uniqueName: 'ContosoIconRecovery', displayName: 'Icon Recovery', publisherPrefix: 'contoso' },
+ app: { name: 'Icon Recovery', tables: [logical, 'contoso_untouched'] },
+ entities: [logical, 'contoso_untouched'].map((schemaName) => ({
+ schemaName, displayName: schemaName,
+ primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [],
+ })),
+ webResources: [{ name: resource, type: 'svg', content: ICON }],
+ appShell: { areas: [{ label: 'Links', groups: [{ label: 'Help', subAreas: [
+ { url: 'https://contoso.example/help', title: 'Help' },
+ ] }] }] },
+ };
+ const options = { publish: false, sampleData: false, verify: false };
+ const seeded = ran(await harness.measure(() => harness.build(seed, options)), 'the complete setup build');
+ assert.equal(seeded.value.result.ok, true, JSON.stringify(seeded.value.result));
+ const desired = structuredClone(seed);
+ for (const entity of desired.entities) entity.existing = true;
+ desired.entities[0].vectorIcon = resource;
+ desired.webResources[0].external = true;
+ const unrelated = structuredClone(org.metadata.tables.get('contoso_untouched'));
+ const successfulPublishes = (since) => observed.slice(since).filter((call) =>
+ isIconPublish(call) && call.status >= 200 && call.status < 300);
+
+ refuseIconPublish = true;
+ const beforeFailure = observed.length;
+ const failed = await harness.measure(() => harness.build(desired, options));
+ assert.deepEqual(failed.unexpected, []);
+ assert.equal(refused, 1, 'the request fault is reached only after the successful icon metadata PUT');
+ assert.ok(failed.error, 'the full build propagates its failed icon publication');
+ assert.match(failed.error.message, /table icon|publish/i);
+ assert.equal(org.metadata.tables.get(logical).IconVectorName, resource, 'saved metadata already has the requested name');
+ assert.equal(successfulPublishes(beforeFailure).length, 0);
+
+ refuseIconPublish = false;
+ const beforeRetry = observed.length;
+ const freshHarness = createLifecycleHarness({ ...org, request }, root);
+ const retry = ran(await freshHarness.measure(() => freshHarness.build(desired, options)), 'the full same-workspace rerun');
+ assert.equal(retry.value.result.ok, true, JSON.stringify(retry.value.result));
+ assert.equal(successfulPublishes(beforeRetry).length, 1,
+ 'a saved icon assignment with a failed publish must finish that publish on rerun');
+ const beforeCompleted = observed.length;
+ const completed = ran(await freshHarness.measure(() => freshHarness.build(desired, options)), 'the completed unchanged rebuild');
+ assert.equal(completed.value.result.ok, true, JSON.stringify(completed.value.result));
+ assert.equal(observed.slice(beforeCompleted).filter((call) =>
+ call.method === 'PUT' && call.body && call.body.IconVectorName === resource).length, 1,
+ 'completed unchanged icons retain the released assignment behavior');
+ assert.equal(successfulPublishes(beforeCompleted).length, 1,
+ 'completed unchanged icons retain their specific-table publish rather than guessing from metadata');
+ assert.deepEqual(org.metadata.tables.get('contoso_untouched'), unrelated, 'the unrelated table definition stays unchanged');
+});
diff --git a/plugins/model-apps/scripts/tests/entity-provision.test.js b/plugins/model-apps/scripts/tests/entity-provision.test.js
index a4f620235..e82496996 100644
--- a/plugins/model-apps/scripts/tests/entity-provision.test.js
+++ b/plugins/model-apps/scripts/tests/entity-provision.test.js
@@ -1248,7 +1248,7 @@ test('requireSuccessfulPush distinguishes an already-exists collision from a ver
(e) => {
assert.strictEqual(e.name, 'BuildHalt');
assert.strictEqual(e.code, 'already-exists');
- assert.match(e.message, /To reset it, stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json, destructive-approval\.json and the page-ownership\.\*\.json records \(the receipts and pending records of the pages the app created: nothing else can find them\), and re-run the build to adopt the existing row\./, 'the halt must name the step that clears it, keeping the baseline, the approval record and the page records');
+ assert.match(e.message, /To reset it, stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json, destructive-approval\.json, web-resource-unconfirmed\.\*\.json \(the durable ids needed to recover unconfirmed web-resource writes\), dashboard-creation\.\*\.json \(the ids of the dashboards an interrupted build created before they joined the solution\) and the page-ownership\.\*\.json records \(the receipts and pending records of the pages the app created: nothing else can find them\), and re-run the build to adopt the existing row\./, 'the halt must name the step that clears it, keeping the baseline, the approval record and the page and resource records');
assert.match(e.message, /halts here again/, 'and say why a plain re-run does not');
assert.doesNotMatch(e.message, /re-download the app/);
assert.doesNotMatch(e.message, /adopt it \(fetchArtifact\)/, 'a plain fetch adopts nothing here — it must not be prescribed');
diff --git a/plugins/model-apps/scripts/tests/fake-lifecycle-org-contract.test.js b/plugins/model-apps/scripts/tests/fake-lifecycle-org-contract.test.js
index 93bc8e390..d3b2d32ad 100644
--- a/plugins/model-apps/scripts/tests/fake-lifecycle-org-contract.test.js
+++ b/plugins/model-apps/scripts/tests/fake-lifecycle-org-contract.test.js
@@ -125,6 +125,31 @@ test("fake contract: a Money column's base-currency twin has the live-measured f
assert.deepEqual([...org.metadata.tables.get('fabrikam_widget').Attributes.keys()].filter((name) => name.startsWith('fabrikam_price')), []);
});
+// MEASURED on a live environment, from a table's ManyToOneRelationships: a File column comes with a CUSTOM relationship to the stock
+// table fileattachment, and an Image column with one, not custom, to imagedescriptor through its `<name>id` — each named for its table and
+// column. A download reads them back (download-model-app.js mediaRelationshipKeys); each goes with its column and with its table.
+test("fake contract: a File and an Image column come with the platform's relationship of each, as measured, which goes with the column and the table", async () => {
+ const org = await populated();
+ const label = (text) => ({ LocalizedLabels: [{ Label: text, LanguageCode: 1033 }] });
+ const where = "/EntityDefinitions(LogicalName='fabrikam_widget')/Attributes";
+ assert.equal((await send(org, 'POST', where, { '@odata.type': 'Microsoft.Dynamics.CRM.FileAttributeMetadata', SchemaName: 'fabrikam_manual', DisplayName: label('Manual'), RequiredLevel: { Value: 'None' }, MaxSizeInKB: 1024 })).status, 204);
+ assert.equal((await send(org, 'POST', where, { '@odata.type': 'Microsoft.Dynamics.CRM.ImageAttributeMetadata', SchemaName: 'fabrikam_photo', DisplayName: label('Photo'), RequiredLevel: { Value: 'None' }, MaxSizeInKB: 10240 })).status, 204);
+ const rows = async () => answered(await send(org, 'GET', "/EntityDefinitions(LogicalName='fabrikam_widget')/ManyToOneRelationships?$select=SchemaName,ReferencedEntity,ReferencingEntity,ReferencingAttribute,IsCustomRelationship")).value
+ .filter((r) => /^(FileAttachment|ImageDescriptor)_/.test(r.SchemaName))
+ .map((r) => [r.SchemaName, r.ReferencedEntity, r.ReferencingEntity, r.ReferencingAttribute, r.IsCustomRelationship]).sort();
+ assert.deepEqual(await rows(), [
+ ['FileAttachment_fabrikam_widget_fabrikam_manual', 'fileattachment', 'fabrikam_widget', 'fabrikam_manual', true],
+ ['ImageDescriptor_fabrikam_widget_fabrikam_photo', 'imagedescriptor', 'fabrikam_widget', 'fabrikam_photoid', false],
+ ]);
+ // The parent of each is a stock table, as the platform reports fileattachment.
+ assert.equal(answered(await send(org, 'GET', "/EntityDefinitions(LogicalName='fileattachment')?$select=IsCustomEntity")).IsCustomEntity, false);
+ assert.equal(answered(await send(org, 'GET', "/EntityDefinitions(LogicalName='imagedescriptor')?$select=IsCustomEntity")).IsCustomEntity, false);
+ assert.equal((await send(org, 'DELETE', `${where}(LogicalName='fabrikam_manual')`)).status, 204);
+ assert.deepEqual((await rows()).map((r) => r[0]), ['ImageDescriptor_fabrikam_widget_fabrikam_photo'], 'the File column took its own with it');
+ assert.equal((await send(org, 'DELETE', "/EntityDefinitions(LogicalName='fabrikam_widget')")).status, 204);
+ assert.deepEqual([...org.metadata.relationships.keys()].filter((name) => /^(fileattachment|imagedescriptor)_/.test(name)), [], 'and the table took the rest');
+});
+
test("fake contract: the content proof sees another maker's work overwritten, which the identity inventory does not", async () => {
const overwrites = [
['the foreign view\'s FetchXML', async (org) => { const v = org.find('savedqueries', (r) => r.name === 'Open Projects')[0]; return send(org, 'PATCH', `/savedqueries(${v.savedqueryid})`, { fetchxml: '<fetch><entity name="wrong_table"/></fetch>' }); }, /changed: savedqueries .* "Open Projects" \(saved\.fetchxml, saved\.modifiedon, saved\.versionnumber\)/],
diff --git a/plugins/model-apps/scripts/tests/feature-flags.test.js b/plugins/model-apps/scripts/tests/feature-flags.test.js
index 15e9ef8a6..6be077adb 100644
--- a/plugins/model-apps/scripts/tests/feature-flags.test.js
+++ b/plugins/model-apps/scripts/tests/feature-flags.test.js
@@ -19,7 +19,7 @@ const {
FLAGS,
} = require(libPath);
-// --- Default OFF (fail-closed) ---------------------------------------------
+// --- Committed defaults and fail-closed fallback ---------------------------
test('connectors flag is retired and unknown fail-closed', () => {
const json = JSON.parse(
@@ -34,10 +34,17 @@ test('connectors flag is retired and unknown fail-closed', () => {
assert.equal(lib[removed], undefined, `${removed} must stay removed now that connectors have no flag`);
}
});
-test('custom-api flag is OFF by default (no env override)', () => {
- // Same fail-closed contract every gated feature relies on: an empty env falls through to the
- // committed feature-flags.json, which ships custom-api:false until the runtime stack is GA in PROD.
- assert.equal(isCustomApiEnabled({ env: {} }), false);
+test('custom-api flag is ON by default without changing the generic fail-closed fallback', () => {
+ assert.equal(isEnabled('custom-api', { env: {} }), true);
+ assert.equal(isCustomApiEnabled({ env: {} }), true);
+ for (const flags of [{}, { 'custom-api': false }, { 'custom-api': 'true' }]) {
+ assert.equal(isEnabled('custom-api', { env: {}, flags }), false);
+ }
+});
+
+test('an explicit custom-api opt-out overrides the committed enabled default', () => {
+ assert.equal(isEnabled('custom-api', { env: { GENPAGE_ENABLE_CUSTOM_API: '0' } }), false);
+ assert.equal(isCustomApiEnabled({ env: { GENPAGE_ENABLE_CUSTOM_API: '0' } }), false);
});
test('custom-telemetry flag is OFF by default (no env override)', () => {
@@ -103,13 +110,19 @@ test('customApiDisabledMessage explains how to enable', () => {
assert.match(m, /feature-flags\.json/);
});
-// --- Committed config actually ships OFF ------------------------------------
+test('the Custom API catalog and disabled guidance describe the enabled default and opt-out', () => {
+ assert.match(FLAGS['custom-api'].summary, /enabled by default/i);
+ assert.match(customApiDisabledMessage(), /GENPAGE_ENABLE_CUSTOM_API=0/);
+ assert.doesNotMatch(customApiDisabledMessage(), /once the dependencies are released/);
+});
-test('committed feature-flags.json ships custom-api: false', () => {
+// --- Committed config keeps each feature's own default ---------------------
+
+test('committed feature-flags.json ships custom-api: true', () => {
const json = JSON.parse(
fs.readFileSync(path.join(__dirname, '..', '..', 'feature-flags.json'), 'utf8')
);
- assert.equal(json['custom-api'], false);
+ assert.equal(json['custom-api'], true);
});
test('committed feature-flags.json ships custom-telemetry: false', () => {
@@ -121,15 +134,23 @@ test('committed feature-flags.json ships custom-telemetry: false', () => {
// --- CLI probe (deterministic gate for the skill markdown) ------------------
-test('CLI prints "disabled" and exits 1 when OFF', () => {
+test('CLI prints "disabled" and exits 1 for an explicit opt-out', () => {
const res = spawnSync(process.execPath, [libPath, 'custom-api'], {
encoding: 'utf8',
- env: { ...process.env, GENPAGE_ENABLE_CUSTOM_API: '' },
+ env: { ...process.env, GENPAGE_ENABLE_CUSTOM_API: '0' },
});
assert.equal(res.status, 1);
assert.match(res.stdout, /disabled/);
});
+test('CLI prints "enabled" and exits 0 without an environment override', () => {
+ const env = { ...process.env };
+ delete env.GENPAGE_ENABLE_CUSTOM_API;
+ const res = spawnSync(process.execPath, [libPath, 'custom-api'], { encoding: 'utf8', env });
+ assert.equal(res.status, 0, res.stderr);
+ assert.equal(res.stdout.trim(), 'enabled');
+});
+
test('CLI prints "enabled" and exits 0 when env override ON', () => {
const res = spawnSync(process.execPath, [libPath, 'custom-api'], {
encoding: 'utf8',
@@ -151,7 +172,7 @@ test('exitIfCustomApiDisabled exits 3 and writes the message when OFF', () => {
let exitCode = null;
let written = '';
exitIfCustomApiDisabled({
- env: {},
+ env: { GENPAGE_ENABLE_CUSTOM_API: '0' },
exit: (c) => { exitCode = c; },
write: (s) => { written += s; },
});
diff --git a/plugins/model-apps/scripts/tests/form-field-options.test.js b/plugins/model-apps/scripts/tests/form-field-options.test.js
index c862b3a03..927786e11 100644
--- a/plugins/model-apps/scripts/tests/form-field-options.test.js
+++ b/plugins/model-apps/scripts/tests/form-field-options.test.js
@@ -20,6 +20,7 @@
const test = require('node:test');
const assert = require('node:assert');
const path = require('node:path');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
const {
compileFormIntent,
@@ -595,3 +596,269 @@ test('__explicitLayout reports what was COMPILED, not what was requested', () =>
const real = compileIntent(realSpec, realSpec.forms[0]);
assert.strictEqual(real.__explicitLayout, true, 'an authored tabs layout IS explicit');
});
+
+// ---------------------------------------------------------------------------
+// fieldOptions keys: one closed list, shared with the inline field entry
+// ---------------------------------------------------------------------------
+//
+// A `fieldOptions` entry was checked only for the VALUES of the keys the build reads. Any other key
+// (a typo such as `readOnlyy`, a casing slip such as `colSpan`, a key of another object such as a
+// subgrid's `before`) validated clean and then disappeared: the compiler projects only readOnly,
+// hidden, after, colspan and rowspan, so the build succeeded and the option was never applied. The
+// inline `fields[]` entry already refused an unknown key as an error, so the map now does the same,
+// over the same five keys. `name` is not one of them: in the map, the KEY names the field.
+
+const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');
+const { buildModelApp } = require('../build-model-app.js');
+const { createFakeBuildOrg } = require('./helpers/fake-app-build-org.js');
+const { runScript } = require('./helpers/run-with-fakes.js');
+
+const OPTION_KEYS_ALLOWED = '(allowed: readOnly, hidden, after, colspan, rowspan)';
+const unknownOptionKey = (field, key, hint = '') =>
+ `form 'Item' (table new_item): unknown key '${key}' on fieldOptions['${field}']${hint} ${OPTION_KEYS_ALLOWED}`;
+const readOnlyTypo = () => specWithBigInt({ fieldOptions: { new_points: { readOnlyy: true } } });
+
+test('validation rejects a misspelled fieldOptions key, naming the form, table, field and key, the key it most likely meant and the keys allowed', () => {
+ assert.deepStrictEqual(errsFor(readOnlyTypo()), [unknownOptionKey('new_points', 'readOnlyy', " — did you mean 'readOnly'?")]);
+});
+
+test('validation rejects a span- or anchor-like key that a fieldOptions entry does not take', () => {
+ // `colSpan` differs from a real key only in case, `before` is a subgrid's placement key, and
+ // `span` is no key at all, so only the first has a likely meaning to offer.
+ const errs = errsFor(specWithBigInt({ fieldOptions: {
+ new_points: { colSpan: 2 },
+ new_duedate: { before: 'new_name' },
+ new_daysremaining: { span: 2 },
+ } }));
+ assert.deepStrictEqual(errs, [
+ unknownOptionKey('new_points', 'colSpan', " — did you mean 'colspan'?"),
+ unknownOptionKey('new_duedate', 'before'),
+ unknownOptionKey('new_daysremaining', 'span'),
+ ]);
+});
+
+test('validation rejects the unknown key of an entry that mixes it with valid keys, and still checks the valid ones', () => {
+ const errs = errsFor(specWithBigInt({ fieldOptions: {
+ new_points: { readOnly: true, hiden: true },
+ new_duedate: { hidden: false, readOnlyy: true },
+ } }));
+ assert.deepStrictEqual(errs.filter((e) => /unknown key/.test(e)), [
+ unknownOptionKey('new_points', 'hiden', " — did you mean 'hidden'?"),
+ unknownOptionKey('new_duedate', 'readOnlyy', " — did you mean 'readOnly'?"),
+ ]);
+ // A valid key beside an unknown one keeps its own check: `hidden: false` is still refused, and
+ // `readOnly: true` adds nothing.
+ assert.strictEqual(errs.length, 3, errs.join(' | '));
+ assert.ok(errs.some((e) => /fieldOptions\['new_duedate'\] sets hidden: false/.test(e)), errs.join(' | '));
+});
+
+test("validation rejects 'name' inside a fieldOptions entry, because the map key already names the field", () => {
+ // An inline `fields[]` entry carries its `name`; a map entry is keyed by it. Accepting `name` here
+ // would let `{ "new_a": { "name": "new_b" } }` say two different things about which field it means.
+ const errs = errsFor(specWithBigInt({ fieldOptions: { new_points: { name: 'new_points', readOnly: true } } }));
+ assert.deepStrictEqual(errs, [unknownOptionKey('new_points', 'name', " — a fieldOptions entry is keyed by the field's logical name, so it takes no 'name'")]);
+});
+
+test("validation points a fieldOptions 'visible' at 'hidden', the option that hides a field", () => {
+ // Tabs and sections take `visible`, so it is a likely key to reach for; no near spelling explains it.
+ const errs = errsFor(specWithBigInt({ fieldOptions: { new_points: { visible: false } } }));
+ assert.deepStrictEqual(errs, [unknownOptionKey('new_points', 'visible', " — to keep the field on the form but not show it, use 'hidden': true")]);
+});
+
+test('a fieldOptions key that collides with Object.prototype is reported as itself, never as a native function', () => {
+ // JSON.parse makes each of these an OWN key of the entry. A hint table that is a plain object would
+ // answer `constructor` with Object's own function and splice its source into the message. The form
+ // has no name here, so the message names it by its table alone.
+ const entry = JSON.parse('{ "constructor": true, "toString": 1 }');
+ const errs = errsFor(specWithBigInt({ name: undefined, fieldOptions: { new_points: entry } }));
+ assert.deepStrictEqual(errs, ['constructor', 'toString'].map((k) => `form 'new_item': unknown key '${k}' on fieldOptions['new_points'] ${OPTION_KEYS_ALLOWED}`));
+});
+
+test('an inline field entry keeps its own contract: name plus the same five options, and an unknown key is still refused', () => {
+ // The layout check already refused these; the shared list must not change what an inline entry
+ // accepts or how a refusal reads.
+ const spec = specWithBigInt({
+ layout: 'explicit',
+ tabs: [{ label: 'G', sections: [{ label: 'D', columns: 1, fields: ['new_name', { name: 'new_points', readOnlyy: true }, { name: 'new_duedate', readonly: true }] }] }],
+ });
+ assert.deepStrictEqual(errsFor(spec), [
+ "form 'Item': unknown key 'readOnlyy' on tab 'G' section 'D' field 'new_points' (allowed: name, readOnly, hidden, after, colspan, rowspan)",
+ "form 'Item': unknown key 'readonly' on tab 'G' section 'D' field 'new_duedate' — did you mean 'readOnly'? (allowed: name, readOnly, hidden, after, colspan, rowspan)",
+ ]);
+});
+
+test('each of the five options still validates and compiles exactly as before, form-level and inline', () => {
+ const none = { readOnly: false, hidden: false, after: undefined, colspan: undefined, rowspan: undefined };
+ const shape = (c) => [c.control.fieldName, c.control.isReadOnly, c.visible, c.colspan, c.rowspan];
+
+ // Form-level, under the AUTO layout (its only route). The one-column auto section clamps the
+ // cell's colspan to 1, while the raw span survives for the reconcile.
+ const auto = specWithBigInt({ fieldOptions: {
+ new_name: { readOnly: true },
+ new_duedate: { hidden: true },
+ new_daysremaining: { after: 'New_DueDate' },
+ new_points: { colspan: 2, rowspan: 1 },
+ } });
+ assert.deepStrictEqual(errsFor(auto), []);
+ assert.deepStrictEqual(fieldOptionsMap(auto.forms[0]), {
+ new_name: { name: 'new_name', ...none, readOnly: true },
+ new_duedate: { name: 'new_duedate', ...none, hidden: true },
+ new_daysremaining: { name: 'new_daysremaining', ...none, after: 'new_duedate' },
+ new_points: { name: 'new_points', ...none, colspan: 2, rowspan: 1 },
+ });
+ const autoIntent = compileFormIntent(auto, auto.forms[0]);
+ assert.deepStrictEqual(autoCells(autoIntent).map(shape), [
+ ['new_name', true, undefined, undefined, undefined],
+ ['new_duedate', undefined, false, undefined, undefined],
+ ['new_daysremaining', undefined, undefined, undefined, undefined],
+ ['new_points', undefined, undefined, 1, 1],
+ ]);
+ assert.deepStrictEqual(autoIntent.__fieldPositions, { new_daysremaining: 'new_duedate' });
+ assert.deepStrictEqual(autoIntent.__fieldSpans, { new_points: { colspan: 2, rowspan: 1 } });
+
+ // Inline, on an EXPLICIT layout: a rowspan above 1 is legal on the last field of its section.
+ const explicit = specWithBigInt({
+ layout: 'explicit',
+ tabs: [{ label: 'G', sections: [{ label: 'D', columns: 2, fields: [
+ { name: 'New_Name', readOnly: true },
+ { name: 'new_duedate', hidden: true },
+ { name: 'new_daysremaining', colspan: 2 },
+ { name: 'new_points', rowspan: 2 },
+ ] }] }],
+ });
+ assert.deepStrictEqual(errsFor(explicit), []);
+ assert.deepStrictEqual(explicit.forms[0].tabs[0].sections[0].fields.map(normalizeFieldEntry), [
+ { name: 'new_name', ...none, readOnly: true },
+ { name: 'new_duedate', ...none, hidden: true },
+ { name: 'new_daysremaining', ...none, colspan: 2 },
+ { name: 'new_points', ...none, rowspan: 2 },
+ ]);
+ const explicitIntent = compileFormIntent(explicit, explicit.forms[0]);
+ assert.deepStrictEqual(explicitIntent.tabs[0].columns[0].sections[0].rows.map((r) => r.cells.map(shape)), [
+ [['new_name', true, undefined, undefined, undefined], ['new_duedate', undefined, false, undefined, undefined]],
+ [['new_daysremaining', undefined, undefined, 2, undefined]],
+ [['new_points', undefined, undefined, undefined, 2]],
+ ]);
+ assert.deepStrictEqual(explicitIntent.__fieldSpans, { new_daysremaining: { colspan: 2 }, new_points: { rowspan: 2 } });
+});
+
+test('the compiler projects exactly the option keys validation accepts, from either route', () => {
+ const { FIELD_OPTION_KEYS } = require(path.join(__dirname, '..', 'lib', 'app-spec.js'));
+ assert.deepStrictEqual([...FIELD_OPTION_KEYS], ['readOnly', 'hidden', 'after', 'colspan', 'rowspan']);
+ assert.ok(Object.isFrozen(FIELD_OPTION_KEYS), 'the shared list cannot be widened at run time');
+ for (const projected of [normalizeFieldEntry('new_a'), normalizeFieldEntry({ name: 'new_a', readOnly: true }), fieldOptionsMap({ fieldOptions: { new_a: {} } }).new_a]) {
+ assert.deepStrictEqual(Object.keys(projected), ['name', ...FIELD_OPTION_KEYS]);
+ }
+ // A key added to the list must arrive with a value it is known to take, so this table has to move
+ // with it: each key, on its own, validates and reaches the projection.
+ const sample = { readOnly: true, hidden: true, after: 'new_name', colspan: 2, rowspan: 1 };
+ assert.deepStrictEqual(Object.keys(sample), [...FIELD_OPTION_KEYS]);
+ for (const key of FIELD_OPTION_KEYS) {
+ const spec = specWithBigInt({ fieldOptions: { new_points: { [key]: sample[key] } } });
+ assert.deepStrictEqual(errsFor(spec), [], key);
+ assert.strictEqual(fieldOptionsMap(spec.forms[0]).new_points[key], sample[key], key);
+ }
+});
+
+test('a key outside the list never reaches the compiled form, even where validation is bypassed', () => {
+ const spec = specWithBigInt({ fieldOptions: { new_points: { readOnly: true, readOnlyy: true, hiden: true } } });
+ assert.deepStrictEqual(fieldOptionsMap(spec.forms[0]).new_points, { name: 'new_points', readOnly: true, hidden: false, after: undefined, colspan: undefined, rowspan: undefined });
+ assert.deepStrictEqual(cellFor(compileFormIntent(spec, spec.forms[0]), 'new_points'), { control: { fieldName: 'new_points', isReadOnly: true } });
+});
+
+test('the build refuses a misspelled fieldOptions key before any request reaches the environment, on a dry run and on an apply', async () => {
+ // The real vendored SDK over a fake Dataverse that records every request it is sent.
+ const org = createFakeBuildOrg({ entities: { new_item: { attributes: { new_name: 'String' } } } });
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(makeTempDir('field-option-keys-')), instanceUrl: org.origin, httpClient: org.httpClient });
+ for (const opts of [{ apply: false, livePlan: true }, { apply: true, publish: true }]) {
+ const r = await buildModelApp(readOnlyTypo(), { ...opts, env: org.origin, retryDelayMs: 0 }, { sdk, provisionSdk: sdk, sleep: async () => {}, log: () => {}, warn: () => {} });
+ assert.strictEqual(r.ok, false, JSON.stringify(opts));
+ assert.deepStrictEqual(r.errors, [unknownOptionKey('new_points', 'readOnlyy', " — did you mean 'readOnly'?")], JSON.stringify(opts));
+ }
+ assert.deepStrictEqual(org.calls, [], 'no request reached the environment');
+});
+
+test('the build command refuses the same spec on a dry run before it reads a token or sends a request', () => {
+ // A dry run reads the environment for its plan unless --no-live-plan is given, so a spec that
+ // validated would be sent requests here.
+ const r = runScript('build-model-app.js', ['--env', 'https://contoso.crm.dynamics.com', '--spec', (dir) => `@${path.join(dir, 'app-spec.json')}`], {
+ files: { 'app-spec.json': JSON.stringify(readOnlyTypo()) },
+ });
+ assert.strictEqual(r.status, 1, r.stderr);
+ assert.deepStrictEqual(JSON.parse(r.stdout).errors, [unknownOptionKey('new_points', 'readOnlyy', " — did you mean 'readOnly'?")]);
+ assert.deepStrictEqual(r.requests, [], 'no request was sent');
+ assert.deepStrictEqual(r.tokenReads, { dataverse: 0, powerApps: 0 }, 'no token was read');
+});
+
+// A spec that a release before this check accepted can carry such a key: the build ignored it then and built
+// the form without the option. Every path that builds or plans a build keeps the refusal above. The paths that
+// only READ a spec to act on what was deployed take the same finding as a warning, so an app built from it can
+// still be torn down, previewed and verified: the structural profile (teardown and preview) always, and
+// read-only verification through `fieldOptionKeys: 'warn'`, which only verify-model-app.js passes.
+
+const { lintSpec } = require('../lint-app-spec.js');
+const { scriptsMatching } = require('./helpers/production-scripts.js');
+const READ_ONLY_TYPO = unknownOptionKey('new_points', 'readOnlyy', " — did you mean 'readOnly'?");
+
+test('an unknown fieldOptions key stays an error under every profile that builds, and is a warning in the same words under the structural profile', () => {
+ for (const profile of ['design', 'plan', 'deploy']) {
+ const result = validateAppSpec(readOnlyTypo(), { profile });
+ assert.strictEqual(result.ok, false, profile);
+ assert.deepStrictEqual(result.errors, [READ_ONLY_TYPO], profile);
+ assert.deepStrictEqual(result.warnings, [], profile);
+ }
+ const structural = validateAppSpec(readOnlyTypo(), { profile: 'structural' });
+ assert.strictEqual(structural.ok, true, JSON.stringify(structural.errors));
+ assert.deepStrictEqual(structural.errors, []);
+ assert.deepStrictEqual(structural.warnings, [READ_ONLY_TYPO]);
+ // The lint, the authoring flow's gate, reports it as a schema error under its default and every profile that builds.
+ for (const options of [undefined, { profile: 'design' }, { profile: 'plan' }, { profile: 'deploy' }]) {
+ const report = lintSpec(readOnlyTypo(), options);
+ assert.strictEqual(report.ok, false, JSON.stringify(options));
+ assert.ok(report.errors.includes(`schema: ${READ_ONLY_TYPO}`), `${JSON.stringify(options)}: ${JSON.stringify(report.errors)}`);
+ }
+});
+
+test('fieldOptionKeys: "warn" moves this finding to the warnings under the deploy profile, and no other value or downgrade moves it', () => {
+ const lenient = validateAppSpec(readOnlyTypo(), { profile: 'deploy', fieldOptionKeys: 'warn' });
+ assert.strictEqual(lenient.ok, true, JSON.stringify(lenient.errors));
+ assert.deepStrictEqual(lenient.errors, []);
+ assert.deepStrictEqual(lenient.warnings, [READ_ONLY_TYPO]);
+ for (const options of [{}, { fieldOptionKeys: true }, { fieldOptionKeys: 'WARN' }, { fieldOptionKeys: 'error' }, { columnValues: 'warn' }, { relationshipCollisions: 'warn' }]) {
+ const result = validateAppSpec(readOnlyTypo(), { profile: 'deploy', ...options });
+ assert.deepStrictEqual(result.errors, [READ_ONLY_TYPO], JSON.stringify(options));
+ }
+});
+
+test('the downgrade moves nothing but this finding: a malformed entry, a value the build cannot apply, an inline unknown key and any other problem stay errors', () => {
+ // One explicit form carries each neighbour of the finding: an inline entry with an unknown key, a form-level
+ // entry that is not an object, and `readOnly: false` beside the misspelled key; the table has a column of no known type.
+ const spec = () => {
+ const s = specWithBigInt({
+ layout: 'explicit',
+ prune: false,
+ tabs: [{ label: 'G', sections: [{ label: 'D', columns: 1, fields: ['new_name', { name: 'new_duedate', readOnlyy: true }] }] }],
+ fieldOptions: { new_points: { readOnly: false, readOnlyy: true }, new_daysremaining: 'hidden' },
+ });
+ s.entities[0].columns.push({ schemaName: 'new_bad', type: 'Nope' });
+ return s;
+ };
+ const strict = validateAppSpec(spec(), { profile: 'deploy' });
+ assert.ok(strict.errors.includes(READ_ONLY_TYPO), JSON.stringify(strict.errors));
+ const kept = strict.errors.filter((e) => e !== READ_ONLY_TYPO);
+ assert.strictEqual(kept.length, 4, JSON.stringify(kept));
+ for (const options of [{ profile: 'structural' }, { profile: 'deploy', fieldOptionKeys: 'warn' }]) {
+ const result = validateAppSpec(spec(), options);
+ const label = JSON.stringify(options);
+ assert.strictEqual(result.ok, false, label);
+ assert.deepStrictEqual(result.errors, kept, label);
+ assert.deepStrictEqual(result.warnings, [READ_ONLY_TYPO], label);
+ }
+ for (const pattern of [/column new_bad has unknown type 'Nope'/, /fieldOptions\['new_daysremaining'\] must be an object/, /fieldOptions\['new_points'\] sets readOnly: false/, /unknown key 'readOnlyy' on tab 'G' section 'D' field 'new_duedate'/]) {
+ assert.ok(kept.some((e) => pattern.test(e)), `${pattern} stays an error: ${JSON.stringify(kept)}`);
+ }
+});
+
+test('no script but the verify CLI passes the fieldOptions key downgrade', () => {
+ assert.deepStrictEqual(scriptsMatching(/fieldOptionKeys\s*:\s*['"]warn['"]/), ['verify-model-app.js']);
+});
diff --git a/plugins/model-apps/scripts/tests/genpage-upload.test.js b/plugins/model-apps/scripts/tests/genpage-upload.test.js
index 298bdde91..01a22ddc5 100644
--- a/plugins/model-apps/scripts/tests/genpage-upload.test.js
+++ b/plugins/model-apps/scripts/tests/genpage-upload.test.js
@@ -2227,7 +2227,8 @@ test('REAL SDK: a publish the budget has no room to wait for is said on stderr w
const refusePublish = (method, requestPath) => {
if (!(throttled && method === 'POST' && /\/PublishXml$/.test(requestPath))) return undefined;
throttled = false;
- return { statusCode: 429, headers: { 'retry-after': '600' }, body: '{"error":{"message":"throttled"}}' };
+ // A throttle of the service protection limits, by its documented code: the one 429 a publish is waited out for. A publish the customization lock refused is sent once (lib/sdk-http-client.js, publishOnce).
+ return { statusCode: 429, headers: { 'retry-after': '600' }, body: '{"error":{"code":"0x80072322","message":"Number of requests exceeded the limit of 6000 over time window of 300 seconds."}}' };
};
const backend = (env, fromScript = {}) => {
const httpClient = createAzHttpClient(env, {
diff --git a/plugins/model-apps/scripts/tests/golden/teardown-published-requests.txt b/plugins/model-apps/scripts/tests/golden/teardown-published-requests.txt
index 7e3737130..b0234c530 100644
--- a/plugins/model-apps/scripts/tests/golden/teardown-published-requests.txt
+++ b/plugins/model-apps/scripts/tests/golden/teardown-published-requests.txt
@@ -1,4 +1,4 @@
-## its published navigation names both pages (32 requests)
+## its published navigation names both pages (37 requests)
GET /EntityDefinitions(LogicalName='webresource')?$select=EntitySetName
GET /webresourceset?$select=content&$filter=name eq 'contoso_probe_pagemanifest'&$top=1
GET /uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=uxagentprojectid,name,componentstate&$filter=uxagentprojectid eq 11111111-1111-4111-8111-111111111111 or uxagentprojectid eq 22222222-2222-4222-8222-222222222222
@@ -10,9 +10,14 @@ GET /EntityDefinitions(LogicalName='sitemap')?$select=EntitySetName
GET /sitemaps?$select=sitemapxml&$filter=sitemapid eq 55555555-5555-4555-8555-555555555555&$top=1
GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,name,appmoduleidunique&$filter=uniquename eq 'contoso_probe'&$top=1
GET /appmodules(33333333-3333-4333-8333-333333333333)?$select=appmoduleid,name,uniquename,description,aiappdescription
-GET /sitemaps?$select=sitemapid&$filter=sitemapnameunique eq 'contoso_probe'&$top=1
+GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq 33333333-3333-4333-8333-333333333333
+GET /appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq 44444444-4444-4444-8444-444444444444 and componenttype eq 62
GET /sitemaps(55555555-5555-4555-8555-555555555555)?$select=sitemapid
GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapnameunique,sitemapxml&$filter=sitemapid eq 55555555-5555-4555-8555-555555555555&$top=1
+GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq 33333333-3333-4333-8333-333333333333
+GET /appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq 44444444-4444-4444-8444-444444444444 and componenttype eq 62
+GET /appmodulecomponents?$select=_appmoduleidunique_value&$filter=componenttype eq 62 and objectid eq 55555555-5555-4555-8555-555555555555
+GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid&$filter=appmoduleidunique eq 44444444-4444-4444-8444-444444444444
POST /$batch [DELETE /appmodules(33333333-3333-4333-8333-333333333333), DELETE /sitemaps(55555555-5555-4555-8555-555555555555)]
GET /agentconversationmessages?$select=agentconversationmessageid,message,messagesender,createdon&$filter=_regardingobjectid_value eq 11111111-1111-4111-8111-111111111111&$orderby=createdon asc,versionnumber asc
DELETE /uxagentprojects(11111111-1111-4111-8111-111111111111)
@@ -32,7 +37,7 @@ GET /EntityDefinitions(LogicalName='solution')?$select=EntitySetName
GET /solutions?$select=solutionid,uniquename&$filter=uniquename eq 'ContosoCore'&$top=1
DELETE /solutions(88888888-8888-4888-8888-888888888888)
-## its published navigation names one page and its saved navigation, which is read for the other, names both (36 requests)
+## its published navigation names one page and its saved navigation, which is read for the other, names both (41 requests)
GET /EntityDefinitions(LogicalName='webresource')?$select=EntitySetName
GET /webresourceset?$select=content&$filter=name eq 'contoso_probe_pagemanifest'&$top=1
GET /uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=uxagentprojectid,name,componentstate&$filter=uxagentprojectid eq 11111111-1111-4111-8111-111111111111 or uxagentprojectid eq 22222222-2222-4222-8222-222222222222
@@ -48,9 +53,14 @@ GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleiduniq
GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapxml,componentstate&$filter=sitemapid eq 55555555-5555-4555-8555-555555555555
GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,name,appmoduleidunique&$filter=uniquename eq 'contoso_probe'&$top=1
GET /appmodules(33333333-3333-4333-8333-333333333333)?$select=appmoduleid,name,uniquename,description,aiappdescription
-GET /sitemaps?$select=sitemapid&$filter=sitemapnameunique eq 'contoso_probe'&$top=1
+GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq 33333333-3333-4333-8333-333333333333
+GET /appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq 44444444-4444-4444-8444-444444444444 and componenttype eq 62
GET /sitemaps(55555555-5555-4555-8555-555555555555)?$select=sitemapid
GET /sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid,sitemapnameunique,sitemapxml&$filter=sitemapid eq 55555555-5555-4555-8555-555555555555&$top=1
+GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq 33333333-3333-4333-8333-333333333333
+GET /appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq 44444444-4444-4444-8444-444444444444 and componenttype eq 62
+GET /appmodulecomponents?$select=_appmoduleidunique_value&$filter=componenttype eq 62 and objectid eq 55555555-5555-4555-8555-555555555555
+GET /appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid&$filter=appmoduleidunique eq 44444444-4444-4444-8444-444444444444
POST /$batch [DELETE /appmodules(33333333-3333-4333-8333-333333333333), DELETE /sitemaps(55555555-5555-4555-8555-555555555555)]
GET /agentconversationmessages?$select=agentconversationmessageid,message,messagesender,createdon&$filter=_regardingobjectid_value eq 11111111-1111-4111-8111-111111111111&$orderby=createdon asc,versionnumber asc
DELETE /uxagentprojects(11111111-1111-4111-8111-111111111111)
diff --git a/plugins/model-apps/scripts/tests/halt-retry-policy.test.js b/plugins/model-apps/scripts/tests/halt-retry-policy.test.js
index 2d3fe2440..70edfce0a 100644
--- a/plugins/model-apps/scripts/tests/halt-retry-policy.test.js
+++ b/plugins/model-apps/scripts/tests/halt-retry-policy.test.js
@@ -85,6 +85,9 @@ const POLICY = {
'pages-publish-failed': { kinds: ['by-failure'], via: PAGES },
'pages-dangling-navref': { kinds: ['never'], via: PAGES },
'pages-update-identity-mismatch': { kinds: ['never'], via: PAGES },
+ // A connector binding whose connection reference in the environment written to is for another connector (lib/page-binding-targets.js): raised at preflight, before anything is
+ // written, and a run again reads the same reference. Held with the doubles of a target environment, under a page name that reads as a transient error.
+ 'pages-binding-reference-conflict': { kinds: ['never'], via: 'page-bindings.test.js' },
'security-role-failed': { kinds: ['by-failure'] },
'role-grant-unresolved': { kinds: ['by-failure'] },
'role-grant-persona-overlap': { kinds: ['never'] },
@@ -222,6 +225,7 @@ const ECHOED_UNIQUE_KEY = " Sql error: Violation of UNIQUE KEY constraint 'ndx_n
// Failures a run again cannot change, as the SDK, the service and the machine report them — every one with a label that reads as transient where a label can be.
// What `enrichDefaultViews` raises when the publish of the views it saved fails: an SdkError of its own code, the publish error's message inside it, and no cause.
const wrappedPublish = (answer, table = 'contoso_order') => new SdkError('ENRICH_DEFAULT_VIEWS_PUBLISH_FAILED', `enrichDefaultViews: 2 view(s) on '${table}' were saved but the publish FAILED, so none of them is live (${answer}). Re-publish the entity to make them visible; the saves themselves are unaffected.`);
+const unconfirmedResource = (cause) => Object.assign(new Error(`Web resource '${LABEL}' has unconfirmed published content`, cause ? { cause } : undefined), { code: 'WEB_RESOURCE_UNVERIFIED' });
// What the build's engine words around an answer it read with a request of its own (lib/entity-provision.js statusError: a column's length, which table answers to a name, the update of a
// column by its ids): the answer's OData `error` rides on the failure (`answered`), and the rule reads its code as it reads the code the SDK's ConnectionError keeps.
const engineAnswer = (status, message, code) => serviceFailure(`the update of the column was refused (HTTP ${status}: ${message})`, { status, words: `HTTP ${status}: ${message}`, answered: { ...(code ? { code } : {}), message } });
@@ -229,6 +233,7 @@ const REFUSALS = [
['a refusal in the SDK\'s words', () => new Error('same-name role is managed and cannot be adopted')],
['a typed validation error that quotes the label', () => Object.assign(new Error(`View '${LABEL}' is invalid`), { code: 'VALIDATION_ERROR' })],
['a 403 from the service whose url carries the label', () => connectionError(403, 'permission denied')],
+ ['an unconfirmed web resource whose non-enumerable cause refuses publication (403)', () => unconfirmedResource(connectionError(403, 'permission denied'))],
['a local file error that quotes the path', () => Object.assign(new Error(`EACCES: permission denied, open '/work/${LABEL}/page.json'`), { code: 'EACCES', syscall: 'open' })],
['an SDK error that wraps a publish the service refused (a 403), on a table called like a timeout', () => wrappedPublish(`HTTP 403 from ${ENV}/api/data/v9.2/PublishXml: permission denied`, 'contoso_sql_timeout')],
// A logical name has no space, but it can be a word of the rule: `CustomizationLockException` is one word, and `contoso_customizationlockexception` is a valid name.
@@ -254,6 +259,8 @@ const GENUINE = [
['a 503', () => connectionError(503, 'The service is unavailable.')],
['a 429', () => connectionError(429, 'Too many requests.')],
['a reset of the connection', () => connectionError(0, 'Request failed: read ECONNRESET')],
+ ['an unconfirmed web resource whose non-enumerable cause is a refused publish (429)', () => unconfirmedResource(connectionError(429, 'another customization is running'))],
+ ['an unconfirmed web resource whose published read-back differs, with no cause', () => unconfirmedResource()],
['an SDK error that wraps a publish the service could not take (a 503)', () => wrappedPublish(`HTTP 503 from ${ENV}/api/data/v9.2/PublishXml: Service Unavailable`)],
['an SDK error that wraps a publish the service throttled (a 429), on a table whose logical name holds a word of the retry rule', () => wrappedPublish(`HTTP 429 from ${ENV}/api/data/v9.2/PublishXml: Too many requests.`, 'contoso_customizationlockexception')],
['an SDK error that wraps a publish the service refused for a customization lock, which is a throttle (a 429), in its words', () => wrappedPublish(`HTTP 429 from ${ENV}/api/data/v9.2/PublishXml: CustomizationLockException: another solution install is running`)],
diff --git a/plugins/model-apps/scripts/tests/helpers/app-sitemap-link-rows.js b/plugins/model-apps/scripts/tests/helpers/app-sitemap-link-rows.js
new file mode 100644
index 000000000..5f07f8707
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/app-sitemap-link-rows.js
@@ -0,0 +1,41 @@
+'use strict';
+
+// The SDK proves a sitemap with a CURRENT app layer, its type-62 component and reverse owners:
+// appmodules/RetrieveUnpublishedMultiple()?$select=appmoduleid,appmoduleidunique,componentstate&$filter=appmoduleid eq <id>
+// appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq <layer> and componenttype eq 62
+// appmodulecomponents?$select=_appmoduleidunique_value&$filter=componenttype eq 62 and objectid eq <sitemap>
+// These small transport fixtures must filter real rows in both directions, not answer every component
+// query with the owned sitemap. Other queries remain their caller's responsibility.
+// https://learn.microsoft.com/en-us/power-apps/developer/data-platform/reference/entities/appmodulecomponent
+function appSitemapLinkRows(url, { apps, components }) {
+ const u = new URL(url);
+ const route = u.pathname.replace(/^\/api\/data\/v\d+\.\d+/, '');
+ const select = (u.searchParams.get('$select') || '').split(',').filter(Boolean);
+ const filter = u.searchParams.get('$filter') || '';
+ let rows;
+ let fields;
+ if (route === '/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()'
+ && ((select.length === 3 && ['appmoduleid', 'appmoduleidunique', 'componentstate'].every((field) => select.includes(field)))
+ || /\bappmoduleidunique eq /i.test(filter))) {
+ rows = apps;
+ fields = new Set(['appmoduleid', 'appmoduleidunique', 'componentstate']);
+ } else if (route === '/appmodulecomponents' && /\bcomponenttype eq 62\b/i.test(filter)) {
+ rows = components;
+ fields = new Set(['objectid', 'componenttype', '_appmoduleidunique_value']);
+ } else {
+ return undefined;
+ }
+ if (!select.length || select.some((field) => !fields.has(field))) {
+ throw new Error(`Unmodeled sitemap-link projection: ${url}`);
+ }
+ const predicates = filter.split(/\s+and\s+/i).map((part) => {
+ const match = /^(\w+) eq ([0-9a-f-]{36}|62)$/i.exec(part);
+ if (!match || !fields.has(match[1])) throw new Error(`Unmodeled sitemap-link filter: ${url}`);
+ return [match[1], match[2].toLowerCase()];
+ });
+ return rows
+ .filter((row) => predicates.every(([field, value]) => String(row[field]).toLowerCase() === value))
+ .map((row) => Object.fromEntries(select.map((field) => [field, row[field] === undefined ? null : row[field]])));
+}
+
+module.exports = { appSitemapLinkRows };
diff --git a/plugins/model-apps/scripts/tests/helpers/fake-app-build-org.js b/plugins/model-apps/scripts/tests/helpers/fake-app-build-org.js
index 0731694d8..7e93c607b 100644
--- a/plugins/model-apps/scripts/tests/helpers/fake-app-build-org.js
+++ b/plugins/model-apps/scripts/tests/helpers/fake-app-build-org.js
@@ -26,6 +26,7 @@
const assert = require('node:assert/strict');
const { randomUUID } = require('node:crypto');
const { createFakeDataverse } = require('./fake-dataverse.js');
+const { appSitemapLinkRows } = require('./app-sitemap-link-rows.js');
const ORIGIN = 'https://contoso.crm.dynamics.com';
const LAYER_ID = '11111111-0000-4000-8000-000000000002';
@@ -63,6 +64,13 @@ function createFakeBuildOrg({ entities, solution = { uniqueName: 'ContosoReview'
calls.push(recorded);
const overridden = overrides.find((o) => o.match(recorded));
if (overridden) return overridden.answer(recorded);
+ if (method === 'GET') {
+ const linked = appSitemapLinkRows(url, {
+ apps: app ? [{ ...app, appmoduleidunique: LAYER_ID }] : [],
+ components: components.map((c) => ({ ...c, _appmoduleidunique_value: LAYER_ID })),
+ });
+ if (linked !== undefined) return rows(linked);
+ }
if (method === 'POST' && p === '/PublishXml') {
if (refusal && /<entities>/.test(body.ParameterXml)) {
const status = refusal;
@@ -73,6 +81,10 @@ function createFakeBuildOrg({ entities, solution = { uniqueName: 'ContosoReview'
app.componentstate = 0;
appVersion += 1;
}
+ for (const [, id] of String(body.ParameterXml).matchAll(/<webresource>([^<]+)<\/webresource>/g)) {
+ const row = resources.get(id.toLowerCase());
+ if (row) row.publishedContent = row.content;
+ }
return fake.httpClient.post(url, body, options);
}
if (method === 'GET' && /^\/appmodulecomponents/.test(p)) {
@@ -93,19 +105,40 @@ function createFakeBuildOrg({ entities, solution = { uniqueName: 'ContosoReview'
// POST /webresourceset { name, content, … } -> 204, OData-EntityId: <API>/webresourceset(<id>)
// PATCH /webresourceset(<id>) { content } -> 204
// GET /webresourceset?$select=webresourceid,content&$filter=name eq '<name>'&$top=1
+ // GET /webresourceset(<id>)?$select=content (the SDK's read-back of what it published)
+ // A web resource has two layers, as the platform holds it: a POST or PATCH writes the SAVED content (`content`), a PublishXml that
+ // names the row (`<webresources><webresource><id></webresource></webresources>`) copies it to the PUBLISHED layer (`publishedContent`),
+ // and every plain read — by name or by id — answers the published content. A row no publish has named is in no plain read, as for the
+ // views, forms and charts above (assumed: the plain read of a never-published web resource is not measured; the SDK's create publishes).
let m;
+ const publishedRow = ({ publishedContent, ...row }) => ({ ...row, content: publishedContent });
if (method === 'POST' && /^\/webresourceset(\?|$)/.test(p)) {
- const id = body.webresourceid || randomUUID();
+ // A name is unique in an environment: a second create of one is refused, whatever layer the first is in (the SDK says so of its own create; the
+ // platform's exact code for it is not measured).
+ if ([...resources.values()].some((row) => String(row.name).toLowerCase() === String(body.name).toLowerCase())) {
+ return { status: 400, headers: {}, body: { error: { code: '0x80040237', message: `A web resource named ${body.name} already exists.` } } };
+ }
+ const id = (body.webresourceid || randomUUID()).toLowerCase();
resources.set(id, { ...body, webresourceid: id });
return { status: 204, headers: { 'odata-entityid': `${ORIGIN}/api/data/v9.0/webresourceset(${id})` }, body: null };
}
- if (method === 'PATCH' && (m = /^\/webresourceset\(([0-9a-f-]{36})\)/i.exec(p)) && resources.has(m[1])) {
- Object.assign(resources.get(m[1]), body);
+ if (method === 'PATCH' && (m = /^\/webresourceset\(([0-9a-f-]{36})\)/i.exec(p))) {
+ // A write by an id no row has any more is refused as the platform refuses it.
+ if (!resources.has(m[1].toLowerCase())) return { status: 404, headers: {}, body: { error: { code: '0x80040217', message: `webresource With Id = ${m[1]} Does Not Exist` } } };
+ Object.assign(resources.get(m[1].toLowerCase()), body);
return { status: 204, headers: {}, body: null };
}
+ if (method === 'GET' && (m = /^\/webresourceset\(([0-9a-f-]{36})\)\?\$select=content$/i.exec(p))) {
+ const row = resources.get(m[1].toLowerCase());
+ return row && row.publishedContent !== undefined ? response({ webresourceid: row.webresourceid, content: row.publishedContent }) : { status: 404, headers: {}, body: { error: { message: 'Does Not Exist' } } };
+ }
+ if (method === 'GET' && (m = /^\/webresourceset\(([0-9a-f-]{36})\)\?\$select=name,displayname,webresourcetype,content,description$/i.exec(p))) {
+ const row = resources.get(m[1].toLowerCase());
+ return row && row.publishedContent !== undefined ? response(publishedRow(row)) : { status: 404, headers: {}, body: { error: { message: 'Does Not Exist' } } };
+ }
if (method === 'GET' && /^\/webresources(et)?\?/.test(p)) {
const named = /name eq '([^']+)'/.exec(p);
- const stored = named ? [...resources.values()].filter((row) => row.name === named[1]) : [];
+ const stored = named ? [...resources.values()].filter((row) => row.name === named[1] && row.publishedContent !== undefined).map(publishedRow) : [];
return rows(stored.length ? stored : p.includes('_icon') ? [{ webresourceid: ICON_ID }] : []);
}
// The environment's generative pages, plain or in the saved layer: every page of the list, whatever the filter asks (a test that needs a narrower answer intercepts).
diff --git a/plugins/model-apps/scripts/tests/helpers/fake-custom-api-preload.js b/plugins/model-apps/scripts/tests/helpers/fake-custom-api-preload.js
new file mode 100644
index 000000000..2cda70dae
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/helpers/fake-custom-api-preload.js
@@ -0,0 +1,91 @@
+'use strict';
+
+// Runs the discovery CLI over the real Dataverse request code without acquiring a real token or
+// reaching a service. The fake honors $select/$expand and the bounded table/privacy filters; it
+// deliberately does not remove unsupported request/response types, which discovery must reject.
+const fs = require('node:fs');
+const path = require('node:path');
+const assert = require('node:assert/strict');
+const auth = require(path.join(__dirname, '..', '..', 'lib', 'dataverse-auth.js'));
+const realRequest = auth.dataverseRequest;
+const fixture = JSON.parse(fs.readFileSync(process.env.FAKE_CUSTOM_API_FIXTURE, 'utf8'));
+const requests = [];
+const API_FIELDS = new Set([
+ 'customapiid', 'uniquename', 'name', 'displayname', 'isfunction',
+ 'bindingtype', 'boundentitylogicalname', 'isprivate',
+]);
+const NAV_FIELDS = {
+ CustomAPIRequestParameters: new Set(['uniquename', 'type', 'isoptional', 'logicalentityname']),
+ CustomAPIResponseProperties: new Set(['type']),
+};
+
+process.on('exit', () => {
+ fs.writeFileSync(process.env.FAKE_CUSTOM_API_LOG, JSON.stringify(requests));
+});
+
+function project(row, fields) {
+ return Object.fromEntries(fields.filter((field) => Object.hasOwn(row, field)).map((field) => [field, row[field]]));
+}
+
+function selectedFields(raw, allowed) {
+ assert.equal(typeof raw, 'string', 'the metadata query must declare its selected fields');
+ const fields = raw.split(',');
+ assert.ok(fields.length > 0 && fields.every((field) => allowed.has(field)), `unexpected selected fields: ${raw}`);
+ return fields;
+}
+
+function answer(request) {
+ requests.push({ method: request.method, url: request.url, body: request.body });
+ assert.equal(requests.length, 1, 'discovery must use one inline metadata read');
+ assert.equal(request.method, 'GET');
+ assert.equal(request.body, null);
+ const url = new URL(request.url);
+ assert.equal(url.origin, 'https://contoso.crm.dynamics.com');
+ assert.equal(url.pathname, '/api/data/v9.2/customapis');
+ if (fixture.refuse) {
+ return { statusCode: fixture.refuse.status, body: JSON.stringify({ error: { message: fixture.refuse.message } }) };
+ }
+
+ const select = selectedFields(url.searchParams.get('$select'), API_FIELDS);
+ const filter = url.searchParams.get('$filter') || '';
+ assert.match(filter, /bindingtype eq 0/);
+ // OData string literals double embedded quotes, e.g. boundentitylogicalname eq 'o''brien'.
+ const entities = [...filter.matchAll(/boundentitylogicalname eq '((?:''|[^'])*)'/g)]
+ .map((match) => match[1].replace(/''/g, "'"));
+ const expansion = url.searchParams.get('$expand') || '';
+ const expanded = [...expansion.matchAll(/(?:^|,)(\w+)\(\$select=([a-z,]+)\)/g)];
+ assert.equal(expanded.map((match) => match[0]).join(''), expansion, 'unexpected metadata expansion syntax');
+ const navigations = expanded.map(([, navigation, fields]) => {
+ assert.ok(Object.hasOwn(NAV_FIELDS, navigation), `unexpected navigation: ${navigation}`);
+ return [navigation, selectedFields(fields, NAV_FIELDS[navigation])];
+ });
+ if (Object.hasOwn(fixture, 'responseBody')) {
+ return { statusCode: 200, body: JSON.stringify(fixture.responseBody) };
+ }
+ const rows = (fixture.apis || [])
+ .filter((row) => Number(row.bindingtype) === 0 || entities.includes(row.boundentitylogicalname))
+ .filter((row) => !/\bisprivate eq false\b/.test(filter) || row.isprivate === false)
+ .map((row) => {
+ const projected = project(row, select);
+ for (const [navigation, fields] of navigations) {
+ projected[navigation] = (row[navigation] || []).map((parameter) => project(parameter, fields));
+ // Dataverse emits ordinary related-collection links for complete single-level expansions,
+ // including empty ones. Successful fixtures must exercise that service shape by default.
+ projected[`${navigation}@odata.nextLink`] =
+ `${url.origin}${url.pathname}(${row.customapiid})/${navigation}?$select=${fields.join(',')}`;
+ }
+ if (fixture.unreadable) {
+ const { navigation, missing, value } = fixture.unreadable;
+ if (missing) delete projected[navigation];
+ else projected[navigation] = value;
+ }
+ return projected;
+ });
+ return { statusCode: 200, body: JSON.stringify({ value: rows }) };
+}
+
+auth.dataverseRequest = (envUrl, method, apiPath, body, options = {}) => realRequest(envUrl, method, apiPath, body, {
+ ...options,
+ getToken: () => 'test-token',
+ request: async (request) => answer(request),
+});
diff --git a/plugins/model-apps/scripts/tests/helpers/fake-genpage.js b/plugins/model-apps/scripts/tests/helpers/fake-genpage.js
index 885601d4d..dac310176 100644
--- a/plugins/model-apps/scripts/tests/helpers/fake-genpage.js
+++ b/plugins/model-apps/scripts/tests/helpers/fake-genpage.js
@@ -115,6 +115,8 @@ function fakeGenpage(options = {}) {
if (args.name) page.name = args.name;
if (args.dataSources !== undefined) page.dataSources = Array.isArray(args.dataSources) ? args.dataSources : String(args.dataSources).split(',');
if (args.model) page.model = args.model;
+ // As the backend does: a binding list that is left out (undefined) is the page's own, one that is given — `[]` too — replaces it.
+ for (const key of ['connectorBindings', 'actionBindings']) if (args[key] !== undefined) page[key] = args[key];
return { pageId: String(id).toLowerCase(), ...(unchanged ? { unchanged: true } : {}), publish: { kind: 'verified', detail: '' }, warnings: [], ...extra };
},
diff --git a/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-metadata.js b/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-metadata.js
index 2bb214cde..62a0ffbac 100644
--- a/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-metadata.js
+++ b/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-metadata.js
@@ -26,6 +26,9 @@
// whatever the create sent — MEASURED: a create sending `false` read back `true` — and a later one does not, `true` sent or not
// (Microsoft Learn: "ignored if set to true when creating a new image column" while another exists). Deleting the primary one
// makes the next the primary (Learn: "another image column for the table is selected automatically");
+// - a File or an Image column gets a relationship of the platform's own to a stock table (MEASURED on a live environment, from the
+// table's ManyToOneRelationships): `FileAttachment_<table>_<file>`, fileattachment -> <table>.<file>, CUSTOM; and
+// `ImageDescriptor_<table>_<image>`, imagedescriptor -> <table>.<image>id, not custom. It goes with the column (mediaRelationshipOf);
// - a 1:N relationship creates its lookup column on the referencing table; an N:N its intersect table.
// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/create-update-entity-definitions-using-web-api
// See: https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/create-update-entity-relationships-using-web-api
@@ -324,6 +327,34 @@ function createMetadataStore({ baseLanguage = 1033, userLanguage = baseLanguage,
const isImage = (attribute) => classOf(attribute) === 'ImageAttributeMetadata';
+ // The relationship the platform makes WITH a File or an Image column (see the header), as a table's ManyToOneRelationships answers it
+ // (MEASURED, abridged):
+ // { "SchemaName": "FileAttachment_<table>_<file>", "ReferencedEntity": "fileattachment", "ReferencedAttribute": "fileattachmentid",
+ // "ReferencingEntity": "<table>", "ReferencingAttribute": "<file>", "IsCustomRelationship": true }
+ // { "SchemaName": "ImageDescriptor_<table>_<image>", "ReferencedEntity": "imagedescriptor", "ReferencedAttribute": "imagedescriptorid",
+ // "ReferencingEntity": "<table>", "ReferencingAttribute": "<image>id", "IsCustomRelationship": false }
+ // Null for a column of any other type.
+ function mediaRelationshipOf(table, attribute) {
+ const cls = classOf(attribute);
+ const kind = cls === 'FileAttributeMetadata' ? { prefix: 'FileAttachment', parent: 'fileattachment', column: attribute.LogicalName, custom: true }
+ : cls === 'ImageAttributeMetadata' ? { prefix: 'ImageDescriptor', parent: 'imagedescriptor', column: `${attribute.LogicalName}id`, custom: false }
+ : null;
+ if (!kind) return null;
+ return {
+ '@odata.type': '#Microsoft.Dynamics.CRM.OneToManyRelationshipMetadata',
+ MetadataId: randomUUID(),
+ SchemaName: `${kind.prefix}_${table.LogicalName}_${attribute.LogicalName}`,
+ RelationshipType: 'OneToManyRelationship',
+ IsCustomRelationship: kind.custom,
+ IsManaged: false,
+ IsValidForAdvancedFind: false,
+ ReferencedEntity: kind.parent,
+ ReferencingEntity: table.LogicalName,
+ ReferencedAttribute: `${kind.parent}id`,
+ ReferencingAttribute: kind.column,
+ };
+ }
+
function addAttribute(table, attribute) {
// The platform's choice of a table's primary image (see the header): the first Image column it gets, whatever was sent.
if (isImage(attribute)) {
@@ -333,6 +364,8 @@ function createMetadataStore({ baseLanguage = 1033, userLanguage = baseLanguage,
}
table.Attributes.set(attribute.LogicalName, attribute);
for (const companion of companionsOf(attribute)) if (!table.Attributes.has(companion.LogicalName)) table.Attributes.set(companion.LogicalName, companion);
+ const media = mediaRelationshipOf(table, attribute);
+ if (media && !relationships.has(lc(media.SchemaName))) relationships.set(lc(media.SchemaName), media);
return attribute;
}
@@ -757,6 +790,9 @@ function createMetadataStore({ baseLanguage = 1033, userLanguage = baseLanguage,
function deleteColumn(table, attribute) {
table.Attributes.delete(attribute.LogicalName);
for (const [name, other] of [...table.Attributes]) if (other.AttributeOf === attribute.LogicalName) table.Attributes.delete(name);
+ // A File or an Image column's relationship of the platform's own goes with it (mediaRelationshipOf).
+ const media = mediaRelationshipOf(table, attribute);
+ if (media) relationships.delete(lc(media.SchemaName));
// The base-currency twin has no AttributeOf to follow (see companionsOf): it goes by its name, as the platform deletes it.
const twin = table.Attributes.get(`${attribute.LogicalName}_base`);
if (classOf(attribute) === 'MoneyAttributeMetadata' && attribute.IsBaseCurrency !== true && twin && twin.IsBaseCurrency === true) table.Attributes.delete(twin.LogicalName);
diff --git a/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-org.js b/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-org.js
index 66a20551b..d617289b4 100644
--- a/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-org.js
+++ b/plugins/model-apps/scripts/tests/helpers/fake-lifecycle-org.js
@@ -678,6 +678,14 @@ function createLifecycleOrg(options = {}) {
for (const p of table.Privileges || []) insertRow('privileges', { privilegeid: p.PrivilegeId, name: p.Name, accessright: p.PrivilegeType, canbebasic: p.CanBeBasic, canbelocal: p.CanBeLocal, canbedeep: p.CanBeDeep, canbeglobal: p.CanBeGlobal });
}
for (const [logical, info] of Object.entries(SYSTEM_TABLES)) seedSystemTable(logical, info);
+ // The two stock tables the platform relates every File and Image column to (fake-lifecycle-metadata.js mediaRelationshipOf), as
+ // definitions only: nothing reads or writes their rows. MEASURED: `fileattachment` reads back `IsCustomEntity: false`.
+ for (const [logical, otc] of [['fileattachment', 55], ['imagedescriptor', 1007]]) {
+ const table = metadata.makeTable({ SchemaName: logical, EntitySetName: `${logical}s`, ObjectTypeCode: otc, OwnershipType: 'OrganizationOwned', DisplayName: logical, DisplayCollectionName: logical, Attributes: [] }, { custom: false });
+ table.PrimaryIdAttribute = `${logical}id`;
+ for (const a of table.Attributes.values()) a.IsCustomAttribute = false;
+ metadata.tables.set(logical, table);
+ }
insertRow('organizations', { organizationid: IDS.organization, name: 'Contoso', languagecode: baseLanguage });
insertRow('businessunits', { businessunitid: IDS.businessUnit, name: 'contoso', _parentbusinessunitid_value: null });
insertRow('systemusers', { systemuserid: IDS.user, fullname: 'Maker', domainname: '[email protected]', _businessunitid_value: IDS.businessUnit });
@@ -934,7 +942,7 @@ function createLifecycleOrg(options = {}) {
const options = attribute.OptionSet.Options;
const value = body.Value !== undefined && body.Value !== null ? Number(body.Value) : Math.max(100000000 - 1, ...options.map((o) => o.Value)) + 1;
if (options.some((o) => o.Value === value)) return failure(400, '0x80047007', `An option with the value ${value} already exists.`);
- options.push({ Value: value, Label: metadata.label(body.Label), Description: metadata.label(null), Color: null, IsManaged: false, ExternalValue: null, ...(p === '/InsertStatusValue' ? { State: Number(body.StateCode) } : {}) });
+ options.push({ Value: value, Label: metadata.label(body.Label), Description: metadata.label(null), Color: body.Color === undefined ? null : body.Color, IsManaged: false, ExternalValue: null, ...(p === '/InsertStatusValue' ? { State: Number(body.StateCode) } : {}) });
return json(200, { NewOptionValue: value });
}
// SaveSettingValue { SettingName, Value, AppUniqueName?, SolutionUniqueName? }: an app-scoped value is the `appsettings` row of that
diff --git a/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.js b/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.js
index c32ef222f..e5871fef2 100644
--- a/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.js
+++ b/plugins/model-apps/scripts/tests/helpers/lifecycle-harness.js
@@ -146,9 +146,9 @@ function createLifecycleHarness(org, root) {
// build-model-app.js: the two SDK instances its makeSdk makes — one that names the solution, and the header-less one that owns the app
// folder's workspace and recovers a form create whose answer was lost — and the deps its main() hands buildModelApp.
- async function build(spec, { apply = true, publish = true, sampleData = true, verify = true, appFolder = appDir, workspace = workspaceDir } = {}) {
- const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(throwaway('sdk-')), instanceUrl: org.origin, httpClient: client, solutionUniqueName: spec.solution.uniqueName, languageCode: 1033 });
- const provisionSdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(apply ? workspace : throwaway('preview-')), instanceUrl: org.origin, httpClient: client, languageCode: 1033, createRecovery: 'adoptExact' });
+ async function build(spec, { apply = true, publish = true, sampleData = true, verify = true, appFolder = appDir, workspace = workspaceDir, languageCode = 1033 } = {}) {
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(throwaway('sdk-')), instanceUrl: org.origin, httpClient: client, solutionUniqueName: spec.solution.uniqueName, languageCode });
+ const provisionSdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(apply ? workspace : throwaway('preview-')), instanceUrl: org.origin, httpClient: client, languageCode, createRecovery: 'adoptExact' });
await provisionSdk.initWorkspace();
const genpage = makeGenpageSdk(org.origin, { httpClient: client });
const warnings = [];
@@ -156,9 +156,9 @@ function createLifecycleHarness(org, root) {
try {
const result = await buildModelApp(spec, {
apply, publish, sampleData, verify, phases: PHASES, profile: apply ? 'deploy' : 'plan', nonInteractive: false,
- appDir: appFolder, env: org.origin, workspaceDir: workspace, preResolvedLanguageCode: apply ? 1033 : undefined,
+ appDir: appFolder, env: org.origin, workspaceDir: workspace, preResolvedLanguageCode: apply ? languageCode : undefined,
}, {
- sdk, provisionSdk, genpage, sleep: async () => {}, warn: (m) => warnings.push(String(m)), log: (m) => log.push(String(m)), provisionedLanguages: async () => [1033],
+ sdk, provisionSdk, genpage, sleep: async () => {}, warn: (m) => warnings.push(String(m)), log: (m) => log.push(String(m)), provisionedLanguages: async () => org.pageServer.languages.provisioned,
verify: async (s, o) => verifySpec(s, readerFor(provisionSdk, appUniqueName(s), { genpage, workspaceDir: workspace }), o),
});
return { result, warnings, log };
@@ -168,7 +168,7 @@ function createLifecycleHarness(org, root) {
}
// download-model-app.js main(), with the seams it gives: the result printer, the process exit, the auth probe, the HTTP client.
- async function downloadApp(appUnique, outDir) {
+ async function downloadApp(appUnique, outDir, { languageCode } = {}) {
let emitted;
const stderr = [];
// runDownload writes its WARNING lines to process.stderr itself (main's `stderr` seam carries the rest): both are what the maker reads.
@@ -176,7 +176,7 @@ function createLifecycleHarness(org, root) {
process.stderr.write = (text) => { stderr.push(String(text)); return true; };
try {
await download.main({
- argv: ['--env', org.origin, '--app', appUnique, '--out', outDir],
+ argv: ['--env', org.origin, '--app', appUnique, '--out', outDir, ...(languageCode ? ['--language-code', String(languageCode)] : [])],
stderr: { write: (text) => { stderr.push(String(text)); return true; } },
exit: (code) => { throw new Error(`download exited ${code}: ${stderr.join('')}`); },
emitResult: (ok, payload) => { emitted = { ok, payload }; },
diff --git a/plugins/model-apps/scripts/tests/helpers/navigation-shapes.js b/plugins/model-apps/scripts/tests/helpers/navigation-shapes.js
index 58a0f08d3..0627571dc 100644
--- a/plugins/model-apps/scripts/tests/helpers/navigation-shapes.js
+++ b/plugins/model-apps/scripts/tests/helpers/navigation-shapes.js
@@ -1,8 +1,9 @@
'use strict';
// The navigation shapes the tests of the navigation check share (app-navigation.test.js and
// app-navigation-build.test.js). `forNew`, `forExisting` and `forUnknown` say what the check must answer for an app
-// that does not exist, one that does, and one whose existence could not be read. They are written out from the
-// rule (lib/app-navigation.js), never computed with the code under test.
+// that does not exist, one that does, and one whose existence could not be read, in a run that does NOT create a new
+// app's pages first; `forNewPagesFirst` and `forUnknownPagesFirst` what it must answer in a run that does (below). They
+// are written out from the rule (lib/app-navigation.js), never computed with the code under test.
//
// refuse the build stops before it writes anything
// ok the build goes on
@@ -18,10 +19,14 @@ const page = (key) => ({ page: key, title: key });
const oneGroup = (...subAreas) => ({ areas: [{ label: 'Main', groups: [{ label: 'Records', subAreas }] }] });
// Dataverse refuses to CREATE a sitemap with no entry and accepts one on an UPDATE (measured), so an app that exists is not refused.
-const NOTHING = { kind: 'empty', forNew: 'refuse', forExisting: 'warn', forUnknown: 'unknown' };
-const UNDECLARED = { kind: 'undeclared', forNew: 'refuse', forExisting: 'refuse', forUnknown: 'refuse' };
-const ONLY_PAGES = { kind: 'pages-only', forNew: 'refuse', forExisting: 'ok', forUnknown: 'unknown' };
-const FINE = { forNew: 'ok', forExisting: 'ok', forUnknown: 'ok' };
+// `forNewPagesFirst` and `forUnknownPagesFirst` are the answers of a run that creates a NEW app's pages before the app (sdk-build.js
+// pagesFirstRule: the app step and the pages phase, not a changed-only re-upload, every page entry naming a page the run builds) —
+// the whole build `--apply` runs. It creates such an app with its pages already in its first navigation, so only a navigation of
+// pages only is answered differently; `forNew` and `forUnknown` are the answers of any other run.
+const NOTHING = { kind: 'empty', forNew: 'refuse', forExisting: 'warn', forUnknown: 'unknown', forNewPagesFirst: 'refuse', forUnknownPagesFirst: 'unknown' };
+const UNDECLARED = { kind: 'undeclared', forNew: 'refuse', forExisting: 'refuse', forUnknown: 'refuse', forNewPagesFirst: 'refuse', forUnknownPagesFirst: 'refuse' };
+const ONLY_PAGES = { kind: 'pages-only', forNew: 'refuse', forExisting: 'ok', forUnknown: 'unknown', forNewPagesFirst: 'ok', forUnknownPagesFirst: 'ok' };
+const FINE = { forNew: 'ok', forExisting: 'ok', forUnknown: 'ok', forNewPagesFirst: 'ok', forUnknownPagesFirst: 'ok' };
const SHAPES = [
{ name: 'a spec with no appShell', ...UNDECLARED, appShell: undefined, said: 'the spec has no appShell.areas' },
diff --git a/plugins/model-apps/scripts/tests/hydrate-spec.test.js b/plugins/model-apps/scripts/tests/hydrate-spec.test.js
index 71e198999..cf07ab1b5 100644
--- a/plugins/model-apps/scripts/tests/hydrate-spec.test.js
+++ b/plugins/model-apps/scripts/tests/hydrate-spec.test.js
@@ -65,6 +65,28 @@ test('hydrateSpec reconstructs a valid, complete spec (entities + appShell + pag
assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
});
+// A download writes no form (hydrate-spec.js says why `forms` stays empty), so it cannot write a
+// `fieldOptions` key the spec gate refuses. The forms of a downloaded spec are the author's: one that
+// uses every per-field option must pass the build's gate after the file round trip, and a misspelled
+// option must not.
+test('a downloaded spec writes no field option, and a form the author adds with every option still passes the build gate', async () => {
+ const spec = JSON.parse(JSON.stringify(await hydrateSpec(deployedRead())));
+ assert.deepStrictEqual(spec.forms, [], 'a download writes no form, so no fieldOptions');
+ spec.entities[0].columns.push({ schemaName: 'new_due', displayName: 'Due', type: 'DateTime' });
+ spec.forms.push({ entity: 'new_order', name: 'Order', fieldOptions: {
+ new_name: { readOnly: true },
+ new_status: { hidden: true, colspan: 2, rowspan: 1 },
+ new_due: { after: 'new_name' },
+ } });
+ const r = validateAppSpec(spec);
+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
+
+ spec.forms[0].fieldOptions.new_due = { aftr: 'new_name' };
+ assert.deepStrictEqual(validateAppSpec(spec).errors, [
+ "form 'Order' (table new_order): unknown key 'aftr' on fieldOptions['new_due'] — did you mean 'after'? (allowed: readOnly, hidden, after, colspan, rowspan)",
+ ]);
+});
+
test('hydrateSpec unwraps Dataverse Label descriptions and omits absent descriptions', async () => {
const spec = await hydrateSpec({
app: async () => ({ name: 'A', description: null, siteMap: { areas: [] } }),
diff --git a/plugins/model-apps/scripts/tests/lifecycle-matrix-real-bundle.test.js b/plugins/model-apps/scripts/tests/lifecycle-matrix-real-bundle.test.js
index fcd0a045c..6f2f4cb08 100644
--- a/plugins/model-apps/scripts/tests/lifecycle-matrix-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/lifecycle-matrix-real-bundle.test.js
@@ -156,9 +156,8 @@ const BUILD_PUBLISHES = [
// The rebuild of the UNCHANGED spec. It is not free: each line is a write the current build still sends when nothing changed, and
// what it depends on. A line that disappears is progress (lower it here); a line that appears is a regression.
const REBUILD_WRITES = {
- 'POST InsertStatusValue': 1, // re-sent at its pinned value; the platform's "already exists" is the skip (entity-provision.js)
- 'POST EntityDefinitions/Keys': 1, // the SDK has no key lister: re-sent, "already exists" is the skip (entity-provision.js)
- 'PUT EntityDefinitions': 2, // the quick-create flag and the table icon are re-asserted on every build (entity-provision.js, sdk-build.js 3c)
+ // Status values and key identities are proved equal before insert; icon publication still needs its own assignment/publish pair.
+ 'PUT EntityDefinitions': 2, // the quick-create flag and the table-icon assignment
'PATCH savedqueries': 4, // the SDK's default-view enrichment saves both generated views of each table on every build (rebuild-writes-real-bundle.test.js)
'PATCH systemforms': 3, // isdefault is set again on each table's chosen Main form (promoteDefaultForm reads nothing first), and the form's security roles are rewritten byte for byte
'PATCH sitemaps': 1, // the sitemap of an existing app is rewritten by the pages finalize, byte for byte
@@ -170,7 +169,7 @@ const REBUILD_WRITES = {
'POST PublishXml': 4, // see REBUILD_PUBLISHES
};
const REBUILD_PUBLISHES = [
- 'contoso_project', // the table icon set again
+ 'contoso_project', // the table-icon assignment; a saved name cannot prove its previous publish completed
'contoso_project contoso_tag contoso_task', // the tables before the app's publish
'app', // the app after the sitemap finalize
'contoso_project contoso_task app', // the publish phase
@@ -200,16 +199,16 @@ const TEARDOWN_WRITES = {
// Reads per phase: a ceiling about a tenth above what each phase reads today, so a read that starts being made once per row fails
// here. HTTP requests (reads, writes and change sets) likewise.
const BUDGET = {
- build: { reads: 335, requests: 430 }, // today 302 / 392
- rebuild: { reads: 295, requests: 320 }, // today 268 / 289
- download: { reads: 130, requests: 130 }, // today 117 / 117 (the File and the Image column's sizes are one read each, of the one table that has them)
- verify: { reads: 85, requests: 85 }, // today 74 / 74
- teardown: { reads: 95, requests: 135 }, // today 86 / 122
+ build: { reads: 335, requests: 430 }, // current app/component identities and published-resource readbacks
+ rebuild: { reads: 318, requests: 343 }, // status/key/icon equality proofs and current component identities
+ download: { reads: 143, requests: 143 }, // conditional type casts, status options, owned SVGs and current component identities
+ verify: { reads: 85, requests: 85 }, // declared status reasons and keys add one conditional read each
+ teardown: { reads: 95, requests: 135 }, // current component identities and reverse-owner proofs
};
// What verify checks, by kind: a kind that stops being checked (or is checked fewer times) fails here even though verify still passes.
const VERIFY_CHECKS = {
- entity: 3, column: 18, relationship: 3,
+ entity: 3, column: 18, 'status-reason': 1, 'alternate-key': 1, relationship: 3,
view: 3, 'view-columns': 3, 'view-filters': 3, 'view-sort': 1, chart: 1,
form: 4, 'form-identities': 4, 'form-default': 2, 'form-order': 1, 'form-order-served': 1, 'form-timeline': 1,
dashboard: 1, command: 1,
@@ -263,6 +262,9 @@ const BUILT = {
contoso_tag_contoso_task: { plural: 'contoso_tag_contoso_task', icon: null, quickCreate: false, intersect: true, columns: {}, keys: [], statusReasons: ['1 Active state 0', '2 Inactive state 1'] },
},
relationships: [
+ // The two the platform makes with the File and the Image column of contoso_project (fake-lifecycle-metadata.js mediaRelationshipOf).
+ 'FileAttachment_contoso_project_contoso_contract 1:N fileattachment->contoso_project.contoso_contract',
+ 'ImageDescriptor_contoso_project_contoso_logo 1:N imagedescriptor->contoso_project.contoso_logoid',
'contoso_contoso_task_account 1:N account->contoso_task.contoso_customer',
'contoso_contoso_task_contact 1:N contact->contoso_task.contoso_customer',
'contoso_project_contoso_project 1:N contoso_project->contoso_project.contoso_parentprojectid',
@@ -348,7 +350,8 @@ test('lifecycle matrix: rebuilding the unchanged spec creates and deletes nothin
// deletes it; the app's immutable `uniqueName` and each page's `pageId` are written; a page's source is stored under
// pages/<pageId>/ and its prompt is written (references/app-spec-schema.md, app.uniqueName and pages[])
// documented a dashboard comes back pinned by `dashboardId`, its tiles bound to the deployed view and chart ids
-// documented an AutoNumber column comes back as Text (download-model-app.js: "no AutoNumber column or format is ever emitted")
+// documented column options equal to the SDK's create defaults are left implicit; AutoNumber masks and non-default options are kept
+// documented primary name lengths stay explicit even at 100, so a fresh build corrects an environment that overrides the create's length
// documented a lookup label that is the referenced table's display name is left out (it is the default)
// documented a File or Image column comes back typed, with the size it was made with unless that is the size a build gives a column
// that sets none (docs/app-builder-capabilities.md, "Round-trip scope")
@@ -358,17 +361,21 @@ test('lifecycle matrix: rebuilding the unchanged spec creates and deletes nothin
// (references/app-spec-schema.md, "Round-trip")
// documented personas[] are not carried (references/app-spec-schema.md: "a download carries none")
// warned a Customer column is left out: its two relationships have no relationships[] form (the download warns)
-// gap solution.displayName, a global choice's displayName, a table's vectorIcon, statusReasons and alternateKeys, a column's
-// type options (format, length, range, precision, labels, date format), a dashboard tile's size, script and
-// table-icon web resources, roleGrants[] and sampleData are not carried
+// documented custom Active/Inactive status reasons, alternate keys, solution/global-choice display names and tile sizes are kept;
+// a table's own unmanaged SVG is carried as external:true, so teardown cannot delete a shared icon
+// gap script resources, raster/foreign/managed table icons, roleGrants[] and sampleData are not carried; Boolean defaults,
+// column capabilities, BigInt ranges and unsupported status states are not reconstructed
function expectedDownload(authored, ids) {
const byName = (a, b) => (a.schemaName < b.schemaName ? -1 : a.schemaName > b.schemaName ? 1 : 0);
const column = (c, primaryImage) => ({
schemaName: c.schemaName,
displayName: c.displayName,
- type: c.type === 'AutoNumber' ? 'Text' : c.type, // documented
+ type: c.type,
...(c.options ? { options: c.options } : {}),
...(c.globalChoice ? { globalChoice: c.globalChoice } : {}),
+ ...Object.fromEntries(['format', 'maxLength', 'minValue', 'maxValue', 'precision', 'integerFormat', 'trueLabel', 'falseLabel', 'dateFormat', 'autoNumberFormat']
+ .filter((key) => c[key] !== undefined && c[key] !== ({ precision: 2, trueLabel: 'Yes', falseLabel: 'No' })[key])
+ .map((key) => [key, c[key]])), // documented default normalization
...((c.type === 'File' || c.type === 'Image') && c.maxSizeKb !== undefined ? { maxSizeKb: c.maxSizeKb } : {}), // documented
...(c === primaryImage ? { isPrimaryImage: true } : {}), // documented
});
@@ -376,12 +383,15 @@ function expectedDownload(authored, ids) {
schemaName: e.schemaName,
displayName: e.displayName,
...(e.pluralName !== `${e.displayName}s` ? { pluralName: e.pluralName } : {}), // documented
- primaryAttribute: { schemaName: e.primaryAttribute.schemaName, displayName: e.primaryAttribute.displayName },
+ primaryAttribute: { schemaName: e.primaryAttribute.schemaName, displayName: e.primaryAttribute.displayName, maxLength: e.primaryAttribute.maxLength || 100 },
columns: e.columns
.filter((c) => c.type !== 'Customer') // warned
.map((c) => column(c, e.columns.find((x) => x.type === 'Image'))).sort(byName),
existing: true,
description: e.description,
+ ...(e.statusReasons ? { statusReasons: e.statusReasons } : {}),
+ ...(e.alternateKeys ? { alternateKeys: e.alternateKeys } : {}),
+ ...(e.vectorIcon ? { vectorIcon: e.vectorIcon } : {}),
});
const tableName = new Map(authored.entities.map((e) => [e.schemaName, e.displayName]));
const relationship = (r) => (r.type === 'ManyToMany'
@@ -392,12 +402,13 @@ function expectedDownload(authored, ids) {
return {
schemaVersion: authored.schemaVersion,
minimumPluginVersion: authored.minimumPluginVersion,
- solution: { uniqueName: authored.solution.uniqueName, publisherPrefix: authored.solution.publisherPrefix, description: authored.solution.description },
+ solution: { uniqueName: authored.solution.uniqueName, displayName: authored.solution.displayName, publisherPrefix: authored.solution.publisherPrefix, description: authored.solution.description },
app: { ...authored.app, uniqueName: 'contoso_kitchensink' },
entities: authored.entities.map(entity),
relationships: authored.relationships.map(relationship),
- globalChoices: authored.globalChoices.map((g) => ({ name: g.name, options: g.options, existing: true })),
- webResources: [],
+ globalChoices: authored.globalChoices.map((g) => ({ name: g.name, displayName: g.displayName, options: g.options, existing: true })),
+ webResources: authored.webResources.filter((wr) => wr.type === 'svg' && authored.entities.some((e) => e.vectorIcon === wr.name))
+ .map((wr) => ({ name: wr.name, displayName: wr.displayName, type: wr.type, contentBase64: Buffer.from(wr.content).toString('base64'), external: true })),
views: [],
charts: [],
forms: [],
@@ -409,7 +420,7 @@ function expectedDownload(authored, ids) {
tiles: [
{ type: 'chart', name: 'Projects by Priority', entity: 'contoso_project', viewId: ids.openProjects, visualizationId: ids.chart },
{ type: 'list', name: 'Open', entity: 'contoso_project', viewId: ids.openProjects },
- { type: 'iframe', name: 'Status', url: 'https://contoso.example/status' },
+ { type: 'iframe', name: 'Status', url: 'https://contoso.example/status', colspan: 2, rowspan: 8 },
],
}],
pages: [{ key: page.key, name: page.name, pageId: ids.page, purpose: page.purpose, dataSources: page.dataSources, prompt: `Generative page ${page.name}`, source: { kind: 'tsx', codeFile: `pages/${ids.page}/page.tsx` } }],
@@ -472,7 +483,9 @@ test('lifecycle matrix: teardown deletes everything the build made and nothing e
t.diagnostic(`teardown ${run.timings.teardown} ms, ${s.end - s.mark} requests; whole lifecycle ${Object.values(run.timings).reduce((a, b) => a + b, 0)} ms`);
const { result } = s.value;
assert.equal(result.ok, true, JSON.stringify(result.errors));
- assert.deepEqual({ errors: result.errors, skipped: result.skipped }, { errors: [], skipped: [] });
+ // Nothing fails and nothing is skipped, but for the relationship from contoso_project to itself: its table's delete took it, so its
+ // own step (planned after the tables) finds nothing and says not found.
+ assert.deepEqual({ errors: result.errors, skipped: result.skipped }, { errors: [], skipped: ['relationship contoso_project_contoso_project'] });
assert.deepEqual(s.writes, TEARDOWN_WRITES);
// The environment is back to where it started, but for the publisher the build made for the prefix: teardown deletes the solution and
// never a publisher, which other solutions may share. Only THAT row is set aside — by its identity, captured after the build — so a
@@ -481,6 +494,9 @@ test('lifecycle matrix: teardown deletes everything the build made and nothing e
assert.match(run.builtPublisher[0], / contosopublisher$/);
const publishers = run.afterTeardown.rows.publishers;
assert.deepEqual(publishers.filter((p) => !run.seed.rows.publishers.includes(p)), run.builtPublisher, 'the one row left that the environment did not have is the build\'s publisher');
+ // ...and the teardown says so, in the one line that follows its closing count.
+ const log = s.value.log.map((line) => line.trim());
+ assert.deepEqual(log.slice(log.findIndex((line) => /^✓ teardown complete — /.test(line)) + 1), ["▸ the publisher with prefix 'contoso' is kept: teardown never deletes a publisher, which other solutions may share — delete it in Power Apps (Solutions → Publishers) once nothing uses it"]);
assert.deepEqual({ ...run.afterTeardown, rows: { ...run.afterTeardown.rows, publishers: publishers.filter((p) => !run.builtPublisher.includes(p)) } }, run.seed, 'every table, column, relationship, option set, row, solution component, link and page the build made is gone, and nothing the environment had before is missing');
// ...and every artifact the environment had before holds exactly what it held: saved and published layers, metadata, page files.
assert.deepEqual(diffContents(run.seedContents, run.contents.teardown, { added: false }), [], 'nothing the environment had before was touched');
diff --git a/plugins/model-apps/scripts/tests/lifecycle-pages-first-real-bundle.test.js b/plugins/model-apps/scripts/tests/lifecycle-pages-first-real-bundle.test.js
new file mode 100644
index 000000000..ca5adabe6
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/lifecycle-pages-first-real-bundle.test.js
@@ -0,0 +1,317 @@
+'use strict';
+// A NEW app whose navigation holds only generative pages, through its whole lifecycle — over the REAL vendored SDK, the plugin's own
+// HTTP client and the stateful fake Dataverse the lifecycle tests share (helpers/fake-lifecycle-org.js, helpers/lifecycle-harness.js),
+// each command run the way its CLI runs it. It is the LIVE CHECK of this change, offline.
+//
+// Dataverse refuses to CREATE a sitemap that holds no entry (measured):
+//
+// HTTP 400: SiteMap needs to have a non-empty Area with a non-empty Group, even when ignoring all Areas, Groups, and SubAreas with an IsVisible child
+//
+// A new app used to be created BEFORE its pages, its first navigation without them, so a navigation of pages only could not be
+// built at all (2.17.0 refused it before writing anything: app-navigation-empty). The build now creates the pages first and then the
+// app, whose first navigation holds them (lib/sdk-build.js, `createAppWithPages`). The fake does not model the platform's refusal, so
+// the seam in front of it adds it, and the cases pin, by what reached the wire and what the environment holds:
+// * built from nothing: the page is created before the app, the one sitemap ever created holds it, no navigation without an entry
+// is ever sent (so no temporary entry exists), and the app is published with the page in it; verify passes;
+// * a build refused between the pages and the app (the app's create): the page, its creation receipt and the manifest are there and
+// there is no app; run again, the page is adopted — not created a second time — and the app is created with it;
+// * a teardown, after the clean build and right after the build that stopped (there is no app then): everything the build made is
+// gone, and everything the environment held before it holds what it held.
+// A failure is provoked only by refusing this test's own app's create, in front of the fake, so the environment holds what it would
+// after a real refusal.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');
+const { createLifecycleHarness, seedForeignWork, diffContents } = require('./helpers/lifecycle-harness.js');
+const { readPageOwnership } = require('../lib/page-ownership-records.js');
+
+const APP_UNIQUE = 'contoso_pagesfirst';
+const PAGE_NAME = 'Kitchen Page';
+const PLATFORM_ANSWER = 'SiteMap needs to have a non-empty Area with a non-empty Group, even when ignoring all Areas, Groups, and SubAreas with an IsVisible child, regardless of their visibility settings.';
+
+// One table the build creates, one page that reads it, and a navigation that holds that page and nothing else. The page's source is the
+// file the harness writes into the app folder (KitchenPage.tsx).
+function pagesOnlySpec() {
+ return {
+ schemaVersion: 2,
+ solution: { uniqueName: 'ContosoPagesFirst', displayName: 'Contoso Pages First', publisherPrefix: 'contoso' },
+ app: { name: 'Pages First', description: 'An app whose navigation is one generative page.' },
+ entities: [{ schemaName: 'contoso_project', displayName: 'Project', pluralName: 'Projects', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] }],
+ pages: [{ key: 'overview', name: PAGE_NAME, purpose: 'A page over projects.', dataSources: ['contoso_project'], source: { kind: 'tsx', codeFile: 'KitchenPage.tsx' } }],
+ appShell: { areas: [{ label: 'Work', groups: [{ label: 'Pages', subAreas: [{ page: 'overview', title: PAGE_NAME }] }] }] },
+ };
+}
+const spec = pagesOnlySpec();
+
+// The request a seam answers, as the fake records it: the path below the API root, the body parsed.
+const pathOf = (req) => decodeURIComponent(new URL(req.url).pathname).replace(/^\/api\/data\/v9\.\d/, '');
+const bodyOf = (req) => { try { return JSON.parse(req.body); } catch { return null; } };
+// A Dataverse OData error the client does not retry, as a real refusal is answered:
+// https://learn.microsoft.com/power-apps/developer/data-platform/webapi/compose-http-requests-handle-errors#parse-errors-from-the-response
+const refusal = (message) => ({ statusCode: 400, headers: { 'content-type': 'application/json; odata.metadata=minimal' }, body: JSON.stringify({ error: { code: '0x80040216', message } }) });
+
+// A fake environment with another maker's work in it, the platform's rule for a sitemap's create, and a seam that refuses an app's
+// create while `refuseAppCreate` is set. A sitemap the SDK creates is sent as
+// POST /sitemaps { "sitemapid": "…", "sitemapnameunique": "contoso_pagesfirst", "sitemapxml": "<SiteMap …><Area …><Group …>…</Group></Area></SiteMap>" }
+// and the rule refuses one whose XML holds no <SubArea>.
+async function environment() {
+ const org = createLifecycleOrg();
+ await seedForeignWork(org);
+ const seen = { emptySitemapCreates: 0, sitemapCreates: [], sitemapWrites: [], appCreatesRefused: 0, refuseAppCreate: false, gatewayRefusals: 0 };
+ const request = async (req) => {
+ const where = pathOf(req);
+ // A gateway that answers the app's create with a 503 the next `gatewayRefusals` times: a failure the HTTP client re-sends, and the build retries.
+ if (seen.gatewayRefusals > 0 && req.method === 'POST' && /^\/appmodules$/.test(where)) {
+ seen.gatewayRefusals -= 1;
+ return { statusCode: 503, headers: { 'content-type': 'application/json; odata.metadata=minimal' }, body: JSON.stringify({ error: { code: '0x80040216', message: 'Service Unavailable' } }) };
+ }
+ if (req.method === 'POST' && /^\/sitemaps$/.test(where)) {
+ const xml = String((bodyOf(req) || {}).sitemapxml || '');
+ seen.sitemapCreates.push(xml);
+ if (!/<SubArea\b/.test(xml)) { seen.emptySitemapCreates += 1; return refusal(PLATFORM_ANSWER); }
+ }
+ // Every navigation the build writes, the create's and any later push's (the placement of the page's default view pushes the app it reads).
+ if ((req.method === 'POST' && /^\/sitemaps$/.test(where)) || (req.method === 'PATCH' && /^\/sitemaps\(/.test(where))) {
+ const body = bodyOf(req) || {};
+ if (typeof body.sitemapxml === 'string') seen.sitemapWrites.push(body.sitemapxml);
+ }
+ if (seen.refuseAppCreate && req.method === 'POST' && /^\/appmodules$/.test(where)) {
+ seen.appCreatesRefused += 1;
+ return refusal('An unexpected error occurred.');
+ }
+ return org.request(req);
+ };
+ const harness = createLifecycleHarness({ ...org, request }, makeTempDir('lifecycle-pages-first-'));
+ return { org, harness, seen, seed: org.inventory(), seedContents: org.contents() };
+}
+
+// A measured step ran: it did not throw, and every request it sent is one the fake models.
+const ran = (step, label) => {
+ assert.ok(step, `${label} ran`);
+ if (step.error) throw step.error;
+ assert.deepEqual(step.unexpected, [], `every request ${label} sent is one the fake models`);
+ return step;
+};
+
+// The entries of a navigation, each as the id of the page it names — `not a page` for an entry that names none:
+// <SubArea Id="sub_0_0_0" GenPageId="2f10af3e-632d-489d-ad61-3820c7b100f0" …> -> '2f10af3e-632d-489d-ad61-3820c7b100f0'
+const entriesOf = (xml) => (String(xml || '').match(/<SubArea\b[^>]*>/g) || []).map((tag) => ((/\bGenPageId="([^"]+)"/.exec(tag) || [])[1] || 'not a page').toLowerCase());
+
+// What the environment holds of this app: the app and whether it is published, its navigation's entries (entriesOf), the pages of that
+// name, how many of them are published, and whether the page manifest is there.
+function holds(org) {
+ const app = org.find('appmodules', (a) => a.uniquename === APP_UNIQUE)[0];
+ const appRow = app && org.rowsOf('appmodules').get(app.appmoduleid);
+ const sitemap = org.find('sitemaps', (m) => m.sitemapnameunique === APP_UNIQUE)[0];
+ const pages = [...org.pageServer.state.projects.values()].filter((p) => p.name === PAGE_NAME);
+ return {
+ app: app ? { published: !!(appRow && appRow.published) } : null,
+ navigation: entriesOf(sitemap && sitemap.sitemapxml),
+ pages: pages.map((p) => String(p.id).toLowerCase()),
+ publishedPages: pages.filter((p) => org.pageServer.publishedPages.has(p.id)).length,
+ manifest: org.find('webresourceset', (w) => w.name === `${APP_UNIQUE}_pagemanifest`).length,
+ };
+}
+
+// The environment is as the seed left it, but for the publisher the build made for the prefix (a teardown keeps a publisher) — set
+// aside by identity, so a publisher the environment had before that went missing still fails. By identity nothing the build made is
+// left and nothing the environment had is missing; by content everything it had holds exactly what it held. (The recovery tests
+// compare the same way: lifecycle-recovery-real-bundle.test.js.)
+function assertBackToSeed(env) {
+ const { org, seed } = env;
+ const now = org.inventory();
+ const made = now.rows.publishers.filter((p) => !seed.rows.publishers.includes(p));
+ assert.equal(made.length, 1, 'the build made one publisher, for its prefix');
+ assert.deepEqual({ ...now, rows: { ...now.rows, publishers: now.rows.publishers.filter((p) => !made.includes(p)) } }, seed, 'every other row is as it was before the build: no more, no fewer');
+ assert.deepEqual(diffContents(env.seedContents, org.contents(), { added: false }), [], 'and every one of them holds exactly what it held');
+}
+
+// A request that creates a generative page: the page service's change set (`$batch`) holds the POST of its project row, or — for a
+// transport that sends it alone — the POST itself.
+const createsPage = (r) => r.method === 'POST' && (/^\/uxagentprojects(\?|$)/.test(r.path) || (r.operations || []).some((o) => o.method === 'POST' && /(^|\/)uxagentprojects(\?|$)/.test(String(o.path))));
+const createsApp = (r) => r.method === 'POST' && /^\/appmodules(\?|$)/.test(r.path);
+
+// CLEAN: built from nothing.
+let cleanP;
+const clean = () => cleanP || (cleanP = (async () => {
+ const env = await environment();
+ env.build = await env.harness.measure(() => env.harness.build(spec));
+ env.afterBuild = holds(env.org);
+ env.workspaceAfterBuild = readPageOwnership(env.harness.workspaceDir, APP_UNIQUE, env.org.origin);
+ return env;
+})());
+
+// STOPPED: the app's create refused, after the pages were written; then run again with the refusal lifted.
+let stoppedP;
+const stopped = () => stoppedP || (stoppedP = (async () => {
+ const env = await environment();
+ env.seen.refuseAppCreate = true;
+ env.failed = await env.harness.measure(() => env.harness.build(spec));
+ env.seen.refuseAppCreate = false;
+ env.afterFailed = holds(env.org);
+ env.navigationWritesAfterFailed = env.seen.sitemapWrites.length;
+ env.workspaceAfterFailed = readPageOwnership(env.harness.workspaceDir, APP_UNIQUE, env.org.origin);
+ return env;
+})());
+
+test('pages first: the spec these cases build is one 2.17.0 refused — a navigation of pages only, for an app that does not exist', () => {
+ const { navigationHolds } = require('../lib/app-navigation.js');
+ const navigation = navigationHolds(spec);
+ assert.deepEqual({ entries: navigation.entries, pages: navigation.pages }, { entries: 1, pages: ['overview'] });
+});
+
+test('pages first: a new app of pages only is built from nothing — the page before the app, and the app\u2019s first navigation already holds it', async () => {
+ const env = await clean();
+ const build = ran(env.build, 'the build');
+ assert.equal(build.value.result.ok, true, JSON.stringify(build.value.result.errors));
+ assert.equal(env.seen.emptySitemapCreates, 0, 'no navigation without an entry was ever sent');
+ assert.equal(env.seen.sitemapCreates.length, 1, 'one sitemap was created');
+ const after = env.afterBuild;
+ assert.equal(after.pages.length, 1, 'the page was created once');
+ assert.deepEqual(entriesOf(env.seen.sitemapCreates[0]), after.pages, 'and it held the page when it was created, and nothing else: no temporary entry');
+ // The page's create comes before the app's: the page service's write of the page, then the app module row.
+ const requests = env.org.since(build.mark);
+ const pageCreate = requests.findIndex(createsPage);
+ const appCreate = requests.findIndex(createsApp);
+ assert.ok(pageCreate >= 0 && appCreate > pageCreate, `the page is created (${pageCreate}) before the app (${appCreate})`);
+ assert.equal(requests.filter(createsPage).length, 1, 'the page is created once');
+ assert.equal(requests.filter(createsApp).length, 1, 'the app is created once');
+ // Every navigation written — the create's, and the push that pins the page's default view into the app — holds the page entry and only it.
+ assert.ok(env.seen.sitemapWrites.length >= 1);
+ for (const xml of env.seen.sitemapWrites) assert.deepEqual(entriesOf(xml), after.pages, 'a navigation write holds the page, and nothing else');
+ assert.deepEqual(after.app, { published: true }, 'the app is published');
+ assert.deepEqual(after.navigation, after.pages, 'the navigation holds the page, and nothing else');
+ assert.equal(after.publishedPages, 1, 'and the page is published');
+ assert.equal(after.manifest, 1, 'the page manifest is there');
+ assert.deepEqual(build.value.result.verify && { ok: build.value.result.verify.ok, missing: build.value.result.verify.missing }, { ok: true, missing: [] }, 'verify passes');
+ // What the log says of the app step: deferred, not done, and then the create.
+ assert.ok(build.value.log.some((line) => /⊘ app "Pages First" \(created after its pages: its navigation holds only page entries\)/.test(line)), build.value.log.join('\n'));
+ assert.ok(build.value.log.some((line) => /✓ app "Pages First" \(created with its pages\)/.test(line)), build.value.log.join('\n'));
+ assert.deepEqual(env.workspaceAfterBuild.created.map((r) => r.pageId), after.pages, 'the page\u2019s creation receipt names it');
+});
+
+test('pages first: an unchanged rebuild of that app is an ordinary rebuild of an existing app — no page and no app is created', async () => {
+ const env = await clean();
+ const rebuild = ran(await env.harness.measure(() => env.harness.build(spec)), 'the rebuild');
+ assert.equal(rebuild.value.result.ok, true, JSON.stringify(rebuild.value.result.errors));
+ const requests = env.org.since(rebuild.mark);
+ assert.equal(requests.filter(createsApp).length, 0, 'the app exists: it is not created again');
+ assert.ok(!requests.some(createsPage), 'nor is the page');
+ assert.ok(!rebuild.value.log.some((line) => /created after its pages|created with its pages/.test(line)), 'the app step reuses the app, as for any existing app');
+ assert.deepEqual(holds(env.org), env.afterBuild, 'and the app, its navigation and its page are what the first build left');
+});
+
+test('pages first: a build refused between the pages and the app leaves the page with its receipt and no app — and says where it stopped', async () => {
+ const env = await stopped();
+ const failed = env.failed;
+ assert.ok(env.seen.appCreatesRefused > 0, 'the app\u2019s create was refused');
+ assert.deepEqual(failed.unexpected, []);
+ assert.ok(failed.error, 'the build stopped');
+ assert.equal(failed.error.phase, 'app-shell', 'at the app\u2019s create, which is the app step\u2019s work');
+ assert.equal(env.seen.emptySitemapCreates, 0);
+ const after = env.afterFailed;
+ assert.equal(after.app, null, 'there is no app');
+ assert.equal(env.navigationWritesAfterFailed, 0, 'and no navigation was written: the app\u2019s create comes before its sitemap\u2019s');
+ assert.equal(after.pages.length, 1, 'the page was created');
+ assert.equal(after.manifest, 1, 'and recorded in the manifest');
+ assert.deepEqual(env.workspaceAfterFailed.created.map((r) => r.pageId), after.pages, 'and in its creation receipt, which is what the next build adopts it by');
+});
+
+test('pages first: run again, the build that stopped adopts its page — it is not created twice — and creates the app with it', async () => {
+ const env = await stopped();
+ const resumed = ran(await env.harness.measure(() => env.harness.build(spec)), 'the build run again');
+ assert.equal(resumed.value.result.ok, true, JSON.stringify(resumed.value.result.errors));
+ const requests = env.org.since(resumed.mark);
+ assert.ok(!requests.some(createsPage), 'no page is created');
+ assert.equal(requests.filter(createsApp).length, 1, 'the app is created, once');
+ const after = holds(env.org);
+ assert.deepEqual(after.pages, env.afterFailed.pages, 'the page is the one the stopped build made');
+ assert.deepEqual(after.navigation, after.pages, 'and it is the app\u2019s navigation');
+ assert.ok(env.seen.sitemapWrites.length > env.navigationWritesAfterFailed);
+ for (const xml of env.seen.sitemapWrites) assert.deepEqual(entriesOf(xml), after.pages, 'every navigation written holds the page, and nothing else');
+ assert.deepEqual(after.app, { published: true });
+ assert.equal(env.seen.emptySitemapCreates, 0);
+ assert.deepEqual(resumed.value.result.verify && { ok: resumed.value.result.verify.ok, missing: resumed.value.result.verify.missing }, { ok: true, missing: [] });
+ // Then the teardown of the app built in two runs: everything the build made is gone.
+ const teardown = ran(await env.harness.measure(() => env.harness.teardown(spec)), 'the teardown');
+ assert.equal(teardown.value.result.ok, true, JSON.stringify(teardown.value.result.errors));
+ assertBackToSeed(env);
+});
+
+test('pages first: the teardown of the clean build deletes everything the build made', async () => {
+ const env = await clean();
+ const teardown = ran(await env.harness.measure(() => env.harness.teardown(spec)), 'the teardown');
+ assert.equal(teardown.value.result.ok, true, JSON.stringify(teardown.value.result.errors));
+ assert.deepEqual(holds(env.org), { app: null, navigation: [], pages: [], publishedPages: 0, manifest: 0 });
+ assertBackToSeed(env);
+});
+
+test('pages first: a teardown right after the build that stopped before its app finds the page by its receipt and deletes it — everything is gone', async () => {
+ // A fresh environment of its own: the run-again case above goes on from the stopped build.
+ const env = await environment();
+ env.seen.refuseAppCreate = true;
+ const failed = await env.harness.measure(() => env.harness.build(spec));
+ env.seen.refuseAppCreate = false;
+ assert.ok(failed.error && env.seen.appCreatesRefused > 0, 'the build stopped at the app\u2019s create');
+ assert.equal(holds(env.org).pages.length, 1, 'with the page created');
+ const teardown = ran(await env.harness.measure(() => env.harness.teardown(spec)), 'the teardown with no app');
+ assert.equal(teardown.value.result.ok, true, JSON.stringify(teardown.value.result.errors));
+ assert.ok(env.org.since(teardown.mark).some((r) => r.method === 'DELETE' && /^\/uxagentprojects\(/.test(r.path)), 'the page was deleted');
+ assert.deepEqual(holds(env.org), { app: null, navigation: [], pages: [], publishedPages: 0, manifest: 0 });
+ assertBackToSeed(env);
+ assert.deepEqual(readPageOwnership(env.harness.workspaceDir, APP_UNIQUE, env.org.origin).created, [], 'and its receipt is consumed');
+ assert.ok(fs.existsSync(path.join(env.harness.appDir, 'KitchenPage.tsx')), 'the page\u2019s source in the app folder is the maker\u2019s, and stays');
+});
+
+test('pages first: a page made by a build of this app in another workspace is not adopted — it names no record here, and the advice does not send the maker to an app that does not exist', async () => {
+ const env = await environment();
+ env.seen.refuseAppCreate = true;
+ await env.harness.measure(() => env.harness.build(spec));
+ env.seen.refuseAppCreate = false;
+ const made = holds(env.org);
+ assert.equal(made.pages.length, 1, 'the stopped build made the page');
+ // The same app folder, another workspace: it holds no creation receipt for the page the manifest names.
+ const elsewhere = path.join(makeTempDir('lifecycle-pages-first-elsewhere-'), '.maker-workspace');
+ fs.mkdirSync(elsewhere, { recursive: true });
+ const other = await env.harness.measure(() => env.harness.build(spec, { workspace: elsewhere }));
+ assert.deepEqual(other.unexpected, []);
+ assert.ok(other.error, 'the build stops');
+ assert.equal(other.error.code, 'pages-identity-conflict');
+ assert.match(other.error.message, /is in no navigation of this app — the app does not exist yet: its navigation holds only page entries, so the build creates it once its pages exist — and this workspace holds no record that this app created it in this environment: if it is this app's page, run the build from the workspace that created it, which holds that record; if not, remove the stale id from the manifest\/spec/);
+ assert.doesNotMatch(other.error.message, /add-to-app/, 'no command for an app that does not exist');
+ const requests = env.org.since(other.mark);
+ assert.ok(!requests.some(createsPage) && !requests.some(createsApp), 'no page and no app was created');
+ assert.deepEqual(holds(env.org), made, 'the environment holds what the stopped build left');
+ // The workspace that made the page builds the app with it.
+ const resumed = ran(await env.harness.measure(() => env.harness.build(spec)), 'the build from the workspace that made the page');
+ assert.equal(resumed.value.result.ok, true, JSON.stringify(resumed.value.result.errors));
+ assert.deepEqual(holds(env.org).navigation, made.pages);
+ const teardown = ran(await env.harness.measure(() => env.harness.teardown(spec)), 'the teardown');
+ assert.equal(teardown.value.result.ok, true, JSON.stringify(teardown.value.result.errors));
+ assertBackToSeed(env);
+});
+
+test('pages first: a gateway failure at the app\u2019s create is retried by the build itself — the retry adopts the page, so one page and one app are made', async () => {
+ const env = await environment();
+ // The HTTP client sends a request at most six times (lib/sdk-http-client.js maxAttempts), so six refusals fail the first attempt of the build
+ // and the seventh send — the build's own retry of a transient halt — gets through.
+ env.seen.gatewayRefusals = 6;
+ const build = ran(await env.harness.measure(() => env.harness.build(spec)), 'the build');
+ assert.equal(env.seen.gatewayRefusals, 0, 'every refusal was spent');
+ assert.equal(build.value.result.ok, true, JSON.stringify(build.value.result.errors));
+ assert.ok(build.value.log.some((line) => /⟳ transient error in app-shell — retrying \(attempt 1\/3\)/.test(line)), build.value.log.join('\n'));
+ const requests = env.org.since(build.mark);
+ assert.equal(requests.filter(createsPage).length, 1, 'the page is created once: the retry adopts it by its receipt');
+ assert.equal(requests.filter((r) => createsApp(r) && r.status < 300).length, 1, 'and the app is created once');
+ const after = holds(env.org);
+ assert.equal(after.pages.length, 1);
+ assert.deepEqual(after.navigation, after.pages);
+ assert.deepEqual(after.app, { published: true });
+ assert.equal(env.seen.emptySitemapCreates, 0);
+ const teardown = ran(await env.harness.measure(() => env.harness.teardown(spec)), 'the teardown');
+ assert.equal(teardown.value.result.ok, true, JSON.stringify(teardown.value.result.errors));
+ assertBackToSeed(env);
+});
diff --git a/plugins/model-apps/scripts/tests/lifecycle-recovery-real-bundle.test.js b/plugins/model-apps/scripts/tests/lifecycle-recovery-real-bundle.test.js
index d36cf0f48..635bdb6bd 100644
--- a/plugins/model-apps/scripts/tests/lifecycle-recovery-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/lifecycle-recovery-real-bundle.test.js
@@ -11,7 +11,7 @@
//
// Two environments serve the tests, each walked in the order a maker meets these steps; as in the matrix, a step that throws is
// recorded and fails its own test (a later test on the same environment then fails after it):
-// CLEAN built -> a maker deletes six artifacts in Maker -> verify -> rebuild | download -> teardown of the downloaded spec ->
+// CLEAN built -> a maker deletes seven artifacts in Maker -> verify -> rebuild | download -> teardown of the downloaded spec ->
// teardown of the authored spec -> a teardown of what is gone
// FAULTED a build refused part way -> the build run again | a teardown refused part way -> the teardown run again
// A failure is provoked only by refusing a request for this test's own app, in front of the fake: the refused request never reaches
@@ -61,7 +61,8 @@ async function inMaker(org, method, where) {
const buttonsOf = (org) => org.find('appactions', () => true).map((a) => a.buttonlabeltext).sort();
// CLEAN: the kitchen sink built, and what it deployed (the reference a recovered environment must end equal to); then a maker deletes
-// a view, a Quick Create form, a button, the persona's role, the N:N relationship and the generative page; verify; the rebuild.
+// a view, a Quick Create form, a button, the persona's role, the N:N relationship, the generative page and the alternate key; verify;
+// the rebuild.
let cleanP;
const clean = () => cleanP || (cleanP = (async () => {
const env = await environment();
@@ -82,6 +83,7 @@ const clean = () => cleanP || (cleanP = (async () => {
const page = [...org.pageServer.state.projects.values()].find((p) => p.name === 'Kitchen Page');
for (const message of org.pageServer.messagesOf(page.id)) await inMaker(org, 'DELETE', `/agentconversationmessages(${message.id})`);
await inMaker(org, 'DELETE', `/uxagentprojects(${page.id})`);
+ await inMaker(org, 'DELETE', "/EntityDefinitions(LogicalName='contoso_project')/Keys(LogicalName='contoso_emailkey')");
env.drifted = await harness.measure(() => harness.verify(spec));
env.rebuild = await harness.measure(() => harness.build(spec));
env.afterRebuild = deployedFeatures(org);
@@ -128,9 +130,10 @@ function assertBackToSeed(env) {
// ====================================================================================================================================
// THE PINNED VALUES — one per step. A value that moves on purpose is a one-line change here.
-// What verify reports for the six deletions, in its order. The deleted "Escalate" button is NOT among them: verify checks one command
+// What verify reports for the seven deletions, in its order. The deleted "Escalate" button is NOT among them: verify checks one command
// bar per table (verify-spec.js, "Commands (existence)"), and the table still has the flyout.
const DRIFT_MISSING = [
+ 'alternate-key contoso_project.contoso_emailkey',
'view contoso_task.My Open Tasks',
'form Task Quick Create',
'relationship contoso_tag_contoso_task',
@@ -154,9 +157,10 @@ const FAILED_BUILD_WRITES = {
};
// The refused teardown: one table's delete fails, the teardown goes on as far as it can, keeps the solution for the re-run, and says so.
+// The relationship from contoso_project to itself went with its table, so its own step finds nothing: 1 not found.
const FAILED_TEARDOWN_LINES = [
"[18/27] ✗ table contoso_tag — HTTP 400 from https://contoso.crm.dynamics.com/api/data/v9.0/EntityDefinitions(LogicalName='contoso_tag'): The Entity component cannot be deleted because it is referenced by 1 other component.",
- '✗ teardown finished with errors — 25 deleted, 0 not found, 1 failed, 1 kept (27 steps)',
+ '✗ teardown finished with errors — 24 deleted, 1 not found, 1 failed, 1 kept (27 steps)',
];
// The teardown run again: the table it could not delete and the solution it kept. A table or global choice is deleted by name, so the
// two tables and the global choice that are already gone are sent again and answered 404, which the teardown reads as "already gone".
@@ -176,9 +180,10 @@ const DOWNLOADED_TEARDOWN_WRITES = {
'DELETE solutions': 1,
};
-// A teardown of what is gone. This overstates what it did: a default-view reset, a relationship, a table or a global choice that was
-// already gone is reported as deleted (each step is idempotent and ends ✓). Once that is fixed this reads "0 deleted, 27 not found".
-const AGAIN_SUMMARY = '✓ teardown complete — 9 deleted, 18 not found, 0 failed (27 steps)';
+// A teardown of what is gone: every step finds nothing, and says so. A default-view reset finds no default view; a relationship is
+// looked up by the SDK, which sends no delete when it finds none; a table and a global choice are deleted by name and answered 404 —
+// the table's own read had already listed no such table, and the global choice's delete is its step's only request.
+const AGAIN_SUMMARY = '✓ teardown complete — 0 deleted, 27 not found, 0 failed (27 steps)';
// ====================================================================================================================================
@@ -252,4 +257,5 @@ test('lifecycle recovery: a teardown of the downloaded spec keeps every table, c
assert.deepEqual(org.since(again.mark).filter((r) => r.method !== 'GET').map((r) => r.status), [404, 404, 404, 404]);
assertBackToSeed(env);
assert.deepEqual(again.value.log.filter((line) => /teardown complete|finished with errors/.test(line)).map((line) => line.trim()), [AGAIN_SUMMARY]);
+ assert.deepEqual(again.value.log.filter((line) => /^\s+\[\d+\/\d+\] /.test(line) && !/^\s+\[\d+\/\d+\] ⊘ .* \(not found\)$/.test(line)), [], 'and every step line says not found');
});
diff --git a/plugins/model-apps/scripts/tests/lifecycle-scenarios-real-bundle.test.js b/plugins/model-apps/scripts/tests/lifecycle-scenarios-real-bundle.test.js
index acb6047ac..8a455622c 100644
--- a/plugins/model-apps/scripts/tests/lifecycle-scenarios-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/lifecycle-scenarios-real-bundle.test.js
@@ -9,6 +9,8 @@
// --publish means what it says a rebuild without it sends none of the bulk publishes it gates, and leaves the rest unpublished
// the edit flow is safe the downloaded spec rebuilds in the same environment without creating or deleting anything, and both
// it and the authored spec verify
+// verify reads what is declared a table's status reasons and alternate keys cost verify one read each, made only for a table that
+// declares them
// (lifecycle-recovery-real-bundle.test.js pins the rest: drift, a failed build or teardown run again, a teardown of a downloaded spec.)
//
// One environment is built once and the tests use it in order — the ones that only read first, then the rebuilds.
@@ -82,8 +84,8 @@ const TEARDOWN_PLAN = [
// table — measured, not derived: 11 publishes where the --publish rebuild of the matrix sends 4, each a PublishXml that takes seconds
// on a real environment. The two tables' views and forms are pushed concurrently, so the publishes are counted, not ordered.
const UNPUBLISHED_REBUILD_PUBLISHES = {
- contoso_project: 5, // the table icon set again; the view "Open Projects" pushed again unchanged (no write, but a publish); the
- // default-view enrichment; the forms "Project" and "Project Card", likewise unchanged
+ contoso_project: 5, // the table-icon assignment and the view "Open Projects" publish,
+ // as do default-view enrichment and the unchanged forms "Project" and "Project Card"
contoso_task: 5, // the views "Open Tasks" and "My Open Tasks"; the default-view enrichment; the forms "Task Quick Create" and "Task"
app: 1, // the app after the sitemap finalize, the last publish
};
@@ -92,15 +94,26 @@ const UNPUBLISHED_REBUILD_PUBLISHES = {
const UNPUBLISHED_AFTER = ['appsettings <id>', 'systemforms Project', 'systemforms Task'];
// The rebuild of the downloaded spec. Its tables are existing and it carries no form, view, chart or command, so nothing of the data
-// model or the record UI is written; what is written is the app's own, as on any rebuild of an existing app.
+// model or the record UI is rewritten, except its declared icon assignment/publish pair; the app writes remain its own.
const DOWNLOADED_REBUILD_WRITES = {
+ 'PUT EntityDefinitions': 1, // table-icon assignment: saved-name equality is not publication proof
'PATCH webresourceset': 1, // the page manifest: the downloaded page's source is pages/<pageId>/page.tsx, where the authored one was KitchenPage.tsx
'PATCH sitemaps': 1, // the sitemap of an existing app is rewritten by the pages finalize, byte for byte (as in the matrix's rebuild)
'POST AddAppComponents': 1, // ...and the push re-adds the app's components
'POST SaveSettingValue': 1, // the new look setting is saved again
- 'POST PublishXml': 5, // the tables before the app's publish, the page, the manifest, the app after the finalize, and the publish phase
+ 'POST PublishXml': 6, // the icon table, tables before the app, page, manifest, app after finalize, and publish phase
};
+// What verify reads for the kitchen sink with its status reasons and alternate key taken out of the spec — what it read before it checked
+// either — and what declaring them adds: one read of the table's status column and one of its keys, for the one table that declares them.
+// (The status column read is the same request the view filter's label read of that table makes among its four; it is not shared, because
+// that read is made only for a table a view filters by a label, and sharing it would cost every other table three reads more.)
+const VERIFY_READS_WITHOUT = 74;
+const VERIFY_READS_ADDED = [
+ "GET /EntityDefinitions(LogicalName='contoso_project')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)",
+ "GET /EntityDefinitions(LogicalName='contoso_project')/Keys?$select=LogicalName,SchemaName,KeyAttributes",
+];
+
// ====================================================================================================================================
test('lifecycle scenarios: a dry run of the build writes nothing, against an empty environment and against the built one', async () => {
@@ -149,6 +162,32 @@ test('lifecycle scenarios: two downloads of an unchanged app write the same spec
assert.deepEqual(diffContents(held, org.contents()), [], 'three downloads change nothing in the environment');
});
+test('lifecycle scenarios: verify reads a table\'s status reasons and alternate keys only when the spec declares them — one read each', async () => {
+ const { org, harness } = await built();
+ const held = org.contents();
+ const plain = kitchenSinkSpec();
+ delete plain.entities[0].statusReasons;
+ delete plain.entities[0].alternateKeys;
+ const without = clean(await harness.measure(() => harness.verify(plain)), 'verify of the spec without them');
+ const declared = clean(await harness.measure(() => harness.verify(spec)), 'verify of the spec');
+ for (const [step, checked] of [[without, []], [declared, ['alternate-key contoso_project.contoso_emailkey', 'status-reason contoso_project.In Review']]]) {
+ assert.deepEqual({ ok: step.value.ok, missing: step.value.missing }, { ok: true, missing: [] });
+ assert.deepEqual(step.value.checks.filter((c) => /^(status-reason|alternate-key)$/.test(c.kind)).map((c) => `${c.kind} ${c.name}`).sort(), checked);
+ }
+ const sent = (step) => org.requests.slice(step.mark, step.end).map((r) => `${r.method} ${r.path}`);
+ assert.equal(sent(without).length, VERIFY_READS_WITHOUT);
+ assert.ok(!sent(without).some((r) => /\/Keys\b/.test(r)), 'a spec that declares no alternate key reads no key');
+ // The difference of the two runs, request by request: exactly the two reads, and nothing else read once more or once less.
+ const rest = [...sent(declared)];
+ for (const r of sent(without)) {
+ const at = rest.indexOf(r);
+ assert.ok(at >= 0, `the run that declares them still sends ${r}`);
+ rest.splice(at, 1);
+ }
+ assert.deepEqual(rest.sort(), VERIFY_READS_ADDED);
+ assert.deepEqual(diffContents(held, org.contents()), [], 'and neither run changes anything');
+});
+
test('lifecycle scenarios: a rebuild without --publish skips the bulk publishes, and leaves the rest unpublished', async () => {
const { org, harness, seedContents } = await built();
const held = org.inventory();
diff --git a/plugins/model-apps/scripts/tests/list-custom-apis.test.js b/plugins/model-apps/scripts/tests/list-custom-apis.test.js
index be28a9b78..117385c98 100644
--- a/plugins/model-apps/scripts/tests/list-custom-apis.test.js
+++ b/plugins/model-apps/scripts/tests/list-custom-apis.test.js
@@ -4,6 +4,7 @@ const assert = require('node:assert/strict');
const path = require('node:path');
const fs = require('node:fs');
const { spawnSync } = require('node:child_process');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
const scriptPath = path.join(__dirname, '..', 'list-custom-apis.js');
const scriptSrc = fs.readFileSync(scriptPath, 'utf8');
@@ -13,7 +14,8 @@ const scriptSrc = fs.readFileSync(scriptPath, 'utf8');
test('queries customapi with request parameters expanded inline (no OR-of-ids param query)', () => {
assert.match(scriptSrc, /customapis\?\$select=customapiid,uniquename,name,displayname,isfunction,bindingtype,boundentitylogicalname/);
// Parameters are pulled inline via $expand of the CustomAPIRequestParameters navigation property...
- assert.match(scriptSrc, /CustomAPIRequestParameters\(\$select=uniquename,type,isoptional\)/);
+ assert.match(scriptSrc, /CustomAPIRequestParameters\(\$select=uniquename,type,isoptional,logicalentityname\)/);
+ assert.match(scriptSrc, /CustomAPIResponseProperties\(\$select=type\)/);
// ...NOT via a second query that ORs every matched API id into one $filter. That pattern overran the
// server's URL-length limit (HTTP 414) in real environments with hundreds of Global Custom APIs.
assert.doesNotMatch(scriptSrc, /_customapiid_value eq/);
@@ -54,13 +56,15 @@ const {
toCustomApiEntry,
} = require(scriptPath);
-test('mapParameterKind maps the customapirequestparameter Type option set to DataverseParameterKind', () => {
+test('mapParameterKind maps primitive request types and never declares structural kinds', () => {
assert.equal(mapParameterKind(10), 'String');
assert.equal(mapParameterKind(7), 'Integer');
assert.equal(mapParameterKind(2), 'Decimal');
assert.equal(mapParameterKind(12), 'Guid');
assert.equal(mapParameterKind(11), 'StringArray');
- assert.equal(mapParameterKind(5), 'EntityReference');
+ assert.equal(mapParameterKind(3), undefined);
+ assert.equal(mapParameterKind(4), undefined);
+ assert.equal(mapParameterKind(5), undefined);
// Unknown/absent types are dropped (undefined), never guessed.
assert.equal(mapParameterKind(999), undefined);
assert.equal(mapParameterKind(undefined), undefined);
@@ -106,6 +110,29 @@ test('parameterKindsFromRows tolerates missing/empty input', () => {
assert.deepEqual(parameterKindsFromRows([]), {});
});
+test('lookup request parameters remain absent from the declared primitive kind map', () => {
+ assert.deepEqual(parameterKindsFromRows([
+ { uniquename: 'Ref', type: 5 },
+ { uniquename: 'Note', type: 10 },
+ ]), { Note: 'String' });
+});
+
+test('every emitted declared kind belongs to the ten supported primitive kinds', () => {
+ const rows = Array.from({ length: 13 }, (_, type) => ({ uniquename: `Parameter${type}`, type }));
+ assert.deepEqual(parameterKindsFromRows(rows), {
+ Parameter0: 'Boolean',
+ Parameter1: 'DateTime',
+ Parameter2: 'Decimal',
+ Parameter6: 'Float',
+ Parameter7: 'Integer',
+ Parameter8: 'Money',
+ Parameter9: 'Picklist',
+ Parameter10: 'String',
+ Parameter11: 'StringArray',
+ Parameter12: 'Guid',
+ });
+});
+
test('toCustomApiEntry omits boundEntityLogicalName for a Global API', () => {
const entry = toCustomApiEntry(
{ uniquename: 'new_NoOp', isfunction: false, bindingtype: 0 },
@@ -130,3 +157,417 @@ test('toCustomApiEntry sets boundEntityLogicalName for an entity-bound Function
assert.equal(entry.displayName, 'Get Order Summary');
assert.deepEqual(entry.parameterKinds, { OrderId: 'Guid' });
});
+
+test('toCustomApiEntry retains lookup names, optionalness and table hints outside parameterKinds', () => {
+ const rows = [
+ { uniquename: 'Ref', type: 5, isoptional: false, logicalentityname: 'account' },
+ { uniquename: 'Fallback', type: 5, isoptional: true, logicalentityname: null },
+ { uniquename: 'Note', type: 10, isoptional: true, logicalentityname: null },
+ ];
+ const entry = toCustomApiEntry({
+ uniquename: 'new_ResolveReference',
+ bindingtype: 0,
+ CustomAPIRequestParameters: rows,
+ }, parameterKindsFromRows(rows));
+ assert.deepEqual(entry.lookupParameters, {
+ Ref: { isOptional: false, logicalEntityName: 'account' },
+ Fallback: { isOptional: true },
+ });
+ assert.deepEqual(entry.parameterKinds, { Note: 'String' });
+});
+
+// The child runs the real CLI, argument parser, feature gate and Dataverse request implementation.
+// Only token acquisition and HTTP transport are replaced; the fake projects exactly the selected
+// fields so an unrequested lookup hint or response expansion cannot accidentally pass.
+const PRELOAD = path.join(__dirname, 'helpers', 'fake-custom-api-preload.js');
+const ENV = 'https://contoso.crm.dynamics.com';
+const PRIMITIVE_KINDS = new Set([
+ 'Boolean', 'DateTime', 'Decimal', 'Float', 'Integer',
+ 'Money', 'Picklist', 'String', 'StringArray', 'Guid',
+]);
+
+function api(name, overrides = {}) {
+ return {
+ customapiid: '11111111-1111-4111-8111-111111111111',
+ uniquename: name,
+ name,
+ displayname: name,
+ isfunction: false,
+ bindingtype: 0,
+ boundentitylogicalname: null,
+ isprivate: false,
+ CustomAPIRequestParameters: [],
+ CustomAPIResponseProperties: [],
+ ...overrides,
+ };
+}
+
+function discover({ apis, entities, enabled = '1', refuse, unreadable, responseBody } = {}) {
+ const dir = makeTempDir('custom-api-discovery-');
+ const fixturePath = path.join(dir, 'fixture.json');
+ const logPath = path.join(dir, 'requests.json');
+ fs.writeFileSync(fixturePath, JSON.stringify({ apis: apis || [], refuse, unreadable, responseBody }));
+ const env = {
+ ...process.env,
+ FAKE_CUSTOM_API_FIXTURE: fixturePath,
+ FAKE_CUSTOM_API_LOG: logPath,
+ POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1',
+ POWER_PLATFORM_SKILLS_TELEMETRY_PCF_OPTOUT: '1',
+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: '1',
+ };
+ if (enabled === null) delete env.GENPAGE_ENABLE_CUSTOM_API;
+ else env.GENPAGE_ENABLE_CUSTOM_API = enabled;
+ const argv = ['--require', PRELOAD, scriptPath, ENV];
+ if (entities) argv.push('--entities', entities);
+ const result = spawnSync(process.execPath, argv, { cwd: dir, env, encoding: 'utf8' });
+ assert.ifError(result.error);
+ assert.equal(result.signal, null, 'discovery must exit normally');
+ const requests = JSON.parse(fs.readFileSync(logPath, 'utf8'));
+ return { ...result, requests, output: result.stdout.trim() ? JSON.parse(result.stdout) : null };
+}
+
+test('discovery selects privacy, lookup hints and response types in one bounded inline query', () => {
+ const result = discover({ apis: [api('new_Primitive')], entities: 'account,contact' });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.requests.length, 1, 'no per-API request-parameter queries');
+ const query = new URL(result.requests[0].url).searchParams;
+ assert.ok(query.get('$select').split(',').includes('isprivate'), 'privacy is part of discovery metadata');
+ assert.equal(query.get('$filter'),
+ "isprivate eq false and (bindingtype eq 0 or (boundentitylogicalname eq 'account' or boundentitylogicalname eq 'contact'))");
+ assert.equal(query.get('$expand'),
+ 'CustomAPIRequestParameters($select=uniquename,type,isoptional,logicalentityname),CustomAPIResponseProperties($select=type)');
+});
+
+test('discovery excludes private, complex request/response and collection-bound APIs', () => {
+ const result = discover({
+ entities: 'account',
+ apis: [
+ api('new_ZPrimitive', { CustomAPIRequestParameters: [{ uniquename: 'Amount', type: 2, isoptional: false }] }),
+ api('new_PrivateGlobal', { isprivate: true }),
+ api('new_PrivateBound', { isprivate: true, bindingtype: 1, boundentitylogicalname: 'account' }),
+ ...[3, 4].map((type) => api(`new_ComplexInput${type}`, {
+ CustomAPIRequestParameters: [{ uniquename: 'Payload', type, isoptional: false }],
+ })),
+ ...[3, 4].map((type) => api(`new_ComplexOutput${type}`, { CustomAPIResponseProperties: [{ type }] })),
+ api('new_Collection', { bindingtype: 2, boundentitylogicalname: 'account' }),
+ api('new_Unrelated', { bindingtype: 1, boundentitylogicalname: 'contact' }),
+ api('new_ABoundFunction', {
+ isfunction: true,
+ bindingtype: 1,
+ boundentitylogicalname: 'account',
+ CustomAPIRequestParameters: [{ uniquename: 'RecordId', type: 12, isoptional: false }],
+ CustomAPIResponseProperties: [{ type: 10 }],
+ }),
+ ],
+ });
+ assert.equal(result.status, 0, result.stderr);
+ assert.deepEqual(result.output.customApis.map((entry) => entry.name), ['new_ABoundFunction', 'new_ZPrimitive']);
+ assert.deepEqual(result.output.customApis[0], {
+ name: 'new_ABoundFunction',
+ displayName: 'new_ABoundFunction',
+ isFunction: true,
+ bindingType: 'Entity',
+ boundEntityLogicalName: 'account',
+ parameterKinds: { RecordId: 'Guid' },
+ });
+ assert.deepEqual(result.output.customApis[1].parameterKinds, { Amount: 'Decimal' });
+});
+
+test('lookup discovery retains the callable input name without emitting an unsupported kind', () => {
+ const result = discover({
+ apis: [api('new_ResolveReference', {
+ CustomAPIRequestParameters: [
+ { uniquename: 'Ref', type: 5, isoptional: false, logicalentityname: 'account' },
+ { uniquename: 'OptionalRef', type: 5, isoptional: true, logicalentityname: null },
+ { uniquename: 'Note', type: 10, isoptional: true, logicalentityname: null },
+ ],
+ CustomAPIResponseProperties: [{ type: 5 }],
+ })],
+ });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.output.customApis.length, 1, 'lookup parameters and outputs remain eligible');
+ const [entry] = result.output.customApis;
+ assert.deepEqual(entry.lookupParameters, {
+ Ref: { isOptional: false, logicalEntityName: 'account' },
+ OptionalRef: { isOptional: true },
+ });
+ assert.deepEqual(entry.parameterKinds, { Note: 'String' });
+ assert.ok(Object.values(entry.parameterKinds).every((kind) => PRIMITIVE_KINDS.has(kind)));
+});
+
+test('default-on discovery reaches the same supported result as an explicit enable', () => {
+ const input = { apis: [api('new_Primitive')] };
+ const expected = discover(input);
+ const result = discover({ ...input, enabled: null });
+ assert.equal(result.status, 0, result.stderr);
+ assert.deepEqual(result.output, expected.output);
+ assert.equal(result.requests.length, 1);
+});
+
+test('an explicit discovery opt-out makes zero requests and emits no bindings', () => {
+ const result = discover({ apis: [api('new_Primitive')], enabled: '0' });
+ assert.equal(result.status, 3);
+ assert.match(result.stderr, /disabled/i);
+ assert.equal(result.output, null);
+ assert.deepEqual(result.requests, []);
+});
+
+test('global-only discovery stays bounded, sorted and independent of the number of matching APIs', () => {
+ const result = discover({
+ apis: [
+ ...Array.from({ length: 1000 }, (_, index) => api(`new_Global${String(999 - index).padStart(4, '0')}`)),
+ api('new_BoundControl', { bindingtype: 1, boundentitylogicalname: 'account' }),
+ api('new_CollectionControl', { bindingtype: 2, boundentitylogicalname: 'account' }),
+ ],
+ });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.output.customApis.length, 1000);
+ assert.equal(result.output.customApis[0].name, 'new_Global0000');
+ assert.equal(result.output.customApis.at(-1).name, 'new_Global0999');
+ assert.equal(result.requests.length, 1);
+ const query = new URL(result.requests[0].url).searchParams;
+ assert.equal(query.get('$filter'), 'isprivate eq false and (bindingtype eq 0)');
+ assert.doesNotMatch(result.requests[0].url, /_customapiid_value/);
+ assert.ok(result.requests[0].url.length < 1000, 'the query never grows with matched API IDs');
+});
+
+test('a refused metadata read is reported as failure rather than a successful empty discovery', () => {
+ const result = discover({ refuse: { status: 403, message: 'Custom API metadata read refused' } });
+ assert.equal(result.status, 1);
+ assert.equal(result.output, null);
+ assert.match(result.stderr, /Custom API metadata read refused/);
+ assert.equal(result.requests.length, 1);
+});
+
+test('unreadable required request or response metadata never becomes a callable binding', () => {
+ for (const unreadable of [
+ { navigation: 'CustomAPIRequestParameters', missing: true },
+ { navigation: 'CustomAPIResponseProperties', missing: true },
+ { navigation: 'CustomAPIResponseProperties', value: null },
+ ]) {
+ const result = discover({ apis: [api('new_Unreadable')], unreadable });
+ assert.equal(result.status, 1, `${JSON.stringify(unreadable)} must not be treated as empty metadata`);
+ assert.equal(result.output, null);
+ assert.match(result.stderr, /metadata|CustomAPIRequestParameters|CustomAPIResponseProperties/i);
+ }
+});
+
+test('unreadable top-level API metadata is not reported as a successful empty list', () => {
+ const result = discover({ responseBody: {} });
+ assert.equal(result.status, 1, 'an absent value array is an unreadable answer, not zero APIs');
+ assert.equal(result.output, null);
+ assert.match(result.stderr, /metadata/i);
+});
+
+test('request and response rows with unreadable types are refused before binding projection', () => {
+ for (const navigation of ['CustomAPIRequestParameters', 'CustomAPIResponseProperties']) {
+ const result = discover({ apis: [api('new_UnreadableType', {
+ [navigation]: [{ uniquename: 'Ref', isoptional: false }],
+ })] });
+ assert.equal(result.status, 1, `${navigation} must supply readable type metadata`);
+ assert.equal(result.output, null);
+ assert.match(result.stderr, /metadata|type/i);
+ }
+});
+
+test('selected API privacy metadata must be readable rather than silently treated as public', () => {
+ const result = discover({
+ apis: [api('new_UnreadablePrivacy')],
+ unreadable: { navigation: 'isprivate', missing: true },
+ });
+ assert.equal(result.status, 1);
+ assert.equal(result.output, null);
+ assert.match(result.stderr, /metadata|private/i);
+});
+
+test('Custom API guidance separates structural lookup authoring from the ten declared wire kinds', () => {
+ const plugin = path.join(__dirname, '..', '..');
+ const builder = fs.readFileSync(path.join(plugin, 'agents', 'genpage-customapi-builder.md'), 'utf8');
+ const reference = fs.readFileSync(path.join(plugin, 'references', 'custom-api.md'), 'utf8');
+ assert.match(builder, /lookupParameters/);
+ assert.match(builder, /discovery-only/);
+ assert.match(builder, /never copy[\s\S]{0,120}lookupParameters[\s\S]{0,120}actions\.json/i);
+ const pageBuilder = fs.readFileSync(path.join(plugin, 'agents', 'genpage-page-builder.md'), 'utf8');
+ assert.match(pageBuilder, /lookup-input notes/i);
+ assert.match(reference, /\{\s*entityName,\s*id\s*\}/);
+ const kinds = /Values are `DataverseParameterKind`\s+strings:([\s\S]*?)\./.exec(reference);
+ assert.ok(kinds, 'the declared wire kind list must be explicit');
+ assert.deepEqual([...kinds[1].matchAll(/`([A-Za-z]+)`/g)].map((match) => match[1]).sort(), [...PRIMITIVE_KINDS].sort());
+});
+
+test('automatic Function invocation requires known read semantics rather than GET alone', () => {
+ const plugin = path.join(__dirname, '..', '..');
+ for (const relative of [
+ ['agents', 'genpage-customapi-builder.md'],
+ ['references', 'custom-api.md'],
+ ['agents', 'genpage-page-builder.md'],
+ ['references', 'rules.md'],
+ ]) {
+ const doc = fs.readFileSync(path.join(plugin, ...relative), 'utf8');
+ assert.match(doc, /known read semantics/i);
+ assert.doesNotMatch(doc, /Functions are read-only[\s\S]{0,80}safe to call on mount/i);
+ }
+});
+
+test('incomplete API or expanded type metadata is reported rather than treated as complete discovery', () => {
+ const root = discover({ responseBody: {
+ value: [],
+ '@odata.nextLink': 'https://contoso.crm.dynamics.com/api/data/v9.2/customapis?$skiptoken=next',
+ } });
+ assert.equal(root.status, 1, 'a continuation is not a complete API inventory');
+ assert.match(root.stderr, /metadata|incomplete/i);
+ for (const navigation of ['CustomAPIRequestParameters', 'CustomAPIResponseProperties']) {
+ const result = discover({
+ apis: [api('new_IncompleteMetadata')],
+ unreadable: { navigation: `${navigation}@odata.nextLink`, value: 'https://contoso.crm.dynamics.com/api/data/v9.2/customapis?$skiptoken=next' },
+ });
+ assert.equal(result.status, 1, `${navigation} cannot prove eligibility while incomplete`);
+ assert.match(result.stderr, /metadata|incomplete/i);
+ }
+});
+
+// A single-level collection expansion has an ordinary relationship link even when all related rows
+// are present. It is not a second page. The documented 5,000-related-row ceiling is a separate
+// completeness boundary, so the absence of a paging token alone must not authorize a capped result.
+// See: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/query/join-tables#single-expand-on-collection-valued-navigation-properties
+function singleLevelExpansionLinks(entry) {
+ const related = `${ENV}/api/data/v9.2/customapis(${entry.customapiid})`;
+ return {
+ ...entry,
+ `${related}/CustomAPIRequestParameters?$select=uniquename,type,isoptional,logicalentityname`,
+ `${related}/CustomAPIResponseProperties?$select=type`,
+ };
+}
+
+test('single-level relationship links preserve complete primitive and lookup discovery in one GET', async (t) => {
+ for (const [label, row, expectedKinds, expectedLookups] of [
+ ['primitive', api('new_LinkedPrimitive', {
+ CustomAPIRequestParameters: [{ uniquename: 'Amount', type: 2, isoptional: false }],
+ CustomAPIResponseProperties: [{ type: 10 }],
+ }), { Amount: 'Decimal' }, undefined],
+ ['lookup and empty response', api('new_LinkedLookup', {
+ CustomAPIRequestParameters: [
+ { uniquename: 'Ref', type: 5, isoptional: false, logicalentityname: 'account' },
+ { uniquename: 'Note', type: 10, isoptional: true },
+ ],
+ }), { Note: 'String' }, { Ref: { isOptional: false, logicalEntityName: 'account' } }],
+ ]) {
+ await t.test(`single-level complete links: ${label}`, () => {
+ const result = discover({ responseBody: { value: [singleLevelExpansionLinks(row)] } });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.output.customApis.length, 1);
+ assert.equal(result.output.customApis[0].name, row.uniquename);
+ assert.deepEqual(result.output.customApis[0].parameterKinds, expectedKinds);
+ assert.deepEqual(result.output.customApis[0].lookupParameters, expectedLookups);
+ assert.equal(result.requests.length, 1, 'ordinary relationship links must not be followed');
+ assert.equal(result.requests[0].method, 'GET');
+ assert.equal(result.requests[0].body, null);
+ });
+ }
+});
+
+test('single-level expansion completeness distinguishes below-limit rows from the ambiguous ceiling', async (t) => {
+ for (const navigation of ['CustomAPIRequestParameters', 'CustomAPIResponseProperties']) {
+ for (const count of [4999, 5000]) {
+ await t.test(`single-level ${navigation} with ${count} rows`, () => {
+ const rows = Array.from({ length: count }, (_, index) => navigation === 'CustomAPIRequestParameters'
+ ? { uniquename: `Input${index}`, type: 10, isoptional: false }
+ : { type: 10 });
+ const row = singleLevelExpansionLinks(api('new_ExpansionLimit', { [navigation]: rows }));
+ const result = discover({ responseBody: { value: [row] } });
+ assert.equal(result.status, count < 5000 ? 0 : 1,
+ `${navigation} at the documented ceiling cannot prove that no rows were omitted`);
+ assert.equal(result.requests.length, 1);
+ if (count < 5000) assert.equal(result.output.customApis.length, 1);
+ else {
+ assert.equal(result.output, null);
+ assert.match(result.stderr, /metadata|incomplete|limit|ambiguous/i);
+ }
+ });
+ }
+ await t.test(`single-level ${navigation} at the ceiling without a link`, () => {
+ const rows = Array.from({ length: 5000 }, (_, index) => navigation === 'CustomAPIRequestParameters'
+ ? { uniquename: `Input${index}`, type: 10, isoptional: false }
+ : { type: 10 });
+ const result = discover({ responseBody: { value: [api('new_UnannotatedLimit', { [navigation]: rows })] } });
+ assert.equal(result.status, 1, 'missing annotations do not prove an expanded collection below its cap');
+ assert.equal(result.output, null);
+ assert.equal(result.requests.length, 1);
+ });
+ }
+});
+
+test('single-level links with genuine paging or ambiguous scope fail without following any URL', async (t) => {
+ const row = singleLevelExpansionLinks(api('new_UncertainExpansion'));
+ for (const navigation of ['CustomAPIRequestParameters', 'CustomAPIResponseProperties']) {
+ const property = `${navigation}@odata.nextLink`;
+ const normal = row[property];
+ for (const [label, link] of [
+ ['paging token', `${normal}&$skiptoken=next`],
+ ['encoded paging option', `${normal}&%24skiptoken=next`],
+ ['limited related query', `${normal}&$top=1`],
+ ['wrong relationship', normal.replace(`/${navigation}?`, '/UnrelatedCollection?')],
+ ['different origin', normal.replace(ENV, 'https://example.org')],
+ ['unreadable annotation', null],
+ ]) {
+ await t.test(`single-level ${navigation}: ${label}`, () => {
+ const result = discover({ responseBody: { value: [{ ...row, [property]: link }] } });
+ assert.equal(result.status, 1);
+ assert.equal(result.output, null);
+ assert.match(result.stderr, /metadata|incomplete|unsupported|ambiguous/i);
+ assert.equal(result.requests.length, 1, 'no continuation or arbitrary relationship URL is followed');
+ });
+ }
+ }
+});
+
+test('malformed lookup names requiredness and supplied hints fail the whole discovery explicitly', async (t) => {
+ const valid = { uniquename: 'Ref', type: 5, isoptional: false, logicalentityname: 'account' };
+ for (const [label, rows, reason] of [
+ ['missing name', [{ ...valid, uniquename: undefined }], /unique.?name|input name|parameter name/i],
+ ['empty name', [{ ...valid, uniquename: '' }], /unique.?name|input name|parameter name/i],
+ ['blank name', [{ ...valid, uniquename: ' ' }], /unique.?name|input name|parameter name/i],
+ ['non-string name', [{ ...valid, uniquename: 7 }], /unique.?name|input name|parameter name/i],
+ ['prototype-setter name', [{ ...valid, uniquename: '__proto__' }], /unique.?name|input name|parameter name/i],
+ ['duplicate lookup name', [valid, { ...valid, isoptional: true }], /duplicate|unique.*name|name.*unique/i],
+ ['lookup and primitive name collision', [valid, { uniquename: 'Ref', type: 10, isoptional: false }], /duplicate|unique.*name|name.*unique/i],
+ ['missing requiredness', [{ ...valid, isoptional: undefined }], /isoptional|optional|requiredness/i],
+ ['null requiredness', [{ ...valid, isoptional: null }], /isoptional|optional|requiredness/i],
+ ['string requiredness', [{ ...valid, isoptional: 'false' }], /isoptional|optional|requiredness/i],
+ ['numeric requiredness', [{ ...valid, isoptional: 0 }], /isoptional|optional|requiredness/i],
+ ['object table hint', [{ ...valid, logicalentityname: { entityName: 'account' } }], /logicalentityname|table hint|logical entity/i],
+ ['numeric table hint', [{ ...valid, logicalentityname: 7 }], /logicalentityname|table hint|logical entity/i],
+ ['array table hint', [{ ...valid, logicalentityname: ['account'] }], /logicalentityname|table hint|logical entity/i],
+ ['blank table hint', [{ ...valid, logicalentityname: ' ' }], /logicalentityname|table hint|logical entity/i],
+ ]) {
+ await t.test(`malformed lookup metadata: ${label}`, () => {
+ const result = discover({ apis: [
+ api('new_PrimitiveControl'),
+ api('new_MetadataLookup', { CustomAPIRequestParameters: rows }),
+ ] });
+ assert.equal(result.status, 1, `${label} must not produce a successful partial binding`);
+ assert.equal(result.output, null);
+ assert.match(result.stderr, /new_MetadataLookup/);
+ assert.match(result.stderr, reason);
+ assert.equal(result.requests.length, 1);
+ });
+ }
+});
+
+test('lookup metadata keeps real boolean requiredness and legitimate absent or null hints', async (t) => {
+ for (const isoptional of [false, true]) {
+ for (const logicalentityname of [undefined, null]) {
+ await t.test(`lookup metadata keeps optional=${isoptional}, hint=${String(logicalentityname)}`, () => {
+ const result = discover({ apis: [api('new_UnrestrictedLookup', {
+ CustomAPIRequestParameters: [{ uniquename: 'Ref', type: 5, isoptional, logicalentityname }],
+ })] });
+ assert.equal(result.status, 0, result.stderr);
+ assert.deepEqual(result.output.customApis[0].lookupParameters, { Ref: { isOptional: isoptional } });
+ assert.deepEqual(result.output.customApis[0].parameterKinds, {});
+ assert.equal(result.requests.length, 1);
+ });
+ }
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/output-token-forms.test.js b/plugins/model-apps/scripts/tests/output-token-forms.test.js
new file mode 100644
index 000000000..c1b7ce0b4
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/output-token-forms.test.js
@@ -0,0 +1,611 @@
+'use strict';
+// lib/output-redaction.js — what is taken out besides a token a text spells whole: the BYTES a stream is given (a Buffer, a Uint8Array, a string the stream decodes), the token's OTHER SPELLINGS (base64 at each of the three
+// byte alignments, standard and URL-safe; percent-encoded and HTML where that differs from the token), a token a formatter CUT SHORT (util.inspect's `... N more characters`, an ellipsis, the end of a text), and a token
+// written in two PIECES (the end of one write, the start of the next). Each is held where it matters — at a real process's descriptors (`script` below runs one as a script runs: the token read from the Azure CLI, which
+// notes it and guards both streams) and at the functions — and so is what must not move: a text or bytes that hold no token are the very ones given, a framed message keeps its length, ordinary base64, URLs and HTML stay
+// as they are, JSON stays JSON, a piece shorter than the floor is left as it was written (the residual, pinned here), and every new path costs time that grows with the text. tests/output-redaction.test.js holds the
+// reader itself; tests/output-token-boundary.test.js what the plugin's own scripts write.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const path = require('node:path');
+const util = require('node:util');
+const { spawnSync } = require('node:child_process');
+const redaction = require('../lib/output-redaction.js');
+const { redactTokens, guardStream } = redaction;
+const { PARTS, TOKEN } = require('./helpers/synthetic-token.js');
+
+const MARK = '<token>';
+const FLOOR = 24;
+const OTHER = ['otherHeaderPartNotARealCredentialAAA', 'otherPayloadPartNotARealCredentialBBB', 'otherSignaturePartNotARealCredentialC'].join('.');
+// An opaque token in standard base64 with the characters a URL and HTML spell differently from the token.
+const SPECIAL = 'opaque+Token/With=Signs&And<Marks>"Quoted"-0123456789';
+const SCRIPTS = path.resolve(__dirname, '..');
+
+// Every run of FLOOR characters of a secret: what must not be left of it (a shorter piece is below the floor a piece is taken out at — the residual these tests pin where it is meant to stay).
+const windowsOf = (secret) => Array.from({ length: Math.max(0, secret.length - FLOOR + 1) }, (_, i) => secret.slice(i, i + FLOOR));
+const piecesIn = (text, secrets) => [...new Set(secrets.flatMap(windowsOf))].filter((window) => text.includes(window));
+// What a piece of the token is once written: taken out when it is FLOOR characters or more (as a text, the marker; as bytes, as many `*`), as it was written when it is shorter.
+const keptAs = (piece, mark) => (piece.length >= FLOOR ? mark(piece) : piece);
+const stars = (piece) => '*'.repeat(piece.length);
+
+// The base64 of a token as it stands inside a longer value, found by trying rather than by the module's arithmetic: the characters that stay the same whatever bytes stand before and after the token.
+function base64Of(token, alphabet) {
+ const spellings = [];
+ for (let offset = 0; offset < 3; offset += 1) {
+ const zeros = Buffer.concat([Buffer.alloc(offset, 0x00), Buffer.from(token), Buffer.alloc(3, 0x00)]).toString(alphabet);
+ const ones = Buffer.concat([Buffer.alloc(offset, 0xff), Buffer.from(token), Buffer.alloc(3, 0xff)]).toString(alphabet);
+ let from = 0;
+ while (zeros[from] !== ones[from]) from += 1;
+ let to = from;
+ while (to < zeros.length && zeros[to] === ones[to]) to += 1;
+ spellings.push(zeros.slice(from, to));
+ }
+ return spellings;
+}
+const BASE64 = [...base64Of(TOKEN, 'base64'), ...base64Of(TOKEN, 'base64url')];
+
+// A small seeded generator, so that a failure names a case that can be run again.
+function generator(seed) {
+ let state = seed >>> 0;
+ const next = () => { state = (state + 0x6d2b79f5) >>> 0; let t = state; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
+ return { next, int: (n) => Math.floor(next() * n), pick: (list) => list[Math.floor(next() * list.length)] };
+}
+
+// A script of our own in a REAL process, run from the plugin's scripts folder; its descriptors come back as bytes. `NOTE` is what a script does before it writes anything: it reads the token from the Azure CLI, which notes
+// it and puts the guards on both streams.
+const NOTE = `require('./lib/dataverse-auth.js').getAuthToken('https://contoso.crm.dynamics.com', { exec: () => ${JSON.stringify(`${TOKEN}\n`)} });`;
+function script(source, env = {}) {
+ const run = spawnSync(process.execPath, ['-e', source], { cwd: SCRIPTS, env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MODEL_APPS_OPTOUT: '1', ...env }, maxBuffer: 64 * 1024 * 1024, timeout: 120000 });
+ assert.equal(run.status, 0, run.stderr.toString());
+ return run;
+}
+
+// A message framed the way a test runner frames what it reports: four bytes that say how many follow, and then those bytes.
+function framed(text) {
+ const payload = Buffer.from(text);
+ const frame = Buffer.alloc(4 + payload.length);
+ frame.writeUInt32BE(payload.length, 0);
+ payload.copy(frame, 4);
+ return frame;
+}
+
+// ── Bytes ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+test('BYTES a script writes reach the descriptor without the token — a Buffer, a Uint8Array, a string the stream decodes (base64, hex), a framed message — each hit masked with as many `*` as it has bytes; bytes with no token are the very object given', () => {
+ const run = script(`
+ const fs = require('node:fs');
+ const seen = [];
+ const beneath = process.stdout.write;
+ process.stdout.write = function recorder(chunk, ...rest) { seen.push(chunk); return beneath.call(this, chunk, ...rest); };
+ ${NOTE}
+ const plain = Buffer.from('bytes with no token in them\\n');
+ const returned = process.stdout.write(plain);
+ const same = seen[0] === plain;
+ process.stdout.write(Buffer.from('a buffer ${TOKEN}\\n'));
+ process.stdout.write(new Uint8Array(Buffer.from('an array ${PARTS[2]}\\n')));
+ process.stdout.write(Buffer.from('decoded ${TOKEN}\\n').toString('base64'), 'base64');
+ process.stdout.write(Buffer.from('decoded ${PARTS[0]}\\n').toString('hex'), 'hex');
+ const payload = Buffer.from(JSON.stringify({ test: 'a test', error: 'bearer ${TOKEN}' }));
+ const frame = Buffer.alloc(4 + payload.length); frame.writeUInt32BE(payload.length, 0); payload.copy(frame, 4);
+ process.stdout.write(frame, () => fs.writeSync(2, JSON.stringify({ same, returned: typeof returned, wrapped: process.stdout.write.name, frameIntact: frame.includes('${TOKEN}') })));
+ `);
+ const frame = framed(JSON.stringify({ test: 'a test', error: `bearer ${stars(TOKEN)}` }));
+ const expected = Buffer.concat([
+ Buffer.from('bytes with no token in them\n'),
+ Buffer.from(`a buffer ${stars(TOKEN)}\n`),
+ Buffer.from(`an array ${stars(PARTS[2])}\n`),
+ Buffer.from(`decoded ${stars(TOKEN)}\n`),
+ Buffer.from(`decoded ${stars(PARTS[0])}\n`),
+ frame,
+ ]);
+ const written = run.stdout.toString('latin1');
+ assert.deepEqual(piecesIn(written, [TOKEN]), [], 'no piece of the token reached stdout as bytes');
+ assert.equal(written, expected.toString('latin1'), 'every hit is masked byte for byte, and nothing else changed');
+ const frameAt = run.stdout.length - frame.length;
+ assert.equal(run.stdout.readUInt32BE(frameAt), frame.length - 4, 'the frame still says how many bytes follow it');
+ assert.deepEqual(JSON.parse(run.stdout.subarray(frameAt + 4).toString()), { test: 'a test', error: `bearer ${stars(TOKEN)}` });
+ assert.deepEqual(JSON.parse(run.stderr.toString()), { same: true, returned: 'boolean', wrapped: 'writeWithoutTokens', frameIntact: true },
+ 'bytes with no token are the very object given; write returns what it returned and calls the callback; the caller\'s own bytes are not written into — a COPY is masked');
+});
+
+test('maskTokenBytes: the very bytes given when they hold no token (a Buffer, a Uint8Array, empty); a copy of the same length with each hit masked when they do — the token, a part, a spelling, a framed message', () => {
+ const { maskTokenBytes } = redaction;
+ const plain = Buffer.from('no token in these bytes');
+ assert.equal(maskTokenBytes(plain, [TOKEN]), plain);
+ const array = new Uint8Array([1, 2, 3, 0xff]);
+ assert.equal(maskTokenBytes(array, [TOKEN]), array);
+ const empty = Buffer.alloc(0);
+ assert.equal(maskTokenBytes(empty, [TOKEN]), empty);
+ const noTokens = Buffer.from(`bearer ${TOKEN}`);
+ assert.equal(maskTokenBytes(noTokens, []), noTokens, 'no token, nothing to mask');
+ assert.equal(maskTokenBytes('a text', [TOKEN]), 'a text', 'what is not bytes is returned as it is');
+ const given = Buffer.from(`a ${TOKEN} b ${PARTS[1]} c ${BASE64[1]} d`);
+ const copy = Buffer.from(given);
+ const masked = maskTokenBytes(given, [TOKEN]);
+ assert.notEqual(masked, given);
+ assert.deepEqual(given, copy, 'the bytes given are not written into');
+ assert.equal(masked.length, given.length);
+ assert.equal(masked.toString(), `a ${'*'.repeat(TOKEN.length)} b ${'*'.repeat(PARTS[1].length)} c ${'*'.repeat(BASE64[1].length)} d`);
+ const frame = framed(JSON.stringify({ diagnostic: `Rejected bearer ${TOKEN}` }));
+ const maskedFrame = maskTokenBytes(frame, [TOKEN]);
+ assert.equal(maskedFrame.length, frame.length);
+ assert.equal(maskedFrame.readUInt32BE(0), frame.length - 4);
+ assert.deepEqual(JSON.parse(maskedFrame.subarray(4).toString()), { diagnostic: `Rejected bearer ${'*'.repeat(TOKEN.length)}` });
+ // A Uint8Array that is not a Buffer comes back as bytes too, and a multi-byte character beside the token is left whole.
+ const wide = new Uint8Array(Buffer.from(`日本語 ${TOKEN} 🧪`));
+ assert.equal(Buffer.from(maskTokenBytes(wide, [TOKEN])).toString(), `日本語 ${'*'.repeat(TOKEN.length)} 🧪`);
+});
+
+test('a guarded stream hands bytes to the write beneath it with everything else as it was — the encoding, the callback, the receiver and what write returns — and masks only where the token is', () => {
+ const { maskTokenBytes } = redaction;
+ const chunks = [];
+ const calls = [];
+ const stream = { write(chunk, ...rest) { chunks.push(chunk); calls.push([this, rest]); return 'returned'; } };
+ guardStream(stream, (chunk) => (typeof chunk === 'string' ? redactTokens(chunk, [TOKEN], { edges: true }) : maskTokenBytes(chunk, [TOKEN], { edges: true })));
+ const done = () => {};
+ const clean = Buffer.from('clean bytes');
+ assert.equal(stream.write(clean, 'utf8', done), 'returned');
+ assert.equal(chunks[0], clean, 'the very Buffer');
+ assert.deepEqual(calls[0], [stream, ['utf8', done]]);
+ assert.equal(stream.write(Buffer.from(`x ${TOKEN}`), done), 'returned');
+ assert.equal(chunks[1].toString(), `x ${'*'.repeat(TOKEN.length)}`);
+ assert.deepEqual(calls[1], [stream, [done]]);
+ const hex = Buffer.from(`clean ${PARTS[0].slice(0, FLOOR - 1)}`).toString('hex');
+ stream.write(hex, 'hex', done);
+ assert.equal(chunks[2], hex, 'a string the stream decodes is the very string when its bytes hold no token');
+ assert.deepEqual(calls[2][1], ['hex', done], 'with its encoding');
+ stream.write(Buffer.from(`y ${TOKEN}`).toString('base64'), 'base64', done);
+ assert.equal(Buffer.isBuffer(chunks[3]) && chunks[3].toString(), `y ${'*'.repeat(TOKEN.length)}`, 'its bytes, masked, in its place');
+ assert.deepEqual(calls[3][1], ['base64', done], 'and the encoding argument as it was given: a stream ignores it for bytes');
+ assert.equal(stream.write(new Uint16Array([1, 2])) && chunks[4] instanceof Uint16Array, true, 'what is neither text nor bytes is passed on for the stream to refuse, as it always was');
+});
+
+// ── Other spellings of a known token ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+test('the token in BASE64 — standard or URL-safe, at each of the three byte alignments, inside a longer value, folded onto lines as MIME folds it, in JSON with an escaped slash — is taken out; what is left of the value holds no piece of it', () => {
+ for (const alphabet of ['base64', 'base64url']) {
+ for (const before of ['', 'B', 'Be', 'Bearer ', 'Authorization: Bearer ']) {
+ for (const after of ['', 'x', '\r\n', ' and the rest of the header']) {
+ const encoded = Buffer.from(`${before}${TOKEN}${after}`).toString(alphabet);
+ for (const written of [encoded, encoded.match(/.{1,76}/g).join('\r\n'), JSON.stringify({ blob: encoded }).replace(/\//g, '\\/')]) {
+ const cleaned = redactTokens(`blob ${written} end`, [TOKEN]);
+ assert.deepEqual(piecesIn(cleaned, BASE64), [], `${alphabet} of ${JSON.stringify(before)} + token + ${JSON.stringify(after)}: ${cleaned}`);
+ assert.ok(cleaned.includes(MARK));
+ }
+ }
+ }
+ }
+ // JSON that held it is JSON still.
+ const json = JSON.stringify({ header: Buffer.from(`Bearer ${TOKEN}`).toString('base64'), ok: false });
+ assert.equal(JSON.parse(redactTokens(json, [TOKEN])).ok, false);
+});
+
+test('a token PERCENT-ENCODED (upper- or lower-case hex) or spelled with HTML ENTITIES is taken out where that spelling differs from the token', () => {
+ const upper = encodeURIComponent(SPECIAL);
+ const lower = upper.replace(/%[0-9A-F]{2}/g, (escape) => escape.toLowerCase());
+ const html = SPECIAL.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
+ for (const spelled of [upper, lower, html]) {
+ assert.notEqual(spelled, SPECIAL);
+ assert.equal(redactTokens(`https://contoso.example/cb?access_token=${spelled}&state=1`, [SPECIAL]), `https://contoso.example/cb?access_token=${MARK}&state=1`, spelled);
+ assert.equal(redactTokens(`<input value="${spelled}">`, [SPECIAL]), `<input value="${MARK}">`, spelled);
+ assert.deepEqual(JSON.parse(redactTokens(JSON.stringify({ url: `a=${spelled}` }), [SPECIAL])), { url: `a=${MARK}` });
+ }
+ assert.equal(redactTokens(`plain ${SPECIAL} end`, [SPECIAL]), `plain ${MARK} end`, 'and the token as it is, as before');
+});
+
+test('spellingsOf is the list of the other spellings taken out: base64 of the token, standard and URL-safe, at each alignment; percent and HTML spellings only where they differ — a JWT has none; nothing shorter than the floor', () => {
+ const { spellingsOf } = redaction;
+ const jwt = spellingsOf(TOKEN);
+ assert.deepEqual([...jwt].sort(), [...new Set(BASE64)].sort(), 'what is spelled the same whatever stands around the token, at each of the three alignments, in both alphabets — and nothing else: a JWT is base64url and dots');
+ assert.ok(jwt.every((spelling) => spelling.length >= FLOOR));
+ const special = spellingsOf(SPECIAL);
+ const upper = encodeURIComponent(SPECIAL);
+ for (const spelling of [upper, upper.replace(/%[0-9A-F]{2}/g, (escape) => escape.toLowerCase()), SPECIAL.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')]) {
+ assert.ok(special.includes(spelling), spelling);
+ }
+ assert.ok(!special.includes(SPECIAL), 'the token itself is a needle already');
+ assert.deepEqual(spellingsOf('short-but-a-token'), [], 'a token whose spellings are all shorter than the floor has none');
+ assert.deepEqual(spellingsOf(''), []);
+ assert.deepEqual(spellingsOf(undefined), []);
+ assert.deepEqual(redaction.needlesOf(TOKEN), [TOKEN, PARTS[2], PARTS[1], PARTS[0]], 'and the list the Dataverse client scrubs with is what it was');
+});
+
+// ── A token a formatter cut short ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+// A string util.inspect cuts after `kept` characters of the token: it prints the first 10,000 characters of a string (https://nodejs.org/api/util.html#utilinspectobject-options, `maxStringLength`).
+const cutAfter = (lead, kept) => `${lead}${'x'.repeat(10000 - lead.length - kept)}${TOKEN}`;
+
+test('a token util.inspect CUT SHORT — in a property, in colours, in the last of several pieces, between double quotes, in JSON — loses the piece it printed when that piece is 24 characters or more; the count after it stays', () => {
+ for (const kept of [FLOOR, 30, PARTS[0].length + 1 + 30, TOKEN.length - 1]) {
+ const printings = [
+ util.inspect({ body: cutAfter('', kept) }),
+ util.inspect({ body: cutAfter('', kept) }, { colors: true }),
+ util.inspect({ error: { body: cutAfter('line one\n', kept) } }),
+ util.inspect({ body: cutAfter("it's ", kept) }),
+ util.inspect([cutAfter('', kept)], { breakLength: Infinity }),
+ ];
+ for (const printed of printings) {
+ assert.equal(printed.split(TOKEN.slice(0, kept)).length, 2, 'the printed text holds the piece once');
+ assert.match(printed, /\.\.\. \d+ more characters?/);
+ const cleaned = redactTokens(printed, [TOKEN]);
+ assert.equal(cleaned, printed.replace(TOKEN.slice(0, kept), MARK), `${kept} characters kept: ${JSON.stringify(cleaned.slice(-120))}`);
+ // In JSON too, which is JSON still. (Not the printing in colours: JSON spells its codes as `\u001b[39m`, which the reader reads as characters, between the pieces of a token as after a cut.)
+ if (!printed.includes('\u001b')) assert.equal(JSON.parse(redactTokens(JSON.stringify({ log: printed }), [TOKEN])).log, cleaned);
+ }
+ }
+ // Below the floor the piece is left: it would be taken out of ordinary words.
+ for (const kept of [10, FLOOR - 1]) {
+ const printed = util.inspect({ body: cutAfter('', kept) });
+ assert.equal(redactTokens(printed, [TOKEN]), printed);
+ }
+});
+
+test('a token cut to a length by hand — an ellipsis after it, `...` or `…`, as the plugin\'s own reasons cut a platform message — loses the piece before the ellipsis when it is 24 characters or more', () => {
+ const reason = `HTTP 400: Principal user rejected bearer ${TOKEN} for this write`;
+ const at = reason.indexOf(TOKEN);
+ for (const kept of [FLOOR, 50, TOKEN.length - 3]) {
+ for (const ellipsis of ['...', '…']) {
+ const brief = `${reason.slice(0, at + kept)}${ellipsis}`;
+ assert.equal(redactTokens(brief, [TOKEN]), `${reason.slice(0, at)}${MARK}${ellipsis}`, `${kept} ${ellipsis}`);
+ assert.deepEqual(JSON.parse(redactTokens(JSON.stringify({ error: brief, code: 1 }), [TOKEN])), { error: `${reason.slice(0, at)}${MARK}${ellipsis}`, code: 1 });
+ }
+ }
+ const short = `${reason.slice(0, at + FLOOR - 1)}...`;
+ assert.equal(redactTokens(short, [TOKEN]), short, 'below the floor the piece is left');
+});
+
+test('REAL PROCESS: a script that prints an error whose body the console cuts inside the token — plainly, in colours, with %o — writes no piece of 24 characters of it; the count of what was cut stays', () => {
+ for (const env of [{}, { FORCE_COLOR: '1' }]) {
+ const run = script(`
+ ${NOTE}
+ const error = new Error('the request failed');
+ error.body = ${JSON.stringify(cutAfter('', 30))};
+ console.error(error);
+ console.error({ answer: { body: ${JSON.stringify(cutAfter('Rejected bearer ', PARTS[0].length + 1 + 30))} } });
+ console.log('%o', ${JSON.stringify(cutAfter('', FLOOR))});
+ `, env);
+ const written = `${run.stdout.toString()}${run.stderr.toString()}`;
+ assert.deepEqual(piecesIn(written, [TOKEN]), [], `${JSON.stringify(env)}: no piece of the token`);
+ assert.equal((written.match(/more characters/g) || []).length, 3, 'each cut is still said');
+ assert.equal((written.match(/<token>/g) || []).length, 3);
+ }
+});
+
+// ── A token written in two pieces ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+// Where a write is split, in the token: inside the first part, at its end, after the dot, in the middle, and at the edges of the floor on either side.
+const SPLITS = [1, 10, FLOOR - 1, FLOOR, 30, PARTS[0].length, PARTS[0].length + 1, 60, TOKEN.length - FLOOR, TOKEN.length - FLOOR + 1, TOKEN.length - 1];
+
+test('REAL PROCESS: a token written in two PIECES — the end of one write, the start of the next, on stdout as text and on stderr as bytes, with a line break between them too — loses each piece of 24 characters or more; a shorter one is left as it was written, and nothing is held back', () => {
+ const run = script(`
+ ${NOTE}
+ for (const split of ${JSON.stringify(SPLITS)}) {
+ process.stdout.write('[' + split + '] bearer ' + ${JSON.stringify(TOKEN)}.slice(0, split));
+ process.stdout.write(${JSON.stringify(TOKEN)}.slice(split) + ' end\\n');
+ process.stderr.write(Buffer.from('[' + split + '] bearer ' + ${JSON.stringify(TOKEN)}.slice(0, split)));
+ process.stderr.write(Buffer.from(${JSON.stringify(TOKEN)}.slice(split) + ' end\\n'));
+ }
+ process.stdout.write(${JSON.stringify(TOKEN)}.slice(0, 40) + '\\n');
+ process.stdout.write(' ' + ${JSON.stringify(TOKEN)}.slice(40) + '\\n');
+ process.stdout.write('{"error":"bearer ' + ${JSON.stringify(TOKEN)}.slice(0, 50));
+ process.stdout.write(${JSON.stringify(TOKEN)}.slice(50) + '","ok":false}\\n');
+ `);
+ const textLines = SPLITS.map((split) => `[${split}] bearer ${keptAs(TOKEN.slice(0, split), () => MARK)}${keptAs(TOKEN.slice(split), () => MARK)} end`);
+ const byteLines = SPLITS.map((split) => `[${split}] bearer ${keptAs(TOKEN.slice(0, split), stars)}${keptAs(TOKEN.slice(split), stars)} end`);
+ const stdout = run.stdout.toString();
+ const stderr = run.stderr.toString();
+ assert.deepEqual(piecesIn(`${stdout}${stderr}`, [TOKEN]), [], 'no piece of 24 characters of the token reached either descriptor');
+ assert.equal(stdout, `${[...textLines, MARK, ` ${MARK}`, `{"error":"bearer ${MARK}${MARK}","ok":false}`].join('\n')}\n`);
+ assert.equal(stderr, `${byteLines.join('\n')}\n`);
+ assert.deepEqual(JSON.parse(stdout.trim().split('\n').pop()), { error: `bearer ${MARK}${MARK}`, ok: false }, 'the two halves of a JSON line are JSON together');
+});
+
+test('a token written in pieces at the function: the end of a text that begins a needle and the start of one that ends it, each of 24 characters or more, with folds and escapes in them; a piece from the middle of a part, and the start read through an escape\'s letters, are the residual', () => {
+ const edges = { edges: true };
+ for (const split of SPLITS) {
+ const head = TOKEN.slice(0, split);
+ const tail = TOKEN.slice(split);
+ assert.equal(redactTokens(`bearer ${head}`, [TOKEN], edges), `bearer ${keptAs(head, () => MARK)}`, `the end of a write, ${split}`);
+ assert.equal(redactTokens(`${tail} end`, [TOKEN], edges), `${keptAs(tail, () => MARK)} end`, `the start of a write, ${split}`);
+ assert.equal(maskTokenBytesText(`bearer ${head}`), `bearer ${keptAs(head, stars)}`, `bytes, the end, ${split}`);
+ assert.equal(maskTokenBytesText(`${tail} end`), `${keptAs(tail, stars)} end`, `bytes, the start, ${split}`);
+ }
+ // Read as any text is read: folded, escaped, in colours, with white space before the start and after the end.
+ const folded = (piece) => piece.match(/.{1,7}/g).join('\\r\\n ');
+ assert.equal(redactTokens(`bearer ${folded(TOKEN.slice(0, 50))}\n`, [TOKEN], edges), `bearer ${MARK}\n`);
+ assert.equal(redactTokens(` \u001b[32m${folded(TOKEN.slice(50))}\u001b[39m end`, [TOKEN], edges), ` \u001b[32m${MARK}\u001b[39m end`);
+ assert.equal(redactTokens(`\\u0073${TOKEN.slice(1, 40)}`, [TOKEN], edges), MARK);
+ // Only with `edges`: a whole text a caller hands over (a file, a test's text) is read as it always was.
+ assert.equal(redactTokens(`bearer ${TOKEN.slice(0, 30)}`, [TOKEN]), `bearer ${TOKEN.slice(0, 30)}`);
+ assert.equal(redactTokens(`${TOKEN.slice(90)} end`, [TOKEN]), `${TOKEN.slice(90)} end`);
+ // The residual: a piece from the middle of a part is neither the start nor the end of a needle (a token written in three pieces or more); and the start of a write is read on its first reading, so a letter that a
+ // literal backslash before it makes an escape (`\n` and then the rest of the token) is read as the escape — that one character is left, the rest is taken out.
+ const middle = TOKEN.slice(PARTS[0].length + 3, PARTS[0].length + 33);
+ assert.equal(redactTokens(middle, [TOKEN], edges), middle);
+ const fromN = TOKEN.slice(PARTS[0].length + 3);
+ assert.equal(fromN[0], 'n');
+ assert.equal(redactTokens(`\\${fromN} end`, [TOKEN], edges), `\\n${MARK} end`);
+ // JSON written in two pieces is JSON again when they are put together.
+ const document = JSON.stringify({ error: `Rejected bearer ${TOKEN}`, ok: false });
+ const at = document.indexOf(TOKEN) + 45;
+ assert.deepEqual(JSON.parse(redactTokens(document.slice(0, at), [TOKEN], edges) + redactTokens(document.slice(at), [TOKEN], edges)), { error: `Rejected bearer ${MARK}${MARK}`, ok: false });
+});
+
+// The bytes of a text, masked as a stream masks them, read back as text.
+function maskTokenBytesText(text) {
+ return Buffer.from(redaction.maskTokenBytes(Buffer.from(text), [TOKEN], { edges: true })).toString();
+}
+
+// ── Exactness: a prefix or a suffix spelled every way the reader reads a text ──────────────────────────────────────────────────────────────────────────
+
+const unicode = (char, upper) => { const hex = char.charCodeAt(0).toString(16).padStart(4, '0'); return `\\u${upper ? hex.toUpperCase() : hex}`; };
+// What may stand between two characters of a token (white space, a JSON line break, JSON inside JSON, a stray backslash, a colour code, util.inspect's join of two pieces), and what may stand after its last one or
+// before its first: the folds that spell no character, which a span does not take with it.
+const INNER = ['', '', '', ' ', '\n', '\r\n ', '\t', '\\r\\n', '\\n ', '\\\\r\\\\n ', '\\u000a', '\u001b[32m', "' +\n '", '\\'];
+const OUTER = ['', ' ', '\n', '\r\n ', '\t', '\u001b[39m'];
+const CUTS = ["'... 9876 more characters", "'\u001b[39m... 1 more character", '"... 12 more characters', '`... 3 more characters', '...', '…'];
+
+// `chars` spelled with folds from `gaps` between them and a \u escape for some; with `strays`, a stray backslash before some of them too. The first is always the character itself or its \u escape: what a reader reads first.
+function spell(random, chars, gaps, strays) {
+ return [...chars].map((char, i) => {
+ let spelled = random.next() < 0.25 ? unicode(char, random.next() < 0.5) : char;
+ if (strays && i > 0 && random.next() < 0.1) spelled = `\\${spelled}`;
+ return (i > 0 ? random.pick(gaps) : '') + spelled;
+ }).join('');
+}
+
+test('a prefix of a needle spelled with folds, escapes, stray backslashes and colour codes, cut by util.inspect, an ellipsis or the end of a write, is taken out from its first character to its last — and only that: the folds after it and the cut stay', () => {
+ for (let seed = 1; seed <= 500; seed += 1) {
+ const random = generator(seed);
+ const length = FLOOR + random.int(TOKEN.length - FLOOR);
+ const prefix = spell(random, TOKEN.slice(0, length), INNER, true);
+ const after = random.pick(OUTER);
+ const before = 'Rejected bearer ';
+ if (random.next() < 0.5) {
+ const cut = random.pick(CUTS);
+ const text = `${before}${prefix}${after}${cut} and on`;
+ assert.equal(redactTokens(text, [TOKEN]), `${before}${MARK}${after}${cut} and on`, `seed ${seed}: ${JSON.stringify(text)}`);
+ } else {
+ const text = `${before}${prefix}${after}`;
+ assert.equal(redactTokens(text, [TOKEN], { edges: true }), `${before}${MARK}${after}`, `seed ${seed}: ${JSON.stringify(text)}`);
+ }
+ }
+});
+
+test('a suffix of a needle at the start of a write, spelled with folds, escapes and colour codes, is taken out from its first character to its last; the folds before it and the text after it stay', () => {
+ // No stray backslash here: the start of a write is read on its first reading, so a stray one before a letter that begins an escape is the residual pinned above.
+ const gaps = INNER.filter((gap) => gap !== '\\');
+ for (let seed = 1; seed <= 500; seed += 1) {
+ const random = generator(seed);
+ const from = 1 + random.int(TOKEN.length - FLOOR);
+ const lead = random.pick(OUTER);
+ const after = random.pick(OUTER);
+ const text = `${lead}${spell(random, TOKEN.slice(from), gaps, false)}${after} for this write`;
+ assert.equal(redactTokens(text, [TOKEN], { edges: true }), `${lead}${MARK}${after} for this write`, `seed ${seed}: ${JSON.stringify(text)}`);
+ }
+});
+
+// ── What must not move ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+test('ordinary text and data are the very string they were — base64 of other bytes, of another token, folded; URLs and HTML; ellipses; util.inspect cutting a string that holds no token — read whole or as a write', () => {
+ const random = generator(7);
+ const noise = Buffer.from(Array.from({ length: 300000 }, () => random.int(256)));
+ const texts = [
+ noise.toString('base64'), noise.toString('base64url'), noise.toString('base64').match(/.{1,76}/g).join('\r\n'),
+ Buffer.from(`Bearer ${OTHER}`).toString('base64'), Buffer.from(`Bearer ${OTHER}`).toString('base64url'),
+ 'https://contoso.example/a%20b?x=%2F%2B%3D&y=caf%C3%A9 — &amp; &lt;b&gt; &quot;q&quot; &#39;',
+ `Waiting for the platform... done. Loading… ${PARTS[0].slice(0, FLOOR - 1)}... ${PARTS[0].slice(1)}... ${TOKEN.slice(PARTS[0].length + 3, PARTS[0].length + 33)}…`,
+ util.inspect({ body: 'x'.repeat(20000) }), util.inspect({ body: 'x'.repeat(20000) }, { colors: true }), util.inspect('it\'s'.repeat(5000)),
+ JSON.stringify({ list: [1, 2, 3], text: 'nothing to see... here…' }, null, 2),
+ ];
+ for (const text of texts) {
+ assert.equal(redactTokens(text, [TOKEN, SPECIAL]), text);
+ assert.equal(redactTokens(text, [TOKEN, SPECIAL], { edges: true }), text);
+ }
+ const bytes = Buffer.from(texts.join('\n'));
+ assert.equal(redaction.maskTokenBytes(bytes, [TOKEN, SPECIAL], { edges: true }), bytes);
+ assert.equal(redaction.maskTokenBytes(noise, [TOKEN, SPECIAL], { edges: true }), noise);
+});
+
+// ── Cost ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+test('every new path costs time that grows with what it reads — bytes of any size and a needle\'s start over and over, many cuts, many small writes, the spellings in a large text — and the bound on readings still fails closed on a cut', (t) => {
+ const started = Date.now();
+ const { maskTokenBytes } = redaction;
+ const filler = 'The platform answered with a diagnostic that says nothing about credentials.\r\n';
+ // Twenty megabytes of bytes with the token in the middle; bytes that are a needle's first 2,999 characters over and over.
+ const big = Buffer.from(filler.repeat(260000));
+ const middle = Buffer.concat([big.subarray(0, big.length / 2), Buffer.from(TOKEN), big.subarray(big.length / 2)]);
+ const masked = maskTokenBytes(middle, [TOKEN], { edges: true });
+ assert.equal(masked.length, middle.length);
+ assert.equal(masked.indexOf(TOKEN), -1);
+ assert.equal(maskTokenBytes(big, [TOKEN], { edges: true }), big);
+ const needle = `${'a'.repeat(2999)}Z`;
+ const nearly = Buffer.alloc(4 * 1024 * 1024, 'a');
+ assert.equal(maskTokenBytes(nearly, [needle]), nearly);
+ assert.equal(maskTokenBytes(Buffer.concat([Buffer.from('Z'), nearly, Buffer.from('Z')]), [needle], { edges: true }).toString('latin1').endsWith(`${'*'.repeat(3000)}`), true);
+ // A text of a hundred thousand cuts, each after a piece of the token; and a hundred thousand quotes and ellipses while a needle is being read.
+ const cuts = `x ${TOKEN.slice(0, 30)}'... 5 more characters\n`.repeat(100000);
+ assert.equal(redactTokens(cuts, [TOKEN]), `x ${MARK}'... 5 more characters\n`.repeat(100000));
+ const quotes = `${TOKEN.slice(0, 30)}${"'.".repeat(200000)}`;
+ assert.equal(redactTokens(quotes, [TOKEN]), quotes);
+ // Cuts while the most readings a real text keeps are alive: escapes that may each be the next letter of a needle that is one letter over and over, then a cut — twenty thousand times.
+ const letters = `${'n'.repeat(60)}Z`;
+ const readings = `${'\\n'.repeat(60)}'... 1 more character `.repeat(20000);
+ assert.equal(redactTokens(readings, [letters]), `${MARK}'... 1 more character `.repeat(20000));
+ // A hundred thousand small writes, each the start of a needle, and a hundred thousand ordinary lines, through a stream guarded as a script's are (the tokens the process obtained, prepared once); and a large text with
+ // each spelling in it.
+ const writes = script(`
+ ${NOTE}
+ const fs = require('node:fs');
+ const chunks = [];
+ const fake = { write(chunk) { chunks.push(chunk); return true; } };
+ require('./lib/output-redaction.js').guardStream(fake);
+ const started = Date.now();
+ for (let i = 0; i < 100000; i += 1) fake.write(${JSON.stringify(TOKEN.slice(0, 30))});
+ for (let i = 0; i < 100000; i += 1) fake.write('progress: step ' + i + ' of 100000 done\\n');
+ const ms = Date.now() - started;
+ fs.writeSync(2, JSON.stringify({ ms, marked: chunks.slice(0, 100000).every((chunk) => chunk === '<token>'), lines: chunks.slice(100000).every((chunk, i) => chunk === 'progress: step ' + i + ' of 100000 done\\n') }));
+ `);
+ const measured = JSON.parse(writes.stderr.toString());
+ assert.deepEqual({ marked: measured.marked, lines: measured.lines }, { marked: true, lines: true });
+ t.diagnostic(`${measured.ms} ms for 200,000 small writes`);
+ const spelled = `${filler.repeat(15000)}${BASE64.join(' ')}${filler.repeat(15000)}`;
+ assert.equal(redactTokens(spelled, [TOKEN], { edges: true }), `${filler.repeat(15000)}${BASE64.map(() => MARK).join(' ')}${filler.repeat(15000)}`);
+ t.diagnostic(`${Date.now() - started} ms for all of the above`);
+ assert.ok(Date.now() - started < 30000, 'linear: tens of megabytes and the worst cases finish in a moment');
+ // Past its bound of readings the search fails rather than guess — at a cut and at the end of a write too — and a guarded stream writes a notice, not the text.
+ const crafted = `${'\\n'.repeat(400)}'... 5 more characters`;
+ const longNeedle = `${'n'.repeat(300)}Z`;
+ assert.throws(() => redactTokens(crafted, [longNeedle], { edges: true }), (error) => error instanceof RangeError);
+ const guarded = [];
+ const failing = { write(chunk) { guarded.push(chunk); return true; } };
+ guardStream(failing, (chunk) => redactTokens(chunk, [longNeedle], { edges: true }));
+ failing.write(`${'\\n'.repeat(400)}`);
+ assert.match(guarded[0], /^\[output withheld/);
+});
+
+// ── An escape split between two writes ────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+// A JSON line whose token has an escape in it — `\/` (the token holds a `/`, as a standard-base64 one does), `\u0073` (a character JSON may escape), a literal `\\` (a stray backslash between two characters of the
+// token), the `\r\n` of a fold — written in two pieces split at every place in and around the escape. Each piece of the token is 24 characters or more, so each is taken out; the escape is kept whole wherever it was cut.
+const SPLIT_ESCAPES = [
+ { name: '\\/', token: `${'A'.repeat(24)}/${'B'.repeat(27)}`, spelled: `${'A'.repeat(24)}\\/${'B'.repeat(27)}` },
+ { name: '\\u0073', token: `${'A'.repeat(24)}s${'B'.repeat(27)}`, spelled: `${'A'.repeat(24)}\\u0073${'B'.repeat(27)}` },
+ { name: '\\\\', token: `${'A'.repeat(24)}${'B'.repeat(27)}`, spelled: `${'A'.repeat(24)}\\\\${'B'.repeat(27)}` },
+ { name: '\\r\\n', token: `${'A'.repeat(24)}${'B'.repeat(27)}`, spelled: `${'A'.repeat(24)}\\r\\n${'B'.repeat(27)}` },
+];
+const splitLines = () => SPLIT_ESCAPES.flatMap(({ name, token, spelled }) => {
+ const line = `{"error":"bearer ${spelled}","ok":false}\n`;
+ const escapeAt = line.indexOf('\\');
+ const escapeEnd = line.lastIndexOf('\\') + (name === '\\u0073' ? 6 : 2);
+ const cases = [];
+ for (let split = escapeAt - 1; split <= escapeEnd + 1; split += 1) cases.push({ name, token, split, first: line.slice(0, split), second: line.slice(split) });
+ return cases;
+});
+
+test('REAL PROCESS: an escape split between two writes — `\\/`, `\\u0073`, `\\\\`, `\\r\\n`, cut at every place in and around it — is kept whole: the JSON the writes make together is JSON still, and no piece of 24 characters of the token is left; on stdout as text, on stderr as bytes', () => {
+ const cases = splitLines();
+ const failures = [];
+ for (const token of [...new Set(cases.map((one) => one.token))]) {
+ const own = cases.filter((one) => one.token === token);
+ const run = script(`
+ require('./lib/dataverse-auth.js').getAuthToken('https://contoso.crm.dynamics.com', { exec: () => ${JSON.stringify(`${token}\n`)} });
+ for (const { first, second } of ${JSON.stringify(own)}) {
+ process.stdout.write(first); process.stdout.write(second);
+ process.stderr.write(Buffer.from(first)); process.stderr.write(Buffer.from(second));
+ }
+ `);
+ for (const [where, written] of [['stdout', run.stdout.toString()], ['stderr', run.stderr.toString()]]) {
+ const lines = written.split('\n').slice(0, -1);
+ own.forEach(({ name, split, first }, i) => {
+ const line = lines[i];
+ let parsed = null;
+ try { parsed = JSON.parse(line); } catch { failures.push(`${where} ${name} split ${split}: not JSON: ${line}`); return; }
+ if (parsed.ok !== false) failures.push(`${where} ${name} split ${split}: the document changed: ${line}`);
+ // Bytes are read literally (no escape is read in them), so a token they spell with an escape is the documented residual — except where each write holds its piece as it is: the cut right after the backslash
+ // of `\/`, which once made the two writes no JSON.
+ const literal = where === 'stdout' || (name === '\\/' && first.endsWith('\\'));
+ const left = literal ? piecesIn(line, [token, 'A'.repeat(24), 'B'.repeat(27)]) : [];
+ if (left.length > 0) failures.push(`${where} ${name} split ${split}: a piece of the token is left: ${line}`);
+ });
+ }
+ }
+ assert.deepEqual(failures, []);
+});
+
+test('a JSON `\\/` cut after its backslash, at the functions: a write that ends inside `\\/` and the next that finishes it — each piece taken out, the escape whole, and two writes with no token in them as they were', () => {
+ const token = SPLIT_ESCAPES[0].token;
+ const chunks = [];
+ const stream = { write(chunk) { chunks.push(chunk); return true; } };
+ guardStream(stream, (chunk, options) => (typeof chunk === 'string' ? redactTokens(chunk, [token], { edges: true, ...options }) : redaction.maskTokenBytes(chunk, [token], { edges: true, ...options })));
+ stream.write(`{"error":"${'A'.repeat(24)}\\`);
+ stream.write(`/${'B'.repeat(27)}"}`);
+ assert.deepEqual(JSON.parse(chunks.join('')), { error: `${MARK}/${MARK}` });
+ chunks.length = 0;
+ stream.write(Buffer.from(`{"error":"${'A'.repeat(24)}\\`));
+ stream.write(Buffer.from(`/${'B'.repeat(27)}"}`));
+ assert.deepEqual(JSON.parse(Buffer.concat(chunks).toString()), { error: `${'*'.repeat(24)}/${'*'.repeat(27)}` });
+ // Writes with no token in them — a path that ends with a backslash, and the next write — are what they were.
+ chunks.length = 0;
+ stream.write('C:\\work\\');
+ stream.write('/next line\n');
+ assert.deepEqual(chunks, ['C:\\work\\', '/next line\n']);
+});
+test('JSON written in pieces cut anywhere — inside escapes of every kind, inside the token, around it — is JSON again when the guarded pieces are put together, as text and as bytes, and the rest of the document is as it was', () => {
+ const token = SPLIT_ESCAPES[0].token;
+ const NOISE = ['plain', ' ', '\n', '\r\n', '\t', '"', '\\', '/', 'é', '日本', '🧪', '\u0001', 'u0041', '\\n', 'x', '...', '…'];
+ const guardedWith = (chunks) => {
+ const stream = { write(chunk) { chunks.push(chunk); return true; } };
+ guardStream(stream, (chunk, options) => (typeof chunk === 'string' ? redactTokens(chunk, [token], { edges: true, ...options }) : redaction.maskTokenBytes(chunk, [token], { edges: true, ...options })));
+ return stream;
+ };
+ for (let seed = 1; seed <= 400; seed += 1) {
+ const random = generator(seed);
+ let note = '';
+ for (let i = 0; i < 1 + random.int(8); i += 1) note += random.pick(NOISE);
+ // The token spelled as JSON may spell it: `/` as `\/` or `\u002f`, a character as its \u escape.
+ const spelled = [...token].map((char) => (char === '/' ? random.pick(['/', '\\/', '\\u002f', '\\u002F']) : random.next() < 0.15 ? `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}` : char)).join('');
+ const document = `{"note":${JSON.stringify(note)},"error":"Rejected bearer ${spelled} here","ok":false}`;
+ assert.equal(JSON.parse(document).error, `Rejected bearer ${token} here`, 'the document spells the token');
+ const cuts = [...new Set(Array.from({ length: 1 + random.int(3) }, () => 1 + random.int(document.length - 1)))].sort((a, b) => a - b);
+ const pieces = [0, ...cuts].map((at, i, all) => document.slice(at, all[i + 1]));
+ const text = [];
+ const asText = guardedWith(text);
+ for (const piece of pieces) asText.write(piece);
+ const bytes = [];
+ const asBytes = guardedWith(bytes);
+ for (const piece of pieces) asBytes.write(Buffer.from(piece));
+ for (const [how, joined] of [['text', text.join('')], ['bytes', Buffer.concat(bytes).toString()]]) {
+ let parsed;
+ assert.doesNotThrow(() => { parsed = JSON.parse(joined); }, `seed ${seed}, ${how}, cut at ${cuts}: ${joined}`);
+ assert.deepEqual([parsed.note, parsed.ok], [note, false], `seed ${seed}, ${how}: the rest of the document is as it was`);
+ }
+ }
+});
+test('a write the stream REFUSES at once — an encoding it does not know, a chunk that is no text and no bytes, bytes it will not take — leaves the memory of the escape the last written one ended inside: the writes after it are what they would have been, JSON again, and the error is the stream\'s own; a write that returns false keeps its memory, and a callback the stream calls at once reads on from it', () => {
+ const token = SPLIT_ESCAPES[0].token;
+ const head = `{"error":"${'A'.repeat(24)}\\`;
+ const tail = `/${'B'.repeat(27)}"}`;
+ const make = (verdictOf) => {
+ const chunks = [];
+ const stream = { write(chunk) { const verdict = verdictOf(chunk); if (verdict instanceof Error) throw verdict; chunks.push(chunk); return verdict; } };
+ guardStream(stream, (chunk, options) => (typeof chunk === 'string' ? redactTokens(chunk, [token], { edges: true, ...options }) : redaction.maskTokenBytes(chunk, [token], { edges: true, ...options })));
+ return { stream, chunks };
+ };
+ // What the two writes make when nothing comes between them.
+ const control = make(() => true);
+ control.stream.write(head);
+ control.stream.write(tail);
+ const expected = control.chunks.join('');
+ assert.deepEqual(JSON.parse(expected), { error: `${MARK}/${MARK}` });
+ const wrong = [];
+ for (const [what, refused, args] of [
+ ['a text in an encoding the stream does not know', 'interleaved text', ['no-such-encoding']],
+ ['a chunk that is no text and no bytes', 42, []],
+ ['bytes the stream will not take', Buffer.from('more'), []],
+ ['a string in base64 the stream will not take', Buffer.from('xyz').toString('base64'), ['base64']],
+ ]) {
+ const rejection = new TypeError(`refused: ${what}`);
+ let refuse = false;
+ const { stream, chunks } = make(() => (refuse ? rejection : true));
+ stream.write(head);
+ refuse = true;
+ assert.throws(() => stream.write(refused, ...args), (error) => error === rejection, `${what}: the stream's own error`);
+ refuse = false;
+ stream.write(tail);
+ if (chunks.join('') !== expected) wrong.push(`${what}: ${chunks.join('')}`);
+ }
+ assert.deepEqual(wrong, [], 'the writes after a refused one are what they would have been');
+ // A write that returns false was taken (the stream asks the writer to wait): its memory stands.
+ const waiting = make((chunk) => !(typeof chunk === 'string' && chunk.endsWith('\\')));
+ assert.equal(waiting.stream.write(head), false);
+ waiting.stream.write(tail);
+ assert.equal(waiting.chunks.join(''), expected);
+ // A callback the stream calls at once, which writes the rest from inside the first write, reads on from that write's memory.
+ const chunks = [];
+ const eager = { write(chunk, callback) { chunks.push(chunk); if (typeof callback === 'function') callback(); return true; } };
+ guardStream(eager, (chunk, options) => redactTokens(chunk, [token], { edges: true, ...options }));
+ eager.write(head, () => eager.write(tail));
+ assert.equal(chunks.join(''), expected);
+});
\ No newline at end of file
diff --git a/plugins/model-apps/scripts/tests/output-token-writers.test.js b/plugins/model-apps/scripts/tests/output-token-writers.test.js
index 5eff3fd73..1efb92770 100644
--- a/plugins/model-apps/scripts/tests/output-token-writers.test.js
+++ b/plugins/model-apps/scripts/tests/output-token-writers.test.js
@@ -57,7 +57,24 @@ test('lib/apply-snapshot-store.js writes the snapshot, the baseline and the reco
writeFileAtomic(path.join(dir, 'clean.json'), '{"a":1}');
assert.strictEqual(fs.readFileSync(path.join(dir, 'clean.json'), 'utf8'), '{"a":1}');
assert.deepStrictEqual(fs.readdirSync(dir).sort(), ['clean.json', 'last-applied.json'], 'no temporary file is left');
- assert.deepStrictEqual(scriptsMatching(/\bwriteFileAtomic\s*\(/), ['lib/apply-snapshot-store.js', 'lib/deployed-baseline.js', 'lib/page-ownership-records.js', 'lib/page-publish-records.js'], 'the baseline and the records are written by it, and by nothing else');
+ assert.deepStrictEqual(scriptsMatching(/\bwriteFileAtomic\s*\(/), ['lib/apply-snapshot-store.js', 'lib/dashboard-creation-records.js', 'lib/deployed-baseline.js', 'lib/page-ownership-records.js', 'lib/page-publish-records.js', 'lib/web-resource-records.js'], 'the baseline and the records are written by it, and by nothing else');
+ const { openUnconfirmedWebResources, unconfirmedRecordPath } = require('../lib/web-resource-records.js');
+ const environment = 'https://contoso.crm.dynamics.com';
+ const record = openUnconfirmedWebResources({ workspaceDir: dir, environment });
+ const id = '11111111-aaaa-4aaa-8aaa-111111111111';
+ assert.strictEqual(record.note('contoso_/clean.js', id), true);
+ assert.strictEqual(record.note(`contoso_/${TOKEN}.js`, id), true);
+ const recovery = fs.readFileSync(unconfirmedRecordPath(dir, environment), 'utf8');
+ assert.deepStrictEqual(leaksIn(recovery, SECRETS), [], 'the new recovery record goes through the same redacting writer');
+ assert.strictEqual(JSON.parse(recovery).webResources['contoso_/clean.js'], id, 'ordinary resource identities are unchanged');
+ // A dashboard's name is the maker's text, so the record of the dashboards a build created goes through the same writer.
+ const { openDashboardCreations, dashboardCreationRecordPath } = require('../lib/dashboard-creation-records.js');
+ const created = openDashboardCreations({ workspaceDir: dir, environment, appUniqueName: 'contoso_app', solutionUniqueName: 'ContosoSolution' });
+ assert.strictEqual(created.note('Clean Overview', id), true);
+ assert.strictEqual(created.note(`Rejected bearer ${TOKEN}`, id), true);
+ const dashboards = fs.readFileSync(dashboardCreationRecordPath(dir, environment, 'contoso_app', 'ContosoSolution'), 'utf8');
+ assert.deepStrictEqual(leaksIn(dashboards, SECRETS), [], 'the dashboard creation record goes through the same redacting writer');
+ assert.strictEqual(JSON.parse(dashboards).dashboards['Clean Overview'].id, id, 'ordinary dashboard names are unchanged');
});
// A form whose labels hold the token — as a label a maker typed could, or an answer that echoes a header — read by the SDK, which writes the form, its metadata and the manifest into the workspace: the SDK factory's storage keeps
diff --git a/plugins/model-apps/scripts/tests/page-binding-contract.test.js b/plugins/model-apps/scripts/tests/page-binding-contract.test.js
new file mode 100644
index 000000000..d065b8f01
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/page-binding-contract.test.js
@@ -0,0 +1,275 @@
+'use strict';
+// What an App Spec states of a generative page's connector and Custom API bindings, and what a rebuild does with it (lib/page-bindings.js).
+//
+// A binding a page holds can carry more than the runtime reads: a connection id of the environment it was made in, a credential someone put in a connectors.json (genpage-upload.js takes any JSON array),
+// a property a later runtime adds — as a value, as a key, inside a URL. The spec is committed, reviewed and shared, so it states a list only WHOLE: every key one of the properties references/connectors.md and
+// references/custom-api.md document, every value of a conservative shape known to be safe (page-bindings.js has the threat model). Anything else leaves the list out of the spec, said by its place and a vetted
+// name, never the value or an unrecognized key. A rebuild into the environment a page came from leaves on the page what a spec does not state: mergeBindings is that rule, and what planEdits (genpage-sdk.js)
+// reads a list as "already holds" with.
+const { test } = require('node:test');
+const assert = require('node:assert');
+const fs = require('node:fs');
+const path = require('node:path');
+const {
+ PAGE_BINDINGS,
+ BINDING_PROPERTIES,
+ PARAMETER_KINDS,
+ UNUSUAL_NAME,
+ statableBinding,
+ statableBindings,
+ bindingProblemText,
+ mergeBindings,
+} = require('../lib/page-bindings.js');
+const { PARAMETER_KIND_BY_TYPE } = require('../list-custom-apis.js');
+
+const WEATHER = { logicalName: 'contoso_msnweather', connectorId: '/providers/Microsoft.PowerApps/apis/shared_msnweather', dataset: '', operations: ['CurrentWeather'] };
+const SHAREPOINT = { logicalName: 'contoso_sharepoint', connectorId: '/providers/Microsoft.PowerApps/apis/shared_sharepointonline', dataset: 'https://contoso.sharepoint.com/sites/x', tables: ['11111111-2222-3333-4444-555555555555'], tableDisplayNames: ['Pets'] };
+const APPROVE = { name: 'contoso_ApproveOrder', isFunction: false, boundEntityLogicalName: 'contoso_item', displayName: 'Approve order', parameterKinds: { Comment: 'String' } };
+
+// A page's own entries: the spec's plus what a spec does not state.
+const HELD_WEATHER = { ...WEATHER, connectionId: 'env-local-connection-placeholder', futureProperty: { kept: true } };
+const HELD_SHAREPOINT = { ...SHAREPOINT, apiKey: 'SYNTHETIC_TEST_SECRET' };
+
+const deepFreeze = (value) => {
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
+ Object.freeze(value);
+ for (const inner of Object.values(value)) deepFreeze(inner);
+ }
+ return value;
+};
+
+// ── the allowlist ────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+test('the properties a spec states of a binding are the ones the references document, and the Custom API parameter kinds are the ones the discovery script writes', () => {
+ assert.deepStrictEqual(PAGE_BINDINGS, { connectorBindings: 'logicalName', actionBindings: 'name' });
+ assert.deepStrictEqual(BINDING_PROPERTIES, {
+ connectorBindings: ['logicalName', 'connectorId', 'dataset', 'tables', 'tableDisplayNames', 'operations'],
+ actionBindings: ['name', 'isFunction', 'boundEntityLogicalName', 'displayName', 'parameterKinds'],
+ });
+ // The identity of an entry is one of its properties: a spec that cannot state it cannot state the binding.
+ for (const [kind, identity] of Object.entries(PAGE_BINDINGS)) assert.ok(BINDING_PROPERTIES[kind].includes(identity), kind);
+ assert.deepStrictEqual([...PARAMETER_KINDS].sort(), Object.values(PARAMETER_KIND_BY_TYPE).sort(), 'list-custom-apis.js writes exactly these kinds into parameterKinds');
+});
+
+test('statableBinding states a documented entry whole — a REST and a tabular connector binding, a SQL dataset and table, a custom connector, a Custom API with its parameter kinds — in the entry\'s order, as copies', () => {
+ const SQL = { logicalName: 'contoso_sql', connectorId: 'shared_sql', dataset: 'contoso.database.windows.net,Sales', tables: ['[dbo].[Orders]'], tableDisplayNames: ['Orders'] };
+ const CUSTOM = { logicalName: 'contoso_widgets', connectorId: '/providers/Microsoft.PowerApps/apis/shared_contoso-5fwidgets-5f6a8c', dataset: '', operations: ['ListWidgets', 'Get-Widget.v2'] };
+ const SUMMARY = { name: 'contoso_GetSummary', isFunction: true, displayName: 'Get summary (v2) — Sales & Ops', parameterKinds: { ItemId: 'Guid', _Note: 'String' } };
+ const SITE = { ...SHAREPOINT, dataset: 'https://contoso.sharepoint.com/sites/Team%20Site/Shared%20Documents', tableDisplayNames: ['Équipes', 'Pets'] };
+ for (const [kind, entry] of [['connectorBindings', WEATHER], ['connectorBindings', SHAREPOINT], ['connectorBindings', SQL], ['connectorBindings', CUSTOM], ['connectorBindings', SITE], ['actionBindings', APPROVE], ['actionBindings', SUMMARY]]) {
+ const { stated, leftOut } = statableBinding(kind, deepFreeze(JSON.parse(JSON.stringify(entry))));
+ assert.deepStrictEqual(leftOut, [], JSON.stringify(entry));
+ assert.deepStrictEqual(stated, entry);
+ assert.deepStrictEqual(Object.keys(stated), Object.keys(entry), 'in the entry\'s own order');
+ }
+ const held = { ...APPROVE, parameterKinds: { Comment: 'String' } };
+ const { stated } = statableBinding('actionBindings', held);
+ assert.notStrictEqual(stated.parameterKinds, held.parameterKinds, 'a copy: a later edit of the spec does not reach the page\'s entry');
+});
+
+test('declared Custom API kinds: the vocabulary contains exactly ten declared primitives', () => {
+ const kinds = ['Boolean', 'DateTime', 'Decimal', 'Float', 'Integer', 'Money', 'Picklist', 'String', 'StringArray', 'Guid'];
+ assert.deepStrictEqual([...PARAMETER_KINDS].sort(), [...kinds].sort());
+});
+
+test('declared Custom API kinds: discovery and validation use one immutable pure contract without a CLI dependency', () => {
+ const shared = require('../lib/custom-api-kinds.js');
+ assert.strictEqual(PARAMETER_KINDS, shared.PARAMETER_KINDS);
+ assert.strictEqual(PARAMETER_KIND_BY_TYPE, shared.PARAMETER_KIND_BY_TYPE);
+ assert.ok(Object.isFrozen(shared.PARAMETER_KINDS) && Object.isFrozen(shared.PARAMETER_KIND_BY_TYPE));
+ const visited = new Set();
+ function visit(module) {
+ if (visited.has(module.id)) return;
+ visited.add(module.id);
+ for (const child of module.children) visit(child);
+ }
+ visit(require.cache[require.resolve('../lib/page-bindings.js')]);
+ assert.ok(!visited.has(require.resolve('../list-custom-apis.js')), 'production statability never loads the CLI entry point');
+ assert.deepStrictEqual(require.cache[require.resolve('../lib/custom-api-kinds.js')].children, []);
+});
+
+test('declared Custom API kinds: both App Spec references agree with the runtime vocabulary', () => {
+ const references = path.join(__dirname, '..', '..', 'references');
+ const schema = fs.readFileSync(path.join(references, 'app-spec-schema.md'), 'utf8');
+ const row = schema.split(/\r?\n/).find((line) => /^\s*\|\s*\|\s*`parameterKinds`\s*\|/.test(line));
+ assert.ok(row);
+ const list = /(?:kinds|accepts)\s*\(([^)]+)\)/.exec(row);
+ assert.ok(list, 'the schema states the closed kind vocabulary');
+ const kinds = [...list[1].matchAll(/`([A-Za-z]+)`/g)].map((match) => match[1]);
+ assert.deepStrictEqual(kinds.sort(), [...PARAMETER_KINDS].sort());
+ const reference = fs.readFileSync(path.join(references, 'custom-api.md'), 'utf8')
+ .split('## In an App Spec')[1].split('## Discovery-only lookup inputs')[0];
+ assert.match(reference, /ten primitive declared kinds documented above/);
+ assert.match(reference, /lookup-only API/);
+ assert.match(reference, /left out whole/);
+});
+
+test('declared Custom API kinds: all ten primitive kinds and sparse lookup maps are statable', () => {
+ const kinds = ['Boolean', 'DateTime', 'Decimal', 'Float', 'Integer', 'Money', 'Picklist', 'String', 'StringArray', 'Guid'];
+ for (const parameterKinds of [...kinds.map((kind) => ({ Value: kind })), { Note: 'String' }, {}]) {
+ const entry = { ...APPROVE, parameterKinds };
+ assert.deepStrictEqual(statableBindings('actionBindings', [entry]), { stated: [entry], problem: null });
+ }
+ const lookupOnly = { name: 'contoso_ResolveReference', isFunction: false };
+ assert.deepStrictEqual(statableBindings('actionBindings', [lookupOnly]), { stated: [lookupOnly], problem: null });
+});
+
+test('declared Custom API kinds: unsupported declarations leave the entire list unstated', async (t) => {
+ for (const kind of ['EntityReference', 'Entity', 'EntityCollection']) {
+ await t.test(`declared Custom API kinds: unstated ${kind}`, () => {
+ const bad = { name: 'contoso_ResolveReference', parameterKinds: { Ref: kind, Note: 'String' } };
+ const projected = statableBindings('actionBindings', [APPROVE, bad]);
+ assert.deepStrictEqual(projected, { stated: null, problem: { entry: 1, property: 'parameterKinds', why: 'parameter-kinds' } });
+ const reason = bindingProblemText('actionBindings', 1, projected.problem);
+ assert.match(reason, /^actionBindings\[1\]\.parameterKinds /);
+ assert.ok(!reason.includes(kind) && !reason.includes('Ref'), 'the diagnostic names the place/property, never its value or map keys');
+ });
+ }
+});
+
+// The values a credential takes when it hides in a property a spec DOES state. Each must leave its value out: a value is stated only with a shape that is positively known to be safe, and a URL only when its
+// PARSED form has no user-info, no query and no fragment. Synthetic markers only.
+const MARK = 'SYNTHETIC_CREDENTIAL_R3';
+const TOKEN = `ghp_${'R'.repeat(36)}`;
+const UNSAFE_VALUES = [
+ ['connectorBindings', 'dataset', `https://${MARK}@contoso.example/data`, 'a token alone in the user-info of a URL'],
+ ['connectorBindings', 'dataset', `https://maker:${MARK}@contoso.example/data`, 'a password in the user-info'],
+ ['connectorBindings', 'dataset', `https://contoso.example/data?api%5Fkey=${MARK}`, 'a percent-encoded key in a query'],
+ ['connectorBindings', 'dataset', `https://contoso.example/data?x=${MARK}`, 'any query'],
+ ['connectorBindings', 'dataset', 'https://contoso.example/data?', 'an empty query, which a parser drops'],
+ ['connectorBindings', 'dataset', `https://contoso.example/data#access_token=${MARK}`, 'a fragment'],
+ ['connectorBindings', 'dataset', `https://contoso.example/sites/a%40${MARK}`, 'an encoded @ in the path'],
+ ['connectorBindings', 'dataset', `https://contoso.example/sites/0123456789abcdef0123456789abcdef${MARK}`, 'a digest-shaped path segment'],
+ ['connectorBindings', 'dataset', `ftp://contoso.example/${MARK}`, 'a scheme that is not http(s)'],
+ ['connectorBindings', 'dataset', JSON.stringify({ accessToken: MARK }), 'JSON text'],
+ ['connectorBindings', 'dataset', `Server=sql.contoso.example;Password=${MARK}`, 'a connection string'],
+ ['connectorBindings', 'logicalName', `Bearer ${MARK}`, 'an authorization value as the identity'],
+ ['connectorBindings', 'logicalName', TOKEN, 'a token-format identity'],
+ ['connectorBindings', 'connectorId', `/providers/Microsoft.PowerApps/apis/shared_x?sig=${MARK}`, 'a connector id with a query'],
+ ['connectorBindings', 'tables', [`${MARK}=1`], 'a table with a key=value'],
+ ['connectorBindings', 'tableDisplayNames', [`https://${MARK}@contoso.example`], 'a label that is a URL'],
+ ['connectorBindings', 'operations', [`eyJhbGciOiJIUzI1NiJ9.${MARK}`], 'a JSON Web Token as an operation'],
+ ['actionBindings', 'displayName', `https://${MARK}@contoso.example/api`, "a Custom API's display name that is a URL"],
+ ['actionBindings', 'displayName', `Bearer ${MARK}`, 'an authorization value as a label'],
+ ['actionBindings', 'displayName', `key=${MARK}`, 'a label with a key=value'],
+ ['actionBindings', 'boundEntityLogicalName', `contoso_item ${MARK}`, 'a table name with a space'],
+ ['actionBindings', 'parameterKinds', { [TOKEN]: 'String' }, 'a token as a parameter name'],
+ ['actionBindings', 'parameterKinds', { [`x${MARK}`.toLowerCase()]: MARK }, 'a parameter kind that is not one'],
+];
+
+test('a value is stated only with a conservative shape known to be safe — a credential in a URL\'s user-info, query or fragment, encoded, as a token, a JWT or JSON text is left out, and never quoted', () => {
+ for (const [kind, property, value, what] of UNSAFE_VALUES) {
+ const base = kind === 'connectorBindings' ? SHAREPOINT : APPROVE;
+ const { stated, leftOut } = statableBinding(kind, { ...base, [property]: value });
+ assert.ok(!(property in stated), `${what}: not stated`);
+ assert.deepStrictEqual(leftOut.map((l) => l.property), [property], what);
+ assert.ok(!JSON.stringify(leftOut).includes(MARK) && !JSON.stringify(leftOut).includes(TOKEN), `${what}: the value is never in what is said`);
+ assert.ok(!bindingProblemText(kind, 0, leftOut[0]).includes(MARK), what);
+ }
+});
+
+// A URL is stated only as it is written: the exact text that goes into app-spec.json is the text that is checked. A parser NORMALIZES what it reads — a dot-segment (`/<x>/../`, `%2e%2e`, `/./`) removes a path
+// segment before any check sees it, and a host is lower-cased — so a URL is a value only when it is already in the form the parser gives back (`new URL(text).href` is the text, or the text and a `/` for an
+// origin with no path). Anything else leaves its list out of the spec, whatever the segment that would have been dropped holds.
+const NOT_CANONICAL = [
+ [`https://contoso.example/${TOKEN}/../site`, 'a dot-segment that drops a token-shaped segment'],
+ [`https://contoso.example/${MARK}/%2e%2e/site`, 'a percent-encoded dot-segment'],
+ [`https://contoso.example/${MARK}/%2E%2E/site`, 'an upper-case percent-encoded dot-segment'],
+ [`https://contoso.example/${MARK}/.%2e/site`, 'a half-encoded dot-segment'],
+ ['https://contoso.example/sites/./x', 'a single-dot segment'],
+ ['https://contoso.example/sites/%2e/x', 'an encoded single-dot segment'],
+ ['https://contoso.example/sites/x/..', 'a trailing dot-segment'],
+ ['https://Contoso.Example/sites/x', 'a host the parser lower-cases'],
+ ['https://contoso.example:443/sites/x', 'a default port the parser drops'],
+ ['HTTPS://contoso.example/sites/x', 'a scheme the parser lower-cases'],
+];
+
+test('a URL is stated only when it is already canonical — the text that is persisted is the text that is checked, so a dot-segment cannot hide a segment the check never saw', () => {
+ for (const [value, what] of NOT_CANONICAL) {
+ for (const [kind, base, property, put] of [
+ ['connectorBindings', SHAREPOINT, 'dataset', (v) => v],
+ ['connectorBindings', { logicalName: 'contoso_widgets', connectorId: '/providers/Microsoft.PowerApps/apis/shared_contoso-5fwidgets-5f6a8c', operations: ['ListWidgets'] }, 'dataset', (v) => v],
+ ['connectorBindings', SHAREPOINT, 'tables', (v) => [v]],
+ ['connectorBindings', SHAREPOINT, 'tableDisplayNames', (v) => [v]],
+ ['actionBindings', APPROVE, 'displayName', (v) => v],
+ ['actionBindings', APPROVE, 'parameterKinds', (v) => ({ [v]: 'String' })],
+ ]) {
+ const { stated, leftOut } = statableBinding(kind, { ...base, [property]: put(value) });
+ assert.ok(!(property in stated), `${what}, as ${kind}.${property}: not stated`);
+ assert.deepStrictEqual(leftOut.map((l) => l.property), [property], `${what}, as ${kind}.${property}`);
+ const said = JSON.stringify(leftOut) + bindingProblemText(kind, 0, leftOut[0]);
+ assert.ok(!said.includes(MARK) && !said.includes(TOKEN) && !said.includes('..'), `${what}: what is said holds nothing of the value`);
+ assert.deepStrictEqual(statableBindings(kind, [base, { ...base, [property]: put(value) }]).stated, null, `${what}: the whole list is left out`);
+ }
+ }
+ // The same token in a canonical path was always refused; and canonical URLs are still stated as they are, an origin with or without its `/` too.
+ assert.deepStrictEqual(statableBinding('connectorBindings', { ...SHAREPOINT, dataset: `https://contoso.example/${TOKEN}/site` }).leftOut.map((l) => l.property), ['dataset']);
+ for (const dataset of ['https://contoso.sharepoint.com/sites/x', 'https://contoso.sharepoint.com', 'https://contoso.sharepoint.com/', 'https://contoso.sharepoint.com/sites/Team%20Site/Shared%20Documents', 'http://intranet.contoso.example:8080/sites/x']) {
+ assert.deepStrictEqual(statableBinding('connectorBindings', { ...SHAREPOINT, dataset }).leftOut, [], dataset);
+ }
+});
+
+test('a key is stated only when it is a documented property — any other is "an unrecognized property", and the key itself is never said: a token can be the NAME of a property', () => {
+ const entry = { ...WEATHER, [TOKEN]: true, connectionId: 'x', credentials: { accessToken: MARK }, constructor: 1 };
+ const { stated, leftOut } = statableBinding('connectorBindings', entry);
+ assert.deepStrictEqual(stated, WEATHER);
+ assert.deepStrictEqual(leftOut, Array(4).fill({ property: UNUSUAL_NAME, why: 'not-stated' }));
+ const said = JSON.stringify(leftOut) + bindingProblemText('connectorBindings', 0, leftOut[0]);
+ for (const secret of [TOKEN, 'connectionId', 'credentials', MARK]) assert.ok(!said.includes(secret), secret);
+ assert.strictEqual(bindingProblemText('connectorBindings', 2, leftOut[0]), 'connectorBindings[2] holds an unrecognized property, which an App Spec does not state (a binding states only logicalName, connectorId, dataset, tables, tableDisplayNames, operations)');
+ assert.strictEqual(bindingProblemText('actionBindings', 0, { property: 'displayName', why: 'label' }), 'actionBindings[0].displayName must be a plain label (letters, digits, spaces and simple punctuation; no URL)');
+});
+
+test('statableBindings states a list WHOLE or not at all — the first entry that holds anything else is said by its place and a vetted name, and nothing of the list is projected', () => {
+ const whole = statableBindings('connectorBindings', [WEATHER, SHAREPOINT]);
+ assert.deepStrictEqual(whole, { stated: [WEATHER, SHAREPOINT], problem: null });
+ // An entry whose identity alone is unsafe: projecting the rest would write an entry with no identity, and a rebuild would replace the page's entry with it.
+ const identity = statableBindings('connectorBindings', [WEATHER, { ...SHAREPOINT, logicalName: `Bearer ${MARK}` }]);
+ assert.deepStrictEqual(identity, { stated: null, problem: { entry: 1, property: 'logicalName', why: 'identifier' } });
+ const unknown = statableBindings('actionBindings', [{ ...APPROVE, [TOKEN]: 1 }]);
+ assert.deepStrictEqual(unknown, { stated: null, problem: { entry: 0, property: UNUSUAL_NAME, why: 'not-stated' } });
+ assert.deepStrictEqual(statableBindings('actionBindings', []), { stated: [], problem: null });
+ assert.ok(!JSON.stringify([identity, unknown]).includes(MARK) && !JSON.stringify(unknown).includes(TOKEN));
+});
+
+test('mergeBindings: the entries a spec states as the page holds them merge into exactly the page\'s own — so nothing is written, and nothing a spec could not state is lost', () => {
+ const held = [HELD_WEATHER, HELD_SHAREPOINT];
+ assert.deepStrictEqual(mergeBindings('connectorBindings', [WEATHER, SHAREPOINT], held), held);
+ // An entry the page holds with a property of a kind a spec cannot state keeps it: the spec left it out, and a rebuild leaves it be.
+ const odd = [{ logicalName: 'contoso_a', operations: 'oops', connectionId: 'x' }];
+ assert.deepStrictEqual(mergeBindings('connectorBindings', [{ logicalName: 'contoso_a' }], odd), odd);
+});
+
+test('mergeBindings: an edit is applied to the entry it is about — the stated properties win, a stated property that is gone is gone, and what a spec could not state stays', () => {
+ const held = [HELD_WEATHER, HELD_SHAREPOINT];
+ const edited = mergeBindings('connectorBindings', [{ ...WEATHER, operations: ['Forecast'] }, SHAREPOINT], held);
+ assert.deepStrictEqual(edited, [{ ...HELD_WEATHER, operations: ['Forecast'] }, HELD_SHAREPOINT]);
+ const { operations, ...withoutOperations } = WEATHER;
+ assert.deepStrictEqual(mergeBindings('connectorBindings', [withoutOperations, SHAREPOINT], held), [{ logicalName: HELD_WEATHER.logicalName, connectorId: HELD_WEATHER.connectorId, dataset: '', connectionId: HELD_WEATHER.connectionId, futureProperty: { kept: true } }, HELD_SHAREPOINT]);
+ // A stated property replaces one the spec could not state, as a spec that states a valid list does where the page holds a text.
+ assert.deepStrictEqual(mergeBindings('connectorBindings', [{ logicalName: 'contoso_a', operations: ['x'] }], [{ logicalName: 'contoso_a', operations: 'oops', connectionId: 'c' }]), [{ logicalName: 'contoso_a', operations: ['x'], connectionId: 'c' }]);
+});
+
+test('mergeBindings: entries are matched by the name they go by — so an entry that is removed, added or moved takes its own extras, or none', () => {
+ const held = [HELD_WEATHER, HELD_SHAREPOINT];
+ assert.deepStrictEqual(mergeBindings('connectorBindings', [SHAREPOINT], held), [HELD_SHAREPOINT], 'removed: the other entry is gone');
+ assert.deepStrictEqual(mergeBindings('connectorBindings', [SHAREPOINT, WEATHER], held), [HELD_SHAREPOINT, HELD_WEATHER], 'moved: the order is the spec\'s');
+ const fresh = { logicalName: 'contoso_new', connectorId: '/providers/Microsoft.PowerApps/apis/shared_new' };
+ assert.deepStrictEqual(mergeBindings('connectorBindings', [WEATHER, fresh], [HELD_WEATHER]), [HELD_WEATHER, fresh], 'added: stated as it is');
+ assert.deepStrictEqual(mergeBindings('connectorBindings', [{ ...WEATHER, logicalName: 'contoso_renamed' }], held), [{ ...WEATHER, logicalName: 'contoso_renamed' }], 'renamed: a new entry, and the old one\'s extras are not carried to it');
+ // Two entries of one name are matched in order.
+ const twins = [{ logicalName: 'contoso_a', connectionId: '1' }, { logicalName: 'contoso_a', connectionId: '2' }];
+ assert.deepStrictEqual(mergeBindings('connectorBindings', [{ logicalName: 'contoso_a' }, { logicalName: 'contoso_a' }], twins), twins);
+ // An entry with no name on either side is matched by its place.
+ assert.deepStrictEqual(mergeBindings('connectorBindings', [{ connectorId: 'x' }], [{ connectorId: 'x', credentials: 1 }]), [{ connectorId: 'x', credentials: 1 }]);
+ assert.deepStrictEqual(mergeBindings('actionBindings', [APPROVE], [{ ...APPROVE, headers: 1 }]), [{ ...APPROVE, headers: 1 }]);
+});
+
+test('mergeBindings answers the list as stated when there is nothing to merge into, and never changes what it is given', () => {
+ const stated = deepFreeze([WEATHER]);
+ for (const held of [undefined, null, 'oops', {}, 7]) assert.strictEqual(mergeBindings('connectorBindings', stated, held), stated, `held ${JSON.stringify(held)}`);
+ assert.deepStrictEqual(mergeBindings('connectorBindings', stated, deepFreeze([HELD_WEATHER])), [HELD_WEATHER]);
+ assert.deepStrictEqual(mergeBindings('connectorBindings', stated, []), [WEATHER]);
+ assert.strictEqual(mergeBindings('connectorBindings', 'x', [HELD_WEATHER]), 'x', 'what is not a list is not this function\'s to judge');
+ assert.deepStrictEqual(mergeBindings('connectorBindings', [null, WEATHER], [HELD_WEATHER]), [null, HELD_WEATHER], 'nor is an entry that is no object');
+});
diff --git a/plugins/model-apps/scripts/tests/page-binding-targets.test.js b/plugins/model-apps/scripts/tests/page-binding-targets.test.js
new file mode 100644
index 000000000..507f74100
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/page-binding-targets.test.js
@@ -0,0 +1,407 @@
+'use strict';
+// What a rebuild checks of the environment it writes a page's bindings into (lib/page-binding-targets.js).
+//
+// A binding names what it goes through — a connection reference by its logical name, a Custom API by its unique name — and the page calls it by that name at run time. The spec can state the name and the connector
+// it was made for (`connectorId`), and cannot make the reference: so before a rebuild writes a binding it reads the environment's references and Custom APIs for the names the spec states. A reference that
+// exists for ANOTHER connector is refused — the page would call that connector under this name, and the name cannot tell them apart — and a name that is not there, or a Custom API of another kind, is said by name.
+const { test } = require('node:test');
+const assert = require('node:assert');
+const { connectorKey, pagesStatingBindings, readBindingTargets, judgeBindingTargets, definedOperations } = require('../lib/page-binding-targets.js');
+
+const WEATHER = { logicalName: 'contoso_msnweather', connectorId: '/providers/Microsoft.PowerApps/apis/shared_msnweather', dataset: '', operations: ['CurrentWeather'] };
+const SHAREPOINT = { logicalName: 'contoso_sharepoint', connectorId: '/providers/Microsoft.PowerApps/apis/shared_sharepointonline', dataset: 'https://contoso.sharepoint.com/sites/x', tables: ['11111111-2222-3333-4444-555555555555'] };
+const APPROVE = { name: 'contoso_ApproveOrder', isFunction: false, boundEntityLogicalName: 'contoso_item' };
+const SUMMARY = { name: 'contoso_GetSummary', isFunction: true };
+const api = (apiFor) => `/providers/Microsoft.PowerApps/apis/${apiFor}`;
+const reference = (logicalName, connector) => ({ connectionreferencelogicalname: logicalName, connectorid: connector === undefined ? undefined : api(connector) });
+const customApi = (uniquename, extra = {}) => ({ uniquename, isfunction: false, bindingtype: 0, ...extra });
+
+test('connectorKey is the name of the connector, whatever form its id is written in', () => {
+ for (const id of ['/providers/Microsoft.PowerApps/apis/shared_msnweather', 'shared_msnweather', 'SHARED_MsnWeather', ' /providers/Microsoft.PowerApps/apis/shared_msnweather/ ', '/providers/Microsoft.PowerApps/apis/SHARED_MSNWEATHER']) {
+ assert.strictEqual(connectorKey(id), 'shared_msnweather', JSON.stringify(id));
+ }
+ assert.strictEqual(connectorKey('/providers/Microsoft.PowerApps/apis/shared_contoso-5fwidgets-5f6a8c'), 'shared_contoso-5fwidgets-5f6a8c', 'a custom connector\'s id differs in every environment');
+ for (const id of [undefined, null, '', ' ', '/', 42, {}, []]) assert.strictEqual(connectorKey(id), null, JSON.stringify(id));
+});
+
+// ── which pages, which names ─────────────────────────────────────────────────────────────────────────────────────────────────
+
+const pageOf = (key, extra = {}) => ({ key, name: key.toUpperCase(), source: { kind: 'tsx', codeFile: `${key}.tsx` }, ...extra });
+
+test('pagesStatingBindings is the pages a build writes that state a binding — and only the lists they state', () => {
+ const spec = { pages: [
+ pageOf('weather', { connectorBindings: [WEATHER, SHAREPOINT], actionBindings: [] }),
+ pageOf('plain'),
+ pageOf('empty', { connectorBindings: [], actionBindings: [] }),
+ pageOf('orders', { actionBindings: [APPROVE] }),
+ { key: 'noSource', name: 'NOSOURCE', connectorBindings: [WEATHER] },
+ { key: 'legacy', name: 'LEGACY', codeFile: 'legacy.tsx', connectorBindings: [WEATHER] },
+ ] };
+ assert.deepStrictEqual(pagesStatingBindings(spec), [
+ { key: 'weather', name: 'WEATHER', connectorBindings: [WEATHER, SHAREPOINT], actionBindings: [] },
+ { key: 'orders', name: 'ORDERS', actionBindings: [APPROVE] },
+ { key: 'legacy', name: 'LEGACY', connectorBindings: [WEATHER] },
+ ]);
+ assert.deepStrictEqual(pagesStatingBindings({ pages: [] }), []);
+ assert.deepStrictEqual(pagesStatingBindings({}), []);
+});
+
+test('pagesStatingBindings: a changed-only run writes the pages it selected, and the navigation targets it may have to make — and no other', () => {
+ const spec = { pages: [
+ pageOf('a', { connectorBindings: [WEATHER] }),
+ pageOf('b', { connectorBindings: [SHAREPOINT], navigatesTo: [{ targetKey: 'c' }] }),
+ pageOf('c', { actionBindings: [APPROVE] }),
+ pageOf('d', { actionBindings: [SUMMARY] }),
+ ] };
+ const keys = (changedOnly) => pagesStatingBindings(spec, { changedOnly }).map((p) => p.key);
+ assert.deepStrictEqual(keys(undefined), ['a', 'b', 'c', 'd'], 'a full build writes every page');
+ assert.deepStrictEqual(keys({ selectedKeys: ['a'] }), ['a', 'c'], 'the selected page, and c, which b navigates to');
+ assert.deepStrictEqual(keys({ selectedKeys: [] }), ['c']);
+ assert.deepStrictEqual(keys({ resolvedAppId: 'x' }), ['a', 'b', 'c', 'd'], 'a changed-only run that selects nothing by key is not narrowed');
+});
+
+// ── reading the environment ──────────────────────────────────────────────────────────────────────────────────────────────────
+
+function readerOf(rows, { failOn } = {}) {
+ const calls = [];
+ const provision = {
+ queryRecords: async (entity, options) => {
+ calls.push({ entity, options });
+ if (failOn && failOn.includes(entity)) throw new Error(`${entity}: HTTP 403`);
+ return rows[entity] || [];
+ },
+ };
+ return { provision, calls };
+}
+
+test('readBindingTargets reads the references and the Custom APIs for the names the pages state — once each, by name — and nothing when no page states one', async () => {
+ const pages = [
+ { key: 'a', name: 'A', connectorBindings: [WEATHER, SHAREPOINT], actionBindings: [APPROVE] },
+ { key: 'b', name: 'B', connectorBindings: [{ ...WEATHER, logicalName: 'CONTOSO_MSNWEATHER' }, { dataset: 'x' }], actionBindings: [SUMMARY, APPROVE] },
+ ];
+ const { provision, calls } = readerOf({
+ connectionreference: [reference('contoso_msnweather', 'shared_msnweather'), reference('contoso_other', 'shared_other')],
+ customapi: [customApi('contoso_ApproveOrder', { boundentitylogicalname: 'contoso_item', bindingtype: 1 }), customApi('contoso_GetSummary', { isfunction: true })],
+ });
+ const targets = await readBindingTargets(provision, pages);
+ assert.deepStrictEqual(calls.map((c) => c.entity), ['connectionreference', 'customapi']);
+ assert.deepStrictEqual(calls[0].options.select, ['connectionreferencelogicalname', 'connectorid', 'connectionid', '_customconnectorid_value']);
+ assert.strictEqual(calls[0].options.paginate, true);
+ assert.strictEqual(calls[0].options.filter, "connectionreferencelogicalname eq 'contoso_msnweather' or connectionreferencelogicalname eq 'contoso_sharepoint'", 'each name once');
+ assert.deepStrictEqual(calls[1].options.select, ['uniquename', 'isfunction', 'bindingtype', 'boundentitylogicalname']);
+ assert.strictEqual(calls[1].options.filter, "uniquename eq 'contoso_ApproveOrder' or uniquename eq 'contoso_GetSummary'", 'as the spec spells them: the service compares them without regard to case, and a name is matched here in lower case');
+ // Only the names asked for are kept, whatever the service answered, by lower-cased name.
+ assert.deepStrictEqual([...targets.references], [['contoso_msnweather', { connectorId: api('shared_msnweather') }]]);
+ assert.deepStrictEqual([...targets.apis], [
+ ['contoso_approveorder', { isFunction: false, boundEntity: 'contoso_item' }],
+ ['contoso_getsummary', { isFunction: true }],
+ ]);
+ assert.deepStrictEqual(targets.problems, {});
+
+ const none = readerOf({});
+ assert.deepStrictEqual(await readBindingTargets(none.provision, [{ key: 'a', name: 'A' }]), { references: null, apis: null, definitions: null, problems: {} });
+ assert.deepStrictEqual(none.calls, [], 'no page states a binding: nothing is read');
+ const onlyReferences = readerOf({});
+ await readBindingTargets(onlyReferences.provision, [{ key: 'a', name: 'A', connectorBindings: [WEATHER] }]);
+ assert.deepStrictEqual(onlyReferences.calls.map((c) => c.entity), ['connectionreference'], 'and a Custom API is read only when a page binds one');
+});
+
+test('readBindingTargets quotes a name into the filter as OData text, reads many names in chunks, and says what it could not read instead of throwing', async () => {
+ const odd = readerOf({});
+ await readBindingTargets(odd.provision, [{ key: 'a', name: 'A', connectorBindings: [{ logicalName: "o'brien_x" }] }]);
+ assert.strictEqual(odd.calls[0].options.filter, "connectionreferencelogicalname eq 'o''brien_x'");
+
+ const many = readerOf({});
+ const bindings = Array.from({ length: 51 }, (_, i) => ({ logicalName: `contoso_ref${String(i).padStart(2, '0')}` }));
+ await readBindingTargets(many.provision, [{ key: 'a', name: 'A', connectorBindings: bindings }]);
+ assert.deepStrictEqual(many.calls.map((c) => c.options.filter.split(' or ').length), [25, 25, 1], 'a request is bounded: the filter of a long list is not');
+
+ const denied = readerOf({}, { failOn: ['connectionreference'] });
+ const targets = await readBindingTargets(denied.provision, [{ key: 'a', name: 'A', connectorBindings: [WEATHER], actionBindings: [APPROVE] }]);
+ assert.strictEqual(targets.references, null);
+ assert.deepStrictEqual(targets.problems, { references: 'connectionreference: HTTP 403' });
+ assert.ok(targets.apis instanceof Map, 'the other read is still made');
+ const cannot = await readBindingTargets({}, [{ key: 'a', name: 'A', connectorBindings: [WEATHER] }]);
+ assert.strictEqual(cannot.references, null);
+ assert.match(cannot.problems.references, /cannot be read here/, 'a reader that cannot read is a read that failed');
+});
+
+// ── judging what was read ────────────────────────────────────────────────────────────────────────────────────────────────────
+
+const pagesA = [{ key: 'weather', name: 'Weather', connectorBindings: [WEATHER, SHAREPOINT], actionBindings: [APPROVE, SUMMARY] }];
+// References as complete rows prove them: the connector, and a connection. Whether a reference is for a custom connector is left out — a row with a null lookup proves nothing about it.
+const targetsOf = ({ references = [], apis = [], problems = {} } = {}) => ({
+ references: new Map(references.map(([name, connector]) => [name, { connectorId: connector === undefined ? undefined : api(connector), connected: true }])),
+ apis: new Map(apis.map(([name, value]) => [name, value])),
+ problems,
+});
+
+test('judgeBindingTargets: a reference of the same name for the SAME connector, in any form of its id, is fine — and a Custom API of the same kind and table', () => {
+ const verdict = judgeBindingTargets(pagesA, targetsOf({
+ references: [['contoso_msnweather', 'SHARED_MSNWEATHER'], ['contoso_sharepoint', 'shared_sharepointonline']],
+ apis: [['contoso_approveorder', { isFunction: false, boundEntity: 'CONTOSO_ITEM' }], ['contoso_getsummary', { isFunction: true }]],
+ }));
+ assert.deepStrictEqual(verdict.findings, []);
+ // The operations Weather's binding calls are not proven to be there: no row named a custom connector whose definition could be read. That is said — it is not "fine" by default.
+ assert.deepStrictEqual(verdict.unchecked.map((u) => [u.what, u.text]), [['custom connector definitions', 'the operations that connector binding "contoso_msnweather" of page "Weather" call were not checked: this environment does not name a custom connector for its connection reference, and only a custom connector\'s definition is read here (a connector the platform publishes defines the same operations in every environment of its cloud)']]);
+});
+
+test('judgeBindingTargets refuses a reference that exists for ANOTHER connector, naming the page, the binding and both connectors', () => {
+ const verdict = judgeBindingTargets(pagesA, targetsOf({
+ references: [['contoso_msnweather', 'shared_office365users'], ['contoso_sharepoint', 'shared_sharepointonline']],
+ apis: [['contoso_approveorder', { isFunction: false, boundEntity: 'contoso_item' }], ['contoso_getsummary', { isFunction: true }]],
+ }));
+ assert.strictEqual(verdict.findings.length, 1);
+ const [conflict] = verdict.findings;
+ assert.deepStrictEqual({ ...conflict, text: undefined }, { severity: 'refuse', kind: 'connector-conflict', page: { key: 'weather', name: 'Weather' }, binding: 'contoso_msnweather', expected: 'shared_msnweather', found: 'shared_office365users', text: undefined });
+ assert.strictEqual(conflict.text, 'page "Weather": connector binding "contoso_msnweather" is for connector shared_msnweather, but the connection reference of that name in this environment is for connector shared_office365users');
+});
+
+test('judgeBindingTargets cannot prove a conflict from a connector that is not stated on both sides — a reference whose row names no connector is NOT CHECKED, said by name, and never a conflict', () => {
+ const pages = [{ key: 'a', name: 'A', connectorBindings: [{ logicalName: 'contoso_one' }, { logicalName: 'contoso_two', connectorId: api('shared_two') }, { logicalName: 'contoso_three', connectorId: '' }] }];
+ const verdict = judgeBindingTargets(pages, targetsOf({ references: [['contoso_one', 'shared_x'], ['contoso_two', undefined], ['contoso_three', 'shared_y']] }));
+ assert.deepStrictEqual(verdict.findings, []);
+ assert.deepStrictEqual(verdict.unchecked, [{ what: 'reference connectors', text: 'this environment\'s row for connection reference contoso_two did not give a connector id this build can read (absent, or not of the form /providers/Microsoft.PowerApps/apis/shared_<name>), so whether connector binding "contoso_two" of page "A" goes through the connector it was made for was not checked' }]);
+});
+
+test('judgeBindingTargets says by name which references and Custom APIs the environment does not have — one line per page, in the page\'s order', () => {
+ const pages = [
+ { key: 'weather', name: 'Weather', connectorBindings: [WEATHER, SHAREPOINT, { ...WEATHER }], actionBindings: [APPROVE] },
+ { key: 'other', name: 'Other', actionBindings: [SUMMARY] },
+ ];
+ const verdict = judgeBindingTargets(pages, targetsOf({ references: [['contoso_sharepoint', 'shared_sharepointonline']] }));
+ assert.deepStrictEqual(verdict.findings.map((f) => [f.severity, f.kind, f.page.key, f.names]), [
+ ['warn', 'reference-missing', 'weather', ['contoso_msnweather']],
+ ['warn', 'api-missing', 'weather', ['contoso_ApproveOrder']],
+ ['warn', 'api-missing', 'other', ['contoso_GetSummary']],
+ ]);
+ assert.strictEqual(verdict.findings[0].text, 'page "Weather": connection reference contoso_msnweather is not in this environment, so the page is written with a binding it cannot resolve yet. A page finds its connector by the reference\'s logical name: create the reference here (create-connection-reference.js, or import the solution that holds it) and the page works without a rebuild');
+ assert.strictEqual(verdict.findings[1].text, 'page "Weather": Custom API contoso_ApproveOrder is not in this environment (list-custom-apis.js lists what it has), so a call through the binding is refused until it is deployed here');
+ const several = judgeBindingTargets([{ key: 'a', name: 'A', connectorBindings: [WEATHER, SHAREPOINT], actionBindings: [APPROVE, SUMMARY] }], targetsOf());
+ assert.match(several.findings[0].text, /^page "A": connection references contoso_msnweather, contoso_sharepoint are not in this environment, so the page is written with bindings it cannot resolve yet\./);
+ assert.match(several.findings[1].text, /^page "A": Custom APIs contoso_ApproveOrder, contoso_GetSummary are not in this environment/);
+});
+
+test('judgeBindingTargets warns of a Custom API that is the other kind, or bound to another table — the runtime refuses such a call, so it is a warning and never a refusal', () => {
+ const verdict = judgeBindingTargets(pagesA, targetsOf({
+ references: [['contoso_msnweather', 'shared_msnweather'], ['contoso_sharepoint', 'shared_sharepointonline']],
+ apis: [['contoso_approveorder', { isFunction: true, boundEntity: 'contoso_item' }], ['contoso_getsummary', { isFunction: true, boundEntity: 'contoso_other' }]],
+ }));
+ assert.deepStrictEqual(verdict.findings.map((f) => [f.severity, f.kind, f.binding]), [['warn', 'api-mismatch', 'contoso_ApproveOrder'], ['warn', 'api-mismatch', 'contoso_GetSummary']]);
+ assert.strictEqual(verdict.findings[0].text, 'page "Weather": Custom API binding "contoso_ApproveOrder" says it is an Action, but the Custom API of that name in this environment is a Function — the runtime refuses the call (wrong_operation_kind)');
+ assert.strictEqual(verdict.findings[1].text, 'page "Weather": Custom API binding "contoso_GetSummary" is for a Global operation, but the Custom API of that name in this environment is bound to table contoso_other — the runtime refuses the call (invalid_bound_to)');
+ const unbound = judgeBindingTargets([{ key: 'a', name: 'A', actionBindings: [APPROVE] }], targetsOf({ apis: [['contoso_approveorder', { isFunction: false }]] }));
+ assert.strictEqual(unbound.findings[0].text, 'page "A": Custom API binding "contoso_ApproveOrder" is bound to table contoso_item, but the Custom API of that name in this environment is Global — the runtime refuses the call (invalid_bound_to)');
+ const differentTable = judgeBindingTargets([{ key: 'a', name: 'A', actionBindings: [APPROVE] }], targetsOf({ apis: [['contoso_approveorder', { isFunction: false, boundEntity: 'contoso_other' }]] }));
+ assert.strictEqual(differentTable.findings[0].text, 'page "A": Custom API binding "contoso_ApproveOrder" is bound to table contoso_item, but the Custom API of that name in this environment is bound to table contoso_other — the runtime refuses the call (invalid_bound_to)');
+ // An Action the binding does not say is a Function is an Action: the documented default.
+ const defaulted = judgeBindingTargets([{ key: 'a', name: 'A', actionBindings: [{ name: 'contoso_Plain' }] }], targetsOf({ apis: [['contoso_plain', { isFunction: false }]] }));
+ assert.deepStrictEqual(defaulted.findings, []);
+});
+
+test('judgeBindingTargets says what it could not check — and does not call a name missing when the read that would have found it failed', () => {
+ const verdict = judgeBindingTargets(pagesA, { references: null, apis: null, problems: { references: 'HTTP 403', apis: 'HTTP 500' } });
+ assert.deepStrictEqual(verdict.findings, []);
+ assert.deepStrictEqual(verdict.unchecked.map((u) => u.text), [
+ 'could not read this environment\'s connection references (HTTP 403), so the connector bindings of page "Weather" were not checked against them',
+ 'could not read this environment\'s Custom APIs (HTTP 500), so the Custom API bindings of page "Weather" were not checked against them',
+ ]);
+ const both = judgeBindingTargets([...pagesA, { key: 'b', name: 'B', connectorBindings: [WEATHER] }], { references: null, apis: new Map(), problems: { references: 'x' } });
+ assert.match(both.unchecked[0].text, /so the connector bindings of pages "Weather", "B" were not checked against them$/);
+ assert.deepStrictEqual(both.findings.map((f) => f.kind), ['api-missing'], 'the Custom APIs that were read are still judged');
+});
+
+test('a name is quoted the way a spec writes it, and a long or odd one is shortened — a message never carries more of a name than it needs', () => {
+ const long = `contoso_${'x'.repeat(200)}`;
+ const verdict = judgeBindingTargets([{ key: 'a', name: 'A', connectorBindings: [{ logicalName: long }] }], targetsOf());
+ assert.ok(verdict.findings[0].text.length < 500, String(verdict.findings[0].text.length));
+ assert.ok(!verdict.findings[0].text.includes(long));
+});
+
+// ── a reference with no connection, and the operations a custom connector defines ──────────────────────────────────────────────
+// A reference of the right connector is still no use to a page when it has no connection — what a solution import leaves when no settings file gives one — so that is said by name. And the operations a binding
+// calls are the connector's: a connector that is not a custom one has one definition for every environment of its cloud (the one the binding's operations were read from), but a CUSTOM connector's definition is a row of
+// the environment it is in — the `connector` table's `openapidefinition`, which the reference points at through `customconnectorid` — and the copy there can be another version than the page was made with.
+const WIDGETS = { logicalName: 'contoso_widgets', connectorId: api('shared_contoso-5fwidgets-5f6a8c'), dataset: '', operations: ['ListWidgets', 'GetWidget'] };
+const WIDGETS_CONNECTOR = 'c0000000-0000-4000-8000-0000000000a1';
+// A custom connector's definition as the `connector` row holds it: a Swagger 2.0 document, as text.
+const swaggerOf = (operationIds, extra = {}) => JSON.stringify({
+ swagger: '2.0', info: { title: 'Widgets', version: '1.0' }, host: 'widgets.contoso.example',
+ paths: Object.fromEntries(operationIds.map((id, i) => [`/widgets/op${i}`, { parameters: [{ name: 'id', in: 'query', type: 'string' }], [i % 2 ? 'post' : 'get']: { operationId: id, responses: { 200: { description: 'OK' } } } }])),
+ ...extra,
+});
+const connected = (row, connectionid = 'shared-connection-0001') => ({ ...row, connectionid });
+
+test('definedOperations reads the operation ids of a Swagger definition — every HTTP method of every path, and nothing else — and null for a text it cannot read as one', () => {
+ assert.deepStrictEqual([...definedOperations(swaggerOf(['ListWidgets', 'GetWidget']))], ['ListWidgets', 'GetWidget']);
+ const methods = JSON.stringify({ swagger: '2.0', paths: { '/w': { parameters: [], get: { operationId: 'A' }, put: { operationId: 'B' }, post: { operationId: 'C' }, delete: { operationId: 'D' }, options: { operationId: 'E' }, head: { operationId: 'F' }, patch: { operationId: 'G' }, 'x-ms-notification-content': { operationId: 'NotAnOperation' } } } });
+ assert.deepStrictEqual([...definedOperations(methods)], ['A', 'B', 'C', 'D', 'E', 'F', 'G'], 'a path item\'s parameters and its extensions are not operations');
+ assert.deepStrictEqual([...definedOperations(`\uFEFF${swaggerOf(['X'])}`)], ['X'], 'a byte-order mark is not part of the document');
+ assert.deepStrictEqual([...definedOperations(JSON.stringify({ swagger: '2.0', paths: {} }))], [], 'a definition with no operation defines none');
+ for (const unreadable of [undefined, null, '', 'not json', '[]', '{}', JSON.stringify({ paths: [] }), JSON.stringify({ paths: { '/w': { $ref: '#/x' } } })]) {
+ assert.strictEqual(definedOperations(unreadable), null, JSON.stringify(unreadable));
+ }
+});
+
+test('readBindingTargets keeps whether a reference has a connection and which custom connector it is for — only when the row says — and reads the definition of a custom connector a binding calls operations of, once', async () => {
+ const pages = [
+ { key: 'a', name: 'A', connectorBindings: [WIDGETS, WEATHER, SHAREPOINT] },
+ { key: 'b', name: 'B', connectorBindings: [{ ...WIDGETS, operations: ['GetWidget'] }] },
+ ];
+ const { provision, calls } = readerOf({
+ connectionreference: [
+ connected({ ...reference('contoso_widgets', 'shared_contoso-5fwidgets-5f6a8c'), _customconnectorid_value: WIDGETS_CONNECTOR.toUpperCase() }),
+ connected(reference('contoso_msnweather', 'shared_msnweather'), null),
+ { ...reference('contoso_sharepoint', 'shared_sharepointonline'), _customconnectorid_value: 'c0000000-0000-4000-8000-0000000000b2' },
+ ],
+ connector: [{ connectorid: WIDGETS_CONNECTOR, openapidefinition: swaggerOf(['ListWidgets']) }],
+ });
+ const targets = await readBindingTargets(provision, pages);
+ assert.deepStrictEqual(calls.map((c) => c.entity), ['connectionreference', 'connector'], 'the definition of the one custom connector a binding calls operations of: SharePoint\'s binding calls none');
+ assert.deepStrictEqual(calls[1].options.select, ['connectorid', 'openapidefinition']);
+ assert.strictEqual(calls[1].options.filter, `connectorid eq ${WIDGETS_CONNECTOR}`, 'by its id, once for both pages');
+ assert.deepStrictEqual([...targets.references], [
+ ['contoso_widgets', { connectorId: api('shared_contoso-5fwidgets-5f6a8c'), connected: true, customConnectorId: WIDGETS_CONNECTOR }],
+ ['contoso_msnweather', { connectorId: api('shared_msnweather'), connected: false }],
+ ['contoso_sharepoint', { connectorId: api('shared_sharepointonline'), customConnectorId: 'c0000000-0000-4000-8000-0000000000b2' }],
+ ], 'a row that does not carry `connectionid` says nothing of a connection');
+ assert.deepStrictEqual([...targets.definitions].map(([id, defined]) => [id, [...defined]]), [[WIDGETS_CONNECTOR, ['ListWidgets']]]);
+ assert.deepStrictEqual(targets.problems, {});
+
+ // A definition that is not there, or not one this can read, or a read of them that fails, is a problem of that connector's — never "it defines nothing".
+ for (const [rows, failOn, expected] of [
+ [[], undefined, /no connector row of that id was found/],
+ [[{ connectorid: WIDGETS_CONNECTOR, openapidefinition: 'not json' }], undefined, /its definition is not a Swagger document this build can read/],
+ [[], ['connector'], /connector: HTTP 403/],
+ ]) {
+ const reader = readerOf({ connectionreference: [connected({ ...reference('contoso_widgets', 'shared_contoso-5fwidgets-5f6a8c'), _customconnectorid_value: WIDGETS_CONNECTOR })], connector: rows }, { failOn });
+ const read = await readBindingTargets(reader.provision, [pages[0]]);
+ const defined = read.definitions.get(WIDGETS_CONNECTOR);
+ assert.ok(!(defined instanceof Set), JSON.stringify(rows));
+ assert.match(defined.problem, expected);
+ assert.ok(read.references instanceof Map, 'the references are still judged');
+ }
+
+ // A binding that calls no operation, or a reference for no custom connector, needs no definition: nothing more is read.
+ const plain = readerOf({ connectionreference: [connected({ ...reference('contoso_widgets', 'shared_contoso-5fwidgets-5f6a8c'), _customconnectorid_value: WIDGETS_CONNECTOR }), connected(reference('contoso_msnweather', 'shared_msnweather'))] });
+ const read = await readBindingTargets(plain.provision, [{ key: 'a', name: 'A', connectorBindings: [{ ...WIDGETS, operations: [] }, WEATHER] }]);
+ assert.deepStrictEqual(plain.calls.map((c) => c.entity), ['connectionreference']);
+ assert.strictEqual(read.definitions, null);
+});
+
+const targetsWith = (references, definitions = []) => ({
+ references: new Map(references),
+ apis: null,
+ definitions: new Map(definitions),
+ problems: {},
+});
+
+test('judgeBindingTargets says by name a reference of the right connector that has no connection — the page\'s calls through it fail until it has one — and says nothing of one whose row did not say', () => {
+ const pages = [{ key: 'weather', name: 'Weather', connectorBindings: [WEATHER, SHAREPOINT] }];
+ const one = judgeBindingTargets(pages, targetsWith([['contoso_msnweather', { connectorId: api('shared_msnweather'), connected: false }], ['contoso_sharepoint', { connectorId: api('shared_sharepointonline'), connected: true }]]));
+ assert.deepStrictEqual(one.findings.map((f) => [f.severity, f.kind, f.page.key, f.names]), [['warn', 'connection-missing', 'weather', ['contoso_msnweather']]]);
+ assert.strictEqual(one.findings[0].text, 'page "Weather": connection reference contoso_msnweather is in this environment but has no connection, so the page\'s calls through it fail until it has one. Give it a connection (import the solution that holds it with a settings file that does: solution-settings.js, or set it in Power Apps, in the solution\'s connection references) and the page works without a rebuild');
+ const both = judgeBindingTargets(pages, targetsWith([['contoso_msnweather', { connectorId: api('shared_msnweather'), connected: false }], ['contoso_sharepoint', { connectorId: api('shared_sharepointonline'), connected: false }]]));
+ assert.match(both.findings[0].text, /^page "Weather": connection references contoso_msnweather, contoso_sharepoint are in this environment but have no connection, so the page's calls through them fail until they have one\. Give them a connection/);
+ const unknown = judgeBindingTargets(pages, targetsWith([['contoso_msnweather', { connectorId: api('shared_msnweather') }], ['contoso_sharepoint', { connectorId: api('shared_sharepointonline') }]]));
+ // A row that does not carry `connectionid` proves nothing: it is NOT CHECKED, said by name — and not a finding.
+ assert.deepStrictEqual(unknown.findings, []);
+ assert.deepStrictEqual(unknown.unchecked.filter((u) => u.what === 'reference connections').map((u) => u.text), ['this environment\'s rows for connection references contoso_msnweather, contoso_sharepoint did not say, in a form this build can read, whether they have a connection, so that was not checked for page "Weather"']);
+ // A reference for another connector is refused, and nothing else is said of it.
+ const conflict = judgeBindingTargets(pages, targetsWith([['contoso_msnweather', { connectorId: api('shared_office365users'), connected: false }], ['contoso_sharepoint', { connectorId: api('shared_sharepointonline'), connected: true }]]));
+ assert.deepStrictEqual(conflict.findings.map((f) => f.kind), ['connector-conflict']);
+});
+
+test('judgeBindingTargets says by name an operation a binding calls that the custom connector of its reference does not define here — a warning, the page is written — and nothing for one it defines', () => {
+ const widgetsReference = { connectorId: WIDGETS.connectorId, connected: true, customConnectorId: WIDGETS_CONNECTOR };
+ const pages = [{ key: 'widgets', name: 'Widgets', connectorBindings: [WIDGETS, { ...WIDGETS }] }];
+ const verdict = judgeBindingTargets(pages, targetsWith([['contoso_widgets', widgetsReference]], [[WIDGETS_CONNECTOR, new Set(['ListWidgets'])]]));
+ assert.deepStrictEqual(verdict.findings.map((f) => [f.severity, f.kind, f.binding, f.operations]), [['warn', 'operation-missing', 'contoso_widgets', ['GetWidget']]], 'said once for the binding, however often the page lists it');
+ assert.strictEqual(verdict.findings[0].text, 'page "Widgets": connector binding "contoso_widgets" calls operation GetWidget, which the custom connector that connection reference is for in this environment does not define, so the page\'s call to it fails there until it does (import the solution that holds the connector as the page was made with it)');
+ const several = judgeBindingTargets(pages, targetsWith([['contoso_widgets', widgetsReference]], [[WIDGETS_CONNECTOR, new Set(['Other'])]]));
+ assert.match(several.findings[0].text, /calls operations ListWidgets, GetWidget, which the custom connector that connection reference is for in this environment does not define, so the page's calls to them fail there until it does/);
+ const defined = judgeBindingTargets(pages, targetsWith([['contoso_widgets', widgetsReference]], [[WIDGETS_CONNECTOR, new Set(['ListWidgets', 'GetWidget', 'DeleteWidget'])]]));
+ assert.deepStrictEqual(defined, { findings: [], unchecked: [] });
+ // Matched exactly, as the connector matches an operation id: another case is another operation.
+ const cased = judgeBindingTargets(pages, targetsWith([['contoso_widgets', widgetsReference]], [[WIDGETS_CONNECTOR, new Set(['listwidgets', 'GetWidget'])]]));
+ assert.deepStrictEqual(cased.findings.map((f) => f.operations), [['ListWidgets']]);
+ // A reference whose row names no custom connector — a connector the platform publishes, or a lookup left unset — is never asked for a definition, and its operations are said to be NOT CHECKED: a null
+ // lookup is no proof that the connector is not a custom one.
+ const managed = judgeBindingTargets([{ key: 'weather', name: 'Weather', connectorBindings: [WEATHER] }], targetsWith([['contoso_msnweather', { connectorId: WEATHER.connectorId, connected: true }]]));
+ assert.deepStrictEqual(managed.findings, []);
+ assert.deepStrictEqual(managed.unchecked.map((u) => u.what), ['custom connector definitions']);
+ assert.match(managed.unchecked[0].text, /^the operations that connector binding "contoso_msnweather" of page "Weather" call were not checked/);
+});
+
+test('judgeBindingTargets says which operations it could not check, and why — a definition it could not read is never one that defines nothing', () => {
+ const widgetsReference = { connectorId: WIDGETS.connectorId, connected: true, customConnectorId: WIDGETS_CONNECTOR };
+ const pages = [{ key: 'widgets', name: 'Widgets', connectorBindings: [WIDGETS] }];
+ const verdict = judgeBindingTargets(pages, targetsWith([['contoso_widgets', widgetsReference]], [[WIDGETS_CONNECTOR, { problem: 'connector: HTTP 403' }]]));
+ assert.deepStrictEqual(verdict.findings, []);
+ assert.deepStrictEqual(verdict.unchecked.map((u) => u.text), ['could not read the definition of the custom connector that connection reference contoso_widgets is for in this environment (connector: HTTP 403), so the operations connector binding "contoso_widgets" of page "Widgets" calls were not checked against it']);
+ const notRead = judgeBindingTargets(pages, { references: new Map([['contoso_widgets', widgetsReference]]), apis: null, problems: {} });
+ assert.match(notRead.unchecked[0].text, /\(its definition was not read\)/);
+});
+
+// ── successful but incomplete: a row that answers without a column the check needs ──────────────────────────────────────────────
+// A read that FAILS is said as not checked. So is a read that SUCCEEDS with a row that lacks what the check needs — the custom connector lookup absent, null or not a GUID, no `connectionid`, no
+// `connectorid`: none of it is evidence of compatibility, and none of it is evidence of a conflict either. Each is said by name as not checked; nothing is refused; what the row did prove is still judged.
+test('a successful answer that lacks a column the check needs is NOT CHECKED, by name — a missing, null or invalid lookup, a missing connectionid or connectorid — and never read as compatible', async () => {
+ const page = { key: 'widgets', name: 'Widgets', connectorBindings: [WIDGETS] };
+ const complete = { connectionreferencelogicalname: 'contoso_widgets', connectorid: WIDGETS.connectorId, connectionid: 'shared-connection-0001', _customconnectorid_value: WIDGETS_CONNECTOR };
+ const definition = { connectorid: WIDGETS_CONNECTOR, openapidefinition: swaggerOf(['ListWidgets']) };
+ const without = (row, ...keys) => { const out = { ...row }; for (const key of keys) delete out[key]; return out; };
+ const judge = async (row) => {
+ const { provision, calls } = readerOf({ connectionreference: [row], connector: [definition] });
+ return { ...judgeBindingTargets([page], await readBindingTargets(provision, [page])), reads: calls.map((c) => c.entity) };
+ };
+ const kinds = (verdict) => [verdict.findings.map((f) => f.kind), verdict.unchecked.map((u) => u.what)];
+
+ // The control: a complete row, and the definition there lacks GetWidget.
+ assert.deepStrictEqual(kinds(await judge(complete)), [['operation-missing'], []]);
+
+ for (const [label, row] of [['a missing lookup', without(complete, '_customconnectorid_value')], ['a null lookup', { ...complete, _customconnectorid_value: null }], ['a lookup that is no GUID', { ...complete, _customconnectorid_value: 'not-a-guid' }]]) {
+ const verdict = await judge(row);
+ assert.deepStrictEqual(kinds(verdict), [[], ['custom connector definitions']], label);
+ assert.deepStrictEqual(verdict.reads, ['connectionreference'], `${label}: no definition is read, as there is none to read by`);
+ assert.strictEqual(verdict.unchecked[0].text, 'the operations that connector binding "contoso_widgets" of page "Widgets" call were not checked: this environment does not name a custom connector for its connection reference, and only a custom connector\'s definition is read here (a connector the platform publishes defines the same operations in every environment of its cloud)');
+ }
+ const noConnection = await judge(without(complete, 'connectionid'));
+ assert.deepStrictEqual(kinds(noConnection), [['operation-missing'], ['reference connections']], 'what the row did prove is still judged');
+ const noConnector = await judge(without(complete, 'connectorid'));
+ assert.deepStrictEqual(kinds(noConnector), [['operation-missing'], ['reference connectors']]);
+ const bare = await judge(without(complete, 'connectorid', 'connectionid', '_customconnectorid_value'));
+ assert.deepStrictEqual(kinds(bare), [[], ['reference connectors', 'reference connections', 'custom connector definitions']]);
+ assert.ok(bare.findings.every((f) => f.severity !== 'refuse'), 'missing evidence never refuses');
+});
+
+// ── malformed, not missing: a row that answers with a value of the wrong shape ──────────────────────────────────────────────────
+// A value that is THERE but is not what the column holds proves nothing either. A `connectorid` that is not a connector's API id as Dataverse writes it (`/providers/Microsoft.PowerApps/apis/shared_<name>`) —
+// `***`, a bare name, a number, an object — is not compared: it is NOT CHECKED, said by name, and never a conflict, so it never stops a rebuild. A `connectionid` that is not a text is not "no connection":
+// only null or a blank text says that. Two VALID connector ids that differ are still refused.
+test('a malformed connectorid or connectionid in a successful answer is NOT CHECKED — never a refusal, never "no connection" — while two valid, different connectors are still refused', async () => {
+ const page = { key: 'weather', name: 'Weather', connectorBindings: [WEATHER] };
+ const judge = async (row) => {
+ const { provision } = readerOf({ connectionreference: [row] });
+ return judgeBindingTargets([page], await readBindingTargets(provision, [page]));
+ };
+ const row = { connectionreferencelogicalname: 'contoso_msnweather', connectorid: WEATHER.connectorId, connectionid: 'shared-connection-0001', _customconnectorid_value: null };
+ for (const connectorid of ['***', 'shared_office365users', '/providers/Microsoft.PowerApps/apis/', '/providers/Microsoft.PowerApps/apis/office365users', '/providers/Microsoft.PowerApps/apis/shared_x/extra', 42, { id: 'shared_x' }, ['/providers/Microsoft.PowerApps/apis/shared_x'], true]) {
+ const verdict = await judge({ ...row, connectorid });
+ assert.deepStrictEqual(verdict.findings, [], `${JSON.stringify(connectorid)}: no finding, and never a refusal`);
+ assert.ok(verdict.unchecked.some((u) => u.what === 'reference connectors'), `${JSON.stringify(connectorid)}: said as not checked`);
+ }
+ for (const connectionid of [42, { id: 'x' }, true, ['shared-connection-0001']]) {
+ const verdict = await judge({ ...row, connectionid });
+ assert.deepStrictEqual(verdict.findings, [], `${JSON.stringify(connectionid)}: not "no connection"`);
+ assert.ok(verdict.unchecked.some((u) => u.what === 'reference connections'), `${JSON.stringify(connectionid)}: said as not checked`);
+ }
+ // What the column DOES say is still judged: null or a blank text is no connection, and a valid connector id of another connector is a conflict.
+ for (const connectionid of [null, '', ' ']) assert.deepStrictEqual((await judge({ ...row, connectionid })).findings.map((f) => f.kind), ['connection-missing'], JSON.stringify(connectionid));
+ const conflict = await judge({ ...row, connectorid: '/providers/Microsoft.PowerApps/apis/SHARED_OFFICE365USERS' });
+ assert.deepStrictEqual(conflict.findings.map((f) => [f.severity, f.kind, f.found]), [['refuse', 'connector-conflict', 'shared_office365users']]);
+ // A binding whose own connectorId is not a connector id is not compared either: there is nothing to contradict.
+ const odd = { key: 'weather', name: 'Weather', connectorBindings: [{ ...WEATHER, connectorId: 'contoso' }] };
+ const { provision } = readerOf({ connectionreference: [{ ...row, connectorid: '/providers/Microsoft.PowerApps/apis/shared_office365users' }] });
+ assert.deepStrictEqual(judgeBindingTargets([odd], await readBindingTargets(provision, [odd])).findings, []);
+});
diff --git a/plugins/model-apps/scripts/tests/page-bindings-real-bundle.test.js b/plugins/model-apps/scripts/tests/page-bindings-real-bundle.test.js
new file mode 100644
index 000000000..5843c34bf
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/page-bindings-real-bundle.test.js
@@ -0,0 +1,433 @@
+'use strict';
+// A page's connector and Custom API bindings through the REAL vendored SDK, over the stateful fake of the tables behind a page (helpers/fake-genpage-server.js).
+//
+// page-bindings.test.js holds the logic with a stand-in for the page backend. What only the real bundle can say, and what a download and a rebuild rest on:
+// - a page the maker laid out, with `connectorBindings` and `actionBindings` in its config.json, is read with both lists, and the folder a download writes holds them;
+// - the lists the download projects, sent back as the spec states them, change nothing — not one row is written — so a rebuild of a downloaded spec costs a page no write;
+// - a list that is changed is written, and what the page holds beside it (a property of config.json the SDK does not model, its prompt, its conversation) is kept;
+// - the same lists, given to a create in another environment, are in the config.json of the page that is made there.
+const { test } = require('node:test');
+const assert = require('node:assert');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { makeGenpageSdk, pageFolderFiles, contentFingerprint } = require('../lib/genpage-sdk.js');
+const { statedPageBindings } = require('../lib/app-spec.js');
+const { parseDownloadedPages, pageBindingsReport } = require('../download-model-app.js');
+const { FakeGenPageServer, INSTANCE, ACCOUNT_TABLE } = require('./helpers/fake-genpage-server.js');
+
+const SOURCE = "import * as React from 'react';\nexport default function Page() { return <div>Hello</div>; }\n";
+const ID = 'd0000000-0000-4000-8000-000000000042';
+const WEATHER = { logicalName: 'contoso_msnweather', connectorId: '/providers/Microsoft.PowerApps/apis/shared_msnweather', dataset: '', operations: ['CurrentWeather'] };
+const SHAREPOINT = { logicalName: 'contoso_sharepoint', connectorId: '/providers/Microsoft.PowerApps/apis/shared_sharepointonline', dataset: 'https://contoso.sharepoint.com/sites/x', tables: ['11111111-2222-3333-4444-555555555555'], tableDisplayNames: ['Pets'] };
+const APPROVE = { name: 'contoso_ApproveOrder', isFunction: false, boundEntityLogicalName: 'account', displayName: 'Approve order', parameterKinds: { Comment: 'String' } };
+
+const tempDirs = [];
+test.after(() => { for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true }); });
+
+function makeServer() {
+ const server = new FakeGenPageServer();
+ server.serveTable(ACCOUNT_TABLE);
+ return server;
+}
+
+// A backend over the real bundle, on a throwaway workspace that dispose() removes.
+async function withBackend(server, fn) {
+ const genpage = makeGenpageSdk(INSTANCE, { httpClient: server.http() });
+ try {
+ return await fn(genpage);
+ } finally {
+ await genpage.dispose();
+ }
+}
+
+// What a download makes of a page the backend read: the folder it writes (lib/genpage-sdk.js pageFolderFiles), read back as the spec's page entry.
+function downloaded(page, unkept = []) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'page-bindings-real-'));
+ tempDirs.push(root);
+ const dir = path.join(root, page.id);
+ fs.mkdirSync(dir, { recursive: true });
+ for (const [name, text] of Object.entries(pageFolderFiles(page))) fs.writeFileSync(path.join(dir, name), text, 'utf8');
+ const [entry] = parseDownloadedPages(root, root, null, [], [], unkept);
+ return { entry, configText: fs.readFileSync(path.join(dir, 'config.json'), 'utf8') };
+}
+
+const changeWrites = (server) => server.writes().filter((w) => !/PublishXml/.test(w));
+// The reads of a page's rows that are NOT of the draft: a read without `MSCRM.IncludeUnpublished` is served the published layer.
+const publishedLayerReads = (server) => server.requests.filter((r) => r.method === 'GET' && /^\/uxagentproject/.test(r.path) && !('MSCRM.IncludeUnpublished' in r.headers));
+const rows = (server, id) => Object.fromEntries(server.filesOf(id).map((f) => [f.filename, server.fileText(f.id)]));
+
+// The page the maker laid out: two lists, a data source, a model, and a property of config.json that the SDK has no field for.
+function seededServer(config = {}) {
+ const server = makeServer();
+ server.seedPage(ID, {
+ name: 'Weather', source: SOURCE, prompt: 'Show the weather', agentMessage: 'Shown',
+ config: { dataSources: ['account'], model: 'gpt-4.1', connectorBindings: [WEATHER, SHAREPOINT], futureSetting: { kept: true }, actionBindings: [APPROVE], ...config },
+ });
+ return server;
+}
+
+test('REAL BUNDLE: a page the maker laid out is read with both binding lists, and the spec\'s page entry holds exactly what its config.json does', async () => {
+ const server = seededServer();
+ await withBackend(server, async (genpage) => {
+ const page = await genpage.read(ID);
+ assert.deepStrictEqual(page.connectorBindings, [WEATHER, SHAREPOINT]);
+ assert.deepStrictEqual(page.actionBindings, [APPROVE]);
+ const unkept = [];
+ const { entry, configText } = downloaded(page, unkept);
+ assert.deepStrictEqual(entry.connectorBindings, [WEATHER, SHAREPOINT]);
+ assert.deepStrictEqual(entry.actionBindings, [APPROVE]);
+ assert.deepStrictEqual(unkept, []);
+ // The folder keeps the whole config.json, the property the spec has no field for included.
+ assert.deepStrictEqual(JSON.parse(configText), { dataSources: ['account'], model: 'gpt-4.1', connectorBindings: [WEATHER, SHAREPOINT], futureSetting: { kept: true }, actionBindings: [APPROVE] });
+ assert.deepStrictEqual(pageBindingsReport([{ ...entry, key: 'weather', name: 'Weather' }], []).neededInTarget, {
+ connectionReferences: ['contoso_msnweather', 'contoso_sharepoint'], customApis: ['contoso_ApproveOrder'], serviceResources: ['contoso_sharepoint'],
+ });
+ });
+});
+
+test('REAL BUNDLE: the lists a download states, sent back by a rebuild, change nothing — not one row is written, and the page is not read as different', async () => {
+ const server = seededServer();
+ await withBackend(server, async (genpage) => {
+ const { entry } = downloaded(await genpage.read(ID));
+ const before = rows(server, ID);
+ server.requests.length = 0;
+ const out = await genpage.update(ID, { source: SOURCE, name: 'Weather', dataSources: entry.dataSources, model: entry.model, ...statedPageBindings(entry), prompt: 'again', agentMessage: 'again' });
+ assert.strictEqual(out.unchanged, true);
+ assert.deepStrictEqual(changeWrites(server), [], 'the page already holds what the spec states');
+ assert.deepStrictEqual(rows(server, ID), before);
+ });
+});
+
+test('REAL BUNDLE: a list that is changed is written, and everything else the page holds — a property the SDK does not model, the other list, its prompt and its conversation — is kept', async () => {
+ const server = seededServer();
+ await withBackend(server, async (genpage) => {
+ const { entry } = downloaded(await genpage.read(ID));
+ const messages = server.messagesOf(ID).map((m) => m.message);
+ // The spec drops SharePoint from the connector list and clears nothing else: the Custom API list is not stated, so it is the page's own.
+ await genpage.update(ID, { source: SOURCE, name: 'Weather', dataSources: entry.dataSources, model: entry.model, connectorBindings: [WEATHER], prompt: 'again', agentMessage: 'again' });
+ const config = JSON.parse(rows(server, ID)['config.json']);
+ assert.deepStrictEqual(config.connectorBindings, [WEATHER], 'the stated list is the page\'s now');
+ assert.deepStrictEqual(config.actionBindings, [APPROVE], 'a list the update does not state is the page\'s own');
+ assert.deepStrictEqual(config.futureSetting, { kept: true }, 'a property the SDK does not model is kept');
+ assert.deepStrictEqual([config.dataSources, config.model], [['account'], 'gpt-4.1']);
+ assert.deepStrictEqual(JSON.parse(rows(server, ID)['firstPrompt.json']), { userMessage: 'Show the weather', agentMessage: 'Shown' }, 'the first prompt is not rewritten');
+ assert.deepStrictEqual(server.messagesOf(ID).map((m) => m.message).slice(0, messages.length), messages, 'the conversation it had is kept');
+
+ // `[]` is a statement: it clears the list.
+ await genpage.update(ID, { source: SOURCE, name: 'Weather', dataSources: entry.dataSources, model: entry.model, actionBindings: [], prompt: 'cleared', agentMessage: 'cleared' });
+ const cleared = JSON.parse(rows(server, ID)['config.json']);
+ assert.deepStrictEqual([cleared.actionBindings, cleared.connectorBindings], [[], [WEATHER]]);
+ });
+});
+
+test('REAL BUNDLE: the lists a download stated, given to a create in ANOTHER environment, are in the config.json of the page that is made there — and a download of that page states them again', async () => {
+ const source = seededServer();
+ let entry;
+ await withBackend(source, async (genpage) => { ({ entry } = downloaded(await genpage.read(ID))); });
+
+ const target = makeServer();
+ await withBackend(target, async (genpage) => {
+ const out = await genpage.create({ name: 'Weather', source: SOURCE, dataSources: entry.dataSources, model: entry.model, ...statedPageBindings(entry), prompt: 'Show the weather', agentMessage: 'Shown' });
+ const config = JSON.parse(rows(target, out.pageId)['config.json']);
+ assert.deepStrictEqual(config, { dataSources: ['account'], model: 'gpt-4.1', connectorBindings: [WEATHER, SHAREPOINT], actionBindings: [APPROVE] });
+ const again = downloaded(await genpage.read(out.pageId)).entry;
+ assert.deepStrictEqual([again.connectorBindings, again.actionBindings], [entry.connectorBindings, entry.actionBindings]);
+ });
+
+ // And a create that is given none writes none: no key, no empty list.
+ const plain = makeServer();
+ await withBackend(plain, async (genpage) => {
+ const out = await genpage.create({ name: 'Plain', source: SOURCE, dataSources: ['account'], model: 'gpt-4.1', prompt: 'p', agentMessage: 'r', ...statedPageBindings({ key: 'plain' }) });
+ assert.deepStrictEqual(JSON.parse(rows(plain, out.pageId)['config.json']), { dataSources: ['account'], model: 'gpt-4.1' });
+ });
+});
+
+test('REAL BUNDLE: a page whose config.json holds null, or an empty list, for a binding list is downloaded as a page that holds none — nothing is stated and nothing is reported', async () => {
+ const server = seededServer({ connectorBindings: null, actionBindings: [] });
+ await withBackend(server, async (genpage) => {
+ const unkept = [];
+ const { entry } = downloaded(await genpage.read(ID), unkept);
+ assert.ok(!('connectorBindings' in entry) && !('actionBindings' in entry));
+ assert.deepStrictEqual(unkept, []);
+ assert.strictEqual(pageBindingsReport([{ ...entry, key: 'weather', name: 'Weather' }], unkept), null);
+ });
+});
+
+test('declared Custom API kinds: REAL BUNDLE omission preserves unsupported payloads until an explicit primitive correction', async (t) => {
+ for (const kind of ['EntityReference', 'Entity', 'EntityCollection']) {
+ await t.test(`declared Custom API kinds: REAL BUNDLE preserves ${kind}`, async () => {
+ const bad = { name: 'contoso_ResolveReference', isFunction: false, parameterKinds: { Ref: kind, Note: 'String' } };
+ const held = [APPROVE, bad];
+ const server = seededServer({ actionBindings: held });
+ await withBackend(server, async (genpage) => {
+ const unkept = [];
+ const { entry } = downloaded(await genpage.read(ID), unkept);
+ assert.ok(!Object.hasOwn(entry, 'actionBindings'), 'the whole action list is omitted, not repaired or partially projected');
+ assert.match(unkept[0].reason, /^actionBindings\[1\]\.parameterKinds /);
+ assert.ok(!JSON.stringify(unkept).includes(kind), 'unsupported values stay only in the raw page config');
+ const record = (await genpage.update(ID, { ...SENT })).fingerprint;
+ const before = rows(server, ID);
+ server.requests.length = 0;
+ server.published.length = 0;
+ const unchanged = await genpage.update(ID, { ...SENT, ...statedPageBindings(entry), specBindings: true, publishedFingerprint: record });
+ assert.deepStrictEqual([unchanged.unchanged, unchanged.publish.kind], [true, 'skipped']);
+ assert.deepStrictEqual(server.writes(), []);
+ assert.deepStrictEqual(server.published, []);
+ assert.deepStrictEqual(rows(server, ID), before, 'omission preserves the exact deployed payload, including the unsupported map');
+
+ const corrected = [APPROVE, { ...bad, parameterKinds: { Note: 'String' } }];
+ await genpage.update(ID, { ...SENT, actionBindings: corrected, specBindings: true, publishedFingerprint: record });
+ const config = JSON.parse(rows(server, ID)['config.json']);
+ assert.deepStrictEqual(config.actionBindings, corrected, 'only explicit author intent replaces the declared map');
+ assert.deepStrictEqual(config.connectorBindings, [WEATHER, SHAREPOINT]);
+ assert.deepStrictEqual(config.futureSetting, { kept: true });
+ });
+ });
+ }
+});
+
+test('declared Custom API kinds: REAL BUNDLE sparse and lookup-only calls retain structural source and binding maps', async (t) => {
+ for (const parameterKinds of [{ Note: 'String' }, {}]) {
+ await t.test(`declared Custom API kinds: REAL BUNDLE ${Object.keys(parameterKinds).length ? 'sparse' : 'lookup-only'} call`, async () => {
+ const binding = { name: 'contoso_ResolveReference', isFunction: false, parameterKinds };
+ const parameters = Object.keys(parameterKinds).length ? ", Note: 'Selected'" : '';
+ const lookupSource = `import * as React from 'react';
+export default function Page(props: { dataApi: { executeAction: Function }; pageInput: { accountId: string } }) {
+ return <button onClick={() => props.dataApi.executeAction({ name: 'contoso_ResolveReference', parameters: { Ref: { entityName: 'account', id: props.pageInput.accountId }${parameters} } })}>Resolve</button>;
+}
+`;
+ const server = makeServer();
+ server.seedPage(ID, { name: 'Weather', source: lookupSource, prompt: 'Resolve selected record', agentMessage: 'Ready',
+ config: { dataSources: ['account'], model: 'gpt-4.1', connectorBindings: [WEATHER], actionBindings: [binding] } });
+ await withBackend(server, async (genpage) => {
+ const page = await genpage.read(ID);
+ assert.strictEqual(pageFolderFiles(page)['page.tsx'], lookupSource);
+ const { entry } = downloaded(page);
+ assert.deepStrictEqual(entry.actionBindings, [binding]);
+ assert.ok(!Object.hasOwn(entry.actionBindings[0].parameterKinds, 'Ref'));
+ assert.ok(!Object.hasOwn(entry.actionBindings[0], 'lookupParameters'));
+ const before = rows(server, ID);
+ server.requests.length = 0;
+ const out = await genpage.update(ID, { ...SENT, source: lookupSource, ...statedPageBindings(entry), specBindings: true });
+ assert.strictEqual(out.unchanged, true);
+ assert.deepStrictEqual(changeWrites(server), []);
+ assert.deepStrictEqual(rows(server, ID), before);
+ });
+ });
+ }
+});
+
+// ── a page that holds more than a spec states ────────────────────────────────────────────────────────────────────────────────
+// A binding a page holds can carry what a spec does not state: a connection id of the environment it was made in, a credential someone wrote into a connectors.json, a property a later runtime adds. A download
+// leaves such a list out of the spec WHOLE (page-bindings.js), so a rebuild sends nothing for it and the page keeps it. A list an AUTHOR states for such a page is read by the build as "what the page already
+// holds" (`specBindings: true`): a binding the spec changes is changed, and what the spec does not state stays on the entry. The backend's other callers replace a list with what they give, as they always did.
+const WEATHER_ON_PAGE = { ...WEATHER, connectionId: 'env-local-connection-placeholder', futureProperty: { kept: true } };
+const SHAREPOINT_ON_PAGE = { ...SHAREPOINT, apiKey: 'SYNTHETIC_TEST_SECRET' };
+const APPROVE_ON_PAGE = { ...APPROVE, headers: { note: 'kept' } };
+const pageHolding = () => seededServer({ connectorBindings: [WEATHER_ON_PAGE, SHAREPOINT_ON_PAGE], actionBindings: [APPROVE_ON_PAGE] });
+const SENT = { source: SOURCE, name: 'Weather', dataSources: ['account'], model: 'gpt-4.1', prompt: 'again', agentMessage: 'again' };
+// What an author states for that page: the documented properties of each binding.
+const AUTHORED = { connectorBindings: [WEATHER, SHAREPOINT], actionBindings: [APPROVE] };
+
+// An identity a spec cannot state, beside a property a spec does not state, in BOTH kinds of list: a projection that kept the rest would write an entry with no identity, and a rebuild would REPLACE the
+// page's entry with it — identity, connection id and all. The download leaves both lists out instead; the rebuild of that spec, with the record of the page's last publish, writes and publishes nothing.
+test('REAL BUNDLE: a page whose lists hold an identity a spec cannot state is downloaded without those lists, and a rebuild of that spec writes nothing, publishes nothing, and keeps every entry as it was', async () => {
+ const connector = { ...WEATHER, logicalName: 'Bearer SYNTHETIC_TEST_ACCESS_TOKEN', connectionId: 'env-local-connection-placeholder', futureProperty: { kept: true } };
+ const action = { ...APPROVE, name: `ghp_${'R'.repeat(36)}`, headers: { note: 'kept' } };
+ const server = seededServer({ connectorBindings: [connector, SHAREPOINT], actionBindings: [action] });
+ await withBackend(server, async (genpage) => {
+ const unkept = [];
+ const { entry } = downloaded(await genpage.read(ID), unkept);
+ assert.ok(!('connectorBindings' in entry) && !('actionBindings' in entry), 'neither list is in the spec: nothing is projected out of them');
+ assert.deepStrictEqual(unkept.map((u) => [u.field, u.reason]), [
+ ['connectorBindings', 'connectorBindings[0].logicalName must be an identifier (a letter, then letters, digits, _ . -)'],
+ ['actionBindings', 'actionBindings[0].name must be an identifier (a letter, then letters, digits, _ . -)'],
+ ]);
+ assert.ok(!/SYNTHETIC|ghp_/.test(JSON.stringify(unkept)), 'the reason never quotes the value');
+
+ // The build's record of the page's last publish, made by a build whose spec stated no lists — what a download into the same folder meets.
+ const record = (await genpage.update(ID, { ...SENT })).fingerprint;
+ const before = rows(server, ID);
+ server.requests.length = 0;
+ server.published.length = 0;
+ const out = await genpage.update(ID, { ...SENT, ...statedPageBindings(entry), specBindings: true, publishedFingerprint: record });
+ assert.deepStrictEqual([out.unchanged, out.publish.kind], [true, 'skipped']);
+ assert.deepStrictEqual(server.writes(), [], 'not a row written and no PublishXml');
+ assert.deepStrictEqual(server.published, []);
+ assert.deepStrictEqual(rows(server, ID), before, 'every entry as it was: identity, connection id, the property no spec states');
+ const held = JSON.parse(rows(server, ID)['config.json']);
+ assert.deepStrictEqual([held.connectorBindings, held.actionBindings], [[connector, SHAREPOINT], [action]]);
+ });
+});
+
+test('REAL BUNDLE: a list an author states for a page that holds more changes nothing when the page holds it — not one row is written — and other callers still replace a list', async () => {
+ const server = pageHolding();
+ await withBackend(server, async (genpage) => {
+ const before = rows(server, ID);
+ server.requests.length = 0;
+ const out = await genpage.update(ID, { ...SENT, ...AUTHORED, specBindings: true });
+ assert.strictEqual(out.unchanged, true, 'the page already holds what the spec states');
+ assert.deepStrictEqual(changeWrites(server), [], 'not a row written');
+ assert.deepStrictEqual(rows(server, ID), before, 'the page keeps what the spec does not state');
+ // The other callers of the backend replace a list with the one they give, as they always did.
+ await genpage.update(ID, { ...SENT, ...AUTHORED, prompt: 'replaced', agentMessage: 'replaced' });
+ const replaced = JSON.parse(rows(server, ID)['config.json']);
+ assert.deepStrictEqual([replaced.connectorBindings, replaced.actionBindings], [[WEATHER, SHAREPOINT], [APPROVE]]);
+ });
+});
+
+test('REAL BUNDLE: a spec that changes one binding changes that binding, and the page keeps the rest of its entries as they were — what a spec does not state included', async () => {
+ const server = pageHolding();
+ await withBackend(server, async (genpage) => {
+ const entry = AUTHORED;
+ const messages = server.messagesOf(ID).length;
+ // Weather's operations change, SharePoint is dropped, and the Custom API list is as it was.
+ await genpage.update(ID, { ...SENT, connectorBindings: [{ ...entry.connectorBindings[0], operations: ['Forecast'] }], actionBindings: entry.actionBindings, specBindings: true });
+ const config = JSON.parse(rows(server, ID)['config.json']);
+ assert.deepStrictEqual(config.connectorBindings, [{ ...WEATHER_ON_PAGE, operations: ['Forecast'] }], 'the edited entry keeps its connection id and its property no spec states; the dropped entry is gone');
+ assert.deepStrictEqual(config.actionBindings, [APPROVE_ON_PAGE], 'a list the edit left as the page held it is not rewritten');
+ assert.deepStrictEqual(config.futureSetting, { kept: true });
+ assert.strictEqual(server.messagesOf(ID).length, messages + 2, 'and the change is a turn of the conversation, as any update is');
+
+ // A binding the spec adds is written as the spec states it; one whose name is changed is a new binding, and takes nothing of the old one's.
+ const added = { logicalName: 'contoso_new', connectorId: '/providers/Microsoft.PowerApps/apis/shared_new', operations: ['Do'] };
+ await genpage.update(ID, { ...SENT, connectorBindings: [{ ...WEATHER, operations: ['Forecast'] }, added], actionBindings: [{ ...APPROVE, name: 'contoso_Renamed' }], specBindings: true });
+ const next = JSON.parse(rows(server, ID)['config.json']);
+ assert.deepStrictEqual(next.connectorBindings, [{ ...WEATHER_ON_PAGE, operations: ['Forecast'] }, added]);
+ assert.deepStrictEqual(next.actionBindings, [{ ...APPROVE, name: 'contoso_Renamed' }]);
+
+ // `[]` is still a statement: it clears the list, and the entries with it.
+ await genpage.update(ID, { ...SENT, connectorBindings: [], specBindings: true });
+ assert.deepStrictEqual(JSON.parse(rows(server, ID)['config.json']).connectorBindings, []);
+ });
+});
+
+test('REAL BUNDLE: the published copy of a page that holds more is read as holding the spec\'s lists, when the build says they are a spec\'s — no false "published again from elsewhere"', async () => {
+ const server = pageHolding();
+ await withBackend(server, async (genpage) => {
+ const asked = { ...SENT, ...AUTHORED };
+ // A first publish of the page as it is: the build's rebuild of a page nobody recorded.
+ const first = await genpage.update(ID, { ...asked, specBindings: true });
+ assert.strictEqual(first.publish.kind, 'verified');
+ const plain = await genpage.publishedDiffers(ID, asked);
+ assert.deepStrictEqual(plain.differing, ['connectorBindings', 'actionBindings'], 'read as another caller reads it, the published copy holds more than the spec states');
+ const spec = await genpage.publishedDiffers(ID, { ...asked, specBindings: true });
+ assert.deepStrictEqual(spec.differing, [], 'read as the build\'s lists, it holds them');
+ assert.strictEqual(spec.fingerprint, first.fingerprint, 'and the fingerprint is the one an update answers for the same arguments');
+ const changed = await genpage.publishedDiffers(ID, { ...asked, connectorBindings: [{ ...WEATHER, operations: ['Forecast'] }], specBindings: true });
+ assert.deepStrictEqual(changed.differing, ['connectorBindings'], 'a list that differs from what was published still does');
+ });
+});
+
+// ── a record of a publish made before a download stated the bindings ─────────────────────────────────────────────────────────
+// The build keeps, per page, the hash of the content it published (contentFingerprint) and hands it back to the next update, which then does not publish a page it finds already holding that content. The hash covers
+// the lists a caller states, so a record made when the build stated none (every record before a download states them) is the hash of the same content WITHOUT them. A page that holds those lists, rebuilt by the
+// spec the download wrote, is the same content: it must not be written, and it must not be published again — only when the published copy is READ and holds the lists too.
+const asPublishedByAnOlderBuild = async (genpage) => (await genpage.update(ID, { ...SENT })).fingerprint;
+
+test('REAL BUNDLE: a record of a publish made before the lists were stated still stands for the page when a spec states them — nothing is written, nothing is published, and the record is renewed', async () => {
+ const cases = [
+ ['a page that holds exactly what the spec states', seededServer({ connectorBindings: [WEATHER], actionBindings: [APPROVE] }), { connectorBindings: [WEATHER], actionBindings: [APPROVE] }],
+ ['a page that holds more', pageHolding(), { connectorBindings: [WEATHER, SHAREPOINT], actionBindings: [APPROVE] }],
+ ];
+ for (const [label, server, stated] of cases) {
+ await withBackend(server, async (genpage) => {
+ const legacy = await asPublishedByAnOlderBuild(genpage);
+ assert.notStrictEqual(contentFingerprint({ source: SOURCE, name: 'Weather', dataSources: ['account'], model: 'gpt-4.1', ...stated }), legacy, `${label}: the lists are part of the hash`);
+ server.requests.length = 0;
+ server.published.length = 0;
+ const out = await genpage.update(ID, { ...SENT, ...stated, specBindings: true, publishedFingerprint: legacy });
+ assert.strictEqual(out.unchanged, true, label);
+ assert.strictEqual(out.publish.kind, 'skipped', label);
+ assert.strictEqual(out.receiptUpgraded, true, `${label}: the caller is told the record it holds can be renewed`);
+ assert.strictEqual(out.fingerprint, contentFingerprint({ source: SOURCE, name: 'Weather', dataSources: ['account'], model: 'gpt-4.1', ...stated }), 'the renewed record is the hash of what the spec states');
+ assert.deepStrictEqual(server.writes(), [], `${label}: no row written and no PublishXml`);
+ assert.deepStrictEqual(server.published, [], label);
+ assert.ok(publishedLayerReads(server).length > 0, `${label}: the published copy was read, to see that it holds the lists`);
+
+ // The renewed record is the one a later update finds: it matches the hash as it is, and reads nothing of the published copy.
+ server.requests.length = 0;
+ const later = await genpage.update(ID, { ...SENT, ...stated, specBindings: true, publishedFingerprint: out.fingerprint });
+ assert.deepStrictEqual([later.publish.kind, later.receiptUpgraded], ['skipped', undefined], label);
+ assert.deepStrictEqual(server.writes(), [], label);
+ assert.deepStrictEqual(publishedLayerReads(server), [], `${label}: the published copy is not read again`);
+ });
+ }
+});
+
+// A record can name ONE of the lists: a build whose spec stated a page's connector bindings and not its Custom API bindings (a list a download could not state, or one the author took out of the spec to keep the
+// page's own) published the page with the hash of its content and that one list. A spec that then states the other list too, which the page holds, is the same content again: stating a list for the first time is
+// not a change to the page, whichever list it is.
+test('REAL BUNDLE: a record of a publish made when the spec stated ONE of the lists still stands when a spec states the other for the first time — nothing is written, nothing is published', async () => {
+ const stated = { connectorBindings: [WEATHER], actionBindings: [APPROVE] };
+ for (const [earlierList, newList] of [['connectorBindings', 'actionBindings'], ['actionBindings', 'connectorBindings']]) {
+ const server = seededServer(stated);
+ await withBackend(server, async (genpage) => {
+ const earlier = await genpage.update(ID, { ...SENT, [earlierList]: stated[earlierList], specBindings: true });
+ assert.strictEqual(earlier.publish.kind, 'verified', 'the earlier build published the page, and its record names one list');
+ server.requests.length = 0;
+ server.published.length = 0;
+ const out = await genpage.update(ID, { ...SENT, ...stated, specBindings: true, publishedFingerprint: earlier.fingerprint });
+ assert.deepStrictEqual([out.unchanged, out.publish.kind, out.receiptUpgraded], [true, 'skipped', true], `${newList} stated for the first time`);
+ assert.strictEqual(out.fingerprint, contentFingerprint({ source: SOURCE, name: 'Weather', dataSources: ['account'], model: 'gpt-4.1', ...stated }), 'the renewed record names both lists');
+ assert.deepStrictEqual(server.writes(), [], `${newList}: no row written and no PublishXml`);
+ assert.deepStrictEqual(server.published, []);
+ assert.ok(publishedLayerReads(server).length > 0, 'the published copy was read, to see that it holds the list the record does not name');
+ });
+ }
+
+ // A record of OTHER content — the one list as it was before the spec changed it — is no record of this content, whatever the spec states now: the page is published, as it always was.
+ const server = seededServer(stated);
+ await withBackend(server, async (genpage) => {
+ const other = contentFingerprint({ source: SOURCE, name: 'Weather', dataSources: ['account'], model: 'gpt-4.1', connectorBindings: [{ ...WEATHER, operations: ['Forecast'] }] });
+ server.published.length = 0;
+ const out = await genpage.update(ID, { ...SENT, ...stated, specBindings: true, publishedFingerprint: other });
+ assert.deepStrictEqual([out.publish.kind, out.receiptUpgraded], ['verified', undefined]);
+ assert.deepStrictEqual(server.published, [ID]);
+ });
+});
+
+test('REAL BUNDLE: the record of an older publish is not taken for the lists when the published copy does not hold them — the page is published, as it always was', async () => {
+ const server = seededServer({ connectorBindings: undefined, actionBindings: undefined });
+ await withBackend(server, async (genpage) => {
+ const legacy = await asPublishedByAnOlderBuild(genpage);
+ // Another writer adds the lists to the draft of the page and does not publish: the published copy holds none, and the page's draft holds what the spec states.
+ const config = JSON.parse(rows(server, ID)['config.json']);
+ server.otherWorkspaceDraft(ID, 'config.json', JSON.stringify({ ...config, connectorBindings: [WEATHER], actionBindings: [APPROVE] }));
+ server.requests.length = 0;
+ server.published.length = 0;
+ const out = await genpage.update(ID, { ...SENT, connectorBindings: [WEATHER], actionBindings: [APPROVE], specBindings: true, publishedFingerprint: legacy });
+ assert.strictEqual(out.unchanged, true, 'the draft already holds the lists: nothing to write');
+ assert.strictEqual(out.publish.kind, 'verified', 'but they were never published, and the record of the older publish says nothing of them');
+ assert.strictEqual(out.receiptUpgraded, undefined);
+ assert.deepStrictEqual(server.published, [ID]);
+ assert.deepStrictEqual(server.writes(), ['POST /PublishXml'], 'the publish, and nothing else');
+ });
+});
+
+test('REAL BUNDLE: a record of an older publish is a reason not to publish only for a page that already holds the content — one the spec changes is written and published whatever was recorded', async () => {
+ const server = pageHolding();
+ await withBackend(server, async (genpage) => {
+ const legacy = await asPublishedByAnOlderBuild(genpage);
+ server.requests.length = 0;
+ server.published.length = 0;
+ const out = await genpage.update(ID, { ...SENT, connectorBindings: [{ ...WEATHER, operations: ['Forecast'] }], actionBindings: [APPROVE], specBindings: true, publishedFingerprint: legacy });
+ assert.strictEqual(out.unchanged, undefined);
+ assert.strictEqual(out.publish.kind, 'verified');
+ assert.deepStrictEqual(server.published, [ID]);
+ assert.deepStrictEqual(JSON.parse(rows(server, ID)['config.json']).connectorBindings.map((b) => b.operations), [['Forecast']]);
+ });
+});
+
+test('REAL BUNDLE: the record of an older publish is read as one that names the lists only for a caller that says its lists are a spec\'s — any other keeps what the record has always meant', async () => {
+ const server = seededServer({ connectorBindings: [WEATHER], actionBindings: [APPROVE] });
+ await withBackend(server, async (genpage) => {
+ const legacy = await asPublishedByAnOlderBuild(genpage);
+ server.requests.length = 0;
+ server.published.length = 0;
+ const out = await genpage.update(ID, { ...SENT, connectorBindings: [WEATHER], actionBindings: [APPROVE], publishedFingerprint: legacy });
+ assert.strictEqual(out.publish.kind, 'verified', 'the hash is another content\'s: the page is published');
+ assert.deepStrictEqual(server.published, [ID]);
+ });
+});
diff --git a/plugins/model-apps/scripts/tests/page-bindings.test.js b/plugins/model-apps/scripts/tests/page-bindings.test.js
new file mode 100644
index 000000000..7d8ad2391
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/page-bindings.test.js
@@ -0,0 +1,1225 @@
+'use strict';
+// A generative page's connector and Custom API bindings, in an App Spec and through a download and a rebuild.
+//
+// A page holds two lists beside its data sources and its model, in its config.json: `connectorBindings` (each entry names a connection reference by its
+// logical name) and `actionBindings` (each names a Custom API by its unique name). They used to be left out of a downloaded spec — the page folder kept
+// them, the spec did not — so a rebuild into the environment the page came from kept them only because it sent none, and a rebuild into another
+// environment deployed the page without them. The spec now states them (`pages[].connectorBindings`, `pages[].actionBindings`), a download writes what a page
+// holds, a rebuild writes what a spec states, and the download says what it cannot bring to another environment.
+//
+// What this holds:
+// - the shape the spec accepts, and the one rule the download shares with the validator (a list of objects);
+// - what the download projects from a page's config.json, what it leaves out and says so, and that it never refuses over it;
+// - the build: a list the spec states is sent (create, navigation target, update), one it leaves out is not (the page keeps its own), `[]` clears;
+// - the round trip in the same environment, and the copy that goes to another one;
+// - what the download tells the operator, on stderr and in its JSON result.
+const { test } = require('node:test');
+const assert = require('node:assert');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { validateAppSpec, pageBindingsProblem, statedPageBindings, migrateAppSpec, PAGE_BINDINGS } = require('../lib/app-spec.js');
+const { statableBindings } = require('../lib/page-bindings.js');
+const { hydrateSpec } = require('../lib/hydrate-spec.js');
+const { runDownload, parseDownloadedPages, pageBindingsReport, pageBindingsNote, main } = require('../download-model-app.js');
+const { runSdkBuild, BuildHalt } = require('../lib/sdk-build.js');
+const { classifyPages } = require('../lib/classify-changes.js');
+const { buildManifest } = require('../lib/page-manifest.js');
+const { makeSimpleMockSdk } = require('./helpers/mock-sdk.js');
+const { currentReadSdk } = require('./helpers/app-membership-sdk.js');
+const { fakeGenpage } = require('./helpers/fake-genpage.js');
+const { createAzHttpClient } = require('../lib/sdk-http-client.js');
+const { makeThrottleBudget } = require('../lib/throttle-budget.js');
+
+const ENV = 'https://contoso.crm.dynamics.com';
+const APP_ID = 'aaaaaaaa-0000-4000-8000-000000000001';
+const APP_UNIQUE = 'contoso_bindings';
+const APP_UNIQUE_ID = 'aaaaaaaa-0000-4000-8000-000000000002';
+const SITEMAP_ID = 'aaaaaaaa-0000-4000-8000-000000000003';
+const SOLUTION_ID = 'aaaaaaaa-0000-4000-8000-000000000004';
+const WEATHER_ID = 'bbbbbbbb-0000-4000-8000-000000000001';
+const DETAIL_ID = 'bbbbbbbb-0000-4000-8000-000000000002';
+
+// Bindings as /genpage writes them (references/connectors.md and references/custom-api.md): only the properties an App Spec states. What a page may hold beyond them (a connection id,
+// a credential, a property the plugin does not know) never reaches a spec, and the tests of that put it on the page side of a fixture (`WEATHER_WITH_EXTRAS`).
+const WEATHER = { logicalName: 'contoso_msnweather', connectorId: '/providers/Microsoft.PowerApps/apis/shared_msnweather', dataset: '', operations: ['CurrentWeather'] };
+const SHAREPOINT = { logicalName: 'contoso_sharepoint', connectorId: '/providers/Microsoft.PowerApps/apis/shared_sharepointonline', dataset: 'https://contoso.sharepoint.com/sites/x', tables: ['11111111-2222-3333-4444-555555555555'], tableDisplayNames: ['Pets'] };
+const APPROVE = { name: 'contoso_ApproveOrder', isFunction: false, boundEntityLogicalName: 'contoso_item', displayName: 'Approve order', parameterKinds: { Comment: 'String' } };
+const SUMMARY = { name: 'contoso_GetSummary', isFunction: true, displayName: 'Get summary', parameterKinds: { ItemId: 'Guid' } };
+const clone = (value) => JSON.parse(JSON.stringify(value));
+
+const tempDirs = [];
+test.after(() => { for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true }); });
+function tmp(prefix) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
+ tempDirs.push(dir);
+ return dir;
+}
+
+// What a download runs while it writes to stderr, kept: runDownload prints its notes as it goes.
+async function withStderr(fn) {
+ const lines = [];
+ const write = process.stderr.write;
+ process.stderr.write = (chunk) => { lines.push(String(chunk)); return true; };
+ try {
+ return { value: await fn(), stderr: lines.join('') };
+ } finally {
+ process.stderr.write = write;
+ }
+}
+
+// ── the spec states them ────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+// A valid two-page spec; `extra` is added to the first page.
+function specWithPages(extra = {}) {
+ return {
+ schemaVersion: 2,
+ solution: { uniqueName: 'ContosoBindings', publisherPrefix: 'contoso' },
+ app: { name: 'Bindings App' },
+ entities: [{ schemaName: 'contoso_item', displayName: 'Item', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] }],
+ pages: [
+ { key: 'weather', name: 'Weather', source: { kind: 'tsx', codeFile: 'weather.tsx' }, ...extra },
+ { key: 'detail', name: 'Detail', source: { kind: 'tsx', codeFile: 'detail.tsx' } },
+ ],
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Pages', subAreas: [{ page: 'weather', title: 'Weather' }, { page: 'detail', title: 'Detail' }, { entity: 'contoso_item', title: 'Items' }] }] }] },
+ };
+}
+
+test('a spec page may state connectorBindings and actionBindings: each entry by the properties an App Spec states', () => {
+ const result = validateAppSpec(specWithPages({ connectorBindings: [WEATHER, SHAREPOINT], actionBindings: [APPROVE, SUMMARY] }));
+ assert.ok(result.ok, JSON.stringify(result.errors));
+ assert.deepStrictEqual(result.warnings, []);
+ // An empty list is a statement too (a rebuild clears the page's list with it), so it is valid.
+ assert.ok(validateAppSpec(specWithPages({ connectorBindings: [], actionBindings: [] })).ok);
+ // And a page that states none is what every spec was: valid, and nothing to say.
+ const plain = validateAppSpec(specWithPages());
+ assert.ok(plain.ok, JSON.stringify(plain.errors));
+ assert.deepStrictEqual(plain.warnings, []);
+});
+
+test('declared Custom API kinds: authored specs refuse unsupported declarations with structural lookup advice', async (t) => {
+ for (const kind of ['EntityReference', 'Entity', 'EntityCollection']) {
+ await t.test(`declared Custom API kinds: authored ${kind}`, () => {
+ const result = validateAppSpec(specWithPages({ actionBindings: [{ ...APPROVE, parameterKinds: { Ref: kind } }] }));
+ assert.strictEqual(result.ok, false);
+ const reason = result.errors.find((text) => /actionBindings\[0\]\.parameterKinds/.test(text));
+ assert.match(reason, /primitive.*Boolean.*Guid/);
+ assert.match(reason, /lookup.*structural.*discovery/i);
+ assert.ok(!reason.includes(kind), 'the supplied kind value is never echoed');
+ });
+ }
+});
+
+test('declared Custom API kinds: invalid maps give actionable advice without echoing their values', () => {
+ const marker = 'SYNTHETIC_NOT_A_PARAMETER_KIND';
+ const result = validateAppSpec(specWithPages({ actionBindings: [{ ...APPROVE, parameterKinds: { Value: marker } }] }));
+ assert.strictEqual(result.ok, false);
+ const reason = result.errors.find((text) => /actionBindings\[0\]\.parameterKinds/.test(text));
+ assert.match(reason, /primitive.*Boolean.*Guid/);
+ assert.match(reason, /lookup.*structural.*discovery/i);
+ assert.ok(!reason.includes(marker));
+});
+
+test('declared Custom API kinds: authored primitive sparse and lookup-only maps remain valid', () => {
+ const kinds = ['Boolean', 'DateTime', 'Decimal', 'Float', 'Integer', 'Money', 'Picklist', 'String', 'StringArray', 'Guid'];
+ const entries = [
+ ...kinds.map((kind) => ({ ...APPROVE, parameterKinds: { Value: kind } })),
+ { name: 'contoso_ResolveReference', parameterKinds: { Note: 'String' } },
+ { name: 'contoso_ResolveReference', parameterKinds: {} },
+ { name: 'contoso_ResolveReference' },
+ ];
+ for (const entry of entries) {
+ const result = validateAppSpec(specWithPages({ actionBindings: [entry] }));
+ assert.ok(result.ok, JSON.stringify(result.errors));
+ }
+ const withAuthoringHints = validateAppSpec(specWithPages({ actionBindings: [{
+ name: 'contoso_ResolveReference', parameterKinds: {}, lookupParameters: { Ref: { isOptional: false } },
+ }] }));
+ assert.strictEqual(withAuthoringHints.ok, false, 'discovery-only hints never become an App Spec binding field');
+});
+
+test('a list that is not a list, or an entry that is not an object, is an error naming the page and the place', () => {
+ for (const [kind, value, expected] of [
+ ['connectorBindings', 'contoso_msnweather', /pages\[0\]\.connectorBindings must be an array/],
+ ['connectorBindings', { logicalName: 'contoso_msnweather' }, /pages\[0\]\.connectorBindings must be an array/],
+ ['actionBindings', 'contoso_ApproveOrder', /pages\[0\]\.actionBindings must be an array/],
+ ['connectorBindings', [WEATHER, null], /pages\[0\]\.connectorBindings\[1\] must be an object/],
+ ['actionBindings', [APPROVE, undefined], /pages\[0\]\.actionBindings\[1\] must be an object/],
+ ]) {
+ const result = validateAppSpec(specWithPages({ [kind]: value }));
+ assert.strictEqual(result.ok, false, `${kind}: ${JSON.stringify(value)}`);
+ assert.ok(result.errors.some((e) => expected.test(e)), `${kind}: ${JSON.stringify(result.errors)}`);
+ }
+ // A string, a number, a list inside the list: none is an object either, and the validator says so as the download does.
+ for (const entry of ['contoso_msnweather', 7, ['contoso_msnweather']]) {
+ assert.strictEqual(pageBindingsProblem('connectorBindings', [entry]), 'connectorBindings[0] is not an object', JSON.stringify(entry));
+ const result = validateAppSpec(specWithPages({ connectorBindings: [entry] }));
+ assert.strictEqual(result.ok, false, JSON.stringify(entry));
+ assert.ok(result.errors.includes("page 'weather': connectorBindings[0] is not an object"), JSON.stringify(result.errors));
+ }
+ // A hole is reported once, by the shape check that repairs it, and not again as an entry that is no object.
+ const hole = validateAppSpec(specWithPages({ actionBindings: [APPROVE, null] }));
+ assert.deepStrictEqual(hole.errors.filter((e) => /actionBindings/.test(e)), ['pages[0].actionBindings[1] must be an object']);
+});
+
+test('an entry with no logicalName (a connector binding) or name (a Custom API binding) is a warning, never an error — it is written as it is; one that is not an identifier is an error, by name', () => {
+ const result = validateAppSpec(specWithPages({ connectorBindings: [{ connectorId: '/providers/Microsoft.PowerApps/apis/shared_msnweather' }, { dataset: '' }], actionBindings: [{ displayName: 'x' }, APPROVE] }));
+ assert.ok(result.ok, JSON.stringify(result.errors));
+ assert.strictEqual(result.warnings.length, 3, JSON.stringify(result.warnings));
+ assert.match(result.warnings[0], /page 'weather': connectorBindings\[0\] has no logicalName/);
+ assert.match(result.warnings[1], /page 'weather': connectorBindings\[1\] has no logicalName/);
+ assert.match(result.warnings[2], /page 'weather': actionBindings\[0\] has no name/);
+ assert.ok(result.warnings.every((w) => /finds a binding by it/.test(w)), 'the warning says why a binding needs it');
+ const blank = validateAppSpec(specWithPages({ connectorBindings: [{ logicalName: ' ' }] }));
+ assert.ok(blank.errors.includes("page 'weather': connectorBindings[0].logicalName must be an identifier (a letter, then letters, digits, _ . -)"), JSON.stringify(blank.errors));
+});
+
+test('what a download carries of a list always validates, and the validator refuses what the download would leave out of it — the rules they share are pageBindingsProblem and statableBindings', () => {
+ const values = [[], [WEATHER], [{}], [{ anything: 1 }], [{ ...WEATHER, connectionId: 'x' }], [WEATHER, { ...SHAREPOINT, dataset: 'https://[email protected]' }], [{ ...APPROVE, displayName: 'https://contoso.example' }], 'x', 5, {}, [null], [WEATHER, 3], [[WEATHER]], [true]];
+ for (const kind of Object.keys(PAGE_BINDINGS)) {
+ const errorsOf = (list) => validateAppSpec(specWithPages({ [kind]: list })).errors.filter((e) => e.includes(kind));
+ for (const value of values) {
+ const container = pageBindingsProblem(kind, value);
+ if (container) {
+ assert.ok(errorsOf(value).length > 0, `${kind}: the validator refuses ${JSON.stringify(value)}: ${container}`);
+ continue;
+ }
+ const { stated, problem } = statableBindings(kind, value);
+ if (stated) assert.deepStrictEqual(errorsOf(stated), [], `${kind}: what a download carries of ${JSON.stringify(value)} validates`);
+ assert.strictEqual(errorsOf(value).length > 0, problem !== null, `${kind}: ${JSON.stringify(value)} is refused exactly when a download would leave it out`);
+ }
+ }
+});
+
+test('statedPageBindings answers the lists a page states — `[]` too — and nothing for a list it leaves out', () => {
+ assert.deepStrictEqual(statedPageBindings({ key: 'a' }), {});
+ assert.deepStrictEqual(statedPageBindings({ connectorBindings: [WEATHER] }), { connectorBindings: [WEATHER] });
+ assert.deepStrictEqual(statedPageBindings({ connectorBindings: [], actionBindings: [APPROVE] }), { connectorBindings: [], actionBindings: [APPROVE] });
+ assert.deepStrictEqual(statedPageBindings({ connectorBindings: 'x', actionBindings: null }), {}, 'what is no list is not stated');
+ assert.deepStrictEqual(statedPageBindings(undefined), {});
+});
+
+test('a spec from before schemaVersion 2 keeps the lists its pages state when it is migrated', () => {
+ const migrated = migrateAppSpec({
+ solution: { uniqueName: 'ContosoBindings', publisherPrefix: 'contoso' },
+ app: { name: 'Bindings App' },
+ pages: [{ name: 'Weather', codeFile: 'weather.tsx', connectorBindings: [WEATHER], actionBindings: [] }],
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Pages', subAreas: [{ page: 'Weather', title: 'Weather' }] }] }] },
+ });
+ assert.strictEqual(migrated.schemaVersion, 2);
+ assert.deepStrictEqual(statedPageBindings(migrated.pages[0]), { connectorBindings: [WEATHER], actionBindings: [] });
+});
+
+// ── what a download projects from a page's config.json ────────────────────────────────────────────────────────────────────────
+
+// A page tree as a download writes it: <root>/<pageId>/{page.tsx, config.json}.
+function pageTree(configs) {
+ const root = tmp('page-bindings-tree-');
+ for (const [id, config] of Object.entries(configs)) {
+ const dir = path.join(root, id);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(path.join(dir, 'page.tsx'), 'export default () => null;', 'utf8');
+ if (config !== undefined) fs.writeFileSync(path.join(dir, 'config.json'), typeof config === 'string' || Buffer.isBuffer(config) ? config : JSON.stringify(config));
+ }
+ return root;
+}
+const A = '11111111-1111-4111-8111-111111111111';
+const B = '22222222-2222-4222-8222-222222222222';
+const C = '33333333-3333-4333-8333-333333333333';
+const D = '44444444-4444-4444-8444-444444444444';
+
+test('declared Custom API kinds: download omits unsupported lists whole and keeps diagnostics value-safe', async (t) => {
+ for (const kind of ['EntityReference', 'Entity', 'EntityCollection']) {
+ await t.test(`declared Custom API kinds: downloaded ${kind}`, () => {
+ const held = [APPROVE, { name: 'contoso_ResolveReference', parameterKinds: { Ref: kind, Note: 'String' } }];
+ const root = pageTree({ [A]: { connectorBindings: [WEATHER], actionBindings: held } });
+ const unkept = [];
+ const [page] = parseDownloadedPages(root, root, null, [], [], unkept);
+ assert.ok(!Object.hasOwn(page, 'actionBindings'), 'one unsupported declaration omits every action binding, not only its parameter');
+ assert.deepStrictEqual(page.connectorBindings, [WEATHER]);
+ assert.strictEqual(unkept.length, 1);
+ assert.deepStrictEqual([unkept[0].pageId, unkept[0].field], [A, 'actionBindings']);
+ assert.match(unkept[0].reason, /^actionBindings\[1\]\.parameterKinds /);
+ const report = pageBindingsReport([{ ...page, key: 'weather', name: 'Weather' }], unkept);
+ const text = JSON.stringify(report) + pageBindingsNote(report);
+ assert.ok(!text.includes(kind) && !text.includes('contoso_ResolveReference'), 'omission diagnostics carry no binding values');
+ assert.deepStrictEqual(JSON.parse(fs.readFileSync(path.join(root, A, 'config.json'), 'utf8')).actionBindings, held);
+ });
+ }
+});
+
+test('parseDownloadedPages carries a page\'s binding lists as its config.json holds them — entries, their order and every property a spec states unchanged', () => {
+ const root = pageTree({
+ [A]: { dataSources: ['contoso_item'], model: 'gpt-4.1', connectorBindings: [SHAREPOINT, WEATHER], actionBindings: [SUMMARY, APPROVE] },
+ [B]: { dataSources: ['contoso_item'] },
+ });
+ const unkept = [];
+ const pages = parseDownloadedPages(root, root, null, [], [], unkept);
+ const byId = new Map(pages.map((p) => [p.pageId, p]));
+ assert.deepStrictEqual(byId.get(A).connectorBindings, [SHAREPOINT, WEATHER], 'order and every property kept');
+ assert.deepStrictEqual(byId.get(A).actionBindings, [SUMMARY, APPROVE]);
+ assert.deepStrictEqual(byId.get(A).dataSources, ['contoso_item'], 'what a page already carried is carried as before');
+ assert.strictEqual(byId.get(A).model, 'gpt-4.1');
+ assert.ok(!('connectorBindings' in byId.get(B)) && !('actionBindings' in byId.get(B)), 'a page with none states none');
+ assert.deepStrictEqual(unkept, []);
+});
+
+test('an empty list, null, or no key at all puts nothing in the page — a spec never states [] for a page that holds none, because a rebuild would read it as "clear them"', () => {
+ const root = pageTree({
+ [A]: { connectorBindings: [], actionBindings: [] },
+ [B]: { connectorBindings: null, actionBindings: null },
+ [C]: { dataSources: [] },
+ [D]: undefined,
+ });
+ const unkept = [];
+ const pages = parseDownloadedPages(root, root, null, [], [], unkept);
+ assert.strictEqual(pages.length, 4);
+ for (const page of pages) assert.ok(!('connectorBindings' in page) && !('actionBindings' in page), page.pageId);
+ assert.deepStrictEqual(unkept, [], 'nothing is reported for any of these: a page holds no bindings in each of them');
+});
+
+test('a list the spec cannot state is left out WHOLE and recorded — the page\'s other list is still carried, and the download does not refuse', () => {
+ const root = pageTree({
+ [A]: { connectorBindings: 'contoso_msnweather', actionBindings: [APPROVE] },
+ [B]: { connectorBindings: [WEATHER, 'oops'], actionBindings: { name: 'contoso_ApproveOrder' } },
+ [C]: { connectorBindings: [WEATHER, [SHAREPOINT]] },
+ });
+ const unkept = [];
+ const unreadable = [];
+ const pages = parseDownloadedPages(root, root, null, unreadable, [], unkept);
+ const byId = new Map(pages.map((p) => [p.pageId, p]));
+ assert.deepStrictEqual(byId.get(A).actionBindings, [APPROVE], 'the page\'s good list is carried');
+ assert.ok(!('connectorBindings' in byId.get(A)));
+ // Whole: a spec that stated part of a list would have a rebuild REPLACE the page's list with that part.
+ assert.ok(!('connectorBindings' in byId.get(B)) && !('actionBindings' in byId.get(B)));
+ assert.ok(!('connectorBindings' in byId.get(C)));
+ assert.deepStrictEqual(unkept.map((u) => [u.pageId, u.field, u.reason]), [
+ [A, 'connectorBindings', 'connectorBindings is present but is not an array'],
+ [B, 'connectorBindings', 'connectorBindings[1] is not an object'],
+ [B, 'actionBindings', 'actionBindings is present but is not an array'],
+ [C, 'connectorBindings', 'connectorBindings[1] is not an object'],
+ ]);
+ assert.deepStrictEqual(unreadable, [], 'a list that cannot be stated is not an unreadable config: the page\'s data sources are known');
+});
+
+test('a BOM-prefixed config.json keeps its binding lists, as it keeps its data sources', () => {
+ const root = pageTree({ [A]: Buffer.from(`\uFEFF${JSON.stringify({ dataSources: ['contoso_item'], connectorBindings: [WEATHER] })}`, 'utf8') });
+ const [page] = parseDownloadedPages(root, root, null, [], [], []);
+ assert.deepStrictEqual(page.connectorBindings, [WEATHER]);
+});
+
+test('a download without the collector of unstated lists still projects (the argument is optional, as the other two are)', () => {
+ const root = pageTree({ [A]: { connectorBindings: 'x', actionBindings: [APPROVE] } });
+ const [page] = parseDownloadedPages(root, root, null);
+ assert.deepStrictEqual(page.actionBindings, [APPROVE]);
+});
+
+// ── what the spec says of a page it was downloaded from ───────────────────────────────────────────────────────────────────────
+
+// hydrateSpec with the least it needs: one entity, an app that navigates to the pages.
+async function hydrated(pages) {
+ return hydrateSpec({
+ app: async () => ({ name: 'Bindings App', uniquename: APP_UNIQUE, description: '', siteMap: { areas: [{ title: 'Main', groups: [{ title: 'Pages', subAreas: pages.map((p) => ({ type: 'GenPage', genPageId: p.pageId, title: p.name })) }] }] } }),
+ pages: async () => pages,
+ entities: async () => [],
+ webResources: async () => [],
+ solution: async () => ({ uniqueName: 'ContosoBindings', publisherPrefix: 'contoso' }),
+ dashboards: async () => [],
+ });
+}
+
+test('hydrateSpec writes the binding lists a page holds, in the keyed and the legacy page shape, and leaves out an empty one', async () => {
+ const base = { codeFile: 'pages/p/page.tsx', prompt: undefined };
+ const keyed = await hydrated([
+ { ...base, pageId: A, key: 'weather', name: 'Weather', dataSources: [], connectorBindings: [WEATHER], actionBindings: [APPROVE] },
+ { ...base, pageId: B, key: 'detail', name: 'Detail', dataSources: [], connectorBindings: [], actionBindings: [] },
+ ]);
+ const [weather, detail] = keyed.pages;
+ assert.deepStrictEqual([weather.connectorBindings, weather.actionBindings], [[WEATHER], [APPROVE]]);
+ assert.ok(!('connectorBindings' in detail) && !('actionBindings' in detail));
+ // The order a spec lists a page's fields in is fixed, so two downloads of one app match byte for byte.
+ assert.deepStrictEqual(Object.keys(weather), ['key', 'name', 'pageId', 'connectorBindings', 'actionBindings', 'source']);
+
+ const legacy = await hydrated([{ ...base, pageId: A, name: 'Weather', dataSources: [], connectorBindings: [WEATHER] }]);
+ assert.strictEqual(legacy.schemaVersion, undefined, 'a page with no key makes the legacy shape');
+ assert.deepStrictEqual(legacy.pages[0].connectorBindings, [WEATHER]);
+});
+
+// ── what the download tells the operator ──────────────────────────────────────────────────────────────────────────────────────
+
+test('pageBindingsReport names, once and in order, what the target environment must have, and is null for pages that hold nothing', () => {
+ const pages = [
+ { pageId: A, key: 'weather', name: 'Weather', connectorBindings: [WEATHER, SHAREPOINT], actionBindings: [APPROVE, SUMMARY, APPROVE] },
+ { pageId: B, key: 'detail', name: 'Detail', connectorBindings: [{ ...WEATHER }] },
+ { pageId: C, key: 'plain', name: 'Plain' },
+ ];
+ const report = pageBindingsReport(pages, []);
+ assert.deepStrictEqual(report.pages, [
+ { key: 'weather', name: 'Weather', connectorBindings: ['contoso_msnweather', 'contoso_sharepoint'], actionBindings: ['contoso_ApproveOrder', 'contoso_GetSummary'] },
+ { key: 'detail', name: 'Detail', connectorBindings: ['contoso_msnweather'] },
+ ]);
+ assert.deepStrictEqual(report.neededInTarget, {
+ connectionReferences: ['contoso_msnweather', 'contoso_sharepoint'],
+ customApis: ['contoso_ApproveOrder', 'contoso_GetSummary'],
+ // Only the binding that points at a dataset or tables of the service: a weather call names no resource of its own.
+ serviceResources: ['contoso_sharepoint'],
+ });
+ assert.ok(!('notCarried' in report));
+ assert.match(report.note, /cannot create what they name/);
+ assert.strictEqual(pageBindingsReport([{ pageId: C, key: 'plain', name: 'Plain' }], []), null);
+ assert.strictEqual(pageBindingsReport([], []), null);
+ assert.strictEqual(pageBindingsReport(undefined, undefined), null);
+});
+
+test('pageBindingsReport lists an entry that has no name as such — a page that holds a binding never reads as one that holds none', () => {
+ const report = pageBindingsReport([{ pageId: A, key: 'a', name: 'A', connectorBindings: [{ connectorId: 'x' }], actionBindings: [{ displayName: 'y' }, APPROVE] }], []);
+ assert.deepStrictEqual(report.pages[0].connectorBindings, ['(no logicalName)']);
+ assert.deepStrictEqual(report.pages[0].actionBindings, ['(no name)', 'contoso_ApproveOrder']);
+ assert.deepStrictEqual(report.neededInTarget, { customApis: ['contoso_ApproveOrder'] }, 'an entry with no name names nothing the target could be missing');
+});
+
+test('pageBindingsReport reports a list the spec could not state, by the page\'s name and key', () => {
+ const pages = [{ pageId: A, key: 'weather', name: 'Weather' }, { pageId: B, key: 'detail', name: 'Detail', actionBindings: [APPROVE] }];
+ const report = pageBindingsReport(pages, [{ pageId: A.toUpperCase(), field: 'connectorBindings', reason: 'connectorBindings is present but is not an array' }]);
+ assert.deepStrictEqual(report.notCarried, [{ key: 'weather', name: 'Weather', field: 'connectorBindings', reason: 'connectorBindings is present but is not an array' }]);
+ assert.deepStrictEqual(report.pages.map((p) => p.key), ['detail']);
+ // Only a list left out, and no page that holds one: there is still something to say.
+ const onlyLost = pageBindingsReport([{ pageId: A, key: 'weather', name: 'Weather' }], [{ pageId: A, field: 'actionBindings', reason: 'actionBindings[0] is not an object' }]);
+ assert.deepStrictEqual(onlyLost.pages, []);
+ assert.deepStrictEqual(onlyLost.neededInTarget, {});
+});
+
+test('pageBindingsNote says what a rebuild into another environment cannot bring, names the scripts that make each piece, and is silent when there is nothing to say', () => {
+ const report = pageBindingsReport([{ pageId: A, key: 'weather', name: 'Weather', connectorBindings: [WEATHER, SHAREPOINT], actionBindings: [APPROVE] }], []);
+ const text = pageBindingsNote(report);
+ assert.match(text, /^NOTE: 1 page\(s\) hold connector or Custom API bindings, and the spec states them \(pages\[\]\.connectorBindings, pages\[\]\.actionBindings\)/);
+ assert.match(text, /Rebuilding into THIS environment keeps them working\. Rebuilding into a DIFFERENT environment writes them, but cannot bring what they name/);
+ assert.match(text, /connection reference\(s\) contoso_msnweather, contoso_sharepoint, and the connection each one goes through/);
+ assert.match(text, /create-connection-reference\.js/);
+ assert.match(text, /add-page-to-solution\.js --connection-refs, then solution-settings\.js/);
+ assert.match(text, /Custom API\(s\) contoso_ApproveOrder: a Custom API is a solution component, not an App Spec item/);
+ assert.match(text, /list-custom-apis\.js/);
+ assert.match(text, /what the connector bindings of contoso_sharepoint point at inside the service/);
+ assert.match(text, /Weather \[weather\] — connectorBindings: contoso_msnweather, contoso_sharepoint; actionBindings: contoso_ApproveOrder/);
+ assert.ok(!/WARNING/.test(text), 'nothing was left out');
+ assert.strictEqual(pageBindingsNote(null), '');
+
+ // A page with a connector binding and no Custom API says nothing of Custom APIs, and the other way round.
+ const connectorOnly = pageBindingsNote(pageBindingsReport([{ pageId: A, key: 'w', name: 'W', connectorBindings: [WEATHER] }], []));
+ assert.ok(/connection reference\(s\)/.test(connectorOnly) && !/Custom API\(s\)/.test(connectorOnly) && !/inside the service/.test(connectorOnly), connectorOnly);
+ const apiOnly = pageBindingsNote(pageBindingsReport([{ pageId: A, key: 'w', name: 'W', actionBindings: [APPROVE] }], []));
+ assert.ok(/Custom API\(s\)/.test(apiOnly) && !/connection reference\(s\)/.test(apiOnly), apiOnly);
+
+ const lost = pageBindingsNote(pageBindingsReport([{ pageId: A, key: 'weather', name: 'Weather' }], [{ pageId: A, field: 'connectorBindings', reason: 'connectorBindings is present but is not an array' }]));
+ assert.match(lost, /^WARNING: 1 list\(s\) of connector or Custom API bindings are NOT in the spec/);
+ assert.match(lost, /"Weather" \(connectorBindings is present but is not an array\)/);
+ assert.match(lost, /Rebuilding into THIS environment leaves such a page's bindings as they are\. Rebuilding into a DIFFERENT environment will not carry them — bind them there with \/genpage/);
+ assert.ok(!/^NOTE/.test(lost), 'no page holds a binding the spec states, so there is no note about them');
+});
+
+// ── a download, end to end over the stand-in SDK ──────────────────────────────────────────────────────────────────────────────
+
+// What one app of two pages looks like to a download: the navigation names both, and the stand-in SDK answers the reads runDownload makes.
+function downloadFixture(pages) {
+ const sitemapXml = `<SiteMap><Area><Group>${pages.map((p) => `<SubArea GenPageId="${p.pageId}" Title="${p.title}"/>`).join('')}<SubArea Entity="contoso_item"/></Group></Area></SiteMap>`;
+ const app = {
+ name: 'Bindings App', uniquename: APP_UNIQUE, description: '',
+ siteMap: { areas: [{ title: 'Main', groups: [{ title: 'Pages', subAreas: [
+ ...pages.map((p) => ({ type: 'GenPage', genPageId: p.pageId, title: p.title })),
+ { type: 'Entity', entity: 'contoso_item' },
+ ] }] }] },
+ };
+ const { sdk } = makeSimpleMockSdk();
+ const fetchArtifact = sdk.fetchArtifact;
+ sdk.fetchArtifact = async (kind, id) => {
+ const artifact = await fetchArtifact(kind, id);
+ return kind === 'app' ? Object.assign(artifact, clone(app)) : artifact;
+ };
+ sdk.findArtifact = async (kind) => (kind === 'app' ? APP_ID : null);
+ sdk.listArtifacts = async (kind) => (kind === 'app' ? [{ id: APP_ID, isDirty: false }] : []);
+ sdk.findTables = async () => [{ logicalName: 'contoso_item', entitySetName: 'contoso_items' }];
+ sdk.fetchEntityMetadata = async (logical) => ({ logicalName: logical, schemaName: logical, displayName: 'Item', primaryNameAttribute: 'contoso_name', entitySetName: 'contoso_items', attributes: [], relationships: [] });
+ sdk.dataverse = { get: async () => ({ status: 200, body: { value: [] } }) };
+ const manifest = buildManifest({ pages: pages.map((p) => ({ key: p.key, name: p.name })) }, new Map(pages.map((p) => [p.key, p.pageId])));
+ let manifestContent = Buffer.from(JSON.stringify(manifest), 'utf8').toString('base64');
+ sdk.queryRecords = async (logical, opts = {}) => {
+ if (logical === 'appmodule') return [{ appmoduleid: APP_ID, appmoduleidunique: APP_UNIQUE_ID, uniquename: APP_UNIQUE }];
+ if (logical === 'appmodulecomponent') return /componenttype eq 62/.test(opts.filter || '') ? [{ objectid: SITEMAP_ID, componenttype: 62 }] : [];
+ if (logical === 'sitemap') return [{ sitemapid: SITEMAP_ID, sitemapxml: sitemapXml }];
+ if (logical === 'webresource') return /_pagemanifest'/.test(opts.filter || '') ? [{ webresourceid: 'manifest', content: manifestContent }] : [];
+ if (logical === 'solutioncomponent') return [{ _solutionid_value: SOLUTION_ID }];
+ if (logical === 'solution') return [{ solutionid: SOLUTION_ID, uniquename: 'ContosoBindings', ismanaged: false }];
+ return [];
+ };
+ sdk.updateWebResource = async (id, value) => { manifestContent = Buffer.from(value.content, 'utf8').toString('base64'); };
+ return { sdk, readSdk: () => currentReadSdk(sdk, { appId: APP_ID, layerId: APP_UNIQUE_ID, sitemapXml }) };
+}
+
+const WEATHER_SOURCE = 'export default function Weather() { return null; }\r\n';
+const DETAIL_SOURCE = 'export default function Detail() { return null; }\r\n';
+const environmentPages = () => [
+ { pageId: WEATHER_ID, key: 'weather', title: 'Weather navigation', name: 'Weather', source: WEATHER_SOURCE, dataSources: ['contoso_item'], model: 'gpt-4.1', connectorBindings: [WEATHER, SHAREPOINT], actionBindings: [APPROVE, SUMMARY] },
+ { pageId: DETAIL_ID, key: 'detail', title: 'Detail navigation', name: 'Item Detail', source: DETAIL_SOURCE, dataSources: ['contoso_item'] },
+];
+const livePages = (pages) => pages.map(({ pageId, name, source, dataSources, model, connectorBindings, actionBindings }) => ({ pageId, name, source, dataSources, model, connectorBindings, actionBindings }));
+
+test('a download states the bindings a page holds in the spec, the spec validates, and the page folder and the spec say the same', async () => {
+ const outDir = tmp('page-bindings-download-');
+ const pages = environmentPages();
+ const { readSdk } = downloadFixture(pages);
+ const genpage = fakeGenpage({ pages: livePages(pages) });
+ const { value: result, stderr } = await withStderr(() => runDownload({ sdk: readSdk(), genpage, outDir, appId: APP_ID, appUnique: APP_UNIQUE }));
+ assert.ok(result.ok, JSON.stringify(result));
+ const spec = JSON.parse(JSON.stringify(result.spec));
+ const validation = validateAppSpec(spec);
+ assert.ok(validation.ok, validation.errors.join('; '));
+ const weather = spec.pages.find((p) => p.key === 'weather');
+ const detail = spec.pages.find((p) => p.key === 'detail');
+ assert.deepStrictEqual(weather.connectorBindings, [WEATHER, SHAREPOINT]);
+ assert.deepStrictEqual(weather.actionBindings, [APPROVE, SUMMARY]);
+ assert.ok(!('connectorBindings' in detail) && !('actionBindings' in detail), 'a page with none states none');
+ // The page folder still holds the raw config, which is what the spec projects.
+ const config = JSON.parse(fs.readFileSync(path.join(outDir, 'pages', WEATHER_ID, 'config.json'), 'utf8'));
+ assert.deepStrictEqual([config.connectorBindings, config.actionBindings], [weather.connectorBindings, weather.actionBindings]);
+
+ // What it says: in the result, and on stderr.
+ assert.deepStrictEqual(result.pageBindings.pages, [{ key: 'weather', name: 'Weather', connectorBindings: ['contoso_msnweather', 'contoso_sharepoint'], actionBindings: ['contoso_ApproveOrder', 'contoso_GetSummary'] }]);
+ assert.deepStrictEqual(result.pageBindings.neededInTarget, { connectionReferences: ['contoso_msnweather', 'contoso_sharepoint'], customApis: ['contoso_ApproveOrder', 'contoso_GetSummary'], serviceResources: ['contoso_sharepoint'] });
+ assert.match(stderr, /NOTE: 1 page\(s\) hold connector or Custom API bindings, and the spec states them/);
+ assert.match(stderr, /Rebuilding into a DIFFERENT environment writes them, but cannot bring what they name/);
+ assert.ok(!/WARNING: \d+ list\(s\) of connector/.test(stderr), 'nothing was left out');
+});
+
+test('an app whose pages hold no bindings downloads exactly as it did: no field in the spec, no note, nothing in the result', async () => {
+ const outDir = tmp('page-bindings-none-');
+ const pages = environmentPages().map(({ connectorBindings, actionBindings, ...rest }) => rest);
+ const { readSdk } = downloadFixture(pages);
+ const { value: result, stderr } = await withStderr(() => runDownload({ sdk: readSdk(), genpage: fakeGenpage({ pages: livePages(pages) }), outDir, appId: APP_ID, appUnique: APP_UNIQUE }));
+ assert.ok(result.ok, JSON.stringify(result));
+ assert.ok(result.spec.pages.every((p) => !('connectorBindings' in p) && !('actionBindings' in p)));
+ assert.strictEqual('pageBindings' in result, false);
+ assert.ok(!/bindings/i.test(stderr), `no word about bindings: ${stderr}`);
+});
+
+test('a page whose list the spec cannot state is downloaded without it, and the download says so — it is a note, not a refusal, with or without --allow-lossy-download', async () => {
+ for (const allowLossy of [false, true]) {
+ const pages = environmentPages();
+ pages[0].connectorBindings = { logicalName: 'contoso_msnweather' };
+ const outDir = tmp('page-bindings-lost-');
+ const { readSdk } = downloadFixture(pages);
+ const { value: result, stderr } = await withStderr(() => runDownload({ sdk: readSdk(), genpage: fakeGenpage({ pages: livePages(pages) }), outDir, appId: APP_ID, appUnique: APP_UNIQUE, allowLossy }));
+ assert.ok(result.ok, `allowLossy ${allowLossy}: ${JSON.stringify(result)}`);
+ const weather = result.spec.pages.find((p) => p.key === 'weather');
+ assert.ok(!('connectorBindings' in weather), 'the list the spec cannot state is left out');
+ assert.deepStrictEqual(weather.actionBindings, [APPROVE, SUMMARY], 'and the other list is still stated');
+ assert.deepStrictEqual(result.pageBindings.notCarried, [{ key: 'weather', name: 'Weather', field: 'connectorBindings', reason: 'connectorBindings is present but is not an array' }]);
+ assert.match(stderr, /WARNING: 1 list\(s\) of connector or Custom API bindings are NOT in the spec/);
+ assert.match(stderr, /Rebuilding into THIS environment leaves such a page's bindings as they are/);
+ }
+});
+
+test('main puts pageBindings in the JSON result, and leaves it out when there is none', async () => {
+ const run = async (result) => {
+ const outDir = tmp('page-bindings-main-');
+ const results = [];
+ await main({
+ argv: ['--env', ENV, '--app', APP_UNIQUE, '--out', outDir],
+ stderr: { write: () => {} },
+ emitResult: (ok, payload) => results.push({ ok, payload }),
+ preflightAuth: async () => ({ ok: true }),
+ makeGenpageSdk: () => ({}),
+ makeDownloadSdk: async () => ({ sdk: { queryRecords: async (_set, opts = {}) => (/uniquename eq/.test(opts.filter || '') ? [{ appmoduleid: APP_ID }] : [{ uniquename: APP_UNIQUE }]) }, cleanup() {} }),
+ runDownload: async () => ({ ok: true, spec: { schemaVersion: 2, solution: { uniqueName: 'ContosoBindings', publisherPrefix: 'contoso' }, app: { name: 'Bindings App', uniqueName: APP_UNIQUE }, entities: [], pages: [], appShell: { areas: [] } }, pages: [], entities: [], webResources: [], droppedSubareas: 0, droppedSubareaDetails: [], dashboardWarnings: [], ...result }),
+ validateAppSpec: () => ({ ok: true, warnings: [] }),
+ });
+ assert.strictEqual(results.length, 1);
+ return results[0];
+ };
+ const report = pageBindingsReport([{ pageId: A, key: 'weather', name: 'Weather', connectorBindings: [WEATHER] }], []);
+ const withReport = await run({ pageBindings: report });
+ assert.strictEqual(withReport.ok, true);
+ assert.deepStrictEqual(withReport.payload.pageBindings, report);
+ const without = await run({});
+ assert.strictEqual('pageBindings' in without.payload, false);
+});
+
+// ── a spec states a list only whole, and only what is known to be safe ───────────────────────────────────────────────────────────
+// The spec is the artifact that is committed, reviewed and shared; the page's own config.json is the environment's. A binding a page holds can carry more than the runtime reads — a connection id of the
+// environment it was made in, a credential someone put in a connectors.json (as a value, a key, or inside a URL), a property a later runtime adds — and none of it is the spec's to carry. So a list is in the
+// spec only when every key of every entry is a documented property and every value has a conservative shape known to be safe (lib/page-bindings.js has the threat model); otherwise the WHOLE list is left out,
+// and the download says where — the page, the list, the entry's place and the vetted property — never what. A list left out is one a rebuild does not send: the page keeps it as it is.
+
+// Synthetic values, none a real credential. Each is looked for in everything a download writes or prints.
+const SECRET = {
+ token: 'SYNTHETIC_TEST_ACCESS_TOKEN',
+ clientSecret: 'SYNTHETIC_TEST_SECRET',
+ password: 'SYNTHETIC_TEST_PASSWORD',
+ signature: 'SYNTHETIC_TEST_SIGNATURE',
+ connection: 'env-local-connection-placeholder',
+ named: `ghp_${'R'.repeat(36)}`,
+};
+const leaked = (text) => Object.values(SECRET).filter((value) => String(text).includes(value));
+
+// The page's side of a binding: what it may hold beyond what a spec states.
+const WEATHER_WITH_EXTRAS = { ...WEATHER, connectionId: SECRET.connection, credentials: { accessToken: SECRET.token, clientSecret: SECRET.clientSecret }, futureProperty: { kept: true } };
+const SHAREPOINT_WITH_EXTRAS = { ...SHAREPOINT, apiKey: SECRET.clientSecret };
+const APPROVE_WITH_EXTRAS = { ...APPROVE, headers: { Authorization: `Bearer ${SECRET.token}` } };
+
+// A download of the app whose first page holds the given lists.
+async function downloadPagesHolding({ connectorBindings, actionBindings, allowLossy } = {}) {
+ const pages = environmentPages();
+ if (connectorBindings !== undefined) pages[0].connectorBindings = connectorBindings;
+ if (actionBindings !== undefined) pages[0].actionBindings = actionBindings;
+ const outDir = tmp('page-bindings-secret-');
+ const { readSdk } = downloadFixture(pages);
+ const { value: result, stderr } = await withStderr(() => runDownload({ sdk: readSdk(), genpage: fakeGenpage({ pages: livePages(pages) }), outDir, appId: APP_ID, appUnique: APP_UNIQUE, allowLossy }));
+ assert.ok(result.ok, JSON.stringify(result));
+ return { result, stderr, outDir, weather: result.spec.pages.find((p) => p.key === 'weather') };
+}
+
+// What `main` writes to disk and prints for a download's result: the persistence path every sink goes through.
+async function persisted(downloaded) {
+ const outDir = tmp('page-bindings-main-out-');
+ const printed = [];
+ await main({
+ argv: ['--env', ENV, '--app', APP_UNIQUE, '--out', outDir],
+ stderr: { write: () => {} },
+ emitResult: (ok, payload) => printed.push({ ok, payload }),
+ preflightAuth: async () => ({ ok: true }),
+ makeGenpageSdk: () => ({}),
+ makeDownloadSdk: async () => ({ sdk: { queryRecords: async (_set, opts = {}) => (/uniquename eq/.test(opts.filter || '') ? [{ appmoduleid: APP_ID }] : [{ uniquename: APP_UNIQUE }]) }, cleanup() {} }),
+ runDownload: async () => downloaded,
+ });
+ assert.strictEqual(printed.length, 1);
+ assert.strictEqual(printed[0].ok, true, JSON.stringify(printed[0].payload));
+ return { spec: fs.readFileSync(path.join(outDir, 'app-spec.json'), 'utf8'), printed: JSON.stringify(printed) };
+}
+
+test('a list that holds a credential, a connection id or a property no spec states — in any entry — is left out of the spec WHOLE, and the download says where, never what', async () => {
+ const { result, stderr, outDir, weather } = await downloadPagesHolding({ connectorBindings: [WEATHER, SHAREPOINT_WITH_EXTRAS], actionBindings: [APPROVE_WITH_EXTRAS, SUMMARY] });
+ assert.ok(!('connectorBindings' in weather), 'not the clean entry alone: a spec that stated part of the list would have a rebuild replace the page\'s list with that part');
+ assert.ok(!('actionBindings' in weather));
+ assert.ok(validateAppSpec(JSON.parse(JSON.stringify(result.spec))).ok, 'the spec validates');
+ assert.deepStrictEqual(result.pageBindings.notCarried, [
+ { key: 'weather', name: 'Weather', field: 'actionBindings', reason: 'actionBindings[0] holds an unrecognized property, which an App Spec does not state (a binding states only name, isFunction, boundEntityLogicalName, displayName, parameterKinds)' },
+ { key: 'weather', name: 'Weather', field: 'connectorBindings', reason: 'connectorBindings[1] holds an unrecognized property, which an App Spec does not state (a binding states only logicalName, connectorId, dataset, tables, tableDisplayNames, operations)' },
+ ]);
+ assert.ok(!('propertiesLeftOut' in result.pageBindings), 'no property is projected out of a list, so none is listed');
+ for (const word of ['apiKey', 'headers']) assert.ok(!JSON.stringify(result).includes(word) && !stderr.includes(word), `an unrecognized key is never said: ${word}`);
+ assert.deepStrictEqual(leaked(JSON.stringify(result) + stderr), []);
+ assert.match(stderr, /WARNING: 2 list\(s\) of connector or Custom API bindings are NOT in the spec/);
+ assert.match(stderr, /still in the page folder's own config\.json \(pages\/<page id>\/config\.json\)/);
+ // The page folder is the page as the environment holds it, and is not rewritten.
+ const sidecar = JSON.parse(fs.readFileSync(path.join(outDir, 'pages', WEATHER_ID, 'config.json'), 'utf8'));
+ assert.strictEqual(sidecar.connectorBindings[1].apiKey, SECRET.clientSecret);
+ // A list whose entries are all known to be safe is stated as the page holds it, beside one that is left out.
+ const mixed = await downloadPagesHolding({ connectorBindings: [WEATHER_WITH_EXTRAS], actionBindings: [APPROVE, SUMMARY] });
+ assert.ok(!('connectorBindings' in mixed.weather));
+ assert.deepStrictEqual(mixed.weather.actionBindings, [APPROVE, SUMMARY]);
+});
+
+// Every form a credential took in an adversarial probe of the earlier rule, through the download's projection AND `main`'s persistence: the list is left out, and the marker is in none of the spec on disk, the
+// printed result or stderr; and an authored spec that states it is refused.
+test('a credential hidden in a URL (user-info alone, an encoded query key, a fragment), in JSON text, in a Custom API\'s display name, as a property NAME or a parameter name, reaches no sink', async () => {
+ const cases = [
+ ['a token alone in the user-info', 'connectorBindings', { ...WEATHER, dataset: `https://${SECRET.token}@contoso.example/data` }],
+ ['a percent-encoded query key', 'connectorBindings', { ...WEATHER, dataset: `https://contoso.example/data?api%5Fkey=${SECRET.token}` }],
+ ['a fragment token', 'connectorBindings', { ...WEATHER, dataset: `https://contoso.example/data#access_token=${SECRET.token}` }],
+ ['JSON text in a dataset', 'connectorBindings', { ...WEATHER, dataset: JSON.stringify({ accessToken: SECRET.token }) }],
+ ['a password in the user-info', 'connectorBindings', { ...WEATHER, dataset: `https://maker:${SECRET.password}@contoso.example/data` }],
+ ['a nested credential in a list', 'connectorBindings', { ...WEATHER, tables: [{ apiKey: SECRET.clientSecret }] }],
+ ['a token as a property name', 'connectorBindings', { ...WEATHER, [SECRET.named]: true }],
+ ['a credential-shaped identity', 'connectorBindings', { ...WEATHER, logicalName: `Bearer ${SECRET.token}` }],
+ ["a Custom API's display name that is a URL", 'actionBindings', { ...APPROVE, displayName: `https://${SECRET.token}@contoso.example/api` }],
+ ['a token as a parameter name', 'actionBindings', { ...APPROVE, parameterKinds: { [SECRET.named]: 'String' } }],
+ ['a credential-shaped Custom API name', 'actionBindings', { ...APPROVE, name: SECRET.named }],
+ ];
+ for (const [what, kind, entry] of cases) {
+ const { result, stderr, weather } = await downloadPagesHolding({ [kind]: [entry] });
+ assert.ok(!(kind in weather), `${what}: the list is left out`);
+ assert.strictEqual(result.pageBindings.notCarried.find((n) => n.field === kind).field, kind, what);
+ const disk = await persisted(result);
+ assert.deepStrictEqual(leaked(disk.spec), [], `${what}: app-spec.json`);
+ assert.deepStrictEqual(leaked(disk.printed), [], `${what}: the printed result`);
+ assert.deepStrictEqual(leaked(stderr), [], `${what}: stderr`);
+ const authored = validateAppSpec(specWithPages({ [kind]: [entry] }));
+ assert.strictEqual(authored.ok, false, `${what}: an authored spec that states it is refused`);
+ assert.deepStrictEqual(leaked(JSON.stringify(authored)), [], `${what}: and the refusal does not quote it`);
+ }
+});
+
+// A parser normalizes what it reads: a dot-segment removes the path segment before it, so a check of the parsed URL never sees that segment, while the spec would keep the text as it was. The text a download
+// would persist is the text that is checked, so such a URL — in any place a binding holds a text — leaves its list out of the spec, and of every other sink.
+test('a URL whose dot-segments would drop a segment — plain or percent-encoded — leaves its list out of every sink: the text checked is the text that would be persisted', async () => {
+ const hidden = (dots) => `https://contoso.example/${SECRET.token}/${dots}/site`;
+ const cases = [
+ ['a dot-segment, as a connector dataset', 'connectorBindings', { ...WEATHER, dataset: hidden('..') }],
+ ['a percent-encoded dot-segment, as a connector dataset', 'connectorBindings', { ...WEATHER, dataset: hidden('%2e%2e') }],
+ ["an upper-case encoded dot-segment, as a custom connector's dataset", 'connectorBindings', { logicalName: 'contoso_widgets', connectorId: '/providers/Microsoft.PowerApps/apis/shared_contoso-5fwidgets-5f6a8c', dataset: hidden('%2E%2E'), operations: ['ListWidgets'] }],
+ ['a dot-segment, as a table id', 'connectorBindings', { ...SHAREPOINT, tables: [hidden('..')] }],
+ ["a dot-segment, as a Custom API's display name", 'actionBindings', { ...APPROVE, displayName: hidden('..') }],
+ ['a dot-segment, as a parameter name', 'actionBindings', { ...APPROVE, parameterKinds: { [hidden('..')]: 'String' } }],
+ ];
+ for (const [what, kind, entry] of cases) {
+ const { result, stderr, weather } = await downloadPagesHolding({ [kind]: [entry] });
+ assert.ok(!(kind in weather), `${what}: the list is left out`);
+ const carried = result.pageBindings.notCarried.find((n) => n.field === kind);
+ assert.ok(carried && !carried.reason.includes(SECRET.token) && !carried.reason.includes('..'), `${what}: the reason says where, never what`);
+ const disk = await persisted(result);
+ assert.deepStrictEqual(leaked(disk.spec), [], `${what}: app-spec.json`);
+ assert.deepStrictEqual(leaked(disk.printed), [], `${what}: the printed result`);
+ assert.deepStrictEqual(leaked(stderr), [], `${what}: stderr`);
+ const authored = validateAppSpec(specWithPages({ [kind]: [entry] }));
+ assert.strictEqual(authored.ok, false, `${what}: an authored spec that states it is refused`);
+ assert.deepStrictEqual(leaked(JSON.stringify(authored)), [], `${what}: and the refusal does not quote it`);
+ }
+});
+
+test('validateAppSpec refuses a binding property an App Spec does not state, and a value without the shape it states — by the vetted name or as "an unrecognized property", never by value or key', () => {
+ const unrecognized = (kind) => `page 'weather': ${kind}[0] holds an unrecognized property, which an App Spec does not state (a binding states only ${kind === 'connectorBindings' ? 'logicalName, connectorId, dataset, tables, tableDisplayNames, operations' : 'name, isFunction, boundEntityLogicalName, displayName, parameterKinds'})`;
+ const cases = [
+ [{ connectorBindings: [{ ...WEATHER, connectionId: SECRET.connection }] }, unrecognized('connectorBindings')],
+ [{ connectorBindings: [{ ...WEATHER, [SECRET.named]: 1 }] }, unrecognized('connectorBindings')],
+ [{ actionBindings: [{ ...APPROVE, headers: { Authorization: SECRET.token } }] }, unrecognized('actionBindings')],
+ [{ connectorBindings: [{ ...WEATHER, operations: [{ credentials: SECRET.token }] }] }, "page 'weather': connectorBindings[0].operations must be a list of identifiers"],
+ [{ connectorBindings: [{ ...WEATHER, dataset: `https://${SECRET.token}@contoso.example/x` }] }, "page 'weather': connectorBindings[0].dataset must be empty, a plain name, or an http(s) URL with no user-info, no query and no fragment"],
+ [{ actionBindings: [{ ...APPROVE, isFunction: 'no' }] }, "page 'weather': actionBindings[0].isFunction must be true or false"],
+ [{ actionBindings: [{ ...APPROVE, parameterKinds: { [SECRET.named]: 'String' } }] }, "page 'weather': actionBindings[0].parameterKinds must map safe parameter names to the ten declared primitive kinds (Boolean, DateTime, Decimal, Float, Integer, Money, Picklist, String, StringArray, Guid); lookup inputs stay in the call as structural values, with discovery-only hints kept out of this map"],
+ [{ actionBindings: [{ ...APPROVE, displayName: `https://contoso.example/?sig=${SECRET.signature}` }] }, "page 'weather': actionBindings[0].displayName must be a plain label (letters, digits, spaces and simple punctuation; no URL)"],
+ ];
+ for (const [extra, expected] of cases) {
+ const result = validateAppSpec(specWithPages(extra));
+ assert.strictEqual(result.ok, false, JSON.stringify(extra));
+ assert.ok(result.errors.includes(expected), `${expected}\n got ${JSON.stringify(result.errors)}`);
+ assert.deepStrictEqual(leaked(JSON.stringify(result)), [], 'the refusal never quotes a value or an unrecognized key');
+ for (const key of ['connectionId', 'headers']) assert.ok(!JSON.stringify(result.errors).includes(key), key);
+ }
+ const clean = validateAppSpec(specWithPages({ connectorBindings: [WEATHER, SHAREPOINT], actionBindings: [APPROVE, SUMMARY] }));
+ assert.ok(clean.ok, JSON.stringify(clean.errors));
+ assert.deepStrictEqual(clean.warnings, []);
+});
+
+test('a build refuses a spec whose binding states a credential or a connection id before it does anything else, and never prints them', async () => {
+ const { buildModelApp } = require('../build-model-app.js');
+ const spec = specWithPages({ connectorBindings: [{ ...WEATHER, credentials: { accessToken: SECRET.token }, connectionId: SECRET.connection }] });
+ const result = await buildModelApp(spec, { apply: true, appDir: tmp('page-bindings-refused-'), profile: 'deploy' }, {});
+ assert.strictEqual(result.ok, false);
+ assert.ok(result.errors.some((e) => /^page 'weather': connectorBindings\[0\] holds an unrecognized property, which an App Spec does not state/.test(e)), JSON.stringify(result.errors));
+ assert.deepStrictEqual(leaked(JSON.stringify(result)), []);
+ assert.ok(!/connectionId|credentials/.test(JSON.stringify(result.errors)), 'nor the names of the keys');
+});
+
+test('pageBindingsNote says which lists are not in the spec — the page, the list, the entry\'s place and the vetted property — and where their values still are', () => {
+ const pages = [{ pageId: A, key: 'weather', name: 'Weather', actionBindings: [APPROVE] }];
+ const unkept = [{ pageId: A, field: 'connectorBindings', reason: 'connectorBindings[0].dataset must be empty, a plain name, or an http(s) URL with no user-info, no query and no fragment' }];
+ const report = pageBindingsReport(pages, unkept);
+ assert.deepStrictEqual(report.notCarried, [{ key: 'weather', name: 'Weather', field: 'connectorBindings', reason: unkept[0].reason }]);
+ assert.ok(!('propertiesLeftOut' in report));
+ const text = pageBindingsNote(report);
+ assert.match(text, /^NOTE: 1 page\(s\) hold connector or Custom API bindings/);
+ assert.match(text, /WARNING: 1 list\(s\) of connector or Custom API bindings are NOT in the spec, because the spec cannot state them as the page holds them: "Weather" \(connectorBindings\[0\]\.dataset must be empty/);
+ assert.match(text, /left out whole \(the values are never printed\)/);
+ assert.match(text, /still in the page folder's own config\.json \(pages\/<page id>\/config\.json\)/);
+ assert.strictEqual(pageBindingsReport([{ pageId: A, key: 'plain', name: 'Plain' }], []), null);
+});
+
+// ── the build ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────
+
+const PHASES = ['solution', 'data-model', 'app-shell', 'pages'];
+
+// What a download wrote, rebuilt into the environment it came from: the page the SDK already holds is updated, never created.
+async function downloadThenRebuild({ edit } = {}) {
+ const appDir = tmp('page-bindings-roundtrip-');
+ const pages = environmentPages();
+ const { sdk, readSdk } = downloadFixture(pages);
+ const genpage = fakeGenpage({ pages: livePages(pages) });
+ const downloaded = await withStderr(() => runDownload({ sdk: readSdk(), genpage, outDir: appDir, appId: APP_ID, appUnique: APP_UNIQUE }));
+ assert.ok(downloaded.value.ok, JSON.stringify(downloaded.value));
+ const spec = JSON.parse(JSON.stringify(downloaded.value.spec));
+ if (edit) edit(spec);
+ assert.ok(validateAppSpec(spec).ok, validateAppSpec(spec).errors.join('; '));
+ const before = genpage.of('update').length;
+ const rebuilt = await runSdkBuild(spec, { sdk, genpage, appDir, env: ENV, apply: true, phases: PHASES });
+ assert.ok(rebuilt.ok);
+ assert.deepStrictEqual(rebuilt.created.pages, { weather: WEATHER_ID, detail: DETAIL_ID });
+ const updates = genpage.of('update').slice(before);
+ assert.strictEqual(updates.length, 2, 'one update per page');
+ assert.strictEqual(genpage.of('create').length, 0, 'a downloaded page is updated, never created');
+ const sentTo = (id) => updates.find((u) => u.args[0] === id).args[1];
+ return { genpage, spec, sentTo, appDir };
+}
+
+test('a rebuild into the environment a spec was downloaded from sends the bindings the spec states — and none for a page that states none, which keeps its own', async () => {
+ const { genpage, sentTo } = await downloadThenRebuild();
+ const weather = sentTo(WEATHER_ID);
+ assert.deepStrictEqual(weather.connectorBindings, [WEATHER, SHAREPOINT]);
+ assert.deepStrictEqual(weather.actionBindings, [APPROVE, SUMMARY]);
+ const detail = sentTo(DETAIL_ID);
+ for (const key of ['connectorBindings', 'actionBindings']) assert.ok(!(key in detail), `${key} is not sent for a page that states none: it keeps its own`);
+ // What the environment holds after the rebuild is what it held before.
+ assert.deepStrictEqual(genpage.pages.get(WEATHER_ID).connectorBindings, [WEATHER, SHAREPOINT]);
+ assert.deepStrictEqual(genpage.pages.get(WEATHER_ID).actionBindings, [APPROVE, SUMMARY]);
+});
+
+test('a spec edit to a page\'s binding lists is what the page holds after the rebuild: a changed list replaces, `[]` clears, and a list the spec no longer states is left as it is', async () => {
+ const { genpage, spec, sentTo } = await downloadThenRebuild({
+ edit: (spec) => {
+ const weather = spec.pages.find((p) => p.key === 'weather');
+ weather.connectorBindings = [WEATHER];
+ weather.actionBindings = [];
+ const detail = spec.pages.find((p) => p.key === 'detail');
+ detail.actionBindings = [SUMMARY];
+ },
+ });
+ assert.deepStrictEqual(sentTo(WEATHER_ID).connectorBindings, [WEATHER]);
+ assert.deepStrictEqual(sentTo(WEATHER_ID).actionBindings, [], 'a stated empty list is sent: it clears the page\'s');
+ assert.deepStrictEqual(genpage.pages.get(WEATHER_ID).connectorBindings, [WEATHER]);
+ assert.deepStrictEqual(genpage.pages.get(WEATHER_ID).actionBindings, []);
+ assert.deepStrictEqual(genpage.pages.get(DETAIL_ID).actionBindings, [SUMMARY], 'a page that held none now holds what the spec states');
+ assert.ok(!('connectorBindings' in sentTo(DETAIL_ID)));
+ assert.ok(spec.pages.length === 2);
+
+ // A list the spec leaves out is not sent, so the page keeps what it holds.
+ const kept = await downloadThenRebuild({ edit: (s) => { delete s.pages.find((p) => p.key === 'weather').connectorBindings; } });
+ assert.ok(!('connectorBindings' in kept.sentTo(WEATHER_ID)));
+ assert.deepStrictEqual(kept.genpage.pages.get(WEATHER_ID).connectorBindings, [WEATHER, SHAREPOINT]);
+ assert.deepStrictEqual(kept.sentTo(WEATHER_ID).actionBindings, [APPROVE, SUMMARY], 'the other list is still sent');
+});
+
+// `--changed-only` applies a change fast only when it is provably one of its shapes; a page whose only change is its source is the one such shape. A change to a binding list is another thing, so the
+// build takes the full way, which sends the lists as the spec states them.
+test('--changed-only reads a change to a page\'s binding list as a structural change, so it takes a full build — a change to the source alone still goes the fast way', () => {
+ const page = (extra = {}) => ({ key: 'weather', name: 'Weather', source: { kind: 'tsx', codeFile: 'weather.tsx' }, __contentSha: 'sha-1', ...extra });
+ const prior = { pages: [page({ connectorBindings: [WEATHER] })] };
+ const edited = classifyPages({ pages: [page({ connectorBindings: [WEATHER, SHAREPOINT] })] }, prior);
+ assert.deepStrictEqual(edited.fast, []);
+ assert.strictEqual(edited.full.length, 1);
+ assert.match(edited.full[0], /pages: page 'weather' changed structurally/);
+ const stated = classifyPages({ pages: [page({ connectorBindings: [WEATHER] })] }, { pages: [page()] });
+ assert.strictEqual(stated.full.length, 1, 'a list the spec states for the first time is a change too');
+ const sourceOnly = classifyPages({ pages: [page({ connectorBindings: [WEATHER], __contentSha: 'sha-2' })] }, prior);
+ assert.deepStrictEqual(sourceOnly.full, []);
+ assert.deepStrictEqual(sourceOnly.fast.map((f) => f.identity), ['weather']);
+});
+
+// A fresh environment: nothing but the app the build makes. The stand-in answers what the solution, data-model, app-shell and pages phases read and write for a spec whose
+// navigation holds its pages and one table (a new app is created with its navigation minus the pages, and Dataverse refuses a navigation with nothing left).
+function freshEnvironmentSdk() {
+ let idc = 0;
+ const store = {};
+ const empty = '<SiteMap><Area><Group></Group></Area></SiteMap>';
+ return {
+ queryRecords: async (e, o) => {
+ const filter = (o && o.filter) || '';
+ if (e === 'appmodule') {
+ const m = filter.match(/uniquename eq '([^']+)'/);
+ return [{ appmoduleid: APP_ID, appmoduleidunique: APP_UNIQUE_ID, uniquename: m ? m[1] : undefined }];
+ }
+ if (e === 'appmodulecomponent') return [{ objectid: SITEMAP_ID, componenttype: 62 }];
+ if (e === 'sitemap') return /sitemapnameunique eq/.test(filter) ? [{ sitemapid: 'sm-1' }] : [{ sitemapxml: empty }];
+ if (e === 'solution' || e === 'webresource' || e === 'systemform') return [];
+ if (e === 'savedquery') return [{ savedqueryid: 'defview-x', isdefault: true }];
+ return [{ publisherid: 'pub-1' }];
+ },
+ findArtifact: async () => null,
+ fetchArtifact: async (t, id) => { if (!store[`${t}:${id}`]) store[`${t}:${id}`] = { id, siteMap: { areas: [] } }; return store[`${t}:${id}`]; },
+ createPublisher: async () => ({ id: 'pub-new' }),
+ createSolution: async () => ({ id: 'sol-1' }),
+ findTables: async () => [],
+ findColumns: async () => [],
+ fetchEntityMetadata: async (logical) => ({ logicalName: logical, entitySetName: `${logical}s`, attributes: [], relationships: [] }),
+ createTable: async (o) => ({ logicalName: o.schemaName.toLowerCase(), entitySetName: `${o.schemaName.toLowerCase()}s`, metadataId: `tbl-${o.schemaName}` }),
+ createColumn: async (e, o) => ({ logicalName: o.schemaName.toLowerCase(), metadataId: `col-${o.schemaName}` }),
+ createRelationship: async (o) => ({ schemaName: o.schemaName }),
+ createWebResource: async (o) => ({ id: `wr-${++idc}`, name: o.name }),
+ updateWebResource: async () => ({}),
+ enrichDefaultViews: async () => ({ updated: [] }),
+ createArtifact: (t, def) => { const id = `${t}-${++idc}`; store[`${t}:${id}`] = Object.assign({ id }, def); return JSON.parse(JSON.stringify(store[`${t}:${id}`])); },
+ getArtifact: async (t, id) => { await Promise.resolve(); return store[`${t}:${id}`] || { id }; },
+ addElement: async () => { await Promise.resolve(); return {}; },
+ updateElement: async () => { await Promise.resolve(); return {}; },
+ removeElement: async () => { await Promise.resolve(); return {}; },
+ pushArtifact: async (t, id) => ({ type: t, id, saved: true, shipped: false, publish: { kind: 'notRequested' } }),
+ addSolutionComponent: async () => {},
+ publishArtifact: async (type, id) => ({ type, id, shipped: true, publish: { kind: 'verified' } }),
+ dataverse: { get: async () => ({ status: 404, body: null }) },
+ };
+}
+
+// The spec of a copy that goes to another environment: what a download wrote, without the ids of the pages of the environment it came from (they belong to it).
+async function portableCopy() {
+ const outDir = tmp('page-bindings-portable-');
+ const pages = environmentPages();
+ const { readSdk } = downloadFixture(pages);
+ const downloaded = await withStderr(() => runDownload({ sdk: readSdk(), genpage: fakeGenpage({ pages: livePages(pages) }), outDir, appId: APP_ID, appUnique: APP_UNIQUE }));
+ assert.ok(downloaded.value.ok, JSON.stringify(downloaded.value));
+ const spec = JSON.parse(JSON.stringify(downloaded.value.spec));
+ for (const page of spec.pages) delete page.pageId;
+ // Weather navigates to Detail, so the build makes Detail first — as a target, in one write — and Weather after it.
+ const weather = spec.pages.find((p) => p.key === 'weather');
+ weather.navigatesTo = [{ targetKey: 'detail' }];
+ fs.writeFileSync(path.join(outDir, weather.source.codeFile), 'export default function Weather() { Xrm.Navigation.navigateTo({ pageType: "generative", pageId: "PAGEREF_detail", data: {} }); return null; }\r\n');
+ return { spec, outDir };
+}
+
+test('a copy of a downloaded spec built into ANOTHER environment writes the bindings onto the pages it creates', async () => {
+ const { spec, outDir } = await portableCopy();
+ const genpage = fakeGenpage();
+ const rebuilt = await runSdkBuild(spec, { sdk: freshEnvironmentSdk(), genpage, appDir: outDir, env: 'https://fabrikam.crm.dynamics.com', apply: true, phases: PHASES });
+ assert.ok(rebuilt.ok);
+ assert.strictEqual(genpage.of('update').length, 0, 'nothing existed there: every page is created');
+ const byName = new Map(genpage.of('create').map((c) => [c.args[0].name, c.args[0]]));
+ assert.deepStrictEqual([...byName.keys()].sort(), ['Item Detail', 'Weather']);
+ assert.deepStrictEqual(byName.get('Weather').connectorBindings, [WEATHER, SHAREPOINT]);
+ assert.deepStrictEqual(byName.get('Weather').actionBindings, [APPROVE, SUMMARY]);
+ for (const key of ['connectorBindings', 'actionBindings']) assert.ok(!(key in byName.get('Item Detail')), `${key} is not sent for the page that states none`);
+ const held = [...genpage.pages.values()].find((page) => page.name === 'Weather');
+ assert.deepStrictEqual([held.connectorBindings, held.actionBindings], [[WEATHER, SHAREPOINT], [APPROVE, SUMMARY]], 'the environment holds what the spec states');
+});
+
+test('a navigation target that states bindings is created with them — the create that makes it is its only write, so it has to carry them', async () => {
+ const { spec, outDir } = await portableCopy();
+ // The other way round: Detail, the target, states the bindings, and Weather states none.
+ const detail = spec.pages.find((p) => p.key === 'detail');
+ const weather = spec.pages.find((p) => p.key === 'weather');
+ detail.connectorBindings = weather.connectorBindings;
+ detail.actionBindings = weather.actionBindings;
+ delete weather.connectorBindings;
+ delete weather.actionBindings;
+ const genpage = fakeGenpage();
+ const rebuilt = await runSdkBuild(spec, { sdk: freshEnvironmentSdk(), genpage, appDir: outDir, env: 'https://fabrikam.crm.dynamics.com', apply: true, phases: PHASES });
+ assert.ok(rebuilt.ok);
+ assert.strictEqual(genpage.of('update').length, 0, 'the target is not written again: its create held everything');
+ const byName = new Map(genpage.of('create').map((c) => [c.args[0].name, c.args[0]]));
+ assert.deepStrictEqual(byName.get('Item Detail').connectorBindings, [WEATHER, SHAREPOINT]);
+ assert.deepStrictEqual(byName.get('Item Detail').actionBindings, [APPROVE, SUMMARY]);
+ for (const key of ['connectorBindings', 'actionBindings']) assert.ok(!(key in byName.get('Weather')), `${key} is not sent for the page that states none`);
+});
+
+// ── a rebuild checks the environment's references before it writes a binding ──────────────────────────────────────────────────
+// A binding is called through the logical name of a connection reference, and the spec cannot make the reference. A rebuild into another environment reads what that environment has for the names the
+// spec states — before it writes anything — and: refuses a reference that is there for ANOTHER connector (the page would call that connector under this name), says by name what is not there, and says by name
+// a Custom API that is the other kind or bound to another table. It never makes one: a connection holds a user's sign-in.
+const FABRIKAM = 'https://fabrikam.crm.dynamics.com';
+const apiId = (name) => `/providers/Microsoft.PowerApps/apis/${name}`;
+// A reference's row as the Web API answers the build's read: complete — its connector, a connection, and no custom connector recorded (a connector the platform publishes).
+const referenceRow = (logicalName, connector) => ({ connectionreferencelogicalname: logicalName, connectorid: connector === undefined ? undefined : apiId(connector), connectionid: `shared-${logicalName}-0001`, _customconnectorid_value: null });
+
+// The environment a copy goes to, with the references (`connectionreference` rows) and Custom APIs (`customapi` rows) it already holds. `reads` are the reads the build made of them, `writes` every write it
+// made to the SDK before it stopped.
+function targetEnvironment({ references = [], apis = [], connectors = [], failReferences, failApis } = {}) {
+ const sdk = freshEnvironmentSdk();
+ const answer = sdk.queryRecords;
+ const reads = [];
+ const writes = [];
+ const answers = { connectionreference: references, customapi: apis, connector: connectors };
+ sdk.queryRecords = async (entity, options) => {
+ if (!(entity in answers)) return answer(entity, options);
+ reads.push({ entity, options });
+ if (entity === 'connectionreference' && failReferences) throw new Error(failReferences);
+ if (entity === 'customapi' && failApis) throw new Error(failApis);
+ return answers[entity];
+ };
+ for (const method of ['createPublisher', 'createSolution', 'createTable', 'createColumn', 'createRelationship', 'createWebResource', 'updateWebResource', 'createArtifact', 'addElement', 'updateElement', 'removeElement', 'pushArtifact', 'publishArtifact', 'addSolutionComponent']) {
+ const original = sdk[method];
+ sdk[method] = (...args) => { writes.push(method); return original(...args); };
+ }
+ return { sdk, reads, writes };
+}
+const BOTH_REFERENCES = [referenceRow('contoso_msnweather', 'shared_msnweather'), referenceRow('contoso_sharepoint', 'shared_sharepointonline')];
+const BOTH_APIS = [
+ { uniquename: 'contoso_ApproveOrder', isfunction: false, bindingtype: 1, boundentitylogicalname: 'contoso_item' },
+ { uniquename: 'contoso_GetSummary', isfunction: true, bindingtype: 0 },
+];
+// The operations of Weather's binding (MSN Weather, a connector the platform publishes) are said to be not checked on every build that writes it: no row names a custom connector for its reference. Pinned once
+// (`a binding whose reference names no custom connector`, below) and left out of the other tests' lists of what is said.
+const OPERATIONS_NOT_CHECKED = /^the operations that connector binding "contoso_msnweather" of page "Weather" call were not checked: /;
+const bindingWords = (messages) => messages.filter((m) => /connection reference|Custom API|binding/i.test(m) && !OPERATIONS_NOT_CHECKED.test(m));
+
+test('a build into another environment refuses a binding whose connection reference is there for ANOTHER connector — before it writes anything', async () => {
+ const { spec, outDir } = await portableCopy();
+ const { sdk, reads, writes } = targetEnvironment({ references: [referenceRow('contoso_msnweather', 'shared_office365users'), BOTH_REFERENCES[1]], apis: BOTH_APIS });
+ const genpage = fakeGenpage();
+ await assert.rejects(runSdkBuild(spec, { sdk, genpage, appDir: outDir, env: FABRIKAM, apply: true, phases: PHASES }), (error) => {
+ assert.ok(error instanceof BuildHalt, String(error && error.stack));
+ assert.deepStrictEqual([error.phase, error.code, error.recoverable, error.transient], ['preflight', 'pages-binding-reference-conflict', false, false], 'a run again reads the same references: it is not retried');
+ assert.match(error.message, /1 connector binding\(s\) name a connection reference this environment already has for ANOTHER connector: page "Weather": connector binding "contoso_msnweather" is for connector shared_msnweather, but the connection reference of that name in this environment is for connector shared_office365users\./);
+ assert.match(error.message, /The build stopped before writing anything\./);
+ assert.match(error.message, /give the binding the logical name of a reference that is for the right connector \(create-connection-reference\.js makes one\)/);
+ assert.match(error.message, /set the binding's connectorId in the spec to the connector this environment has/);
+ assert.ok(!/contoso_sharepoint/.test(error.message), 'only the binding that conflicts is named');
+ return true;
+ });
+ assert.deepStrictEqual(writes, [], 'nothing was written: no solution, no table, no app');
+ assert.deepStrictEqual(genpage.calls.filter((c) => c.method === 'create' || c.method === 'update'), [], 'and no page');
+ assert.deepStrictEqual(reads.map((r) => r.entity), ['connectionreference', 'customapi'], 'what it read: the references and the Custom APIs the pages state, once');
+});
+
+// The halt's text opens with the page's name, and the build decides from a halt's text whether it is a transient error to run every phase again for (isTransientHalt, build-model-app.js). A page
+// called "SQL Timeout 503 try again later" must not make this refusal read as one: it is raised before anything is written, and a run again reads the same reference. The words alone DO read as
+// transient (the control), so it is the halt's own policy (`retry: RETRY.NEVER`) that is held here — tests/halt-retry-policy.test.js names this file for it.
+test('the conflict halt of a page whose name reads as a transient error is still final — the build does not run again for it', async () => {
+ const { isTransientHalt } = require('../build-model-app.js');
+ const { spec, outDir } = await portableCopy();
+ spec.pages.find((p) => p.key === 'weather').name = 'SQL Timeout 503 try again later';
+ const { sdk, writes } = targetEnvironment({ references: [referenceRow('contoso_msnweather', 'shared_office365users'), BOTH_REFERENCES[1]], apis: BOTH_APIS });
+ const halt = await runSdkBuild(spec, { sdk, genpage: fakeGenpage(), appDir: outDir, env: FABRIKAM, apply: true, phases: PHASES }).then(() => null, (error) => error);
+ assert.ok(halt instanceof BuildHalt, String(halt && halt.stack));
+ assert.strictEqual(halt.code, 'pages-binding-reference-conflict');
+ assert.match(halt.message, /page "SQL Timeout 503 try again later": connector binding "contoso_msnweather" is for connector shared_msnweather/);
+ assert.deepStrictEqual(writes, []);
+ assert.strictEqual(isTransientHalt(halt, { spec }), false, 'the halt reads as final');
+ assert.strictEqual(halt.transient, false, 'because it says so');
+ assert.strictEqual(isTransientHalt(new Error(halt.message), { spec }), true, 'its words alone would have read as a transient error');
+});
+
+test('a build with no conflict goes on: the same connector under another spelling of its id, and a Custom API of the same kind and table, are fine — and nothing is said', async () => {
+ const { spec, outDir } = await portableCopy();
+ const { sdk, writes } = targetEnvironment({ references: [referenceRow('CONTOSO_MsnWeather', 'SHARED_MSNWEATHER'), { connectionreferencelogicalname: 'contoso_sharepoint', connectorid: '/providers/Microsoft.PowerApps/apis/Shared_SharePointOnline', connectionid: 'shared-sharepoint-0001', _customconnectorid_value: null }], apis: BOTH_APIS });
+ const genpage = fakeGenpage();
+ const warnings = [];
+ const rebuilt = await runSdkBuild(spec, { sdk, genpage, appDir: outDir, env: FABRIKAM, apply: true, phases: PHASES, warn: (m) => warnings.push(m) });
+ assert.ok(rebuilt.ok);
+ assert.ok(writes.length > 0);
+ assert.strictEqual(genpage.of('create').length, 2);
+ assert.deepStrictEqual(bindingWords(warnings), []);
+});
+
+test('a build says by name what the environment does not have — and writes the pages with their bindings all the same: a reference made later makes the page work without a rebuild', async () => {
+ const { spec, outDir } = await portableCopy();
+ const { sdk } = targetEnvironment({ references: [BOTH_REFERENCES[1]], apis: [BOTH_APIS[1]] });
+ const genpage = fakeGenpage();
+ const warnings = [];
+ const rebuilt = await runSdkBuild(spec, { sdk, genpage, appDir: outDir, env: FABRIKAM, apply: true, phases: PHASES, warn: (m) => warnings.push(m) });
+ assert.ok(rebuilt.ok);
+ const bound = bindingWords(warnings);
+ assert.strictEqual(bound.length, 2, JSON.stringify(bound));
+ assert.match(bound[0], /^page "Weather": connection reference contoso_msnweather is not in this environment, so the page is written with a binding it cannot resolve yet\. A page finds its connector by the reference's logical name: create the reference here \(create-connection-reference\.js, or import the solution that holds it\) and the page works without a rebuild$/);
+ assert.match(bound[1], /^page "Weather": Custom API contoso_ApproveOrder is not in this environment \(list-custom-apis\.js lists what it has\), so a call through the binding is refused until it is deployed here$/);
+ const weather = genpage.of('create').map((c) => c.args[0]).find((c) => c.name === 'Weather');
+ assert.deepStrictEqual([weather.connectorBindings, weather.actionBindings], [[WEATHER, SHAREPOINT], [APPROVE, SUMMARY]], 'the bindings are written: the spec states them');
+});
+
+test('a Custom API of the other kind, or bound to another table, is a warning by name, never a refusal', async () => {
+ const { spec, outDir } = await portableCopy();
+ const { sdk } = targetEnvironment({ references: BOTH_REFERENCES, apis: [{ ...BOTH_APIS[0], isfunction: true }, { ...BOTH_APIS[1], bindingtype: 1, boundentitylogicalname: 'contoso_other' }] });
+ const warnings = [];
+ const rebuilt = await runSdkBuild(spec, { sdk, genpage: fakeGenpage(), appDir: outDir, env: FABRIKAM, apply: true, phases: PHASES, warn: (m) => warnings.push(m) });
+ assert.ok(rebuilt.ok);
+ assert.deepStrictEqual(bindingWords(warnings), [
+ 'page "Weather": Custom API binding "contoso_ApproveOrder" says it is an Action, but the Custom API of that name in this environment is a Function — the runtime refuses the call (wrong_operation_kind)',
+ 'page "Weather": Custom API binding "contoso_GetSummary" is for a Global operation, but the Custom API of that name in this environment is bound to table contoso_other — the runtime refuses the call (invalid_bound_to)',
+ ]);
+});
+
+// A page made with a CUSTOM connector: its binding goes through a reference whose connector's definition is a row of the environment (`connector.openapidefinition`), and the copy there can be another version.
+const WIDGETS_BINDING = { logicalName: 'contoso_widgets', connectorId: '/providers/Microsoft.PowerApps/apis/shared_contoso-5fwidgets-5f6a8c', dataset: '', operations: ['ListWidgets', 'GetWidget'] };
+const WIDGETS_CONNECTOR_ID = 'c0000000-0000-4000-8000-0000000000a1';
+const widgetsDefinition = (operationIds) => JSON.stringify({ swagger: '2.0', info: { title: 'Widgets', version: '1.0' }, paths: Object.fromEntries(operationIds.map((id, i) => [`/widgets/${i}`, { get: { operationId: id, responses: { 200: { description: 'OK' } } } }])) });
+
+test('a build says by name a reference that has no connection, and an operation the custom connector of a reference does not define there — and writes the pages with their bindings all the same', async () => {
+ const { spec, outDir } = await portableCopy();
+ const weather = spec.pages.find((p) => p.key === 'weather');
+ weather.connectorBindings = [WIDGETS_BINDING, SHAREPOINT];
+ const { sdk, reads } = targetEnvironment({
+ references: [
+ { connectionreferencelogicalname: 'contoso_widgets', connectorid: WIDGETS_BINDING.connectorId, connectionid: 'shared-contoso-5fwidgets-0001', _customconnectorid_value: WIDGETS_CONNECTOR_ID },
+ { ...BOTH_REFERENCES[1], connectionid: null },
+ ],
+ apis: BOTH_APIS,
+ connectors: [{ connectorid: WIDGETS_CONNECTOR_ID, openapidefinition: widgetsDefinition(['ListWidgets']) }],
+ });
+ const genpage = fakeGenpage();
+ const warnings = [];
+ const rebuilt = await runSdkBuild(spec, { sdk, genpage, appDir: outDir, env: FABRIKAM, apply: true, phases: PHASES, warn: (m) => warnings.push(m) });
+ assert.ok(rebuilt.ok);
+ assert.deepStrictEqual(reads.map((r) => r.entity), ['connectionreference', 'connector', 'customapi'], 'the definition of the custom connector is read once, by id, between the two reads it already made');
+ assert.deepStrictEqual(bindingWords(warnings), [
+ 'page "Weather": connection reference contoso_sharepoint is in this environment but has no connection, so the page\'s calls through it fail until it has one. Give it a connection (import the solution that holds it with a settings file that does: solution-settings.js, or set it in Power Apps, in the solution\'s connection references) and the page works without a rebuild',
+ 'page "Weather": connector binding "contoso_widgets" calls operation GetWidget, which the custom connector that connection reference is for in this environment does not define, so the page\'s call to it fails there until it does (import the solution that holds the connector as the page was made with it)',
+ ]);
+ const created = genpage.of('create').map((c) => c.args[0]).find((c) => c.name === 'Weather');
+ assert.deepStrictEqual(created.connectorBindings, [WIDGETS_BINDING, SHAREPOINT], 'the page is written with the bindings the spec states');
+});
+
+// Successful but incomplete: the target answers the read, and its row for the custom connector's reference does not name the custom connector. The build has no definition to read, so the operation the
+// binding calls is not proven to be there — and it is said, by name, as not checked: not "fine", and not a refusal either.
+test('a build whose target row names no custom connector for a binding\'s reference says its operations were NOT CHECKED — it is not read as compatible, and nothing is refused', async () => {
+ const { spec, outDir } = await portableCopy();
+ spec.pages.find((p) => p.key === 'weather').connectorBindings = [WIDGETS_BINDING];
+ for (const lookup of [undefined, null, 'not-a-guid']) {
+ const row = { connectionreferencelogicalname: 'contoso_widgets', connectorid: WIDGETS_BINDING.connectorId, connectionid: 'shared-contoso-5fwidgets-0001', ...(lookup === undefined ? {} : { _customconnectorid_value: lookup }) };
+ const { sdk, reads } = targetEnvironment({ references: [row], apis: BOTH_APIS, connectors: [{ connectorid: WIDGETS_CONNECTOR_ID, openapidefinition: widgetsDefinition(['ListWidgets']) }] });
+ const genpage = fakeGenpage();
+ const warnings = [];
+ const rebuilt = await runSdkBuild(spec, { sdk, genpage, appDir: outDir, env: FABRIKAM, apply: true, phases: PHASES, warn: (m) => warnings.push(m) });
+ assert.ok(rebuilt.ok, String(lookup));
+ assert.deepStrictEqual(reads.map((r) => r.entity), ['connectionreference', 'customapi'], 'no definition to read it by');
+ assert.deepStrictEqual(warnings.filter((m) => /contoso_widgets/.test(m)), ['the operations that connector binding "contoso_widgets" of page "Weather" call were not checked: this environment does not name a custom connector for its connection reference, and only a custom connector\'s definition is read here (a connector the platform publishes defines the same operations in every environment of its cloud)'], String(lookup));
+ assert.strictEqual(genpage.of('create').length, 2, 'the pages are written: missing evidence refuses nothing');
+ }
+ // The same build with a complete row says what the definition lacks.
+ const complete = targetEnvironment({ references: [{ connectionreferencelogicalname: 'contoso_widgets', connectorid: WIDGETS_BINDING.connectorId, connectionid: 'shared-contoso-5fwidgets-0001', _customconnectorid_value: WIDGETS_CONNECTOR_ID }], apis: BOTH_APIS, connectors: [{ connectorid: WIDGETS_CONNECTOR_ID, openapidefinition: widgetsDefinition(['ListWidgets']) }] });
+ const warnings = [];
+ await runSdkBuild(spec, { sdk: complete.sdk, genpage: fakeGenpage(), appDir: outDir, env: FABRIKAM, apply: true, phases: PHASES, warn: (m) => warnings.push(m) });
+ assert.ok(warnings.some((m) => /calls operation GetWidget, which the custom connector that connection reference is for in this environment does not define/.test(m)));
+});
+
+// Malformed target metadata never stops a rebuild: a `connectorid` that is not a connector's API id, and a `connectionid` that is not a text, are said as not checked. Only two VALID connector ids that differ
+// are a conflict.
+test('a build whose target row holds a malformed connectorid or connectionid goes on and says it was not checked — it never halts on a value it cannot read', async () => {
+ const { spec, outDir } = await portableCopy();
+ const malformed = [{ ...referenceRow('contoso_msnweather', 'shared_msnweather'), connectorid: '***' }, { ...BOTH_REFERENCES[1], connectionid: 42 }];
+ const { sdk, writes } = targetEnvironment({ references: malformed, apis: BOTH_APIS });
+ const genpage = fakeGenpage();
+ const warnings = [];
+ const rebuilt = await runSdkBuild(spec, { sdk, genpage, appDir: outDir, env: FABRIKAM, apply: true, phases: PHASES, warn: (m) => warnings.push(m) });
+ assert.ok(rebuilt.ok, 'no pages-binding-reference-conflict for a connector id it cannot read');
+ assert.ok(writes.length > 0);
+ assert.strictEqual(genpage.of('create').length, 2, 'the pages are written');
+ assert.ok(warnings.some((m) => /connection reference contoso_msnweather did not give a connector id this build can read/.test(m)), JSON.stringify(bindingWords(warnings)));
+ assert.ok(warnings.some((m) => /connection reference contoso_sharepoint did not say, in a form this build can read, whether it has a connection/.test(m)), JSON.stringify(bindingWords(warnings)));
+ assert.ok(!warnings.some((m) => /has no connection/.test(m)), 'a connectionid that is not a text is not "no connection"');
+});
+
+test('a binding whose reference names no custom connector — a connector the platform publishes — has its operations said to be not checked, once per page', async () => {
+ const { spec, outDir } = await portableCopy();
+ const { sdk } = targetEnvironment({ references: BOTH_REFERENCES, apis: BOTH_APIS });
+ const warnings = [];
+ await runSdkBuild(spec, { sdk, genpage: fakeGenpage(), appDir: outDir, env: FABRIKAM, apply: true, phases: PHASES, warn: (m) => warnings.push(m) });
+ assert.strictEqual(warnings.filter((m) => OPERATIONS_NOT_CHECKED.test(m)).length, 1);
+});
+
+test('a read of the environment that fails is said, and the build goes on as it did: the page is written, and not checked', async () => {
+ const { spec, outDir } = await portableCopy();
+ const { sdk } = targetEnvironment({ failReferences: 'HTTP 403', apis: BOTH_APIS });
+ const warnings = [];
+ const rebuilt = await runSdkBuild(spec, { sdk, genpage: fakeGenpage(), appDir: outDir, env: FABRIKAM, apply: true, phases: PHASES, warn: (m) => warnings.push(m) });
+ assert.ok(rebuilt.ok);
+ assert.deepStrictEqual(bindingWords(warnings), ['could not read this environment\'s connection references (HTTP 403), so the connector bindings of page "Weather" were not checked against them']);
+});
+
+// Exercise the real client's refusal bookkeeping at the SDK read boundary: a best-effort binding read catches its HTTP error, but the attempt must still stop before its first mutation.
+async function failedBindingPreflight(entity, statusCode, earlierRefusal) {
+ const { spec, outDir } = await portableCopy();
+ const references = entity === 'connector'
+ ? [{ connectionreferencelogicalname: WIDGETS_BINDING.logicalName, connectorid: WIDGETS_BINDING.connectorId, connectionid: 'shared-widgets-0001', _customconnectorid_value: WIDGETS_CONNECTOR_ID }]
+ : BOTH_REFERENCES;
+ if (entity === 'connector') spec.pages.find((p) => p.key === 'weather').connectorBindings = [WIDGETS_BINDING];
+ const { sdk, writes } = targetEnvironment({ references, apis: BOTH_APIS });
+ const throttle = makeThrottleBudget();
+ if (earlierRefusal) throttle.decline({ askedMs: 600000, waitMs: 600000 });
+ const requests = [];
+ const http = createAzHttpClient(FABRIKAM, {
+ getToken: () => 'SYNTHETIC_BINDING_PREFLIGHT_TOKEN',
+ throttle,
+ now: () => 0,
+ random: () => 0,
+ sleep: async () => { assert.fail('a refused wait or a permanent metadata failure must not sleep'); },
+ request: async (request) => {
+ requests.push({ method: request.method, url: request.url });
+ return { statusCode, headers: statusCode === 429 ? { 'retry-after': '600' } : {}, body: JSON.stringify({ error: { message: 'Metadata unavailable' } }) };
+ },
+ });
+ const query = sdk.queryRecords;
+ sdk.queryRecords = async (logical, options) => {
+ if (logical !== entity) return query(logical, options);
+ const response = await http.get(`${FABRIKAM}/api/data/v9.2/${logical}`);
+ throw Object.assign(new Error(`HTTP ${response.status}`), { statusCode: response.status });
+ };
+ const genpage = fakeGenpage();
+ const warnings = [];
+ const events = [];
+ return {
+ spec, throttle, writes, genpage, requests, warnings, events,
+ opts: { sdk, genpage, appDir: outDir, env: FABRIKAM, apply: true, phases: PHASES, throttle, warn: (m) => warnings.push(m), emit: (event) => events.push(event) },
+ };
+}
+
+for (const entity of ['connectionreference', 'customapi', 'connector']) {
+ test(`a refused preflight wait from ${entity} halts before any SDK or page mutation`, async () => {
+ for (const earlierRefusal of [false, true]) {
+ const f = await failedBindingPreflight(entity, 429, earlierRefusal);
+ const halt = await runSdkBuild(f.spec, f.opts).then(() => null, (error) => error);
+ assert.deepStrictEqual(f.requests, [{ method: 'GET', url: `${FABRIKAM}/api/data/v9.2/${entity}` }], 'the throttled request was sent once and never resent');
+ assert.deepStrictEqual(f.throttle.declined(), { count: Number(earlierRefusal) + 1, askedMs: 600000, waitMs: 600000 });
+ assert.strictEqual(halt && halt.code, 'throttle-budget-exhausted', 'a refused preflight wait must stop before any mutation');
+ assert.ok(halt instanceof BuildHalt);
+ assert.strictEqual(halt.phase, 'preflight');
+ assert.strictEqual(halt.statusCode, 429);
+ assert.match(halt.message, /the service asked to wait 600 s/);
+ assert.deepStrictEqual(f.writes, [], 'no SDK mutation, including solution or manifest writes');
+ assert.deepStrictEqual(f.genpage.calls, [], 'no page read, create, update, placement, removal or delete');
+ assert.deepStrictEqual(f.events, [], 'no mutation step started');
+ }
+ });
+
+ test(`an unchecked ${entity} read still permits mutation when no new throttle wait is refused`, async () => {
+ for (const earlierRefusal of [false, true]) {
+ const f = await failedBindingPreflight(entity, 403, earlierRefusal);
+ assert.ok((await runSdkBuild(f.spec, f.opts)).ok);
+ assert.deepStrictEqual(f.requests, [{ method: 'GET', url: `${FABRIKAM}/api/data/v9.2/${entity}` }], 'a permanent metadata failure was not resent');
+ assert.strictEqual(f.throttle.declined().count, Number(earlierRefusal), 'no refusal belongs to this attempt');
+ assert.ok(f.warnings.some((m) => /HTTP 403/.test(m) && /not checked/.test(m)), 'unavailable metadata is still reported as unchecked');
+ assert.ok(f.writes.length > 0, 'the build continues past an ordinary unchecked read');
+ assert.strictEqual(f.genpage.of('create').length, 2, 'the pages are still created, even after an earlier attempt refused a wait');
+ }
+ });
+}
+
+test('a spec that states no binding makes no read of references or Custom APIs, and a rebuild of it is as it was', async () => {
+ const { spec, outDir } = await portableCopy();
+ for (const page of spec.pages) { delete page.connectorBindings; delete page.actionBindings; }
+ const { sdk, reads } = targetEnvironment({ references: [referenceRow('contoso_msnweather', 'shared_office365users')] });
+ const warnings = [];
+ const rebuilt = await runSdkBuild(spec, { sdk, genpage: fakeGenpage(), appDir: outDir, env: FABRIKAM, apply: true, phases: PHASES, warn: (m) => warnings.push(m) });
+ assert.ok(rebuilt.ok);
+ assert.deepStrictEqual(reads, []);
+ assert.deepStrictEqual(bindingWords(warnings), []);
+});
+
+test('a run without the pages phase does not read them either: the bindings are not written, so there is nothing to check', async () => {
+ const { spec, outDir } = await portableCopy();
+ const { sdk, reads } = targetEnvironment({ references: [referenceRow('contoso_msnweather', 'shared_office365users')] });
+ const rebuilt = await runSdkBuild(spec, { sdk, genpage: fakeGenpage(), appDir: outDir, env: FABRIKAM, apply: true, phases: ['solution', 'data-model', 'app-shell'] });
+ assert.ok(rebuilt.ok);
+ assert.deepStrictEqual(reads, []);
+});
+
+test('a dry run says what an apply would stop at — on the page\'s own line — and reads nothing when it is asked not to read the environment', async () => {
+ const { spec, outDir } = await portableCopy();
+ const conflicting = [referenceRow('contoso_msnweather', 'shared_office365users'), BOTH_REFERENCES[1]];
+ const warnings = [];
+ const { sdk, reads, writes } = targetEnvironment({ references: conflicting, apis: BOTH_APIS });
+ const planned = await runSdkBuild(spec, { sdk, genpage: fakeGenpage(), appDir: outDir, env: FABRIKAM, apply: false, phases: PHASES, warn: (m) => warnings.push(m) });
+ assert.strictEqual(planned.dryRun, true);
+ assert.deepStrictEqual(writes, [], 'a dry run writes nothing');
+ assert.ok(reads.length > 0, 'it read the environment for the names the pages state');
+ const weather = planned.planItems.find((item) => item.label === 'page "Weather"');
+ assert.deepStrictEqual([weather.state, weather.wouldHalt], ['unknown', true]);
+ assert.strictEqual(weather.stateWhy, 'the build would stop before writing anything: page "Weather": connector binding "contoso_msnweather" is for connector shared_msnweather, but the connection reference of that name in this environment is for connector shared_office365users');
+ assert.deepStrictEqual(planned.planItems.filter((item) => item.wouldHalt).map((item) => item.label), ['page "Weather"'], 'no other line is marked');
+
+ // A reference that is not there is a warning in the plan, as it is in the build, and halts nothing.
+ const missing = targetEnvironment({ references: [BOTH_REFERENCES[1]], apis: BOTH_APIS });
+ const missingWarnings = [];
+ const missingPlan = await runSdkBuild(spec, { sdk: missing.sdk, genpage: fakeGenpage(), appDir: outDir, env: FABRIKAM, apply: false, phases: PHASES, warn: (m) => missingWarnings.push(m) });
+ assert.deepStrictEqual(missingPlan.planItems.filter((item) => item.wouldHalt), []);
+ assert.match(bindingWords(missingWarnings)[0], /^page "Weather": connection reference contoso_msnweather is not in this environment/);
+
+ // `livePlan: false` is a plan that does not read the environment: it reads no reference either.
+ const offline = targetEnvironment({ references: conflicting });
+ const offlinePlan = await runSdkBuild(spec, { sdk: offline.sdk, genpage: fakeGenpage(), appDir: outDir, env: FABRIKAM, apply: false, livePlan: false, phases: PHASES });
+ assert.deepStrictEqual(offline.reads, []);
+ assert.deepStrictEqual(offlinePlan.planItems.filter((item) => item.wouldHalt), []);
+});
+
+test('a dry run whose read of the references fails says so, and halts nothing', async () => {
+ const { spec, outDir } = await portableCopy();
+ const { sdk } = targetEnvironment({ failReferences: 'HTTP 403', apis: BOTH_APIS });
+ const warnings = [];
+ const planned = await runSdkBuild(spec, { sdk, genpage: fakeGenpage(), appDir: outDir, env: FABRIKAM, apply: false, phases: PHASES, warn: (m) => warnings.push(m) });
+ assert.deepStrictEqual(planned.planItems.filter((item) => item.wouldHalt), []);
+ assert.strictEqual(bindingWords(warnings).length, 1);
+ assert.match(bindingWords(warnings)[0], /^could not read this environment's connection references \(HTTP 403\)/);
+});
diff --git a/plugins/model-apps/scripts/tests/page-ownership-records.test.js b/plugins/model-apps/scripts/tests/page-ownership-records.test.js
index c47edc6d5..490863b79 100644
--- a/plugins/model-apps/scripts/tests/page-ownership-records.test.js
+++ b/plugins/model-apps/scripts/tests/page-ownership-records.test.js
@@ -17,20 +17,28 @@ function workspace(t) {
}
const lib = () => require('../lib/page-ownership-records.js');
-// The workspace-reset advice every halt that asks for one gives (`RESET_WORKSPACE`) says to keep the `page-ownership.*.json` records: they are the only trace of a page this app created, of a delete under
-// way, and of a create that was started and never answered (a page that may still land) — and deleting them is the way to the second page for one spec entry that the pending record prevents.
-// The glob it names has to cover every kind of record the module writes.
-test('the workspace-reset advice keeps every kind of ownership record: the three kinds the module writes all carry the name the advice protects', (t) => {
+// The reset remedy must preserve every non-reconstructible store, not only SDK cache. Page receipts
+// retain pending creates and deletion progress; resource receipts retain the id needed to rewrite an
+// unconfirmed publication; dashboard creation records retain the id of a dashboard an interrupted build
+// created before it joined the solution. Its named globs must cover the actual files these modules write.
+test('the workspace-reset advice keeps the baseline, approval and every page, resource and dashboard recovery store', (t) => {
const { RESET_WORKSPACE } = require('../lib/entity-provision.js');
const dir = workspace(t);
lib().recordPageCreation(dir, APP, 'overview', ID, 'Overview', ENV_A);
lib().recordPagePending(dir, APP, 'detail', OTHER, 'Detail', ENV_A, 'a'.repeat(64));
lib().recordPageTeardown(dir, APP, [{ id: ID, key: 'overview', name: 'Overview' }], ENV_A);
+ const { openUnconfirmedWebResources, unconfirmedRecordPath } = require('../lib/web-resource-records.js');
+ assert.equal(openUnconfirmedWebResources({ workspaceDir: dir, environment: ENV_A }).note('contoso_/reset.js', ID), true);
+ const { openDashboardCreations, dashboardCreationRecordPath } = require('../lib/dashboard-creation-records.js');
+ assert.equal(openDashboardCreations({ workspaceDir: dir, environment: ENV_A, appUniqueName: APP, solutionUniqueName: 'ContosoPages' }).note('Overview', OTHER), true);
const written = fs.readdirSync(dir);
- assert.equal(written.length, 3);
- assert.deepEqual(written.map((name) => name.split('.')[1]).sort(), ['created', 'pending', 'teardown']);
- assert.ok(written.every((name) => /^page-ownership\..+\.json$/.test(name)), 'every record is page-ownership.<kind>.<hash>.json');
- assert.match(RESET_WORKSPACE, /except last-applied\.json, destructive-approval\.json and the page-ownership\.\*\.json records/);
+ assert.equal(written.length, 5);
+ const pageRecords = written.filter((name) => name.startsWith('page-ownership.'));
+ assert.deepEqual(pageRecords.map((name) => name.split('.')[1]).sort(), ['created', 'pending', 'teardown']);
+ assert.ok(pageRecords.every((name) => /^page-ownership\..+\.json$/.test(name)), 'every page record is page-ownership.<kind>.<hash>.json');
+ assert.match(path.basename(unconfirmedRecordPath(dir, ENV_A)), /^web-resource-unconfirmed\.[a-f0-9]{64}\.json$/);
+ assert.match(path.basename(dashboardCreationRecordPath(dir, ENV_A, APP, 'ContosoPages')), /^dashboard-creation\.[a-f0-9]{64}\.json$/);
+ assert.match(RESET_WORKSPACE, /except last-applied\.json, destructive-approval\.json, web-resource-unconfirmed\.\*\.json \(the durable ids needed to recover unconfirmed web-resource writes\), dashboard-creation\.\*\.json \(the ids of the dashboards an interrupted build created before they joined the solution\) and the page-ownership\.\*\.json records/);
assert.match(RESET_WORKSPACE, /pending records/);
});
diff --git a/plugins/model-apps/scripts/tests/preview-form.test.js b/plugins/model-apps/scripts/tests/preview-form.test.js
index 6f4c1a23c..7fc1c4bba 100644
--- a/plugins/model-apps/scripts/tests/preview-form.test.js
+++ b/plugins/model-apps/scripts/tests/preview-form.test.js
@@ -96,3 +96,31 @@ test('invalid App Spec prints validation errors instead of throwing from the ren
assert.match(res.stderr, /form references unknown entity 'new_missing'/);
assert.doesNotMatch(res.stderr, /TypeError/);
});
+
+// A key a form's `fieldOptions` entry does not take is refused by the build and the lint, but a release before that check
+// accepted it and built the form without the option. The preview reads the spec under the structural profile, as teardown
+// does, where that finding is a warning: the form still renders, without the misspelled option.
+function specWithFieldOptions(entry) {
+ const spec = validSpec();
+ spec.forms[0] = { entity: 'new_account', name: 'Account Main', fieldOptions: { new_status: entry } };
+ return spec;
+}
+
+test('a form whose fieldOptions entry carries a key it does not take still renders, without that option', () => {
+ const res = run(['--spec', '@' + writeSpec(specWithFieldOptions({ readOnlyy: true })), '--entity', 'new_account']);
+
+ assert.equal(res.status, 0, res.stderr);
+ assert.match(res.stdout, /Account Main/);
+ assert.match(res.stdout, /Status/);
+ assert.doesNotMatch(res.stdout, /read-only/, 'the misspelled option is not applied');
+});
+
+test('such a form is still refused for any other problem of its fieldOptions, and the unknown key is no part of the refusal', () => {
+ const res = run(['--spec', '@' + writeSpec(specWithFieldOptions({ readOnlyy: true, readOnly: false }))]);
+
+ assert.equal(res.status, 1);
+ assert.equal(res.stdout, '');
+ assert.match(res.stderr, /Invalid App Spec:/);
+ assert.match(res.stderr, /fieldOptions\['new_status'\] sets readOnly: false/);
+ assert.doesNotMatch(res.stderr, /unknown key/);
+});
diff --git a/plugins/model-apps/scripts/tests/record-writers-lease.test.js b/plugins/model-apps/scripts/tests/record-writers-lease.test.js
new file mode 100644
index 000000000..3e1ce210e
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/record-writers-lease.test.js
@@ -0,0 +1,374 @@
+'use strict';
+// Two builds that share a workspace and an environment write the same recovery record: the web resources a build wrote and could not confirm
+// were published (lib/web-resource-records.js), and the dashboards a build created and has not yet seen join the app's solution
+// (lib/dashboard-creation-records.js). Each record is ONE file that holds every entry, replaced whole on each change. A run read it once and then
+// wrote its own copy: with both runs reading before either wrote, A noting `a` and then B noting `b` answered true twice and left only `b` on disk,
+// and A clearing `a` afterwards deleted the file — `b` with it, the id the next build needed to repair an unconfirmed publication, or to find a
+// dashboard outside its solution. Replacing the file atomically does not prevent that: each write is whole, and the later one still wins. Each
+// change is now made under the record's writer lease (lib/record-lease.js) to the record as it is on disk at that moment.
+//
+// Held here, for each record:
+// 1. the interleavings: both runs read, A notes, B notes, A clears, B clears — every entry stays until its own run clears it, and the file goes
+// with the last one
+// 2. a change touches only what its run knows: an entry of the same name that another run recorded since, under another id, is neither replaced
+// nor removed, and a reported id is added only to the entry its run noted; a file that has become unreadable since a run read it is treated as
+// an unreadable one always was (the dashboard record is not written over, the web-resource record is replaced by a note); a clear in a workspace
+// that has gone makes nothing
+// 3. the lease: one that another live run holds is waited for a bounded time, and then the change is not made — said once, the file left as it
+// was, never a hang; one left by a run that is gone is taken over; reads never wait for it
+// 4. an entry is compared whole: a web-resource entry by its id AND the revision of the note that made it, a dashboard entry by both its ids — so a
+// newer entry of the same row, or a reported id recorded since, is never taken on the word of an older one
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const { performance } = require('node:perf_hooks');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { acquireLease, releaseLease } = require('../lib/apply-snapshot-store.js');
+const { ownerStamp, ownerState } = require('../lib/process-owner.js');
+const webResources = require('../lib/web-resource-records.js');
+const dashboards = require('../lib/dashboard-creation-records.js');
+
+// Loaded where it is used, so that a test fails on its own assertion when the module is not there.
+const recordLease = () => require('../lib/record-lease.js');
+
+const ENV = 'https://contoso.crm.dynamics.com';
+const APP = 'contoso_app';
+const SOLUTION = 'ContosoSolution';
+const ID_A = '11111111-aaaa-4aaa-8aaa-111111111111';
+const ID_B = '22222222-bbbb-4bbb-8bbb-222222222222';
+const ID_C = '33333333-cccc-4ccc-8ccc-333333333333';
+// The bound lib/record-lease.js promises: a held lease is tried this many times, this many milliseconds apart, and then given up.
+const LEASE_ATTEMPTS = 10;
+const LEASE_WAIT_MS = 100;
+
+// The two records, behind one shape: `open(dir, extra)` is a run's view of it, `ids(view, name)` what that view answers for a name, `onDisk(dir)` the
+// names and ids the file holds now (read afresh, as the next build reads it: an id, or [id, reported id]), and `file(dir)` the record's path.
+const RECORDS = [
+ {
+ kind: 'the web-resource record',
+ names: ['contoso_/a.js', 'contoso_/b.js'],
+ open: (dir, extra = {}) => webResources.openUnconfirmedWebResources({ workspaceDir: dir, environment: ENV, ...extra }),
+ ids: (view, name) => { const id = view.idOf(name); return id ? [id] : undefined; },
+ onDisk: (dir) => Object.fromEntries([...webResources.readUnconfirmedWebResources(dir, ENV).values()].map((e) => [e.name, e.id])),
+ file: (dir) => webResources.unconfirmedRecordPath(dir, ENV),
+ },
+ {
+ kind: 'the dashboard record',
+ names: ['Ops Overview', 'Sales'],
+ open: (dir, extra = {}) => dashboards.openDashboardCreations({ workspaceDir: dir, environment: ENV, appUniqueName: APP, solutionUniqueName: SOLUTION, ...extra }),
+ ids: (view, name) => view.idsOf(name),
+ onDisk: (dir) => Object.fromEntries([...dashboards.readDashboardCreations(dir, ENV, APP, SOLUTION).values()].map((e) => [e.name, e.reportedId ? [e.id, e.reportedId] : e.id])),
+ file: (dir) => dashboards.dashboardCreationRecordPath(dir, ENV, APP, SOLUTION),
+ },
+];
+
+// The lock a run takes to change a record, held here as another live build would hold it: by this process, stamped as a build stamps it.
+function holdLease(dir, recordPath) {
+ const lease = acquireLease(dir, { file: `${path.basename(recordPath)}.lock`, stamp: ownerStamp(), isStale: (held) => ownerState(held).state === 'gone' });
+ assert.equal(lease.ok, true, JSON.stringify(lease));
+ return lease;
+}
+
+// --- 1. the interleavings ------------------------------------------------------------------------------------------------------------------------------
+
+for (const r of RECORDS) {
+ const [a, b] = r.names;
+ test(`${r.kind}: two builds that share the workspace both read it, then A notes '${a}' and B notes '${b}' — both are on disk; A clears its own — '${b}' stays; B clears its own — the file goes with the last entry`, () => {
+ const dir = makeTempDir('record-lease-');
+ const A = r.open(dir);
+ const B = r.open(dir);
+ assert.equal(r.ids(A, a), undefined, 'A read the record: nothing is in it');
+ assert.equal(r.ids(B, b), undefined, 'and so did B, before either wrote');
+ assert.equal(A.note(a, ID_A), true);
+ assert.equal(B.note(b, ID_B), true);
+ assert.deepEqual(r.onDisk(dir), { [a]: ID_A, [b]: ID_B }, 'both entries are on disk: B wrote its own beside A\'s');
+ A.clear(a);
+ assert.deepEqual(r.onDisk(dir), { [b]: ID_B }, 'A\'s clear took its own entry and no other');
+ assert.deepEqual(r.ids(r.open(dir), b), [ID_B], 'the next build still finds B\'s');
+ B.clear(b);
+ assert.equal(fs.existsSync(r.file(dir)), false, 'the clear of the last entry removes the file');
+ assert.deepEqual(fs.readdirSync(dir), [], 'and nothing is left behind: no lock either');
+ });
+}
+
+test('the dashboard record: A notes, B notes, then A records the id its push reported — beside its own entry, and B\'s stays as B wrote it', () => {
+ const r = RECORDS[1];
+ const [a, b] = r.names;
+ const dir = makeTempDir('record-lease-');
+ const A = r.open(dir);
+ const B = r.open(dir);
+ assert.equal(r.ids(A, a), undefined);
+ assert.equal(r.ids(B, b), undefined);
+ assert.equal(A.note(a, ID_A), true);
+ assert.equal(B.note(b, ID_B), true);
+ assert.equal(A.observe(a, ID_C), true);
+ assert.deepEqual(r.onDisk(dir), { [a]: [ID_A, ID_C], [b]: ID_B });
+ assert.deepEqual(r.ids(A, a), [ID_A, ID_C], 'A\'s own view has it too');
+});
+
+// --- 2. a change touches only what its run knows ---------------------------------------------------------------------------------------------------------
+
+for (const r of RECORDS) {
+ const [a] = r.names;
+ test(`${r.kind}: a clear removes only the entry its build knows — one of the same name that another build recorded since, under another id, stays`, () => {
+ const dir = makeTempDir('record-lease-');
+ const A = r.open(dir);
+ assert.equal(A.note(a, ID_A), true);
+ // Another build reads the record after A wrote — so it knows A's entry — and records a later write of the same name under another id.
+ const B = r.open(dir);
+ assert.deepEqual(r.ids(B, a), [ID_A]);
+ assert.equal(B.note(a, ID_B), true, 'B knew the entry it replaces');
+ A.clear(a);
+ assert.deepEqual(r.onDisk(dir), { [a]: ID_B }, 'A\'s clear did not take B\'s entry');
+ });
+
+ test(`${r.kind}: a note does not replace an entry of the same name that another build recorded after this build read the record — it answers false, says so once, and the other build's entry stays`, () => {
+ const dir = makeTempDir('record-lease-');
+ const warnings = [];
+ const A = r.open(dir, { warn: (w) => warnings.push(w) });
+ assert.equal(r.ids(A, a), undefined, 'A read the record: nothing is in it');
+ assert.equal(r.open(dir).note(a, ID_B), true, 'another build records the name since');
+ assert.equal(A.note(a, ID_A), false, 'A does not write over it');
+ assert.equal(A.note(a, ID_C), false, 'nor with another id');
+ assert.deepEqual(r.onDisk(dir), { [a]: ID_B }, 'the other build\'s entry stays');
+ assert.equal(warnings.length, 1, `said once: ${JSON.stringify(warnings)}`);
+ assert.match(warnings[0], new RegExp(`already holds '${a.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')}' as ${ID_B}, which another build recorded since this one read it`));
+ assert.equal(A.note(a, ID_B), true, 'the id that is recorded already is no conflict');
+ });
+}
+
+test('the dashboard record: A records the id its push reported only to the entry it noted — one another build has replaced since is left as it is, said once', () => {
+ const r = RECORDS[1];
+ const [a] = r.names;
+ const dir = makeTempDir('record-lease-');
+ const warnings = [];
+ const A = r.open(dir, { warn: (w) => warnings.push(w) });
+ assert.equal(A.note(a, ID_A), true);
+ // Another build reads the record after A wrote — so it knows A's entry — and records a create of its own under the same name.
+ const B = r.open(dir);
+ assert.deepEqual(r.ids(B, a), [ID_A]);
+ assert.equal(B.note(a, ID_B), true);
+ assert.equal(A.observe(a, ID_C), false, 'A does not add to B\'s entry');
+ assert.deepEqual(r.onDisk(dir), { [a]: ID_B }, 'B\'s entry stays as B wrote it');
+ assert.equal(warnings.length, 1, `said once: ${JSON.stringify(warnings)}`);
+ assert.match(warnings[0], new RegExp(`no longer holds '${a}' as ${ID_A}`));
+ assert.deepEqual(r.ids(A, a), [ID_A], 'and A\'s view does not claim the reported id is recorded');
+});
+
+test('the dashboard record: a file that has become unreadable since this build read it is not written over — the note answers false, said once, and the file stays as it is', () => {
+ const r = RECORDS[1];
+ const [a, b] = r.names;
+ const dir = makeTempDir('record-lease-');
+ assert.equal(r.open(dir).note(a, ID_A), true);
+ const warnings = [];
+ const A = r.open(dir, { warn: (w) => warnings.push(w) });
+ assert.deepEqual(r.ids(A, a), [ID_A], 'A read it');
+ // Then it is damaged — by hand, or by a build that writes an entry this one does not.
+ const damaged = Buffer.from('{ not json');
+ fs.writeFileSync(r.file(dir), damaged);
+ assert.equal(A.note(b, ID_B), false);
+ A.clear(a);
+ assert.deepEqual(fs.readFileSync(r.file(dir)), damaged, 'not written over, not removed');
+ assert.equal(warnings.length, 1, JSON.stringify(warnings));
+ assert.match(warnings[0], /could not be read .*records none of its own/);
+ assert.deepEqual(fs.readdirSync(dir), [path.basename(r.file(dir))], 'and no lock is left');
+});
+
+test('the web-resource record: a file that has become unreadable since this build read it is replaced by the note, as an unreadable one always was — said once', () => {
+ const r = RECORDS[0];
+ const [a, b] = r.names;
+ const dir = makeTempDir('record-lease-');
+ const warnings = [];
+ const A = r.open(dir, { warn: (w) => warnings.push(w) });
+ assert.equal(r.ids(A, a), undefined, 'A read it: nothing is in it');
+ fs.writeFileSync(r.file(dir), '{ not json');
+ assert.equal(A.note(b, ID_B), true);
+ assert.deepEqual(r.onDisk(dir), { [b]: ID_B }, 'the note replaced it');
+ assert.equal(warnings.length, 1, JSON.stringify(warnings));
+ assert.match(warnings[0], /could not be read .*so this build reuses every web resource that exists as it is/);
+});
+
+for (const r of RECORDS) {
+ test(`${r.kind}: a clear in a workspace that has gone since makes nothing — no folder, no lock`, () => {
+ const dir = makeTempDir('record-lease-');
+ const run = r.open(dir);
+ assert.equal(run.note(r.names[0], ID_A), true);
+ fs.rmSync(dir, { recursive: true, force: true });
+ run.clear(r.names[0]);
+ assert.equal(fs.existsSync(dir), false);
+ });
+}
+
+// --- 3. the lease -------------------------------------------------------------------------------------------------------------------------------------
+
+for (const r of RECORDS) {
+ const [a, b] = r.names;
+ test(`${r.kind}: a lease another live build holds is waited for a bounded time, and then the change is not made — said once, the file left as it was — while reads never wait for it`, () => {
+ const dir = makeTempDir('record-lease-');
+ assert.equal(r.open(dir).note(a, ID_A), true);
+ const before = fs.readFileSync(r.file(dir));
+ const held = holdLease(dir, r.file(dir));
+ const slept = [];
+ const warnings = [];
+ try {
+ const run = r.open(dir, { warn: (w) => warnings.push(w), lease: { sleep: (ms) => slept.push(ms) } });
+ assert.deepEqual(r.ids(run, a), [ID_A], 'a read answers while the lease is held');
+ assert.deepEqual(slept, [], 'without waiting for it');
+ assert.equal(run.note(b, ID_B), false, 'the change is not made');
+ assert.deepEqual(slept, Array(LEASE_ATTEMPTS - 1).fill(LEASE_WAIT_MS), 'after a bounded wait');
+ run.clear(a);
+ assert.deepEqual(fs.readFileSync(r.file(dir)), before, 'the file is left as it was');
+ assert.deepEqual(r.ids(run, a), [ID_A], 'and the run\'s own view still holds its entry');
+ assert.equal(warnings.length, 1, `said once: ${JSON.stringify(warnings)}`);
+ assert.match(warnings[0], /could not be written \(its lock .*\.lock is held by another build of this workspace \(lease held by pid \d+/);
+ assert.ok(warnings[0].includes(`${r.file(dir)}.lock`), 'the warning names the lock');
+ } finally {
+ releaseLease(held);
+ }
+ const free = r.open(dir);
+ assert.equal(free.note(b, ID_B), true, 'once it is free, a change goes through');
+ assert.deepEqual(r.onDisk(dir), { [a]: ID_A, [b]: ID_B });
+ });
+
+ test(`${r.kind}: a lease left behind by a build that is gone is taken over — the change is made at once, and no lock is left`, () => {
+ const dir = makeTempDir('record-lease-');
+ const lock = `${r.file(dir)}.lock`;
+ // The owner record of a build on this machine whose process is no longer running (the seams: pid 4242 runs nowhere here).
+ const owner = { hostname: () => 'build-box', platform: 'win32', probe: (pid) => (pid === 4242 ? 'gone' : 'alive') };
+ fs.writeFileSync(lock, JSON.stringify({ ...ownerStamp({ ...owner, pid: 4242 }), rnd: 'left-behind' }));
+ const run = r.open(dir, { lease: { owner, sleep: () => { throw new Error('a lease of a build that is gone is not waited for'); } } });
+ assert.equal(run.note(a, ID_A), true);
+ assert.deepEqual(r.onDisk(dir), { [a]: ID_A });
+ assert.equal(fs.existsSync(lock), false, 'no lock is left');
+ assert.deepEqual(fs.readdirSync(dir), [path.basename(r.file(dir))], 'only the record is');
+ });
+}
+
+test('a held lease never hangs a build: with the real pause, a change gives up after the bounded wait — about a second — and the record is as it was', () => {
+ const r = RECORDS[0];
+ const [a, b] = r.names;
+ const dir = makeTempDir('record-lease-');
+ assert.equal(r.open(dir).note(a, ID_A), true);
+ const held = holdLease(dir, r.file(dir));
+ let ms;
+ try {
+ const run = r.open(dir);
+ const started = performance.now();
+ assert.equal(run.note(b, ID_B), false);
+ ms = performance.now() - started;
+ } finally {
+ releaseLease(held);
+ }
+ const bound = (LEASE_ATTEMPTS - 1) * LEASE_WAIT_MS;
+ assert.ok(ms >= bound * 0.8, `it waited (${Math.round(ms)} ms, the bound is ${bound} ms)`);
+ assert.ok(ms < bound + 5000, `and then gave up (${Math.round(ms)} ms)`);
+ assert.deepEqual(r.onDisk(dir), { [a]: ID_A });
+ assert.deepEqual({ attempts: recordLease().LEASE_ATTEMPTS, waitMs: recordLease().LEASE_WAIT_MS }, { attempts: LEASE_ATTEMPTS, waitMs: LEASE_WAIT_MS }, 'the module waits as long as it says');
+});
+
+// --- 4. an entry is compared whole ---------------------------------------------------------------------------------------------------------------------
+//
+// An id alone does not say which build's entry it is. A web resource's id is the row's own, so a build that writes the same row again and cannot confirm
+// that write records the SAME id; a dashboard's entry gains the id the service reported after it was noted. A change that matched the id alone took
+// another build's newer entry — a write nothing has confirmed, or the row a re-keyed create made — on the word of an older one.
+
+test('the web-resource record: a clear by a build that verified an EARLIER write of the row leaves the entry another build noted since for the same row — a later write nothing has confirmed', () => {
+ const r = RECORDS[0];
+ const [a] = r.names;
+ const dir = makeTempDir('record-lease-');
+ assert.equal(r.open(dir).note(a, ID_A), true, 'an earlier build could not confirm its write of the row');
+ const A = r.open(dir);
+ const B = r.open(dir);
+ assert.deepEqual(r.ids(A, a), [ID_A], 'A reads it, writes the row again by that id, and verifies the write');
+ assert.deepEqual(r.ids(B, a), [ID_A], 'B reads it too');
+ assert.equal(B.note(a, ID_A), true, 'B writes the same row again after that, and cannot confirm its write');
+ A.clear(a);
+ assert.deepEqual(r.onDisk(dir), { [a]: ID_A }, 'A\'s clear did not take B\'s later entry: the next build writes the row again');
+ B.clear(a);
+ assert.equal(fs.existsSync(r.file(dir)), false, 'B\'s own clear, once its write is verified, does');
+});
+
+test('the web-resource record: the name-to-id map keeps its shape, a revision beside it; an entry written without one is matched by its id, as before, and stays without one', () => {
+ const r = RECORDS[0];
+ const [a, b] = r.names;
+ const dir = makeTempDir('record-lease-');
+ assert.equal(r.open(dir).note(a, ID_A), true);
+ const written = JSON.parse(fs.readFileSync(r.file(dir), 'utf8'));
+ assert.deepEqual(written.webResources, { [a]: ID_A }, 'name to id, as before');
+ assert.deepEqual(Object.keys(written.revisions), [a]);
+ assert.match(written.revisions[a], /^[0-9a-f]{16}$/, 'and the revision of that note beside it');
+ // The record as a build wrote it before there were revisions.
+ fs.writeFileSync(r.file(dir), `${JSON.stringify({ schemaVersion: 1, environmentFingerprint: written.environmentFingerprint, webResources: { [a]: ID_A, [b]: ID_B } })}\n`);
+ const run = r.open(dir);
+ assert.deepEqual(r.ids(run, a), [ID_A]);
+ run.clear(a);
+ assert.deepEqual(r.onDisk(dir), { [b]: ID_B }, 'an entry without a revision is cleared by its id');
+ assert.equal('revisions' in JSON.parse(fs.readFileSync(r.file(dir), 'utf8')), false, 'and the rest is written as it was: no revision is made up for it');
+ run.clear(b);
+ assert.equal(fs.existsSync(r.file(dir)), false);
+});
+
+test('the dashboard record: a clear by a build that read the entry before its creator recorded the id its push reported leaves the entry — both ids — and answers null', () => {
+ const r = RECORDS[1];
+ const [a] = r.names;
+ const dir = makeTempDir('record-lease-');
+ const A = r.open(dir);
+ assert.equal(A.note(a, ID_A), true, 'A notes the id it sends its create with');
+ const B = r.open(dir);
+ assert.deepEqual(r.ids(B, a), [ID_A], 'B reads the entry');
+ assert.equal(A.observe(a, ID_C), true, 'A\'s push reports another id: the row its create made');
+ assert.equal(B.clear(a), null, 'B\'s clear leaves it, and says the entry changed');
+ assert.deepEqual(r.onDisk(dir), { [a]: [ID_A, ID_C] }, 'both ids stay');
+ assert.equal(A.clear(a), true, 'A, which knows both, removes it');
+ assert.equal(fs.existsSync(r.file(dir)), false);
+});
+
+test('the dashboard record: a note by a build that read the entry before the reported id was recorded does not replace it — said once, and it answers false', () => {
+ const r = RECORDS[1];
+ const [a] = r.names;
+ const dir = makeTempDir('record-lease-');
+ const A = r.open(dir);
+ assert.equal(A.note(a, ID_A), true);
+ const warnings = [];
+ const B = r.open(dir, { warn: (w) => warnings.push(w) });
+ assert.deepEqual(r.ids(B, a), [ID_A]);
+ assert.equal(A.observe(a, ID_C), true);
+ assert.equal(B.note(a, ID_B), false, 'B does not replace it');
+ assert.deepEqual(r.onDisk(dir), { [a]: [ID_A, ID_C] }, 'both of A\'s ids stay');
+ assert.equal(warnings.length, 1, `said once: ${JSON.stringify(warnings)}`);
+ assert.match(warnings[0], new RegExp(`already holds '${a}' as ${ID_A} \\(the service reported ${ID_C}\\), which another build recorded since this one read it`));
+});
+
+test('the dashboard record: a note of the id the entry holds already keeps the id the service reported beside it — by the build that noted it, or another', () => {
+ const r = RECORDS[1];
+ const [a] = r.names;
+ const dir = makeTempDir('record-lease-');
+ const run = r.open(dir);
+ assert.equal(run.note(a, ID_A), true);
+ assert.equal(run.observe(a, ID_C), true);
+ assert.equal(run.note(a, ID_A), true);
+ assert.deepEqual(r.onDisk(dir), { [a]: [ID_A, ID_C] }, 'the reported id stays');
+ assert.deepEqual(r.ids(run, a), [ID_A, ID_C]);
+ assert.equal(r.open(dir).note(a, ID_A), true, 'another build that read the entry');
+ assert.deepEqual(r.onDisk(dir), { [a]: [ID_A, ID_C] });
+});
+
+test('the dashboard record: an observe adds a reported id only to the entry as its build noted it — never over another reported id recorded since — said once', () => {
+ const r = RECORDS[1];
+ const [a] = r.names;
+ const dir = makeTempDir('record-lease-');
+ assert.equal(r.open(dir).note(a, ID_A), true);
+ const warnings = [];
+ const A = r.open(dir);
+ const B = r.open(dir, { warn: (w) => warnings.push(w) });
+ assert.deepEqual(r.ids(A, a), [ID_A]);
+ assert.deepEqual(r.ids(B, a), [ID_A]);
+ assert.equal(A.observe(a, ID_C), true);
+ assert.equal(B.observe(a, ID_B), false, 'B does not write over the reported id A recorded');
+ assert.deepEqual(r.onDisk(dir), { [a]: [ID_A, ID_C] });
+ assert.equal(warnings.length, 1, `said once: ${JSON.stringify(warnings)}`);
+ assert.match(warnings[0], new RegExp(`no longer holds '${a}' as ${ID_A} — another build has changed it since`));
+ assert.equal(B.observe(a, ID_C), true, 'the reported id the record holds already is no conflict');
+ assert.deepEqual(r.onDisk(dir), { [a]: [ID_A, ID_C] });
+});
diff --git a/plugins/model-apps/scripts/tests/role-grants.test.js b/plugins/model-apps/scripts/tests/role-grants.test.js
index dd2c7dacf..411b3bba9 100644
--- a/plugins/model-apps/scripts/tests/role-grants.test.js
+++ b/plugins/model-apps/scripts/tests/role-grants.test.js
@@ -77,6 +77,31 @@ test('roleGrants: roleId must be a GUID', () => {
assert.ok(errs.some((e) => /roleId must be a GUID/.test(e)), JSON.stringify(errs));
});
+// Which role an entry names is decided by one function, which the design document asks too (lib/app-access.js roleGrantRefusals): the gate
+// reports exactly its words for each way an entry can fail to name one role, and nothing else about the entry's identity.
+test('roleGrants: the identity check is one shared function, and the gate reports exactly its words', () => {
+ const { roleGrantIdentityErrors, roleGrantEntryLabel } = require('../lib/app-spec.js');
+ const privileges = [{ entity: 'contoso_order', access: ['read'] }];
+ const cases = [
+ [{ role: 'Contoso PM - Project Manager', roleId: '11111111-1111-1111-1111-111111111111', privileges }, 1],
+ [{ privileges }, 1],
+ [{ role: ' ', privileges }, 1],
+ [{ roleId: 'Project Manager', privileges }, 1],
+ [{ role: 5, roleId: 'x', privileges }, 3],
+ [{ role: 'Contoso PM - Project Manager', privileges }, 0],
+ [{ roleId: '11111111-1111-1111-1111-111111111111', privileges }, 0],
+ ];
+ for (const [entry, count] of cases) {
+ const identity = roleGrantIdentityErrors(entry, roleGrantEntryLabel(entry, 0));
+ assert.strictEqual(identity.length, count, JSON.stringify({ entry, identity }));
+ const s = base();
+ s.roleGrants = [entry];
+ const gate = validateAppSpec(s, { profile: 'plan' }).errors;
+ for (const message of identity) assert.ok(gate.includes(message), JSON.stringify({ message, gate }));
+ assert.deepStrictEqual(gate.filter((e) => /not both|name the existing role to extend|role must be the non-empty display name|roleId must be a GUID/.test(e)), identity);
+ }
+});
+
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));
diff --git a/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js b/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js
index 8ae5bf56f..5bac7cd8b 100644
--- a/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-build-pages-deploy.test.js
@@ -2703,6 +2703,157 @@ test('deploy: a record that cannot be saved is ONE warning — the pages are sti
} finally { fs.rmSync(appDir, { recursive: true, force: true }); }
});
+// ── A page that holds bindings, rebuilt by the spec a download wrote ─────────────────────────────────────────────────────────────────────────
+// A page's connector and Custom API bindings are in the spec a download writes (pages[].connectorBindings, pages[].actionBindings), and the build sends them with the page's content. The record of a publish is the
+// hash of that content, and the record an earlier build made of a page it published was made when the build stated no lists: it is the hash of the content WITHOUT them. The page has not changed, and the first
+// rebuild after a download used to meet a hash it did not know and publish every such page again — one PublishXml of several seconds each. It must not: the page is neither written nor published, and its record is
+// renewed, so the build after it asks nothing more of the published copy. What stays as it was: a page the spec CHANGES is written and published, and so is one whose published copy does not hold the lists.
+const { contentFingerprint } = require('../lib/genpage-sdk.js');
+const HELD_WEATHER = { logicalName: 'contoso_msnweather', connectorId: '/providers/Microsoft.PowerApps/apis/shared_msnweather', dataset: '', operations: ['CurrentWeather'] };
+const HELD_APPROVE = { name: 'contoso_ApproveOrder', isFunction: false, boundEntityLogicalName: 'contoso_item', displayName: 'Approve order', parameterKinds: { Comment: 'String' } };
+const STATED_LISTS = { connectorBindings: [HELD_WEATHER], actionBindings: [HELD_APPROVE] };
+const CONNECTION_PLACEHOLDER = 'env-local-connection-placeholder';
+
+// The environment of an app whose pages the maker laid out: the first holds bindings (and, with `extras`, a connection id a spec does not state), the second none. Each page's file is what the spec points at, so the
+// pages hold what the spec asks for and a rebuild has nothing to write.
+function seededBindingApp({ extras = true } = {}) {
+ const { appDir, spec } = twoPageApp();
+ const server = new FakeGenPageServer();
+ const ids = { alpha: 'a1000000-0000-4000-8000-000000000001', beta: 'a2000000-0000-4000-8000-000000000002' };
+ for (const [key, id] of Object.entries(ids)) {
+ const page = spec.pages.find((p) => p.key === key);
+ const lists = key === 'alpha' ? { connectorBindings: [extras ? { ...HELD_WEATHER, connectionId: CONNECTION_PLACEHOLDER } : HELD_WEATHER], actionBindings: [HELD_APPROVE] } : {};
+ server.seedPage(id, { name: page.name, source: fs.readFileSync(path.join(appDir, `${key}.tsx`), 'utf8'), config: { dataSources: [], model: '', ...lists } });
+ }
+ return { appDir, spec, server, ids };
+}
+const quiet = (requests) => [requests.changeSets, requests.publishes, requests.otherWrites];
+
+test('deploy: a page that holds bindings, built by a spec that stated none and then by the spec a download wrote, is neither written nor published by the second build — the record of its publish stands, and is renewed', async () => {
+ for (const extras of [false, true]) {
+ const { appDir, spec, server, ids } = seededBindingApp({ extras });
+ try {
+ // Build 1, as every build was before a spec could state the lists: the pages hold what the spec asks for, so they are only published, and the publish is recorded — with no lists in its hash.
+ await rebuildPages(spec, appDir, server, ids);
+ assert.deepStrictEqual([...publishedOf(spec, appDir).keys()].sort(), Object.values(ids).sort());
+ const legacy = publishedOf(spec, appDir).get(ids.alpha).fingerprint;
+ const betaRecord = publishedOf(spec, appDir).get(ids.beta);
+
+ // The download states the bindings, without what a spec does not state.
+ Object.assign(spec.pages[0], STATED_LISTS);
+ const alphaSource = fs.readFileSync(path.join(appDir, 'alpha.tsx'), 'utf8');
+ const stated = contentFingerprint({ source: alphaSource, name: 'Alpha', dataSources: [], ...STATED_LISTS });
+ assert.notStrictEqual(stated, legacy, 'the lists are part of the hash');
+ const publishedBefore = server.published.length;
+ let from = server.requests.length;
+ await rebuildPages(spec, appDir, server, ids);
+ assert.deepStrictEqual(quiet(requestsOf(server, from)), [0, 0, 0], `extras ${extras}: neither a change set, nor a publish, nor any other write — only reads`);
+ assert.strictEqual(server.published.length, publishedBefore);
+ const renewed = publishedOf(spec, appDir).get(ids.alpha);
+ assert.strictEqual(renewed.fingerprint, stated, 'the record is now the hash of what the spec states');
+ assert.deepStrictEqual(renewed.files, versionsNow(server, ids.alpha), 'with the versions the page has: nothing moved it');
+ assert.deepStrictEqual(publishedOf(spec, appDir).get(ids.beta), betaRecord, 'a page that states none keeps its record as it was');
+ const held = JSON.parse(server.rowText(ids.alpha, 'config.json'));
+ assert.strictEqual(held.connectorBindings[0].connectionId, extras ? CONNECTION_PLACEHOLDER : undefined, 'the page keeps what the spec could not state');
+
+ // And the build after it asks nothing: the record is the hash as it is, and the published copy is not read again to see that it holds the lists.
+ from = server.requests.length;
+ await rebuildPages(spec, appDir, server, ids);
+ assert.deepStrictEqual(quiet(requestsOf(server, from)), [0, 0, 0]);
+ assert.strictEqual(server.requests.slice(from).filter((r) => r.method === 'GET' && /^\/uxagentproject/.test(r.path) && !('MSCRM.IncludeUnpublished' in r.headers) && !/versionnumber/.test(r.path)).length, 0, 'no read of the published copy: the versions the record is held to are the only plain reads');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+ }
+});
+
+test('deploy: the renewed record is no licence — a page a maker saved since is published again, and a page the spec changes is written and published whatever was recorded', async () => {
+ const { appDir, spec, server, ids } = seededBindingApp();
+ try {
+ await rebuildPages(spec, appDir, server, ids);
+ Object.assign(spec.pages[0], STATED_LISTS);
+ await rebuildPages(spec, appDir, server, ids);
+ const config = JSON.parse(server.rowText(ids.alpha, 'config.json'));
+
+ // A maker saves the page's settings as a draft, adding a setting and nothing else: the page's files moved, so the record no longer stands and the page is published once — with nothing to write.
+ server.otherWorkspaceDraft(ids.alpha, 'config.json', JSON.stringify({ ...config, futureSetting: { kept: true } }));
+ let from = server.requests.length;
+ await rebuildPages(spec, appDir, server, ids);
+ assert.deepStrictEqual(quiet(requestsOf(server, from)), [0, 1, 0], 'a publish, and no write');
+ from = server.requests.length;
+ await rebuildPages(spec, appDir, server, ids);
+ assert.deepStrictEqual(quiet(requestsOf(server, from)), [0, 0, 0], 'after which it is left alone again');
+
+ // The spec edits a binding: the page is written — one change set — and published, and keeps what the spec could not state of the entry it changes.
+ spec.pages[0].connectorBindings = [{ ...HELD_WEATHER, operations: ['Forecast'] }];
+ from = server.requests.length;
+ await rebuildPages(spec, appDir, server, ids);
+ assert.deepStrictEqual(quiet(requestsOf(server, from)), [1, 1, 0]);
+ const edited = JSON.parse(server.rowText(ids.alpha, 'config.json'));
+ assert.deepStrictEqual(edited.connectorBindings, [{ ...HELD_WEATHER, connectionId: CONNECTION_PLACEHOLDER, operations: ['Forecast'] }]);
+ assert.deepStrictEqual(edited.futureSetting, { kept: true });
+ // The write was published and recorded, with the lists in the hash: the next build leaves the page alone.
+ from = server.requests.length;
+ await rebuildPages(spec, appDir, server, ids);
+ assert.deepStrictEqual(quiet(requestsOf(server, from)), [0, 0, 0]);
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+test('deploy: a page whose record names ONE of its lists, built by a spec that states both, is neither written nor published — a list stated for the first time is no change to the page', async () => {
+ const { appDir, spec, server, ids } = seededBindingApp({ extras: false });
+ try {
+ // The first build states the page's connector bindings and not its Custom API bindings: the page is published, and the record is the hash of its content with that one list.
+ spec.pages[0].connectorBindings = STATED_LISTS.connectorBindings;
+ await rebuildPages(spec, appDir, server, ids);
+ const alphaSource = fs.readFileSync(path.join(appDir, 'alpha.tsx'), 'utf8');
+ assert.strictEqual(publishedOf(spec, appDir).get(ids.alpha).fingerprint, contentFingerprint({ source: alphaSource, name: 'Alpha', dataSources: [], connectorBindings: STATED_LISTS.connectorBindings }));
+ // The next states the Custom API bindings too, which the page holds: nothing is written, nothing is published, and the record is renewed to name both lists.
+ spec.pages[0].actionBindings = STATED_LISTS.actionBindings;
+ const from = server.requests.length;
+ await rebuildPages(spec, appDir, server, ids);
+ assert.deepStrictEqual(quiet(requestsOf(server, from)), [0, 0, 0], 'neither a change set, nor a publish, nor any other write — only reads');
+ assert.strictEqual(publishedOf(spec, appDir).get(ids.alpha).fingerprint, contentFingerprint({ source: alphaSource, name: 'Alpha', dataSources: [], ...STATED_LISTS }));
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
+// ── a changed-only run checks the bindings of the pages it writes, and only those ────────────────────────────────────────────────────────────
+test('changed-only: a binding whose reference is another connector\'s stops a run that writes its page before anything is uploaded — and does not stop one that leaves the page alone', async () => {
+ const appDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sel-bindings-'));
+ try {
+ fs.writeFileSync(path.join(appDir, 'overview.tsx'), 'export default function O(){ return null; }', 'utf8');
+ fs.writeFileSync(path.join(appDir, 'detail.tsx'), 'export default function D(){ return null; }', 'utf8');
+ const spec = {
+ schemaVersion: 2,
+ solution: { uniqueName: 'SelBindings', displayName: 'S', publisherPrefix: 'contoso' },
+ app: { name: 'Sel Bindings App' },
+ entities: [{ schemaName: 'contoso_item', displayName: 'Item', primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] }],
+ pages: [
+ { key: 'overview', name: 'Overview', source: { kind: 'tsx', codeFile: 'overview.tsx' } },
+ { key: 'detail', name: 'Detail', source: { kind: 'tsx', codeFile: 'detail.tsx' }, connectorBindings: [HELD_WEATHER] },
+ ],
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'G', subAreas: [{ page: 'overview', title: 'Overview' }, { page: 'detail', title: 'Detail' }] }] }] },
+ };
+ const live = [{ pageId: OVERVIEW_ID, name: 'Overview' }, { pageId: DETAIL_ID, name: 'Detail' }];
+ const manifest = { schemaVersion: 1, pages: [{ key: 'overview', name: 'Overview', pageId: OVERVIEW_ID }, { key: 'detail', name: 'Detail', pageId: DETAIL_ID }] };
+ const environment = () => {
+ const { sdk } = mockSdk({ pageManifest: Buffer.from(JSON.stringify(manifest), 'utf8').toString('base64'), liveSitemapXml: pageSitemap([OVERVIEW_ID, DETAIL_ID]), pageRows: live.map((p) => ({ uxagentprojectid: p.pageId, name: p.name })) });
+ const answer = sdk.queryRecords;
+ sdk.queryRecords = async (entity, options) => (entity === 'connectionreference'
+ ? [{ connectionreferencelogicalname: 'contoso_msnweather', connectorid: '/providers/Microsoft.PowerApps/apis/shared_office365users' }]
+ : answer(entity, options));
+ return sdk;
+ };
+ const run = (selectedKeys, genpageCli) => runSdkBuild(spec, { sdk: environment(), apply: true, env: 'https://x', appDir, genpageCli, phases: PAGES_ONLY, changedOnly: { fastApply: true, resolvedAppId: APP_ID, skipSitemapFinalize: true, selectedKeys } });
+
+ const left = mockGenpageCli(live);
+ const fine = await run(['overview'], left);
+ assert.ok(fine.ok);
+ assert.deepStrictEqual(left.uploads.map((u) => u.name), ['Overview'], 'the page that is not written is not held to its bindings');
+
+ const stopped = mockGenpageCli(live);
+ await assert.rejects(run(['detail'], stopped), (e) => e.code === 'pages-binding-reference-conflict' && e.phase === 'preflight' && /page "Detail": connector binding "contoso_msnweather" is for connector shared_msnweather/.test(e.message));
+ assert.deepStrictEqual(stopped.uploads, [], 'and nothing was uploaded');
+ } finally { fs.rmSync(appDir, { recursive: true, force: true }); }
+});
+
test('deploy: the record keeps only the pages the spec still binds — a page it no longer names is dropped when the next is written', async () => {
const { appDir, spec } = twoPageApp();
const server = new FakeGenPageServer();
diff --git a/plugins/model-apps/scripts/tests/sdk-build.test.js b/plugins/model-apps/scripts/tests/sdk-build.test.js
index cceb80d20..a08f8c75e 100644
--- a/plugins/model-apps/scripts/tests/sdk-build.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-build.test.js
@@ -1328,7 +1328,7 @@ test('#583 the deferred routing-description push refuses a copy holding an earli
await assert.rejects(runSdkBuild(spec, { sdk, apply: true, phases: appShellPhases }), (e) => {
assert.strictEqual(e.code, 'app-copy-unpushed-edits', e.message);
assert.match(e.message, /holds edits an earlier run did not push/);
- assert.match(e.message, /To reset it, stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json, destructive-approval\.json and the page-ownership\.\*\.json records \(the receipts and pending records of the pages the app created: nothing else can find them\), and re-run\./, 'the baseline, the approval record and the page records are kept');
+ assert.match(e.message, /To reset it, stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json, destructive-approval\.json, web-resource-unconfirmed\.\*\.json \(the durable ids needed to recover unconfirmed web-resource writes\), dashboard-creation\.\*\.json \(the ids of the dashboards an interrupted build created before they joined the solution\) and the page-ownership\.\*\.json records \(the receipts and pending records of the pages the app created: nothing else can find them\), and re-run\./, 'the baseline, the approval record and the page and resource records are kept');
return true;
});
assert.strictEqual(appCalls(calls, 'addElement', (c) => c.args[2] === '').length, 0, 'nothing applied');
@@ -1394,7 +1394,7 @@ test('#583 when the workspace copy cannot be reset, the halt names the workspace
const { sdk } = mockSdk({ artifactsExist: true, appPushThrows: 'APP_DRAFT_HEADER_NOT_WRITABLE', failOverwriteFetch: true });
await assert.rejects(runSdkBuild(routingSpec(), { sdk, apply: true, phases: appShellPhases }), (e) => {
assert.strictEqual(e.code, 'app-header-unpublished', e.message);
- assert.match(e.message, /then re-run the build\. First reset the workspace, which still holds this run's unpushed copy of the app \(a re-run would refuse to overwrite it\): stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json, destructive-approval\.json and the page-ownership\.\*\.json records \(the receipts and pending records of the pages the app created: nothing else can find them\)\./);
+ assert.match(e.message, /then re-run the build\. First reset the workspace, which still holds this run's unpushed copy of the app \(a re-run would refuse to overwrite it\): stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json, destructive-approval\.json, web-resource-unconfirmed\.\*\.json \(the durable ids needed to recover unconfirmed web-resource writes\), dashboard-creation\.\*\.json \(the ids of the dashboards an interrupted build created before they joined the solution\) and the page-ownership\.\*\.json records \(the receipts and pending records of the pages the app created: nothing else can find them\)\./);
return true;
});
});
@@ -1564,7 +1564,7 @@ test('a push refused for an earlier version\u2019s workspace copy halts with the
};
await assert.rejects(runSdkBuild(makeSpec(), { sdk, apply: true, phases: appShellPhases }), (e) => {
assert.strictEqual(e.code, 'ARTIFACT_PROJECTION_STALE', e.message);
- assert.match(e.message, /To reset it, stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json, destructive-approval\.json and the page-ownership\.\*\.json records \(the receipts and pending records of the pages the app created: nothing else can find them\), and re-run/);
+ assert.match(e.message, /To reset it, stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json, destructive-approval\.json, web-resource-unconfirmed\.\*\.json \(the durable ids needed to recover unconfirmed web-resource writes\), dashboard-creation\.\*\.json \(the ids of the dashboards an interrupted build created before they joined the solution\) and the page-ownership\.\*\.json records \(the receipts and pending records of the pages the app created: nothing else can find them\), and re-run/);
return true;
});
});
diff --git a/plugins/model-apps/scripts/tests/sdk-http-client.test.js b/plugins/model-apps/scripts/tests/sdk-http-client.test.js
index 7edcfa8b2..9018e80a7 100644
--- a/plugins/model-apps/scripts/tests/sdk-http-client.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-http-client.test.js
@@ -1786,3 +1786,124 @@ test('sendOnce names a request by its method and URL, so a record DELETE it does
assert.strictEqual(await sendTo(named), 1, 'the named delete: once');
assert.strictEqual(await sendTo('https://org.crm.dynamics.com/api/data/v9.0/solutions(2)'), 2, 'another one: its 429 exception as before');
});
+
+// --- a publish is sent ONCE ---------------------------------------------------------------------------------------------------------------------------------------
+// `POST …/PublishXml` is never sent again by this client for a 429 of the customization lock, a 5xx or a failure of the transport: a publish the lock refused
+// is not shown to have changed nothing, and an accepted re-send of one was measured publishing old content. Only the two answers that prove the platform never
+// started it are answered with a second send: a 401 (the token is refreshed) and a 429 of the service protection limits, whose documented codes ask for it.
+// A deadlock victim is re-sent by the layer above (the SDK's publishXml, or lib/publish-xml.js), never here (sdk-resend-layers.test.js counts the layers).
+const { scrub: scrubToken, SERVICE_PROTECTION_CODES, isServiceProtectionRefusal } = require('../lib/sdk-http-client.js');
+const PUBLISH = `${ORG}/api/data/v9.2/PublishXml`;
+const PUBLISH_BODY = { ParameterXml: '<importexportxml><entities><entity>contoso_task</entity></entities></importexportxml>' };
+const PUBLISH_TOKEN = 'eyJ0eXAiOiJKV1QifQ.eyJhdWQiOiJodHRwczovL2NvbnRvc28ifQ.c2lnbmF0dXJlLW9mLXRoZS10b2tlbg';
+const LOCK_WORDS = 'Cannot start the requested operation [Publish] because there is another [WorkflowSetState] running at this moment.';
+const lockAnswer = (statusCode, code) => ({ statusCode, headers: {}, body: JSON.stringify({ error: { code, message: `${LOCK_WORDS} (sent with ${PUBLISH_TOKEN})` } }) });
+const PUBLISH_ONCE_ANSWERS = [
+ ['a 429 of the customization lock (0x80071151)', () => lockAnswer(429, '0x80071151')],
+ ['a 429 of another lock code (0x8004F064)', () => lockAnswer(429, '0x8004F064')],
+ ['a 429 with no code', () => ({ statusCode: 429, headers: { 'retry-after': '1' }, body: '{"error":{"message":"Too many requests"}}' })],
+ ['a 429 whose body is not JSON', () => ({ statusCode: 429, headers: {}, body: '<html>busy</html>' })],
+ ['a 500 that carries a lock code', () => lockAnswer(500, '0x80071151')],
+ ['a 500 SQL deadlock victim', () => ({ statusCode: 500, headers: {}, body: JSON.stringify({ error: { code: '0x80044150', message: ' Sql error: Generic SQL error. CRM ErrorCode: -2147204784 Sql ErrorCode: -2146232060 Sql Number: 1205' } }) })],
+ ['a 502', () => ({ statusCode: 502, headers: {}, body: 'Bad Gateway' })],
+ ['a 503', () => ({ statusCode: 503, headers: { 'retry-after': '1' }, body: 'Service Unavailable' })],
+ ['a 504', () => ({ statusCode: 504, headers: {}, body: 'Gateway Timeout' })],
+];
+
+test('publish once: a PublishXml answered 429 by the lock or a 5xx — a lock code, a deadlock victim, a gateway — is sent ONCE, and its answer reaches the caller as it came, the token taken out', async () => {
+ for (const [what, answer] of PUBLISH_ONCE_ANSWERS) {
+ const slept = [];
+ const { request, calls } = fakeTransport(() => (calls.length <= 1 ? answer() : { statusCode: 204, headers: {}, body: '' }));
+ const http = createAzHttpClient(ORG, { getToken: () => PUBLISH_TOKEN, request, sleep: async (ms) => { slept.push(ms); } });
+ const res = await http.post(PUBLISH, PUBLISH_BODY);
+ const first = answer();
+ assert.strictEqual(calls.length, 1, `${what}: one send`);
+ assert.deepStrictEqual(slept, [], `${what}: nothing waited for`);
+ assert.strictEqual(res.status, first.statusCode, `${what}: the status it was answered with`);
+ let sent;
+ try { sent = JSON.parse(first.body); } catch { sent = first.body; }
+ assert.deepStrictEqual(res.body, typeof sent === 'string' ? sent : JSON.parse(scrubToken(first.body, PUBLISH_TOKEN)), `${what}: the body it was answered with — its code and its words — with the token taken out`);
+ assert.ok(!JSON.stringify(res.body).includes(PUBLISH_TOKEN), `${what}: no access token in what the caller is given`);
+ }
+});
+
+test('publish once: a PublishXml that got no answer — a reset, a timeout, an answer cut off — is not sent again', async () => {
+ for (const failure of [{ error: 'read ECONNRESET', code: 'ECONNRESET' }, { error: 'Request timed out' }, { error: 'socket hang up', code: 'ECONNRESET' }, { error: 'Response aborted before it completed', incompleteResponse: true, statusCode: 204 }]) {
+ const { request, calls } = fakeTransport(() => (calls.length <= 1 ? failure : { statusCode: 204, headers: {}, body: '' }));
+ const http = createAzHttpClient(ORG, { getToken: () => 'TOK', request, sleep: async () => {} });
+ await assert.rejects(http.post(PUBLISH, PUBLISH_BODY), /^Error: Request failed: /, failure.error);
+ assert.strictEqual(calls.length, 1, `${failure.error}: one send`);
+ }
+});
+
+test('publish once: a 401 is refused before the publish ran — the token is refreshed and the publish sent again, once', async () => {
+ const tokens = [];
+ const { request, calls } = fakeTransport(() => (calls.length <= 1 ? { statusCode: 401, headers: {}, body: '' } : { statusCode: 204, headers: {}, body: '' }));
+ const http = createAzHttpClient(ORG, { getToken: (_url, options) => { tokens.push(Boolean(options && options.fresh)); return 'TOK'; }, request, sleep: async () => {} });
+ const res = await http.post(PUBLISH, PUBLISH_BODY);
+ assert.strictEqual(res.status, 204);
+ assert.strictEqual(calls.length, 2, 'the refused send and the one with the new token');
+ assert.deepStrictEqual(tokens, [false, true], 'a fresh token for the second');
+});
+
+test('publish once: a 429 of the service protection limits — each of the three documented codes — is waited out and sent again, as any throttled request is', async () => {
+ for (const code of ['0x80072322', '0x80072321', '0x80072326', '0X80072322']) {
+ const slept = [];
+ const refused = { statusCode: 429, headers: { 'retry-after': '20' }, body: JSON.stringify({ error: { code, message: 'Number of requests exceeded the limit of 6000 over time window of 300 seconds.' } }) };
+ const { request, calls } = fakeTransport(() => (calls.length <= 2 ? refused : { statusCode: 204, headers: {}, body: '' }));
+ const http = createAzHttpClient(ORG, { getToken: () => 'TOK', request, random: () => 0, sleep: async (ms) => { slept.push(ms); } });
+ assert.strictEqual((await http.post(PUBLISH, PUBLISH_BODY)).status, 204, code);
+ assert.strictEqual(calls.length, 3, `${code}: two refusals, then the send that was accepted`);
+ assert.deepStrictEqual(slept, [20000, 20000], `${code}: the Retry-After it asked for`);
+ }
+ // Inside a run's budget, as every throttled request of a budgeted client.
+ const run = budgeted();
+ const t = fakeTransport(() => (t.calls.length <= 1 ? throttledAnswer(30) : { statusCode: 204, headers: {}, body: '' }));
+ assert.strictEqual((await clientOf(t, run).post(PUBLISH, PUBLISH_BODY)).status, 204);
+ assert.deepStrictEqual([t.calls.length, run.slept, run.throttle.spentMs()], [2, [30000], 30000], 'drawn from the budget');
+ // And a budget with no room for the wait hands the 429 back, as for any request.
+ const spent = budgeted({ spent: 300000 });
+ const t2 = fakeTransport(() => throttledAnswer(30));
+ assert.strictEqual((await clientOf(t2, spent).post(PUBLISH, PUBLISH_BODY)).status, 429);
+ assert.strictEqual(t2.calls.length, 1);
+});
+
+test('publish once: PublishAllXml and the action named with its namespace are publishes too; a custom action whose name ends the same way, a read, and every other POST keep the retry', async () => {
+ const answer = lockAnswer(429, '0x80071151');
+ const sends = async (url, method = 'post') => {
+ const { request, calls } = fakeTransport(() => (calls.length <= 1 ? answer : { statusCode: 204, headers: {}, body: '' }));
+ const http = createAzHttpClient(ORG, { getToken: () => 'TOK', request, sleep: async () => {} });
+ if (method === 'get') await http.get(url);
+ else await http.post(url, {});
+ return calls.length;
+ };
+ assert.strictEqual(await sends(`${ORG}/api/data/v9.2/PublishAllXml`), 1, 'PublishAllXml');
+ assert.strictEqual(await sends(`${ORG}/api/data/v9.0/Microsoft.Dynamics.CRM.PublishXml`), 1, 'the namespace-qualified PublishXml');
+ assert.strictEqual(await sends(`${ORG}/api/data/v9.2/new_PublishXml`), 2, 'a custom action is not a publish');
+ assert.strictEqual(await sends(`${ORG}/api/data/v9.2/systemforms`), 2, 'a form create is re-sent after the lock, as before');
+ assert.strictEqual(await sends(PUBLISH, 'get'), 2, 'a read of the same address is not a publish');
+});
+
+test('publish once: a form create refused by the lock, or answered 503, is still re-sent on its schedule — six sends at most, as before', async () => {
+ for (const answer of [lockAnswer(429, '0x80071151'), { statusCode: 503, headers: {}, body: 'busy' }]) {
+ const { request, calls } = fakeTransport(answer);
+ const http = createAzHttpClient(ORG, { getToken: () => 'TOK', request, sleep: async () => {} });
+ assert.strictEqual((await http.post(`${ORG}/api/data/v9.2/systemforms`, { name: 'Main' })).status, answer.statusCode);
+ assert.strictEqual(calls.length, 6, String(answer.statusCode));
+ }
+});
+
+test('publish once: the service protection codes are the three the api-limits page documents, and a 429 is one only by its code', () => {
+ assert.deepStrictEqual([...SERVICE_PROTECTION_CODES].sort(), ['0x80072321', '0x80072322', '0x80072326']);
+ const answer = (statusCode, body) => ({ statusCode, headers: {}, body });
+ assert.strictEqual(isServiceProtectionRefusal(answer(429, '{"error":{"code":"0x80072326","message":"Number of concurrent requests exceeded the limit of 52."}}')), true);
+ assert.strictEqual(isServiceProtectionRefusal(answer(429, { error: { code: '0x80072321' } })), true, 'a body already parsed');
+ for (const [what, res] of [
+ ['the lock', answer(429, '{"error":{"code":"0x80071151","message":"Number of requests exceeded the limit of 6000 over time window of 300 seconds."}}')],
+ ['the words alone', answer(429, '{"error":{"message":"Number of requests exceeded the limit of 6000 over time window of 300 seconds. 0x80072322"}}')],
+ ['the code on another status', answer(503, '{"error":{"code":"0x80072322"}}')],
+ ['a code that is not a string', answer(429, '{"error":{"code":2147015902}}')],
+ ['no body', answer(429, '')],
+ ['nothing', null],
+ ]) assert.strictEqual(isServiceProtectionRefusal(res), false, what);
+});
diff --git a/plugins/model-apps/scripts/tests/sdk-resend-layers.test.js b/plugins/model-apps/scripts/tests/sdk-resend-layers.test.js
index d0c016524..3dbf37eb5 100644
--- a/plugins/model-apps/scripts/tests/sdk-resend-layers.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-resend-layers.test.js
@@ -24,6 +24,7 @@ const os = require('node:os');
const path = require('node:path');
const { createAzHttpClient } = require('../lib/sdk-http-client.js');
const { KIND_HANDLERS, deleteStep, runTeardown } = require('../lib/sdk-teardown.js');
+const { appSitemapLinkRows } = require('./helpers/app-sitemap-link-rows.js');
const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
const ENV = 'https://contoso.crm.dynamics.com';
@@ -90,6 +91,11 @@ function appOrg(script) {
}
const meta = /EntityDefinitions\(LogicalName='([^']+)'\)/.exec(where);
if (meta) return json(200, { LogicalName: meta[1], EntitySetName: `${meta[1]}s` });
+ const linked = appSitemapLinkRows(url, {
+ apps: [{ appmoduleid: APP_ID, appmoduleidunique: APP_UNIQUE_ID, componentstate: 0 }],
+ components: [{ _appmoduleidunique_value: APP_UNIQUE_ID, objectid: SITEMAP_ID, componenttype: 62 }],
+ });
+ if (linked !== undefined) return json(200, { value: linked });
if (/\/appmodules\([^)]+\)/.test(where)) return json(200, { appmoduleid: APP_ID, appmoduleidunique: APP_UNIQUE_ID, uniquename: APP_UNIQUE, name: 'Support Desk', '@odata.etag': 'W/"1001"' }, { etag: 'W/"1001"' });
if (/\/sitemaps\([^)]+\)/.test(where)) return json(200, { '@odata.etag': 'W/"2002"', sitemapid: SITEMAP_ID }, { etag: 'W/"2002"' });
if (where.includes('/sitemaps')) return json(200, { value: [{ '@odata.etag': 'W/"2003"', sitemapid: SITEMAP_ID, sitemapnameunique: APP_UNIQUE, sitemapxml: '<SiteMap></SiteMap>' }] });
@@ -280,6 +286,105 @@ test('a view create that deadlocks every time stays bounded: the client\u2019s a
assert.ok(org.posts() > 6, 'and the SDK\u2019s re-send is what takes it past the client\u2019s own six');
});
+// --- a publish ----------------------------------------------------------------------------------------------------
+//
+// A publish is sent ONCE by the client (lib/sdk-http-client.js, `publishOnce`), and its deadlock victim is re-sent by exactly one
+// layer above it: the SDK's publishXml for a publish the SDK makes, lib/publish-xml.js (postPublishXml) for one the plugin sends
+// itself. So a deadlock that clears costs one re-send, and one that never clears four sends — where the client's six times the
+// SDK's four (24) was the bound before. A publish the customization lock refuses is sent once by every layer.
+const WEB_RESOURCE_ID = '88888888-8888-4888-8888-888888888888';
+const LOCK = { code: '0x80071151', message: 'Cannot start the requested operation [Publish] because there is another [WorkflowSetState] running at this moment.' };
+// A web resource the SDK creates, publishes and reads back: the POST writes the saved content, an accepted PublishXml copies it to the
+// published layer, and the plain read by id answers the published one. Each PublishXml is answered from `answers` in turn (the last repeats).
+function publishOrg(answers) {
+ const requests = [];
+ let publishes = 0;
+ const row = { saved: undefined, published: undefined };
+ async function request({ url, method, body }) {
+ const u = new URL(url);
+ requests.push({ method, path: decodeURIComponent(u.pathname + u.search) });
+ if (method === 'POST' && /\/PublishXml$/.test(u.pathname)) {
+ const answer = answers[Math.min(publishes, answers.length - 1)];
+ publishes += 1;
+ if (answer === 'deadlock') return json(500, { error: DEADLOCK });
+ if (answer === 'lock') return json(429, { error: LOCK });
+ row.published = row.saved;
+ return { statusCode: 204, headers: {}, body: '' };
+ }
+ if (method === 'POST' && /\/webresourceset$/.test(u.pathname)) {
+ row.saved = JSON.parse(body).content;
+ return { statusCode: 204, headers: { 'odata-entityid': `${ENV}/api/data/v9.0/webresourceset(${WEB_RESOURCE_ID})` }, body: '' };
+ }
+ if (method === 'GET' && /\/webresourceset\(/.test(u.pathname)) return row.published === undefined ? json(404, { error: { message: 'Does Not Exist' } }) : json(200, { content: row.published });
+ return json(200, { value: [] });
+ }
+ return { request, publishes: () => publishes };
+}
+const webResource = { name: 'co_/scripts/form.js', type: 'js', content: 'var Form = {};' };
+
+test('a publish the SDK makes that loses one deadlock is re-sent by the SDK alone: one re-send in all, and the client waits for nothing', async (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const sleeps = [];
+ const org = publishOrg(['deadlock', 'ok']);
+ const sdk = await sdkOver(org.request, sleeps);
+ const created = await settle(t, sdk.createWebResource(webResource));
+ assert.strictEqual(created.id, WEB_RESOURCE_ID);
+ assert.strictEqual(org.publishes(), 2, 'the first send and the SDK\u2019s one re-send');
+ assert.deepStrictEqual(sleeps, [], 'the client sent the publish once: it never backed off');
+});
+
+test('a publish the SDK makes that deadlocks every time is sent four times — the SDK\u2019s bound — not the client\u2019s six times the SDK\u2019s four', async (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const sleeps = [];
+ const org = publishOrg(['deadlock']);
+ const sdk = await sdkOver(org.request, sleeps);
+ const error = await settle(t, sdk.createWebResource(webResource)).then(() => assert.fail('the publish never landed'), (e) => e);
+ assert.strictEqual(error.code, 'WEB_RESOURCE_UNVERIFIED', 'the row exists and its publication is unconfirmed');
+ assert.strictEqual(org.publishes(), 4);
+ assert.deepStrictEqual(sleeps, []);
+});
+
+test('a publish the lock refuses is sent ONCE by the SDK and the client alike, and its refusal is the cause of what the SDK throws', async (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const sleeps = [];
+ const org = publishOrg(['lock', 'ok']);
+ const sdk = await sdkOver(org.request, sleeps);
+ const error = await settle(t, sdk.createWebResource(webResource)).then(() => assert.fail('a refused publish is not success'), (e) => e);
+ assert.strictEqual(error.code, 'WEB_RESOURCE_UNVERIFIED');
+ assert.strictEqual(error.id, WEB_RESOURCE_ID, 'naming the row that exists');
+ assert.deepStrictEqual([error.cause && error.cause.code, error.cause && error.cause.statusCode], ['CONNECTION_ERROR', 429]);
+ assert.strictEqual(org.publishes(), 1);
+ assert.deepStrictEqual(sleeps, []);
+});
+
+test('a publish the plugin sends itself (publishTablesXml, publishAppComponents) is re-sent for a deadlock by postPublishXml alone — 1 s, 2 s, 4 s, four sends at most — and sent once when the lock refuses it', async (t) => {
+ t.mock.timers.enable({ apis: ['setTimeout'] });
+ const { publishTablesXml } = require('../lib/table-publish.js');
+ const { publishAppComponents } = require('../lib/app-components.js');
+ for (const [what, answers, sends, waits, ok] of [
+ ['one deadlock', ['deadlock', 'ok'], 2, [1000], true],
+ ['a deadlock that never clears', ['deadlock'], 4, [1000, 2000, 4000], false],
+ ['the lock', ['lock', 'ok'], 1, [], false],
+ ]) {
+ const clientSleeps = [];
+ const org = publishOrg(answers);
+ const sdk = await sdkOver(org.request, clientSleeps);
+ const waited = [];
+ const outcome = await settle(t, publishTablesXml(sdk.dataverse, ['co_ticket'], { sleep: async (ms) => { waited.push(ms); } }));
+ assert.strictEqual(outcome.ok, ok, `${what}: ${JSON.stringify(outcome)}`);
+ assert.strictEqual(org.publishes(), sends, `${what}: the table publish`);
+ assert.deepStrictEqual(waited, waits, `${what}: postPublishXml's waits`);
+ assert.deepStrictEqual(clientSleeps, [], `${what}: the client's none`);
+ if (!ok) assert.match(outcome.reason, answers[0] === 'lock' ? /^PublishXml answered HTTP 429: Cannot start the requested operation \[Publish\]/ : /^PublishXml answered HTTP 500: /, what);
+ const app = publishOrg(answers);
+ const appSdk = await sdkOver(app.request);
+ const published = settle(t, publishAppComponents(appSdk.dataverse, APP_ID, { sleep: async () => {} }));
+ if (ok) await published;
+ else await assert.rejects(published, (e) => e.code === 'APP_TABLES_NOT_PUBLISHED' && e.statusCode === (answers[0] === 'lock' ? 429 : 500), what);
+ assert.strictEqual(app.publishes(), sends, `${what}: the app publish`);
+ }
+});
+
// --- the SDK's kind check on a form or dashboard delete ----------------------------------------------
// `deleteRemoteArtifact('form' | 'dashboard')` reads the row's type before it deletes, and refuses another kind:
diff --git a/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js b/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js
index 797de7c78..03a2a9f9d 100644
--- a/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-surface-contract.test.js
@@ -92,6 +92,8 @@ const SKILL_SDK_SURFACE = [
// saved copy it lists.
'getManifest',
'getSolution',
+ // Recovery of an unconfirmed web-resource write verifies the recorded id's name before touching its content.
+ 'getWebResource',
'importSolution',
'initWorkspace',
'insertStatusValue',
diff --git a/plugins/model-apps/scripts/tests/sdk-teardown.test.js b/plugins/model-apps/scripts/tests/sdk-teardown.test.js
index 6b630d585..eb8b93f1c 100644
--- a/plugins/model-apps/scripts/tests/sdk-teardown.test.js
+++ b/plugins/model-apps/scripts/tests/sdk-teardown.test.js
@@ -139,12 +139,12 @@ function mockSdk(state = {}) {
}
};
+ // As the real SDK's deleteRelationship: it looks the relationship up by its schema name first and, finding none, throws its
+ // InvalidArgumentError (`code: 'INVALID_ARGUMENT'`, no HTTP status) without sending a delete.
const deleteRelationship = async (schemaName) => {
calls.push({ method: 'deleteRelationship', schemaName });
if (!db.relationships.has(schemaName)) {
- const err = new Error(`Relationship ${schemaName} not found`);
- err.statusCode = 404;
- throw err;
+ throw Object.assign(new Error(`relationship '${schemaName}' not found`), { code: 'INVALID_ARGUMENT' });
}
db.relationships.delete(schemaName);
};
@@ -436,6 +436,8 @@ test('runTeardown deletes declared global choices by name (tolerating an already
const gcCalls = sdk.calls.filter((c) => c.method === 'deleteGlobalOptionSet').map((c) => c.name);
assert.deepStrictEqual(gcCalls, ['new_present', 'new_absent'], 'both declared choices attempted');
assert.strictEqual(sdk.db.globalchoices.has('new_present'), false, 'present choice deleted');
+ assert.deepStrictEqual(res.deleted.globalChoice, ['new_present'], 'only the choice that was there is counted as deleted');
+ assert.ok(res.skipped.includes('global choice new_absent'), 'the absent one is a step that found nothing');
});
test('deleteStep skips a system view that cannot be deleted (best-effort, no throw)', async () => {
@@ -1041,12 +1043,11 @@ test('not-found artifacts are skipped, not errors, and issue no delete', async (
const sdk = mockSdk(); // empty env — nothing exists
const r = await runTeardown(fullSpec(), { apply: true }, { sdk });
assert.strictEqual(r.ok, true);
- // Tables will attempt deleteTable (synthetic item) but get not-found immediately, counted as deleted
- // Relationships will attempt deleteRelationship but get not-found, counted as deleted (tolerateNotFound)
+ // Tables still send deleteTable (a synthetic item) and get not-found: the table read had listed none, so each is not found too.
+ // Relationships are looked up by the SDK, which finds none and sends no delete: not found.
// Other artifacts (app, dashboard, commands, forms, charts, views, webResource, solution) skip when resolve returns []
- assert.strictEqual(r.skipped.length, 16); // app, genpage, dashboard, commands, 3 forms, 2 charts, 3 views, webResource, generated app-icon WR, page-manifest WR, solution
- assert.strictEqual((r.deleted.table || []).length, 3); // tables counted as deleted (tolerateNotFound)
- assert.strictEqual((r.deleted.relationship || []).length, 2); // relationships counted as deleted (tolerateNotFound)
+ assert.strictEqual(r.skipped.length, 21); // app, genpage, dashboard, commands, 3 forms, 2 charts, 3 views, 2 relationships, 3 tables, webResource, generated app-icon WR, page-manifest WR, solution
+ assert.deepStrictEqual([r.deleted.table, r.deleted.relationship], [undefined, undefined], 'nothing was there, so no table or relationship is counted as deleted');
// Only table/relationship deletes were attempted (synthetic items); other kinds skipped before delete
const deletesDone = sdk.calls.filter((c) => c.method !== 'resolveArtifact' && c.method !== 'queryRecords' && c.method !== 'findTables');
assert.ok(deletesDone.every((c) => c.method === 'deleteTable' || c.method === 'deleteRelationship'), 'only table/relationship deletes attempted');
@@ -1093,14 +1094,109 @@ test('teardown deletes a created custom table but skips a reused system table in
assert.ok(!sdk.db.tables.has('new_order'), 'created table deleted; system table left intact');
});
-test('a table that does not exist skips the delete', async () => {
+test('a table that does not exist is still sent its delete, and is reported not found', async () => {
const sdk = mockSdk(); // no tables
const spec = { solution: { uniqueName: 'S', publisherPrefix: 'new' }, entities: [{ schemaName: 'new_x', primaryAttribute: { schemaName: 'new_name' } }] };
- const r = await runTeardown(spec, { apply: true }, { sdk });
+ const events = [];
+ const r = await runTeardown(spec, { apply: true }, { sdk, emit: (e) => events.push(e) });
assert.strictEqual(r.ok, true);
- // The table resolve returns a synthetic item, but deleteTable throws not-found immediately (table never existed)
- // The handler tolerates not-found, so it counts as deleted
- assert.strictEqual((r.deleted.table || []).length, 1);
+ // The table resolve returns a synthetic item and deleteTable is sent; its not-found answer, after a table read that listed no
+ // such table, says the table was never there — not a deletion.
+ assert.deepStrictEqual(sdk.calls.filter((c) => c.method === 'deleteTable').map((c) => c.logical), ['new_x']);
+ assert.strictEqual(r.deleted.table, undefined);
+ assert.ok(events.some((e) => e.status === 'skip' && e.skip === 'not-found' && e.label === 'table new_x (not found)'), JSON.stringify(events));
+});
+
+// A delete answered "not found" says one of two things: nothing was there when the step began, or the step's own delete removed it —
+// a metadata delete that the client sent again after a timeout gets the second answer once the first send did the work. Each kind
+// reports the one it can tell from what it already knows, and sends exactly the deletes it always sent.
+test('a teardown of what is already gone says not found for every default-view reset, relationship, table and global choice, and still succeeds', async () => {
+ const spec = fullSpec();
+ spec.globalChoices = [{ name: 'new_severity', displayName: 'Severity', options: ['Low', 'High'] }];
+ const sdk = mockSdk(); // nothing exists
+ // The default-view reset as the real SDK runs it in a teardown (saved with publish: false, published once later): a table that is
+ // gone has no default view to reset.
+ sdk.enrichDefaultViews = async (logical, cols, opts) => { sdk.calls.push({ method: 'enrichDefaultViews', logical, opts }); return { updated: [], results: [], pendingPublish: [] }; };
+ sdk.publishArtifact = async () => ({ publish: { kind: 'published' } });
+ sdk.publishArtifacts = async (targets) => targets.map(() => ({ publish: { kind: 'published' } }));
+ const events = [];
+ const r = await runTeardown(spec, { apply: true }, { sdk, emit: (e) => events.push(e) });
+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
+ const steps = events.filter((e) => e.status !== 'start' && /^(reset default views|relationship|table|global choice) /.test(e.label));
+ assert.deepStrictEqual(steps.map((e) => [e.status, e.skip, e.label]), [
+ ['skip', 'not-found', 'reset default views for new_ticket (drop parent lookups) (not found)'],
+ ['skip', 'not-found', 'reset default views for new_comment (drop parent lookups) (not found)'],
+ ['skip', 'not-found', 'relationship new_customer_new_ticket (not found)'],
+ ['skip', 'not-found', 'relationship new_ticket_new_comment (not found)'],
+ ['skip', 'not-found', 'table new_comment (not found)'],
+ ['skip', 'not-found', 'table new_ticket (not found)'],
+ ['skip', 'not-found', 'table new_customer (not found)'],
+ ['skip', 'not-found', 'global choice new_severity (not found)'],
+ ]);
+ assert.deepStrictEqual(r.deleted, {});
+ // ...and what is sent is what was always sent: each reset, each relationship lookup, each table and global choice delete.
+ const sent = (method) => sdk.calls.filter((c) => c.method === method).length;
+ assert.deepStrictEqual([sent('enrichDefaultViews'), sent('deleteRelationship'), sent('deleteTable'), sent('deleteGlobalOptionSet')], [2, 2, 3, 1]);
+});
+
+test('a not-found answer to a delete is "not found" only where the step knows nothing was there; everywhere else it stays the deletion it was', async () => {
+ const notFound = (props) => Object.assign(new Error('Could not find an entity with the specified logical name'), props);
+ const outcome = async (sdk, kind, item) => {
+ const { deletedIds, absentIds } = await deleteStep(sdk, KIND_HANDLERS[kind], [item]);
+ return { deletedIds, absentIds };
+ };
+ // A table: the step's read listed no such table — not found; the read saw it — the not-found a re-sent delete gets once its first
+ // send did the work, so a deletion; the read could not be made — unknown, a deletion as before.
+ const table = { deleteTable: async () => { throw notFound({ statusCode: 404 }); } };
+ assert.deepStrictEqual(await outcome(table, 'table', { id: 'new_x', logical: 'new_x', seen: false }), { deletedIds: [], absentIds: ['new_x'] });
+ assert.deepStrictEqual(await outcome(table, 'table', { id: 'new_x', logical: 'new_x', seen: true }), { deletedIds: ['new_x'], absentIds: [] });
+ assert.deepStrictEqual(await outcome(table, 'table', { id: 'new_x', logical: 'new_x' }), { deletedIds: ['new_x'], absentIds: [] });
+ // A relationship: the SDK's own lookup found none and sent no delete (its error carries no HTTP status) — not found; the delete
+ // itself answered 404, or 400 "…but 0 were found", after the lookup found it — a deletion, as before.
+ const relationship = (err) => ({ deleteRelationship: async () => { throw err; } });
+ assert.deepStrictEqual(await outcome(relationship(notFound({ message: "relationship 'new_a_new_b' not found", code: 'INVALID_ARGUMENT' })), 'relationship', { id: 'new_a_new_b', schemaName: 'new_a_new_b' }), { deletedIds: [], absentIds: ['new_a_new_b'] });
+ assert.deepStrictEqual(await outcome(relationship(notFound({ statusCode: 404 })), 'relationship', { id: 'new_a_new_b', schemaName: 'new_a_new_b' }), { deletedIds: ['new_a_new_b'], absentIds: [] });
+ assert.deepStrictEqual(await outcome(relationship(notFound({ message: 'There should be one and only one relationship related to the entity relationship with id cb989759-967a-f111-9d0f-7ced8d711dbf, but 0 were found', statusCode: 400 })), 'relationship', { id: 'new_a_new_b', schemaName: 'new_a_new_b' }), { deletedIds: ['new_a_new_b'], absentIds: [] });
+ // A global choice: its delete is the step's only request, so its not-found is the platform saying there is no such choice.
+ assert.deepStrictEqual(await outcome({ deleteGlobalOptionSet: async () => { throw notFound({ statusCode: 404 }); } }, 'globalChoice', { id: 'new_c', name: 'new_c' }), { deletedIds: [], absentIds: ['new_c'] });
+ assert.deepStrictEqual(await outcome({ deleteGlobalOptionSet: async () => undefined }, 'globalChoice', { id: 'new_c', name: 'new_c' }), { deletedIds: ['new_c'], absentIds: [] });
+ // Every other kind that tolerates a not-found found its artifact first, so a not-found from its delete stays a deletion.
+ assert.deepStrictEqual(await outcome({ deleteSecurityRole: async () => { throw notFound({ statusCode: 404 }); } }, 'role', { id: 'r1', name: 'Planner' }), { deletedIds: ['r1'], absentIds: [] });
+});
+
+test('the table read says whether the table was there before its delete: seen, listed as absent, or not known', async () => {
+ const resolveWith = (findTables) => KIND_HANDLERS.table.resolve({ findTables }, { logical: 'new_x', schemaName: 'new_X' });
+ assert.deepStrictEqual(await resolveWith(async () => [{ logicalName: 'new_x', isCustom: true }]), [{ id: 'new_x', logical: 'new_x', seen: true }]);
+ assert.deepStrictEqual(await resolveWith(async () => [{ logicalName: 'new_xy', isCustom: true }]), [{ id: 'new_x', logical: 'new_x', seen: false }]);
+ assert.deepStrictEqual(await resolveWith(async () => []), [{ id: 'new_x', logical: 'new_x', seen: false }]);
+ // A read that failed, or a list cut at the 50 matches it asks for, does not say the table is absent.
+ assert.deepStrictEqual(await resolveWith(async () => { throw new Error('HTTP 503'); }), [{ id: 'new_x', logical: 'new_x' }]);
+ const fifty = Array.from({ length: 50 }, (_, i) => ({ logicalName: `new_x${i}`, isCustom: true }));
+ assert.deepStrictEqual(await resolveWith(async () => fifty), [{ id: 'new_x', logical: 'new_x' }]);
+});
+
+test('a default-view reset that finds no default view says not found; one that finds views, or fails after finding them, reads as before', async () => {
+ const PARTIAL = Symbol.for('cds-maker-sdk.partialDefaultViewEnrichment');
+ const deferred = () => ({ deferPublish: true, owedByTable: new Map(), warnings: [] });
+ const item = { id: 'new_task', cols: [{ name: 'new_name', width: 300, order: 0 }] };
+ const outcome = async (enrichDefaultViews, ctx = deferred()) => {
+ const { deletedIds, absentIds } = await deleteStep({ enrichDefaultViews }, KIND_HANDLERS.resetDefaultViews, [item], ctx);
+ return { deletedIds, absentIds };
+ };
+ const absent = { deletedIds: [], absentIds: ['new_task'] };
+ const asBefore = { deletedIds: ['new_task'], absentIds: [] };
+ // The SDK found no default view of the table: it is gone.
+ assert.deepStrictEqual(await outcome(async () => ({ updated: [], results: [], pendingPublish: [] })), absent);
+ // The SDK's read of the table's default views answered not-found (no partial record: it failed before it found any view).
+ assert.deepStrictEqual(await outcome(async () => { throw Object.assign(new Error("The entity with a name = 'new_task' was not found in the MetadataCache."), { statusCode: 400 }); }), absent);
+ // Views found and saved, or found and already as the reset leaves them: as before.
+ assert.deepStrictEqual(await outcome(async () => ({ updated: ['v1'], results: [{ saved: true }], pendingPublish: [{ artifacts: [{ type: 'view', id: 'v1' }] }] })), asBefore);
+ assert.deepStrictEqual(await outcome(async () => ({ updated: [], results: [{ saved: false }], pendingPublish: [] })), asBefore);
+ // A failure after the views were found (the SDK attaches what it had saved), even a not-found one, or any other failure: as before.
+ assert.deepStrictEqual(await outcome(async () => { throw Object.assign(new Error('HTTP 404 from https://contoso.crm.dynamics.com/api/data/v9.0/savedqueries(v1): Not found'), { statusCode: 404, [PARTIAL]: { updated: [], results: [], pendingPublish: [] } }); }), asBefore);
+ assert.deepStrictEqual(await outcome(async () => { throw new Error('HTTP 500 from https://contoso.crm.dynamics.com/api/data/v9.0/savedqueries: boom'); }), asBefore);
+ // An SDK that cannot defer the publish answers only what it saved, which cannot tell "no view" from "nothing to change": as before.
+ assert.deepStrictEqual(await outcome(async () => ({ updated: [] }), undefined), asBefore);
});
test('appaction delete not-found (cascade already removed it) is tolerated', async () => {
@@ -1776,24 +1872,26 @@ test('a table kept for a failed rule keeps its icon, the global choice its colum
assert.deepStrictEqual(res.errors.map((e) => e.step), ['business rule "Gate" (new_ticket)']);
assert.deepStrictEqual(events.filter((e) => e.status === 'error').map((e) => e.label), ['business rule "Gate" (new_ticket)']);
- // What is kept, in the order the plan reaches it — each a `(kept — …)` skip that names the table, and the solution last.
- assert.deepStrictEqual(res.skipped.slice(0, 4), [
+ // What is kept, in the order the plan reaches it — each a `(kept — …)` skip that names the table, and the solution last. Between
+ // them, the deleted table's relationship to itself, which went with its table: its step found nothing, and says so.
+ assert.deepStrictEqual(res.skipped.slice(0, 5), [
keptTableLabel('new_ticket', ['Gate']),
keptWithTable('relationship new_ticket_new_ticket', 'it relates table new_ticket to itself'),
+ 'relationship new_customer_new_customer',
keptWithTable('web resource new_ticket.svg', 'it is the icon of table new_ticket'),
keptWithTable('global choice new_priority', 'a column of table new_ticket binds it'),
]);
- assert.strictEqual(res.skipped.length, 5, JSON.stringify(res.skipped));
- assert.match(res.skipped[4], solutionKept, 'the solution is kept for the re-run, as for any earlier failure');
+ assert.strictEqual(res.skipped.length, 6, JSON.stringify(res.skipped));
+ assert.match(res.skipped[5], solutionKept, 'the solution is kept for the re-run, as for any earlier failure');
assert.deepStrictEqual(events.filter((e) => e.status === 'skip').map((e) => [e.phase, e.skip]), [
- ['tables', 'kept'], ['relationships', 'kept'], ['web-resources', 'kept'], ['global-choices', 'kept'], ['solution', 'kept'],
+ ['tables', 'kept'], ['relationships', 'kept'], ['relationships', 'not-found'], ['web-resources', 'kept'], ['global-choices', 'kept'], ['solution', 'kept'],
], 'each is a kept skip, which the summary counts as kept');
// What was deleted as before: the other table with everything it holds, the script, the relationship between the two tables.
assert.deepStrictEqual(res.deleted.table, ['new_customer']);
assert.deepStrictEqual(res.deleted.webResource, ['wr-customer', 'wr-js']);
assert.deepStrictEqual(res.deleted.globalChoice, ['new_tier']);
- assert.deepStrictEqual(res.deleted.relationship, ['new_customer_new_ticket', 'new_customer_new_customer']);
+ assert.deepStrictEqual(res.deleted.relationship, ['new_customer_new_ticket']);
// What the environment holds afterwards: the table with the rule and everything that hangs on it, nothing the platform refused.
assert.deepStrictEqual([...sdk.db.tables], ['new_ticket']);
@@ -1847,7 +1945,8 @@ test('with no failed rule the same spec is torn down exactly as before: the same
const sdk = dependentsWorld();
const res = await runTeardown(dependentsSpec(), { apply: true }, { sdk, emit: () => {} });
assert.strictEqual(res.ok, true, JSON.stringify(res.errors));
- assert.deepStrictEqual(res.skipped, []);
+ // Nothing kept: the only steps that skip are the two relationships to themselves, which went with their tables and so find nothing.
+ assert.deepStrictEqual(res.skipped, ['relationship new_ticket_new_ticket', 'relationship new_customer_new_customer']);
assert.deepStrictEqual(ruleRequests(sdk), [
'queryRecords workflow',
'updateRecord workflow gate-def {"statecode":0,"statuscode":1}',
diff --git a/plugins/model-apps/scripts/tests/spec-lint.test.js b/plugins/model-apps/scripts/tests/spec-lint.test.js
index 17c74eeec..e922a16fa 100644
--- a/plugins/model-apps/scripts/tests/spec-lint.test.js
+++ b/plugins/model-apps/scripts/tests/spec-lint.test.js
@@ -682,6 +682,65 @@ test('lint warns on lead and opportunity D365-owned tables', () => {
assert.ok(r.warnings.some((w) => /opportunity/i.test(w) && /Dynamics 365/i.test(w)));
});
+// A table's entry in ai.summaries.tables is read for three keys only — `enabled`, `instruction` (its row-summary prompt) and `columns` — and
+// validation rejects none of the others, so a misnamed key validates, builds green and does nothing. Seen live: `prompt` for the prompt.
+test('lint warns on a per-table summary prompt key that is never read, naming where the prompt goes', () => {
+ const s = base();
+ s.ai = { summaries: { default: 'off', tables: { new_ticket: { enabled: true, prompt: 'Summarise the ticket in two sentences.', instructions: 'x', colour: 'red' } } } };
+ const { validateAppSpec } = require('../lib/app-spec.js');
+ assert.deepStrictEqual(validateAppSpec(s, { profile: 'plan' }).errors.filter((e) => /ai\.summaries/.test(e)), [], 'validation does not reject an unknown key, so lint is where it is caught');
+ const r = lintAppSpec(s);
+ assert.deepStrictEqual(r.errors, [], 'a warning, not an error');
+ assert.deepStrictEqual(r.warnings.filter((w) => /ai\.summaries\.tables/.test(w)), [
+ "ai.summaries.tables['new_ticket'].prompt is ignored — a table's row-summary prompt is its instruction: rename the key to ai.summaries.tables['new_ticket'].instruction (when a summary is enabled, omitting instruction uses the default prompt)",
+ "ai.summaries.tables['new_ticket']: unknown key 'instructions' is ignored — did you mean 'instruction'? (a table's entry reads only enabled, instruction and columns)",
+ "ai.summaries.tables['new_ticket']: unknown key 'colour' is ignored (a table's entry reads only enabled, instruction and columns)",
+ ]);
+ // The keys the build reads say nothing.
+ const ok = base();
+ ok.ai = { summaries: { tables: { new_ticket: { enabled: true, instruction: 'Summarise the ticket.', columns: ['new_priority'] }, new_customer: { enabled: false } } } };
+ assert.deepStrictEqual(lintAppSpec(ok).warnings.filter((w) => /is ignored/.test(w)), []);
+});
+
+test('a prompt warning does not enable a disabled-by-default summary', () => {
+ const { validateAppSpec } = require('../lib/app-spec.js');
+ const { selectSummaryTables } = require('../lib/ai-candidates.js');
+ const { buildPromptSpec } = require('../lib/ai-prompt.js');
+ const instruction = 'Summarise the ticket in two sentences.';
+ const defaultInstruction = 'Summarize this Ticket as a short paragraph highlighting the most important details and any recent activity.';
+ for (const [mode, enabled, selected] of [
+ ['off', undefined, []],
+ ['off', true, ['new_ticket']],
+ ['auto', false, []],
+ ['auto', undefined, ['new_ticket']],
+ ]) {
+ const s = base();
+ s.app = { name: 'Ticket summaries' };
+ const override = { prompt: instruction };
+ if (enabled !== undefined) override.enabled = enabled;
+ s.ai = { summaries: { default: mode, tables: { new_ticket: override } } };
+ const before = structuredClone(s);
+ assert.strictEqual(validateAppSpec(s, { profile: 'plan' }).ok, true);
+ assert.deepStrictEqual(selectSummaryTables(s), selected);
+ const r = lintAppSpec(s);
+ assert.deepStrictEqual(s, before, 'lint must not change summary selection or the authored spec');
+ assert.deepStrictEqual(r.errors, []);
+ assert.deepStrictEqual(r.warnings.filter((w) => /ai\.summaries\.tables/.test(w)), [
+ "ai.summaries.tables['new_ticket'].prompt is ignored — a table's row-summary prompt is its instruction: rename the key to ai.summaries.tables['new_ticket'].instruction (when a summary is enabled, omitting instruction uses the default prompt)",
+ ]);
+ const prompts = () => selectSummaryTables(s).map((schema) =>
+ buildPromptSpec(s.entities.find((e) => e.schemaName === schema), { spec: s, override }).instruction);
+ assert.deepStrictEqual(prompts(), selected.map(() => defaultInstruction), 'only a selected summary gets the default prompt');
+
+ delete override.prompt;
+ override.instruction = instruction;
+ assert.strictEqual(validateAppSpec(s, { profile: 'plan' }).ok, true);
+ assert.deepStrictEqual(lintAppSpec(s).warnings.filter((w) => /ai\.summaries\.tables/.test(w)), []);
+ assert.deepStrictEqual(selectSummaryTables(s), selected, 'renaming prompt to instruction does not enable a summary');
+ assert.deepStrictEqual(prompts(), selected.map(() => instruction));
+ }
+});
+
test('lint warns when a summary table has no descriptive columns', () => {
const s = base();
// new_customer has no columns at all in base() — should warn
diff --git a/plugins/model-apps/scripts/tests/table-columns-in-create.test.js b/plugins/model-apps/scripts/tests/table-columns-in-create.test.js
index 8c0632ace..92264e568 100644
--- a/plugins/model-apps/scripts/tests/table-columns-in-create.test.js
+++ b/plugins/model-apps/scripts/tests/table-columns-in-create.test.js
@@ -188,10 +188,14 @@ function fakeDataverse({
const p = relative(url);
log.push({ method: 'GET', path: p });
let m;
- if ((m = /^\/EntityDefinitions\(LogicalName='([^']+)'\)\?\$select=LogicalName,EntitySetName$/.exec(p))) {
+ if ((m = /^\/EntityDefinitions\(LogicalName='([^']+)'\)\?\$select=LogicalName,EntitySetName(&\$expand=Keys\(\$select=SchemaName,KeyAttributes\))?$/.exec(p))) {
const t = tables.get(m[1]);
if (t && t.lagReads > 0) { t.lagReads -= 1; return reply(404, { error: { message: `no table ${m[1]} yet` } }); }
- return t ? reply(200, { LogicalName: t.logical, EntitySetName: `${t.logical}s` }) : reply(404, { error: { message: `no table ${m[1]}` } });
+ return t ? reply(200, {
+ LogicalName: t.logical, EntitySetName: `${t.logical}s`,
+ // The no-op key proof carries identity scalars only, never labels ahead of a create.
+ ...(m[2] ? { Keys: [...t.keys.values()].map((k) => ({ SchemaName: k.body.SchemaName, KeyAttributes: clone(k.body.KeyAttributes) })) } : {}),
+ }) : reply(404, { error: { message: `no table ${m[1]}` } });
}
// Which table answers to a name right now: its MetadataId and its primary name column, in one narrow request by name.
if ((m = /^\/EntityDefinitions\(LogicalName='([^']+)'\)\?\$select=MetadataId,PrimaryNameAttribute$/.exec(p))) {
@@ -648,7 +652,7 @@ test('a table that already exists, an SDK without createColumns, or inlineColumn
findColumns: async () => [],
dataverse: { get: async (url) => {
seen.reads.push(url);
- if (/\?\$select=LogicalName,EntitySetName$/.test(url)) return existing ? { status: 200, body: { LogicalName: 'new_t', EntitySetName: 'new_ts' } } : { status: 404, body: null };
+ if (/\?\$select=LogicalName,EntitySetName(?:&\$expand=Keys\(\$select=SchemaName,KeyAttributes\))?$/.test(url)) return existing ? { status: 200, body: { LogicalName: 'new_t', EntitySetName: 'new_ts' } } : { status: 404, body: null };
return { status: 200, body: { value: [] } };
} },
};
@@ -1876,7 +1880,7 @@ function orderDoubles({ failOn, existing = [] } = {}) {
if (/Attributes\?\$select=MetadataId,LogicalName$/.test(url)) return { status: 200, body: { value: ['new_x', 'new_y'].map((n) => ({ LogicalName: n, MetadataId: attributeId('new_t', n) })) } };
if (/Attributes\?\$select=LogicalName,RequiredLevel$/.test(url)) return { status: 200, body: { value: [] } };
if (/Relationships\?\$select=/.test(url)) return { status: 200, body: { value: [] } };
- const table = /EntityDefinitions\(LogicalName='([^']+)'\)\?\$select=LogicalName,EntitySetName$/.exec(url);
+ const table = /EntityDefinitions\(LogicalName='([^']+)'\)\?\$select=LogicalName,EntitySetName(?:&\$expand=Keys\(\$select=SchemaName,KeyAttributes\))?$/.exec(url);
if (table && existing.includes(table[1])) return { status: 200, body: { LogicalName: table[1], EntitySetName: `${table[1]}s` } };
return { status: 404, body: null };
} } };
@@ -1997,8 +2001,9 @@ test('a phase that halts after creating tables still sets the name column length
...FIRST_TABLE_CALLS, 'createTable new_b', SET_FIRST_LENGTH,
]],
// A table that existed before is never set, a halt or not: only the table this run created is.
+ // Its status comparison waits until every labelled create finishes; a halted phase never reaches it.
['the first table already existed, and a column of the second is refused', (call) => /^createColumns? new_b[ .]new_y$/.test(call), ['new_a'], [
- 'updateTable new_a {"quickCreateEnabled":true}', 'createColumn new_a.new_x', 'createColumn new_a.new_file', 'insertStatusValue new_a: On hold', 'createAlternateKey new_a.new_a_key',
+ 'updateTable new_a {"quickCreateEnabled":true}', 'createColumn new_a.new_x', 'createColumn new_a.new_file', 'createAlternateKey new_a.new_a_key',
'createTable new_b', 'createColumns new_b new_y', 'createColumn new_b.new_y', SET_SECOND_LENGTH,
]],
]) {
@@ -2559,6 +2564,21 @@ test('the primary column length step is planned exactly when the spec asks for a
}
});
+test('a downloaded 100-character primary name stays explicit so a fresh build corrects the platform default', async () => {
+ const { entityFromMetadata } = require('../download-model-app.js');
+ const authored = oneTable([], asksFor(100));
+ const source = await provisionOver(authored);
+ const actualLength = source.dv.tables.get('new_ticket').primaryLength;
+ assert.strictEqual(actualLength, 100);
+ const entity = entityFromMetadata({
+ schemaName: 'new_ticket', primaryNameAttribute: 'new_name',
+ attributes: [{ logicalName: 'new_name', displayName: 'Name', attributeType: 'String', maxLength: actualLength }],
+ }, 'new_ticket');
+ const target = await provisionOver({ ...authored, entities: [entity] });
+ assert.strictEqual(target.dv.tables.get('new_ticket').primaryLength, actualLength,
+ 'the explicit downloaded length must trigger the post-create correction even at the SDK default');
+});
+
// --- an alternate key over a new table's name column -----------------------------------------------------------------------------
// The platform validates a key when it is created, and a key may hold at most 1,700 bytes (KEY_BYTES_LIMIT, 2 a character of text), which
// the 850 characters an environment may make of a new name column fill by themselves. The name column of a new table has the length the
@@ -3756,7 +3776,8 @@ test('the run after a first build that made such a key after the length step fin
['skip', 'primary column length new_ticket.new_name (table exists — kept)'],
['skip', 'column new_ticket.new_code (exists)'],
['skip', 'alt key new_ticket.new_pairkey (exists)'],
- ], 'every step is a skip, the key\'s too: the platform answers that it exists');
+ ], 'every step is a skip, the key\'s too: the scalar metadata proves that it exists');
+ assert.strictEqual(keyPosts(first).length, 1, 'only the first build asks to create the key; the rebuild reuses its identity proof');
assert.deepStrictEqual(again.warnings, []);
assert.strictEqual(puts(first).length, 1, 'the one write of the length is the first build\'s');
assert.strictEqual(first.dv.tables.get('new_ticket').primaryLength, 120);
@@ -4475,5 +4496,3 @@ test('a rebuild that finds the AutoNumber column already there never reaches the
assert.deepStrictEqual(stated.log.filter((r) => r.method === 'POST'), [], 'nothing is created');
for (const put of stated.log.filter((r) => r.method === 'PUT')) assert.ok(!('AutoNumberFormat' in put.body), 'an update of the column carries no format');
});
-
-
diff --git a/plugins/model-apps/scripts/tests/teardown-dangling-sitemap-real-bundle.test.js b/plugins/model-apps/scripts/tests/teardown-dangling-sitemap-real-bundle.test.js
new file mode 100644
index 000000000..571fce244
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/teardown-dangling-sitemap-real-bundle.test.js
@@ -0,0 +1,643 @@
+'use strict';
+// The teardown of a published app whose navigation link names a sitemap that no longer exists.
+//
+// An app is two rows, the appmodule and its sitemap, and the bundled SDK deletes the two together once it has found the sitemap through the
+// app's SiteMap component (componenttype 62) on its current layer. Before 2.18.0, the teardown of one app deleted the sitemap it used even when
+// another app used that sitemap too. 2.18.0 refuses that, but environments where it happened hold apps whose SiteMap component names a sitemap
+// that is gone: measured live, the component outlives the row it names. 2.17.0's delete looked an app's sitemap up by the app's unique name and, when
+// no sitemap had that name, deleted such an app alone; the component-aware delete of the 2.18.0 SDK refuses it, on every run:
+// APP_SITEMAP_UNRESOLVED Refusing to delete app '<app>': sitemap '<sitemap>' was not returned by the unpublished-aware read. … Retry.
+// — and its "Retry." can never succeed.
+//
+// Teardown now proves the sitemap gone itself — by its id, in the published and in the saved layer, with no other app's current layer naming
+// it, and with the link unchanged — having read the app's row version FIRST. Then it deletes the app ALONE, with one DELETE conditioned on that
+// version, so a change of the app while the proof ran (a repair, a relink, a publish) makes the platform refuse the delete; it proves the app gone
+// in both layers, and goes on. In every other case it refuses, with what it found and what the maker can do, never with "Retry" — and every error
+// of this path stops the teardown before the steps that depend on the app, whatever its words say. It is reached only by a teardown that gets to
+// the app step: an app whose live generative pages must first be proven from its navigation stops at that proof, as it did before.
+//
+// Over the REAL vendored SDK, the plugin's own HTTP client and the strict stateful fake of helpers/fake-lifecycle-org.js: a row that does not
+// exist answers 404 0x80040217 by id and is in no collection read; a plain read of a collection is the published layer, and
+// RetrieveUnpublishedMultiple is the saved one. The app is made by the build. The dangling link is made by a DISCLOSED FIXTURE STEP (`strand`):
+// the sitemap is deleted the way another app's teardown deleted it, and the app's SiteMap component is put back, because the platform kept it
+// (measured live) where this fake drops every component that names a row it deletes. A failure is provoked in front of the fake, for this
+// test's own requests only; so is the platform's If-Match rule for the app's DELETE (`honourIfMatch`), which this fake does not apply to deletes.
+//
+// 1. the SDK's refusal: the one shape teardown recognises
+// 2. a dangling link: teardown deletes that app alone and finishes — or, when that delete is refused (a change of the app while the proof ran
+// among others) or cannot be read back, stops before the steps that depend on the app, and a run again finishes
+// 3. a dangling link teardown cannot prove gone: refused, never retried, nothing deleted — and no error of this path is taken for a row that is
+// not found or an artifact that cannot be deleted, whatever the app is called
+// 4. what is unchanged: an ordinary teardown, and the SDK's own refusals — a sitemap another app shares, a link that changes while the SDK
+// reads it, a SiteMap component it cannot read, a namesake sitemap that is another app's navigation
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const { makeTempDir } = require('./helpers/temp-dirs.js');
+const { createLifecycleOrg } = require('./helpers/fake-lifecycle-org.js');
+const { createLifecycleHarness, diffContents } = require('./helpers/lifecycle-harness.js');
+const { createMakerSdk, createNodeWorkspaceStorage } = require('../lib/maker-sdk.js');
+const { KIND_HANDLERS } = require('../lib/sdk-teardown.js');
+const { RETRY, retryPolicyFor } = require('../lib/retry-policy.js');
+
+// Loaded where it is used, so that a test fails on its own assertion when the module is not there.
+const dangling = () => require('../lib/app-sitemap-dangling.js');
+
+const SOLUTION = 'ContosoNav';
+const APP = 'contoso_navc';
+const APP_NAME = 'Nav C';
+const OTHER_APP = '66666666-6666-4666-8666-666666666666';
+const OTHER_LAYER = '77777777-7777-4777-8777-777777777777';
+const ELSEWHERE = '44444444-4444-4444-8444-444444444444';
+
+// The smallest app the build makes with navigation of its own: in its solution, published, a table in its sitemap. `appName` is its display name.
+const spec = (appName = APP_NAME) => ({
+ schemaVersion: 2,
+ solution: { uniqueName: SOLUTION, displayName: 'Contoso Nav', publisherPrefix: 'contoso' },
+ app: { name: appName, uniqueName: APP },
+ entities: [{ schemaName: 'contact', displayName: 'Contact', existing: true, primaryAttribute: { schemaName: 'fullname', displayName: 'Full Name' }, columns: [] }],
+ appShell: { areas: [{ label: 'Work', groups: [{ label: 'People', subAreas: [{ entity: 'contact', title: 'Contacts' }] }] }] },
+});
+
+// --- the environment ---------------------------------------------------------------------------------------------------------------------------------------
+
+// A fake environment, and a seam in front of its transport that answers what a test's faults name instead of the fake. A refused request never
+// reaches the fake (and so is not in its record of requests: a fault counts its own `hits`). A Dataverse refusal is an OData error:
+// { "error": { "code": "0x80040216", "message": "An unexpected error occurred." } }
+// See: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/compose-http-requests-handle-errors#parse-errors-from-the-response
+function environment() {
+ const org = createLifecycleOrg();
+ const seed = { inventory: org.inventory(), contents: org.contents() };
+ const faults = [];
+ const request = async (req) => {
+ const url = new URL(req.url);
+ const where = decodeURIComponent(url.pathname + url.search).replace(/^\/api\/data\/v9\.\d/, '');
+ const fault = faults.find((f) => f.method === req.method && f.matches(where));
+ if (!fault) return org.request(req);
+ fault.hits += 1;
+ return fault.answer(req, where);
+ };
+ const add = (method, matches, answer) => {
+ const fault = { method, matches, answer, hits: 0 };
+ faults.push(fault);
+ return fault;
+ };
+ const harness = createLifecycleHarness({ ...org, request }, makeTempDir('teardown-dangling-'));
+ return { org, seed, harness, add };
+}
+
+const answered = (statusCode, body) => () => ({ statusCode, headers: { 'content-type': 'application/json; odata.metadata=minimal' }, body: JSON.stringify(body) });
+const refusedWith = (statusCode, code, message) => answered(statusCode, { error: { code, message } });
+
+// What another command or a maker does in the environment, sent to the fake as the Web API call it makes — around the seam.
+async function direct(org, method, where, body) {
+ const res = await org.request({ url: `${org.API}${where}`, method, headers: body === undefined ? {} : { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
+ assert.ok(res.statusCode < 300, `${method} ${where} answered ${res.statusCode}: ${res.body}`);
+ return res;
+}
+
+// The app the build made from `appSpec`: its id, its current layer, and the sitemap its SiteMap component names.
+async function built(env, appSpec = spec()) {
+ const { result } = await env.harness.build(appSpec);
+ assert.equal(result.ok, true, JSON.stringify(result.errors));
+ const [app] = env.org.find('appmodules', (a) => a.uniquename === APP);
+ const layer = String(app.appmoduleidunique).toLowerCase();
+ const links = env.org.find('appmodulecomponents', (c) => String(c._appmoduleidunique_value).toLowerCase() === layer && Number(c.componenttype) === 62);
+ assert.equal(links.length, 1, 'the build links its app to one sitemap');
+ return { id: String(app.appmoduleid).toLowerCase(), layer, sitemapId: String(links[0].objectid).toLowerCase(), link: links[0] };
+}
+
+// THE FIXTURE STEP. The app's sitemap is deleted the way another app's teardown deleted a sitemap the two apps shared — one DELETE of the row —
+// and the app's SiteMap component is put back as it was. Measured live, the platform keeps the component of an app whose sitemap is deleted:
+// GET /appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq <the app's layer> and componenttype eq 62 -> { "value": [ { "objectid": "<the deleted sitemap>" } ] }
+// GET /sitemaps(<the deleted sitemap>)?$select=sitemapid -> 404
+// This fake drops every component that names a row it deletes, so the component is written back.
+async function strand(env, app) {
+ await direct(env.org, 'DELETE', `/sitemaps(${app.sitemapId})`);
+ await direct(env.org, 'POST', '/appmodulecomponents', {
+ appmodulecomponentid: app.link.appmodulecomponentid, _appmoduleidunique_value: app.layer, objectid: app.sitemapId, componenttype: 62, rootcomponentbehavior: Number(app.link.rootcomponentbehavior) || 0,
+ });
+ assert.deepEqual(env.org.find('sitemaps', (s) => String(s.sitemapid).toLowerCase() === app.sitemapId), [], 'the sitemap is gone, in both layers');
+ assert.equal(env.org.find('appmodulecomponents', (c) => String(c._appmoduleidunique_value).toLowerCase() === app.layer && String(c.objectid).toLowerCase() === app.sitemapId).length, 1, 'and the app still names it');
+}
+
+// The row version of the app as its read by id answers it (the version a conditional delete of it carries).
+async function rowVersion(org, id) {
+ const res = await direct(org, 'GET', `/appmodules(${id})?$select=appmoduleid`);
+ return res.headers.etag;
+}
+
+// The reads teardown makes to prove the sitemap gone — by id, in each layer — the link, the app's row version, and the app gone after its delete.
+const PUBLISHED_SITEMAP = (id) => `/sitemaps?$select=sitemapid&$filter=sitemapid eq ${id}`;
+const SAVED_SITEMAP = (id) => `/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=sitemapid&$filter=sitemapid eq ${id}`;
+const LINK = (layer) => `/appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq ${layer} and componenttype eq 62`;
+const APP_ROW = (id) => `/appmodules(${id})?$select=appmoduleid`;
+const PUBLISHED_APP = (id) => `/appmodules?$select=appmoduleid&$filter=appmoduleid eq ${id}`;
+const SAVED_APP = (id) => `/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()?$select=appmoduleid&$filter=appmoduleid eq ${id}`;
+const proofReads = (app) => [PUBLISHED_SITEMAP(app.sitemapId), SAVED_SITEMAP(app.sitemapId), LINK(app.layer), APP_ROW(app.id), PUBLISHED_APP(app.id), SAVED_APP(app.id)];
+
+// What an ordinary teardown of this spec reads, by resource, in order: the page manifest's table and row; the app; the SDK's resolution of its sitemap (its
+// read of the app, its current layer, the link, the sitemap by id and in the saved layer, the layer and the link again, and the apps that name that
+// sitemap); then the generated web resources, the table the teardown keeps, and the solution.
+const ORDINARY_READS = [
+ 'GET EntityDefinitions', 'GET webresourceset', 'GET appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple', 'GET appmodules',
+ 'GET appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple', 'GET appmodulecomponents', 'GET sitemaps', 'GET sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple',
+ 'GET appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple', 'GET appmodulecomponents', 'GET appmodulecomponents', 'GET appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple',
+ 'GET webresourceset', 'GET webresourceset', 'GET EntityDefinitions', 'GET solutions',
+];
+// What the teardown of an app with a dangling link reads: the ordinary reads up to the SDK's refusal (its saved-layer read of the sitemap answers no
+// row); the app's row version, read BEFORE the proof so that the delete is conditioned on the app as it was proven; the proof — the app's current
+// layer and its link, the sitemap in the published and the saved layer, the apps that name it, the layer and the link again; after the app's
+// delete, the app in the published and the saved layer; then the steps after the app, as ever.
+const DANGLING_READS = [
+ ...ORDINARY_READS.slice(0, 8),
+ 'GET appmodules',
+ 'GET appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple', 'GET appmodulecomponents', 'GET sitemaps', 'GET sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple',
+ 'GET appmodulecomponents', 'GET appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple', 'GET appmodulecomponents',
+ 'GET appmodules', 'GET appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple',
+ ...ORDINARY_READS.slice(12),
+];
+
+// A measured step ran: it did not throw, and every request it sent is one the fake models.
+function ran(step, label) {
+ assert.ok(step, `${label} ran`);
+ if (step.error) throw step.error;
+ assert.deepEqual(step.unexpected, [], `every request ${label} sent is one the fake models`);
+ return step;
+}
+
+// Back where the environment started, but for the publisher the build made for the prefix (teardown never deletes a publisher), and nothing the
+// environment had before was touched (the proof the lifecycle matrix makes of a whole teardown).
+function backToSeed(env) {
+ const after = env.org.inventory();
+ const made = after.rows.publishers.filter((p) => !env.seed.inventory.rows.publishers.includes(p));
+ assert.equal(made.length, 1, 'the one row left that the environment did not have is the build\'s publisher');
+ assert.deepEqual({ ...after, rows: { ...after.rows, publishers: after.rows.publishers.filter((p) => !made.includes(p)) } }, env.seed.inventory, 'everything the build made is gone, and nothing the environment had is missing');
+ assert.deepEqual(diffContents(env.seed.contents, env.org.contents(), { added: false }), [], 'nothing the environment had before was touched');
+}
+
+// The SDK's own refusal for an app whose sitemap is gone, word for word.
+const sdkRefusal = (app) => `Refusing to delete app '${app.id}': sitemap '${app.sitemapId}' was not returned by the unpublished-aware read. Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`;
+
+// --- 1. the SDK's refusal ----------------------------------------------------------------------------------------------------------------------------------
+
+test('the SDK refuses to delete an app whose sitemap is gone, in the one shape teardown recognises — and no other refusal is taken for it', async () => {
+ const env = environment();
+ const app = await built(env);
+ await strand(env, app);
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(makeTempDir('teardown-dangling-sdk-')), instanceUrl: env.org.origin, httpClient: env.harness.client });
+ await sdk.initWorkspace();
+ const mark = env.org.mark();
+ const refused = await sdk.deleteAppCascade(app.id, app.layer).then(() => null, (e) => e);
+ assert.ok(refused, 'the SDK refuses');
+ assert.equal(refused.code, 'APP_SITEMAP_UNRESOLVED');
+ assert.equal(refused.message, sdkRefusal(app));
+ assert.deepEqual(env.org.writes(mark), [], 'and writes nothing');
+ assert.deepEqual(dangling().danglingSitemapOf(refused, app.id), { sitemapId: app.sitemapId }, 'teardown recognises it, for this app');
+ assert.deepEqual(dangling().danglingSitemapOf(refused, app.id.toUpperCase()), { sitemapId: app.sitemapId }, 'however the app id is spelled');
+ assert.equal(dangling().danglingSitemapOf(refused, OTHER_APP), null, 'and never as the refusal of another app');
+ // The SDK raises the same code for every way its resolution of the sitemap can fail; each other one is the SDK's to explain, and stays as it is.
+ for (const message of [
+ `Refusing to delete app '${app.id}': its sitemap link changed while it was read (sitemap '${app.sitemapId}' by component, then '${ELSEWHERE}' by component). Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`,
+ `Refusing to delete app '${app.id}': reading sitemap '${app.sitemapId}' returned HTTP 503. Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`,
+ `Refusing to delete app '${app.id}': its current layer carries 2 SiteMap components, where an app can hold one, so it cannot be determined which sitemap is this app's. Nothing was deleted. Retry.`,
+ ]) assert.equal(dangling().danglingSitemapOf({ code: 'APP_SITEMAP_UNRESOLVED', message }, app.id), null, message);
+ assert.equal(dangling().danglingSitemapOf({ code: 'APP_SITEMAP_SHARED', message: refused.message }, app.id), null, 'nor another code with the same words');
+ assert.equal(dangling().danglingSitemapOf(new Error(refused.message), app.id), null, 'nor an error with no code');
+ assert.deepEqual(env.org.unexpected, []);
+});
+
+// --- 2. a dangling link: the app alone -------------------------------------------------------------------------------------------------------------------
+
+test('a dangling link on this spec\'s own app: teardown deletes exactly that app, alone and conditioned on its row version, proves it gone in both layers, and finishes', async () => {
+ const env = environment();
+ const app = await built(env);
+ await strand(env, app);
+ const version = await rowVersion(env.org, app.id);
+ const run = ran(await env.harness.measure(() => env.harness.teardown(spec())), 'the teardown');
+ const { result, log } = run.value;
+ assert.equal(result.ok, true, JSON.stringify(result.errors));
+ assert.deepEqual(result.deleted.app, [app.id], 'the app step deleted that app');
+
+ const writes = env.org.writes(run.mark);
+ assert.deepEqual(writes.filter((w) => /^\/(appmodules|sitemaps|\$batch)\b/.test(w.path)).map((w) => `${w.method} ${w.path}${w.batched ? ' (in a change set)' : ''}`), [`DELETE /appmodules(${app.id})`], 'one request: the app, alone');
+ assert.ok(!writes.some((w) => /sitemap/i.test(w.path)), 'no sitemap is written, let alone deleted');
+ const appDelete = writes.find((w) => w.path === `/appmodules(${app.id})`);
+ const ifMatch = Object.entries(appDelete.headers || {}).find(([k]) => k.toLowerCase() === 'if-match');
+ assert.deepEqual(ifMatch && ifMatch[1], version, 'conditioned on the row version the app had');
+ assert.deepEqual(run.writes, { 'DELETE appmodules': 1, 'DELETE webresourceset': 1, 'DELETE solutions': 1 }, 'an ordinary teardown\'s writes, but for the sitemap, which was already gone');
+
+ // The proof came first, by id in each layer, and the app was read again in both layers after its delete.
+ const sent = env.org.since(run.mark).map((r) => `${r.method} ${r.path}`);
+ const at = (line) => { const i = sent.indexOf(line); assert.ok(i > -1, `sent: ${line}`); return i; };
+ const deleted = at(`DELETE /appmodules(${app.id})`);
+ for (const read of [PUBLISHED_SITEMAP(app.sitemapId), SAVED_SITEMAP(app.sitemapId), LINK(app.layer), APP_ROW(app.id)]) assert.ok(at(`GET ${read}`) < deleted, `${read} before the delete`);
+ for (const read of [PUBLISHED_APP(app.id), SAVED_APP(app.id)]) assert.ok(at(`GET ${read}`) > deleted, `${read} after the delete`);
+ assert.ok(at(`GET ${APP_ROW(app.id)}`) < at(`GET ${LINK(app.layer)}`), 'the app\'s row version is read BEFORE the proof begins: the delete is conditioned on the app as it was proven');
+ assert.equal(sent.filter((line) => line === `GET ${LINK(app.layer)}`).length, 2, 'the link is read again after the sitemap, as the SDK reads it again');
+ assert.deepEqual(env.org.readNames(run.mark), DANGLING_READS);
+ assert.equal(run.end - run.mark, 25, 'the reads, the app\'s delete, and the two deletes after it');
+
+ assert.equal(env.org.rowsOf('appmodules').has(app.id), false, 'the app is gone');
+ backToSeed(env);
+ // Said once, in the result and in the log: the app went without its sitemap, and why.
+ assert.equal((result.warnings || []).length, 1, JSON.stringify(result.warnings));
+ assert.match(result.warnings[0], new RegExp(`^app "${APP_NAME}" \\(${app.id}\\) was deleted without its sitemap: its navigation link named sitemap ${app.sitemapId}, which is in neither the published nor the saved layer .*no sitemap was touched`));
+ assert.ok(log.some((line) => line.includes(`⚠ teardown warning: ${result.warnings[0]}`)), 'and the log says it');
+ assert.ok(log.some((line) => /^✓ teardown complete — /.test(line.trim())), 'the teardown completes');
+});
+
+// The platform's answer to a delete conditioned on a version the row no longer has, and the final refusal teardown makes of it.
+const VERSION_MOVED = "The version of the existing record doesn't match the RowVersion property provided.";
+const versionMoved = (app, name = APP_NAME) => `app "${name}" (${app.id}) was not deleted: its sitemap ${app.sitemapId} is gone, but the app changed while teardown was proving that, so the platform refused a delete conditioned on the version the proof began at (HTTP 412: 0x80060882 ${VERSION_MOVED}). Nothing was deleted. Run the teardown again: it proves the app as it is now before it deletes anything.`;
+const notAttempted = (result) => result.skipped.length > 0 && result.skipped.every((line) => / \(not attempted — the app was not deleted\)$/.test(line));
+
+test('a dangling link, and the platform refuses the app\'s delete on its row version (412): a final refusal — nothing is deleted, no step after the app is attempted, and nothing asks for a retry', async () => {
+ const env = environment();
+ const app = await built(env);
+ await strand(env, app);
+ const refused = env.add('DELETE', (w) => w === `/appmodules(${app.id})`, refusedWith(412, '0x80060882', VERSION_MOVED));
+ const before = env.org.contents();
+ const run = ran(await env.harness.measure(() => env.harness.teardown(spec())), 'the teardown');
+ const { result } = run.value;
+ assert.equal(refused.hits, 1, 'the app\'s delete was sent once');
+ assert.equal(result.ok, false);
+ assert.deepEqual(env.org.contents(), before, 'the environment holds exactly what it held');
+ assert.deepEqual(result.errors, [{ step: `app module "${APP_NAME}"`, message: versionMoved(app) }]);
+ assert.doesNotMatch(result.errors[0].message, /\bretry\b/i);
+ assert.ok(notAttempted(result), JSON.stringify(result.skipped));
+});
+
+test('a dangling link, and the app cannot be read back after its delete: the steps that depend on it wait, and the teardown run again finds the app gone and finishes', async () => {
+ const env = environment();
+ const app = await built(env);
+ await strand(env, app);
+ const unreadable = env.add('GET', (w) => w === PUBLISHED_APP(app.id), refusedWith(503, '0x80040216', 'Service Unavailable'));
+ const first = ran(await env.harness.measure(() => env.harness.teardown(spec())), 'the teardown');
+ // The client sends a read that answers 503 again before it gives up (lib/sdk-http-client.js), so the fault is met more than once.
+ assert.ok(unreadable.hits >= 1, 'the app was read back');
+ assert.equal(first.value.result.ok, false);
+ assert.equal(env.org.rowsOf('appmodules').has(app.id), false, 'the delete ran');
+ assert.deepEqual(first.writes, { 'DELETE appmodules': 1 }, 'and nothing after it');
+ const [error] = first.value.result.errors;
+ assert.match(error.message, new RegExp(`^app "${APP_NAME}" \\(${app.id}\\): its sitemap ${app.sitemapId} is gone and the app's delete was sent \\(HTTP 204\\), but whether the app is gone could not be read \\(.*HTTP 503.*\\), so the steps that depend on it are not attempted\\. Run the teardown again: `));
+ assert.ok(first.value.result.skipped.every((line) => / \(not attempted — the app was not deleted\)$/.test(line)), JSON.stringify(first.value.result.skipped));
+
+ // The read answers again, as an environment does once it is back.
+ unreadable.matches = () => false;
+ const again = ran(await env.harness.measure(() => env.harness.teardown(spec())), 'the teardown run again');
+ assert.equal(again.value.result.ok, true, JSON.stringify(again.value.result.errors));
+ assert.deepEqual(again.writes, { 'DELETE webresourceset': 1, 'DELETE solutions': 1 }, 'the rest, and no app or sitemap write');
+ backToSeed(env);
+});
+
+// The strict fake does not apply If-Match to a DELETE, so this seam applies the platform's documented rule to the app's delete: a delete conditioned
+// on a version the row no longer has is refused — 412 0x80060882 — and changes nothing. An app's read by id answers its version as W/"<n>"
+// (helpers/fake-lifecycle-org.js), the token such a delete carries.
+// See: https://learn.microsoft.com/power-apps/developer/data-platform/webapi/perform-conditional-operations-using-web-api#apply-optimistic-concurrency
+function honourIfMatch(env, app) {
+ return env.add('DELETE', (w) => w === `/appmodules(${app.id})`, (req) => {
+ const sent = Object.entries(req.headers || {}).find(([name]) => name.toLowerCase() === 'if-match');
+ const row = env.org.rowsOf('appmodules').get(app.id);
+ if (sent && row && sent[1] !== `W/"${row.version}"`) return refusedWith(412, '0x80060882', VERSION_MOVED)();
+ return env.org.request(req);
+ });
+}
+
+test('a dangling link the app is repaired from while teardown proves it — relinked to a new sitemap and published right after teardown\'s last read of its link: the delete, conditioned on the version the proof began at, is refused, and the app, its new sitemap and every step after the app stay', async () => {
+ const env = environment();
+ const app = await built(env);
+ await strand(env, app);
+ const REPAIRED = '55555555-5555-4555-8555-555555555555';
+ let linkReads = 0;
+ env.add('GET', (w) => w === LINK(app.layer), async (req) => {
+ linkReads += 1;
+ const answer = await env.org.request(req);
+ if (linkReads === 2) {
+ // Another maker repairs the app the moment teardown has read its link the second, last time: a new sitemap, the app linked to it in place
+ // of the one that is gone, and the app published. Each is a change of THIS app, and each moves its row version.
+ await direct(env.org, 'POST', '/sitemaps', { sitemapid: REPAIRED, sitemapname: 'Repaired', sitemapnameunique: 'contoso_repaired', sitemapxml: '<SiteMap><Area Id="a"><Group Id="g"><SubArea Id="s" Url="https://contoso.example/repaired" /></Group></Area></SiteMap>' });
+ await direct(env.org, 'POST', '/RemoveAppComponents', { AppId: app.id, Components: [{ '@odata.type': 'Microsoft.Dynamics.CRM.sitemap', sitemapid: app.sitemapId }] });
+ await direct(env.org, 'POST', '/AddAppComponents', { AppId: app.id, Components: [{ '@odata.type': 'Microsoft.Dynamics.CRM.sitemap', sitemapid: REPAIRED }] });
+ await direct(env.org, 'POST', '/PublishXml', { ParameterXml: `<importexportxml><appmodules><appmodule>${app.id}</appmodule></appmodules></importexportxml>` });
+ }
+ return answer;
+ });
+ const appDelete = honourIfMatch(env, app);
+ const run = ran(await env.harness.measure(() => env.harness.teardown(spec())), 'the teardown');
+ const { result } = run.value;
+ assert.equal(linkReads, 2, 'the repair came after teardown\'s second, last read of the link');
+ assert.equal(result.ok, false, 'the repaired app is not deleted');
+ assert.equal(env.org.rowsOf('appmodules').has(app.id), true, 'the app is still there');
+ assert.equal(env.org.find('sitemaps', (s) => String(s.sitemapid).toLowerCase() === REPAIRED).length, 1, 'so is its new sitemap');
+ assert.equal(env.org.find('appmodulecomponents', (c) => String(c.objectid).toLowerCase() === REPAIRED && Number(c.componenttype) === 62).length, 1, 'still its navigation');
+ assert.equal(appDelete.hits, 1, 'the app\'s delete was sent once');
+ assert.deepEqual(env.org.writes(run.mark).filter((w) => w.method === 'DELETE'), [], 'no delete reached the environment');
+ assert.deepEqual(result.errors, [{ step: `app module "${APP_NAME}"`, message: versionMoved(app) }]);
+ assert.ok(notAttempted(result), JSON.stringify(result.skipped));
+});
+
+test('an app whose display name reads like a platform refusal ("System Managed Ops"), with a dangling link teardown cannot prove gone: the refusal is not taken for an undeletable artifact — nothing is written, and no step after the app is attempted', async () => {
+ const env = environment();
+ const NAMED = 'System Managed Ops';
+ const app = await built(env, spec(NAMED));
+ await strand(env, app);
+ const fault = env.add('GET', (w) => w === SAVED_SITEMAP(app.sitemapId), refusedWith(403, '0x80040220', 'The user is not a member of the organization.'));
+ const before = env.org.contents();
+ const run = ran(await env.harness.measure(() => env.harness.teardown(spec(NAMED))), 'the teardown');
+ const { result } = run.value;
+ assert.equal(result.ok, false, 'the app step failed, and was not skipped as undeletable');
+ assert.deepEqual(env.org.writes(run.mark), [], 'not one write: no web resource, no solution');
+ assert.deepEqual(env.org.contents(), before, 'the environment holds exactly what it held');
+ assert.equal(result.errors.length, 1, JSON.stringify(result.errors));
+ assert.equal(result.errors[0].step, `app module "${NAMED}"`);
+ assert.match(result.errors[0].message, new RegExp(`^app "${NAMED}" \\(${app.id}\\) was not deleted: .*the saved layer could not be read \\(.*HTTP 403`));
+ assert.ok(notAttempted(result), JSON.stringify(result.skipped));
+ assert.ok(fault.hits >= 1, 'the read teardown could not use was sent');
+});
+
+// A read back refused with words that say "not found" — an OData 404 of a proxy or of the service:
+// { "error": { "code": "0x80060888", "message": "Resource not found for the segment 'appmodules'." } }
+for (const [layer, readBack] of [['published', PUBLISHED_APP], ['saved', SAVED_APP]]) {
+ test(`a dangling link, and the app's read back in the ${layer} layer is refused with words that say "not found": the step fails rather than count as a delete, nothing that depends on the app is touched, and a run again finishes`, async () => {
+ const env = environment();
+ const app = await built(env);
+ await strand(env, app);
+ const proxy = env.add('GET', (w) => w === readBack(app.id), refusedWith(404, '0x80060888', "Resource not found for the segment 'appmodules'."));
+ const first = ran(await env.harness.measure(() => env.harness.teardown(spec())), 'the teardown');
+ assert.ok(proxy.hits >= 1, 'the app was read back');
+ assert.equal(first.value.result.ok, false, 'not counted as a delete');
+ assert.equal(env.org.rowsOf('appmodules').has(app.id), false, 'the delete ran');
+ assert.deepEqual(first.writes, { 'DELETE appmodules': 1 }, 'and nothing after it');
+ assert.equal(first.value.result.warnings, undefined, 'no note that the app went without its sitemap: that is not proven');
+ assert.match(first.value.result.errors[0].message, new RegExp(`^app "${APP_NAME}" \\(${app.id}\\): its sitemap ${app.sitemapId} is gone and the app's delete was sent \\(HTTP 204\\), but whether the app is gone could not be read \\(.*Resource not found for the segment 'appmodules'.*\\)`));
+ assert.ok(notAttempted(first.value.result), JSON.stringify(first.value.result.skipped));
+
+ proxy.matches = () => false;
+ const again = ran(await env.harness.measure(() => env.harness.teardown(spec())), 'the teardown run again');
+ assert.equal(again.value.result.ok, true, JSON.stringify(again.value.result.errors));
+ assert.deepEqual(again.writes, { 'DELETE webresourceset': 1, 'DELETE solutions': 1 }, 'the rest, and no app or sitemap write');
+ backToSeed(env);
+ });
+}
+
+// --- 3. a dangling link teardown cannot prove gone ---------------------------------------------------------------------------------------------------------
+
+// The words of a refusal for a sitemap teardown could not prove gone: why, after the rule (`words` is a pattern).
+const unproven = (words) => new RegExp(`Teardown deletes such an app on its own only once that sitemap is proven gone, and it could not prove it: ${words}`);
+
+// Each case: what goes wrong (arranged after the fixture step; a fault in front of the fake, or what the environment holds), and the words of
+// the refusal that say so. A case that answers in place of the fake returns its fault, which must have been hit.
+const UNPROVEN = [
+ {
+ title: 'the published layer cannot be read',
+ arrange: (env, app) => env.add('GET', (w) => w === PUBLISHED_SITEMAP(app.sitemapId), refusedWith(503, '0x80040216', 'Service Unavailable')),
+ why: () => unproven('the published layer could not be read \\(.*HTTP 503'),
+ },
+ {
+ title: 'the saved layer cannot be read',
+ arrange: (env, app) => env.add('GET', (w) => w === SAVED_SITEMAP(app.sitemapId), refusedWith(403, '0x80040220', 'The user is not a member of the organization.')),
+ why: () => unproven('the saved layer could not be read \\(.*HTTP 403'),
+ },
+ {
+ title: 'the saved layer answers with no list',
+ arrange: (env, app) => env.add('GET', (w) => w === SAVED_SITEMAP(app.sitemapId), answered(200, { value: 'none' })),
+ why: () => unproven('the saved layer could not be read \\(.*no readable result set'),
+ },
+ {
+ title: 'the saved layer answers a row of another sitemap',
+ arrange: (env, app) => env.add('GET', (w) => w === SAVED_SITEMAP(app.sitemapId), answered(200, { value: [{ sitemapid: ELSEWHERE }] })),
+ why: () => unproven('the saved layer answered a row that is not that sitemap\\.'),
+ },
+ {
+ title: 'the published layer still answers the sitemap',
+ arrange: (env, app) => env.add('GET', (w) => w === PUBLISHED_SITEMAP(app.sitemapId), answered(200, { value: [{ sitemapid: app.sitemapId }] })),
+ why: () => unproven('the published layer still holds it\\.'),
+ },
+ {
+ title: 'another app\'s current layer names the sitemap too',
+ arrange: async (env, app) => {
+ await direct(env.org, 'POST', '/appmodules', { appmoduleid: OTHER_APP, appmoduleidunique: OTHER_LAYER, uniquename: 'contoso_other', name: 'Other', clienttype: 4 });
+ await direct(env.org, 'POST', '/appmodulecomponents', { _appmoduleidunique_value: OTHER_LAYER, objectid: app.sitemapId, componenttype: 62, rootcomponentbehavior: 0 });
+ return null;
+ },
+ why: () => unproven(`the navigation of app '${OTHER_APP}' names it too\\.`),
+ },
+ {
+ title: 'the link changes while teardown reads it',
+ // Another writer relinks the app between teardown's two reads of the link: the second read answers the new link.
+ arrange: (env, app) => {
+ const fault = env.add('GET', (w) => w === LINK(app.layer), (req) => {
+ if (fault.hits === 2) env.org.rowsOf('appmodulecomponents').get(String(app.link.appmodulecomponentid).toLowerCase()).data.objectid = ELSEWHERE;
+ return env.org.request(req);
+ });
+ return fault;
+ },
+ why: (app) => unproven(`the link changed while teardown read it \\(sitemap ${app.sitemapId}, then sitemap ${ELSEWHERE}\\)\\.`),
+ relinks: true,
+ },
+ {
+ title: 'the app has no row version to make its delete conditional on',
+ arrange: (env, app) => env.add('GET', (w) => w === APP_ROW(app.id), refusedWith(404, '0x80040217', `appmodule With Id = ${app.id} Does Not Exist`)),
+ why: () => /Teardown deletes such an app on its own only with a delete conditioned on the app's row version, and it could not read one: its read by id answered HTTP 404: it was never published, or it was deleted meanwhile\. /,
+ },
+];
+
+for (const c of UNPROVEN) {
+ test(`a dangling link teardown cannot prove gone — ${c.title}: refused with what was found and what to do, never "Retry", and nothing is deleted`, async () => {
+ const env = environment();
+ const app = await built(env);
+ await strand(env, app);
+ const fault = await c.arrange(env, app);
+ const before = env.org.contents();
+ const run = ran(await env.harness.measure(() => env.harness.teardown(spec())), 'the teardown');
+ const { result } = run.value;
+ assert.equal(result.ok, false);
+ assert.deepEqual(env.org.writes(run.mark), [], 'not one write reached the environment');
+ const after = env.org.contents();
+ if (c.relinks) {
+ // The relink itself is the one change, and it is the fault's, not the teardown's.
+ const key = `row appmodulecomponents ${String(app.link.appmodulecomponentid).toLowerCase()}`;
+ delete before[key];
+ delete after[key];
+ }
+ assert.deepEqual(after, before, 'the environment holds exactly what it held');
+ assert.equal(env.org.rowsOf('appmodules').has(app.id), true, 'the app is still there');
+
+ assert.equal(result.errors.length, 1, JSON.stringify(result.errors));
+ const [error] = result.errors;
+ assert.equal(error.step, `app module "${APP_NAME}"`);
+ assert.match(error.message, new RegExp(`^app "${APP_NAME}" \\(${app.id}\\) was not deleted: its navigation link names sitemap ${app.sitemapId}, which the SDK could not read\\. `));
+ assert.match(error.message, c.why(app));
+ assert.match(error.message, /Nothing was deleted\. If this app is yours, delete it in Power Apps \(make\.powerapps\.com, Apps\), then run the teardown again: it removes the rest\.$/);
+ assert.doesNotMatch(error.message, /\bretry\b/i, 'a run again as it is changes nothing, so it is not asked for');
+ assert.ok(result.skipped.length > 0 && result.skipped.every((line) => / \(not attempted — the app was not deleted\)$/.test(line)), `every later step is not attempted: ${JSON.stringify(result.skipped)}`);
+ if (fault) assert.ok(fault.hits >= 1, 'the read teardown could not use was sent');
+ });
+}
+
+test('the refusal is final: it is marked so, the build\'s retry policy never runs it again, and the SDK\'s own refusal stays its cause', async () => {
+ const env = environment();
+ const app = await built(env);
+ await strand(env, app);
+ env.add('GET', (w) => w === SAVED_SITEMAP(app.sitemapId), refusedWith(503, '0x80040216', 'Service Unavailable'));
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(makeTempDir('teardown-dangling-sdk-')), instanceUrl: env.org.origin, httpClient: env.harness.client });
+ await sdk.initWorkspace();
+ const [item] = await KIND_HANDLERS.app.resolve(sdk, { uniqueName: APP });
+ assert.equal(item.id, app.id);
+ const error = await KIND_HANDLERS.app.del(sdk, item, { warnings: [] }).then(() => null, (e) => e);
+ assert.ok(error, 'the app step fails');
+ assert.equal(error.transient, false, 'marked final');
+ assert.equal(retryPolicyFor(error), RETRY.NEVER, 'even with a 503 in the read that failed: a run again proves nothing new on its own');
+ assert.doesNotMatch(error.message, /\bretry\b/i);
+ assert.equal(error.cause && error.cause.code, 'APP_SITEMAP_UNRESOLVED', 'the SDK\'s refusal is kept as its cause');
+ assert.equal(error.cause.message, sdkRefusal(app));
+});
+
+// Every error that leaves this path stops the teardown before what depends on the app, whatever its words: it is marked `failClosed`, which
+// deleteStep passes on before its shortcuts (below). A proof that cannot be made and a delete refused on a moved version are final as well.
+test('every error the dangling-link path throws is marked failClosed; a proof that cannot be made and a delete refused on its version are final', async () => {
+ const CASES = [
+ ['a proof that cannot be made', (env, app) => env.add('GET', (w) => w === SAVED_SITEMAP(app.sitemapId), refusedWith(403, '0x80040220', 'The user is not a member of the organization.')), true],
+ ['a delete refused on its version', (env, app) => env.add('DELETE', (w) => w === `/appmodules(${app.id})`, refusedWith(412, '0x80060882', VERSION_MOVED)), true],
+ ['a delete answered with no change', (env, app) => env.add('DELETE', (w) => w === `/appmodules(${app.id})`, refusedWith(400, '0x80040216', 'An unexpected error occurred.')), false],
+ ['a read back that cannot be made', (env, app) => env.add('GET', (w) => w === PUBLISHED_APP(app.id), refusedWith(404, '0x80060888', "Resource not found for the segment 'appmodules'.")), false],
+ ];
+ for (const [what, arrange, final] of CASES) {
+ const env = environment();
+ const app = await built(env);
+ await strand(env, app);
+ arrange(env, app);
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(makeTempDir('teardown-dangling-sdk-')), instanceUrl: env.org.origin, httpClient: env.harness.client });
+ await sdk.initWorkspace();
+ const [item] = await KIND_HANDLERS.app.resolve(sdk, { uniqueName: APP });
+ const error = await KIND_HANDLERS.app.del(sdk, item, { warnings: [] }).then(() => null, (e) => e);
+ assert.ok(error, `${what}: the app step fails`);
+ assert.equal(error.failClosed, true, `${what}: marked failClosed`);
+ assert.doesNotMatch(error.message, /\bretry\b/i, what);
+ if (final) {
+ assert.equal(error.transient, false, `${what}: final`);
+ assert.equal(retryPolicyFor(error), RETRY.NEVER, what);
+ }
+ }
+});
+
+test('deleteStep: an error marked failClosed is passed on before every shortcut — not found, a dependency block, an undeletable artifact — and an unmarked one is read exactly as before', async () => {
+ const { deleteStep } = require('../lib/sdk-teardown.js');
+ const item = { id: 'a1', name: 'System Managed Ops' };
+ let asked = 0;
+ const handler = (error, extra = {}) => ({ del: async () => { throw error; }, confirmAbsent: async () => { asked += 1; return true; }, ...extra });
+ // Unmarked, as before: words that say "not found", once the platform confirms the row absent, are a deletion; a dependency block is a skip for a
+ // handler that tolerates one; system-managed words are an undeletable skip.
+ assert.deepEqual(await deleteStep({}, handler(new Error('appmodule With Id = a1 Does Not Exist')), [item]), { deletedIds: ['a1'], absentIds: [], skippedIds: [], skipped: [] });
+ assert.equal(asked, 1);
+ assert.deepEqual(await deleteStep({}, handler(new Error('The uxagentproject component cannot be deleted because it is referenced by 1 other components.'), { tolerateDependencyBlock: true }), [item]),
+ { deletedIds: [], absentIds: [], skippedIds: ['a1'], skipped: [{ id: 'a1', reason: 'referenced' }] });
+ assert.deepEqual(await deleteStep({}, handler(new Error('The view is system-managed and cannot be deleted.')), [item]), { deletedIds: [], absentIds: [], skippedIds: ['a1'], skipped: [{ id: 'a1', reason: 'undeletable' }] });
+ // Marked: passed on as it is, and nothing is asked of the platform about it.
+ for (const [words, extra] of [
+ ['appmodule With Id = a1 Does Not Exist', {}],
+ ['The uxagentproject component cannot be deleted because it is referenced by 1 other components.', { tolerateDependencyBlock: true }],
+ ['app "System Managed Ops" (a1) was not deleted', {}],
+ ]) {
+ const marked = Object.assign(new Error(words), { failClosed: true });
+ await assert.rejects(deleteStep({}, handler(marked, extra), [item]), (e) => e === marked, words);
+ }
+ const status404 = Object.assign(new Error('HTTP 404'), { statusCode: 404, failClosed: true });
+ await assert.rejects(deleteStep({}, handler(status404, { tolerateNotFound: true }), [item]), (e) => e === status404, 'a marked 404 even where not-found is tolerated');
+ assert.equal(asked, 1, 'confirmAbsent was never asked about a marked error');
+});
+
+// --- 4. what is unchanged ----------------------------------------------------------------------------------------------------------------------------------
+
+test('unchanged: an ordinary teardown sends exactly the requests it sent before — the app and its sitemap in one change set — and none of the dangling-link proof', async () => {
+ const env = environment();
+ const app = await built(env);
+ const run = ran(await env.harness.measure(() => env.harness.teardown(spec())), 'the teardown');
+ const { result } = run.value;
+ assert.equal(result.ok, true, JSON.stringify(result.errors));
+ assert.deepEqual(run.writes, { 'DELETE appmodules': 1, 'DELETE sitemaps': 1, 'DELETE webresourceset': 1, 'DELETE solutions': 1 });
+ assert.deepEqual(env.org.writes(run.mark).filter((w) => /^\/(appmodules|sitemaps)\(/.test(w.path)).map((w) => `${w.method} ${w.path} ${w.batched ? 'in a change set' : 'alone'}`),
+ [`DELETE /appmodules(${app.id}) in a change set`, `DELETE /sitemaps(${app.sitemapId}) in a change set`]);
+ assert.deepEqual(env.org.readNames(run.mark), ORDINARY_READS);
+ assert.equal(run.reads, 16);
+ assert.equal(run.end - run.mark, 19, 'requests in all');
+ const sent = env.org.since(run.mark).map((r) => r.path);
+ for (const read of proofReads(app)) assert.ok(!sent.includes(read), `not sent: ${read}`);
+ assert.equal(result.warnings, undefined, 'and nothing to warn about');
+ backToSeed(env);
+});
+
+test('unchanged: a sitemap another app\'s current layer shares is refused by the SDK in its own words, with the same reads and no write', async () => {
+ const env = environment();
+ const app = await built(env);
+ await direct(env.org, 'POST', '/appmodules', { appmoduleid: OTHER_APP, appmoduleidunique: OTHER_LAYER, uniquename: 'contoso_other', name: 'Other', clienttype: 4 });
+ await direct(env.org, 'POST', '/appmodulecomponents', { _appmoduleidunique_value: OTHER_LAYER, objectid: app.sitemapId, componenttype: 62, rootcomponentbehavior: 0 });
+ const before = env.org.contents();
+ const run = ran(await env.harness.measure(() => env.harness.teardown(spec())), 'the teardown');
+ const { result } = run.value;
+ assert.equal(result.ok, false);
+ assert.deepEqual(result.errors, [{ step: `app module "${APP_NAME}"`, message: `Refusing to delete app '${app.id}': its sitemap '${app.sitemapId}' is also the navigation of app '${OTHER_APP}'. The delete removes an app's sitemap with it, and the platform does not stop that for a sitemap another app uses, so those apps would be left without navigation. Nothing was deleted. Remove the sitemap from the other app first, then retry.` }]);
+ assert.deepEqual(env.org.writes(run.mark), []);
+ assert.deepEqual(env.org.contents(), before);
+ assert.deepEqual(env.org.readNames(run.mark), [...ORDINARY_READS.slice(0, 12), ...Array(3).fill('GET appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple')]);
+ const sent = env.org.since(run.mark).map((r) => r.path);
+ for (const read of proofReads(app)) assert.ok(!sent.includes(read), `not sent: ${read}`);
+});
+
+test('unchanged: a link that changes while the SDK reads it is refused by the SDK in its own words, with the same reads and no write', async () => {
+ const env = environment();
+ const app = await built(env);
+ await direct(env.org, 'POST', '/sitemaps', { sitemapid: ELSEWHERE, sitemapname: 'Elsewhere', sitemapnameunique: 'contoso_elsewhere', sitemapxml: '<SiteMap><Area Id="a"><Group Id="g"><SubArea Id="s" Url="https://contoso.example/elsewhere" /></Group></Area></SiteMap>' });
+ // The SDK reads the link twice, around its read of the sitemap; another writer relinks the app between the two.
+ const sdkLink = `/appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq ${app.layer} and componenttype eq 62`;
+ const fault = env.add('GET', (w) => w === sdkLink, (req) => {
+ if (fault.hits === 2) env.org.rowsOf('appmodulecomponents').get(String(app.link.appmodulecomponentid).toLowerCase()).data.objectid = ELSEWHERE;
+ return env.org.request(req);
+ });
+ const run = ran(await env.harness.measure(() => env.harness.teardown(spec())), 'the teardown');
+ const { result } = run.value;
+ assert.equal(fault.hits, 2);
+ assert.equal(result.ok, false);
+ assert.deepEqual(result.errors, [{ step: `app module "${APP_NAME}"`, message: `Refusing to delete app '${app.id}': its sitemap link changed while it was read (sitemap '${app.sitemapId}' by component, then '${ELSEWHERE}' by component). Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.` }]);
+ assert.deepEqual(env.org.writes(run.mark), []);
+ assert.deepEqual(env.org.readNames(run.mark), [...ORDINARY_READS.slice(0, 11), ...Array(2).fill('GET appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple')]);
+ const sent = env.org.since(run.mark).map((r) => r.path);
+ for (const read of proofReads(app)) assert.ok(!sent.includes(read), `not sent: ${read}`);
+});
+
+test('unchanged: a SiteMap component the SDK cannot read is refused by the SDK in its own words, and nothing is written or read for the dangling-link proof', async () => {
+ const env = environment();
+ const app = await built(env);
+ const sdkLink = `/appmodulecomponents?$select=objectid&$filter=_appmoduleidunique_value eq ${app.layer} and componenttype eq 62`;
+ const fault = env.add('GET', (w) => w === sdkLink, refusedWith(403, '0x80040220', 'The user is not a member of the organization.'));
+ const before = env.org.contents();
+ const run = ran(await env.harness.measure(() => env.harness.teardown(spec())), 'the teardown');
+ const { result } = run.value;
+ assert.equal(fault.hits, 1);
+ assert.equal(result.ok, false);
+ assert.equal(result.errors.length, 1);
+ assert.match(result.errors[0].message, new RegExp(`^Refusing to delete app '${app.id}': reading its SiteMap component failed \\(.*HTTP 403.*\\), so it cannot be determined which sitemap is this app's\\. Nothing was deleted\\. Retry\\.$`));
+ assert.deepEqual(env.org.writes(run.mark), []);
+ assert.deepEqual(env.org.contents(), before);
+ const sent = env.org.since(run.mark).map((r) => r.path);
+ for (const read of proofReads(app)) assert.ok(!sent.includes(read), `not sent: ${read}`);
+});
+
+test('unchanged: an app with no SiteMap component whose namesake sitemap is another app\'s navigation is refused by the SDK in its own words, with no write', async () => {
+ const env = environment();
+ const app = await built(env);
+ const [sitemap] = env.org.find('sitemaps', (s) => String(s.sitemapid).toLowerCase() === app.sitemapId);
+ assert.equal(sitemap.sitemapnameunique, APP, 'the build names the app\'s sitemap like the app');
+ await direct(env.org, 'DELETE', `/appmodulecomponents(${app.link.appmodulecomponentid})`);
+ await direct(env.org, 'POST', '/appmodules', { appmoduleid: OTHER_APP, appmoduleidunique: OTHER_LAYER, uniquename: 'contoso_other', name: 'Other', clienttype: 4 });
+ await direct(env.org, 'POST', '/appmodulecomponents', { _appmoduleidunique_value: OTHER_LAYER, objectid: app.sitemapId, componenttype: 62, rootcomponentbehavior: 0 });
+ const before = env.org.contents();
+ const run = ran(await env.harness.measure(() => env.harness.teardown(spec())), 'the teardown');
+ const { result } = run.value;
+ assert.equal(result.ok, false);
+ assert.deepEqual(result.errors, [{ step: `app module "${APP_NAME}"`, message: `Refusing to delete app '${app.id}': its sitemap '${app.sitemapId}' is also the navigation of app '${OTHER_APP}'. The delete removes an app's sitemap with it, and the platform does not stop that for a sitemap another app uses, so those apps would be left without navigation. Nothing was deleted. Remove the sitemap from the other app first, then retry.` }]);
+ assert.deepEqual(env.org.writes(run.mark), []);
+ assert.deepEqual(env.org.contents(), before);
+ const sent = env.org.since(run.mark).map((r) => r.path);
+ for (const read of proofReads(app)) assert.ok(!sent.includes(read), `not sent: ${read}`);
+});
diff --git a/plugins/model-apps/scripts/tests/teardown-model-app.test.js b/plugins/model-apps/scripts/tests/teardown-model-app.test.js
index 97a4c3393..298510831 100644
--- a/plugins/model-apps/scripts/tests/teardown-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/teardown-model-app.test.js
@@ -10,6 +10,7 @@ const vm = require('node:vm');
const { teardownModelApp: engineTeardownModelApp, cliEmit } = require(path.join(__dirname, '..', 'teardown-model-app.js'));
const teardownModelApp = (spec, opts, deps) => engineTeardownModelApp(spec, { env: 'https://contoso.crm.dynamics.com', ...opts }, deps);
const { validateFlagsFromParsed } = require('./helpers/fake-auth.js');
+const { validateAppSpec } = require(path.join(__dirname, '..', 'lib', 'app-spec.js'));
const desk = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'samples', 'app-spec.support-desk.json'), 'utf8'));
@@ -110,6 +111,51 @@ test('apply --allow-destructive performs the deletes', async () => {
assert.ok(sdk.calls.some((c) => c.method === 'deleteAppCascade'), 'app deleted');
});
+// A key a form's `fieldOptions` entry does not take is refused by the build and the lint, but a release before that check
+// accepted it and built the form without the option. Teardown reads the spec under the structural profile, where that finding
+// is a warning, so an app built from such a spec is still torn down, behind the same authorization as any other.
+const FIELD_OPTION_TYPO = "form 'Ticket' (table new_ticket): unknown key 'readOnlyy' on fieldOptions['new_priority'] — did you mean 'readOnly'? (allowed: readOnly, hidden, after, colspan, rowspan)";
+function deskWithFieldOptionTypo() {
+ const spec = JSON.parse(JSON.stringify(desk));
+ spec.forms.find((f) => f.entity === 'new_ticket').fieldOptions = { new_priority: { readOnlyy: true } };
+ return spec;
+}
+
+test('a spec whose fieldOptions entry carries a key it does not take is still torn down: the dry run lists the same plan', async () => {
+ const structural = validateAppSpec(deskWithFieldOptionTypo(), { profile: 'structural' });
+ assert.deepStrictEqual([structural.ok, structural.errors, structural.warnings], [true, [], [FIELD_OPTION_TYPO]], 'the finding is a warning there');
+ const reads = [];
+ const r = await teardownModelApp(deskWithFieldOptionTypo(), { apply: false }, { sdk: { queryRecords: async (entity) => { reads.push(entity); return []; } } });
+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
+ assert.strictEqual(r.dryRun, true);
+ const plain = await teardownModelApp(desk, { apply: false }, { sdk: { queryRecords: async () => [] } });
+ assert.deepStrictEqual(r.plan, plain.plan, 'the plan of the same spec without the key');
+ assert.deepStrictEqual(reads, ['webresource']);
+});
+
+test('such a spec still needs --allow-destructive to be torn down, and with it the deletes run', async () => {
+ const held = presentSdk();
+ const refused = await teardownModelApp(deskWithFieldOptionTypo(), { apply: true }, { sdk: held });
+ assert.strictEqual(refused.ok, false);
+ assert.ok(refused.errors.some((e) => /requires --allow-destructive/.test(e)), JSON.stringify(refused.errors));
+ assert.ok(!refused.errors.some((e) => /unknown key/.test(e)), JSON.stringify(refused.errors));
+ assert.strictEqual(held.calls.length, 0, 'nothing was touched');
+ const sdk = presentSdk();
+ const r = await teardownModelApp(deskWithFieldOptionTypo(), { apply: true, allowDestructive: true }, { sdk });
+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
+ assert.ok(sdk.calls.some((c) => c.method === 'deleteAppCascade'), 'app deleted');
+});
+
+test('such a spec is still refused before any teardown for any other problem, and the fieldOptions key is no part of the refusal', async () => {
+ const spec = deskWithFieldOptionTypo();
+ spec.forms.push({ entity: 'new_missing', name: 'Ghost' });
+ const sdk = presentSdk();
+ const r = await teardownModelApp(spec, { apply: true, allowDestructive: true }, { sdk });
+ assert.strictEqual(r.ok, false);
+ assert.deepStrictEqual(r.errors, ["form references unknown entity 'new_missing'"]);
+ assert.strictEqual(sdk.calls.length, 0, 'no SDK calls on a bad spec');
+});
+
// REVERSED by #587 item 5, deliberately. This test used to assert that teardown CONTINUES after a
// failed app delete ("later steps still run after the app refusal"), on a best-effort rationale:
// one failure should not strand the rest. Deep lifecycle testing showed that is the wrong rule for
@@ -227,6 +273,30 @@ test('dry-run lists the plan with a ▢ marker and no summary', async () => {
await teardownModelApp(desk, { apply: false }, { sdk: throwing, log: cap.log });
assert.ok(cap.logs.some((l) => /\[\d+\/\d+\] ▢ /.test(l)), 'plan items use the ▢ marker');
assert.ok(!cap.logs.some((l) => /teardown complete/.test(l)), 'no summary on a dry-run');
+ assert.ok(!cap.logs.some((l) => /publisher/.test(l)), 'nor the publisher line, which belongs to the summary');
+});
+
+// A publisher is never deleted: the build reuses any publisher with the spec's prefix, and other solutions may share the one it made,
+// so nothing tells a teardown that this app alone uses it. A maker who checks the environment afterwards finds it there, so the
+// summary says so — one line, right after the closing count, on a clean run and on a failed one alike.
+const PUBLISHER_KEPT = "▸ the publisher with prefix 'new' is kept: teardown never deletes a publisher, which other solutions may share — delete it in Power Apps (Solutions → Publishers) once nothing uses it";
+test('the teardown summary says the publisher is kept, in one line after the closing count', async () => {
+ const clean = logCapture();
+ const sdk = presentSdk();
+ const r = await teardownModelApp(desk, { apply: true, allowDestructive: true }, { sdk, log: clean.log });
+ assert.strictEqual(r.ok, true, JSON.stringify(r.errors));
+ const closing = clean.logs.findIndex((l) => /teardown complete — /.test(l));
+ assert.ok(closing >= 0, clean.logs.join('\n'));
+ assert.deepStrictEqual(clean.logs.slice(closing + 1), [PUBLISHER_KEPT]);
+ assert.ok(!sdk.calls.some((c) => /publisher/i.test(JSON.stringify(c))), 'and nothing is asked of a publisher');
+
+ const failed = logCapture();
+ const refusing = presentSdk();
+ refusing.deleteWebResource = async () => { throw new Error('HTTP 500: boom'); };
+ const f = await teardownModelApp(desk, { apply: true, allowDestructive: true }, { sdk: refusing, log: failed.log });
+ assert.strictEqual(f.ok, false);
+ const closingFailed = failed.logs.findIndex((l) => /teardown finished with errors — /.test(l));
+ assert.deepStrictEqual(failed.logs.slice(closingFailed + 1), [PUBLISHER_KEPT]);
});
test('cliEmit: an error event with no detail has no dangling separator', () => {
diff --git a/plugins/model-apps/scripts/tests/teardown-navigation-proof-real-bundle.test.js b/plugins/model-apps/scripts/tests/teardown-navigation-proof-real-bundle.test.js
index 180d576d4..150590ee9 100644
--- a/plugins/model-apps/scripts/tests/teardown-navigation-proof-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/teardown-navigation-proof-real-bundle.test.js
@@ -26,6 +26,7 @@ const { runTeardown } = require('../lib/sdk-teardown.js');
const { manifestResourceName } = require('../lib/page-manifest.js');
const { createFakeAppsOrg, json } = require('./helpers/fake-apps-org.js');
const { assertGolden } = require('./helpers/golden.js');
+const { appSitemapLinkRows } = require('./helpers/app-sitemap-link-rows.js');
const ORIGIN = 'https://contoso.crm.dynamics.com';
const PAGE_A = '11111111-1111-4111-8111-111111111111';
@@ -67,8 +68,15 @@ async function world(t, { xml = navigation(entry(PAGE_A), entry(PAGE_B)), sitema
const first = org.state.sitemaps.find((row) => !id || row.sitemapid.toLowerCase() === id.toLowerCase());
return json(200, { value: first ? [first] : [] });
}
- // The app's sitemap, as a component of its layer: GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <layer key> and componenttype eq 62&$top=1
- if (req.method === 'GET' && req.path.startsWith('/appmodulecomponents')) return json(200, { value: componentLinked ? [{ objectid: SITEMAP, componenttype: 62 }] : [] });
+ if (req.method === 'GET') {
+ // The SDK reads this link in both directions: the reverse projection needs the layer id,
+ // not the objectid returned by the plugin's forward navigation lookup.
+ const linked = appSitemapLinkRows(`${ORIGIN}/api/data/v9.0${req.path}`, {
+ apps: org.state.apps,
+ components: componentLinked ? [{ _appmoduleidunique_value: LAYER, objectid: SITEMAP, componenttype: 62 }] : [],
+ });
+ if (linked !== undefined) return json(200, { value: linked });
+ }
if (req.method === 'GET' && req.path.startsWith('/webresourceset')) {
const name = (/name eq '([^']+)'/.exec(req.path) || [])[1];
if (name === manifestResourceName(APP_NAME)) return json(200, { value: [{ webresourceid: MANIFEST_ID, name, content: manifest }] });
@@ -382,20 +390,20 @@ for (const [route, setup] of PROOF_ROUTES) {
}
}
-// A published app costs exactly what it cost before: the same reads, in the same order, and the same writes — its sitemap is read in the published layer, and in the saved layer only for a page the published one does not
-// name, and a saved layer that cannot be read is tried again by the client and then reported. The three sequences are in golden/teardown-published-requests.txt (one section each, `METHOD path`, a `$batch` change set
-// taken apart). They were recorded from the teardown as it ran before the proof of a page was changed to read the entries of the navigation, so an extra look, or a lookup that is not needed, makes this fail. A teardown of
-// an app that was never published is the one that grew a read: its saved layer.
+// The SDK's delete now proves the current layer/component twice and reads the sitemap's reverse owner
+// plus that owner's current app: six reads replace one name lookup, net +5. The plugin's published/saved
+// navigation proof and every write stay unchanged. A refused saved-layer proof still stops before the
+// SDK delete and gains no reads. Pin all three sequences, not just a larger request ceiling.
const requestLog = (org) => org.requests.map((r) => (r.operations ? `${r.method} ${r.path} [${r.operations.map((op) => `${op.method} ${op.path}`).join(', ')}]` : `${r.method} ${r.path}`));
const REFUSED_SAVED_LAYER = (req) => (req.method === 'GET' && req.path.startsWith('/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple')
? json(503, { error: { message: 'Offline refusal' } }) : null);
const PUBLISHED_SCENARIOS = [
- ['its published navigation names both pages', { published: true }, { requests: 32, ok: true }],
- ['its published navigation names one page and its saved navigation, which is read for the other, names both', { published: true, xml: navigation(entry(PAGE_A)), answer: savedLayer(navigation(entry(PAGE_A), entry(PAGE_B))) }, { requests: 36, ok: true }],
+ ['its published navigation names both pages', { published: true }, { requests: 37, ok: true }],
+ ['its published navigation names one page and its saved navigation, which is read for the other, names both', { published: true, xml: navigation(entry(PAGE_A)), answer: savedLayer(navigation(entry(PAGE_A), entry(PAGE_B))) }, { requests: 41, ok: true }],
['its published navigation names one page and its saved navigation cannot be read', { published: true, xml: navigation(entry(PAGE_A)), answer: REFUSED_SAVED_LAYER }, { requests: 18, ok: false }],
];
-test('REAL BUNDLE: the requests a teardown of a published app makes — the reads of its sitemap in both layers, and every write — are exactly the ones it made before', async (t) => {
+test('REAL BUNDLE: published teardown pins the SDK identity proofs, unchanged navigation reads and every conditional write', async (t) => {
const sections = [];
for (const [what, options, expected] of PUBLISHED_SCENARIOS) {
const w = await world(t, options);
diff --git a/plugins/model-apps/scripts/tests/teardown-never-published-real-bundle.test.js b/plugins/model-apps/scripts/tests/teardown-never-published-real-bundle.test.js
index 750510be7..d6d56393c 100644
--- a/plugins/model-apps/scripts/tests/teardown-never-published-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/teardown-never-published-real-bundle.test.js
@@ -21,6 +21,7 @@ const { runTeardown } = require('../lib/sdk-teardown.js');
const { manifestResourceName } = require('../lib/page-manifest.js');
const { createApp } = require('../apps.js');
const { createFakeAppsOrg, json } = require('./helpers/fake-apps-org.js');
+const { appSitemapLinkRows } = require('./helpers/app-sitemap-link-rows.js');
const ORIGIN = 'https://contoso.crm.dynamics.com';
const PAGE_A = '0f8fad5b-d9cb-469f-a165-70867728950e'; // in the app's navigation, published
@@ -46,8 +47,15 @@ async function scenario(t, { publish = false, refuse = () => null, inNavigation
answer: (req) => {
const refused = armed ? refuse(req) : null;
if (refused) return refused;
- // The app's sitemap, as a component of its layer: GET /appmodulecomponents?$select=objectid,componenttype&$filter=_appmoduleidunique_value eq <layer key> and componenttype eq 62&$top=1
- if (req.method === 'GET' && req.path.startsWith('/appmodulecomponents')) return json(200, { value: [{ objectid: made.sitemapId, componenttype: 62 }] });
+ if (req.method === 'GET') {
+ // After create, model the actual pin on this app's layer for both the forward lookup and
+ // the SDK's reverse-owner proof. Unrelated component reads are not answered here.
+ const linked = appSitemapLinkRows(`${ORIGIN}/api/data/v9.0${req.path}`, {
+ apps: org.state.apps,
+ components: made.sitemapId ? [{ _appmoduleidunique_value: LAYER, objectid: made.sitemapId, componenttype: 62 }] : [],
+ });
+ if (linked !== undefined) return json(200, { value: linked });
+ }
if (req.method === 'GET' && req.path.startsWith('/webresourceset')) {
const name = (/name eq '([^']+)'/.exec(req.path) || [])[1];
if (name === manifestResourceName(made.uniqueName)) return json(200, { value: [{ webresourceid: MANIFEST_ID, name, content: manifest() }] });
diff --git a/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js b/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js
index c2eb312a6..9acdab94d 100644
--- a/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js
+++ b/plugins/model-apps/scripts/tests/vendor-sdk-smoke.test.js
@@ -12,6 +12,7 @@ const fs = require('node:fs');
const BUNDLE = path.resolve(__dirname, '..', 'vendor', 'cds-maker-sdk.cjs');
// The migration's pure intent helpers, used to drive the generic surface in the CONTRACT tests below.
const { formEventsRegionIntent, findFieldCellPointer } = require('../lib/artifact-intent.js');
+const { appSitemapLinkRows } = require('./helpers/app-sitemap-link-rows.js');
// Every app the PLUGIN creates carries an icon: `ensureAppIcon` (sdk-build.js) resolves the author's
// `spec.app.icon` or generates an SVG web resource, and `appDef` passes its id as
@@ -353,8 +354,13 @@ test('CONTRACT: vendored deleteAppCascade returns a structured { success, delete
const ln = (url.match(/LogicalName='([^']+)'/) || [])[1] || 'x';
return { status: 200, headers: {}, body: { MetadataId: '33333333-3333-3333-3333-333333333333', EntitySetName: `${ln}s`, LogicalName: ln } };
}
- // The app row supplies the uniquename the sitemap is linked by + the ETag the conditional
- // delete is issued against; both are mandatory now (the SDK refuses to guess).
+ const linked = appSitemapLinkRows(url, {
+ apps: [{ appmoduleid: APP_ID, appmoduleidunique: APP_UNIQUE, componentstate: 0 }],
+ components: [{ _appmoduleidunique_value: APP_UNIQUE, objectid: SITEMAP_ID, componenttype: 62 }],
+ });
+ if (linked !== undefined) return { status: 200, headers: {}, body: { value: linked } };
+ // The by-id app row supplies the conditional delete's ETag; the current layer above supplies
+ // the actual type-62 sitemap identity. Neither can be guessed from a matching name.
if (/\/appmodules\([^)]+\)/.test(url)) {
return { status: 200, headers: {}, body: { '@odata.etag': 'W/"1"', appmoduleid: APP_ID, appmoduleidunique: APP_UNIQUE, uniquename: 'new_cascadeapp', name: 'Cascade App' } };
}
diff --git a/plugins/model-apps/scripts/tests/verify-model-app.test.js b/plugins/model-apps/scripts/tests/verify-model-app.test.js
index b01fbc485..bae2e7ac8 100644
--- a/plugins/model-apps/scripts/tests/verify-model-app.test.js
+++ b/plugins/model-apps/scripts/tests/verify-model-app.test.js
@@ -959,6 +959,36 @@ test('verify CLI still refuses a spec that is invalid for another reason — bef
assert.deepStrictEqual(reads, [], 'nothing was read');
});
+// --- a form whose fieldOptions entry carries a key it does not take -------------------------------------------------------------------
+// The build and the lint refuse a key a `fieldOptions` entry does not take, but a release before that check accepted one and built the form
+// without the option. Verification keeps the deploy profile, whose checks of forms and pages it relies on, and passes fieldOptionKeys: 'warn':
+// the finding is a warning that names the key and the option it most likely meant, and the verdict is the deployment's. The form of these specs
+// is not in the fake environment, so its check fails: what is pinned is that the check ran.
+const FIELD_OPTION_TYPO = "form 'Ticket' (table new_ticket): unknown key 'readOnlyy' on fieldOptions['new_ref'] — did you mean 'readOnly'? (allowed: readOnly, hidden, after, colspan, rowspan)";
+const withTypoForm = (spec) => ({ ...spec, forms: [{ entity: 'new_ticket', name: 'Ticket', fieldOptions: { new_ref: { readOnlyy: true } } }] });
+
+test('verify CLI still verifies the deployment of a form whose fieldOptions entry carries a key it does not take — and warns, naming the key', async () => {
+ const { reads, emitted, stderr } = await verifyOlderSpec(withTypoForm(appSpec({ columns: [column({ type: 'Text' })] })));
+ const result = JSON.parse(JSON.stringify(emitted.payload));
+ assert.ok(Number.isInteger(result.total) && result.total > 0 && Array.isArray(result.missing), `a verdict, not a refusal: ${JSON.stringify(result)}`);
+ assert.ok(reads.includes('columns new_ticket'), `the deployed columns were read: ${JSON.stringify(reads)}`);
+ assert.match(stderr, /^ {2}[✓✗] form: Ticket/m, 'the form was looked for in the deployment');
+ assert.ok(stderr.includes(`WARNING: ${FIELD_OPTION_TYPO}\n`), stderr);
+ assert.deepStrictEqual(result.warnings, [FIELD_OPTION_TYPO]);
+ assert.ok(!result.errors.some((e) => /unknown key/.test(e)), JSON.stringify(result.errors));
+});
+
+test('verify CLI still refuses such a spec for any other problem — before any read — and the fieldOptions key is no part of the refusal', async () => {
+ const spec = withTypoForm(appSpec({ columns: [column({ type: 'Text' }), column({ schemaName: 'new_bad', type: 'Nope' })] }));
+ const { reads, emitted, stderr } = await verifyOlderSpec(spec);
+ const result = JSON.parse(JSON.stringify(emitted.payload));
+ assert.strictEqual(emitted.ok, false);
+ assert.deepStrictEqual(result.errors, ["entity new_ticket: column new_bad has unknown type 'Nope'"]);
+ assert.deepStrictEqual(result.warnings, [FIELD_OPTION_TYPO]);
+ assert.ok(stderr.includes(`WARNING: ${FIELD_OPTION_TYPO}\n`), stderr);
+ assert.deepStrictEqual(reads, [], 'nothing was read');
+});
+
// --- the result JSON carries what stderr warns -----------------------------------------------------------------------------------------
// A person reads the `WARNING:` lines verify prints, but a caller that reads only the JSON result — a skill, a pipeline — lost them. The result's optional
// `warnings` array holds the same messages, without the prefix and in the order they were printed, and is left out when there is none, as `unverified` is.
diff --git a/plugins/model-apps/scripts/tests/verify-parallel-checks.test.js b/plugins/model-apps/scripts/tests/verify-parallel-checks.test.js
index 85d9be82b..6f0ffcd76 100644
--- a/plugins/model-apps/scripts/tests/verify-parallel-checks.test.js
+++ b/plugins/model-apps/scripts/tests/verify-parallel-checks.test.js
@@ -31,7 +31,12 @@ function richSpec() {
solution: { uniqueName: 'verify_checks', publisherPrefix: 'new' },
app: { name: 'Verify Checks', uniqueName: 'new_verifychecks' },
schemaVersion: 2,
- entities: TABLES.map((t) => ({ schemaName: t, columns: [{ schemaName: `${t}_a` }, { schemaName: `${t}_b` }] })),
+ entities: TABLES.map((t) => ({
+ schemaName: t,
+ columns: [{ schemaName: `${t}_a` }, { schemaName: `${t}_b` }],
+ // Two tables declare status reasons and alternate keys: their reads join the overlapped pass like any other.
+ ...(t === 'new_t0' || t === 'new_t1' ? { statusReasons: [{ label: 'Held' }], alternateKeys: [{ schemaName: `${t}_key`, columns: [`${t}_a`] }] } : {}),
+ })),
views: TABLES.map((t) => ({ entity: t, name: `Active ${t}` })),
charts: TABLES.slice(0, 3).map((t) => ({ entity: t, name: `Chart ${t}` })),
forms: TABLES.flatMap((t) => [
@@ -107,6 +112,9 @@ function richReader() {
sitemapXml: async () => sitemap,
entityRelationships: async () => [],
commandBar: async (entity) => entity !== 'new_t2',
+ // new_t1's status reason and key are not there, so the pass reports a mix of the new checks too.
+ statusReasons: async (entity) => ({ state: 'ok', options: [{ value: 1, state: 0, labels: ['Active'], shown: 'Active' }, ...(entity === 'new_t0' ? [{ value: 100000000, state: 0, labels: ['Held'], shown: 'Held' }] : [])] }),
+ alternateKeys: async (entity) => ({ state: 'ok', keys: entity === 'new_t0' ? [{ logicalName: 'new_t0_key', schemaName: 'new_t0_key', columns: ['new_t0_a'] }] : [] }),
appRoleIds: async () => ({ ok: true, roleIds: ['role-Agent'] }),
// Every persona holds the same table privilege, so the same two privilege sets are asked for by all of them.
entityPrivileges: async (entity) => [{ Name: `prvRead${entity}`, PrivilegeId: `${entity}-read`, PrivilegeType: 'Read' }],
@@ -128,7 +136,7 @@ test('the fixture reaches most of verify and reports a mix of passes and failure
const { result } = await runRich({ concurrency: 1 }, { latency: () => 0 });
const kinds = new Set(result.checks.map((c) => c.kind));
assert.ok(result.checks.length >= 60, `${result.checks.length} checks`);
- for (const kind of ['entity', 'column', 'view', 'chart', 'form', 'form-default', 'form-default-unique', 'form-order', 'form-order-served', 'relationship', 'command', 'business-rule', 'role', 'role-privileges', 'app-role', 'subarea', 'app-table-component', 'page', 'page-subarea']) {
+ for (const kind of ['entity', 'column', 'status-reason', 'alternate-key', 'view', 'chart', 'form', 'form-default', 'form-default-unique', 'form-order', 'form-order-served', 'relationship', 'command', 'business-rule', 'role', 'role-privileges', 'app-role', 'subarea', 'app-table-component', 'page', 'page-subarea']) {
assert.ok(kinds.has(kind), `the fixture should produce '${kind}' checks (got ${[...kinds].join(', ')})`);
}
assert.ok(result.checks.some((c) => c.present) && result.missing.length > 0, 'some checks pass and some fail');
diff --git a/plugins/model-apps/scripts/tests/verify-status-reasons-keys.test.js b/plugins/model-apps/scripts/tests/verify-status-reasons-keys.test.js
new file mode 100644
index 000000000..d12cad3a9
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/verify-status-reasons-keys.test.js
@@ -0,0 +1,385 @@
+'use strict';
+// Verify checks a table's STATUS REASONS and ALTERNATE KEYS (`entities[].statusReasons[]`, `entities[].alternateKeys[]`).
+//
+// Before, neither was checked: a status reason the build skipped because its value was already another reason's, one a maker renamed
+// or deleted, and an alternate key that was never made or was made over other columns all verified PASS. Now each declared one is a
+// check of its own, reported like the others — missing, or there but different — by name:
+// status-reason <table>.<label> present when one of the table's status reasons carries the label under the declared state
+// (Active unless the spec says Inactive), with the declared value when the spec pins one
+// alternate-key <table>.<schemaName> present when the table has a key of that name over exactly the declared columns
+// One read each, for a table that declares any, and none for a table that declares neither (the request pins below).
+const { test } = require('node:test');
+const assert = require('node:assert');
+const { verifySpec } = require('../lib/verify-spec.js');
+const { readerFor } = require('../verify-model-app.js');
+const { readChoiceAttributes } = require('../lib/view-filter-labels.js');
+const { statusReasonTargets } = require('../lib/entity-provision.js');
+const { instrument } = require('./helpers/read-probe.js');
+
+// A status option as the reader answers it: { value, state, labels, shown }.
+const option = (value, state, ...labels) => ({ value, state, labels, shown: labels[0] });
+const statusAnswer = (...options) => ({ state: 'ok', options });
+const key = (schemaName, columns) => ({ logicalName: schemaName.toLowerCase(), schemaName, columns });
+const keysAnswer = (...keys) => ({ state: 'ok', keys });
+
+// The two status reasons every table is made with: Active (1, state 0) and Inactive (2, state 1).
+const STOCK = [option(1, 0, 'Active'), option(2, 1, 'Inactive')];
+
+function reader({ statusReasons, alternateKeys, tables = ['new_o'] } = {}) {
+ return {
+ findTable: async (logical) => (tables.includes(logical) ? { logicalName: logical } : null),
+ findColumns: async () => [{ logicalName: 'new_email' }],
+ queryRecords: async () => [],
+ sitemapXml: async () => '',
+ ...(statusReasons ? { statusReasons } : {}),
+ ...(alternateKeys ? { alternateKeys } : {}),
+ };
+}
+const specOf = (entity) => ({ entities: [{ schemaName: 'new_o', columns: [], ...entity }], appShell: { areas: [] } });
+const checksOf = (r, kind) => r.checks.filter((c) => c.kind === kind).map((c) => [c.name, c.present, c.detail]);
+
+test('a status reason is present when the table holds its label under the declared state, and named when it does not', async () => {
+ const spec = specOf({
+ statusReasons: [
+ { label: 'In Review', state: 'Active' },
+ { label: 'Closed Won', state: 'Inactive' },
+ { label: 'Escalated' },
+ { label: 'Parked', state: 'Inactive' },
+ ],
+ });
+ const r = await verifySpec(spec, reader({
+ statusReasons: async () => statusAnswer(...STOCK, option(100000000, 0, 'In Review'), option(100000001, 0, 'Closed Won'), option(100000003, 1, 'Parked')),
+ }));
+ assert.deepStrictEqual(checksOf(r, 'status-reason'), [
+ ['new_o.In Review', true, ''],
+ ['new_o.Closed Won', false, 'a status reason of the Active state; the spec declares it under Inactive'],
+ ['new_o.Escalated', false, ''],
+ ['new_o.Parked', true, ''],
+ ]);
+ assert.strictEqual(r.ok, false);
+});
+
+test('an omitted or unknown authored status state defaults to Active, as the build makes it', async () => {
+ const spec = specOf({ statusReasons: [{ label: 'Escalated' }, { label: 'Odd', state: 'Pending' }] });
+ const r = await verifySpec(spec, reader({ statusReasons: async () => statusAnswer(...STOCK, option(100000000, 0, 'Escalated'), option(100000001, 0, 'Odd')) }));
+ assert.deepStrictEqual(checksOf(r, 'status-reason'), [['new_o.Escalated', true, ''], ['new_o.Odd', true, '']]);
+ assert.strictEqual(r.ok, true);
+});
+
+test('a pinned status reason value is held to: the label at another value is named with both', async () => {
+ const spec = specOf({ statusReasons: [{ label: 'On Hold', state: 'Active', value: 100000007 }, { label: 'Queued', value: 100000009 }] });
+ const r = await verifySpec(spec, reader({ statusReasons: async () => statusAnswer(...STOCK, option(100000000, 0, 'On Hold'), option(100000009, 0, 'Queued')) }));
+ assert.deepStrictEqual(checksOf(r, 'status-reason'), [
+ ['new_o.On Hold', false, 'its value is 100000000; the spec pins 100000007'],
+ ['new_o.Queued', true, ''],
+ ]);
+});
+
+test('a status reason renamed in the environment is named with the label its value carries — a build does not rename one', async () => {
+ // The build gives the first declared reason 100000000 and the second 100000001 (entity-provision.js), and inserts it again on a rebuild,
+ // which the platform refuses as "already exists" while another label holds the value — so the rename is never undone.
+ const spec = specOf({ statusReasons: [{ label: 'In Review' }, { label: 'Approved' }] });
+ const r = await verifySpec(spec, reader({ statusReasons: async () => statusAnswer(...STOCK, option(100000000, 0, 'Under Review')) }));
+ assert.deepStrictEqual(checksOf(r, 'status-reason'), [
+ ['new_o.In Review', false, "its value, 100000000, is the status reason 'Under Review' in the environment, and a build does not rename one"],
+ ['new_o.Approved', false, ''],
+ ]);
+});
+
+test('a status reason is found by its label in any language it is written in', async () => {
+ const spec = specOf({ statusReasons: [{ label: { 1033: 'In Review', 3082: 'En revisión' } }, { label: 'Abierto' }] });
+ const r = await verifySpec(spec, reader({ statusReasons: async () => statusAnswer(...STOCK, option(100000000, 0, 'In Review', 'En revisión'), option(100000001, 0, 'Open', 'Abierto')) }));
+ assert.deepStrictEqual(checksOf(r, 'status-reason'), [['new_o.In Review', true, ''], ['new_o.Abierto', true, '']]);
+});
+
+test('an alternate key is present when the table has a key of that name over exactly the declared columns, and named when not', async () => {
+ const spec = specOf({
+ alternateKeys: [
+ { schemaName: 'new_EmailKey', columns: ['new_Email'] },
+ { schemaName: 'new_codekey', columns: ['new_code', 'new_region'] },
+ { schemaName: 'new_pairkey', columns: ['new_a', 'new_b'] },
+ { schemaName: 'new_gonekey', columns: ['new_x'] },
+ { schemaName: 'new_twinkey', columns: ['new_y'] },
+ ],
+ });
+ const r = await verifySpec(spec, reader({
+ alternateKeys: async () => keysAnswer(
+ key('new_EmailKey', ['new_email']),
+ key('new_codekey', ['new_region']),
+ // The platform answers a key's columns in an order of its own (live: a key made over name, code read back as code, name).
+ key('new_pairkey', ['new_b', 'new_a']),
+ key('new_OtherKey', ['new_y']),
+ ),
+ }));
+ assert.deepStrictEqual(checksOf(r, 'alternate-key'), [
+ ['new_o.new_EmailKey', true, ''],
+ ['new_o.new_codekey', false, 'its columns are new_region; the spec declares new_code, new_region'],
+ ['new_o.new_pairkey', true, ''],
+ ['new_o.new_gonekey', false, ''],
+ ['new_o.new_twinkey', false, "a key over the same columns is there as 'new_OtherKey'"],
+ ]);
+ assert.strictEqual(r.ok, false);
+});
+
+test('a read that fails is a failed check with the reason — never a pass, and never the end of the run', async () => {
+ const spec = specOf({ statusReasons: [{ label: 'In Review' }], alternateKeys: [{ schemaName: 'new_emailkey', columns: ['new_email'] }] });
+ const answered = await verifySpec(spec, reader({
+ statusReasons: async () => ({ state: 'error', why: 'HTTP 503: Service Unavailable' }),
+ alternateKeys: async () => ({ state: 'error', why: 'HTTP 429: Too many requests' }),
+ }));
+ assert.deepStrictEqual([...checksOf(answered, 'status-reason'), ...checksOf(answered, 'alternate-key')], [
+ ['new_o.In Review', false, 'could not be read: HTTP 503: Service Unavailable'],
+ ['new_o.new_emailkey', false, 'could not be read: HTTP 429: Too many requests'],
+ ]);
+ // A reader that throws, or answers nothing it can use, is the same failure.
+ const thrown = await verifySpec(spec, reader({
+ statusReasons: async () => { throw new Error('socket hang up'); },
+ alternateKeys: async () => null,
+ }));
+ assert.deepStrictEqual([...checksOf(thrown, 'status-reason'), ...checksOf(thrown, 'alternate-key')], [
+ ['new_o.In Review', false, 'could not be read: socket hang up'],
+ ['new_o.new_emailkey', false, 'could not be read: no answer'],
+ ]);
+ assert.ok(thrown.checks.some((c) => c.kind === 'entity' && c.present), 'the rest of the pass ran');
+});
+
+test('a table that is not there has no status reason or key checks, as it has no column checks — and nothing is read for them', async () => {
+ const spec = specOf({ statusReasons: [{ label: 'In Review' }], alternateKeys: [{ schemaName: 'new_emailkey', columns: ['new_email'] }] });
+ const probe = instrument(reader({ tables: [], statusReasons: async () => statusAnswer(...STOCK), alternateKeys: async () => keysAnswer() }), { latency: () => 0 });
+ const r = await verifySpec(spec, probe.read);
+ assert.ok(r.missing.some((m) => m.kind === 'entity'));
+ assert.deepStrictEqual([...checksOf(r, 'status-reason'), ...checksOf(r, 'alternate-key')], []);
+ assert.deepStrictEqual(probe.stats.calls.filter((c) => c.name === 'statusReasons' || c.name === 'alternateKeys'), []);
+});
+
+test('a reader without the two reads makes neither check — an existence-only reader is unaffected', async () => {
+ const spec = specOf({ statusReasons: [{ label: 'In Review' }], alternateKeys: [{ schemaName: 'new_emailkey', columns: ['new_email'] }] });
+ const r = await verifySpec(spec, reader());
+ assert.deepStrictEqual([...checksOf(r, 'status-reason'), ...checksOf(r, 'alternate-key')], []);
+ assert.strictEqual(r.ok, true);
+});
+
+test('REQUESTS: one read of each per table that declares any, however many it declares — none for a table that declares neither', async () => {
+ const spec = {
+ entities: [
+ { schemaName: 'new_o', columns: [], statusReasons: [{ label: 'In Review' }, { label: 'Done', state: 'Inactive' }], alternateKeys: [{ schemaName: 'new_k1', columns: ['new_email'] }, { schemaName: 'new_k2', columns: ['new_email', 'new_name'] }] },
+ { schemaName: 'new_p', columns: [], statusReasons: [{ label: 'Open' }] },
+ { schemaName: 'new_q', columns: [], alternateKeys: [{ schemaName: 'new_k3', columns: ['new_email'] }] },
+ { schemaName: 'new_r', columns: [] },
+ ],
+ appShell: { areas: [] },
+ };
+ const probe = instrument(reader({
+ tables: ['new_o', 'new_p', 'new_q', 'new_r'],
+ statusReasons: async () => statusAnswer(...STOCK),
+ alternateKeys: async () => keysAnswer(),
+ }), { latency: () => 0 });
+ await verifySpec(spec, probe.read);
+ const reads = (name) => probe.stats.calls.filter((c) => c.name === name).map((c) => c.args[0]).sort();
+ assert.deepStrictEqual(reads('statusReasons'), ['new_o', 'new_p']);
+ assert.deepStrictEqual(reads('alternateKeys'), ['new_o', 'new_q']);
+ // A spec that declares neither reads exactly what it read before: the table and its columns, nothing more.
+ const plain = instrument(reader({ statusReasons: async () => statusAnswer(...STOCK), alternateKeys: async () => keysAnswer() }), { latency: () => 0 });
+ await verifySpec(specOf({ columns: [{ schemaName: 'new_email' }] }), plain.read);
+ assert.deepStrictEqual(plain.stats.calls.map((c) => c.name).sort(), ['findColumns', 'findTable', 'sitemapXml']);
+});
+
+// ---- the reader (verify-model-app.js readerFor) ----------------------------------------------------------------------------------
+
+// The SDK's raw client: `dataverse.get` RESOLVES on a non-2xx with { status, body } and throws only on a transport failure.
+function recordingSdk(answer) {
+ const paths = [];
+ return {
+ paths,
+ sdk: {
+ findTables: async () => [], findColumns: async () => [], queryRecords: async () => [],
+ dataverse: { get: async (p) => { paths.push(p); return answer(p); } },
+ },
+ };
+}
+const label = (...pairs) => ({ LocalizedLabels: pairs.map(([LanguageCode, Label]) => ({ Label, LanguageCode })), UserLocalizedLabel: { Label: pairs[0][1], LanguageCode: pairs[0][0] } });
+
+test('readerFor.statusReasons sends ONE narrow read of the table\'s status column and answers each reason with its value, state and every label', async () => {
+ const { sdk, paths } = recordingSdk(() => ({ status: 200, headers: {}, body: { value: [{ LogicalName: 'statuscode', MetadataId: '00000000-0000-4000-8000-000000000001', OptionSet: { Options: [
+ { Value: 1, State: 0, Label: label([1033, 'Active']) },
+ { Value: 2, State: 1, Label: label([1033, 'Inactive']) },
+ { Value: 100000000, State: 0, Label: label([1033, 'In Review'], [3082, 'En revisión']) },
+ ] } }] } }));
+ const got = await readerFor(sdk, 'contoso_app', {}).statusReasons('NEW_O');
+ assert.deepStrictEqual(paths, ["/EntityDefinitions(LogicalName='new_o')/Attributes/Microsoft.Dynamics.CRM.StatusAttributeMetadata?$select=LogicalName&$expand=OptionSet($select=Options)"]);
+ assert.strictEqual(got.state, 'ok');
+ assert.deepStrictEqual(got.options.map((o) => [o.value, o.state, o.labels]), [[1, 0, ['Active']], [2, 1, ['Inactive']], [100000000, 0, ['In Review', 'En revisión']]]);
+});
+
+for (const [description, fields] of [
+ ['omitted', {}], ['null', { State: null }], ['a string', { State: '1' }],
+ ['fractional', { State: 1.5 }], ['a boolean', { State: true }], ['an object', { State: {} }],
+]) {
+ test(`readerFor.statusReasons: State that is ${description} cannot prove the declared state`, async () => {
+ for (const state of ['Inactive', 'Active']) {
+ for (const pinned of [true, false]) {
+ const { sdk, paths } = recordingSdk(() => ({ status: 200, headers: {}, body: { value: [{
+ LogicalName: 'statuscode',
+ OptionSet: { Options: [{ Value: 100000000, Label: label([1033, 'Closed']), ...fields }] },
+ }] } }));
+ const read = readerFor(sdk, 'contoso_app', {});
+ const spec = specOf({ statusReasons: [{ label: 'Closed', state, ...(pinned ? { value: 100000000 } : {}) }] });
+ const r = await verifySpec(spec, { ...reader(), statusReasons: read.statusReasons });
+ assert.strictEqual(checksOf(r, 'status-reason')[0][1], false);
+ assert.deepStrictEqual(checksOf(r, 'status-reason'), [
+ ['new_o.Closed', false, `its state could not be read; the spec declares it under ${state}`],
+ ]);
+ assert.strictEqual(r.ok, false);
+ assert.strictEqual(paths.length, 1);
+ }
+ }
+ });
+}
+
+test('readerFor.statusReasons: known raw State values still prove a correct state or name the wrong state', async () => {
+ for (const [State, present, detail] of [
+ [0, false, 'a status reason of the Active state; the spec declares it under Inactive'],
+ [1, true, ''],
+ [2, false, 'a status reason of the state 2 state; the spec declares it under Inactive'],
+ ]) {
+ const { sdk, paths } = recordingSdk(() => ({ status: 200, headers: {}, body: { value: [{
+ LogicalName: 'statuscode', OptionSet: { Options: [{ Value: 100000000, State, Label: label([1033, 'Closed']) }] },
+ }] } }));
+ const read = readerFor(sdk, 'contoso_app', {});
+ const r = await verifySpec(specOf({ statusReasons: [{ label: 'Closed', state: 'Inactive', value: 100000000 }] }), { ...reader(), statusReasons: read.statusReasons });
+ assert.deepStrictEqual(checksOf(r, 'status-reason'), [['new_o.Closed', present, detail]]);
+ assert.strictEqual(r.ok, present);
+ assert.strictEqual(paths.length, 1);
+ }
+});
+
+test('readerFor.statusReasons: an unreadable state at another value still reports the pinned-value difference', async () => {
+ const { sdk } = recordingSdk(() => ({ status: 200, headers: {}, body: { value: [{
+ LogicalName: 'statuscode', OptionSet: { Options: [{ Value: 100000000, Label: label([1033, 'Closed']) }] },
+ }] } }));
+ const read = readerFor(sdk, 'contoso_app', {});
+ const r = await verifySpec(specOf({ statusReasons: [{ label: 'Closed', state: 'Inactive', value: 100000007 }] }), { ...reader(), statusReasons: read.statusReasons });
+ assert.deepStrictEqual(checksOf(r, 'status-reason'), [['new_o.Closed', false, 'its value is 100000000; the spec pins 100000007']]);
+});
+
+test('readerFor.statusReasons: a readable matching option still proves the state when another same-label option omits it', async () => {
+ const { sdk } = recordingSdk(() => ({ status: 200, headers: {}, body: { value: [{
+ LogicalName: 'statuscode', OptionSet: { Options: [
+ { Value: 100000000, Label: label([1033, 'Closed']) },
+ { Value: 100000001, State: 1, Label: label([1033, 'Closed']) },
+ ] },
+ }] } }));
+ const read = readerFor(sdk, 'contoso_app', {});
+ const r = await verifySpec(specOf({ statusReasons: [{ label: 'Closed', state: 'Inactive' }] }), { ...reader(), statusReasons: read.statusReasons });
+ assert.deepStrictEqual(checksOf(r, 'status-reason'), [['new_o.Closed', true, '']]);
+ assert.strictEqual(r.ok, true);
+});
+
+test('readerFor.alternateKeys sends ONE read of the table\'s keys and answers each with its name and columns', async () => {
+ const { sdk, paths } = recordingSdk(() => ({ status: 200, headers: {}, body: { value: [
+ { LogicalName: 'new_emailkey', SchemaName: 'new_EmailKey', KeyAttributes: ['new_email'], MetadataId: '00000000-0000-4000-8000-000000000002' },
+ { LogicalName: 'new_pairkey', SchemaName: 'new_PairKey', KeyAttributes: ['new_b', 'new_a'], MetadataId: '00000000-0000-4000-8000-000000000003' },
+ ] } }));
+ const got = await readerFor(sdk, 'contoso_app', {}).alternateKeys('NEW_O');
+ assert.deepStrictEqual(paths, ["/EntityDefinitions(LogicalName='new_o')/Keys?$select=LogicalName,SchemaName,KeyAttributes"]);
+ assert.deepStrictEqual(got, { state: 'ok', keys: [
+ { logicalName: 'new_emailkey', schemaName: 'new_EmailKey', columns: ['new_email'] },
+ { logicalName: 'new_pairkey', schemaName: 'new_PairKey', columns: ['new_b', 'new_a'] },
+ ] });
+});
+
+test('readerFor: a read that fails, or answers no list, is an error with the reason — never an empty answer', async () => {
+ for (const read of ['statusReasons', 'alternateKeys']) {
+ const failed = await readerFor(recordingSdk(() => ({ status: 503, headers: {}, body: { error: { code: '0x80040216', message: 'Service Unavailable' } } })).sdk, 'contoso_app', {})[read]('new_o');
+ assert.deepStrictEqual(failed, { state: 'error', why: 'HTTP 503: Service Unavailable' }, read);
+ const thrown = await readerFor(recordingSdk(() => { throw new Error('socket hang up'); }).sdk, 'contoso_app', {})[read]('new_o');
+ assert.deepStrictEqual(thrown, { state: 'error', why: 'socket hang up' }, read);
+ const shapeless = await readerFor(recordingSdk(() => ({ status: 200, headers: {}, body: {} })).sdk, 'contoso_app', {})[read]('new_o');
+ assert.strictEqual(shapeless.state, 'error', read);
+ assert.match(shapeless.why, /no list/, read);
+ // A table the environment does not have answers 404: there is nothing to compare with.
+ const absent = await readerFor(recordingSdk(() => ({ status: 404, headers: {}, body: { error: { message: 'not found' } } })).sdk, 'contoso_app', {})[read]('new_o');
+ assert.deepStrictEqual(absent, { state: 'absent' }, read);
+ }
+ // A key row without its columns cannot be compared, so the answer is not used.
+ const columnless = await readerFor(recordingSdk(() => ({ status: 200, headers: {}, body: { value: [{ LogicalName: 'new_emailkey', SchemaName: 'new_emailkey' }] } })).sdk, 'contoso_app', {}).alternateKeys('new_o');
+ assert.deepStrictEqual(columnless, { state: 'error', why: "the key 'new_emailkey' was answered without its columns" });
+});
+
+test('a status reason is held to what the build gives it: the build\'s own state and value, from one rule', () => {
+ // The data-model phase inserts each reason at statusReasonTargets' state and value (entity-provision.js), and verify compares with the
+ // same — so this pins the rule both read: Active unless Inactive, and the pinned value, else 100000000 + the reason's place in the list.
+ const targets = statusReasonTargets({ statusReasons: [{ label: 'A' }, { label: 'B', state: 'Inactive' }, { label: 'C', value: 7 }, { label: 'D', state: 'Pending' }] });
+ assert.deepStrictEqual(targets.map((t) => [t.statusReason.label, t.stateCode, t.value]), [['A', 0, 100000000], ['B', 1, 100000001], ['C', 0, 7], ['D', 0, 100000003]]);
+ assert.deepStrictEqual(statusReasonTargets({}), []);
+});
+
+test('an absent answer is a failed check that says the table answered no such thing', async () => {
+ const spec = specOf({ statusReasons: [{ label: 'In Review' }], alternateKeys: [{ schemaName: 'new_emailkey', columns: ['new_email'] }] });
+ const r = await verifySpec(spec, reader({ statusReasons: async () => ({ state: 'absent' }), alternateKeys: async () => ({ state: 'absent' }) }));
+ assert.deepStrictEqual([...checksOf(r, 'status-reason'), ...checksOf(r, 'alternate-key')], [
+ ['new_o.In Review', false, 'could not be read: the environment answered that the table is not there'],
+ ['new_o.new_emailkey', false, 'could not be read: the environment answered that the table is not there'],
+ ]);
+});
+
+test('the view filter\'s choice read is unchanged: only a status reason gains its state, every other option keeps its shape', async () => {
+ // readChoiceAttributes shares the option parser with the status reason read; what it answered for a choice column must not move.
+ const { sdk } = recordingSdk((p) => {
+ const cast = /Microsoft\.Dynamics\.CRM\.(\w+)AttributeMetadata/.exec(p)[1];
+ const rows = {
+ Picklist: [{ LogicalName: 'new_tier', OptionSet: { Options: [{ Value: 227350000, Label: label([1033, 'Silver']) }] } }],
+ Status: [{ LogicalName: 'statuscode', OptionSet: { Options: [{ Value: 1, State: 0, Label: label([1033, 'Active']) }] } }],
+ }[cast] || [];
+ return { status: 200, headers: {}, body: { value: rows } };
+ });
+ const got = await readChoiceAttributes(sdk.dataverse, 'new_o');
+ assert.deepStrictEqual(got.attributes.get('new_tier').options, [{ value: 227350000, labels: ['Silver'], shown: 'Silver' }]);
+ assert.deepStrictEqual(got.attributes.get('statuscode').options, [{ value: 1, labels: ['Active'], shown: 'Active', state: 0 }]);
+});
+
+test('metadata checks preserve one command-bar presence check per table without checking individual controls', async () => {
+ const spec = {
+ ...specOf({
+ statusReasons: [{ label: 'In Review' }],
+ alternateKeys: [{ schemaName: 'new_emailkey', columns: ['new_email'] }],
+ }),
+ commands: [
+ { entity: 'new_o', label: 'Escalate', library: 'new_o.js', function: 'O.escalate' },
+ { entity: 'NEW_O', label: 'More', type: 'FlyoutAnchor', children: [{ label: 'Approve', library: 'new_o.js', function: 'O.approve' }] },
+ ],
+ };
+ for (const result of [true, false, 'unreadable']) {
+ const calls = [];
+ const r = await verifySpec(spec, {
+ ...reader({
+ statusReasons: async () => statusAnswer(...STOCK, option(100000000, 0, 'In Review')),
+ alternateKeys: async () => keysAnswer(key('new_emailkey', ['new_email'])),
+ }),
+ commandBar: async (entity) => {
+ calls.push(entity);
+ if (result === 'unreadable') throw new Error('command bar could not be resolved');
+ return result;
+ },
+ commandButtons: async () => assert.fail('individual controls are not read'),
+ });
+ assert.deepStrictEqual(calls, ['new_o']);
+ assert.deepStrictEqual(checksOf(r, 'command'), [['new_o command bar', result === true, '']]);
+ assert.deepStrictEqual(checksOf(r, 'command-button'), []);
+ assert.deepStrictEqual(checksOf(r, 'status-reason'), [['new_o.In Review', true, '']]);
+ assert.deepStrictEqual(checksOf(r, 'alternate-key'), [['new_o.new_emailkey', true, '']]);
+ assert.strictEqual(r.ok, result === true);
+ }
+});
+
+test('readerFor retains table-level command resolution without a per-control reader', async () => {
+ for (const rows of [[], [{ id: 'bar-1' }]]) {
+ const calls = [];
+ const { sdk } = recordingSdk(() => assert.fail('command-bar presence makes no metadata read'));
+ sdk.resolveArtifact = async (...args) => { calls.push(args); return rows; };
+ const read = readerFor(sdk, 'contoso_app', {});
+ assert.strictEqual(Object.hasOwn(read, 'commandButtons'), false);
+ assert.strictEqual(await read.commandBar('NEW_O'), rows.length !== 0);
+ assert.deepStrictEqual(calls, [['command', { entity: 'new_o' }]]);
+ }
+});
diff --git a/plugins/model-apps/scripts/tests/view-filter-labels.test.js b/plugins/model-apps/scripts/tests/view-filter-labels.test.js
index e3ab67dcf..d22dd5492 100644
--- a/plugins/model-apps/scripts/tests/view-filter-labels.test.js
+++ b/plugins/model-apps/scripts/tests/view-filter-labels.test.js
@@ -873,13 +873,16 @@ test('ADO 6691114 pre-flight: what the environment already held is final and not
assert.ifError((await had.run(spec, { phases: FULL })).error);
assert.strictEqual(castReads(had), 4, 'read once, before the build; the views phase took that answer');
assert.deepStrictEqual(viewCondition(had.defs, 'Gold customers', 'new_tier'), ['227350001']);
- // A status reason the build inserts is not there to read until it has run, so the views phase asks again: eight.
+ // A status reason the build inserts is not there to read until it has run, so the views phase
+ // asks again: eight resolver casts, plus the data model's one deferred no-op status proof.
const byTable = { account: { Status: { statuscode: opts([1, [1033, 'Active']], [2, [1033, 'Inactive']]) } } };
const made = viewsEngine({ byTable });
made.sdk.insertStatusValue = async (logical, o) => { byTable.account.Status.statuscode.push({ Value: 100000000, Label: lbl([1033, o.label]) }); return 100000000; };
const withReason = specOf([{ ...ACCOUNT, statusReasons: [{ label: 'Passed QA', state: 'Active' }] }], [view('account', [eq('statuscode', 'Passed QA')], 'Passed accounts')]);
assert.ifError((await made.run(withReason, { phases: FULL })).error);
- assert.strictEqual(castReads(made), 8, 'four cast reads before the build, four after it');
+ assert.strictEqual(castReads(made), 9, 'four resolver casts before the build, four after it, and one status no-op proof');
+ assert.strictEqual(made.client.paths.filter((p) => /StatusAttributeMetadata\?/.test(p)).length, 3);
+ assert.deepStrictEqual(viewCondition(made.defs, 'Passed accounts', 'statuscode'), ['100000000']);
// A run with nothing written before the views phase has no pre-flight, so its own check is the only one.
const only = viewsEngine({ byTable: { new_customer: { Picklist: { new_tier: TIER } } } });
assert.ifError((await only.run(spec, { phases: ['views'] })).error);
diff --git a/plugins/model-apps/scripts/tests/web-resource-unconfirmed.test.js b/plugins/model-apps/scripts/tests/web-resource-unconfirmed.test.js
new file mode 100644
index 000000000..02bd1161b
--- /dev/null
+++ b/plugins/model-apps/scripts/tests/web-resource-unconfirmed.test.js
@@ -0,0 +1,775 @@
+'use strict';
+// A web resource whose publication the bundled SDK could not confirm (WEB_RESOURCE_UNVERIFIED) — at every place the build writes one: the spec's web
+// resources, the generated app icon and the page manifest.
+//
+// The SDK writes a web resource, publishes it, and reads its PUBLISHED content back (a plain GET by id); when the publish fails or the read-back cannot
+// confirm the content it throws WebResourceUnverifiedError — after the row exists, with its id, and with the failure as its non-enumerable `cause`. A
+// second create of the name is refused. Before the build handled it, the step threw before it recorded the row or added it to the solution, and every
+// run after that found the name and reused the row untouched: outside the solution, its content never confirmed. Now the build records the row (in the
+// run's result, and in the workspace: lib/web-resource-records.js), adds it to the solution, and stops with what a run again does — which is to write the
+// content again by id, never to create the name again. Held here:
+// 1. the record itself;
+// 2. the build's retry policy for the error: it is judged by the failure it carries, and when it carries none — the read-back differed — it is run again;
+// 3. each site, over the real bundle and the stateful fake of helpers/fake-app-build-org.js (a web resource held in a saved and a published layer, a plain
+// read answering the published one), with the customization lock refusing the publish: the halt, the row in the solution, the record, the next run —
+// the build's own re-run and a new invocation — writing the content again by id, and an unchanged rebuild after it sending what it always did.
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { createMakerSdk, createNodeWorkspaceStorage } = require('../vendor/cds-maker-sdk.cjs');
+const { createMakerSdk: createClientSdk } = require('../lib/maker-sdk.js');
+const { createAzHttpClient } = require('../lib/sdk-http-client.js');
+const { runSdkBuild } = require('../lib/sdk-build.js');
+const { requireSuccessfulPush } = require('../lib/entity-provision.js');
+const { buildModelApp, isTransientHalt } = require('../build-model-app.js');
+const { retryPolicyFor, judgeFailure, RETRY } = require('../lib/retry-policy.js');
+const { openUnconfirmedWebResources, readUnconfirmedWebResources, unconfirmedRecordPath, PREFIX } = require('../lib/web-resource-records.js');
+const { createFakeBuildOrg } = require('./helpers/fake-app-build-org.js');
+
+const dirs = [];
+test.after(() => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); });
+const tempDir = () => { const d = fs.mkdtempSync(path.join(os.tmpdir(), 'wr-unconfirmed-')); dirs.push(d); return d; };
+const ENV = 'https://contoso.crm.dynamics.com';
+const ID_A = '11111111-aaaa-4aaa-8aaa-111111111111';
+const ID_B = '22222222-bbbb-4bbb-8bbb-222222222222';
+const LOCK = { code: '0x80071151', message: 'Cannot start the requested operation [Publish] because there is another [WorkflowSetState] running at this moment.' };
+const base64 = (text) => Buffer.from(text, 'utf8').toString('base64');
+
+// --- 1. the record ------------------------------------------------------------------------------------------------------------------------------------------
+
+test('the record: a row noted is read back by any letter case of its name, by the next run too; cleared, it is gone, and the file with its last entry', () => {
+ const dir = tempDir();
+ const run = openUnconfirmedWebResources({ workspaceDir: dir, environment: ENV });
+ assert.equal(run.idOf('contoso_/a.js'), undefined, 'nothing recorded yet, and no file');
+ assert.equal(run.note('contoso_/a.js', ID_A.toUpperCase()), true, 'on disk');
+ assert.equal(run.note('contoso_/b.js', ID_B), true);
+ assert.equal(run.idOf('CONTOSO_/A.JS'), ID_A, 'a name is compared as Dataverse compares it; the id is kept in lower case');
+ const next = openUnconfirmedWebResources({ workspaceDir: dir, environment: ENV });
+ assert.equal(next.idOf('contoso_/b.js'), ID_B, 'the next run reads what this one recorded');
+ assert.deepEqual([...readUnconfirmedWebResources(dir, ENV).values()].map((e) => [e.name, e.id]), [['contoso_/a.js', ID_A], ['contoso_/b.js', ID_B]]);
+ next.clear('contoso_/a.js');
+ assert.equal(openUnconfirmedWebResources({ workspaceDir: dir, environment: ENV }).idOf('contoso_/a.js'), undefined);
+ next.clear('contoso_/b.js');
+ assert.equal(fs.existsSync(unconfirmedRecordPath(dir, ENV)), false, 'an empty record is no file');
+ assert.deepEqual(fs.readdirSync(dir).filter((f) => f.startsWith(PREFIX)), []);
+});
+
+test('the record is one file per environment, and another environment\'s rows are not this one\'s', () => {
+ const dir = tempDir();
+ openUnconfirmedWebResources({ workspaceDir: dir, environment: ENV }).note('contoso_/a.js', ID_A);
+ assert.equal(openUnconfirmedWebResources({ workspaceDir: dir, environment: 'https://fabrikam.crm.dynamics.com' }).idOf('contoso_/a.js'), undefined);
+ assert.equal(openUnconfirmedWebResources({ workspaceDir: dir, environment: `${ENV}/` }).idOf('contoso_/a.js'), ID_A, 'the same origin, written another way');
+});
+
+test('the record never stops a build: a damaged file is "nothing recorded", said once; with no workspace or environment nothing is recorded, and a note says so', () => {
+ const dir = tempDir();
+ fs.writeFileSync(unconfirmedRecordPath(dir, ENV), '{ not json');
+ const warnings = [];
+ const run = openUnconfirmedWebResources({ workspaceDir: dir, environment: ENV, warn: (w) => warnings.push(w) });
+ assert.equal(run.idOf('contoso_/a.js'), undefined);
+ assert.equal(run.idOf('contoso_/b.js'), undefined);
+ assert.equal(warnings.length, 1, JSON.stringify(warnings));
+ assert.match(warnings[0], /could not be read .*so this build reuses every web resource that exists as it is/);
+ for (const options of [{}, { workspaceDir: dir }, { environment: ENV }]) {
+ const none = openUnconfirmedWebResources(options);
+ assert.equal(none.note('contoso_/a.js', ID_A), false, JSON.stringify(options));
+ assert.equal(none.idOf('contoso_/a.js'), undefined);
+ }
+ assert.equal(openUnconfirmedWebResources({ workspaceDir: dir, environment: ENV }).note('contoso_/a.js', 'not-a-guid'), false, 'an id that is no id is not recorded');
+});
+
+// --- 2. the retry policy ------------------------------------------------------------------------------------------------------------------------------------
+//
+// The REAL SDK's error, made by the real bundle over a transport that answers the create, the publish and the read-back as each case asks. Its `cause` is not
+// enumerable — what the policy reads is reached all the same.
+async function sdkError({ publish = { status: 204 }, readBack } = {}) {
+ let saved;
+ const answer = (a) => ({ status: a.status, headers: a.headers || {}, body: a.body === undefined ? {} : a.body });
+ const httpClient = {
+ get: async (url) => (/\/webresourceset\(/.test(url) ? answer(readBack ? readBack(saved) : { status: 200, body: { content: saved } }) : answer({ status: 200, body: { value: [] } })),
+ post: async (url, body) => {
+ if (/\/webresourceset$/.test(url)) { saved = body.content; return { status: 204, headers: { 'odata-entityid': `${ENV}/api/data/v9.2/webresourceset(${ID_A})` }, body: {} }; }
+ return answer(publish);
+ },
+ patch: async () => answer({ status: 204 }),
+ delete: async () => answer({ status: 204 }),
+ put: async () => answer({ status: 204 }),
+ };
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(tempDir()), instanceUrl: ENV, httpClient });
+ await sdk.initWorkspace();
+ return sdk.createWebResource({ name: 'contoso_/scripts/sql_timeout_try_again_later.js', type: 'js', content: 'var Form = {};' }).then(() => assert.fail('the create was confirmed'), (e) => e);
+}
+
+test('retry policy: WEB_RESOURCE_UNVERIFIED is judged by the failure it carries — a lock, a 503 or a reset is run again, a 400, 401, 403, 404 or 412 is not — read through a cause that is not enumerable', async () => {
+ const cases = [
+ ['the publish refused by the customization lock (429 0x80071151)', { publish: { status: 429, body: { error: LOCK } } }, RETRY.SERVICE],
+ ['the publish answered 503', { publish: { status: 503, body: { error: { message: 'Service Unavailable' } } } }, RETRY.SERVICE],
+ ['the publish answered 500 with the lock\'s code', { publish: { status: 500, body: { error: LOCK } } }, RETRY.SERVICE],
+ ['the publish refused 400', { publish: { status: 400, body: { error: { code: '0x80040216', message: 'An unexpected error occurred. SQL timeout, try again later' } } } }, RETRY.NEVER],
+ ['the publish refused 401', { publish: { status: 401, body: {} } }, RETRY.NEVER],
+ ['the publish refused 403', { publish: { status: 403, body: { error: { code: '0x80040220', message: 'Principal user is missing prvPublishCustomizations privilege. Try again later.' } } } }, RETRY.NEVER],
+ ['the publish answered 412 (the SDK\'s typed VERSION_CONFLICT)', { publish: { status: 412, body: {} } }, RETRY.NEVER],
+ ['the read-back answered 404', { readBack: () => ({ status: 404, body: { error: { message: 'Does Not Exist' } } }) }, RETRY.NEVER],
+ ['the read-back answered 503', { readBack: () => ({ status: 503, body: {} }) }, RETRY.SERVICE],
+ ['the read-back answered other content (no cause)', { readBack: () => ({ status: 200, body: { content: base64('var Old = {};') } }) }, RETRY.SERVICE],
+ ['the read-back carried no content (no cause)', { readBack: () => ({ status: 200, body: { content: null } }) }, RETRY.SERVICE],
+ ];
+ for (const [what, answers, policy] of cases) {
+ const error = await sdkError(answers);
+ assert.equal(error.code, 'WEB_RESOURCE_UNVERIFIED', what);
+ assert.equal(error.id, ID_A, `${what}: the row is named`);
+ assert.ok(!Object.keys(error).includes('cause'), `${what}: the cause is not enumerable`);
+ assert.equal(retryPolicyFor(error), policy, what);
+ assert.equal(isTransientHalt(error), policy === RETRY.SERVICE, `${what}: the build's own re-run decides alike`);
+ // The build's own error around it (the halt's cause), whose words name the web resource: judged the same, and no word of either is read.
+ const wrapped = Object.assign(new Error(`${error.message} — this build recorded the row as its own`, { cause: error }), { code: 'WEB_RESOURCE_UNVERIFIED', id: error.id });
+ assert.equal(retryPolicyFor(wrapped), policy, `${what}: around the build's own error`);
+ assert.equal(judgeFailure(wrapped).text.includes('sql_timeout'), false, `${what}: the name is never read`);
+ }
+});
+
+test('retry policy: the wrapper alone, with no failure behind it, is run again — and an error of another code that carries no cause is still a typed refusal', () => {
+ const unconfirmed = Object.assign(new Error('Web resource \'contoso_/a.js\' (id) was written and published, but the published content is not what was sent'), { code: 'WEB_RESOURCE_UNVERIFIED', id: ID_A });
+ assert.equal(retryPolicyFor(unconfirmed), RETRY.SERVICE);
+ assert.equal(judgeFailure(unconfirmed).unconfirmed, true);
+ assert.equal(retryPolicyFor(Object.assign(new Error('x'), { code: 'VALIDATION_ERROR' })), RETRY.NEVER, 'the neighbour: a typed refusal stays one');
+ assert.equal(retryPolicyFor(Object.assign(new Error('x'), { code: 'WEB_RESOURCE_UNVERIFIED', cause: { transient: false } })), RETRY.NEVER, 'a cause that says never is final');
+});
+
+// --- 3. the sites, over the real bundle --------------------------------------------------------------------------------------------------------------------
+
+// What the customization lock answers a publish it refuses, and the fake's intercept of the publishes that name a web resource: `refusals` of them are refused.
+const lockRefused = () => ({ status: 429, headers: {}, body: { error: LOCK } });
+const namesWebResource = (c) => c.method === 'POST' && c.path === '/PublishXml' && /<webresource>/.test(c.body.ParameterXml);
+function refuseWebResourcePublishes(org, refusals = 1) {
+ let left = refusals;
+ return org.intercept((c) => namesWebResource(c) && left > 0 && (left -= 1, true), lockRefused);
+}
+
+function scenario({ realClient = false } = {}) {
+ const org = createFakeBuildOrg({ entities: {} });
+ const dir = tempDir();
+ const warnings = [];
+ const wire = [];
+ const httpClient = realClient ? createAzHttpClient(org.origin, {
+ getToken: () => 'offline-resource-reset-token',
+ sleep: async () => {},
+ request: async (request) => {
+ wire.push({ ...request, recoveryId: openUnconfirmedWebResources({ workspaceDir: dir, environment: org.origin }).idOf(SCRIPT) });
+ const verb = request.method.toLowerCase();
+ const options = { headers: request.headers };
+ const response = ['get', 'delete'].includes(verb)
+ ? await org.httpClient[verb](request.url, options)
+ : await org.httpClient[verb](request.url, request.body ? JSON.parse(request.body) : undefined, options);
+ return { statusCode: response.status, headers: response.headers || {}, body: typeof response.body === 'string' ? response.body : JSON.stringify(response.body) };
+ },
+ }) : org.httpClient;
+ async function build(spec, { phases = ['web-resources'], workspaceDir = dir, ...extra } = {}) {
+ const sdk = (realClient ? createClientSdk : createMakerSdk)({ workspaceStorage: createNodeWorkspaceStorage(dir), instanceUrl: org.origin, httpClient });
+ await sdk.initWorkspace();
+ const mark = org.calls.length;
+ try {
+ const outcome = await runSdkBuild(spec, { sdk, apply: true, publish: true, phases, workspaceDir, appDir: dir, env: org.origin, warn: (w) => warnings.push(String(w)), ...extra });
+ return { outcome, mark, calls: org.calls.slice(mark) };
+ } catch (halt) {
+ return { halt, mark, calls: org.calls.slice(mark) };
+ }
+ }
+ const row = (name) => [...org.resources.values()].find((r) => r.name === name);
+ return { org, dir, build, row, warnings, wire };
+}
+
+const SCRIPT = 'contoso_/scripts/form.js';
+const SCRIPT_CODE = 'var Form = { onLoad: function () {} };';
+const spec = (webResources = [{ name: SCRIPT, type: 'js', content: SCRIPT_CODE }]) => ({
+ solution: { uniqueName: 'ContosoReview', displayName: 'Contoso Review', publisherPrefix: 'contoso' },
+ app: { name: 'Publish Review', uniqueName: 'contoso_publishreview' },
+ entities: [{ schemaName: 'contoso_item', displayName: 'Item', existing: true, primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] }],
+ webResources,
+});
+const writesOf = (calls) => calls.filter((c) => c.method !== 'GET').map((c) => `${c.method} ${c.path.replace(/\([0-9a-f-]{36}\)/i, '(id)')}${c.path === '/PublishXml' ? ` ${/<(\w+)>[^<]*<\/\1><\/\w+><\/importexportxml>/.exec(c.body.ParameterXml)[1]}` : ''}${c.path === '/AddSolutionComponent' ? ` ${c.body.ComponentId === undefined ? '' : 'web resource'}` : ''}`);
+const added = (calls, id) => calls.filter((c) => c.method === 'POST' && c.path === '/AddSolutionComponent' && String(c.body.ComponentId).toLowerCase() === id);
+
+test('a spec web resource whose publish the lock refuses: the build stops naming it, unconfirmed and not lost — the row is in the solution and recorded, and the build\'s own retry runs again', async () => {
+ const s = scenario();
+ refuseWebResourcePublishes(s.org);
+ const first = await s.build(spec());
+ assert.ok(first.halt, 'the build stopped');
+ const id = s.row(SCRIPT).webresourceid;
+ assert.equal(first.halt.code, 'WEB_RESOURCE_UNVERIFIED');
+ assert.equal(first.halt.phase, 'web-resources');
+ assert.match(first.halt.message, new RegExp(`Web resource '${SCRIPT.replace(/[/.]/g, '\\$&')}' \\(${id}\\)`), 'it names the web resource and its id');
+ assert.match(first.halt.message, /this build recorded the row as its own and added it to the solution\. Its publication is UNCONFIRMED, not lost: run the build again — it writes the content again by that id, publishes it and reads it back/);
+ assert.equal(added(first.calls, id).length, 1, 'the row is added to the solution as the success path adds it');
+ assert.equal(openUnconfirmedWebResources({ workspaceDir: s.dir, environment: s.org.origin }).idOf(SCRIPT), id, 'and recorded for the next run');
+ assert.equal(retryPolicyFor(first.halt), RETRY.SERVICE, 'a lock is the service\'s to clear');
+ assert.equal(isTransientHalt(first.halt), true, 'so the build runs again');
+ assert.equal(s.row(SCRIPT).publishedContent, undefined, 'nothing of it is published');
+});
+
+test('the run that follows writes it again by id — no second create of the name — publishes and reads it back, puts it in the solution and clears the record; the run after that sends what any rebuild does', async () => {
+ const s = scenario();
+ refuseWebResourcePublishes(s.org);
+ await s.build(spec());
+ const id = s.row(SCRIPT).webresourceid;
+ const next = await s.build(spec());
+ assert.ok(next.outcome && next.outcome.ok, String(next.halt && next.halt.message));
+ assert.deepEqual(writesOf(next.calls), ['PATCH /webresourceset(id)', 'POST /PublishXml webresource', 'POST /AddSolutionComponent web resource'], 'written again by id: never POSTed');
+ assert.ok(next.calls.some((c) => c.method === 'GET' && c.path === `/webresourceset(${id})?$select=content`), 'and its published content read back');
+ assert.ok(!next.calls.some((c) => c.method === 'GET' && /^\/webresourceset\?/.test(c.path)), 'the name is not even looked up: the record names the row');
+ assert.equal(s.row(SCRIPT).publishedContent, base64(SCRIPT_CODE), 'what is published is what the spec says');
+ assert.equal(fs.existsSync(unconfirmedRecordPath(s.dir, s.org.origin)), false, 'confirmed, the record is gone');
+ assert.equal(next.outcome.created.webResources[SCRIPT], id);
+ // An unchanged rebuild after it: the name is found and reused, exactly as for a web resource whose first write was confirmed.
+ const quiet = scenario();
+ await quiet.build(spec());
+ const clean = await quiet.build(spec());
+ const after = await s.build(spec());
+ assert.deepEqual(writesOf(after.calls), [], 'nothing written');
+ assert.deepEqual(after.calls.map((c) => `${c.method} ${c.path}`), clean.calls.map((c) => `${c.method} ${c.path}`), 'and the same requests as a rebuild of a web resource whose first write was confirmed');
+});
+
+function followEmittedResetAdvice(dir) {
+ let advice;
+ try {
+ // Select the real shared remedy with a by-value refusal; the resource's write, unverified error
+ // and recovery below still traverse the actual bundle and production HTTP client.
+ requireSuccessfulPush({ saved: false, error: { code: 'ARTIFACT_ALREADY_EXISTS', message: 'An owned fixture row already exists.' } }, 'owned fixture');
+ } catch (halt) {
+ assert.equal(halt.code, 'already-exists');
+ advice = halt.message;
+ }
+ assert.match(advice, /stop any other build or teardown/);
+ assert.match(advice, /then delete everything in it except /);
+ // Read the emitted preservation names, e.g. `last-applied.json` or `page-ownership.*.json`,
+ // instead of giving this test a separate keep-list that could conceal missing operator advice.
+ const patterns = [...advice.matchAll(/\b[a-z][a-z0-9-]*(?:\.[a-z0-9*-]+)*\.json\b/g)].map(([name]) => {
+ const literal = (part) => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ return new RegExp(`^${name.split('*').map(literal).join('.*')}$`);
+ });
+ assert.ok(patterns.length >= 3, 'the emitted rule names the baseline, approval and page records');
+ const removed = [];
+ for (const name of fs.readdirSync(dir)) {
+ if (patterns.some((pattern) => pattern.test(name))) continue;
+ fs.rmSync(path.join(dir, name), { recursive: true, force: true });
+ removed.push(name);
+ }
+ return removed;
+}
+
+for (const stalePublished of [false, true]) {
+ test(`workspace reset ${stalePublished ? 'does not turn unconfirmed published content into successful stale reuse' : 'retains the recovery identity of a never-published partial resource'} through the real client`, async (t) => {
+ const s = scenario({ realClient: true });
+ const stop = stalePublished ? s.org.intercept(namesWebResource, () => {
+ s.row(SCRIPT).publishedContent = base64('var Form = { old: true };');
+ return { status: 204, headers: {}, body: null };
+ }) : refuseWebResourcePublishes(s.org);
+ const first = await s.build(spec());
+ stop();
+ assert.equal(first.halt && first.halt.code, 'WEB_RESOURCE_UNVERIFIED');
+ const row = s.row(SCRIPT);
+ const id = row.webresourceid;
+ const receipt = unconfirmedRecordPath(s.dir, s.org.origin);
+ assert.equal(openUnconfirmedWebResources({ workspaceDir: s.dir, environment: s.org.origin }).idOf(SCRIPT), id);
+ assert.equal(s.wire.filter((request) => request.method === 'POST' && new URL(request.url).pathname.endsWith('/PublishXml')).length, 1);
+ assert.equal(row.publishedContent, stalePublished ? base64('var Form = { old: true };') : undefined);
+
+ fs.writeFileSync(path.join(s.dir, 'last-applied.json'), '{"baseline":"keep"}\n');
+ fs.writeFileSync(path.join(s.dir, 'destructive-approval.json'), '{"approved":"keep"}\n');
+ const pages = require('../lib/page-ownership-records.js');
+ pages.recordPageCreation(s.dir, 'contoso_reset', 'overview', ID_A, 'Overview', s.org.origin);
+ pages.recordPagePending(s.dir, 'contoso_reset', 'detail', ID_B, 'Detail', s.org.origin, 'a'.repeat(64));
+ pages.recordPageTeardown(s.dir, 'contoso_reset', [{ id: ID_A, key: 'overview', name: 'Overview' }], s.org.origin);
+ const existingStores = new Map(fs.readdirSync(s.dir)
+ .filter((name) => ['last-applied.json', 'destructive-approval.json'].includes(name) || name.startsWith('page-ownership.'))
+ .map((name) => [name, fs.readFileSync(path.join(s.dir, name))]));
+ assert.equal(existingStores.size, 5, 'baseline, approval and all three page-record kinds coexist with the resource receipt');
+ fs.writeFileSync(path.join(s.dir, 'reset-cache.json'), '{"cache":"discard"}\n');
+ fs.mkdirSync(path.join(s.dir, 'reset-cache'));
+ fs.writeFileSync(path.join(s.dir, 'reset-cache', 'artifact.json'), '{"cache":"discard"}\n');
+ const removed = followEmittedResetAdvice(s.dir);
+ assert.ok(removed.includes('reset-cache.json') && removed.includes('reset-cache'), 'nonessential files and cached directories are reset');
+ assert.equal(fs.existsSync(path.join(s.dir, 'manifest.json')), false, 'the SDK manifest is reconstructible cache, not an essential record');
+ for (const [name, bytes] of existingStores) assert.deepEqual(fs.readFileSync(path.join(s.dir, name)), bytes, `${name} is preserved byte for byte`);
+
+ const mark = s.wire.length;
+ const next = await s.build(spec());
+ const sent = s.wire.slice(mark);
+ const creates = sent.filter((request) => request.method === 'POST' && new URL(request.url).pathname.endsWith('/webresourceset'));
+ const patches = sent.filter((request) => request.method === 'PATCH');
+ t.diagnostic(JSON.stringify({ stalePublished, resultOk: next.outcome && next.outcome.ok, failureCode: next.halt && next.halt.code, creates: creates.length, patches: patches.length }));
+ assert.equal(next.outcome && next.outcome.ok, true, 'following the emitted reset must recover instead of retrying a refused duplicate create');
+ assert.equal(row.publishedContent, base64(SCRIPT_CODE), 'a successful rebuild must publish the intended bytes, not silently reuse stale content');
+ assert.equal(next.outcome.created.webResources[SCRIPT], id, 'the original durable id is retained');
+ assert.equal(creates.length, 0, 'reset does not authorize another create by name');
+ assert.equal(patches.length, 1);
+ assert.equal(new URL(patches[0].url).pathname.endsWith(`/webresourceset(${id})`), true);
+ assert.equal(JSON.parse(patches[0].body).content, base64(SCRIPT_CODE));
+ const verified = sent.findIndex((request) => request.method === 'GET' && new URL(request.url).pathname.endsWith(`/webresourceset(${id})`) && new URL(request.url).searchParams.get('$select') === 'content');
+ assert.ok(verified > sent.indexOf(patches[0]), 'published content is verified after rewriting the original row');
+ assert.equal(sent[verified].recoveryId, id, 'verification still has the durable receipt');
+ assert.equal(sent.filter((request) => request.method === 'POST' && new URL(request.url).pathname.endsWith('/PublishXml')).length, 1);
+ assert.equal(fs.existsSync(receipt), false, 'only successful recovery clears the receipt');
+ for (const [name, bytes] of existingStores) assert.deepEqual(fs.readFileSync(path.join(s.dir, name)), bytes, `${name} also survives recovery`);
+ });
+}
+
+test('a write again that the lock refuses too keeps the record and stops again, and a quiet run then converges — one create in three runs', async () => {
+ const s = scenario();
+ refuseWebResourcePublishes(s.org, 2);
+ await s.build(spec());
+ const id = s.row(SCRIPT).webresourceid;
+ const second = await s.build(spec());
+ assert.equal(second.halt && second.halt.code, 'WEB_RESOURCE_UNVERIFIED');
+ assert.deepEqual(writesOf(second.calls), ['PATCH /webresourceset(id)', 'POST /PublishXml webresource', 'POST /AddSolutionComponent web resource'], 'the second attempt wrote by id too');
+ assert.equal(openUnconfirmedWebResources({ workspaceDir: s.dir, environment: s.org.origin }).idOf(SCRIPT), id, 'still recorded');
+ const third = await s.build(spec());
+ assert.ok(third.outcome && third.outcome.ok, String(third.halt && third.halt.message));
+ assert.equal(s.row(SCRIPT).publishedContent, base64(SCRIPT_CODE));
+ assert.equal(s.org.calls.filter((c) => c.method === 'POST' && c.path === '/webresourceset').length, 1, 'one create in three runs');
+});
+
+test('an unconfirmed update still names the web resource, not only the id the SDK reports', async () => {
+ const s = scenario();
+ refuseWebResourcePublishes(s.org, 2);
+ await s.build(spec());
+ const again = await s.build(spec());
+ assert.equal(again.halt && again.halt.code, 'WEB_RESOURCE_UNVERIFIED');
+ assert.match(again.halt.message, /Web resource 'contoso_\/scripts\/form\.js'/);
+});
+
+test('a missing recorded row whose name another maker now holds is refused without writing or adopting that replacement', async () => {
+ const s = scenario();
+ refuseWebResourcePublishes(s.org);
+ await s.build(spec());
+ const gone = s.row(SCRIPT).webresourceid;
+ s.org.resources.delete(gone);
+ s.org.resources.set(ID_B, { webresourceid: ID_B, name: SCRIPT, content: base64('var Theirs = {};'), publishedContent: base64('var Theirs = {};') });
+ const next = await s.build(spec());
+ assert.equal(next.halt && next.halt.code, 'WEB_RESOURCE_IDENTITY_CONFLICT');
+ assert.equal(retryPolicyFor(next.halt), RETRY.NEVER);
+ assert.deepEqual(writesOf(next.calls), ['PATCH /webresourceset(id)'], 'only the write to the old id was attempted; never a second create or a write to the replacement');
+ assert.equal(s.org.resources.get(ID_B).content, base64('var Theirs = {};'));
+ assert.equal(openUnconfirmedWebResources({ workspaceDir: s.dir, environment: s.org.origin }).idOf(SCRIPT), gone, 'the unresolved receipt is kept');
+});
+
+test('a recorded resource whose id now reads as another name is refused before writing it', async () => {
+ const s = scenario();
+ refuseWebResourcePublishes(s.org);
+ await s.build(spec());
+ const resource = s.row(SCRIPT);
+ resource.name = 'fabrikam_/foreign.js';
+ resource.content = resource.publishedContent = base64('var Theirs = {};');
+ const next = await s.build(spec());
+ assert.equal(next.halt && next.halt.code, 'WEB_RESOURCE_IDENTITY_CONFLICT');
+ assert.equal(retryPolicyFor(next.halt), RETRY.NEVER);
+ assert.deepEqual(writesOf(next.calls), []);
+ assert.equal(resource.content, base64('var Theirs = {};'));
+ assert.equal(openUnconfirmedWebResources({ workspaceDir: s.dir, environment: s.org.origin }).idOf(SCRIPT), resource.webresourceid);
+});
+
+test('a write again whose publish is accepted and publishes the OLD content is caught by the read-back: the build stops again, is run again, and a quiet run converges', async () => {
+ const s = scenario();
+ // A row this build created and whose last write it could not confirm, published since with the old content (measured under the lock: a later accepted
+ // publish published the OLD content).
+ const id = '44444444-dddd-4ddd-8ddd-444444444444';
+ s.org.resources.set(id, { webresourceid: id, name: SCRIPT, content: base64('var Old = {};'), publishedContent: base64('var Old = {};') });
+ openUnconfirmedWebResources({ workspaceDir: s.dir, environment: s.org.origin }).note(SCRIPT, id);
+ const stale = s.org.intercept((c) => namesWebResource(c), () => ({ status: 204, headers: {}, body: null }));
+ const run = await s.build(spec());
+ stale();
+ assert.equal(run.halt && run.halt.code, 'WEB_RESOURCE_UNVERIFIED', 'the read-back found the published content is not what was written');
+ assert.match(run.halt.message, /the published content is not what was sent/);
+ assert.equal(retryPolicyFor(run.halt), RETRY.SERVICE, 'with no failure behind it, the build runs again');
+ assert.equal(openUnconfirmedWebResources({ workspaceDir: s.dir, environment: s.org.origin }).idOf(SCRIPT), id, 'still recorded');
+ const quiet = await s.build(spec());
+ assert.ok(quiet.outcome && quiet.outcome.ok, String(quiet.halt && quiet.halt.message));
+ assert.equal(s.row(SCRIPT).publishedContent, base64(SCRIPT_CODE));
+ assert.equal(s.org.calls.filter((c) => c.method === 'POST' && c.path === '/webresourceset').length, 0, 'never created');
+});
+
+test('the build\'s own re-run of the halt writes it again by id in the same invocation — the record carries the row from one attempt to the next', async () => {
+ const s = scenario();
+ refuseWebResourcePublishes(s.org);
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(s.dir), instanceUrl: s.org.origin, httpClient: s.org.httpClient });
+ await sdk.initWorkspace();
+ const result = await buildModelApp(spec(), { apply: true, publish: true, maxRetries: 3, retryDelayMs: 0, appDir: s.dir, workspaceDir: s.dir }, {
+ sdk,
+ warn: (w) => s.warnings.push(String(w)),
+ runBuild: (runSpec, options) => runSdkBuild(runSpec, { ...options, phases: ['web-resources'], env: s.org.origin }),
+ });
+ assert.equal(result.ok, true);
+ assert.deepEqual(writesOf(s.org.calls), ['POST /webresourceset', 'POST /PublishXml webresource', 'POST /AddSolutionComponent web resource', 'PATCH /webresourceset(id)', 'POST /PublishXml webresource', 'POST /AddSolutionComponent web resource'], 'one create; the second attempt wrote it again by id');
+ assert.equal(s.row(SCRIPT).publishedContent, base64(SCRIPT_CODE));
+});
+
+// Two builds that share the workspace recover the same row. A writes it again by its recorded id and verifies the write; while A waits for the answer
+// to its membership add, B writes the same row again from a newer spec, the lock refuses B's publish, and B records its unconfirmed write — under the
+// same id, since it is the same row. A's clear comes after that: it must take only the entry A verified, so that the next build writes B's content again
+// by id instead of reusing the row with A's content published.
+test('a recovery whose membership add is answered after another build recorded a later, unconfirmed write of the same row leaves that record: the next build writes the newer content again by id', async () => {
+ const s = scenario();
+ refuseWebResourcePublishes(s.org);
+ await s.build(spec());
+ const id = s.row(SCRIPT).webresourceid;
+ const NEWER = 'var Form = { onLoad: function () { return 2; } };';
+ let other;
+ const stop = s.org.intercept((c) => c.method === 'POST' && c.path === '/AddSolutionComponent' && String(c.body.ComponentId).toLowerCase() === id, async (c) => {
+ stop();
+ refuseWebResourcePublishes(s.org);
+ other = await s.build(spec([{ name: SCRIPT, type: 'js', content: NEWER }]));
+ return s.org.fake.httpClient.post(`${s.org.origin}/api/data/v9.2${c.path}`, c.body);
+ });
+ const recovered = await s.build(spec());
+ assert.ok(recovered.outcome && recovered.outcome.ok, String(recovered.halt && recovered.halt.message));
+ assert.ok(other && other.halt, 'the other build ran while A waited for its add, and stopped');
+ assert.equal(other.halt.code, 'WEB_RESOURCE_UNVERIFIED', 'its write of the same row unconfirmed');
+ assert.equal(openUnconfirmedWebResources({ workspaceDir: s.dir, environment: s.org.origin }).idOf(SCRIPT), id, 'A\'s clear left the record of that later write');
+ assert.equal(s.row(SCRIPT).publishedContent, base64(SCRIPT_CODE), 'what is published is still what A verified');
+ const next = await s.build(spec([{ name: SCRIPT, type: 'js', content: NEWER }]));
+ assert.ok(next.outcome && next.outcome.ok, String(next.halt && next.halt.message));
+ assert.deepEqual(writesOf(next.calls), ['PATCH /webresourceset(id)', 'POST /PublishXml webresource', 'POST /AddSolutionComponent web resource'], 'the next build writes the row again by id');
+ assert.equal(s.row(SCRIPT).publishedContent, base64(NEWER), 'and what is published is the newer content');
+ assert.equal(fs.existsSync(unconfirmedRecordPath(s.dir, s.org.origin)), false, 'confirmed, the record is gone');
+});
+
+test('a web resource of the name that this build did not write — or whose write it confirmed — is reused untouched, as before: not written, not added', async () => {
+ const s = scenario();
+ // Another maker's row, published: it is in the plain read by name.
+ const theirs = '33333333-cccc-4ccc-8ccc-333333333333';
+ s.org.resources.set(theirs, { webresourceid: theirs, name: SCRIPT, content: base64('var Theirs = {};'), publishedContent: base64('var Theirs = {};') });
+ const run = await s.build(spec());
+ assert.ok(run.outcome && run.outcome.ok);
+ assert.deepEqual(writesOf(run.calls), [], 'not one write');
+ assert.equal(s.org.resources.get(theirs).publishedContent, base64('var Theirs = {};'), 'their content stands');
+ assert.equal(run.outcome.created.webResources[SCRIPT], theirs, 'and it is the one the build uses');
+});
+
+test('a row the record names that is gone by the next run is created again, as on a first build — and the record of it is replaced', async () => {
+ const s = scenario();
+ refuseWebResourcePublishes(s.org);
+ await s.build(spec());
+ const gone = s.row(SCRIPT).webresourceid;
+ s.org.resources.delete(gone);
+ const next = await s.build(spec());
+ assert.ok(next.outcome && next.outcome.ok, String(next.halt && next.halt.message));
+ assert.deepEqual(writesOf(next.calls), ['PATCH /webresourceset(id)', 'POST /webresourceset', 'POST /PublishXml webresource', 'POST /AddSolutionComponent web resource'], 'the write by id found nothing (404), so it was created');
+ assert.notEqual(s.row(SCRIPT).webresourceid, gone);
+ assert.equal(fs.existsSync(unconfirmedRecordPath(s.dir, s.org.origin)), false);
+});
+
+test('without a workspace nothing is recorded, and the halt requires recovery by the known id instead of an automatic phase replay', async () => {
+ const s = scenario();
+ refuseWebResourcePublishes(s.org);
+ const run = await s.build(spec(), { workspaceDir: null });
+ assert.equal(run.halt && run.halt.code, 'WEB_RESOURCE_UNVERIFIED');
+ assert.match(run.halt.message, /this build added it to the solution, but could not save its local recovery record\. Its publication is UNCONFIRMED, not lost/);
+ assert.match(run.halt.message, /will not automatically retry it without that record/);
+ assert.deepEqual(fs.readdirSync(s.dir).filter((f) => f.startsWith(PREFIX)), []);
+});
+
+test('a write whose receipt cannot be saved is not automatically replayed, whether no workspace was supplied or the receipt path is blocked', async () => {
+ for (const blocked of [false, true]) {
+ const s = scenario();
+ if (blocked) fs.mkdirSync(unconfirmedRecordPath(s.dir, s.org.origin));
+ refuseWebResourcePublishes(s.org);
+ const first = await s.build(spec(), blocked ? {} : { workspaceDir: null });
+ assert.equal(first.halt && first.halt.code, 'WEB_RESOURCE_UNVERIFIED');
+ assert.equal(isTransientHalt(first.halt), false, 'without durable identity a phase replay could create the same name again');
+ if (blocked) {
+ assert.match(first.halt.message, /could not save.*record/i);
+ assert.doesNotMatch(first.halt.message, /had no workspace/);
+ }
+ assert.equal(added(first.calls, s.row(SCRIPT).webresourceid).length, 1, 'failed persistence does not skip solution membership');
+ }
+});
+
+test('the solution add refused beside the unconfirmed publish: the halt says so, and the run that follows adds it', async () => {
+ const s = scenario();
+ refuseWebResourcePublishes(s.org);
+ const stop = s.org.intercept((c) => c.method === 'POST' && c.path === '/AddSolutionComponent', () => ({ status: 429, headers: {}, body: { error: LOCK } }));
+ const first = await s.build(spec());
+ stop();
+ assert.match(first.halt.message, /this build recorded the row as its own and could not add it to the solution \(.*429.*; a run again adds it\)/);
+ const id = s.row(SCRIPT).webresourceid;
+ const next = await s.build(spec());
+ assert.ok(next.outcome && next.outcome.ok);
+ assert.equal(added(next.calls, id).length, 1);
+});
+
+test('a solution-add 404 after a verified recovery does not retire the resource receipt or create the name again', async () => {
+ const s = scenario();
+ refuseWebResourcePublishes(s.org);
+ await s.build(spec());
+ const id = s.row(SCRIPT).webresourceid;
+ const refuseAdd = s.org.intercept((c) => c.method === 'POST' && c.path === '/AddSolutionComponent', () => ({ status: 404, headers: {}, body: { error: { message: 'solution was not found' } } }));
+ const next = await s.build(spec());
+ refuseAdd();
+ assert.equal(next.halt && next.halt.code, 'CONNECTION_ERROR');
+ assert.equal(openUnconfirmedWebResources({ workspaceDir: s.dir, environment: s.org.origin }).idOf(SCRIPT), id);
+ assert.equal(s.org.calls.filter((c) => c.method === 'POST' && c.path === '/webresourceset').length, 1, 'a membership failure cannot justify another create');
+ const final = await s.build(spec());
+ assert.ok(final.outcome && final.outcome.ok);
+ assert.equal(added(final.calls, id).length, 1);
+});
+
+test('a permanent solution-add refusal stops automatic replay even when publication was refused transiently', async () => {
+ const s = scenario();
+ refuseWebResourcePublishes(s.org);
+ s.org.intercept((c) => c.method === 'POST' && c.path === '/AddSolutionComponent', () => ({ status: 403, headers: {}, body: { error: { message: 'missing solution component privilege' } } }));
+ const first = await s.build(spec());
+ assert.equal(first.halt && first.halt.code, 'WEB_RESOURCE_UNVERIFIED');
+ assert.equal(retryPolicyFor(first.halt), RETRY.NEVER);
+ assert.match(first.halt.message, /could not add it to the solution/);
+ assert.equal(openUnconfirmedWebResources({ workspaceDir: s.dir, environment: s.org.origin }).idOf(SCRIPT), s.row(SCRIPT).webresourceid);
+});
+
+// --- the generated app icon --------------------------------------------------------------------------------------------------------------------------------
+
+const APP_SPEC = () => ({
+ ...spec([]),
+ appShell: { areas: [{ label: 'Main', groups: [{ label: 'Records', subAreas: [{ entity: 'contoso_item', title: 'Items' }] }] }] },
+});
+const ICON = 'contoso_publishreview_icon';
+
+test('the generated app icon whose publish the lock refuses: the app step stops naming it, the icon is in the solution and recorded — and the next run writes it again by id and builds the app with it', async () => {
+ const s = scenario();
+ // An environment with no icon of that name yet (the fake answers one by default, as for an app built before).
+ const noIcon = s.org.intercept((c) => c.method === 'GET' && /^\/webresources(et)?\?/.test(c.path) && c.path.includes('_icon') && !s.row(ICON), () => ({ status: 200, headers: {}, body: { value: [] } }));
+ refuseWebResourcePublishes(s.org);
+ const first = await s.build(APP_SPEC(), { phases: ['app-shell'] });
+ noIcon();
+ assert.equal(first.halt && first.halt.code, 'WEB_RESOURCE_UNVERIFIED', String(first.halt && first.halt.message));
+ assert.equal(first.halt.phase, 'app-shell');
+ const id = s.row(ICON).webresourceid;
+ assert.match(first.halt.message, new RegExp(`'${ICON}' \\(${id}\\)`));
+ assert.equal(added(first.calls, id).length, 1, 'in the solution');
+ assert.equal(s.org.appId(), undefined, 'the app is not written over an icon that is not confirmed');
+ const next = await s.build(APP_SPEC(), { phases: ['app-shell'] });
+ assert.ok(next.outcome && next.outcome.ok, String(next.halt && next.halt.message));
+ assert.equal(s.org.calls.filter((c) => c.method === 'POST' && c.path === '/webresourceset').length, 1, 'the icon is never created again');
+ assert.ok(next.calls.some((c) => c.method === 'PATCH' && c.path === `/webresourceset(${id})`), 'it is written again by id');
+ assert.equal(next.outcome.created.webResources[ICON], id);
+ const app = s.org.calls.find((c) => c.method === 'POST' && /^\/appmodules(\?|$)/.test(c.path));
+ assert.ok(app, 'and the app is created');
+ assert.equal(String(app.body.webresourceid).toLowerCase(), id, 'with that icon');
+ assert.equal(fs.existsSync(unconfirmedRecordPath(s.dir, s.org.origin)), false);
+});
+
+test('the generated icon recovers by id inside the build retry loop without creating the app or icon twice', async () => {
+ const s = scenario();
+ s.org.intercept((c) => c.method === 'GET' && /^\/webresources(et)?\?/.test(c.path) && c.path.includes('_icon') && !s.row(ICON), () => ({ status: 200, headers: {}, body: { value: [] } }));
+ refuseWebResourcePublishes(s.org);
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(s.dir), instanceUrl: s.org.origin, httpClient: s.org.httpClient });
+ await sdk.initWorkspace();
+ const result = await buildModelApp(APP_SPEC(), { apply: true, publish: true, maxRetries: 3, retryDelayMs: 0, appDir: s.dir, workspaceDir: s.dir }, {
+ sdk,
+ runBuild: (runSpec, options) => runSdkBuild(runSpec, { ...options, phases: ['app-shell'], env: s.org.origin }),
+ });
+ assert.equal(result.ok, true);
+ assert.equal(s.org.calls.filter((c) => c.method === 'POST' && c.path === '/webresourceset').length, 1);
+ assert.equal(s.org.calls.filter((c) => c.method === 'POST' && /^\/appmodules(\?|$)/.test(c.path)).length, 1);
+ assert.equal(s.row(ICON).publishedContent, s.row(ICON).content);
+});
+
+// --- the page manifest -------------------------------------------------------------------------------------------------------------------------------------
+//
+// The pages go through the REAL page backend over the stateful fake of the page service, as in publish-scope-real-bundle.test.js; the manifest is a web
+// resource of the app's fake. The page's identity is the manifest, the page list, and the workspace's creation receipts: what a run after an unconfirmed
+// manifest write does is proven here — it binds the page it created by its receipt, creates no second page, and writes the manifest again by id.
+const { makeGenpageSdk } = require('../lib/genpage-sdk.js');
+const { FakeGenPageServer, ACCOUNT_TABLE } = require('./helpers/fake-genpage-server.js');
+const PAGE_CODE = "import * as React from 'react';\nexport default function Overview() { return <div>Overview</div>; }\n";
+const MANIFEST = 'contoso_publishreview_pagemanifest';
+
+function pageScenario(t) {
+ const s = scenario();
+ const server = new FakeGenPageServer();
+ server.serveTable({ ...ACCOUNT_TABLE, logicalName: 'contoso_page_only', schemaName: 'contoso_PageOnly', entitySetName: 'contoso_page_onlys' });
+ s.org.fake.seedDefaultViews('contoso_page_only', 'Page Data');
+ const pages = makeGenpageSdk(s.org.origin, { httpClient: server.http() });
+ const placement = makeGenpageSdk(s.org.origin, { httpClient: s.org.httpClient });
+ t.after(async () => { await pages.dispose(); await placement.dispose(); });
+ const created = [];
+ const backend = {
+ enumerateEnv: (...args) => pages.enumerateEnv(...args),
+ fileVersions: (...args) => pages.fileVersions(...args),
+ projectVersions: (...args) => pages.projectVersions(...args),
+ publishedDiffers: (...args) => pages.publishedDiffers(...args),
+ read: (...args) => pages.read(...args),
+ create: async (options) => {
+ const result = await pages.create(options);
+ created.push(result.pageId);
+ s.org.pages.set(result.pageId, { uxagentprojectid: result.pageId, name: options.name, componentstate: 0 });
+ return result;
+ },
+ update: (...args) => pages.update(...args),
+ placeInApp: (appId, options) => placement.placeInApp(appId, options),
+ };
+ fs.writeFileSync(path.join(s.dir, 'Overview.tsx'), PAGE_CODE);
+ fs.writeFileSync(path.join(s.dir, 'Details.tsx'), PAGE_CODE.replace(/Overview/g, 'Details'));
+ const pageSpec = ({ details = false } = {}) => {
+ const out = APP_SPEC();
+ out.schemaVersion = 2;
+ out.entities.push({ schemaName: 'contoso_page_only', displayName: 'Page data', existing: true, primaryAttribute: { schemaName: 'contoso_name', displayName: 'Name' }, columns: [] });
+ out.pages = [{ key: 'overview', name: 'Overview', dataSources: ['contoso_page_only'], source: { kind: 'tsx', codeFile: 'Overview.tsx' } }];
+ out.appShell.areas[0].groups[0].subAreas.push({ page: 'overview', title: 'Overview' });
+ if (details) {
+ out.pages.push({ key: 'details', name: 'Details', dataSources: ['contoso_page_only'], source: { kind: 'tsx', codeFile: 'Details.tsx' } });
+ out.appShell.areas[0].groups[0].subAreas.push({ page: 'details', title: 'Details' });
+ }
+ return out;
+ };
+ const manifest = () => {
+ const wr = s.row(MANIFEST);
+ return wr && wr.publishedContent ? JSON.parse(Buffer.from(wr.publishedContent, 'base64').toString('utf8')) : null;
+ };
+ return { ...s, backend, created, pageSpec, manifest, build: (built, options = {}) => s.build(built, { phases: ['app-shell', 'pages', 'publish'], genpage: backend, ...options }) };
+}
+const manifestCreates = (calls) => calls.filter((c) => c.method === 'POST' && c.path === '/webresourceset' && c.body.name === MANIFEST).length;
+const listsPages = (m) => (m && Array.isArray(m.pages) ? m.pages.map((p) => p.pageId).filter(Boolean).sort() : []);
+
+test('a page manifest whose first write the lock refuses: the pages step stops naming it, the manifest is in the solution and recorded; the next run creates no second page and writes the manifest again by id', async (t) => {
+ const p = pageScenario(t);
+ refuseWebResourcePublishes(p.org);
+ const first = await p.build(p.pageSpec());
+ assert.equal(first.halt && first.halt.code, 'WEB_RESOURCE_UNVERIFIED', String(first.halt && first.halt.message));
+ assert.equal(first.halt.phase, 'pages');
+ const id = p.row(MANIFEST).webresourceid;
+ assert.match(first.halt.message, new RegExp(`'${MANIFEST}' \\(${id}\\)`));
+ assert.equal(p.created.length, 1, 'the page was created');
+ assert.equal(added(first.calls, id).length, 1, 'the manifest is in the solution');
+ assert.equal(p.manifest(), null, 'and nothing of it is published');
+ const next = await p.build(p.pageSpec());
+ assert.ok(next.outcome && next.outcome.ok, String(next.halt && next.halt.message));
+ assert.equal(p.created.length, 1, 'no second page: the run binds the page it created by its creation receipt');
+ assert.equal(manifestCreates(p.org.calls), 1, 'and never creates the manifest\'s name again');
+ assert.ok(next.calls.some((c) => c.method === 'PATCH' && c.path === `/webresourceset(${id})`), 'it writes it by the id the record holds — no plain read finds a manifest never published');
+ assert.deepEqual(listsPages(p.manifest()), p.created, 'the published manifest names the page');
+ assert.equal(fs.existsSync(unconfirmedRecordPath(p.dir, p.org.origin)), false);
+});
+
+test('the same, inside one invocation: the build\'s own re-run of the halt binds the page it created, writes the manifest by id and finishes', async (t) => {
+ const p = pageScenario(t);
+ refuseWebResourcePublishes(p.org);
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(p.dir), instanceUrl: p.org.origin, httpClient: p.org.httpClient });
+ await sdk.initWorkspace();
+ const result = await buildModelApp(p.pageSpec(), { apply: true, publish: true, maxRetries: 3, retryDelayMs: 0, appDir: p.dir, workspaceDir: p.dir }, {
+ sdk,
+ warn: (w) => p.warnings.push(String(w)),
+ runBuild: (runSpec, options) => runSdkBuild(runSpec, { ...options, phases: ['app-shell', 'pages', 'publish'], env: p.org.origin, genpage: p.backend }),
+ });
+ assert.equal(result.ok, true, JSON.stringify(result.errors || result.halt));
+ assert.equal(p.created.length, 1, 'one page');
+ assert.equal(manifestCreates(p.org.calls), 1, 'one create of the manifest');
+ assert.deepEqual(listsPages(p.manifest()), p.created);
+});
+
+test('a manifest UPDATE whose publish the lock refuses — a second page added: the next run reads the published manifest (the old one), binds the new page by its receipt, and writes the manifest again by the id it read', async (t) => {
+ const p = pageScenario(t);
+ const first = await p.build(p.pageSpec());
+ assert.ok(first.outcome && first.outcome.ok, String(first.halt && first.halt.message));
+ const id = p.row(MANIFEST).webresourceid;
+ // The publish of the manifest that names the new page — the write made right after its create — is the one the lock refuses.
+ let refusals = 1;
+ p.org.intercept((c) => namesWebResource(c) && p.created.length === 2 && refusals > 0 && (refusals -= 1, true), lockRefused);
+ const second = await p.build(p.pageSpec({ details: true }));
+ assert.equal(second.halt && second.halt.code, 'WEB_RESOURCE_UNVERIFIED', String(second.halt && second.halt.message));
+ assert.equal(p.created.length, 2, 'the second page was created');
+ assert.deepEqual(listsPages(p.manifest()), [p.created[0]], 'the published manifest does not name the new page');
+ const third = await p.build(p.pageSpec({ details: true }));
+ assert.ok(third.outcome && third.outcome.ok, String(third.halt && third.halt.message));
+ assert.equal(p.created.length, 2, 'no third page');
+ assert.equal(manifestCreates(p.org.calls), 1, 'one create of the manifest, in three runs');
+ assert.ok(third.calls.some((c) => c.method === 'PATCH' && c.path === `/webresourceset(${id})`));
+ assert.deepEqual(listsPages(p.manifest()), [...p.created].sort());
+ assert.equal(fs.existsSync(unconfirmedRecordPath(p.dir, p.org.origin)), false);
+});
+
+test('an unconfirmed manifest update names the manifest and recovers inside one invocation without another page', async (t) => {
+ const p = pageScenario(t);
+ await p.build(p.pageSpec());
+ let left = 1;
+ p.org.intercept((c) => namesWebResource(c) && p.created.length === 2 && left > 0 && (left -= 1, true), lockRefused);
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(p.dir), instanceUrl: p.org.origin, httpClient: p.org.httpClient });
+ await sdk.initWorkspace();
+ const halts = [];
+ const result = await buildModelApp(p.pageSpec({ details: true }), { apply: true, publish: true, maxRetries: 3, retryDelayMs: 0, appDir: p.dir, workspaceDir: p.dir }, {
+ sdk,
+ runBuild: async (runSpec, options) => {
+ try { return await runSdkBuild(runSpec, { ...options, phases: ['app-shell', 'pages', 'publish'], env: p.org.origin, genpage: p.backend }); }
+ catch (e) { halts.push(e); throw e; }
+ },
+ });
+ assert.equal(result.ok, true);
+ assert.equal(halts.length, 1);
+ assert.match(halts[0].message, /Web resource 'contoso_publishreview_pagemanifest'/);
+ assert.equal(p.created.length, 2);
+ assert.equal(manifestCreates(p.org.calls), 1);
+ assert.deepEqual(listsPages(p.manifest()), [...p.created].sort());
+});
+
+test('a published manifest whose id contradicts the unconfirmed receipt is refused before page work, never overwritten as the build\'s own row', async (t) => {
+ const p = pageScenario(t);
+ await p.build(p.pageSpec());
+ const original = p.row(MANIFEST);
+ openUnconfirmedWebResources({ workspaceDir: p.dir, environment: p.org.origin }).note(MANIFEST, original.webresourceid);
+ p.org.resources.delete(original.webresourceid);
+ p.org.resources.set(ID_B, { ...original, webresourceid: ID_B });
+ const next = await p.build(p.pageSpec({ details: true }));
+ assert.equal(next.halt && next.halt.code, 'WEB_RESOURCE_IDENTITY_CONFLICT');
+ assert.equal(retryPolicyFor(next.halt), RETRY.NEVER);
+ assert.equal(p.created.length, 1, 'identity is checked before creating another page');
+ assert.ok(!next.calls.some((c) => c.method !== 'GET' && c.path.includes(ID_B)), 'no write or add of the replacement');
+ assert.equal(p.org.resources.get(ID_B).content, original.content);
+ assert.equal(openUnconfirmedWebResources({ workspaceDir: p.dir, environment: p.org.origin }).idOf(MANIFEST), original.webresourceid);
+});
+
+test('a recorded manifest renamed to another resource is refused before page writes even though its old name is absent', async (t) => {
+ const p = pageScenario(t);
+ refuseWebResourcePublishes(p.org);
+ await p.build(p.pageSpec());
+ const resource = p.row(MANIFEST);
+ resource.name = 'fabrikam_/foreign_manifest.js';
+ resource.publishedContent = resource.content;
+ const next = await p.build(p.pageSpec({ details: true }));
+ assert.equal(next.halt && next.halt.code, 'WEB_RESOURCE_IDENTITY_CONFLICT');
+ assert.equal(p.created.length, 1);
+ assert.ok(!next.calls.some((c) => c.method === 'PATCH' && c.path.includes(resource.webresourceid)));
+ assert.equal(openUnconfirmedWebResources({ workspaceDir: p.dir, environment: p.org.origin }).idOf(MANIFEST), resource.webresourceid);
+});
+
+test('an unchanged rebuild of an app with pages writes no manifest, and reads no record file it does not have — the requests are what they were', async (t) => {
+ const p = pageScenario(t);
+ await p.build(p.pageSpec());
+ const again = await p.build(p.pageSpec());
+ assert.ok(again.outcome && again.outcome.ok);
+ assert.ok(!again.calls.some((c) => c.method !== 'GET' && /webresourceset/.test(c.path)), 'no write of any web resource');
+ assert.ok(!again.calls.some((c) => namesWebResource(c)), 'and no publish of one');
+});
+
+test('a publish refused for good (403) stops the build once — the row is still recorded and in the solution — and the run after the cause is resolved writes it again by id', async () => {
+ const s = scenario();
+ const refusal = s.org.intercept((c) => namesWebResource(c), () => ({ status: 403, headers: {}, body: { error: { code: '0x80040220', message: 'Principal user is missing prvPublishCustomizations privilege. Try again later.' } } }));
+ const sdk = createMakerSdk({ workspaceStorage: createNodeWorkspaceStorage(s.dir), instanceUrl: s.org.origin, httpClient: s.org.httpClient });
+ await sdk.initWorkspace();
+ const halted = await buildModelApp(spec(), { apply: true, publish: true, maxRetries: 3, retryDelayMs: 0, appDir: s.dir, workspaceDir: s.dir }, {
+ sdk,
+ warn: (w) => s.warnings.push(String(w)),
+ runBuild: (runSpec, options) => runSdkBuild(runSpec, { ...options, phases: ['web-resources'], env: s.org.origin }),
+ }).then(() => assert.fail('a refused publish is no success'), (e) => e);
+ assert.equal(halted.code, 'WEB_RESOURCE_UNVERIFIED');
+ assert.equal(retryPolicyFor(halted), RETRY.NEVER, 'a 403 is a verdict');
+ assert.equal(s.org.calls.filter((c) => namesWebResource(c)).length, 1, 'so the build did not run again');
+ assert.match(halted.message, /Resolve that failure first/, 'the SDK\u2019s words say to resolve the cause first');
+ const id = s.row(SCRIPT).webresourceid;
+ assert.equal(added(s.org.calls, id).length, 1, 'the row is in the solution');
+ assert.equal(openUnconfirmedWebResources({ workspaceDir: s.dir, environment: s.org.origin }).idOf(SCRIPT), id, 'and recorded');
+ refusal();
+ const next = await s.build(spec());
+ assert.ok(next.outcome && next.outcome.ok, String(next.halt && next.halt.message));
+ assert.deepEqual(writesOf(next.calls), ['PATCH /webresourceset(id)', 'POST /PublishXml webresource', 'POST /AddSolutionComponent web resource']);
+ assert.equal(s.row(SCRIPT).publishedContent, base64(SCRIPT_CODE));
+});
diff --git a/plugins/model-apps/scripts/tests/workspace-projection-real-bundle.test.js b/plugins/model-apps/scripts/tests/workspace-projection-real-bundle.test.js
index 2b64e35b6..98787fee9 100644
--- a/plugins/model-apps/scripts/tests/workspace-projection-real-bundle.test.js
+++ b/plugins/model-apps/scripts/tests/workspace-projection-real-bundle.test.js
@@ -123,7 +123,7 @@ test('REAL BUNDLE: an old copy holding unpushed edits is refused at push, and th
assert.strictEqual(err.code, 'ARTIFACT_PROJECTION_STALE', 'with the SDK code kept for the caller');
assert.match(err.message, /Refusing to push app/, 'the SDK reason stays in the message');
assert.match(err.message, /earlier version of this plugin/, 'it says where the copy came from');
- assert.match(err.message, /To reset it, stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json, destructive-approval\.json and the page-ownership\.\*\.json records \(the receipts and pending records of the pages the app created: nothing else can find them\), and re-run/,
+ assert.match(err.message, /To reset it, stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json, destructive-approval\.json, web-resource-unconfirmed\.\*\.json \(the durable ids needed to recover unconfirmed web-resource writes\), dashboard-creation\.\*\.json \(the ids of the dashboards an interrupted build created before they joined the solution\) and the page-ownership\.\*\.json records \(the receipts and pending records of the pages the app created: nothing else can find them\), and re-run/,
'and names the step an operator can take, keeping the navigation baseline, the approval record and the page records');
return true;
});
@@ -146,7 +146,7 @@ test('REAL BUNDLE: a copy holding unpushed edits over a moved environment halts
assert.ok(err instanceof BuildHalt);
assert.strictEqual(err.code, 'LOCAL_EDITS_WOULD_BE_LOST', 'the SDK code is kept');
assert.match(err.message, /the environment's copy changed after this workspace copy was fetched/);
- assert.match(err.message, /A re-run applies the spec over that change, so first look at it in Maker and put into the spec anything that should stay; then stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json, destructive-approval\.json and the page-ownership\.\*\.json records \(the receipts and pending records of the pages the app created: nothing else can find them\), and re-run\./,
+ assert.match(err.message, /A re-run applies the spec over that change, so first look at it in Maker and put into the spec anything that should stay; then stop any other build or teardown using the \.maker-workspace directory \(or the --workspace one\), then delete everything in it except last-applied\.json, destructive-approval\.json, web-resource-unconfirmed\.\*\.json \(the durable ids needed to recover unconfirmed web-resource writes\), dashboard-creation\.\*\.json \(the ids of the dashboards an interrupted build created before they joined the solution\) and the page-ownership\.\*\.json records \(the receipts and pending records of the pages the app created: nothing else can find them\), and re-run\./,
'the review comes before the reset: the copy may be the fence a concurrent-edit halt keeps');
return true;
});
diff --git a/plugins/model-apps/scripts/vendor/PROVENANCE.json b/plugins/model-apps/scripts/vendor/PROVENANCE.json
index 8f172d545..8e3124815 100644
--- a/plugins/model-apps/scripts/vendor/PROVENANCE.json
+++ b/plugins/model-apps/scripts/vendor/PROVENANCE.json
@@ -1,13 +1,13 @@
{
- "commit": "d603c7996f7918da669b3ef16c6fa63f5b9fb7a0",
+ "commit": "a3443479b88ec538be2e74293fa92230c4ef1aab",
"dirtySdkPackage": 0,
- "libBuiltAt": "2026-10-20T01:32:45.044Z",
- "newestSrcAt": "2026-10-20T01:31:52.361Z",
+ "libBuiltAt": "2026-10-20T20:18:04.982Z",
+ "newestSrcAt": "2026-10-20T19:21:12.668Z",
"libIsStale": false,
"nostub": false,
"esbuildVersion": "0.28.1",
- "nodeVersion": "v20.20.2",
- "builtAt": "2026-10-20T01:34:40.388Z",
- "bundleSha256": "16246ee08fe653de994989f08fbf4a8e243f4d3cbe961a7c89c40be37bef1a88",
- "bundleBytes": 1020302
+ "nodeVersion": "v24.21.0",
+ "builtAt": "2026-10-20T20:20:30.581Z",
+ "bundleSha256": "eebd70a2a7f6e12e45d18744640fd803479a738bc936b8e0dce1a9f97a0a4f8c",
+ "bundleBytes": 1029451
}
diff --git a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs
index c8ac6679b..6f798fd8d 100644
--- a/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs
+++ b/plugins/model-apps/scripts/vendor/cds-maker-sdk.cjs
@@ -25,33 +25,33 @@
}
globalThis.document=globalThis.document||globalThis.window.document;
})();
-var AU=Object.create;var bc=Object.defineProperty;var SU=Object.getOwnPropertyDescriptor;var NU=Object.getOwnPropertyNames;var _U=Object.getPrototypeOf,TU=Object.prototype.hasOwnProperty;var k=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var v=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Hr=(e,t)=>{for(var r in t)bc(e,r,{get:t[r],enumerable:!0})},yc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of NU(t))!TU.call(e,i)&&i!==r&&bc(e,i,{get:()=>t[i],enumerable:!(n=SU(t,i))||n.enumerable});return e},Ji=(e,t,r)=>(yc(e,t,"default"),r&&yc(r,t,"default")),Ee=(e,t,r)=>(r=e!=null?AU(_U(e)):{},yc(t||!e||!e.__esModule?bc(r,"default",{value:e,enumerable:!0}):r,e)),Fr=e=>yc(bc({},"__esModule",{value:!0}),e);var Yi=v(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.DateTimeBehavior=T.PrecisionSource=T.StringFormatName=T.SourceType=T.ImeMode=T.SolutionEntityTypeCodeExtToComponentTypeCode=T.SolutionComponentTypeCodeToEntityTypeCodeExt=T.SolutionComponentVirtualAttributeSubtype=T.EntityTypeCode=T.SolutionComponentTypeCodeExt=T.RootComponentBehavior=T.SolutionComponentTypeCode=T.EntityKeyIndexStatus=T.ViewStateCode=T.ViewStatusCode=T.RelationshipSecurityTypes=T.CascadeType=T.RelationshipTypeExt=T.RelationshipType=T.AppSubType=T.BusinessProcessType=T.WorkflowCategory=T.WorkflowScope=T.WorkflowTypeCode=T.StatusCodeEnabledDisabled=T.StateCodeEnabledDisabled=T.StatusCode=T.StateCode=T.OptionSetType=T.AttributeTypeCodeNum=T.AttributeFormatName=T.AttributeFormatCode=T.AttributeTypeName=T.AttributeTypeCode=T.PluginSourceType=T.AuthType=T.PluginIsolationMode=T.ComponentState=T.ChartType=T.ChartsType=T.ViewType=T.AttributeType=T.ActivationState=T.FormPresentation=T.FormType=T.TableTypeCode=T.TableTypes=T.ActivityTypeMask=T.PrincipalType=T.OwnershipTypes=void 0;T.QueryType=T.KnownCustomSolutionComponentEntitySetName=T.TeamTypeEnum=T.EnvironmentVariableDefinitionTypeEnum=T.ConnectorTypeEnum=T.RoleInheritance=T.DefaultRoleTemplates=T.DeleteDependencyErrorCode=T.ServiceEndpointConnectionMode=T.ServiceEndpointContract=T.ServiceNamespaceFormat=T.ConnectionRoleCategory=T.ReportTypeCode=T.SdkMessageProcessingMode=T.SupportedDeployment=T.SdkMessageProcessingStage=T.WebResourceTypeCode=T.IntegerFormat=T.DateTimeFormat=void 0;var Yv;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(Yv||(T.OwnershipTypes=Yv={}));var Qv;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(Qv||(T.PrincipalType=Qv={}));var Xv;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(Xv||(T.ActivityTypeMask=Xv={}));var Zv;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(Zv||(T.TableTypes=Zv={}));var ew;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(ew||(T.TableTypeCode=ew={}));var tw;(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"})(tw||(T.FormType=tw={}));var rw;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(rw||(T.FormPresentation=rw={}));var nw;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(nw||(T.ActivationState=nw={}));var iw;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(iw||(T.AttributeType=iw={}));var ow;(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"})(ow||(T.ViewType=ow={}));var aw;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(aw||(T.ChartsType=aw={}));var sw;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(sw||(T.ChartType=sw={}));var lw;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(lw||(T.ComponentState=lw={}));var uw;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(uw||(T.PluginIsolationMode=uw={}));var cw;(function(e){e[e.BasicAuth=0]="BasicAuth"})(cw||(T.AuthType=cw={}));var dw;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(dw||(T.PluginSourceType=dw={}));var fw;(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"})(fw||(T.AttributeTypeCode=fw={}));var pw;(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"})(pw||(T.AttributeTypeName=pw={}));var mw;(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"})(mw||(T.AttributeFormatCode=mw={}));var hw;(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"})(hw||(T.AttributeFormatName=hw={}));var gw;(function(e){e[e.Boolean=0]="Boolean",e[e.Customer=1]="Customer",e[e.DateTime=2]="DateTime",e[e.Decimal=3]="Decimal",e[e.Double=4]="Double",e[e.Integer=5]="Integer",e[e.Lookup=6]="Lookup",e[e.Memo=7]="Memo",e[e.Money=8]="Money",e[e.Owner=9]="Owner",e[e.PartyList=10]="PartyList",e[e.Picklist=11]="Picklist",e[e.State=12]="State",e[e.Status=13]="Status",e[e.String=14]="String",e[e.Uniqueidentifier=15]="Uniqueidentifier",e[e.CalendarRules=16]="CalendarRules",e[e.Virtual=17]="Virtual",e[e.BigInt=18]="BigInt",e[e.ManagedProperty=19]="ManagedProperty",e[e.EntityName=20]="EntityName"})(gw||(T.AttributeTypeCodeNum=gw={}));var yw;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(yw||(T.OptionSetType=yw={}));var bw;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(bw||(T.StateCode=bw={}));var vw;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(vw||(T.StatusCode=vw={}));var ww;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(ww||(T.StateCodeEnabledDisabled=ww={}));var Cw;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(Cw||(T.StatusCodeEnabledDisabled=Cw={}));var Ew;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(Ew||(T.WorkflowTypeCode=Ew={}));var Aw;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(Aw||(T.WorkflowScope=Aw={}));var Sw;(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"})(Sw||(T.WorkflowCategory=Sw={}));var Nw;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(Nw||(T.BusinessProcessType=Nw={}));var _w;(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"})(_w||(T.AppSubType=_w={}));var Tw;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Tw||(T.RelationshipType=Tw={}));var Dw;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Dw||(T.RelationshipTypeExt=Dw={}));var Iw;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(Iw||(T.CascadeType=Iw={}));var Ow;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(Ow||(T.RelationshipSecurityTypes=Ow={}));var Pw;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(Pw||(T.ViewStatusCode=Pw={}));var Rw;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(Rw||(T.ViewStateCode=Rw={}));var Lw;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(Lw||(T.EntityKeyIndexStatus=Lw={}));var kw;(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"})(kw||(T.SolutionComponentTypeCode=kw={}));var $w;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})($w||(T.RootComponentBehavior=$w={}));var vc;(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"})(vc||(T.SolutionComponentTypeCodeExt=vc={}));var wc;(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"})(wc||(T.EntityTypeCode=wc={}));var xw;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(xw||(T.SolutionComponentVirtualAttributeSubtype=xw={}));function DU(e){let t=vc[e];return wc[t]}T.SolutionComponentTypeCodeToEntityTypeCodeExt=DU;function IU(e){let t=wc[e];return vc[t]}T.SolutionEntityTypeCodeExtToComponentTypeCode=IU;var Fw;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(Fw||(T.ImeMode=Fw={}));var Mw;(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"})(Mw||(T.SourceType=Mw={}));var Uw;(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"})(Uw||(T.StringFormatName=Uw={}));var Bw;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(Bw||(T.PrecisionSource=Bw={}));var qw;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(qw||(T.DateTimeBehavior=qw={}));var Vw;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(Vw||(T.DateTimeFormat=Vw={}));var Gw;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(Gw||(T.IntegerFormat=Gw={}));var Ww;(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"})(Ww||(T.WebResourceTypeCode=Ww={}));var zw;(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"})(zw||(T.SdkMessageProcessingStage=zw={}));var jw;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(jw||(T.SupportedDeployment=jw={}));var Hw;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(Hw||(T.SdkMessageProcessingMode=Hw={}));var Kw;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(Kw||(T.ReportTypeCode=Kw={}));var Jw;(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"})(Jw||(T.ConnectionRoleCategory=Jw={}));var Yw;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(Yw||(T.ServiceNamespaceFormat=Yw={}));var Qw;(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"})(Qw||(T.ServiceEndpointContract=Qw={}));var Xw;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(Xw||(T.ServiceEndpointConnectionMode=Xw={}));var Zw;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(Zw||(T.DeleteDependencyErrorCode=Zw={}));var eC;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(eC||(T.DefaultRoleTemplates=eC={}));var tC;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(tC||(T.RoleInheritance=tC={}));var rC;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(rC||(T.ConnectorTypeEnum=rC={}));var nC;(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"})(nC||(T.EnvironmentVariableDefinitionTypeEnum=nC={}));var iC;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(iC||(T.TeamTypeEnum=iC={}));var oC;(function(e){e.Bots="bots"})(oC||(T.KnownCustomSolutionComponentEntitySetName=oC={}));var aC;(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"})(aC||(T.QueryType=aC={}))});var Q=v(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.IncompatibleWorkspaceError=X.PathTraversalError=X.AmbiguousArtifactError=X.JsonPointerError=X.NotImplementedError=X.WorkspaceOrgMismatchError=X.WorkspaceNotInitializedError=X.attachCause=X.ConnectionError=X.VersionConflictError=X.LocalEditsWouldBeLostError=X.StaleArtifactError=X.InvalidArgumentError=X.ValidationError=X.PathNotFoundError=X.ArtifactNotFoundError=X.readCleanupWarnings=X.withCleanupWarnings=X.readPartialEnrichment=X.withPartialEnrichment=X.readPartialTokens=X.withPartialTokens=X.SdkError=void 0;var wt=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};X.SdkError=wt;var sC=Symbol.for("cds-maker-sdk.partialWriteTokens");function OU(e,t){return typeof e=="object"&&e!==null&&(e[sC]=t),e}X.withPartialTokens=OU;function PU(e){return wm(e,sC)}X.readPartialTokens=PU;function wm(e,t){let r=e;for(let n=0;r&&typeof r=="object"&&n<8;n++){let i=r[t];if(i&&typeof i=="object")return i;r=r.cause}}var lC=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function RU(e,t){return typeof e=="object"&&e!==null&&(e[lC]=t),e}X.withPartialEnrichment=RU;function LU(e){return wm(e,lC)}X.readPartialEnrichment=LU;var im=Symbol.for("cds-maker-sdk.cleanupWarnings");function kU(e,t){if(typeof e=="object"&&e!==null&&t.length>0){let r=e,n=r[im];r[im]=[...Array.isArray(n)?n:[],...t]}return e}X.withCleanupWarnings=kU;function $U(e){let t=wm(e,im);return t?[...t]:void 0}X.readCleanupWarnings=$U;var om=class extends wt{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};X.ArtifactNotFoundError=om;var am=class extends wt{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};X.PathNotFoundError=am;var sm=class extends wt{constructor(t,r,n,i){var o,a,s,l;let u=Array.isArray(n)?n:[{pointer:n,rule:i??"invalid",message:i??"invalid"}];super("VALIDATION_ERROR",`Validation failed for ${t}/${r}:
+var kU=Object.create;var Nc=Object.defineProperty;var LU=Object.getOwnPropertyDescriptor;var $U=Object.getOwnPropertyNames;var xU=Object.getPrototypeOf,FU=Object.prototype.hasOwnProperty;var L=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var v=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Jr=(e,t)=>{for(var r in t)Nc(e,r,{get:t[r],enumerable:!0})},Sc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of $U(t))!FU.call(e,i)&&i!==r&&Nc(e,i,{get:()=>t[i],enumerable:!(n=LU(t,i))||n.enumerable});return e},Yi=(e,t,r)=>(Sc(e,t,"default"),r&&Sc(r,t,"default")),Ae=(e,t,r)=>(r=e!=null?kU(xU(e)):{},Sc(t||!e||!e.__esModule?Nc(r,"default",{value:e,enumerable:!0}):r,e)),Br=e=>Sc(Nc({},"__esModule",{value:!0}),e);var Qi=v(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.DateTimeBehavior=T.PrecisionSource=T.StringFormatName=T.SourceType=T.ImeMode=T.SolutionEntityTypeCodeExtToComponentTypeCode=T.SolutionComponentTypeCodeToEntityTypeCodeExt=T.SolutionComponentVirtualAttributeSubtype=T.EntityTypeCode=T.SolutionComponentTypeCodeExt=T.RootComponentBehavior=T.SolutionComponentTypeCode=T.EntityKeyIndexStatus=T.ViewStateCode=T.ViewStatusCode=T.RelationshipSecurityTypes=T.CascadeType=T.RelationshipTypeExt=T.RelationshipType=T.AppSubType=T.BusinessProcessType=T.WorkflowCategory=T.WorkflowScope=T.WorkflowTypeCode=T.StatusCodeEnabledDisabled=T.StateCodeEnabledDisabled=T.StatusCode=T.StateCode=T.OptionSetType=T.AttributeTypeCodeNum=T.AttributeFormatName=T.AttributeFormatCode=T.AttributeTypeName=T.AttributeTypeCode=T.PluginSourceType=T.AuthType=T.PluginIsolationMode=T.ComponentState=T.ChartType=T.ChartsType=T.ViewType=T.AttributeType=T.ActivationState=T.FormPresentation=T.FormType=T.TableTypeCode=T.TableTypes=T.ActivityTypeMask=T.PrincipalType=T.OwnershipTypes=void 0;T.QueryType=T.KnownCustomSolutionComponentEntitySetName=T.TeamTypeEnum=T.EnvironmentVariableDefinitionTypeEnum=T.ConnectorTypeEnum=T.RoleInheritance=T.DefaultRoleTemplates=T.DeleteDependencyErrorCode=T.ServiceEndpointConnectionMode=T.ServiceEndpointContract=T.ServiceNamespaceFormat=T.ConnectionRoleCategory=T.ReportTypeCode=T.SdkMessageProcessingMode=T.SupportedDeployment=T.SdkMessageProcessingStage=T.WebResourceTypeCode=T.IntegerFormat=T.DateTimeFormat=void 0;var ow;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(ow||(T.OwnershipTypes=ow={}));var aw;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(aw||(T.PrincipalType=aw={}));var sw;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(sw||(T.ActivityTypeMask=sw={}));var lw;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(lw||(T.TableTypes=lw={}));var uw;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(uw||(T.TableTypeCode=uw={}));var cw;(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"})(cw||(T.FormType=cw={}));var dw;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(dw||(T.FormPresentation=dw={}));var fw;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(fw||(T.ActivationState=fw={}));var pw;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(pw||(T.AttributeType=pw={}));var mw;(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"})(mw||(T.ViewType=mw={}));var hw;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(hw||(T.ChartsType=hw={}));var gw;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(gw||(T.ChartType=gw={}));var yw;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(yw||(T.ComponentState=yw={}));var bw;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(bw||(T.PluginIsolationMode=bw={}));var vw;(function(e){e[e.BasicAuth=0]="BasicAuth"})(vw||(T.AuthType=vw={}));var ww;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(ww||(T.PluginSourceType=ww={}));var Cw;(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"})(Cw||(T.AttributeTypeCode=Cw={}));var Ew;(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"})(Ew||(T.AttributeTypeName=Ew={}));var Aw;(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"})(Aw||(T.AttributeFormatCode=Aw={}));var Sw;(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"})(Sw||(T.AttributeFormatName=Sw={}));var Nw;(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"})(Nw||(T.AttributeTypeCodeNum=Nw={}));var _w;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(_w||(T.OptionSetType=_w={}));var Tw;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(Tw||(T.StateCode=Tw={}));var Dw;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(Dw||(T.StatusCode=Dw={}));var Iw;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(Iw||(T.StateCodeEnabledDisabled=Iw={}));var Ow;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(Ow||(T.StatusCodeEnabledDisabled=Ow={}));var Pw;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(Pw||(T.WorkflowTypeCode=Pw={}));var Rw;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(Rw||(T.WorkflowScope=Rw={}));var kw;(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"})(kw||(T.WorkflowCategory=kw={}));var Lw;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(Lw||(T.BusinessProcessType=Lw={}));var $w;(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"})($w||(T.AppSubType=$w={}));var xw;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(xw||(T.RelationshipType=xw={}));var Fw;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Fw||(T.RelationshipTypeExt=Fw={}));var Mw;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(Mw||(T.CascadeType=Mw={}));var Uw;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(Uw||(T.RelationshipSecurityTypes=Uw={}));var Bw;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(Bw||(T.ViewStatusCode=Bw={}));var qw;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(qw||(T.ViewStateCode=qw={}));var Vw;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(Vw||(T.EntityKeyIndexStatus=Vw={}));var Gw;(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"})(Gw||(T.SolutionComponentTypeCode=Gw={}));var Ww;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(Ww||(T.RootComponentBehavior=Ww={}));var _c;(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"})(_c||(T.SolutionComponentTypeCodeExt=_c={}));var Tc;(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"})(Tc||(T.EntityTypeCode=Tc={}));var zw;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(zw||(T.SolutionComponentVirtualAttributeSubtype=zw={}));function MU(e){let t=_c[e];return Tc[t]}T.SolutionComponentTypeCodeToEntityTypeCodeExt=MU;function UU(e){let t=Tc[e];return _c[t]}T.SolutionEntityTypeCodeExtToComponentTypeCode=UU;var jw;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(jw||(T.ImeMode=jw={}));var Hw;(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"})(Hw||(T.SourceType=Hw={}));var Kw;(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"})(Kw||(T.StringFormatName=Kw={}));var Jw;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(Jw||(T.PrecisionSource=Jw={}));var Yw;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(Yw||(T.DateTimeBehavior=Yw={}));var Qw;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(Qw||(T.DateTimeFormat=Qw={}));var Xw;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(Xw||(T.IntegerFormat=Xw={}));var Zw;(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"})(Zw||(T.WebResourceTypeCode=Zw={}));var eC;(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"})(eC||(T.SdkMessageProcessingStage=eC={}));var tC;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(tC||(T.SupportedDeployment=tC={}));var rC;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(rC||(T.SdkMessageProcessingMode=rC={}));var nC;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(nC||(T.ReportTypeCode=nC={}));var iC;(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"})(iC||(T.ConnectionRoleCategory=iC={}));var oC;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(oC||(T.ServiceNamespaceFormat=oC={}));var aC;(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"})(aC||(T.ServiceEndpointContract=aC={}));var sC;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(sC||(T.ServiceEndpointConnectionMode=sC={}));var lC;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(lC||(T.DeleteDependencyErrorCode=lC={}));var uC;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(uC||(T.DefaultRoleTemplates=uC={}));var cC;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(cC||(T.RoleInheritance=cC={}));var dC;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(dC||(T.ConnectorTypeEnum=dC={}));var fC;(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"})(fC||(T.EnvironmentVariableDefinitionTypeEnum=fC={}));var pC;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(pC||(T.TeamTypeEnum=pC={}));var mC;(function(e){e.Bots="bots"})(mC||(T.KnownCustomSolutionComponentEntitySetName=mC={}));var hC;(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"})(hC||(T.QueryType=hC={}))});var Q=v(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.IncompatibleWorkspaceError=X.PathTraversalError=X.AmbiguousArtifactError=X.JsonPointerError=X.NotImplementedError=X.WorkspaceOrgMismatchError=X.WorkspaceNotInitializedError=X.attachCause=X.WebResourceUnverifiedError=X.ConnectionError=X.VersionConflictError=X.LocalEditsWouldBeLostError=X.StaleArtifactError=X.InvalidArgumentError=X.ValidationError=X.PathNotFoundError=X.ArtifactNotFoundError=X.readCleanupWarnings=X.withCleanupWarnings=X.readPartialEnrichment=X.withPartialEnrichment=X.readPartialTokens=X.withPartialTokens=X.SdkError=void 0;var dt=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};X.SdkError=dt;var gC=Symbol.for("cds-maker-sdk.partialWriteTokens");function BU(e,t){return typeof e=="object"&&e!==null&&(e[gC]=t),e}X.withPartialTokens=BU;function qU(e){return Dm(e,gC)}X.readPartialTokens=qU;function Dm(e,t){let r=e;for(let n=0;r&&typeof r=="object"&&n<8;n++){let i=r[t];if(i&&typeof i=="object")return i;r=r.cause}}var yC=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function VU(e,t){return typeof e=="object"&&e!==null&&(e[yC]=t),e}X.withPartialEnrichment=VU;function GU(e){return Dm(e,yC)}X.readPartialEnrichment=GU;var dm=Symbol.for("cds-maker-sdk.cleanupWarnings");function WU(e,t){if(typeof e=="object"&&e!==null&&t.length>0){let r=e,n=r[dm];r[dm]=[...Array.isArray(n)?n:[],...t]}return e}X.withCleanupWarnings=WU;function zU(e){let t=Dm(e,dm);return t?[...t]:void 0}X.readCleanupWarnings=zU;var fm=class extends dt{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};X.ArtifactNotFoundError=fm;var pm=class extends dt{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};X.PathNotFoundError=pm;var mm=class extends dt{constructor(t,r,n,i){var o,a,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=(a=(o=u[0])===null||o===void 0?void 0:o.pointer)!==null&&a!==void 0?a:"",this.rule=(l=(s=u[0])===null||s===void 0?void 0:s.rule)!==null&&l!==void 0?l:"invalid"}};X.ValidationError=sm;var lm=class extends wt{constructor(t){super("INVALID_ARGUMENT",t)}};X.InvalidArgumentError=lm;var um=class extends wt{constructor(t,r,n,i="revalidated"){super("STALE_ARTIFACT",i==="pushed"?`Cannot apply the edit at ${n} to ${t}/${r}: a push made after this pointer's copy was read replaced the local copy with the record the server holds, which differs from that copy (ids and defaults the SDK filled in at save, a rewrite the platform made on save, or another writer's save), so the pointer may now identify a different node. Read the whole artifact (getArtifact), re-derive the pointer, and retry.`:`Cannot apply the edit at ${n} to ${t}/${r}: the cached copy was stale and the server copy has since changed, so any pointer derived from the old copy may now identify a different node. The local copy has been refreshed \u2014 re-read the artifact, re-derive the pointer, and retry.`),this.type=t,this.id=r,this.pointer=n,this.reason=i}};X.StaleArtifactError=um;var cm=class extends wt{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}};X.LocalEditsWouldBeLostError=cm;var dm=class extends wt{constructor(t,r,n,i,o){super("VERSION_CONFLICT",`Version conflict for ${t}/${r}: local=${n??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.${o?` ${o}`:""}`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i,this.detail=o}};X.VersionConflictError=dm;var fm=class extends wt{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,Object.defineProperty(this,"cause",{value:i,enumerable:!1,writable:!1,configurable:!0})}};X.ConnectionError=fm;function xU(e,t){return typeof e=="object"&&e!==null&&Object.defineProperty(e,"cause",{value:t,enumerable:!1,writable:!0,configurable:!0}),e}X.attachCause=xU;var pm=class extends wt{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};X.WorkspaceNotInitializedError=pm;var mm=class extends wt{constructor(t,r){super("WORKSPACE_ORG_MISMATCH",`This workspace belongs to ${t?`'${t}'`:"no recorded org"}, but this SDK targets '${r}'. Its local copies, baselines and cached metadata are that org's, so nothing was read or written. Use one workspace per org, or call cleanWorkspace() to discard this workspace's contents and bind it to '${r}'.`),this.workspaceInstanceUrl=t,this.instanceUrl=r}};X.WorkspaceOrgMismatchError=mm;var hm=class extends wt{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};X.NotImplementedError=hm;var gm=class extends wt{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};X.JsonPointerError=gm;var ym=class extends wt{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}};X.AmbiguousArtifactError=ym;var bm=class extends wt{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}};X.PathTraversalError=bm;var vm=class extends wt{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}};X.IncompatibleWorkspaceError=vm});var se=v(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.odataQuery=rt.normalizeGuid=rt.createSafeXmlElement=rt.assertNoControlChars=rt.assertODataName=rt.assertXmlName=rt.xmlText=rt.odataPathLiteral=rt.odataLiteral=void 0;var Cc=Q();function uC(e){return String(e??"").replace(/'/g,"''")}rt.odataLiteral=uC;function FU(e){return encodeURIComponent(uC(e))}rt.odataPathLiteral=FU;function MU(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}rt.xmlText=MU;function cC(e,t){let r=String(e??""),n=/^[A-Za-z_][0-9A-Za-z_.-]*$/,i=r.split(":");if(!(i.length<=2&&i.every(a=>n.test(a))&&!/^xmlns/i.test(r)))throw new Cc.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}rt.assertXmlName=cC;function UU(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new Cc.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}rt.assertODataName=UU;function BU(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new Cc.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}rt.assertNoControlChars=BU;function qU(e,t,r){return e.createElement(cC(t,r))}rt.createSafeXmlElement=qU;var VU=/^[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 GU(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!VU.test(n))throw new Cc.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}rt.normalizeGuid=GU;function WU(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}rt.odataQuery=WU});var ye=v(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.nowIso=j.isAlreadyDeleted=j.deleteRecord=j.resendAppSearchIndexRace=j.resendDeadlockVictim=j.resendWhile=j.isAppSearchIndexRace=j.namesAppSearchIndexRace=j.isTransactionNotStarted=j.TRANSACTION_NOT_STARTED_CODE=j.LOCK_BACKOFF_MS=j.isConcurrencyLockRefusal=j.CONCURRENCY_LOCK_CODE=j.AMBIGUOUS_WRITE_STATUSES=j.DEADLOCK_BACKOFF_MS=j.isSqlDeadlockVictim=j.ensureSuccess=j.resolveCreatedId=j.requireCreatedId=j.withClientMintedId=j.readCreatedId=j.readRowEtag=j.readEtag=j.requireEtag=j.isVersionToken=j.echoWrite=j.UPDATE_NO_ETAG_CODE=j.VERSION_CONFLICT_CODE=void 0;var Pa=Q(),Ra=se();j.VERSION_CONFLICT_CODE="VERSION_CONFLICT";j.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function zU(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}j.echoWrite=zU;function dC(e){return typeof e=="string"&&e.trim()!==""&&e.trim()!=="*"}j.isVersionToken=dC;function jU(e,t,r){if(!dC(e))throw new Pa.SdkError(j.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${r}': ${e?`the concurrency token held for it ('${e}') is not a version`:"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}j.requireEtag=jU;function fC(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}j.readEtag=fC;async function HU(e,t,r,n){let i=`/${t}(${n})${(0,Ra.odataQuery)([["$select",r]])}`;return fC(Em(await e.get(i),e.apiUrl(i)))}j.readRowEtag=HU;function Cm(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,Ra.normalizeGuid)(n[t],t);let i=(r=e.headers)!==null&&r!==void 0?r:{};for(let o of Object.keys(i))if(o.toLowerCase()==="odata-entityid"){let a=/\(([0-9a-fA-F-]{36})\)/.exec(i[o]);if(a)return(0,Ra.normalizeGuid)(a[1],t)}return null}j.readCreatedId=Cm;function KU(e,t,r){return r?{...e,[t]:(0,Ra.normalizeGuid)(r,t)}:e}j.withClientMintedId=KU;function JU(e,t,r){let n=Cm(e,t);if(!n)throw new Pa.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}j.requireCreatedId=JU;function YU(e,t,r,n){let i=Cm(e,t);if(i)return i;if(n)return(0,Ra.normalizeGuid)(n,t);throw new Pa.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}j.resolveCreatedId=YU;function Em(e,t){if(e.status===412)throw new Pa.SdkError(j.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new Pa.ConnectionError(t,e.status,rB(e.body),e.body);return e}j.ensureSuccess=Em;function pC(e){if(e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/\bSql Number:\s*1205\b/i.test(t)}j.isSqlDeadlockVictim=pC;j.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];j.AMBIGUOUS_WRITE_STATUSES=new Set([408,502,503,504]);j.CONCURRENCY_LOCK_CODE="0x80071151";function QU(e){var t,r;if(e.status!==429)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.CONCURRENCY_LOCK_CODE}j.isConcurrencyLockRefusal=QU;j.LOCK_BACKOFF_MS=[2e3,3e3,...Array.from({length:35},()=>5e3)];j.TRANSACTION_NOT_STARTED_CODE="0x80040251";function XU(e){var t,r;if(e.status!==500)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.TRANSACTION_NOT_STARTED_CODE}j.isTransactionNotStarted=XU;var ZU=/(?:^|[^a-z0-9_])AppModule_DVTableSearch_M365AppModuleId(?![a-z0-9_])/i;function mC(e){return ZU.test(e)&&/\bSql Number:\s*547\b/i.test(e)}j.namesAppSearchIndexRace=mC;function hC(e){return e.status!==400||e.body===void 0||e.body===null?!1:mC(typeof e.body=="string"?e.body:JSON.stringify(e.body))}j.isAppSearchIndexRace=hC;async function Am(e,t,r=j.DEADLOCK_BACKOFF_MS){for(let n=0;;n+=1){let i=await t();if(n>=r.length||!e(i))return i;await new Promise(o=>setTimeout(o,r[n]))}}j.resendWhile=Am;function eB(e){return Am(pC,e,j.DEADLOCK_BACKOFF_MS)}j.resendDeadlockVictim=eB;function tB(e){return Am(hC,e,j.DEADLOCK_BACKOFF_MS)}j.resendAppSearchIndexRace=tB;function rB(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 nB(e,t,r,n){let i=(0,Ra.normalizeGuid)(r,"id"),o=`/${t}(${i})`;Em(await e.delete(o,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(o))}j.deleteRecord=nB;function iB(e){return e instanceof Pa.ConnectionError&&e.statusCode===404}j.isAlreadyDeleted=iB;function oB(){return new Date().toISOString()}j.nowIso=oB});var Lt=v(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.describeMalformedValue=La.collectPages=void 0;var gC=ye(),Sm=Q();async function aB(e,t,r,n,i){let o=[],a=new Set,s=e.apiUrl(t),l=(0,gC.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new Sm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${Nm(c)}; refusing to return partial results.`);for(let f of c)o.push(f);let d=u?.["@odata.nextLink"];if(d==null)break;if(typeof d!="string"||d.length===0)throw new Sm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${Nm(d)}); cannot follow it, and refusing to return partial results.`);if(a.has(d))throw new Sm.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);a.add(d),s=d,l=(0,gC.ensureSuccess)(await e.getAbsolute(d,i),d)}return o}La.collectPages=aB;function Nm(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}La.describeMalformedValue=Nm});var _m=v(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.assertWorkflowKind=Lo.WORKFLOW_KIND_MISMATCH_CODE=void 0;var Ro=Yi(),sB=Q(),yC=ye(),lB=se();Lo.WORKFLOW_KIND_MISMATCH_CODE="WORKFLOW_KIND_MISMATCH";var bC={[Ro.WorkflowCategory.Workflow]:"classic workflow",[Ro.WorkflowCategory.Dialog]:"dialog",[Ro.WorkflowCategory.BusinessRule]:"business rule",[Ro.WorkflowCategory.Action]:"custom action",[Ro.WorkflowCategory.BusinessProcessFlow]:"business process flow",[Ro.WorkflowCategory.Flow]:"cloud flow",[Ro.WorkflowCategory.UIFlow]:"desktop flow"};async function uB(e,t,r){var n,i;let o=`/workflows(${t})${(0,lB.odataQuery)([["$select","category"]])}`,a=await e.get(o);if(a.status===404)return null;(0,yC.ensureSuccess)(a,e.apiUrl(o));let s=(n=a.body)===null||n===void 0?void 0:n.category,l=typeof s=="number"?s:typeof s=="string"&&s!==""?Number(s):NaN;if(l!==r){let u=Number.isFinite(l)?`a ${(i=bC[l])!==null&&i!==void 0?i:"process"} (category ${l})`:"a process whose category could not be read";throw new sB.SdkError(Lo.WORKFLOW_KIND_MISMATCH_CODE,`Refusing to delete workflow '${t}' as a ${bC[r]}: it is ${u}. Nothing was changed. Check the id.`)}return(0,yC.readEtag)(a)}Lo.assertWorkflowKind=uB});var Dm=v(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.deleteWorkflowResending=Kr.isWorkflowDeleteUnsettled=Kr.failedAfterResend=Kr.WORKFLOW_DELETE_UNSETTLED_CODE=void 0;var ml=Q(),mi=ye(),wC=se();Kr.WORKFLOW_DELETE_UNSETTLED_CODE="WORKFLOW_DELETE_UNSETTLED";var CC=new WeakSet;function Tm(e){return typeof e=="object"&&e!==null&&CC.add(e),e}function cB(e){return typeof e=="object"&&e!==null&&CC.has(e)}Kr.failedAfterResend=cB;function dB(e){return e instanceof ml.SdkError&&e.code===Kr.WORKFLOW_DELETE_UNSETTLED_CODE}Kr.isWorkflowDeleteUnsettled=dB;function fB(e,t){try{(0,mi.ensureSuccess)(e,t)}catch(r){return r}}function pB(e){return(0,mi.isSqlDeadlockVictim)(e)?"lost a SQL deadlock (HTTP 500, Sql Number 1205)":`lost its transaction (HTTP 500 ${mi.TRANSACTION_NOT_STARTED_CODE})`}async function vC(e,t){try{return(await e.get(`/workflows(${t})${(0,wC.odataQuery)([["$select","workflowid"]])}`)).status===404}catch{return!1}}async function mB(e,t,{bindingToken:r,kindName:n,deactivated:i=!1,resendDeadlockVictim:o=!1,ifMatchOnFirst:a=!1}){let s=(0,wC.normalizeGuid)(t,"id");if(a&&!r)throw new ml.InvalidArgumentError(`Refusing to delete ${n} '${s}': its delete must be conditional on a token this operation holds, and it holds none.`);let l=`/workflows(${s})`,u=e.apiUrl(l),c=p=>(0,mi.isTransactionNotStarted)(p)||o&&(0,mi.isSqlDeadlockVictim)(p),d=0,f,m;try{m=await(0,mi.resendWhile)(c,async()=>{d+=1;let p=d>1||a,h=await e.delete(l,p?{headers:{"If-Match":r}}:void 0);return f=f??h,h},r?mi.DEADLOCK_BACKOFF_MS:[])}catch(p){if(p instanceof ml.ConnectionError&&p.statusCode===0&&r&&await vC(e,s))return;throw d>1?Tm(p):p}if(!(d>1&&m.status===404)){if(d>1&&m.status===412){let p=pB(f),h=new ml.SdkError(Kr.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting ${n} '${s}' ${p}, and its re-send was refused (HTTP 412): the row at that id is no longer the version this delete checked \u2014 it was edited, or deleted and re-created at the same id \u2014 so nothing more was deleted. `+(i?"This delete had deactivated the process first and has NOT re-activated it: it MAY be left DISABLED. ":"")+"Read the row before deleting it again.");throw Tm((0,ml.attachCause)(h,fB(f,u)))}if(!(r&&mi.AMBIGUOUS_WRITE_STATUSES.has(m.status)&&await vC(e,s)))try{(0,mi.ensureSuccess)(m,u)}catch(p){throw d>1?Tm(p):p}}}Kr.deleteWorkflowResending=mB});var Im=v(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.businessRuleApi=Un.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=Un.WFOM_API_UNAVAILABLE_CODE=void 0;var Mn=Yi(),hB=Lt(),gB=_m(),yB=Dm(),Vt=ye(),hi=se(),Ac=Q();Un.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";Un.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function EC(e,t,r,n){let i=`/workflows(${wB})/Microsoft.Dynamics.CRM.${t}`;try{return(0,Vt.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new Ac.SdkError(Un.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 bB(e,t){let r=`/workflows(${t})${(0,hi.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,Vt.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function vB(e,t,r){let n=await bB(e,t);if(n===null||n.etag===null)throw new Ac.SdkError(Vt.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 Ac.SdkError(Vt.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 wB="00000000-0000-0000-0000-000000000000",Ec={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},CB="workflowid,name,description,primaryentity,statecode,category,type",EB="category eq 2 and type eq 1";async function AC(e,t,r){var n;if(r==="Draft")return null;let i=(0,hi.normalizeGuid)(t,"workflowid"),o=r==="Active",a={statecode:o?Mn.StateCode.Activated:Mn.StateCode.Draft,statuscode:o?Mn.StatusCode.Activated:Mn.StatusCode.Draft},s=`/workflows(${i})`,l=(0,Vt.ensureSuccess)(await e.patch(s,a,{headers:Ec}),e.apiUrl(s));return(n=(0,Vt.readEtag)(l))!==null&&n!==void 0?n:await hl(e,i)}async function hl(e,t){let r=`/workflows(${t})${(0,hi.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,Vt.readEtag)(n):null}catch{return null}}async function AB(e,t,r){let n=await hl(e,t),i=await r(),o=(0,Vt.readEtag)(i);if(o)return{response:i,etag:o};let a=await hl(e,t);return{response:i,etag:n!==null&&n===a?a:null}}Un.businessRuleApi={async get(e,t){let r=(0,hi.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await AB(e,r,async()=>(0,Vt.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:o}},async list(e,t){let r=[EB];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,hi.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,hi.odataQuery)([["$select",CB],["$filter",r.join(" and ")]])}`;return(await(0,hB.collectPages)(e,n,"listArtifacts('businessRule')")).map(o=>{var a,s;return{type:"businessRule",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){var r;let n=t,i=(0,hi.normalizeGuid)(n.Entity.workflowid,"workflowid"),o=await EC(e,"CreateProcessWithWfomJson",n,Ec),a=(0,Vt.resolveCreatedId)(o,"workflowid","business rule",i),s=null;try{s=await AC(e,a,n.status)}catch(l){try{await(0,Vt.deleteRecord)(e,"workflows",a)}catch{}throw l}return{id:a,etag:(r=s??(0,Vt.readEtag)(o))!==null&&r!==void 0?r:await hl(e,a)}},async update(e,t,r,n){var i,o;let a=r,s=(0,hi.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...Ec,"If-Match":(0,Vt.requireEtag)(n,"business rule",s)},c=await vB(e,s,u["If-Match"]),d=c.statecode===Mn.StateCode.Activated;d&&(0,Vt.ensureSuccess)(await e.patch(l,{statecode:Mn.StateCode.Draft,statuscode:Mn.StatusCode.Draft},{headers:u}),e.apiUrl(l));let f;try{f=await EC(e,"UpdateProcessWithWfomJson",a,u)}catch(p){if(d)try{(0,Vt.ensureSuccess)(await e.patch(l,{statecode:Mn.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:Mn.StatusCode.Activated},{headers:Ec}),e.apiUrl(l))}catch(h){throw new Ac.SdkError(Un.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: ${p instanceof Error?p.message:String(p)}. Restore failure: ${h instanceof Error?h.message:String(h)}`)}throw p}let m=await AC(e,s,a.status);return{id:s,etag:(o=m??(0,Vt.readEtag)(f))!==null&&o!==void 0?o:await hl(e,s)}},async delete(e,t){let r=(0,hi.normalizeGuid)(t,"id"),n=await(0,gB.assertWorkflowKind)(e,r,Mn.WorkflowCategory.BusinessRule);return(0,yB.deleteWorkflowResending)(e,r,{bindingToken:n,kindName:"business rule"})}}});var Jr=v(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.publishBoundEntity=Ct.boundEntityPublishScope=Ct.publishGenPageById=Ct.publishDashboardById=Ct.publishWebResourceById=Ct.publishEntity=Ct.publishAppModule=Ct.publishXml=void 0;var SC=ye(),gl=se(),NC="/PublishXml";async function ka(e,t){(0,SC.ensureSuccess)(await(0,SC.resendDeadlockVictim)(()=>e.post(NC,{ParameterXml:t})),e.apiUrl(NC))}Ct.publishXml=ka;function SB(e,t){return ka(e,`<importexportxml><appmodules><appmodule>${(0,gl.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}Ct.publishAppModule=SB;function _C(e,t){return ka(e,`<importexportxml><entities><entity>${(0,gl.xmlText)(t)}</entity></entities></importexportxml>`)}Ct.publishEntity=_C;function NB(e,t){return ka(e,`<importexportxml><webresources><webresource>${(0,gl.xmlText)(t)}</webresource></webresources></importexportxml>`)}Ct.publishWebResourceById=NB;function _B(e,t){return ka(e,`<importexportxml><dashboards><dashboard>${(0,gl.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}Ct.publishDashboardById=_B;function TB(e,t){return ka(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,gl.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}Ct.publishGenPageById=TB;function DB(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}Ct.boundEntityPublishScope=DB;function IB(e,t){let r=t?.entityLogicalName;return r?_C(e,r):Promise.resolve()}Ct.publishBoundEntity=IB});var $a=v(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});Nc.JsonPointer=void 0;var Mr=Q(),Sc=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 Mr.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new Mr.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 o of n)if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0)return;i=i[a]}else if(i!==null&&typeof i=="object"){let a=i;if(e.isReservedToken(o)||!Object.prototype.hasOwnProperty.call(a,o))return;i=a[o]}else return;return i}static set(t,r,n){let i=e.parse(r);if(i.length===0)throw new Mr.JsonPointerError(r,"cannot set the document root");let{parent:o,lastToken:a}=e.resolveParent(t,i,r);if(Array.isArray(o)){let s=e.toArrayIndex(a,o.length);if(s===void 0)throw new Mr.JsonPointerError(r,`'${a}' is not a valid array index`);if(s>o.length)throw new Mr.JsonPointerError(r,`array index '${a}' is out of range`);o[s]=n}else{if(e.isReservedToken(a))throw new Mr.JsonPointerError(r,`refusing to write reserved property '${a}'`);o[a]=n}}static remove(t,r){let n=e.parse(r);if(n.length===0)throw new Mr.JsonPointerError(r,"cannot remove the document root");let{parent:i,lastToken:o}=e.resolveParent(t,n,r);if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0||a>=i.length)throw new Mr.JsonPointerError(r,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new Mr.JsonPointerError(r,`refusing to remove reserved property '${o}'`);delete i[o]}}static add(t,r,n,i){let o=e.parse(r);if(o.length>0&&o[o.length-1]==="-"){let l=e.compile(o.slice(0,-1)),u=e.resolve(t,l);if(!Array.isArray(u))throw new Mr.JsonPointerError(r,"add target must be an array");u.push(n);return}let a=e.resolve(t,r);if(!Array.isArray(a))throw new Mr.JsonPointerError(r,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new Mr.JsonPointerError(r,`insert index ${s} is out of range`);a.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],o=e.compile(r.slice(0,-1)),a=e.resolve(t,o);if(a===null||typeof a!="object")throw new Mr.JsonPointerError(n,"parent path does not resolve to an object or array");return{parent:a,lastToken:i}}static toArrayIndex(t,r){if(t==="-")return r;if(/^(0|[1-9][0-9]*)$/.test(t))return Number(t)}};Nc.JsonPointer=Sc;Sc.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var DC=v(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.findElements=void 0;var TC=$a();function OB(e,t){let r=[];return Om(e,"",t,r),r}_c.findElements=OB;function Om(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,o)=>{Om(i,TC.JsonPointer.append(t,o),r,n)});else for(let i of Object.keys(e))Om(e[i],TC.JsonPointer.append(t,i),r,n)}});var Pm=v(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.assertMutationResult=Bn.assertExistsResult=Bn.assertReadResult=Bn.assertStorageContract=void 0;var PB=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],RB=["ensureContainer","exists"];function LB(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of PB)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of RB){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}Bn.assertStorageContract=LB;function kB(e,t){if(e===null||typeof e=="string")return e;throw new Error(`workspaceStorage.readText must resolve to a string or null for ${t}; got ${typeof e}. Absence is null \u2014 resolving undefined would make a present value look absent.`)}Bn.assertReadResult=kB;function $B(e,t){if(typeof e=="boolean")return e;throw new Error(`workspaceStorage.exists must resolve to a boolean for ${t}; got ${typeof e}. A truthy non-boolean would make an absent value look present.`)}Bn.assertExistsResult=$B;function xB(e,t){if(e!==void 0)throw new Error(`workspaceStorage.${t} must resolve to undefined; got ${typeof e}. A status-returning implementation would let a failed write be reported as a completed one.`)}Bn.assertMutationResult=xB});var Rm=v(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.retryTransientIoAsync=xa.retryTransientIo=void 0;var FB=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),MB=5,IC=10;function UB(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!OC(r,t))throw r;qB(IC*t)}}xa.retryTransientIo=UB;async function BB(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!OC(r,t))throw r;await new Promise(n=>setTimeout(n,IC*t))}}xa.retryTransientIoAsync=BB;function OC(e,t){let r=e.code;return t<MB&&!!r&&FB.has(r)}function qB(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var $C=v(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.canonicalArtifactId=Ur.WorkspaceManager=Ur.WORKSPACE_SCHEMA_VERSION=Ur.retryTransientIo=void 0;var Gt=Pm(),qn=Q(),VB=Rm();Object.defineProperty(Ur,"retryTransientIo",{enumerable:!0,get:function(){return VB.retryTransientIo}});function PC(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Ur.WORKSPACE_SCHEMA_VERSION=1;var Qi={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},GB="manifest.json",Fa=".metadata",Lm="entities";function RC(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}function km(e){if(e.schemaVersion!==void 0&&e.schemaVersion>Ur.WORKSPACE_SCHEMA_VERSION)throw new qn.IncompatibleWorkspaceError(e.schemaVersion,Ur.WORKSPACE_SCHEMA_VERSION)}function LC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tc(e){return e.trim().toLowerCase().replace(/\/+$/,"")}var $m=class{withManifest(t){let r=this.manifestQueue.then(t,t);return this.manifestQueue=r.then(()=>{},()=>{}),r}constructor(t,r,n){if(this.workspaceLabel=t,this.instanceUrl=r,this.manifestQueue=Promise.resolve(),this.bound=!1,n==null)throw new Error("WorkspaceManager requires a WorkspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'.");this.storage=n}artifactKey(t,r){return this.assertSafeId(r),[Qi[t],`${yl(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[Fa,Qi[t],`${yl(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[Fa,Lm,`${t.toLowerCase()}.json`]}fsStore(){let t=PC(this.storage);if(!t)throw new Error("This workspace is not filesystem-backed, so it has no physical paths. Use the artifact/metadata/manifest accessors instead of the path helpers.");return t}getRoot(){let t=PC(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([Qi[t]])}getArtifactFilePath(t,r){return this.fsStore().pathFor(this.artifactKey(t,r))}getMetaFilePath(t,r){return this.fsStore().pathFor(this.metaKey(t,r))}getEntityMetaFilePath(t){return this.fsStore().pathFor(this.entityKey(t))}assertSafeId(t){if(typeof t!="string"||t.length===0||/[\u0000-\u001f]/.test(t)||t.includes("/")||t.includes("\\")||t.includes(":")||t==="."||t===".."||t.includes(".."))throw new qn.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[GB]}assertDataKey(t,r){if(!Array.isArray(t)||t.length<2)throw new qn.InvalidArgumentError(`${r} writes only inside the workspace's folders; '${String(t)}' is at its root, where only the manifest lives \u2014 and the manifest is changed only by the workspace itself.`);t.forEach(n=>this.assertSafeId(n))}async init(){let t=await this.withManifest(async()=>{let r=await this.readStoredManifest();return r.present&&this.assertBoundHere(r.value),r.present});await this.ensureLayout(),t||await this.withManifest(async()=>{let r=await this.readStoredManifest();if(r.present){this.assertBoundHere(r.value);return}let n={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};await this.writeManifest(n)}),this.bound=!0}async readStoredManifest(){let t=(0,Gt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json");return t===null?{present:!1}:{present:!0,value:JSON.parse(t)}}async ensureLayout(){if(!this.storage.ensureContainer)return;let t=this.storage.ensureContainer.bind(this.storage),r=[[Fa,Lm]];for(let i of Object.keys(Qi))r.push([Qi[i]],[Fa,Qi[i]]);let n=await Promise.allSettled(r.map(i=>RC(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,Gt.assertMutationResult)(i.value,"ensureContainer")}}async isInitialized(){return this.storage.exists?(0,Gt.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,Gt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json")!==null}async ensureInitialized(){if(!this.bound){await this.verifyBinding();return}if(!await this.isInitialized())throw new qn.WorkspaceNotInitializedError(this.workspaceLabel)}async ensureReady(){await this.ensureInitialized()}async ensureBound(){this.bound||await this.verifyBinding()}verifyBinding(){if(!this.verifying){let t=()=>{this.verifying=void 0};this.verifying=this.readAndCheckBinding().then(t,r=>{throw t(),r})}return this.verifying}async readAndCheckBinding(){let t=await this.readStoredManifest();if(!t.present)throw new qn.WorkspaceNotInitializedError(this.workspaceLabel);this.assertBoundHere(t.value),this.bound=!0}assertBoundHere(t){if(!LC(t))throw new qn.WorkspaceOrgMismatchError("",this.instanceUrl);km(t);let r=typeof t.instanceUrl=="string"?t.instanceUrl.trim():"",n=Tc(r);if(!n||n!==Tc(this.instanceUrl))throw new qn.WorkspaceOrgMismatchError(r,this.instanceUrl)}async clean(){let t=await this.readStoredManifest();if(!t.present||!LC(t.value))throw new qn.WorkspaceNotInitializedError(this.workspaceLabel);let r=t.value;km(r);let n=Object.keys(Qi).map(o=>[Qi[o]]);n.push([Fa]);let i=await Promise.allSettled(n.map(o=>RC(()=>this.storage.deleteByPrefix(o))));for(let o of i){if(o.status==="rejected")throw o.reason;(0,Gt.assertMutationResult)(o.value,"deleteByPrefix")}await this.ensureLayout(),await this.withManifest(()=>this.writeManifest({...r,instanceUrl:this.instanceUrl,artifacts:[],lastSyncAt:void 0})),this.bound=!0}async readArtifact(t,r){return await this.ensureInitialized(),this.readJsonUnchecked(this.artifactKey(t,r))}async readArtifactWithText(t,r){await this.ensureInitialized();let n=this.artifactKey(t,r),i=(0,Gt.assertReadResult)(await this.storage.readText(n),n.join("/"));return i===null?null:{artifact:JSON.parse(i),text:i}}async writeArtifact(t,r,n,i){await this.ensureInitialized();let o=kC(n);if(i!==void 0&&o===i){await this.upsertManifestEntry(t,r,n,{unlessCurrent:!0});return}(0,Gt.assertMutationResult)(await this.storage.writeTextAtomic(this.artifactKey(t,r),o),"writeTextAtomic"),await this.upsertManifestEntry(t,r,n)}async deleteArtifact(t,r){await this.ensureInitialized(),(0,Gt.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,Gt.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=yl(r);await this.withManifest(async()=>{let i=await this.getManifest();i.artifacts=i.artifacts.filter(o=>!(o.type===t&&o.id===n)),await this.writeManifest(i)})}async readMeta(t,r){return await this.ensureBound(),this.readJsonUnchecked(this.metaKey(t,r))}async writeMeta(t,r,n){await this.ensureBound(),await this.writeJsonUnchecked(this.metaKey(t,r),n)}async listArtifacts(t,r){return await this.ensureInitialized(),(await this.getManifest()).artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}async readEntityMetadata(t){await this.ensureInitialized();let r=await this.readJsonUnchecked(this.entityKey(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}async writeEntityMetadata(t,r){await this.ensureInitialized(),await this.writeJsonUnchecked(this.entityKey(t),r)}async dropEntityMetadata(t){if(await this.ensureInitialized(),t===void 0){(0,Gt.assertMutationResult)(await this.storage.deleteByPrefix([Fa,Lm]),"deleteByPrefix");return}(0,Gt.assertMutationResult)(await this.storage.deleteFile(this.entityKey(t)),"deleteFile")}async getManifest(){await this.ensureInitialized();let t=await this.readJsonUnchecked(this.manifestKey);if(!t)throw new qn.WorkspaceNotInitializedError(this.workspaceLabel);return km(t),t}async writeManifest(t){await this.writeJsonUnchecked(this.manifestKey,{...t,schemaVersion:Ur.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();if(t.instanceUrl!==void 0&&Tc(String(t.instanceUrl))!==Tc(r.instanceUrl))throw new qn.InvalidArgumentError("updateManifest cannot change the workspace's org: it is bound to the org it was created for. cleanWorkspace() discards its contents and binds it to the org of the SDK that calls it.");await this.writeManifest({...r,...t,instanceUrl:r.instanceUrl})})}async upsertManifestEntry(t,r,n,i={}){await this.withManifest(async()=>{let o=await this.getManifest(),a=yl(r),s=n,l=typeof s.name=="string"?s.name:`${t}:${a}`,u=typeof s.entityLogicalName=="string"?s.entityLogicalName:void 0,c=o.artifacts.find(d=>d.type===t&&d.id===a);i.unlessCurrent&&c?.name===l&&c.entityLogicalName===u||(c?(c.name=l,c.entityLogicalName=u):o.artifacts.push({type:t,id:a,name:l,entityLogicalName:u,isDirty:!1}),await this.writeManifest(o))})}async readJson(t){return await this.ensureBound(),this.readJsonUnchecked(t)}async writeJson(t,r){this.assertDataKey(t,"writeJson"),await this.ensureBound(),await this.writeJsonUnchecked(t,r)}async removeFile(t){this.assertDataKey(t,"removeFile"),await this.ensureBound(),(0,Gt.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return await this.ensureBound(),this.storage.exists?(0,Gt.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,Gt.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}async readJsonUnchecked(t){let r=(0,Gt.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJsonUnchecked(t,r){(0,Gt.assertMutationResult)(await this.storage.writeTextAtomic(t,kC(r)),"writeTextAtomic")}};Ur.WorkspaceManager=$m;function kC(e){return`${JSON.stringify(e,null,2)}
-`}function yl(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()}Ur.canonicalArtifactId=yl});var xm=v(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.deepEqual=Ma.deepDiff=void 0;var WB=$a();function zB(e,t){let r=[];return FC(e,t,"",r,0),r}Ma.deepDiff=zB;var Dc=Symbol("missing"),Ic=512;function FC(e,t,r,n,i){if(e===t)return;if(i>Ic)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${Ic}`);let o=Oc(e),a=Oc(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=jB(e,t);for(let l of s){let u=xC(e,l),c=xC(t,l),d=WB.JsonPointer.append(r,l);u===Dc?n.push({pointer:d,type:"added",newValue:c}):c===Dc?n.push({pointer:d,type:"removed",oldValue:u}):FC(u,c,d,n,i+1)}return}MC(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function Oc(e){return e!==null&&typeof e=="object"}function jB(e,t){if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length),i=[];for(let o=0;o<n;o++)i.push(String(o));return i}let r=new Set([...Object.keys(e),...Object.keys(t)]);return Array.from(r)}function xC(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:Dc}return t in e?e[t]:Dc}function MC(e,t){return UC(e,t,0)}Ma.deepEqual=MC;function UC(e,t,r){if(e===t)return!0;if(r>Ic)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${Ic}`);if(!Oc(e)||!Oc(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(o=>o in t&&UC(e[o],t[o],r+1))}});var qC=v(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.VersionManager=Ua.PROJECTION_VERSION=void 0;var BC=xm(),HB=ye();Ua.PROJECTION_VERSION=8;var Fm=class{constructor(t){this.workspace=t}async storeMeta(t,r,n,i){var o;let a=i===void 0?await this.getMeta(t,r):i,s=((o=n.snapshot)===null||o===void 0?void 0:o.status)==="Active",l=a?.everActivated===!0||s;await this.workspace.writeMeta(t,r,l?{...n,everActivated:l}:n)}async getMeta(t,r){return this.workspace.readMeta(t,r)}async isDirty(t,r,n){let i=await this.workspace.readArtifact(t,r);if(i===null)return!1;let o=n===void 0?await this.getMeta(t,r):n;return o?!(0,BC.deepEqual)(o.snapshot,i):!0}async diff(t,r){let n=await this.workspace.readArtifact(t,r),i=await this.getMeta(t,r),o;return n===null?o=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?o=(0,BC.deepDiff)(i.snapshot,n):o=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:o}}async checkConflict(t,r,n){let i=await this.getMeta(t,r);return!i||!(0,HB.isVersionToken)(i.etag)?!0:i.etag!==n}};Ua.VersionManager=Fm});var GC=v((Mm,VC)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof Mm=="object"?VC.exports=t():e.compareVersions=t()})(Mm,function(){var e=/^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;function t(o,a){return o.indexOf(a)===-1?o.length:o.indexOf(a)}function r(o){var a=o.replace(/^v/,"").replace(/\+.*$/,""),s=t(a,"-"),l=a.substring(0,s).split(".");return l.push(a.substring(s+1)),l}function n(o){return isNaN(Number(o))?o:Number(o)}function i(o){if(typeof o!="string")throw new TypeError("Invalid argument expected string");if(!e.test(o))throw new Error("Invalid argument not valid semver ('"+o+"' received)")}return function(a,s){[a,s].forEach(i);for(var l=r(a),u=r(s),c=0;c<Math.max(l.length-1,u.length-1);c++){var d=parseInt(l[c]||0,10),f=parseInt(u[c]||0,10);if(d>f)return 1;if(f>d)return-1}var m=l[l.length-1],p=u[u.length-1];if(m&&p){var h=m.split(".").map(n),g=p.split(".").map(n);for(c=0;c<Math.max(h.length,g.length);c++){if(h[c]===void 0||typeof g[c]=="string"&&typeof h[c]=="number")return-1;if(g[c]===void 0||typeof h[c]=="string"&&typeof g[c]=="number"||h[c]>g[c])return 1;if(g[c]>h[c])return-1}}else if(m||p)return m?-1:1;return 0}})});var KC=v(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.EnvironmentFlowHostingType=Ke.EnvironmentDisableReasonCode=Ke.EnvironmentMigrationConstants=Ke.EnvironmentProvisioningStates=Ke.EnvironmentLocations=Ke.EnvironmentCreationTypeConstants=Ke.EnvironmentType=Ke.EnvironmentSkuConstants=Ke.environmentPermissions=Ke.DatabaseType=void 0;var WC;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(WC||(Ke.DatabaseType=WC={}));Ke.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"};Ke.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var zC;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(zC||(Ke.EnvironmentType=zC={}));Ke.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Ke.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"};Ke.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Ke.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var jC;(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"})(jC||(Ke.EnvironmentDisableReasonCode=jC={}));var HC;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(HC||(Ke.EnvironmentFlowHostingType=HC={}))});var rE=v(_=>{"use strict";var KB=_&&_.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(_,"__esModule",{value:!0});_.hasCommonDataServiceDatabase=_.getEnvironmentDiscoveryUrl=_.getEnvironmentWebApiUrl=_.getEnvironmentInstanceApiUrl=_.getEnvironmentLanguageCode=_.getEnvironmentUpdateCadence=_.checkVersions=_.isCds2EnvironmentVersionAtLeast=_.getSecurityOrConnectedGroupId=_.hasSecurityGroupId=_.doesCds2VersionSupportApiVersion9_1=_.doesCds2EnvironmentSupportApiVersion9_1=_.cdsVersionSupportingOSColorEdit=_.getEnvironmentDisplayName=_.getEnvironmentName=_.isEnvironmentInFirstReleaseCluster=_.isEnvironmentInPreprodCluster=_.isEnvironmentInTestCluster=_.isLiteEnvironmentUpgrading=_.isEnvironmentExpired=_.isEnvironmentInDeletedState=_.isEnvironmentInCreatingState=_.isDatabaseInProvisioningState=_.canUserCreateDatabase=_.isDisabledEnvironment=_.isDefaultEnvironment=_.isTrialEnvironment=_.isPlatformEnvironment=_.isTeamsEnvironment=_.isSandboxEnvironment=_.isProdEnvironment=_.isDevEnvironment=_.getEnvironmentType=_.getCrmInstanceName=_.getCrmInstanceUrl=_.getCrmAppDesignerUrl=_.getDevResourcesUrl=_.isEnvironmentInSuccessfulState=_.getAllThemesUrl=_.getAllPublishersUrl=_.getAllSolutionsUrl=_.getSecurityRolesUrl=_.getSecurityUsersUrl=_.environmentHasCds2Database=_.DEFAULT_SOLUTION_UNIQUE_NAME=_.DEFAULT_SOLUTION_ID=_.crmBapSolutionId=_.doesUserHavePermission=_.getLinkedEnvironmentMetadata=_.getCrmVersion=void 0;_.doesUserHaveFlowRunOnlyPermission=_.isUserPautoMakerWithoutDataAccess=_.isUserPautoMakerWithDataAccess=_.doesUserHaveCreateFlowPermission=_.equalsIgnoreCase=_.doesUserHaveCreateDatabasePermission=_.doesUserHaveDatabaseTablePermissions=_.isUserMakerWithoutDataAccess=_.isUserMakerWithDataAccess=_.doesUserHaveCreateAppPermission=_.doesUserHaveAdminPermission=void 0;var JB=KB(GC()),Oe=KC(),bl=Bm();function YB(e){let t=yi(e);return t&&t.version}_.getCrmVersion=YB;function yi(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}_.getLinkedEnvironmentMetadata=yi;function gi(e,t){return e?!!e[t]:!1}_.doesUserHavePermission=gi;_.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";_.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";_.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function ko(e){return!!yi(e)&&JC(e)}_.environmentHasCds2Database=ko;function QB(e){if(e&&ko(e)){let t=Xi(e);return(0,bl.getCrmAdminSecurityRolesUrl)(t)}return""}_.getSecurityUsersUrl=QB;function XB(e){if(e&&ko(e)){let t=Xi(e);return(0,bl.getCrmAdminSecurityUsersUrl)(t)}return""}_.getSecurityRolesUrl=XB;function ZB(e){if(e&&ko(e)){let t=Xi(e);(0,bl.getCrmAllSolutionsUrl)(t)}return""}_.getAllSolutionsUrl=ZB;function eq(e){if(e&&ko(e)){let t=Xi(e);return(0,bl.getCrmAllPublishersUrl)(t)}return""}_.getAllPublishersUrl=eq;function tq(e){return e&&ko(e)?Xi(e):""}_.getAllThemesUrl=tq;function JC(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===Oe.EnvironmentProvisioningStates.Succeeded.toUpperCase()}_.isEnvironmentInSuccessfulState=JC;function rq(e){if(e&&ko(e)){let t=Xi(e);return(0,bl.getCrmDevResourcesUrl)(t)}return""}_.getDevResourcesUrl=rq;function nq(e){return`${e}designer/app/{${_.crmBapSolutionId}}/CreateNewApp}}`}_.getCrmAppDesignerUrl=nq;function Xi(e){let t=yi(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}_.getCrmInstanceUrl=Xi;function iq(e){let t=yi(e);return t?t.uniqueName:""}_.getCrmInstanceName=iq;function oq(e){return yi(e)?Oe.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?Oe.EnvironmentType.CDS1:Oe.EnvironmentType.Empty}_.getEnvironmentType=oq;function aq(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Developer}_.isDevEnvironment=aq;function sq(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Production}_.isProdEnvironment=sq;function lq(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Sandbox}_.isSandboxEnvironment=lq;function vl(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Teams}_.isTeamsEnvironment=vl;function uq(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Platform}_.isPlatformEnvironment=uq;var cq=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===Oe.EnvironmentSkuConstants.Trial};_.isTrialEnvironment=cq;function dq(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===Oe.EnvironmentCreationTypeConstants.DefaultTenant)}_.isDefaultEnvironment=dq;function fq(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}_.isDisabledEnvironment=fq;function pq(e){return e&&e.properties&&gi(e.properties.permissions,Oe.environmentPermissions.CreateDatabase)}_.canUserCreateDatabase=pq;function mq(e){return!!(e&&e.properties&&e.properties.provisioningState&&tE(e.properties.provisioningState,Oe.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}_.isDatabaseInProvisioningState=mq;function hq(e){return!!e&&!!e.properties&&e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Creating}_.isEnvironmentInCreatingState=hq;function gq(e){return e&&e.properties&&(e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===Oe.EnvironmentProvisioningStates.FailedDeleting)}_.isEnvironmentInDeletedState=gq;function yq(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}_.isEnvironmentExpired=yq;function bq(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"}_.isLiteEnvironmentUpgrading=bq;function vq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}_.isEnvironmentInTestCluster=vq;function wq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}_.isEnvironmentInPreprodCluster=wq;function Cq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}_.isEnvironmentInFirstReleaseCluster=Cq;function Eq(e){return e&&e.name||""}_.getEnvironmentName=Eq;function Aq(e){return e&&e.properties&&e.properties.displayName||""}_.getEnvironmentDisplayName=Aq;var YC="9.1.0.8202";_.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function Sq(e){return ZC(e,YC)}_.doesCds2EnvironmentSupportApiVersion9_1=Sq;function Nq(e){return Um(e,YC)}_.doesCds2VersionSupportApiVersion9_1=Nq;function QC(e){let t=yi(e);if(t)return t.securityGroupId}function XC(e){return e&&e.properties&&e.properties.connectedGroups}function _q(e,t){let r=XC(e);return!!r&&!!r.find(n=>n.id===t)||QC(e)===t}_.hasSecurityGroupId=_q;function Tq(e){let t=XC(e);return t&&t.length>0&&t[0].id?t[0].id:QC(e)}_.getSecurityOrConnectedGroupId=Tq;function ZC(e,t){let r=e.version;return r?Um(r,t):!1}_.isCds2EnvironmentVersionAtLeast=ZC;function Um(e,t){return t?e?(0,JB.default)(e,t)>=0:!1:!0}_.checkVersions=Um;function Dq(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}_.getEnvironmentUpdateCadence=Dq;function Iq(e){let t=yi(e);return t?Number(t.baseLanguage):0}_.getEnvironmentLanguageCode=Iq;function eE(e){let t=yi(e);return t?t.instanceApiUrl:void 0}_.getEnvironmentInstanceApiUrl=eE;function Oq(e){let t=eE(e);return t?t+"/api/data/v9.2":""}_.getEnvironmentWebApiUrl=Oq;function Pq(e){let t=Xi(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"}_.getEnvironmentDiscoveryUrl=Pq;var Rq=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===Oe.DatabaseType.CommonDataService};_.hasCommonDataServiceDatabase=Rq;var Lq=e=>{var t;return gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.AdminReadEnvironment)};_.doesUserHaveAdminPermission=Lq;var kq=e=>{var t;return gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreatePowerApp)};_.doesUserHaveCreateAppPermission=kq;var $q=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateAppPermission)(e)?vl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserMakerWithDataAccess=$q;var xq=e=>(0,_.doesUserHaveCreateAppPermission)(e)&&!vl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserMakerWithoutDataAccess=xq;var Fq=e=>[Oe.environmentPermissions.CreateDatabaseEntities,Oe.environmentPermissions.ListDatabaseEntities,Oe.environmentPermissions.UpdateDatabaseEntities,Oe.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return gi((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});_.doesUserHaveDatabaseTablePermissions=Fq;var Mq=e=>{var t;return gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateDatabase)};_.doesUserHaveCreateDatabasePermission=Mq;function tE(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}_.equalsIgnoreCase=tE;var Uq=e=>{var t;return gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateFlow)};_.doesUserHaveCreateFlowPermission=Uq;var Bq=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateFlowPermission)(e)?vl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserPautoMakerWithDataAccess=Bq;var qq=e=>(0,_.doesUserHaveCreateFlowPermission)(e)&&!vl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserPautoMakerWithoutDataAccess=qq;var Vq=e=>{var t,r;return!gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateFlow)&&gi((r=e.properties)===null||r===void 0?void 0:r.permissions,Oe.environmentPermissions.ReadEnvironment)};_.doesUserHaveFlowRunOnlyPermission=Vq});var Bm=v(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.getRequiredComponentsQueryUrl=A.solutionComponentCountSummariesQueryUrl=A.solutionComponentSummariesQueryUrl=A.solutionComponentConfigurationsQueryUrl=A.chartsQueryUrl=A.workflowsQueryUrl=A.entityDefinitionsQueryUrl=A.solutionComponentDefinitionsQueryUrl=A.getCreateNewArticleTemplateUrl=A.getCreateNewPublisherUrl=A.getEnableSecurityRolesUrl=A.getArticleTemplateUrl=A.getFieldSecurityProfileDesignerUrl=A.getSecurityRoleDesignerUrl=A.getMailMergeTemplateDesignerUrl=A.getEmailTemplateDesignerUrl=A.getConnectionRoleDesignerUrl=A.getSiteMapDesignerUrl=A.getWebResourceFileUrl=A.getWebResourceDesignerUrl=A.getReportDesignerUrl=A.getBusinessProcessFlowDesignerUrl=A.getProcessShareUrl=A.getProcessDesignerUrl=A.getChartDesignerUrl=A.getOpenModernEntityDashboardUrl=A.getNewModernEntityDashboardUrl=A.getNewModernDashboardUrl=A.getOpenModernDashboardUrl=A.getDashboardDesignerUrl=A.getAppModuleDesignerUrl=A.privilegesQueryUrls=A.xrmApiUrl=A.getPlayAppModuleUrl=A.getCrmAdminSecurityUsersUrl=A.getCrmAdminSecurityRolesUrl=A.getCrmMyAppsUrl=A.getCrmAppDesignerUrl=A.getCrmDevResourcesUrl=A.getCrmAllPublishersUrl=A.getCrmAllSolutionsUrl=A.getSolutionPublisherUrl=A.getExportTranslationFileName=A.getExportSolutionTranslationUrl=A.getImportSolutionTranslationUrl=A.getShowSolutionDependenciesUrl=A.getShowComponentDependenciesUrl=A.cdsServiceUrl=A.ODATA_NEXT_LINK=A.ODATA_MAX_PAGE_SIZE=void 0;A.retrieveOrganizationResources=A.getUCIEntityRecordEditUrl=A.getUCIEntityRecordBaseUrl=A.getBusinessRuleDesignerUri=A.retrieveUnpublishedSuffix=A.getSavePowerSettingUri=A.getPowerSettingUri=A.getPowerSettingsUri=A.RetrievePlatform=A.getAppSettingOverrideUri=A.AppSettingOverrideName=A.getOrgSettingOverrideUri=A.OrgSettingOverrideName=A.getSettingDefinitionsUri=A.retrieveFeatureControlSettingsByNamespaceUrl=A.retrieveDeploymentPipelineConfigAppUrl=A.SPNPrincipalIdUrl=A.retrieveDeploymentEnvironmentInfoUrl=A.devSolutionInfoUrl=A.deployOperationStatusUrl=A.getAIGeneratedDeploymentNotesUrl=A.deploymentStageRunUrl=A.validatePackageAsyncUrl=A.deployPackageAsyncUrl=A.updateDeploymentStageRunUrl=A.createDeploymentStageRunUrl=A.retrieveDeploymentStagesUrl=A.retrievePipelinesUrl=A.retrieveDeploymentPipelineInfoUrl=A.getDeploymentStageRunsUrl=A.appDeploymentUrls=A.getProvisionLanguageUrl=A.getSolutionQueryUrl=A.getSolutionsByUniqueNameQueryUrl=A.solutionsQueryUrl=A.getDependentComponentsWithMetadataQueryUrl=void 0;var nE=rE();A.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";A.ODATA_NEXT_LINK="@odata.nextLink";A.cdsServiceUrl="https://cds-org/";var Cl;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Cl||(Cl={}));function Gq(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}A.getShowComponentDependenciesUrl=Gq;function Wq(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}A.getShowSolutionDependenciesUrl=Wq;function zq(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}A.getImportSolutionTranslationUrl=zq;function jq(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}A.getExportSolutionTranslationUrl=jq;function Hq(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}A.getExportTranslationFileName=Hq;function Kq(e,t,r){return r?`${e}tools/publisher/edit.aspx?appSolutionId=%7b${r}%7d&id=%7b${t}%7d`:`${e}tools/publisher/edit.aspx?id=%7b${t}%7d`}A.getSolutionPublisherUrl=Kq;function qm(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function Jq(e){return qm(e,Cl.AllSolutions)}A.getCrmAllSolutionsUrl=Jq;function Yq(e){return qm(e,Cl.AllPublishers)}A.getCrmAllPublishersUrl=Yq;function Qq(e){return qm(e,Cl.DevResources)}A.getCrmDevResourcesUrl=Qq;function Xq(e,t=nE.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}A.getCrmAppDesignerUrl=Xq;function Zq(e){return`${e}apps`}A.getCrmMyAppsUrl=Zq;function e3(e){return iE(e,"role")+"&forceUCI=0"}A.getCrmAdminSecurityRolesUrl=e3;function t3(e){return`${iE(e,"systemuser")}&forceclassic=1`}A.getCrmAdminSecurityUsersUrl=t3;function iE(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function r3(e,t){return`${e}main.aspx?appid=${t}`}A.getPlayAppModuleUrl=r3;A.xrmApiUrl="api/data/v9.0";A.privilegesQueryUrls={systemUserInfo:e=>`${e}${A.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${A.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${A.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function n3(e,t,r=nE.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}A.getAppModuleDesignerUrl=n3;function i3(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}A.getDashboardDesignerUrl=i3;function o3(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}A.getOpenModernDashboardUrl=o3;function a3(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}A.getNewModernDashboardUrl=a3;function s3(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}A.getNewModernEntityDashboardUrl=s3;function l3(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}A.getOpenModernEntityDashboardUrl=l3;function u3(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}A.getChartDesignerUrl=u3;function c3(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessDesignerUrl=c3;function d3(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessShareUrl=d3;function f3(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}A.getBusinessProcessFlowDesignerUrl=f3;function p3(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}A.getReportDesignerUrl=p3;function m3(e,t,r){return`${e}main.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&etc=9333&id=%7b${t}%7d&pagetype=webresourceedit`}A.getWebResourceDesignerUrl=m3;function h3(e,t){return`${e}WebResources/${t}`}A.getWebResourceFileUrl=h3;function g3(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}A.getSiteMapDesignerUrl=g3;function y3(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getConnectionRoleDesignerUrl=y3;function b3(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getEmailTemplateDesignerUrl=b3;function v3(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getMailMergeTemplateDesignerUrl=v3;function w3(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getSecurityRoleDesignerUrl=w3;function C3(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getFieldSecurityProfileDesignerUrl=C3;function E3(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}A.getArticleTemplateUrl=E3;function A3(e,t,r,n){return`${e}tools/FormEditor/Dialogs/FormRoleAssignment.aspx?appSolutionId=%7b${t}%7d&dType=1&formId=%7b${r}%7d&objectTypeCode=0&type=${n}`}A.getEnableSecurityRolesUrl=A3;function S3(e){return`${e}tools/publisher/edit.aspx`}A.getCreateNewPublisherUrl=S3;function N3(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}A.getCreateNewArticleTemplateUrl=N3;A.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";A.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";A.workflowsQueryUrl="api/data/v9.0/workflows";A.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";A.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";A.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";A.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function _3(e,t){return`${A.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}A.getRequiredComponentsQueryUrl=_3;function T3(e,t){return`${A.cdsServiceUrl}${A.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}A.getDependentComponentsWithMetadataQueryUrl=T3;A.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function D3(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}A.getSolutionsByUniqueNameQueryUrl=D3;function I3(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}A.getSolutionQueryUrl=I3;function O3(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}A.getProvisionLanguageUrl=O3;A.appDeploymentUrls={associateEnvironmentToPipelineUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})/deploymentpipeline_deploymentenvironment/$ref`,deploymentArtifactsUrl:"/api/data/v9.0/deploymentartifacts",deploymentEnvironmentUrl:"/api/data/v9.0/deploymentenvironments",deploymentPipelinesUrl:"/api/data/v9.0/deploymentpipelines",deploymentStagesUrl:"/api/data/v9.0/deploymentstages",retrieveDeploymentPipelinesUrl:e=>`/api/data/v9.0/RetrieveDeploymentPipelines(SourceEnvironmentId='${e}')`,deletePipelinesUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})`};function P3(e,t,r,n=!1,i=!1,o=!1,a=!1,s=!1,l=!1,u=!1){return`/api/data/v9.1/deploymentstageruns
+`)),this.type=t,this.id=r,this.issues=u,this.pointer=(a=(o=u[0])===null||o===void 0?void 0:o.pointer)!==null&&a!==void 0?a:"",this.rule=(l=(s=u[0])===null||s===void 0?void 0:s.rule)!==null&&l!==void 0?l:"invalid"}};X.ValidationError=mm;var hm=class extends dt{constructor(t){super("INVALID_ARGUMENT",t)}};X.InvalidArgumentError=hm;var gm=class extends dt{constructor(t,r,n,i="revalidated"){super("STALE_ARTIFACT",i==="pushed"?`Cannot apply the edit at ${n} to ${t}/${r}: a push made after this pointer's copy was read replaced the local copy with the record the server holds, which differs from that copy (ids and defaults the SDK filled in at save, a rewrite the platform made on save, or another writer's save), so the pointer may now identify a different node. Read the whole artifact (getArtifact), re-derive the pointer, and retry.`:`Cannot apply the edit at ${n} to ${t}/${r}: the cached copy was stale and the server copy has since changed, so any pointer derived from the old copy may now identify a different node. The local copy has been refreshed \u2014 re-read the artifact, re-derive the pointer, and retry.`),this.type=t,this.id=r,this.pointer=n,this.reason=i}};X.StaleArtifactError=gm;var ym=class extends dt{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}};X.LocalEditsWouldBeLostError=ym;var bm=class extends dt{constructor(t,r,n,i,o){super("VERSION_CONFLICT",`Version conflict for ${t}/${r}: local=${n??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.${o?` ${o}`:""}`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i,this.detail=o}};X.VersionConflictError=bm;var vm=class extends dt{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,Object.defineProperty(this,"cause",{value:i,enumerable:!1,writable:!1,configurable:!0})}};X.ConnectionError=vm;var wm=class extends dt{constructor(t,r,n){super("WEB_RESOURCE_UNVERIFIED",n),this.id=t,this.webResourceName=r}};X.WebResourceUnverifiedError=wm;function jU(e,t){return typeof e=="object"&&e!==null&&Object.defineProperty(e,"cause",{value:t,enumerable:!1,writable:!0,configurable:!0}),e}X.attachCause=jU;var Cm=class extends dt{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};X.WorkspaceNotInitializedError=Cm;var Em=class extends dt{constructor(t,r){super("WORKSPACE_ORG_MISMATCH",`This workspace belongs to ${t?`'${t}'`:"no recorded org"}, but this SDK targets '${r}'. Its local copies, baselines and cached metadata are that org's, so nothing was read or written. Use one workspace per org, or call cleanWorkspace() to discard this workspace's contents and bind it to '${r}'.`),this.workspaceInstanceUrl=t,this.instanceUrl=r}};X.WorkspaceOrgMismatchError=Em;var Am=class extends dt{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};X.NotImplementedError=Am;var Sm=class extends dt{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};X.JsonPointerError=Sm;var Nm=class extends dt{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}};X.AmbiguousArtifactError=Nm;var _m=class extends dt{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}};X.PathTraversalError=_m;var Tm=class extends dt{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}};X.IncompatibleWorkspaceError=Tm});var le=v(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.odataQuery=nt.normalizeGuid=nt.createSafeXmlElement=nt.assertNoControlChars=nt.assertODataName=nt.assertXmlName=nt.xmlText=nt.odataPathLiteral=nt.odataLiteral=void 0;var Dc=Q();function bC(e){return String(e??"").replace(/'/g,"''")}nt.odataLiteral=bC;function HU(e){return encodeURIComponent(bC(e))}nt.odataPathLiteral=HU;function KU(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}nt.xmlText=KU;function vC(e,t){let r=String(e??""),n=/^[A-Za-z_][0-9A-Za-z_.-]*$/,i=r.split(":");if(!(i.length<=2&&i.every(a=>n.test(a))&&!/^xmlns/i.test(r)))throw new Dc.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}nt.assertXmlName=vC;function JU(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new Dc.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}nt.assertODataName=JU;function YU(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new Dc.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}nt.assertNoControlChars=YU;function QU(e,t,r){return e.createElement(vC(t,r))}nt.createSafeXmlElement=QU;var XU=/^[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 ZU(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!XU.test(n))throw new Dc.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}nt.normalizeGuid=ZU;function eB(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}nt.odataQuery=eB});var ye=v(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.nowIso=z.isAlreadyDeleted=z.deleteRecord=z.resendAppSearchIndexRace=z.resendDeadlockVictim=z.resendWhile=z.isAppSearchIndexRace=z.namesAppSearchIndexRace=z.isTransactionNotStarted=z.TRANSACTION_NOT_STARTED_CODE=z.LOCK_BACKOFF_MS=z.isConcurrencyLockRefusalError=z.isConcurrencyLockRefusal=z.CONCURRENCY_LOCK_CODE=z.AMBIGUOUS_WRITE_STATUSES=z.DEADLOCK_BACKOFF_MS=z.isSqlDeadlockVictim=z.ensureSuccess=z.resolveCreatedId=z.requireCreatedId=z.withClientMintedId=z.readCreatedId=z.readRowEtag=z.readEtag=z.requireEtag=z.isVersionToken=z.echoWrite=z.UPDATE_NO_ETAG_CODE=z.VERSION_CONFLICT_CODE=void 0;var ko=Q(),$a=le();z.VERSION_CONFLICT_CODE="VERSION_CONFLICT";z.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function tB(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}z.echoWrite=tB;function wC(e){return typeof e=="string"&&e.trim()!==""&&e.trim()!=="*"}z.isVersionToken=wC;function rB(e,t,r){if(!wC(e))throw new ko.SdkError(z.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${r}': ${e?`the concurrency token held for it ('${e}') is not a version`:"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}z.requireEtag=rB;function CC(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}z.readEtag=CC;async function nB(e,t,r,n){let i=`/${t}(${n})${(0,$a.odataQuery)([["$select",r]])}`;return CC(Om(await e.get(i),e.apiUrl(i)))}z.readRowEtag=nB;function Im(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,$a.normalizeGuid)(n[t],t);let i=(r=e.headers)!==null&&r!==void 0?r:{};for(let o of Object.keys(i))if(o.toLowerCase()==="odata-entityid"){let a=/\(([0-9a-fA-F-]{36})\)/.exec(i[o]);if(a)return(0,$a.normalizeGuid)(a[1],t)}return null}z.readCreatedId=Im;function iB(e,t,r){return r?{...e,[t]:(0,$a.normalizeGuid)(r,t)}:e}z.withClientMintedId=iB;function oB(e,t,r){let n=Im(e,t);if(!n)throw new ko.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}z.requireCreatedId=oB;function aB(e,t,r,n){let i=Im(e,t);if(i)return i;if(n)return(0,$a.normalizeGuid)(n,t);throw new ko.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}z.resolveCreatedId=aB;function Om(e,t){if(e.status===412)throw new ko.SdkError(z.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new ko.ConnectionError(t,e.status,fB(e.body),e.body);return e}z.ensureSuccess=Om;function EC(e){if(e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/\bSql Number:\s*1205\b/i.test(t)}z.isSqlDeadlockVictim=EC;z.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];z.AMBIGUOUS_WRITE_STATUSES=new Set([408,502,503,504]);z.CONCURRENCY_LOCK_CODE="0x80071151";function AC(e){var t,r;if(e.status!==429)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===z.CONCURRENCY_LOCK_CODE}z.isConcurrencyLockRefusal=AC;function sB(e){return e instanceof ko.ConnectionError&&e.statusCode===429&&AC({status:429,headers:{},body:e.cause})}z.isConcurrencyLockRefusalError=sB;z.LOCK_BACKOFF_MS=[2e3,3e3,...Array.from({length:35},()=>5e3)];z.TRANSACTION_NOT_STARTED_CODE="0x80040251";function lB(e){var t,r;if(e.status!==500)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===z.TRANSACTION_NOT_STARTED_CODE}z.isTransactionNotStarted=lB;var uB=/(?:^|[^a-z0-9_])AppModule_DVTableSearch_M365AppModuleId(?![a-z0-9_])/i;function SC(e){return uB.test(e)&&/\bSql Number:\s*547\b/i.test(e)}z.namesAppSearchIndexRace=SC;function NC(e){return e.status!==400||e.body===void 0||e.body===null?!1:SC(typeof e.body=="string"?e.body:JSON.stringify(e.body))}z.isAppSearchIndexRace=NC;async function Pm(e,t,r=z.DEADLOCK_BACKOFF_MS){for(let n=0;;n+=1){let i=await t();if(n>=r.length||!e(i))return i;await new Promise(o=>setTimeout(o,r[n]))}}z.resendWhile=Pm;function cB(e){return Pm(EC,e,z.DEADLOCK_BACKOFF_MS)}z.resendDeadlockVictim=cB;function dB(e){return Pm(NC,e,z.DEADLOCK_BACKOFF_MS)}z.resendAppSearchIndexRace=dB;function fB(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 pB(e,t,r,n){let i=(0,$a.normalizeGuid)(r,"id"),o=`/${t}(${i})`;Om(await e.delete(o,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(o))}z.deleteRecord=pB;function mB(e){return e instanceof ko.ConnectionError&&e.statusCode===404}z.isAlreadyDeleted=mB;function hB(){return new Date().toISOString()}z.nowIso=hB});var Lt=v(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.describeMalformedValue=xa.collectPages=void 0;var _C=ye(),Rm=Q();async function gB(e,t,r,n,i){let o=[],a=new Set,s=e.apiUrl(t),l=(0,_C.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new Rm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${km(c)}; refusing to return partial results.`);for(let f of c)o.push(f);let d=u?.["@odata.nextLink"];if(d==null)break;if(typeof d!="string"||d.length===0)throw new Rm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${km(d)}); cannot follow it, and refusing to return partial results.`);if(a.has(d))throw new Rm.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);a.add(d),s=d,l=(0,_C.ensureSuccess)(await e.getAbsolute(d,i),d)}return o}xa.collectPages=gB;function km(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}xa.describeMalformedValue=km});var Lm=v($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.assertWorkflowKind=$o.WORKFLOW_KIND_MISMATCH_CODE=void 0;var Lo=Qi(),yB=Q(),TC=ye(),bB=le();$o.WORKFLOW_KIND_MISMATCH_CODE="WORKFLOW_KIND_MISMATCH";var DC={[Lo.WorkflowCategory.Workflow]:"classic workflow",[Lo.WorkflowCategory.Dialog]:"dialog",[Lo.WorkflowCategory.BusinessRule]:"business rule",[Lo.WorkflowCategory.Action]:"custom action",[Lo.WorkflowCategory.BusinessProcessFlow]:"business process flow",[Lo.WorkflowCategory.Flow]:"cloud flow",[Lo.WorkflowCategory.UIFlow]:"desktop flow"};async function vB(e,t,r){var n,i;let o=`/workflows(${t})${(0,bB.odataQuery)([["$select","category"]])}`,a=await e.get(o);if(a.status===404)return null;(0,TC.ensureSuccess)(a,e.apiUrl(o));let s=(n=a.body)===null||n===void 0?void 0:n.category,l=typeof s=="number"?s:typeof s=="string"&&s!==""?Number(s):NaN;if(l!==r){let u=Number.isFinite(l)?`a ${(i=DC[l])!==null&&i!==void 0?i:"process"} (category ${l})`:"a process whose category could not be read";throw new yB.SdkError($o.WORKFLOW_KIND_MISMATCH_CODE,`Refusing to delete workflow '${t}' as a ${DC[r]}: it is ${u}. Nothing was changed. Check the id.`)}return(0,TC.readEtag)(a)}$o.assertWorkflowKind=vB});var xm=v(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.deleteWorkflowResending=Yr.isWorkflowDeleteUnsettled=Yr.failedAfterResend=Yr.WORKFLOW_DELETE_UNSETTLED_CODE=void 0;var bl=Q(),hi=ye(),OC=le();Yr.WORKFLOW_DELETE_UNSETTLED_CODE="WORKFLOW_DELETE_UNSETTLED";var PC=new WeakSet;function $m(e){return typeof e=="object"&&e!==null&&PC.add(e),e}function wB(e){return typeof e=="object"&&e!==null&&PC.has(e)}Yr.failedAfterResend=wB;function CB(e){return e instanceof bl.SdkError&&e.code===Yr.WORKFLOW_DELETE_UNSETTLED_CODE}Yr.isWorkflowDeleteUnsettled=CB;function EB(e,t){try{(0,hi.ensureSuccess)(e,t)}catch(r){return r}}function AB(e){return(0,hi.isSqlDeadlockVictim)(e)?"lost a SQL deadlock (HTTP 500, Sql Number 1205)":`lost its transaction (HTTP 500 ${hi.TRANSACTION_NOT_STARTED_CODE})`}async function IC(e,t){try{return(await e.get(`/workflows(${t})${(0,OC.odataQuery)([["$select","workflowid"]])}`)).status===404}catch{return!1}}async function SB(e,t,{bindingToken:r,kindName:n,deactivated:i=!1,resendDeadlockVictim:o=!1,ifMatchOnFirst:a=!1}){let s=(0,OC.normalizeGuid)(t,"id");if(a&&!r)throw new bl.InvalidArgumentError(`Refusing to delete ${n} '${s}': its delete must be conditional on a token this operation holds, and it holds none.`);let l=`/workflows(${s})`,u=e.apiUrl(l),c=p=>(0,hi.isTransactionNotStarted)(p)||o&&(0,hi.isSqlDeadlockVictim)(p),d=0,f,m;try{m=await(0,hi.resendWhile)(c,async()=>{d+=1;let p=d>1||a,h=await e.delete(l,p?{headers:{"If-Match":r}}:void 0);return f=f??h,h},r?hi.DEADLOCK_BACKOFF_MS:[])}catch(p){if(p instanceof bl.ConnectionError&&p.statusCode===0&&r&&await IC(e,s))return;throw d>1?$m(p):p}if(!(d>1&&m.status===404)){if(d>1&&m.status===412){let p=AB(f),h=new bl.SdkError(Yr.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting ${n} '${s}' ${p}, and its re-send was refused (HTTP 412): the row at that id is no longer the version this delete checked \u2014 it was edited, or deleted and re-created at the same id \u2014 so nothing more was deleted. `+(i?"This delete had deactivated the process first and has NOT re-activated it: it MAY be left DISABLED. ":"")+"Read the row before deleting it again.");throw $m((0,bl.attachCause)(h,EB(f,u)))}if(!(r&&hi.AMBIGUOUS_WRITE_STATUSES.has(m.status)&&await IC(e,s)))try{(0,hi.ensureSuccess)(m,u)}catch(p){throw d>1?$m(p):p}}}Yr.deleteWorkflowResending=SB});var Fm=v(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.businessRuleApi=Bn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=Bn.WFOM_API_UNAVAILABLE_CODE=void 0;var Un=Qi(),NB=Lt(),_B=Lm(),TB=xm(),Gt=ye(),gi=le(),Oc=Q();Bn.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";Bn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function RC(e,t,r,n){let i=`/workflows(${OB})/Microsoft.Dynamics.CRM.${t}`;try{return(0,Gt.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new Oc.SdkError(Bn.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 DB(e,t){let r=`/workflows(${t})${(0,gi.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,Gt.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function IB(e,t,r){let n=await DB(e,t);if(n===null||n.etag===null)throw new Oc.SdkError(Gt.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 Oc.SdkError(Gt.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 OB="00000000-0000-0000-0000-000000000000",Ic={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},PB="workflowid,name,description,primaryentity,statecode,category,type",RB="category eq 2 and type eq 1";async function kC(e,t,r){var n;if(r==="Draft")return null;let i=(0,gi.normalizeGuid)(t,"workflowid"),o=r==="Active",a={statecode:o?Un.StateCode.Activated:Un.StateCode.Draft,statuscode:o?Un.StatusCode.Activated:Un.StatusCode.Draft},s=`/workflows(${i})`,l=(0,Gt.ensureSuccess)(await e.patch(s,a,{headers:Ic}),e.apiUrl(s));return(n=(0,Gt.readEtag)(l))!==null&&n!==void 0?n:await vl(e,i)}async function vl(e,t){let r=`/workflows(${t})${(0,gi.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,Gt.readEtag)(n):null}catch{return null}}async function kB(e,t,r){let n=await vl(e,t),i=await r(),o=(0,Gt.readEtag)(i);if(o)return{response:i,etag:o};let a=await vl(e,t);return{response:i,etag:n!==null&&n===a?a:null}}Bn.businessRuleApi={async get(e,t){let r=(0,gi.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await kB(e,r,async()=>(0,Gt.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:o}},async list(e,t){let r=[RB];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,gi.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,gi.odataQuery)([["$select",PB],["$filter",r.join(" and ")]])}`;return(await(0,NB.collectPages)(e,n,"listArtifacts('businessRule')")).map(o=>{var a,s;return{type:"businessRule",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){var r;let n=t,i=(0,gi.normalizeGuid)(n.Entity.workflowid,"workflowid"),o=await RC(e,"CreateProcessWithWfomJson",n,Ic),a=(0,Gt.resolveCreatedId)(o,"workflowid","business rule",i),s=null;try{s=await kC(e,a,n.status)}catch(l){try{await(0,Gt.deleteRecord)(e,"workflows",a)}catch{}throw l}return{id:a,etag:(r=s??(0,Gt.readEtag)(o))!==null&&r!==void 0?r:await vl(e,a)}},async update(e,t,r,n){var i,o;let a=r,s=(0,gi.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...Ic,"If-Match":(0,Gt.requireEtag)(n,"business rule",s)},c=await IB(e,s,u["If-Match"]),d=c.statecode===Un.StateCode.Activated;d&&(0,Gt.ensureSuccess)(await e.patch(l,{statecode:Un.StateCode.Draft,statuscode:Un.StatusCode.Draft},{headers:u}),e.apiUrl(l));let f;try{f=await RC(e,"UpdateProcessWithWfomJson",a,u)}catch(p){if(d)try{(0,Gt.ensureSuccess)(await e.patch(l,{statecode:Un.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:Un.StatusCode.Activated},{headers:Ic}),e.apiUrl(l))}catch(h){throw new Oc.SdkError(Bn.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: ${p instanceof Error?p.message:String(p)}. Restore failure: ${h instanceof Error?h.message:String(h)}`)}throw p}let m=await kC(e,s,a.status);return{id:s,etag:(o=m??(0,Gt.readEtag)(f))!==null&&o!==void 0?o:await vl(e,s)}},async delete(e,t){let r=(0,gi.normalizeGuid)(t,"id"),n=await(0,_B.assertWorkflowKind)(e,r,Un.WorkflowCategory.BusinessRule);return(0,TB.deleteWorkflowResending)(e,r,{bindingToken:n,kindName:"business rule"})}}});var Qr=v(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.publishBoundEntity=Et.boundEntityPublishScope=Et.publishGenPageById=Et.publishDashboardById=Et.publishWebResourceById=Et.publishEntity=Et.publishAppModule=Et.publishXml=void 0;var LC=ye(),wl=le(),$C="/PublishXml";async function Fa(e,t){(0,LC.ensureSuccess)(await(0,LC.resendDeadlockVictim)(()=>e.post($C,{ParameterXml:t})),e.apiUrl($C))}Et.publishXml=Fa;function LB(e,t){return Fa(e,`<importexportxml><appmodules><appmodule>${(0,wl.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}Et.publishAppModule=LB;function xC(e,t){return Fa(e,`<importexportxml><entities><entity>${(0,wl.xmlText)(t)}</entity></entities></importexportxml>`)}Et.publishEntity=xC;function $B(e,t){return Fa(e,`<importexportxml><webresources><webresource>${(0,wl.xmlText)(t)}</webresource></webresources></importexportxml>`)}Et.publishWebResourceById=$B;function xB(e,t){return Fa(e,`<importexportxml><dashboards><dashboard>${(0,wl.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}Et.publishDashboardById=xB;function FB(e,t){return Fa(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,wl.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}Et.publishGenPageById=FB;function MB(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}Et.boundEntityPublishScope=MB;function UB(e,t){let r=t?.entityLogicalName;return r?xC(e,r):Promise.resolve()}Et.publishBoundEntity=UB});var Ma=v(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});Rc.JsonPointer=void 0;var qr=Q(),Pc=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 qr.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new qr.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 o of n)if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0)return;i=i[a]}else if(i!==null&&typeof i=="object"){let a=i;if(e.isReservedToken(o)||!Object.prototype.hasOwnProperty.call(a,o))return;i=a[o]}else return;return i}static set(t,r,n){let i=e.parse(r);if(i.length===0)throw new qr.JsonPointerError(r,"cannot set the document root");let{parent:o,lastToken:a}=e.resolveParent(t,i,r);if(Array.isArray(o)){let s=e.toArrayIndex(a,o.length);if(s===void 0)throw new qr.JsonPointerError(r,`'${a}' is not a valid array index`);if(s>o.length)throw new qr.JsonPointerError(r,`array index '${a}' is out of range`);o[s]=n}else{if(e.isReservedToken(a))throw new qr.JsonPointerError(r,`refusing to write reserved property '${a}'`);o[a]=n}}static remove(t,r){let n=e.parse(r);if(n.length===0)throw new qr.JsonPointerError(r,"cannot remove the document root");let{parent:i,lastToken:o}=e.resolveParent(t,n,r);if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0||a>=i.length)throw new qr.JsonPointerError(r,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new qr.JsonPointerError(r,`refusing to remove reserved property '${o}'`);delete i[o]}}static add(t,r,n,i){let o=e.parse(r);if(o.length>0&&o[o.length-1]==="-"){let l=e.compile(o.slice(0,-1)),u=e.resolve(t,l);if(!Array.isArray(u))throw new qr.JsonPointerError(r,"add target must be an array");u.push(n);return}let a=e.resolve(t,r);if(!Array.isArray(a))throw new qr.JsonPointerError(r,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new qr.JsonPointerError(r,`insert index ${s} is out of range`);a.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],o=e.compile(r.slice(0,-1)),a=e.resolve(t,o);if(a===null||typeof a!="object")throw new qr.JsonPointerError(n,"parent path does not resolve to an object or array");return{parent:a,lastToken:i}}static toArrayIndex(t,r){if(t==="-")return r;if(/^(0|[1-9][0-9]*)$/.test(t))return Number(t)}};Rc.JsonPointer=Pc;Pc.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var MC=v(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});kc.findElements=void 0;var FC=Ma();function BB(e,t){let r=[];return Mm(e,"",t,r),r}kc.findElements=BB;function Mm(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,o)=>{Mm(i,FC.JsonPointer.append(t,o),r,n)});else for(let i of Object.keys(e))Mm(e[i],FC.JsonPointer.append(t,i),r,n)}});var Um=v(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.assertMutationResult=qn.assertExistsResult=qn.assertReadResult=qn.assertStorageContract=void 0;var qB=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],VB=["ensureContainer","exists"];function GB(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of qB)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of VB){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}qn.assertStorageContract=GB;function WB(e,t){if(e===null||typeof e=="string")return e;throw new Error(`workspaceStorage.readText must resolve to a string or null for ${t}; got ${typeof e}. Absence is null \u2014 resolving undefined would make a present value look absent.`)}qn.assertReadResult=WB;function zB(e,t){if(typeof e=="boolean")return e;throw new Error(`workspaceStorage.exists must resolve to a boolean for ${t}; got ${typeof e}. A truthy non-boolean would make an absent value look present.`)}qn.assertExistsResult=zB;function jB(e,t){if(e!==void 0)throw new Error(`workspaceStorage.${t} must resolve to undefined; got ${typeof e}. A status-returning implementation would let a failed write be reported as a completed one.`)}qn.assertMutationResult=jB});var Bm=v(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.retryTransientIoAsync=Ua.retryTransientIo=void 0;var HB=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),KB=5,UC=10;function JB(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!BC(r,t))throw r;QB(UC*t)}}Ua.retryTransientIo=JB;async function YB(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!BC(r,t))throw r;await new Promise(n=>setTimeout(n,UC*t))}}Ua.retryTransientIoAsync=YB;function BC(e,t){let r=e.code;return t<KB&&!!r&&HB.has(r)}function QB(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var zC=v(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.canonicalArtifactId=Vr.WorkspaceManager=Vr.WORKSPACE_SCHEMA_VERSION=Vr.retryTransientIo=void 0;var Wt=Um(),Vn=Q(),XB=Bm();Object.defineProperty(Vr,"retryTransientIo",{enumerable:!0,get:function(){return XB.retryTransientIo}});function qC(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Vr.WORKSPACE_SCHEMA_VERSION=1;var Xi={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},ZB="manifest.json",Ba=".metadata",qm="entities";function VC(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}function Vm(e){if(e.schemaVersion!==void 0&&e.schemaVersion>Vr.WORKSPACE_SCHEMA_VERSION)throw new Vn.IncompatibleWorkspaceError(e.schemaVersion,Vr.WORKSPACE_SCHEMA_VERSION)}function GC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Lc(e){return e.trim().toLowerCase().replace(/\/+$/,"")}var Gm=class{withManifest(t){let r=this.manifestQueue.then(t,t);return this.manifestQueue=r.then(()=>{},()=>{}),r}constructor(t,r,n){if(this.workspaceLabel=t,this.instanceUrl=r,this.manifestQueue=Promise.resolve(),this.bound=!1,n==null)throw new Error("WorkspaceManager requires a WorkspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'.");this.storage=n}artifactKey(t,r){return this.assertSafeId(r),[Xi[t],`${Cl(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[Ba,Xi[t],`${Cl(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[Ba,qm,`${t.toLowerCase()}.json`]}fsStore(){let t=qC(this.storage);if(!t)throw new Error("This workspace is not filesystem-backed, so it has no physical paths. Use the artifact/metadata/manifest accessors instead of the path helpers.");return t}getRoot(){let t=qC(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([Xi[t]])}getArtifactFilePath(t,r){return this.fsStore().pathFor(this.artifactKey(t,r))}getMetaFilePath(t,r){return this.fsStore().pathFor(this.metaKey(t,r))}getEntityMetaFilePath(t){return this.fsStore().pathFor(this.entityKey(t))}assertSafeId(t){if(typeof t!="string"||t.length===0||/[\u0000-\u001f]/.test(t)||t.includes("/")||t.includes("\\")||t.includes(":")||t==="."||t===".."||t.includes(".."))throw new Vn.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[ZB]}assertDataKey(t,r){if(!Array.isArray(t)||t.length<2)throw new Vn.InvalidArgumentError(`${r} writes only inside the workspace's folders; '${String(t)}' is at its root, where only the manifest lives \u2014 and the manifest is changed only by the workspace itself.`);t.forEach(n=>this.assertSafeId(n))}async init(){let t=await this.withManifest(async()=>{let r=await this.readStoredManifest();return r.present&&this.assertBoundHere(r.value),r.present});await this.ensureLayout(),t||await this.withManifest(async()=>{let r=await this.readStoredManifest();if(r.present){this.assertBoundHere(r.value);return}let n={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};await this.writeManifest(n)}),this.bound=!0}async readStoredManifest(){let t=(0,Wt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json");return t===null?{present:!1}:{present:!0,value:JSON.parse(t)}}async ensureLayout(){if(!this.storage.ensureContainer)return;let t=this.storage.ensureContainer.bind(this.storage),r=[[Ba,qm]];for(let i of Object.keys(Xi))r.push([Xi[i]],[Ba,Xi[i]]);let n=await Promise.allSettled(r.map(i=>VC(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,Wt.assertMutationResult)(i.value,"ensureContainer")}}async isInitialized(){return this.storage.exists?(0,Wt.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,Wt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json")!==null}async ensureInitialized(){if(!this.bound){await this.verifyBinding();return}if(!await this.isInitialized())throw new Vn.WorkspaceNotInitializedError(this.workspaceLabel)}async ensureReady(){await this.ensureInitialized()}async ensureBound(){this.bound||await this.verifyBinding()}verifyBinding(){if(!this.verifying){let t=()=>{this.verifying=void 0};this.verifying=this.readAndCheckBinding().then(t,r=>{throw t(),r})}return this.verifying}async readAndCheckBinding(){let t=await this.readStoredManifest();if(!t.present)throw new Vn.WorkspaceNotInitializedError(this.workspaceLabel);this.assertBoundHere(t.value),this.bound=!0}assertBoundHere(t){if(!GC(t))throw new Vn.WorkspaceOrgMismatchError("",this.instanceUrl);Vm(t);let r=typeof t.instanceUrl=="string"?t.instanceUrl.trim():"",n=Lc(r);if(!n||n!==Lc(this.instanceUrl))throw new Vn.WorkspaceOrgMismatchError(r,this.instanceUrl)}async clean(){let t=await this.readStoredManifest();if(!t.present||!GC(t.value))throw new Vn.WorkspaceNotInitializedError(this.workspaceLabel);let r=t.value;Vm(r);let n=Object.keys(Xi).map(o=>[Xi[o]]);n.push([Ba]);let i=await Promise.allSettled(n.map(o=>VC(()=>this.storage.deleteByPrefix(o))));for(let o of i){if(o.status==="rejected")throw o.reason;(0,Wt.assertMutationResult)(o.value,"deleteByPrefix")}await this.ensureLayout(),await this.withManifest(()=>this.writeManifest({...r,instanceUrl:this.instanceUrl,artifacts:[],lastSyncAt:void 0})),this.bound=!0}async readArtifact(t,r){return await this.ensureInitialized(),this.readJsonUnchecked(this.artifactKey(t,r))}async readArtifactWithText(t,r){await this.ensureInitialized();let n=this.artifactKey(t,r),i=(0,Wt.assertReadResult)(await this.storage.readText(n),n.join("/"));return i===null?null:{artifact:JSON.parse(i),text:i}}async writeArtifact(t,r,n,i){await this.ensureInitialized();let o=WC(n);if(i!==void 0&&o===i){await this.upsertManifestEntry(t,r,n,{unlessCurrent:!0});return}(0,Wt.assertMutationResult)(await this.storage.writeTextAtomic(this.artifactKey(t,r),o),"writeTextAtomic"),await this.upsertManifestEntry(t,r,n)}async deleteArtifact(t,r){await this.ensureInitialized(),(0,Wt.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,Wt.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=Cl(r);await this.withManifest(async()=>{let i=await this.getManifest();i.artifacts=i.artifacts.filter(o=>!(o.type===t&&o.id===n)),await this.writeManifest(i)})}async readMeta(t,r){return await this.ensureBound(),this.readJsonUnchecked(this.metaKey(t,r))}async writeMeta(t,r,n){await this.ensureBound(),await this.writeJsonUnchecked(this.metaKey(t,r),n)}async listArtifacts(t,r){return await this.ensureInitialized(),(await this.getManifest()).artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}async readEntityMetadata(t){await this.ensureInitialized();let r=await this.readJsonUnchecked(this.entityKey(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}async writeEntityMetadata(t,r){await this.ensureInitialized(),await this.writeJsonUnchecked(this.entityKey(t),r)}async dropEntityMetadata(t){if(await this.ensureInitialized(),t===void 0){(0,Wt.assertMutationResult)(await this.storage.deleteByPrefix([Ba,qm]),"deleteByPrefix");return}(0,Wt.assertMutationResult)(await this.storage.deleteFile(this.entityKey(t)),"deleteFile")}async getManifest(){await this.ensureInitialized();let t=await this.readJsonUnchecked(this.manifestKey);if(!t)throw new Vn.WorkspaceNotInitializedError(this.workspaceLabel);return Vm(t),t}async writeManifest(t){await this.writeJsonUnchecked(this.manifestKey,{...t,schemaVersion:Vr.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();if(t.instanceUrl!==void 0&&Lc(String(t.instanceUrl))!==Lc(r.instanceUrl))throw new Vn.InvalidArgumentError("updateManifest cannot change the workspace's org: it is bound to the org it was created for. cleanWorkspace() discards its contents and binds it to the org of the SDK that calls it.");await this.writeManifest({...r,...t,instanceUrl:r.instanceUrl})})}async upsertManifestEntry(t,r,n,i={}){await this.withManifest(async()=>{let o=await this.getManifest(),a=Cl(r),s=n,l=typeof s.name=="string"?s.name:`${t}:${a}`,u=typeof s.entityLogicalName=="string"?s.entityLogicalName:void 0,c=o.artifacts.find(d=>d.type===t&&d.id===a);i.unlessCurrent&&c?.name===l&&c.entityLogicalName===u||(c?(c.name=l,c.entityLogicalName=u):o.artifacts.push({type:t,id:a,name:l,entityLogicalName:u,isDirty:!1}),await this.writeManifest(o))})}async readJson(t){return await this.ensureBound(),this.readJsonUnchecked(t)}async writeJson(t,r){this.assertDataKey(t,"writeJson"),await this.ensureBound(),await this.writeJsonUnchecked(t,r)}async removeFile(t){this.assertDataKey(t,"removeFile"),await this.ensureBound(),(0,Wt.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return await this.ensureBound(),this.storage.exists?(0,Wt.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,Wt.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}async readJsonUnchecked(t){let r=(0,Wt.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJsonUnchecked(t,r){(0,Wt.assertMutationResult)(await this.storage.writeTextAtomic(t,WC(r)),"writeTextAtomic")}};Vr.WorkspaceManager=Gm;function WC(e){return`${JSON.stringify(e,null,2)}
+`}function Cl(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()}Vr.canonicalArtifactId=Cl});var Wm=v(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.deepEqual=qa.deepDiff=void 0;var eq=Ma();function tq(e,t){let r=[];return HC(e,t,"",r,0),r}qa.deepDiff=tq;var $c=Symbol("missing"),xc=512;function HC(e,t,r,n,i){if(e===t)return;if(i>xc)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${xc}`);let o=Fc(e),a=Fc(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=rq(e,t);for(let l of s){let u=jC(e,l),c=jC(t,l),d=eq.JsonPointer.append(r,l);u===$c?n.push({pointer:d,type:"added",newValue:c}):c===$c?n.push({pointer:d,type:"removed",oldValue:u}):HC(u,c,d,n,i+1)}return}KC(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function Fc(e){return e!==null&&typeof e=="object"}function rq(e,t){if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length),i=[];for(let o=0;o<n;o++)i.push(String(o));return i}let r=new Set([...Object.keys(e),...Object.keys(t)]);return Array.from(r)}function jC(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:$c}return t in e?e[t]:$c}function KC(e,t){return JC(e,t,0)}qa.deepEqual=KC;function JC(e,t,r){if(e===t)return!0;if(r>xc)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${xc}`);if(!Fc(e)||!Fc(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(o=>o in t&&JC(e[o],t[o],r+1))}});var QC=v(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.VersionManager=Va.PROJECTION_VERSION=void 0;var YC=Wm(),nq=ye();Va.PROJECTION_VERSION=8;var zm=class{constructor(t){this.workspace=t}async storeMeta(t,r,n,i){var o;let a=i===void 0?await this.getMeta(t,r):i,s=((o=n.snapshot)===null||o===void 0?void 0:o.status)==="Active",l=a?.everActivated===!0||s;await this.workspace.writeMeta(t,r,l?{...n,everActivated:l}:n)}async getMeta(t,r){return this.workspace.readMeta(t,r)}async isDirty(t,r,n){let i=await this.workspace.readArtifact(t,r);if(i===null)return!1;let o=n===void 0?await this.getMeta(t,r):n;return o?!(0,YC.deepEqual)(o.snapshot,i):!0}async diff(t,r){let n=await this.workspace.readArtifact(t,r),i=await this.getMeta(t,r),o;return n===null?o=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?o=(0,YC.deepDiff)(i.snapshot,n):o=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:o}}async checkConflict(t,r,n){let i=await this.getMeta(t,r);return!i||!(0,nq.isVersionToken)(i.etag)?!0:i.etag!==n}};Va.VersionManager=zm});var ZC=v((jm,XC)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof jm=="object"?XC.exports=t():e.compareVersions=t()})(jm,function(){var e=/^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;function t(o,a){return o.indexOf(a)===-1?o.length:o.indexOf(a)}function r(o){var a=o.replace(/^v/,"").replace(/\+.*$/,""),s=t(a,"-"),l=a.substring(0,s).split(".");return l.push(a.substring(s+1)),l}function n(o){return isNaN(Number(o))?o:Number(o)}function i(o){if(typeof o!="string")throw new TypeError("Invalid argument expected string");if(!e.test(o))throw new Error("Invalid argument not valid semver ('"+o+"' received)")}return function(a,s){[a,s].forEach(i);for(var l=r(a),u=r(s),c=0;c<Math.max(l.length-1,u.length-1);c++){var d=parseInt(l[c]||0,10),f=parseInt(u[c]||0,10);if(d>f)return 1;if(f>d)return-1}var m=l[l.length-1],p=u[u.length-1];if(m&&p){var h=m.split(".").map(n),g=p.split(".").map(n);for(c=0;c<Math.max(h.length,g.length);c++){if(h[c]===void 0||typeof g[c]=="string"&&typeof h[c]=="number")return-1;if(g[c]===void 0||typeof h[c]=="string"&&typeof g[c]=="number"||h[c]>g[c])return 1;if(g[c]>h[c])return-1}}else if(m||p)return m?-1:1;return 0}})});var iE=v(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.EnvironmentFlowHostingType=He.EnvironmentDisableReasonCode=He.EnvironmentMigrationConstants=He.EnvironmentProvisioningStates=He.EnvironmentLocations=He.EnvironmentCreationTypeConstants=He.EnvironmentType=He.EnvironmentSkuConstants=He.environmentPermissions=He.DatabaseType=void 0;var eE;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(eE||(He.DatabaseType=eE={}));He.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"};He.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var tE;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(tE||(He.EnvironmentType=tE={}));He.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};He.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"};He.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};He.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var rE;(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"})(rE||(He.EnvironmentDisableReasonCode=rE={}));var nE;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(nE||(He.EnvironmentFlowHostingType=nE={}))});var fE=v(_=>{"use strict";var iq=_&&_.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(_,"__esModule",{value:!0});_.hasCommonDataServiceDatabase=_.getEnvironmentDiscoveryUrl=_.getEnvironmentWebApiUrl=_.getEnvironmentInstanceApiUrl=_.getEnvironmentLanguageCode=_.getEnvironmentUpdateCadence=_.checkVersions=_.isCds2EnvironmentVersionAtLeast=_.getSecurityOrConnectedGroupId=_.hasSecurityGroupId=_.doesCds2VersionSupportApiVersion9_1=_.doesCds2EnvironmentSupportApiVersion9_1=_.cdsVersionSupportingOSColorEdit=_.getEnvironmentDisplayName=_.getEnvironmentName=_.isEnvironmentInFirstReleaseCluster=_.isEnvironmentInPreprodCluster=_.isEnvironmentInTestCluster=_.isLiteEnvironmentUpgrading=_.isEnvironmentExpired=_.isEnvironmentInDeletedState=_.isEnvironmentInCreatingState=_.isDatabaseInProvisioningState=_.canUserCreateDatabase=_.isDisabledEnvironment=_.isDefaultEnvironment=_.isTrialEnvironment=_.isPlatformEnvironment=_.isTeamsEnvironment=_.isSandboxEnvironment=_.isProdEnvironment=_.isDevEnvironment=_.getEnvironmentType=_.getCrmInstanceName=_.getCrmInstanceUrl=_.getCrmAppDesignerUrl=_.getDevResourcesUrl=_.isEnvironmentInSuccessfulState=_.getAllThemesUrl=_.getAllPublishersUrl=_.getAllSolutionsUrl=_.getSecurityRolesUrl=_.getSecurityUsersUrl=_.environmentHasCds2Database=_.DEFAULT_SOLUTION_UNIQUE_NAME=_.DEFAULT_SOLUTION_ID=_.crmBapSolutionId=_.doesUserHavePermission=_.getLinkedEnvironmentMetadata=_.getCrmVersion=void 0;_.doesUserHaveFlowRunOnlyPermission=_.isUserPautoMakerWithoutDataAccess=_.isUserPautoMakerWithDataAccess=_.doesUserHaveCreateFlowPermission=_.equalsIgnoreCase=_.doesUserHaveCreateDatabasePermission=_.doesUserHaveDatabaseTablePermissions=_.isUserMakerWithoutDataAccess=_.isUserMakerWithDataAccess=_.doesUserHaveCreateAppPermission=_.doesUserHaveAdminPermission=void 0;var oq=iq(ZC()),Pe=iE(),El=Km();function aq(e){let t=bi(e);return t&&t.version}_.getCrmVersion=aq;function bi(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}_.getLinkedEnvironmentMetadata=bi;function yi(e,t){return e?!!e[t]:!1}_.doesUserHavePermission=yi;_.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";_.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";_.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function xo(e){return!!bi(e)&&oE(e)}_.environmentHasCds2Database=xo;function sq(e){if(e&&xo(e)){let t=Zi(e);return(0,El.getCrmAdminSecurityRolesUrl)(t)}return""}_.getSecurityUsersUrl=sq;function lq(e){if(e&&xo(e)){let t=Zi(e);return(0,El.getCrmAdminSecurityUsersUrl)(t)}return""}_.getSecurityRolesUrl=lq;function uq(e){if(e&&xo(e)){let t=Zi(e);(0,El.getCrmAllSolutionsUrl)(t)}return""}_.getAllSolutionsUrl=uq;function cq(e){if(e&&xo(e)){let t=Zi(e);return(0,El.getCrmAllPublishersUrl)(t)}return""}_.getAllPublishersUrl=cq;function dq(e){return e&&xo(e)?Zi(e):""}_.getAllThemesUrl=dq;function oE(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===Pe.EnvironmentProvisioningStates.Succeeded.toUpperCase()}_.isEnvironmentInSuccessfulState=oE;function fq(e){if(e&&xo(e)){let t=Zi(e);return(0,El.getCrmDevResourcesUrl)(t)}return""}_.getDevResourcesUrl=fq;function pq(e){return`${e}designer/app/{${_.crmBapSolutionId}}/CreateNewApp}}`}_.getCrmAppDesignerUrl=pq;function Zi(e){let t=bi(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}_.getCrmInstanceUrl=Zi;function mq(e){let t=bi(e);return t?t.uniqueName:""}_.getCrmInstanceName=mq;function hq(e){return bi(e)?Pe.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?Pe.EnvironmentType.CDS1:Pe.EnvironmentType.Empty}_.getEnvironmentType=hq;function gq(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Developer}_.isDevEnvironment=gq;function yq(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Production}_.isProdEnvironment=yq;function bq(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Sandbox}_.isSandboxEnvironment=bq;function Al(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Teams}_.isTeamsEnvironment=Al;function vq(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Platform}_.isPlatformEnvironment=vq;var wq=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===Pe.EnvironmentSkuConstants.Trial};_.isTrialEnvironment=wq;function Cq(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===Pe.EnvironmentCreationTypeConstants.DefaultTenant)}_.isDefaultEnvironment=Cq;function Eq(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}_.isDisabledEnvironment=Eq;function Aq(e){return e&&e.properties&&yi(e.properties.permissions,Pe.environmentPermissions.CreateDatabase)}_.canUserCreateDatabase=Aq;function Sq(e){return!!(e&&e.properties&&e.properties.provisioningState&&dE(e.properties.provisioningState,Pe.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}_.isDatabaseInProvisioningState=Sq;function Nq(e){return!!e&&!!e.properties&&e.properties.provisioningState===Pe.EnvironmentProvisioningStates.Creating}_.isEnvironmentInCreatingState=Nq;function _q(e){return e&&e.properties&&(e.properties.provisioningState===Pe.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===Pe.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===Pe.EnvironmentProvisioningStates.FailedDeleting)}_.isEnvironmentInDeletedState=_q;function Tq(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}_.isEnvironmentExpired=Tq;function Dq(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"}_.isLiteEnvironmentUpgrading=Dq;function Iq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}_.isEnvironmentInTestCluster=Iq;function Oq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}_.isEnvironmentInPreprodCluster=Oq;function Pq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}_.isEnvironmentInFirstReleaseCluster=Pq;function Rq(e){return e&&e.name||""}_.getEnvironmentName=Rq;function kq(e){return e&&e.properties&&e.properties.displayName||""}_.getEnvironmentDisplayName=kq;var aE="9.1.0.8202";_.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function Lq(e){return uE(e,aE)}_.doesCds2EnvironmentSupportApiVersion9_1=Lq;function $q(e){return Hm(e,aE)}_.doesCds2VersionSupportApiVersion9_1=$q;function sE(e){let t=bi(e);if(t)return t.securityGroupId}function lE(e){return e&&e.properties&&e.properties.connectedGroups}function xq(e,t){let r=lE(e);return!!r&&!!r.find(n=>n.id===t)||sE(e)===t}_.hasSecurityGroupId=xq;function Fq(e){let t=lE(e);return t&&t.length>0&&t[0].id?t[0].id:sE(e)}_.getSecurityOrConnectedGroupId=Fq;function uE(e,t){let r=e.version;return r?Hm(r,t):!1}_.isCds2EnvironmentVersionAtLeast=uE;function Hm(e,t){return t?e?(0,oq.default)(e,t)>=0:!1:!0}_.checkVersions=Hm;function Mq(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}_.getEnvironmentUpdateCadence=Mq;function Uq(e){let t=bi(e);return t?Number(t.baseLanguage):0}_.getEnvironmentLanguageCode=Uq;function cE(e){let t=bi(e);return t?t.instanceApiUrl:void 0}_.getEnvironmentInstanceApiUrl=cE;function Bq(e){let t=cE(e);return t?t+"/api/data/v9.2":""}_.getEnvironmentWebApiUrl=Bq;function qq(e){let t=Zi(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"}_.getEnvironmentDiscoveryUrl=qq;var Vq=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===Pe.DatabaseType.CommonDataService};_.hasCommonDataServiceDatabase=Vq;var Gq=e=>{var t;return yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.AdminReadEnvironment)};_.doesUserHaveAdminPermission=Gq;var Wq=e=>{var t;return yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.CreatePowerApp)};_.doesUserHaveCreateAppPermission=Wq;var zq=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateAppPermission)(e)?Al(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserMakerWithDataAccess=zq;var jq=e=>(0,_.doesUserHaveCreateAppPermission)(e)&&!Al(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserMakerWithoutDataAccess=jq;var Hq=e=>[Pe.environmentPermissions.CreateDatabaseEntities,Pe.environmentPermissions.ListDatabaseEntities,Pe.environmentPermissions.UpdateDatabaseEntities,Pe.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return yi((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});_.doesUserHaveDatabaseTablePermissions=Hq;var Kq=e=>{var t;return yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.CreateDatabase)};_.doesUserHaveCreateDatabasePermission=Kq;function dE(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}_.equalsIgnoreCase=dE;var Jq=e=>{var t;return yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.CreateFlow)};_.doesUserHaveCreateFlowPermission=Jq;var Yq=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateFlowPermission)(e)?Al(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserPautoMakerWithDataAccess=Yq;var Qq=e=>(0,_.doesUserHaveCreateFlowPermission)(e)&&!Al(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserPautoMakerWithoutDataAccess=Qq;var Xq=e=>{var t,r;return!yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.CreateFlow)&&yi((r=e.properties)===null||r===void 0?void 0:r.permissions,Pe.environmentPermissions.ReadEnvironment)};_.doesUserHaveFlowRunOnlyPermission=Xq});var Km=v(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.getRequiredComponentsQueryUrl=A.solutionComponentCountSummariesQueryUrl=A.solutionComponentSummariesQueryUrl=A.solutionComponentConfigurationsQueryUrl=A.chartsQueryUrl=A.workflowsQueryUrl=A.entityDefinitionsQueryUrl=A.solutionComponentDefinitionsQueryUrl=A.getCreateNewArticleTemplateUrl=A.getCreateNewPublisherUrl=A.getEnableSecurityRolesUrl=A.getArticleTemplateUrl=A.getFieldSecurityProfileDesignerUrl=A.getSecurityRoleDesignerUrl=A.getMailMergeTemplateDesignerUrl=A.getEmailTemplateDesignerUrl=A.getConnectionRoleDesignerUrl=A.getSiteMapDesignerUrl=A.getWebResourceFileUrl=A.getWebResourceDesignerUrl=A.getReportDesignerUrl=A.getBusinessProcessFlowDesignerUrl=A.getProcessShareUrl=A.getProcessDesignerUrl=A.getChartDesignerUrl=A.getOpenModernEntityDashboardUrl=A.getNewModernEntityDashboardUrl=A.getNewModernDashboardUrl=A.getOpenModernDashboardUrl=A.getDashboardDesignerUrl=A.getAppModuleDesignerUrl=A.privilegesQueryUrls=A.xrmApiUrl=A.getPlayAppModuleUrl=A.getCrmAdminSecurityUsersUrl=A.getCrmAdminSecurityRolesUrl=A.getCrmMyAppsUrl=A.getCrmAppDesignerUrl=A.getCrmDevResourcesUrl=A.getCrmAllPublishersUrl=A.getCrmAllSolutionsUrl=A.getSolutionPublisherUrl=A.getExportTranslationFileName=A.getExportSolutionTranslationUrl=A.getImportSolutionTranslationUrl=A.getShowSolutionDependenciesUrl=A.getShowComponentDependenciesUrl=A.cdsServiceUrl=A.ODATA_NEXT_LINK=A.ODATA_MAX_PAGE_SIZE=void 0;A.retrieveOrganizationResources=A.getUCIEntityRecordEditUrl=A.getUCIEntityRecordBaseUrl=A.getBusinessRuleDesignerUri=A.retrieveUnpublishedSuffix=A.getSavePowerSettingUri=A.getPowerSettingUri=A.getPowerSettingsUri=A.RetrievePlatform=A.getAppSettingOverrideUri=A.AppSettingOverrideName=A.getOrgSettingOverrideUri=A.OrgSettingOverrideName=A.getSettingDefinitionsUri=A.retrieveFeatureControlSettingsByNamespaceUrl=A.retrieveDeploymentPipelineConfigAppUrl=A.SPNPrincipalIdUrl=A.retrieveDeploymentEnvironmentInfoUrl=A.devSolutionInfoUrl=A.deployOperationStatusUrl=A.getAIGeneratedDeploymentNotesUrl=A.deploymentStageRunUrl=A.validatePackageAsyncUrl=A.deployPackageAsyncUrl=A.updateDeploymentStageRunUrl=A.createDeploymentStageRunUrl=A.retrieveDeploymentStagesUrl=A.retrievePipelinesUrl=A.retrieveDeploymentPipelineInfoUrl=A.getDeploymentStageRunsUrl=A.appDeploymentUrls=A.getProvisionLanguageUrl=A.getSolutionQueryUrl=A.getSolutionsByUniqueNameQueryUrl=A.solutionsQueryUrl=A.getDependentComponentsWithMetadataQueryUrl=void 0;var pE=fE();A.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";A.ODATA_NEXT_LINK="@odata.nextLink";A.cdsServiceUrl="https://cds-org/";var Nl;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Nl||(Nl={}));function Zq(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}A.getShowComponentDependenciesUrl=Zq;function e3(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}A.getShowSolutionDependenciesUrl=e3;function t3(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}A.getImportSolutionTranslationUrl=t3;function r3(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}A.getExportSolutionTranslationUrl=r3;function n3(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}A.getExportTranslationFileName=n3;function i3(e,t,r){return r?`${e}tools/publisher/edit.aspx?appSolutionId=%7b${r}%7d&id=%7b${t}%7d`:`${e}tools/publisher/edit.aspx?id=%7b${t}%7d`}A.getSolutionPublisherUrl=i3;function Jm(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function o3(e){return Jm(e,Nl.AllSolutions)}A.getCrmAllSolutionsUrl=o3;function a3(e){return Jm(e,Nl.AllPublishers)}A.getCrmAllPublishersUrl=a3;function s3(e){return Jm(e,Nl.DevResources)}A.getCrmDevResourcesUrl=s3;function l3(e,t=pE.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}A.getCrmAppDesignerUrl=l3;function u3(e){return`${e}apps`}A.getCrmMyAppsUrl=u3;function c3(e){return mE(e,"role")+"&forceUCI=0"}A.getCrmAdminSecurityRolesUrl=c3;function d3(e){return`${mE(e,"systemuser")}&forceclassic=1`}A.getCrmAdminSecurityUsersUrl=d3;function mE(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function f3(e,t){return`${e}main.aspx?appid=${t}`}A.getPlayAppModuleUrl=f3;A.xrmApiUrl="api/data/v9.0";A.privilegesQueryUrls={systemUserInfo:e=>`${e}${A.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${A.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${A.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function p3(e,t,r=pE.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}A.getAppModuleDesignerUrl=p3;function m3(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}A.getDashboardDesignerUrl=m3;function h3(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}A.getOpenModernDashboardUrl=h3;function g3(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}A.getNewModernDashboardUrl=g3;function y3(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}A.getNewModernEntityDashboardUrl=y3;function b3(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}A.getOpenModernEntityDashboardUrl=b3;function v3(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}A.getChartDesignerUrl=v3;function w3(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessDesignerUrl=w3;function C3(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessShareUrl=C3;function E3(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}A.getBusinessProcessFlowDesignerUrl=E3;function A3(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}A.getReportDesignerUrl=A3;function S3(e,t,r){return`${e}main.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&etc=9333&id=%7b${t}%7d&pagetype=webresourceedit`}A.getWebResourceDesignerUrl=S3;function N3(e,t){return`${e}WebResources/${t}`}A.getWebResourceFileUrl=N3;function _3(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}A.getSiteMapDesignerUrl=_3;function T3(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getConnectionRoleDesignerUrl=T3;function D3(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getEmailTemplateDesignerUrl=D3;function I3(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getMailMergeTemplateDesignerUrl=I3;function O3(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getSecurityRoleDesignerUrl=O3;function P3(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getFieldSecurityProfileDesignerUrl=P3;function R3(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}A.getArticleTemplateUrl=R3;function k3(e,t,r,n){return`${e}tools/FormEditor/Dialogs/FormRoleAssignment.aspx?appSolutionId=%7b${t}%7d&dType=1&formId=%7b${r}%7d&objectTypeCode=0&type=${n}`}A.getEnableSecurityRolesUrl=k3;function L3(e){return`${e}tools/publisher/edit.aspx`}A.getCreateNewPublisherUrl=L3;function $3(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}A.getCreateNewArticleTemplateUrl=$3;A.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";A.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";A.workflowsQueryUrl="api/data/v9.0/workflows";A.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";A.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";A.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";A.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function x3(e,t){return`${A.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}A.getRequiredComponentsQueryUrl=x3;function F3(e,t){return`${A.cdsServiceUrl}${A.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}A.getDependentComponentsWithMetadataQueryUrl=F3;A.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function M3(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}A.getSolutionsByUniqueNameQueryUrl=M3;function U3(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}A.getSolutionQueryUrl=U3;function B3(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}A.getProvisionLanguageUrl=B3;A.appDeploymentUrls={associateEnvironmentToPipelineUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})/deploymentpipeline_deploymentenvironment/$ref`,deploymentArtifactsUrl:"/api/data/v9.0/deploymentartifacts",deploymentEnvironmentUrl:"/api/data/v9.0/deploymentenvironments",deploymentPipelinesUrl:"/api/data/v9.0/deploymentpipelines",deploymentStagesUrl:"/api/data/v9.0/deploymentstages",retrieveDeploymentPipelinesUrl:e=>`/api/data/v9.0/RetrieveDeploymentPipelines(SourceEnvironmentId='${e}')`,deletePipelinesUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})`};function q3(e,t,r,n=!1,i=!1,o=!1,a=!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,${o?"predeploymentstepnotes,":""}validationresults,${a?"approvalcomments,":""}_devdeploymentenvironment_value,_targetdeploymentenvironment_value
&$expand=deploymentstageid($select=deploymentstageid,name,_deploymentpipelineid_value),targetdeploymentenvironment($select=deploymentenvironmentid,environmentid,name),createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)${l?",RetryUser($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}
&$filter=deploymentstageid/_deploymentpipelineid_value eq ${e} and devenvironmentid eq '${t}' and artifactname eq '${r}' and ((operation ne 200000201) or (operation eq 200000201 and operationstatus eq 200000003))
- &$orderby=starttime desc`}A.getDeploymentStageRunsUrl=P3;function R3(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}A.retrieveDeploymentPipelineInfoUrl=R3;function L3(e){return`/api/data/v9.0/deploymentenvironments
+ &$orderby=starttime desc`}A.getDeploymentStageRunsUrl=q3;function V3(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}A.retrieveDeploymentPipelineInfoUrl=V3;function G3(e){return`/api/data/v9.0/deploymentenvironments
?$select=deploymentenvironmentid,environmentid,environmenttype,name
&$expand=deploymentpipeline_deploymentenvironment($select=name,description,deploymentpipelineid;$orderby=name asc)
- &$filter=(environmentid eq '${e}')`}A.retrievePipelinesUrl=L3;function k3(e){return`/api/data/v9.0/deploymentstages
+ &$filter=(environmentid eq '${e}')`}A.retrievePipelinesUrl=G3;function W3(e){return`/api/data/v9.0/deploymentstages
?$filter=(_deploymentpipelineid_value eq ${e})
&$select=name,description,deploymentstageid,_previousdeploymentstageid_value
- &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}A.retrieveDeploymentStagesUrl=k3;function $3(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}A.createDeploymentStageRunUrl=$3;function x3(e){return`/api/data/v9.0/deploymentstageruns(${e})`}A.updateDeploymentStageRunUrl=x3;function F3(){return"/api/data/v9.0/DeployPackageAsync"}A.deployPackageAsyncUrl=F3;function M3(){return"/api/data/v9.0/ValidatePackageAsync"}A.validatePackageAsyncUrl=M3;function U3(e,t=!1,r=!1){return`/api/data/v9.0/deploymentstageruns(${e})
- ?$select=deploymentstagerunid,stagerunstatus,errormessage,operation,operationdetails,operationstatus,${t?"scheduledtime,":""}targetenvironmentid,validationresults,artifactname,deploymentsettingsjson${r?"&$expand=createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}`}A.deploymentStageRunUrl=U3;function B3(e){return`/api/data/v9.0/deploymentstageruns(${e})
- ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}A.getAIGeneratedDeploymentNotesUrl=B3;function q3(e){let t="";for(let r=0;r<e.length;r++)r===e.length-1?t=t.concat(`deploymentstagerunid eq ${e[r]}`):t=t.concat(`deploymentstagerunid eq ${e[r]} or `);return`/api/data/v9.0/deploymentstageruns
+ &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}A.retrieveDeploymentStagesUrl=W3;function z3(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}A.createDeploymentStageRunUrl=z3;function j3(e){return`/api/data/v9.0/deploymentstageruns(${e})`}A.updateDeploymentStageRunUrl=j3;function H3(){return"/api/data/v9.0/DeployPackageAsync"}A.deployPackageAsyncUrl=H3;function K3(){return"/api/data/v9.0/ValidatePackageAsync"}A.validatePackageAsyncUrl=K3;function J3(e,t=!1,r=!1){return`/api/data/v9.0/deploymentstageruns(${e})
+ ?$select=deploymentstagerunid,stagerunstatus,errormessage,operation,operationdetails,operationstatus,${t?"scheduledtime,":""}targetenvironmentid,validationresults,artifactname,deploymentsettingsjson${r?"&$expand=createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}`}A.deploymentStageRunUrl=J3;function Y3(e){return`/api/data/v9.0/deploymentstageruns(${e})
+ ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}A.getAIGeneratedDeploymentNotesUrl=Y3;function Q3(e){let t="";for(let r=0;r<e.length;r++)r===e.length-1?t=t.concat(`deploymentstagerunid eq ${e[r]}`):t=t.concat(`deploymentstagerunid eq ${e[r]} or `);return`/api/data/v9.0/deploymentstageruns
?$filter=(${t})
- &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}A.deployOperationStatusUrl=q3;function V3(e){return`/api/data/v9.0/solutions(${e})
- ?$select=solutionid,uniquename,version`}A.devSolutionInfoUrl=V3;function G3(e){return`/api/data/v9.0/deploymentenvironments
+ &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}A.deployOperationStatusUrl=Q3;function X3(e){return`/api/data/v9.0/solutions(${e})
+ ?$select=solutionid,uniquename,version`}A.devSolutionInfoUrl=X3;function Z3(e){return`/api/data/v9.0/deploymentenvironments
?$select=deploymentenvironmentid,environmentid,environmenttype,name
- &$filter=(environmentid eq '${e}')`}A.retrieveDeploymentEnvironmentInfoUrl=G3;var W3=e=>`/api/data/v9.0/systemusers
+ &$filter=(environmentid eq '${e}')`}A.retrieveDeploymentEnvironmentInfoUrl=Z3;var eV=e=>`/api/data/v9.0/systemusers
?$select=azureactivedirectoryobjectid
- &$filter=(applicationid eq '${e}')`;A.SPNPrincipalIdUrl=W3;function z3(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}A.retrieveDeploymentPipelineConfigAppUrl=z3;A.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function j3(e){return`/api/data/v9.0/settingdefinitions${e}`}A.getSettingDefinitionsUri=j3;A.OrgSettingOverrideName="organizationsettings";function H3(e,t=!1){let r=`/api/data/v9.0/${A.OrgSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl}${r}`:r}A.getOrgSettingOverrideUri=H3;A.AppSettingOverrideName="appsettings";function K3(e,t=!1){let r=`/api/data/v9.0/${A.AppSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl.replace("/$","")}${r}`:r}A.getAppSettingOverrideUri=K3;var wl;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(wl||(A.RetrievePlatform=wl={}));function J3(e,t,r,n=wl.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),r&&o.push(`RetrieveHiddenSettings=${r}`),n!==wl.All&&o.push(`RetrievePlatformSettings=${n===wl.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${A.cdsServiceUrl}${a}`:a}A.getPowerSettingsUri=J3;function Y3(e,t,r,n=!1){let i=[`SettingName='${e}'`];t!==void 0&&i.push(`SolutionName='${t}'`),r!==void 0&&i.push(`AppUniqueName='${r}'`);let o="/api/data/v9.0/RetrieveUnpublishedSettingInfo";return i.length&&(o=`${o}(${i.join(",")})`),n?`${A.cdsServiceUrl}${o}`:o}A.getPowerSettingUri=Y3;function Q3(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${A.cdsServiceUrl}${t}`:t}A.getSavePowerSettingUri=Q3;A.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function X3(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}A.getBusinessRuleDesignerUri=X3;function oE({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}A.getUCIEntityRecordBaseUrl=oE;function Z3({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||oE({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}A.getUCIEntityRecordEditUrl=Z3;A.retrieveOrganizationResources=`${A.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var lE=v(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});Pc.DataverseClient=void 0;var eV=Bm(),$o=Q(),aE=ye(),tV=new Set(["entitydefinitions","relationshipdefinitions","globaloptionsetdefinitions"]);function rV(e){var t,r,n,i;let o=e.split("?")[0].split("/").filter(l=>l!==""),a=((t=o[0])===null||t===void 0?void 0:t.toLowerCase())==="api"&&((r=o[1])===null||r===void 0?void 0:r.toLowerCase())==="data"&&/^v\d/i.test((n=o[2])!==null&&n!==void 0?n:""),s=((i=o[a?3:0])!==null&&i!==void 0?i:"").split("(")[0].toLowerCase();return tV.has(s)}function nV(e){let t=e.indexOf("://"),r=t===-1?"":e.slice(t+3),n=r.search(/[/?#]/),i=n===-1?"":r.slice(n),o=i.search(/[?#]/);return o===-1?i:i.slice(0,o)}function sE(e,t){var r;if(!rV(e))return t;let n=(r=t?.headers)!==null&&r!==void 0?r:{};return Object.keys(n).some(i=>i.toLowerCase()==="consistency")?t:{...t,headers:{...n,Consistency:"Strong"}}}var Vm=class e{constructor(t,r,n,i=1){this.instanceUrl=t,this.httpClient=r,this.solutionUniqueName=n,this.readConcurrency=i}withSolutionScope(t){return new e(this.instanceUrl,this.httpClient,t,this.readConcurrency)}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}/${eV.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof $o.SdkError?n:new $o.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t),i=sE(t,r);return(0,aE.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,i)))}getAbsolute(t,r){this.assertSameOrigin(t);let n=sE(nV(t),r);return(0,aE.resendDeadlockVictim)(()=>this.send(t,()=>this.httpClient.get(t,n)))}assertSameOrigin(t){let r,n;try{r=new URL(t),n=new URL(this.instanceUrl)}catch{throw new $o.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new $o.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 supportsPut(){return typeof this.httpClient.put=="function"}get solutionName(){return this.solutionUniqueName}postBatch(t,r,n){if(!this.httpClient.postRaw)throw new $o.InvalidArgumentError("The injected HttpClient does not implement postRaw(), required for atomic $batch change sets");let i=this.apiUrl("/$batch"),o={...n,headers:{...n?.headers,"Content-Type":`multipart/mixed;boundary=${r}`}};return this.send(i,()=>this.httpClient.postRaw(i,t,o))}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 $o.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 $o.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)))}};Pc.DataverseClient=Vm});var dE=v(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.findColumns=rr.findTables=rr.readCheckColumns=rr.readColumnHints=rr.fetchEntityMetadataFromApi=rr.COLUMN_DETAIL_VERSION=void 0;var kc=ye(),hr=se();function Yr(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}rr.COLUMN_DETAIL_VERSION=2;function Gm(e){var t,r;return typeof((t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)=="string"||((r=e?.LocalizedLabels)!==null&&r!==void 0?r:[]).some(n=>typeof n?.Label=="string")}function xo(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 Rc(e,t){return(await $c(e,t)).rows}async function $c(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?{rows:[],ok:!1}:{rows:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[],ok:!0}}function Br(e){return`/EntityDefinitions(LogicalName='${(0,hr.odataPathLiteral)(e)}')`}async function iV(e,t,r){let n=await Rc(e,`${Br(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,hr.odataQuery)([["$select","LogicalName,MaxLength"]])}`);for(let i of n){let o=r.get(i.LogicalName);o&&typeof i.MaxLength=="number"&&(o.maxLength=i.MaxLength)}}function oV(e){return`${Br(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,hr.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function aV(e,t){var r;let{rows:n}=await e;for(let i of n){let o=t.get(i.LogicalName);o&&(!((r=i.OptionSet)===null||r===void 0)&&r.Options)&&(o.options=i.OptionSet.Options.map(a=>{var s;return{value:(s=a.Value)!==null&&s!==void 0?s:0,label:Yr(a.Label),...xo(a.Label)?{localizedLabel:xo(a.Label)}:{}}}))}}function Wm(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:Yr(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function sV(e,t,r){var n;let i=c=>$c(e,c).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([r.catch(()=>({rows:[],ok:!1})),...o.map(c=>i(`${Br(t)}/Attributes/Microsoft.Dynamics.CRM.${c}${(0,hr.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`))]),s=new Map,l=!0;for(let{rows:c}of a)for(let d of c)!((n=d.OptionSet)===null||n===void 0)&&n.Options&&(l=l&&d.OptionSet.Options.every(f=>Gm(f.Label)),s.set(d.LogicalName,d.OptionSet.Options.map(Wm)));let u=await i(`${Br(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,hr.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let c of u.rows){let d=c.OptionSet;d?.TrueOption&&d.FalseOption&&(l=l&&Gm(d.TrueOption.Label)&&Gm(d.FalseOption.Label),s.set(c.LogicalName,[Wm(d.FalseOption),Wm(d.TrueOption)]))}return{byColumn:s,complete:l&&u.ok&&a.every(c=>c.ok)}}async function lV(e,t,r){let{rows:n,ok:i}=await $c(e,`${Br(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,hr.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let o of n){let a=r.get(o.LogicalName);a&&o.Targets&&(a.targets=o.Targets)}return i}function Lc(e,t){return e<t?-1:e>t?1:0}var uE={OneToMany:0,ManyToOne:1,ManyToMany:2};function uV(e,t){return uE[e.type]-uE[t.type]||Lc(e.schemaName,t.schemaName)||Lc(e.relatedEntity,t.relatedEntity)||Lc(e.relatedAttribute,t.relatedAttribute)}async function cV(e,t){var r,n,i,o;let a=[],s=await Rc(e,`${Br(t)}/OneToManyRelationships${(0,hr.odataQuery)([["$select","SchemaName,ReferencingEntity,ReferencingAttribute"]])}`);for(let c of s)a.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 Rc(e,`${Br(t)}/ManyToOneRelationships${(0,hr.odataQuery)([["$select","SchemaName,ReferencedEntity,ReferencedAttribute"]])}`);for(let c of l)a.push({schemaName:c.SchemaName,type:"ManyToOne",relatedEntity:(i=c.ReferencedEntity)!==null&&i!==void 0?i:"",relatedAttribute:(o=c.ReferencedAttribute)!==null&&o!==void 0?o:""});let u=await Rc(e,`${Br(t)}/ManyToManyRelationships${(0,hr.odataQuery)([["$select","SchemaName,Entity1LogicalName,Entity2LogicalName"]])}`);for(let c of u){let d=c.Entity1LogicalName===t?c.Entity2LogicalName:c.Entity1LogicalName;a.push({schemaName:c.SchemaName,type:"ManyToMany",relatedEntity:d??"",relatedAttribute:""})}return a.sort(uV)}async function dV(e,t){var r,n,i,o,a;let s=`${Br(t)}`+(0,hr.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf)"]]),u=(0,kc.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(g=>{var b,w,E;return{logicalName:g.LogicalName,displayName:Yr(g.DisplayName),...xo(g.DisplayName)?{localizedDisplayName:xo(g.DisplayName)}:{},attributeType:(b=g.AttributeType)!==null&&b!==void 0?b:"Unknown",isCustomAttribute:!!g.IsCustomAttribute,attributeTypeName:(E=(w=g.AttributeTypeName)===null||w===void 0?void 0:w.Value)!==null&&E!==void 0?E:"",...typeof g.IsValidForUpdate=="boolean"?{isValidForUpdate:g.IsValidForUpdate}:{},...typeof g.IsValidForRead=="boolean"?{isValidForRead:g.IsValidForRead}:{},...g.AttributeOf?{attributeOf:g.AttributeOf}:{},...Yr(g.Description)?{description:Yr(g.Description)}:{}}}).sort((g,b)=>Lc(g.logicalName,b.logicalName)),d=new Map(c.map(g=>[g.logicalName,g])),f=$c(e,oV(t)),[,,m,p,h]=await Promise.all([iV(e,t,d),aV(f,d),sV(e,t,f),lV(e,t,d),cV(e,t)]);for(let g of c){let b=m.byColumn.get(g.logicalName);b&&(g.choices=b)}return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:Yr(u.DisplayName),...xo(u.DisplayName)?{localizedDisplayName:xo(u.DisplayName)}:{},entitySetName:(i=u.EntitySetName)!==null&&i!==void 0?i:"",primaryNameAttribute:(o=u.PrimaryNameAttribute)!==null&&o!==void 0?o:"",primaryIdAttribute:(a=u.PrimaryIdAttribute)!==null&&a!==void 0?a:"",...u.PrimaryImageAttribute?{primaryImageAttribute:u.PrimaryImageAttribute}:{},isCustomEntity:!!u.IsCustomEntity,...Yr(u.Description)?{description:Yr(u.Description)}:{},columnDetailComplete:m.complete&&p,columnDetailVersion:rr.COLUMN_DETAIL_VERSION,attributes:c,relationships:h}}rr.fetchEntityMetadataFromApi=dV;var cE=40;async function zm(e,t,r,n){var i,o;let a=[...new Set(n.filter(l=>l!==""))],s=[];for(let l=0;l<a.length;l+=cE){let u=a.slice(l,l+cE).map(f=>`LogicalName eq '${(0,hr.odataLiteral)(f)}'`).join(" or "),c=t+(0,hr.odataQuery)([["$select",r],["$filter",u]]),d=(0,kc.ensureSuccess)(await e.get(c),e.apiUrl(c));s.push(...(o=(i=d.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[])}return s}async function fV(e,t,r){return(await zm(e,`${Br(t)}/Attributes`,"LogicalName,AttributeType,DisplayName",r)).map(i=>{var o;let a=xo(i.DisplayName);return{logicalName:i.LogicalName,displayName:Yr(i.DisplayName),...a?{localizedDisplayName:a}:{},attributeType:(o=i.AttributeType)!==null&&o!==void 0?o:"Unknown"}})}rr.readColumnHints=fV;async function pV(e,t,r){let i=(await zm(e,`${Br(t)}/Attributes`,"LogicalName,AttributeType,DisplayName,IsCustomAttribute",r)).map(s=>{var l;return{logicalName:s.LogicalName,displayName:Yr(s.DisplayName),attributeType:(l=s.AttributeType)!==null&&l!==void 0?l:"Unknown",isCustomAttribute:!!s.IsCustomAttribute}}),o=new Map(i.filter(s=>s.attributeType==="String").map(s=>[s.logicalName,s])),a=await zm(e,`${Br(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata`,"LogicalName,MaxLength",[...o.keys()]);for(let s of a){let l=o.get(s.LogicalName);l&&typeof s.MaxLength=="number"&&(l.maxLength=s.MaxLength)}return i}rr.readCheckColumns=pV;async function mV(e,t,r){var n,i;let o=`/EntityDefinitions${(0,hr.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,kc.ensureSuccess)(await e.get(o),e.apiUrl(o)).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,f;return{logicalName:c.LogicalName,schemaName:(d=c.SchemaName)!==null&&d!==void 0?d:c.LogicalName,displayName:Yr(c.DisplayName),entitySetName:(f=c.EntitySetName)!==null&&f!==void 0?f:"",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}rr.findTables=mV;async function hV(e,t,r,n){var i,o;let a=`${Br(t)}/Attributes`+(0,hr.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(o=(i=(0,kc.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[],u=(r??"").toLowerCase(),c=l.map(d=>{var f,m;return{logicalName:d.LogicalName,schemaName:(f=d.SchemaName)!==null&&f!==void 0?f:d.LogicalName,displayName:Yr(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}rr.findColumns=hV});var Km=v(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.renderTypeRegistrations=gr.buildGenPageLegacyEnums=gr.renderGenPageAuthoringTypes=gr.buildGenPageRuntimeTypes=gr.toDesignerEntity=gr.TABLE_LOGICAL_NAME=void 0;gr.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function jm(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var gV=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function xc(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function mE(e){var t,r;let n=e.choices;if(!n||n.length===0)return;let i=xc(e)==="boolean",o={};for(let a of n)o[a.value]={text:(r=(t=a.invariantName)!==null&&t!==void 0?t:a.label)!==null&&r!==void 0?r:"",value:a.value,...!i&&a.color?{color:a.color}:{}};return o}function fE(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function hE(e){return!gV.has(e.logicalName)&&(!e.attributeOf||xc(e)==="image")&&e.isValidForRead!==!1}var pE=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function gE(e){let t=e.primaryImageAttribute,r=new Set([e.primaryIdAttribute,e.primaryNameAttribute,t,t?`${t}_url`:void 0,"processid","statecode","statuscode"].filter(o=>!!o)),n=e.attributes.filter(o=>r.has(o.logicalName)).sort(fE),i=e.attributes.filter(o=>!r.has(o.logicalName)).sort(fE);return[...n,...i]}function Hm(e){var t;let r=[],n=new Set,i=gE(e);for(let o of i){let a=xc(o),s=a==="image";hE(o)&&(s&&o.attributeOf&&n.add(o.attributeOf),r.push({AttributeTypeName:a,IsReadOnly:!o.isValidForUpdate,LogicalName:o.logicalName,OptionSet:mE(o),Targets:o.targets,Description:o.description,MaxLength:o.maxLength}))}return{Description:(t=e.description)!==null&&t!==void 0?t:"",LogicalName:e.logicalName,PrimaryIdAttribute:e.primaryIdAttribute,Attributes:r.filter(o=>!n.has(o.LogicalName))}}gr.toDesignerEntity=Hm;function yE(e,t="None"){let r={};for(let n of e)r[n.logicalName]=Hm(n);return wE(r,t)}gr.buildGenPageRuntimeTypes=yE;var bE=`export interface TableRegistrations extends BaseTableRegistrations {
-`,vE=`export interface EnumRegistrations extends BaseEnumRegistrations {
-`;function yV(e,t){return e.length>0?yE(e,t).text:EE(`${bE}}
-`,`${vE}}
-`,"","")}gr.renderGenPageAuthoringTypes=yV;function bV(e){let t=new Set;for(let n of e)for(let i of Hm(n).Attributes)pE.has(i.AttributeTypeName)&&t.add(`${n.logicalName}_${i.LogicalName}`);let r=new Map;for(let n of e)for(let i of gE(n)){let o=`${n.logicalName}_${i.logicalName}`,a=mE(i);if(hE(i)||!pE.has(xc(i))||!a||t.has(o)||r.has(o))continue;let s={name:o,runtime:{},labels:new Map};r.set(o,{declaration:CE(o,a,!1,s),model:s})}return r}gr.buildGenPageLegacyEnums=bV;function wE(e,t="None"){var r,n;let i=new Map,o=Object.values(e);if(o.length===0)return{text:"",enums:i};let a=t==="ColorsDefaultsConstraints"||t==="ColorsDefaultsConstraintsDescriptions",s=t==="ColorsDefaultsConstraintsDescriptions",l=bE,u=vE,c="",d="";for(let f of o){s&&f.Description&&(c+=`// ${jm(f.Description)}
+ &$filter=(applicationid eq '${e}')`;A.SPNPrincipalIdUrl=eV;function tV(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}A.retrieveDeploymentPipelineConfigAppUrl=tV;A.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function rV(e){return`/api/data/v9.0/settingdefinitions${e}`}A.getSettingDefinitionsUri=rV;A.OrgSettingOverrideName="organizationsettings";function nV(e,t=!1){let r=`/api/data/v9.0/${A.OrgSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl}${r}`:r}A.getOrgSettingOverrideUri=nV;A.AppSettingOverrideName="appsettings";function iV(e,t=!1){let r=`/api/data/v9.0/${A.AppSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl.replace("/$","")}${r}`:r}A.getAppSettingOverrideUri=iV;var Sl;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(Sl||(A.RetrievePlatform=Sl={}));function oV(e,t,r,n=Sl.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),r&&o.push(`RetrieveHiddenSettings=${r}`),n!==Sl.All&&o.push(`RetrievePlatformSettings=${n===Sl.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${A.cdsServiceUrl}${a}`:a}A.getPowerSettingsUri=oV;function aV(e,t,r,n=!1){let i=[`SettingName='${e}'`];t!==void 0&&i.push(`SolutionName='${t}'`),r!==void 0&&i.push(`AppUniqueName='${r}'`);let o="/api/data/v9.0/RetrieveUnpublishedSettingInfo";return i.length&&(o=`${o}(${i.join(",")})`),n?`${A.cdsServiceUrl}${o}`:o}A.getPowerSettingUri=aV;function sV(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${A.cdsServiceUrl}${t}`:t}A.getSavePowerSettingUri=sV;A.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function lV(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}A.getBusinessRuleDesignerUri=lV;function hE({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}A.getUCIEntityRecordBaseUrl=hE;function uV({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||hE({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}A.getUCIEntityRecordEditUrl=uV;A.retrieveOrganizationResources=`${A.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var bE=v(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});Mc.DataverseClient=void 0;var cV=Km(),Fo=Q(),gE=ye(),dV=new Set(["entitydefinitions","relationshipdefinitions","globaloptionsetdefinitions"]);function fV(e){var t,r,n,i;let o=e.split("?")[0].split("/").filter(l=>l!==""),a=((t=o[0])===null||t===void 0?void 0:t.toLowerCase())==="api"&&((r=o[1])===null||r===void 0?void 0:r.toLowerCase())==="data"&&/^v\d/i.test((n=o[2])!==null&&n!==void 0?n:""),s=((i=o[a?3:0])!==null&&i!==void 0?i:"").split("(")[0].toLowerCase();return dV.has(s)}function pV(e){let t=e.indexOf("://"),r=t===-1?"":e.slice(t+3),n=r.search(/[/?#]/),i=n===-1?"":r.slice(n),o=i.search(/[?#]/);return o===-1?i:i.slice(0,o)}function yE(e,t){var r;if(!fV(e))return t;let n=(r=t?.headers)!==null&&r!==void 0?r:{};return Object.keys(n).some(i=>i.toLowerCase()==="consistency")?t:{...t,headers:{...n,Consistency:"Strong"}}}var Ym=class{constructor(t,r,n,i=1){this.instanceUrl=t,this.httpClient=r,this.solutionUniqueName=n,this.readConcurrency=i}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}/${cV.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof Fo.SdkError?n:new Fo.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t),i=yE(t,r);return(0,gE.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,i)))}getAbsolute(t,r){this.assertSameOrigin(t);let n=yE(pV(t),r);return(0,gE.resendDeadlockVictim)(()=>this.send(t,()=>this.httpClient.get(t,n)))}assertSameOrigin(t){let r,n;try{r=new URL(t),n=new URL(this.instanceUrl)}catch{throw new Fo.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new Fo.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 supportsPut(){return typeof this.httpClient.put=="function"}get solutionName(){return this.solutionUniqueName}postBatch(t,r,n){if(!this.httpClient.postRaw)throw new Fo.InvalidArgumentError("The injected HttpClient does not implement postRaw(), required for atomic $batch change sets");let i=this.apiUrl("/$batch"),o={...n,headers:{...n?.headers,"Content-Type":`multipart/mixed;boundary=${r}`}};return this.send(i,()=>this.httpClient.postRaw(i,t,o))}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 Fo.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 Fo.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)))}};Mc.DataverseClient=Ym});var CE=v(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.findColumns=or.findTables=or.readCheckColumns=or.readColumnHints=or.fetchEntityMetadataFromApi=or.COLUMN_DETAIL_VERSION=void 0;var qc=ye(),br=le();function Xr(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}or.COLUMN_DETAIL_VERSION=2;function Qm(e){var t,r;return typeof((t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)=="string"||((r=e?.LocalizedLabels)!==null&&r!==void 0?r:[]).some(n=>typeof n?.Label=="string")}function Mo(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 Uc(e,t){return(await Vc(e,t)).rows}async function Vc(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?{rows:[],ok:!1}:{rows:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[],ok:!0}}function Gr(e){return`/EntityDefinitions(LogicalName='${(0,br.odataPathLiteral)(e)}')`}async function mV(e,t,r){let n=await Uc(e,`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,br.odataQuery)([["$select","LogicalName,MaxLength"]])}`);for(let i of n){let o=r.get(i.LogicalName);o&&typeof i.MaxLength=="number"&&(o.maxLength=i.MaxLength)}}function hV(e){return`${Gr(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,br.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function gV(e,t){var r;let{rows:n}=await e;for(let i of n){let o=t.get(i.LogicalName);o&&(!((r=i.OptionSet)===null||r===void 0)&&r.Options)&&(o.options=i.OptionSet.Options.map(a=>{var s;return{value:(s=a.Value)!==null&&s!==void 0?s:0,label:Xr(a.Label),...Mo(a.Label)?{localizedLabel:Mo(a.Label)}:{}}}))}}function Xm(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:Xr(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function yV(e,t,r){var n;let i=c=>Vc(e,c).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([r.catch(()=>({rows:[],ok:!1})),...o.map(c=>i(`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.${c}${(0,br.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`))]),s=new Map,l=!0;for(let{rows:c}of a)for(let d of c)!((n=d.OptionSet)===null||n===void 0)&&n.Options&&(l=l&&d.OptionSet.Options.every(f=>Qm(f.Label)),s.set(d.LogicalName,d.OptionSet.Options.map(Xm)));let u=await i(`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,br.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let c of u.rows){let d=c.OptionSet;d?.TrueOption&&d.FalseOption&&(l=l&&Qm(d.TrueOption.Label)&&Qm(d.FalseOption.Label),s.set(c.LogicalName,[Xm(d.FalseOption),Xm(d.TrueOption)]))}return{byColumn:s,complete:l&&u.ok&&a.every(c=>c.ok)}}async function bV(e,t,r){let{rows:n,ok:i}=await Vc(e,`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,br.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let o of n){let a=r.get(o.LogicalName);a&&o.Targets&&(a.targets=o.Targets)}return i}function Bc(e,t){return e<t?-1:e>t?1:0}var vE={OneToMany:0,ManyToOne:1,ManyToMany:2};function vV(e,t){return vE[e.type]-vE[t.type]||Bc(e.schemaName,t.schemaName)||Bc(e.relatedEntity,t.relatedEntity)||Bc(e.relatedAttribute,t.relatedAttribute)}async function wV(e,t){var r,n,i,o;let a=[],s=await Uc(e,`${Gr(t)}/OneToManyRelationships${(0,br.odataQuery)([["$select","SchemaName,ReferencingEntity,ReferencingAttribute"]])}`);for(let c of s)a.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 Uc(e,`${Gr(t)}/ManyToOneRelationships${(0,br.odataQuery)([["$select","SchemaName,ReferencedEntity,ReferencedAttribute"]])}`);for(let c of l)a.push({schemaName:c.SchemaName,type:"ManyToOne",relatedEntity:(i=c.ReferencedEntity)!==null&&i!==void 0?i:"",relatedAttribute:(o=c.ReferencedAttribute)!==null&&o!==void 0?o:""});let u=await Uc(e,`${Gr(t)}/ManyToManyRelationships${(0,br.odataQuery)([["$select","SchemaName,Entity1LogicalName,Entity2LogicalName"]])}`);for(let c of u){let d=c.Entity1LogicalName===t?c.Entity2LogicalName:c.Entity1LogicalName;a.push({schemaName:c.SchemaName,type:"ManyToMany",relatedEntity:d??"",relatedAttribute:""})}return a.sort(vV)}async function CV(e,t){var r,n,i,o,a;let s=`${Gr(t)}`+(0,br.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf)"]]),u=(0,qc.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(g=>{var b,w,C;return{logicalName:g.LogicalName,displayName:Xr(g.DisplayName),...Mo(g.DisplayName)?{localizedDisplayName:Mo(g.DisplayName)}:{},attributeType:(b=g.AttributeType)!==null&&b!==void 0?b:"Unknown",isCustomAttribute:!!g.IsCustomAttribute,attributeTypeName:(C=(w=g.AttributeTypeName)===null||w===void 0?void 0:w.Value)!==null&&C!==void 0?C:"",...typeof g.IsValidForUpdate=="boolean"?{isValidForUpdate:g.IsValidForUpdate}:{},...typeof g.IsValidForRead=="boolean"?{isValidForRead:g.IsValidForRead}:{},...g.AttributeOf?{attributeOf:g.AttributeOf}:{},...Xr(g.Description)?{description:Xr(g.Description)}:{}}}).sort((g,b)=>Bc(g.logicalName,b.logicalName)),d=new Map(c.map(g=>[g.logicalName,g])),f=Vc(e,hV(t)),[,,m,p,h]=await Promise.all([mV(e,t,d),gV(f,d),yV(e,t,f),bV(e,t,d),wV(e,t)]);for(let g of c){let b=m.byColumn.get(g.logicalName);b&&(g.choices=b)}return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:Xr(u.DisplayName),...Mo(u.DisplayName)?{localizedDisplayName:Mo(u.DisplayName)}:{},entitySetName:(i=u.EntitySetName)!==null&&i!==void 0?i:"",primaryNameAttribute:(o=u.PrimaryNameAttribute)!==null&&o!==void 0?o:"",primaryIdAttribute:(a=u.PrimaryIdAttribute)!==null&&a!==void 0?a:"",...u.PrimaryImageAttribute?{primaryImageAttribute:u.PrimaryImageAttribute}:{},isCustomEntity:!!u.IsCustomEntity,...Xr(u.Description)?{description:Xr(u.Description)}:{},columnDetailComplete:m.complete&&p,columnDetailVersion:or.COLUMN_DETAIL_VERSION,attributes:c,relationships:h}}or.fetchEntityMetadataFromApi=CV;var wE=40;async function Zm(e,t,r,n){var i,o;let a=[...new Set(n.filter(l=>l!==""))],s=[];for(let l=0;l<a.length;l+=wE){let u=a.slice(l,l+wE).map(f=>`LogicalName eq '${(0,br.odataLiteral)(f)}'`).join(" or "),c=t+(0,br.odataQuery)([["$select",r],["$filter",u]]),d=(0,qc.ensureSuccess)(await e.get(c),e.apiUrl(c));s.push(...(o=(i=d.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[])}return s}async function EV(e,t,r){return(await Zm(e,`${Gr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName",r)).map(i=>{var o;let a=Mo(i.DisplayName);return{logicalName:i.LogicalName,displayName:Xr(i.DisplayName),...a?{localizedDisplayName:a}:{},attributeType:(o=i.AttributeType)!==null&&o!==void 0?o:"Unknown"}})}or.readColumnHints=EV;async function AV(e,t,r){let i=(await Zm(e,`${Gr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName,IsCustomAttribute",r)).map(s=>{var l;return{logicalName:s.LogicalName,displayName:Xr(s.DisplayName),attributeType:(l=s.AttributeType)!==null&&l!==void 0?l:"Unknown",isCustomAttribute:!!s.IsCustomAttribute}}),o=new Map(i.filter(s=>s.attributeType==="String").map(s=>[s.logicalName,s])),a=await Zm(e,`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata`,"LogicalName,MaxLength",[...o.keys()]);for(let s of a){let l=o.get(s.LogicalName);l&&typeof s.MaxLength=="number"&&(l.maxLength=s.MaxLength)}return i}or.readCheckColumns=AV;async function SV(e,t,r){var n,i;let o=`/EntityDefinitions${(0,br.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,qc.ensureSuccess)(await e.get(o),e.apiUrl(o)).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,f;return{logicalName:c.LogicalName,schemaName:(d=c.SchemaName)!==null&&d!==void 0?d:c.LogicalName,displayName:Xr(c.DisplayName),entitySetName:(f=c.EntitySetName)!==null&&f!==void 0?f:"",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}or.findTables=SV;async function NV(e,t,r,n){var i,o;let a=`${Gr(t)}/Attributes`+(0,br.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(o=(i=(0,qc.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[],u=(r??"").toLowerCase(),c=l.map(d=>{var f,m;return{logicalName:d.LogicalName,schemaName:(f=d.SchemaName)!==null&&f!==void 0?f:d.LogicalName,displayName:Xr(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}or.findColumns=NV});var rh=v(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.renderTypeRegistrations=vr.buildGenPageLegacyEnums=vr.renderGenPageAuthoringTypes=vr.buildGenPageRuntimeTypes=vr.toDesignerEntity=vr.TABLE_LOGICAL_NAME=void 0;vr.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function eh(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var _V=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function Gc(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function SE(e){var t,r;let n=e.choices;if(!n||n.length===0)return;let i=Gc(e)==="boolean",o={};for(let a of n)o[a.value]={text:(r=(t=a.invariantName)!==null&&t!==void 0?t:a.label)!==null&&r!==void 0?r:"",value:a.value,...!i&&a.color?{color:a.color}:{}};return o}function EE(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function NE(e){return!_V.has(e.logicalName)&&(!e.attributeOf||Gc(e)==="image")&&e.isValidForRead!==!1}var AE=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function _E(e){let t=e.primaryImageAttribute,r=new Set([e.primaryIdAttribute,e.primaryNameAttribute,t,t?`${t}_url`:void 0,"processid","statecode","statuscode"].filter(o=>!!o)),n=e.attributes.filter(o=>r.has(o.logicalName)).sort(EE),i=e.attributes.filter(o=>!r.has(o.logicalName)).sort(EE);return[...n,...i]}function th(e){var t;let r=[],n=new Set,i=_E(e);for(let o of i){let a=Gc(o),s=a==="image";NE(o)&&(s&&o.attributeOf&&n.add(o.attributeOf),r.push({AttributeTypeName:a,IsReadOnly:!o.isValidForUpdate,LogicalName:o.logicalName,OptionSet:SE(o),Targets:o.targets,Description:o.description,MaxLength:o.maxLength}))}return{Description:(t=e.description)!==null&&t!==void 0?t:"",LogicalName:e.logicalName,PrimaryIdAttribute:e.primaryIdAttribute,Attributes:r.filter(o=>!n.has(o.LogicalName))}}vr.toDesignerEntity=th;function TE(e,t="None"){let r={};for(let n of e)r[n.logicalName]=th(n);return OE(r,t)}vr.buildGenPageRuntimeTypes=TE;var DE=`export interface TableRegistrations extends BaseTableRegistrations {
+`,IE=`export interface EnumRegistrations extends BaseEnumRegistrations {
+`;function TV(e,t){return e.length>0?TE(e,t).text:RE(`${DE}}
+`,`${IE}}
+`,"","")}vr.renderGenPageAuthoringTypes=TV;function DV(e){let t=new Set;for(let n of e)for(let i of th(n).Attributes)AE.has(i.AttributeTypeName)&&t.add(`${n.logicalName}_${i.LogicalName}`);let r=new Map;for(let n of e)for(let i of _E(n)){let o=`${n.logicalName}_${i.logicalName}`,a=SE(i);if(NE(i)||!AE.has(Gc(i))||!a||t.has(o)||r.has(o))continue;let s={name:o,runtime:{},labels:new Map};r.set(o,{declaration:PE(o,a,!1,s),model:s})}return r}vr.buildGenPageLegacyEnums=DV;function OE(e,t="None"){var r,n;let i=new Map,o=Object.values(e);if(o.length===0)return{text:"",enums:i};let a=t==="ColorsDefaultsConstraints"||t==="ColorsDefaultsConstraintsDescriptions",s=t==="ColorsDefaultsConstraintsDescriptions",l=DE,u=IE,c="",d="";for(let f of o){s&&f.Description&&(c+=`// ${eh(f.Description)}
`),c+=`export type ${f.LogicalName} = TableRow<{
// Primary Key Column
readonly ${f.PrimaryIdAttribute}: string,
@@ -62,19 +62,19 @@ var AU=Object.create;var bc=Object.defineProperty;var SU=Object.getOwnPropertyDe
`;break;case"customer":case"lookup":{let g=(r=m.Targets)!==null&&r!==void 0?r:m.AttributeTypeName==="customer"?["account","contact"]:void 0;if(!g||g.length===0){h=!1;break}p=` // Foreign Key Column
${m.IsReadOnly||g.every(w=>!e[w])?" readonly ":""}_${m.LogicalName}_value: `;let b="";for(let w of g)b+=`${b.length===0?"":" | "}\`/${w}(\${string})\``;p+=`${b},
`;break}case"boolean":case"picklist":case"multiselectpicklist":case"state":case"status":{let g=`${f.LogicalName}_${m.LogicalName}`;p+=`: ${g},
-`;let b=(n=i.get(g))!==null&&n!==void 0?n:{name:g,runtime:{},labels:new Map};i.set(g,b),d+=CE(g,m.OptionSet,a,b),u+=` "${f.LogicalName}-${m.LogicalName}": ${g},
+`;let b=(n=i.get(g))!==null&&n!==void 0?n:{name:g,runtime:{},labels:new Map};i.set(g,b),d+=PE(g,m.OptionSet,a,b),u+=` "${f.LogicalName}-${m.LogicalName}": ${g},
`;break}case"image":c+=` // This is an image encoded as a base64 string
`,p+=`: string,
-`;break;default:h=!1}h&&(s&&m.Description&&(c+=` // ${jm(m.Description)}
+`;break;default:h=!1}h&&(s&&m.Description&&(c+=` // ${eh(m.Description)}
`),a&&m.MaxLength&&(c+=" // Maximum length: "+m.MaxLength+`
`),c+=` ${p}`)}c+=`}>
`}return l+=`}
`,u+=`}
-`,{text:EE(l,u,c,d),enums:i}}gr.renderTypeRegistrations=wE;function CE(e,t,r,n){var i;let o=`const enum ${e} {
-`;for(let a of Object.values(t??{}))if(a){r&&(o+=`${a.color?`// Option Color: ${jm(a.color)}
+`,{text:RE(l,u,c,d),enums:i}}vr.renderTypeRegistrations=OE;function PE(e,t,r,n){var i;let o=`const enum ${e} {
+`;for(let a of Object.values(t??{}))if(a){r&&(o+=`${a.color?`// Option Color: ${eh(a.color)}
`:""}`),o+=`${JSON.stringify(a.text)} = ${a.value},
`,n.runtime[a.text]=a.value,n.runtime[String(a.value)]=a.text;let s=(i=n.labels.get(a.text))!==null&&i!==void 0?i:[];s.includes(a.value)||s.push(a.value),n.labels.set(a.text,s)}return`${o}}
-`}function EE(e,t,r,n){return`
+`}function RE(e,t,r,n){return`
// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------
${e}
${t}
@@ -345,23 +345,23 @@ export interface GeneratedComponentProps {
dataApi: UxAgentDataApi;
pageInput?: PageInput;
}
-`}});var NE=v(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});Fc.generateGenPageRuntimeTypes=void 0;var SE=Km(),Fo=Q(),AE=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),Mo="generateGenPageRuntimeTypes";async function vV(e,t,r){let n=wV(t),i=CV(r),o=[];for(let a of n){let s=await e(a);if(s.columnDetailComplete!==!0)throw new Fo.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${Mo}: the column metadata of data source '${a}' could not be read completely (a choice or lookup read failed, or returned options with no label), so its RuntimeTypes would lack enums a page can use. Retry.`);o.push(s)}return(0,SE.renderGenPageAuthoringTypes)(o,i)}Fc.generateGenPageRuntimeTypes=vV;function wV(e){if(!Array.isArray(e))throw new Fo.InvalidArgumentError(`${Mo}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!SE.TABLE_LOGICAL_NAME.test(r))throw new Fo.InvalidArgumentError(`${Mo}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new Fo.InvalidArgumentError(`${Mo}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function CV(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Fo.InvalidArgumentError(`${Mo}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new Fo.InvalidArgumentError(`${Mo}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!AE.has(r))throw new Fo.InvalidArgumentError(`${Mo}: detail must be one of ${[...AE].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var PE=v(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.getEnvironmentLanguages=Uo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE=void 0;var EV=Q(),DE=ye();Uo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE="ENVIRONMENT_LANGUAGES_UNREADABLE";var _E="/organizations?$select=languagecode",AV="/RetrieveProvisionedLanguages()",SV="/RetrieveAvailableLanguages()";function IE(e,t){return new EV.SdkError(Uo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE,`The org's languages could not be read: ${e} ${t}. Nothing is assumed in its place \u2014 retry, or check the caller's access to the org.`)}function OE(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}async function TE(e,t,r,n){let i=(0,DE.ensureSuccess)(await e.get(t),e.apiUrl(t)).body,o=i?.[r];if(!Array.isArray(o)||o.length===0||!o.every(OE))throw IE(n,`answered no list of language codes in '${r}'`);return[...new Set(o)]}async function NV(e){var t;let r=(0,DE.ensureSuccess)(await e.get(_E),e.apiUrl(_E)).body,n=r?.value,i=Array.isArray(n)&&n.length===1?(t=n[0])===null||t===void 0?void 0:t.languagecode:void 0;if(!OE(i))throw IE("the organization read","did not answer one row with a language code");let o=await TE(e,AV,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages"),a=await TE(e,SV,"LocaleIds","RetrieveAvailableLanguages");return{baseLanguage:i,available:a,provisioned:o}}Uo.getEnvironmentLanguages=NV});var Al=v(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.projectConnectorOperationSchema=nt.projectConnectorOperations=nt.validateConnectorSwagger=nt.CONNECTOR_SCHEMA_TOO_LARGE_CODE=nt.CONNECTOR_OPERATION_NOT_FOUND_CODE=nt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE=nt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE=void 0;var El=Q();nt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE="CONNECTIVITY_RESPONSE_UNREADABLE";nt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE="CONNECTOR_SWAGGER_UNSUPPORTED";nt.CONNECTOR_OPERATION_NOT_FOUND_CODE="CONNECTOR_OPERATION_NOT_FOUND";nt.CONNECTOR_SCHEMA_TOO_LARGE_CODE="CONNECTOR_SCHEMA_TOO_LARGE";var RE=64,LE=128,kE=2e5,$E=4e6,_V=new Set(["get","put","post","delete","patch","head","options"]),TV=new Set(["query","header","path","formData","body"]);function Qr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Et(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Xe(e){return e.length>80?`'${e.slice(0,80)}\u2026'`:`'${e}'`}function ke(e,t){return new El.SdkError(nt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`The connector's swagger could not be read: ${e} ${t}. Nothing was skipped or assumed in its place.`)}function Zi(e,t){return new El.SdkError(nt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE,`The connector's swagger is outside the supported contract (Swagger 2.0 as the Power Apps API serves it): ${e} ${t}.`)}function DV(e,t){let r=e;for(let n of t.slice(2).split("/")){let i=n.replace(/~1/g,"/").replace(/~0/g,"~");if(typeof r!="object"||r===null||!vn(r,i))return{found:!1};r=r[i]}return{found:!0,value:r}}function Qm(e,t,r){if(!t.startsWith("#/"))throw Zi(r,`has a $ref that is not a local '#/\u2026' pointer (${Xe(t)})`);if(t.includes("%"))throw Zi(r,`has a $ref with a percent-encoded character (${Xe(t)}), which is not decoded`);if(/~(?![01])/.test(t))throw ke(r,`has a $ref with a malformed escape (${Xe(t)}): a '~' not followed by 0 or 1`);let n=DV(e,t);if(!n.found)throw ke(r,`has a $ref that does not resolve (${Xe(t)})`);return n.value}function Mc(e,t){if(vn(e,"$ref")){if(typeof e.$ref!="string")throw ke(t,`has a $ref that is ${Et(e.$ref)}, not a string`);return e.$ref}}function IV(e,t,r){if(!Qr(t))throw ke(r,`is ${Et(t)}, not a parameter object`);let n=t,i=Mc(t,r);if(i!==void 0){let s=Qm(e,i,r);if(!Qr(s))throw ke(r,`has a $ref (${Xe(i)}) that resolves to ${Et(s)}, not a parameter object`);if(Mc(s,`${r} \u2192 ${Xe(i)}`)!==void 0)throw Zi(r,`has a $ref (${Xe(i)}) to a parameter that is itself a $ref`);n=s}if(typeof n.name!="string")throw ke(r,"has no string name");let o=n.in;if(typeof o!="string"||!TV.has(o))throw ke(r,`has an in that is ${typeof o=="string"?Xe(o):Et(o)}, not one of query, header, path, formData or body`);if(vn(n,"required")&&typeof n.required!="boolean")throw ke(r,`has a required that is ${Et(n.required)}, not a boolean`);let a=n["x-ms-visibility"];if(vn(n,"x-ms-visibility")&&typeof a!="string")throw ke(r,`has an x-ms-visibility that is ${Et(a)}, not a string`);return{name:n.name,in:o,required:n.required===!0,internal:a==="internal"}}function Jm(e){return`${e.in}:${e.name}`}function FE(e,t,r){if(!vn(t,"parameters"))return[];let n=t.parameters;if(!Array.isArray(n))throw ke(r,`has parameters that are ${Et(n)}, not an array`);let i=new Set;return n.map((o,a)=>{let s=`${r} parameters[${a}]`,l=IV(e,o,s),u=Jm(l);if(i.has(u))throw ke(s,`repeats the parameter ${Xe(l.name)} in ${Xe(l.in)}, which must be unique in its list`);return i.add(u),l})}function ME(e,t,r){let n=t.responses;if(!vn(n,"200"))return;let i=`${r} response 200`,o=n[200];if(!Qr(o))throw ke(i,`is ${Et(o)}, not a response object`);let a=o,s=Mc(o,i);if(s!==void 0){if(s.startsWith("#/")&&!/^#\/responses\/[^/]+$/.test(s))throw ke(i,`has a $ref (${Xe(s)}) that does not name a response ('#/responses/<name>')`);let l=Qm(e,s,i);if(!Qr(l))throw ke(i,`has a $ref (${Xe(s)}) that resolves to ${Et(l)}, not a response object`);if(Mc(l,`${i} \u2192 ${Xe(s)}`)!==void 0)throw Zi(i,`has a $ref (${Xe(s)}) to a response that is itself a $ref`);a=l}if(vn(a,"content"))throw Zi(i,"is an OpenAPI 3 response (it has content), not a Swagger 2.0 one");if(vn(a,"schema")){if(!Qr(a.schema))throw ke(i,`has a schema that is ${Et(a.schema)}, not an object`);return a.schema}}function xE(e,t,r){if(!vn(e,t))return;let n=e[t];if(typeof n!="string")throw ke(r,`has a ${t} that is ${Et(n)}, not a string`);return n}function OV(e,t,r,n,i){if(!Qr(t))throw ke(r,`is ${Et(t)}, not an operation object`);let o=t.operationId;if(typeof o!="string")throw ke(r,`has no string operationId (${Et(o)})`);if(n.has(o))throw ke(r,`repeats the operationId ${Xe(o)}, which must be unique in the document`);n.add(o);let a=xE(t,"summary",r),s=xE(t,"description",r),l=FE(e,t,r);if(!Qr(t.responses))throw ke(r,`has no responses object (${Et(t.responses)})`);return ME(e,t,r),{id:o,summary:a,description:s,node:t,where:r,parameters:l,pathParameters:i}}function Xm(e){if(!Qr(e))throw ke("the document",`is ${Et(e)}, not an object`);if(vn(e,"openapi"))throw Zi("the document","is OpenAPI 3 (it has an openapi member), not Swagger 2.0");if(!vn(e,"swagger"))throw ke("the document","names no Swagger version");if(e.swagger!=="2.0")throw Zi("the document",`declares swagger ${Xe(String(e.swagger))}, not 2.0`);let t=e.paths;if(!Qr(t))throw ke("the document",`has paths that are ${Et(t)}, not an object`);let r=[],n=new Set;for(let i of Object.keys(t)){let o=t[i],a=`paths[${Xe(i)}]`;if(!Qr(o))throw ke(a,`is ${Et(o)}, not a path item object`);let s=[];for(let l of Object.keys(o))if(_V.has(l.toLowerCase()))r.push(OV(e,o[l],`${a}.${l}`,n,s));else if(l==="parameters")for(let u of FE(e,o,a))s.push(u);else if(!l.startsWith("x-"))throw Zi(a,`has a ${Xe(l)} member; a path item may hold only HTTP methods, parameters and x- extensions`)}return{document:e,operations:r}}function PV(e){Xm(e)}nt.validateConnectorSwagger=PV;var Ym=class{constructor(t,r){this.root=t,this.where=r,this.nodes=0,this.characters=0,this.path=[]}run(t){return this.visit(t,0)}tooLarge(t){return new El.SdkError(nt.CONNECTOR_SCHEMA_TOO_LARGE_CODE,`The response schema of ${this.where} is too large to return: it has ${t}. That is far above any connector measured, so this one is not read.`)}node(){if(this.nodes+=1,this.nodes>kE)throw this.tooLarge(`more than ${kE} nodes`)}text(t){if(this.characters+=t,this.characters>$E)throw this.tooLarge(`more than ${$E} characters of strings and keys`)}checkDepth(t){if(t>LE)throw this.tooLarge(`nesting deeper than ${LE} levels`)}visit(t,r){if(this.checkDepth(r),Array.isArray(t)){this.node();let n=[];for(let i of t)n.push(this.visit(i,r+1));return n}if(Qr(t)){if(typeof t.$ref=="string")return this.reference(t.$ref,r);this.node();let n={};for(let i of Object.keys(t))this.text(i.length),Object.defineProperty(n,i,{value:this.visit(t[i],r+1),enumerable:!0,writable:!0,configurable:!0});return n}return this.node(),typeof t=="string"&&this.text(t.length),t}reference(t,r){if(this.path.includes(t)){this.checkDepth(r+1);let o=t.slice(t.lastIndexOf("/")+1);return this.node(),this.text(4),this.node(),this.text(o.length),{$ref:o}}if(this.path.length>=RE)throw this.tooLarge(`a $ref chain of more than ${RE} references`);let n=Qm(this.root,t,this.where);if(!Qr(n))throw ke(this.where,`has a schema $ref (${Xe(t)}) that resolves to ${Et(n)}, not a schema object`);this.path.push(t);let i=this.visit(n,r);return this.path.pop(),i}};function RV(e){let{operations:t}=Xm(e);return{operations:t.map(r=>{var n,i;return{name:r.id,summary:(i=(n=r.summary)!==null&&n!==void 0?n:r.description)!==null&&i!==void 0?i:null}})}}nt.projectConnectorOperations=RV;function LV(e,t){if(typeof t!="string"||t==="")throw new El.InvalidArgumentError("operationId must be a non-empty string.");let{document:r,operations:n}=Xm(e),i=n.find(u=>u.id===t);if(!i)throw new El.SdkError(nt.CONNECTOR_OPERATION_NOT_FOUND_CODE,`The connector has no operation with the id ${Xe(t)} (ids are matched exactly, case included). List the connector\u2019s operations to see its ids.`);let o=new Set(i.parameters.map(Jm)),a=[...i.parameters,...i.pathParameters.filter(u=>!o.has(Jm(u)))].filter(u=>!u.internal).map(({name:u,required:c})=>({name:u,required:c})),s=ME(r,i.node,i.where),l=s===void 0?{}:new Ym(r,`${i.where} (${Xe(i.id)})`).run(s);return{operation:i.id,parameters:a,response:l}}nt.projectConnectorOperationSchema=LV});var Bo=v(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.readEnvironmentName=J.readConnection=J.connectorShortName=J.CONNECTOR_PREFIX=J.connectivityUnauthorized=J.errorCodeOf=J.messageOf=J.environmentFilter=J.unreadable=J.connectivityCloudOf=J.sameOrigin=J.parseUrl=J.bounded=J.kindOf=J.isObject=J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE=J.CONNECTOR_NOT_TABULAR_CODE=J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=J.CONNECTIVITY_UNAUTHORIZED_CODE=J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=J.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var Sl=Q(),kV=ye(),$V=Al();J.CONNECTIVITY_NOT_CONFIGURED_CODE="CONNECTIVITY_NOT_CONFIGURED";J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE="CONNECTIVITY_CLOUD_UNSUPPORTED";J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE="CONNECTIVITY_ENVIRONMENT_UNVERIFIED";J.CONNECTIVITY_UNAUTHORIZED_CODE="CONNECTIVITY_UNAUTHORIZED";J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE="CONNECTIVITY_ROUTE_DECOMMISSIONED";J.CONNECTOR_NOT_TABULAR_CODE="CONNECTOR_NOT_TABULAR";J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE="CONNECTOR_RUNTIME_UNSUPPORTED";function yr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}J.isObject=yr;function Ba(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}J.kindOf=Ba;function qa(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}J.bounded=qa;function BE(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}J.parseUrl=BE;function xV(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}J.sameOrigin=xV;var FV=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,MV=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/;function UV(e){let t=BE(e),r=t?t.host.toLowerCase():"";if(MV.test(r))return"Test";let n=FV.exec(r);return n&&n[1]!=="9"?"Public":"Unsupported"}J.connectivityCloudOf=UV;function Vn(e,t){return new Sl.SdkError($V.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}J.unreadable=Vn;function BV(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}J.environmentFilter=BV;function qV(e){if(typeof e=="string"&&e.length>0)return qa(e,500);if(yr(e)){let t=yr(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return qa(r,500)}return"request failed"}J.messageOf=qV;function qE(e){return yr(e)&&yr(e.error)?e.error.code:void 0}J.errorCodeOf=qE;function VV(e){if(yr(e)&&yr(e.error)&&yr(e.error.innererror))return e.error.innererror.code}function GV(e,t,r){let n=[],i=qE(t);typeof i=="string"&&i.length>0&&n.push(qa(i,80));let o=VV(t);typeof o=="string"&&o.length>0&&n.push(qa(o,80));let a=n.length>0?` (${n.join("; ")})`:"";return(0,Sl.attachCause)(new Sl.SdkError(J.CONNECTIVITY_UNAUTHORIZED_CODE,`A connectivity request was refused with HTTP ${e}${a}: the token's audience, scopes, expiry, or access was rejected. Supply a valid token for this route, or fall back to pac.`),r)}J.connectivityUnauthorized=GV;J.CONNECTOR_PREFIX="/providers/Microsoft.PowerApps/apis/";var WV=/^[A-Za-z0-9_.-]{1,128}$/,zV=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]);function jV(e){if(typeof e=="string"){let r=e.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()===J.CONNECTOR_PREFIX.toLowerCase()?e.slice(J.CONNECTOR_PREFIX.length):e;if(WV.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Sl.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${J.CONNECTOR_PREFIX}shared_office365users'); got ${typeof e=="string"?`'${qa(e,80)}'`:Ba(e)}.`)}J.connectorShortName=jV;function HV(e,t,r){let n=`Connection row ${t}`;if(!yr(e))throw Vn(n,`it is ${Ba(e)}, not an object`);let i=e.properties;if(!yr(i))throw Vn(n,`its properties are ${Ba(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()!==J.CONNECTOR_PREFIX.toLowerCase())throw Vn(n,`its apiId is not '${J.CONNECTOR_PREFIX}<connector>'`);let a=o.slice(J.CONNECTOR_PREFIX.length);if(a===""||a.includes("/"))throw Vn(n,"its apiId names no single connector");if(zV.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Vn(n,"it has no name");let l=i.environment,u=yr(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Vn(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Vn(n,`its displayName is ${Ba(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Vn(n,`its statuses are ${Ba(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=yr(f)?f.status:void 0;if(typeof m!="string")throw Vn(n,"one of its statuses has no string status");return m})}}J.readConnection=HV;var UE="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'";async function KV(e){let t=(0,kV.ensureSuccess)(await e.get(UE),e.apiUrl(UE)).body,r=yr(t)?t.Detail:void 0,n=yr(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw new Sl.SdkError(J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,"The environment of this org could not be verified: the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId).");return n}J.readEnvironmentName=KV});var KE=v(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});br.ConnectivityApi=br.CONNECTIVITY_UNAUTHORIZED_CODE=br.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=br.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=br.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=br.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var Wt=Q(),JV=ye(),Bc=Al(),_l=Bo(),Tl=Bo();Object.defineProperty(br,"CONNECTIVITY_NOT_CONFIGURED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_NOT_CONFIGURED_CODE}});Object.defineProperty(br,"CONNECTIVITY_CLOUD_UNSUPPORTED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE}});Object.defineProperty(br,"CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE}});Object.defineProperty(br,"CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE}});Object.defineProperty(br,"CONNECTIVITY_UNAUTHORIZED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_UNAUTHORIZED_CODE}});var VE="2016-11-01",YV="2021-04-01",QV="https://api.bap.microsoft.com",XV="https://test.api.bap.microsoft.com",ZV=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,e4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,GE="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'",bi="/providers/Microsoft.PowerApps/apis/",t4=/^[A-Za-z0-9_.-]{1,128}$/,r4=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]),n4="ServiceDecommissioned";function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function eo(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Gn(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Nl(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}function WE(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}function i4(e){return/^[a-z0-9][a-z0-9.-]*$/.test(e)&&(e==="api.powerapps.com"||e.endsWith(".api.powerapps.com"))}function Xr(e,t){return new Wt.SdkError(Bc.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}function Uc(e){return new Wt.SdkError(_l.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: ${e}. The Power Apps service was not asked about it.`)}function zE(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}function jE(e){if(typeof e=="string"&&e.length>0)return Gn(e,500);if(ct(e)){let t=ct(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Gn(r,500)}return"request failed"}function o4(e){return ct(e)&&ct(e.error)?e.error.code:void 0}function HE(e){if(typeof e=="string"){let r=e.slice(0,bi.length).toLowerCase()===bi.toLowerCase()?e.slice(bi.length):e;if(t4.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Wt.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${bi}shared_office365users'); got ${typeof e=="string"?`'${Gn(e,80)}'`:eo(e)}.`)}function a4(e,t,r){let n=`Connection row ${t}`;if(!ct(e))throw Xr(n,`it is ${eo(e)}, not an object`);let i=e.properties;if(!ct(i))throw Xr(n,`its properties are ${eo(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,bi.length).toLowerCase()!==bi.toLowerCase())throw Xr(n,`its apiId is not '${bi}<connector>'`);let a=o.slice(bi.length);if(a===""||a.includes("/"))throw Xr(n,"its apiId names no single connector");if(r4.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Xr(n,"it has no name");let l=i.environment,u=ct(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Xr(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Xr(n,`its displayName is ${eo(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Xr(n,`its statuses are ${eo(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=ct(f)?f.status:void 0;if(typeof m!="string")throw Xr(n,"one of its statuses has no string status");return m})}}var Zm=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.service=n,this.swaggers=new Map}async listConnections(){let t=this.requireService(),r=await this.resolveEnvironment(t),n=[],i=new Set,o=`${r.origin}/providers/Microsoft.PowerApps/connections?api-version=${VE}&$filter=${zE(r.id)}`,a=await this.send(t,o,!0),s=1,l=0;for(;;){let u=`Page ${s} of the connections`,c=a.body,d=c?.value;if(!Array.isArray(d))throw Xr(u,`its value is ${eo(d)}, not an array`);for(let m of d){let p=a4(m,l,r.id);l+=1,p&&n.push(p)}let f=c?.nextLink;if(f==null)return n;if(typeof f!="string"||f.length===0)throw Xr(u,`its nextLink is ${f===""?"an empty string":eo(f)}, not a non-empty string`);if(i.has(f))throw new Wt.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${Gn(f)}'), which would loop indefinitely.`);i.add(f),this.assertSameOrigin(f,r.parsed),a=await this.send(t,f,!0),s+=1}}async listConnectorOperations(t){let r=this.requireService(),n=HE(t);return(0,Bc.projectConnectorOperations)(await this.swagger(r,n))}async getConnectorOperationSchema(t,r){let n=this.requireService(),i=HE(t);if(typeof r!="string"||r==="")throw new Wt.InvalidArgumentError("operationId must be a non-empty string.");return(0,Bc.projectConnectorOperationSchema)(await this.swagger(n,i),r)}requireService(){if(!this.service)throw new Wt.SdkError(_l.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a powerAppsServiceClient (MakerSdkOptions), so it cannot read connections or connectors: it needs an HttpClient that authenticates for https://service.powerapps.com/ and does not follow redirects. Nothing was requested.");return this.service}resolveEnvironment(t){if(!this.environment){let r=this.verifyEnvironment(t);this.environment=r,r.catch(()=>{this.environment===r&&(this.environment=void 0)})}return this.environment}async verifyEnvironment(t){let r=this.candidateBapOrigin(),n=await this.readEnvironmentId(),i=`${r}/providers/Microsoft.BusinessAppPlatform/environments/${encodeURIComponent(n)}?api-version=${YV}`,o=(await this.send(t,i,!1)).body,a=ct(o)?o.properties:void 0,s=ct(o)?o.name:void 0;if(typeof s!="string"||s.toLowerCase()!==n.toLowerCase())throw Uc(`BAP's environment row is not the one named '${Gn(n,80)}' (its name)`);let l=ct(a)&&ct(a.linkedEnvironmentMetadata)?a.linkedEnvironmentMetadata.instanceUrl:void 0,u=typeof l=="string"?Nl(l):void 0,c=Nl(this.instanceUrl);if(!u||!c||!WE(u,c))throw Uc("BAP's row is not linked to this org (its linkedEnvironmentMetadata.instanceUrl is another origin)");let d=ct(a)?a.runtimeEndpoints:void 0,f=ct(d)?d["microsoft.PowerApps"]:void 0,m=typeof f=="string"?Nl(f):void 0;if(!m||m.protocol!=="https:"||!i4(m.host.toLowerCase()))throw Uc("BAP's Power Apps runtime endpoint is not an https host of api.powerapps.com (runtimeEndpoints['microsoft.PowerApps'])");return{id:n,origin:m.origin.toLowerCase(),parsed:m}}candidateBapOrigin(){let t=Nl(this.instanceUrl),r=t?t.host.toLowerCase():"",n=ZV.exec(r);if(n&&n[1]!=="9")return QV;if(e4.test(r))return XV;throw new Wt.SdkError(_l.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The org's host is not one of the clouds this reads in (${t?`'${Gn(t.host,80)}'`:`'${Gn(this.instanceUrl,80)}', which is not a URL`}): a Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are not supported. Nothing was requested.`)}async readEnvironmentId(){let t=(0,JV.ensureSuccess)(await this.org.get(GE),this.org.apiUrl(GE)).body,r=ct(t)?t.Detail:void 0,n=ct(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw Uc("the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId)");return n}swagger(t,r){let n=r.toLowerCase(),i=this.swaggers.get(n);if(!i){let o=this.readSwagger(t,r);i=o,this.swaggers.set(n,o),o.catch(()=>{this.swaggers.get(n)===o&&this.swaggers.delete(n)})}return i}async readSwagger(t,r){let n=await this.resolveEnvironment(t),i=encodeURIComponent(r),o=`${n.origin}${bi}${i}?api-version=${VE}&$filter=${zE(n.id)}`,a=(await this.send(t,o,!0)).body,s=ct(a)?a.properties:void 0,l=ct(s)?s.swagger:void 0;if(!ct(l))throw Xr(`The connector '${Gn(r,80)}'`,`its properties.swagger is ${eo(l)}, not an object`);return(0,Bc.validateConnectorSwagger)(l),l}assertSameOrigin(t,r){let n=Nl(t);if(!n)throw new Wt.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${Gn(t)}'`);if(!WE(n,r))throw new Wt.InvalidArgumentError(`Refusing to follow a cross-origin link ('${Gn(n.origin,120)}' is not the environment's Power Apps endpoint '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n){let i;try{i=await t.get(r)}catch(o){throw o instanceof Wt.ConnectionError&&typeof o.statusCode=="number"&&o.statusCode>0?this.mapNon2xx(r,o.statusCode,void 0,n,o):o instanceof Wt.SdkError?o:new Wt.ConnectionError(r,0,o instanceof Error?o.message:String(o),o)}if(!i||typeof i.status!="number")throw new Wt.ConnectionError(r,0,"the transport returned no HTTP response");if(i.status>=200&&i.status<300)return i;throw this.mapNon2xx(r,i.status,i.body,n)}mapNon2xx(t,r,n,i,o){let a=o??new Wt.ConnectionError(t,r,jE(n),n);return i&&r===410&&o4(n)===n4?(0,Wt.attachCause)(new Wt.SdkError(_l.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE,`The Power Apps API this reads through is decommissioned for this environment: ${jE(n)} Fall back to pac, or to the Power Platform API when the host has a client for it; the SDK does not fall back.`),a):r===401||r===403?(0,_l.connectivityUnauthorized)(r,n,a):a}};br.ConnectivityApi=Zm});var ih=v(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.projectConnectorTableSchema=Me.projectConnectorTables=Me.tableSchemaSuffix=Me.tablesSuffix=Me.encodeTable=Me.encodeDataset=Me.checkTabularConnection=Me.runtimeAuthority=Me.tabularRevision=Me.checkTableSchemaArguments=Me.checkListTablesArguments=void 0;var qo=Q(),M=Bo(),s4=/^[A-Za-z0-9_.-]{1,128}$/,Vo=/^\.{1,2}$/,l4="shared_sharepointonline",u4=/^[0-9]{1,9}$/,c4=/^[A-Za-z0-9._~-]+$/,d4=/^\/apim\/([A-Za-z0-9._-]+)\/?$/,f4=/^\/connectors\/runtime\/invoke\/scalegroups\/([A-Za-z0-9._-]+)\/(scaleunits|shards)\/([A-Za-z0-9._-]+)\/apis\/([A-Za-z0-9._-]+)\/connections\/?$/,p4=/^[A-Za-z0-9._~!'()*-]$/,m4=/^[0-9A-Fa-f]{2}$/;function vi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Dl(e){return typeof e=="string"?`'${(0,M.bounded)(e,80)}'`:(0,M.kindOf)(e)}function eh(e,t){return new qo.SdkError(M.CONNECTOR_NOT_TABULAR_CODE,`The connector '${(0,M.bounded)(e,80)}' has no tables: ${t}.`)}function qc(e,t){return new qo.SdkError(M.CONNECTOR_RUNTIME_UNSUPPORTED_CODE,`The connector '${(0,M.bounded)(e,80)}' runs where this SDK does not send a token: ${t}. Nothing was sent to it.`)}function h4(e){if(typeof e=="string"&&s4.test(e)&&!Vo.test(e))return e;throw new qo.InvalidArgumentError(`connectionId must be a connection's name (letters, digits, '_', '.', '-'; at most 128; not '.' or '..'); got ${Dl(e)}.`)}function g4(e){if(e!=null){if(typeof e=="string"&&e!==""&&e.split(",").find(r=>r===""||Vo.test(r))===void 0)return e;throw new qo.InvalidArgumentError(`dataset must be a non-empty string (a SharePoint site URL, a SQL 'server,database', \u2026) none of whose ','-separated parts is empty, '.' or '..', or absent for a connector without datasets; got ${Dl(e)}.`)}}function y4(e){if(typeof e=="string"&&e!==""&&!Vo.test(e))return e;throw new qo.InvalidArgumentError(`table must be a non-empty string other than '.' and '..'; got ${Dl(e)}.`)}function YE(e,t,r){return{short:(0,M.connectorShortName)(e),connectionId:h4(t),dataset:g4(r)}}Me.checkListTablesArguments=YE;function b4(e,t,r,n){return{...YE(e,t,r),table:y4(n)}}Me.checkTableSchemaArguments=b4;function v4(e,t){let r=`The connector '${(0,M.bounded)(t,80)}'`,n=e.properties;if(!(0,M.isObject)(n))throw(0,M.unreadable)(r,`its properties are ${(0,M.kindOf)(n)}, not an object`);if(!vi(n,"interfaces"))throw eh(t,"it declares no interfaces");let i=n.interfaces;if(!(0,M.isObject)(i))throw(0,M.unreadable)(r,`its properties.interfaces are ${(0,M.kindOf)(i)}, not an object`);if(!vi(i,"CDPTabular1"))throw eh(t,"it declares no CDPTabular1 interface");let o=i.CDPTabular1;if(!(0,M.isObject)(o))throw(0,M.unreadable)(r,`its CDPTabular1 interface is ${(0,M.kindOf)(o)}, not an object`);let a=o.revisions;if(!(0,M.isObject)(a))throw(0,M.unreadable)(r,`its CDPTabular1 revisions are ${(0,M.kindOf)(a)}, not an object`);let s,l=new Map;for(let u of Object.keys(a)){let c=a[u],d=`its CDPTabular1 revision '${(0,M.bounded)(u,40)}'`;if(!(0,M.isObject)(c)||typeof c.status!="string")throw(0,M.unreadable)(r,`${d} is not an object with a string status`);if(c.status!=="Production")continue;if(!u4.test(u))throw(0,M.unreadable)(r,`${d} is a Production revision whose key is not a decimal integer of 1\u20139 digits`);let f=w4(c.baseUrl);if(f===void 0)throw(0,M.unreadable)(r,`${d} has a baseUrl that is not '/' or '/'-separated [A-Za-z0-9._~-] segments`);let m=Number(u),p=l.get(m);if(p!==void 0)throw(0,M.unreadable)(r,`its Production revisions '${p}' and '${(0,M.bounded)(u,40)}' have the same number`);l.set(m,u),(!s||m>s.revisionNumber)&&(s={revisionNumber:m,revision:f})}if(!s)throw eh(t,"its CDPTabular1 interface has no Production revision");return s.revision}Me.tabularRevision=v4;function w4(e){if(typeof e!="string")return;let t=e.replace(/^\/+/,"").replace(/\/+$/,"");return t===""?"":t.split("/").every(i=>c4.test(i)&&!Vo.test(i))?t:void 0}function C4(e,t,r){let n=(0,M.isObject)(e.properties)?e.properties:void 0,i=n?n.primaryRuntimeUrl:void 0;if(typeof i!="string")throw qc(r,`its primaryRuntimeUrl is ${(0,M.kindOf)(i)}, not a string`);let o=t.cloud==="Test",a=(o?`https://${t.name}.tip2-001.tip2.azure-apihub.net`:t.origin).toLowerCase(),s=(0,M.parseUrl)(i);if(!s||s.protocol!=="https:"||s.origin.toLowerCase()!==a)throw qc(r,`its runtime ('${(0,M.bounded)(i,120)}') is not ${o?"this environment's measured API Hub host (<environment name>.tip2-001.tip2.azure-apihub.net)":"under this environment's own Power Platform API origin"} over https`);let l=i.slice(0,a.length).toLowerCase()===a?i.slice(a.length):void 0;if(o){let c=l===void 0?null:d4.exec(l);if(!c||Vo.test(c[1]))throw qc(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <host>/apim/<connector>`);return{transport:"invoke",origin:a,path:`/apim/${c[1]}`}}let u=l===void 0?null:f4.exec(l);if(!u||[u[1],u[3],u[4]].some(c=>Vo.test(c)))throw qc(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <origin>/connectors/runtime/invoke/scalegroups/<group>/(scaleunits|shards)/<unit>/apis/<api>/connections`);return{transport:"direct",origin:a,path:`/connectors/runtime/invoke/scalegroups/${u[1]}/${u[2]}/${u[3]}/apis/${u[4]}/connections`}}Me.runtimeAuthority=C4;function E4(e,t,r,n){let i=`The connection '${(0,M.bounded)(t,128)}'`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(i,`it is ${(0,M.kindOf)(e)}, not an object`);if(e.name!==t)throw(0,M.unreadable)(i,`its name is ${Dl(e.name)}, not the requested connection`);let o=e.properties;if(!(0,M.isObject)(o))throw(0,M.unreadable)(i,`its properties are ${(0,M.kindOf)(o)}, not an object`);let a=o.apiId;if(typeof a!="string"||a.toLowerCase()!==`${M.CONNECTOR_PREFIX}${r}`.toLowerCase())throw(0,M.unreadable)(i,`its apiId is ${Dl(a)}, not the connector '${(0,M.bounded)(r,80)}'`);let s=o.environment,l=(0,M.isObject)(s)?s.name:void 0;if(typeof l!="string"||l.toLowerCase()!==n.toLowerCase())throw(0,M.unreadable)(i,"it is not a connection of this environment (properties.environment.name)");return t}Me.checkTabularConnection=E4;function JE(e){return encodeURIComponent(e).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}function A4(e){if(e==="")return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="%"){if(!m4.test(e.slice(t+1,t+3)))return!1;t+=2}else if(!p4.test(e[t]))return!1;return!0}function QE(e,t){let r,n,i;try{r=JE(e),n=JE(r),i=decodeURIComponent(n)}catch{throw new qo.InvalidArgumentError(`${t} is not well-formed Unicode (it has a lone surrogate), so it cannot be sent.`)}if(!A4(n)||Vo.test(n)||i!==r)throw new qo.InvalidArgumentError(`${t} cannot be sent as one path segment.`);return n}function nh(e){return e.split(",").map((t,r)=>QE(t,`dataset part ${r}`)).join(",")}Me.encodeDataset=nh;function XE(e){return QE(e,"table")}Me.encodeTable=XE;function S4(e,t){if(t===void 0)return"/tables";let r=e.toLowerCase()===l4?"allTables":"tables";return`/datasets/${nh(t)}/${r}`}Me.tablesSuffix=S4;function N4(e,t){return`/$metadata.json${e===void 0?"":`/datasets/${nh(e)}`}/tables/${XE(t)}`}Me.tableSchemaSuffix=N4;function Va(e,t){let r=t.toLowerCase();for(let n of Object.keys(e))if(n.toLowerCase()===r)return{found:!0,value:e[n]};return{found:!1}}function _4(e){let t="The table list",r;if(Array.isArray(e))r=e;else if((0,M.isObject)(e)){for(let o of["nextLink","@odata.nextLink"])if(Va(e,o).found)throw(0,M.unreadable)(t,`it carries a ${o} \u2014 a paged answer is refused, never read as a partial list`);let n=Va(e,"value"),i=n.found?n:Va(e,"tables");if(!i.found)throw(0,M.unreadable)(t,"it is an object with neither a value nor a tables member");if(!Array.isArray(i.value))throw(0,M.unreadable)(t,`its ${n.found?"value":"tables"} is ${(0,M.kindOf)(i.value)}, not an array`);r=i.value}else throw(0,M.unreadable)(t,`it is ${(0,M.kindOf)(e)}, not an array or an object`);return{tables:r.map((n,i)=>T4(n,i))}}Me.projectConnectorTables=_4;function T4(e,t){let r=`Table row ${t}`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=Va(e,"name");if(!n.found||typeof n.value!="string"||n.value==="")throw(0,M.unreadable)(r,"it has no non-empty string name");let i=Va(e,"displayName");if(i.found&&typeof i.value!="string")throw(0,M.unreadable)(r,`its displayName is ${(0,M.kindOf)(i.value)}, not a string`);let o=Va(e,"id");if(o.found&&(typeof o.value!="string"||o.value===""))throw(0,M.unreadable)(r,`its id is ${o.value===""?"an empty string":(0,M.kindOf)(o.value)}, not a non-empty string`);return{name:n.value,displayName:i.found?i.value:null,id:o.found?o.value:n.value}}function th(e,t,r){if(!vi(e,t))return;let n=e[t];if(!(0,M.isObject)(n))throw(0,M.unreadable)("The table schema",`its ${r} is ${(0,M.kindOf)(n)}, not an object`);return n}function rh(e,t,r){if(!vi(e,t))return;let n=e[t];if(typeof n!="string")throw(0,M.unreadable)(r,`its ${t} is ${(0,M.kindOf)(n)}, not a string`);return n}function D4(e,t){var r,n;if(vi(e,"$ref"))throw(0,M.unreadable)(t,"it is a $ref, whose type is not guessed");let i=rh(e,"type",t),o=rh(e,"format",t),a=(r=i??o)!==null&&r!==void 0?r:"object";if(!vi(e,"items"))return a;let s=e.items;if(!(0,M.isObject)(s))throw(0,M.unreadable)(t,`its items are ${(0,M.kindOf)(s)}, not an object`);if(vi(s,"$ref"))throw(0,M.unreadable)(t,"its items are a $ref, whose type is not guessed");return`${a}<${(n=rh(s,"type",`${t} items`))!==null&&n!==void 0?n:"object"}>`}function I4(e,t){let r="The table schema";if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=th(e,"items","items"),i=th(e,"schema","schema"),o=i?th(i,"items","schema.items"):void 0,a=[[e,"the answer"],[n,"items"],[i,"schema"],[o,"schema.items"]],s=new Set;for(let[c,d]of a)if(c&&vi(c,"required")){let f=c.required;if(!Array.isArray(f))throw(0,M.unreadable)(r,`the required of ${d} is ${(0,M.kindOf)(f)}, not an array`);f.forEach(m=>{if(typeof m!="string")throw(0,M.unreadable)(r,`the required of ${d} has an entry that is ${(0,M.kindOf)(m)}, not a string`);s.add(m.toLowerCase())})}let l;for(let[c,d]of a)if(c&&vi(c,"properties")){if(!(0,M.isObject)(c.properties))throw(0,M.unreadable)(r,`the properties of ${d} are ${(0,M.kindOf)(c.properties)}, not an object`);l=c.properties;break}if(!l)throw(0,M.unreadable)(r,"it has no properties, items.properties, schema.properties or schema.items.properties");let u=Object.keys(l).map(c=>{let d=`Column '${(0,M.bounded)(c,80)}'`,f=l[c];if(!(0,M.isObject)(f))throw(0,M.unreadable)(d,`it is ${(0,M.kindOf)(f)}, not an object`);return{name:c,type:D4(f,d),required:s.has(c.toLowerCase())}});return{table:t,columns:u}}Me.projectConnectorTableSchema=I4});var ZE=v(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.PowerPlatformApiDiscovery=void 0;var oh=class{constructor(t){this.clusterCategory=t}getTokenAudience(){return`https://${this._getEnvironmentApiHostNameSuffix()}`}getTokenEndpointHost(){return this._getEnvironmentApiHostNameSuffix()}getTenantEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant")}getTenantIslandClusterEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant","il-")}getEnvironmentEndpoint(t){return this._generatePowerPlatformApiDomain(t,"environment")}_generatePowerPlatformApiDomain(t,r,n=""){if(!/^[a-zA-Z0-9\-]+$/g.test(t))throw new Error(`Cannot generate Power Platform API endpoint because the ${r} identifier contains invalid host name characters, only alphanumeric and dash characters are expected: ${t}`);let i=this._getHexApiSuffixLength(),o=t.toLowerCase().replace(/-/g,"");if(i>=o.length)throw new Error(`Cannot generate Power Platform API endpoint because the normalized ${r} identifier must be at least ${i+1} characters in length: ${o}`);let a=o.substring(o.length-i),s=o.substring(0,o.length-i),l=this._getEnvironmentApiHostNameSuffix();return`${n}${s}.${a}.${r}.${l}`}_getHexApiSuffixLength(){switch(this.clusterCategory){case"firstrelease":case"prod":return 2;default:return 1}}_getEnvironmentApiHostNameSuffix(){switch(this.clusterCategory){case"local":return"api.powerplatform.localhost";case"dev":return"api.dev.powerplatform.com";case"test":return"api.test.powerplatform.com";case"preprod":return"api.preprod.powerplatform.com";case"firstrelease":case"prod":return"api.powerplatform.com";case"gov":return"api.gov.powerplatform.microsoft.us";case"high":return"api.high.powerplatform.microsoft.us";case"dod":return"api.appsplatform.us";case"mooncake":return"api.powerplatform.partner.microsoftonline.cn";case"ex":return"api.powerplatform.eaglex.ic.gov";case"rx":return"api.powerplatform.microsoft.scloud";default:throw new Error(`Invalid ClusterCategory value: ${this.clusterCategory}`)}}};Vc.PowerPlatformApiDiscovery=oh});var eA=v(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.PowerPlatformApiDiscovery=void 0;var O4=ZE();Object.defineProperty(Gc,"PowerPlatformApiDiscovery",{enumerable:!0,get:function(){return O4.PowerPlatformApiDiscovery}})});var iA=v(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.platformTokenAudience=to.platformEnvironment=to.platformClusterOf=void 0;var tA=eA(),rA=Q(),nA=Bo(),P4=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,R4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,L4=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,k4=/^default-/i;function ah(e,t=80){return e.length>t?`${e.slice(0,t)}\u2026`:e}function $4(e){try{return new URL(e).host.toLowerCase()}catch{return}}function x4(e){let t=$4(e);if(t){if(R4.test(t))return{cloud:"Test",category:"test"};let r=P4.exec(t);if(r&&r[1]!=="9")return{cloud:"Public",category:"prod"}}throw new rA.SdkError(nA.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The Power Platform API route is built for the Test and Public clouds; this org (${t?`'${ah(t)}'`:`'${ah(e)}', which is not a URL`}) is another cloud. A Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are pending or out of scope. Nothing was requested.`)}to.platformClusterOf=x4;function F4(e,t){let r=k4.test(e)?e.slice(8):e;if(!L4.test(r))throw new rA.SdkError(nA.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: its name ('${ah(e)}') is neither a GUID nor 'Default-<GUID>', the forms this route is measured for. The Power Platform API was not asked about it.`);return{origin:`https://${new tA.PowerPlatformApiDiscovery(t).getEnvironmentEndpoint(e)}`,guid:r.toLowerCase()}}to.platformEnvironment=F4;function M4(e){return new tA.PowerPlatformApiDiscovery(e).getTokenAudience()}to.platformTokenAudience=M4});var aA=v(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.PlatformConnectivityApi=Ga.assertTabularCloud=void 0;var wn=Q(),sh=Al(),fe=Bo(),oA=iA(),wi=ih(),lh="1";function uh(e){let t=(0,fe.connectivityCloudOf)(e);if(t!=="Test"&&t!=="Public")throw new wn.SdkError(fe.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"Connector tables are read in the Test and Public clouds; this org's cloud is neither (GCC, GCC High and DoD are pending). Nothing was requested.")}Ga.assertTabularCloud=uh;var ch=class{constructor(t,r,n,i){this.org=t,this.instanceUrl=r,this.client=n,this.runtime=i,this.records=new Map,this.swaggers=new Map}async listConnections(){let t=await this.resolveEnvironment(),r=[],n=new Set,i=await this.send(this.client,"GET",`${t.origin}/connectivity/connections?api-version=${lh}`,[401,403]),o=1,a=0;for(;;){let s=`Page ${o} of the connections`,l=i.body,u=l?.value;if(!Array.isArray(u))throw(0,fe.unreadable)(s,`its value is ${(0,fe.kindOf)(u)}, not an array`);for(let d of u){let f=(0,fe.readConnection)(d,a,t.name);a+=1,f&&r.push(f)}let c=l?.nextLink;if(c==null)return r;if(typeof c!="string"||c.length===0)throw(0,fe.unreadable)(s,`its nextLink is ${c===""?"an empty string":(0,fe.kindOf)(c)}, not a non-empty string`);if(n.has(c))throw new wn.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${(0,fe.bounded)(c)}'), which would loop indefinitely.`);n.add(c),this.assertSameOrigin(c,t.parsed),i=await this.send(this.client,"GET",c,[401,403]),o+=1}}async listConnectorOperations(t){let r=(0,fe.connectorShortName)(t);return(0,sh.projectConnectorOperations)(await this.swagger(r))}async getConnectorOperationSchema(t,r){let n=(0,fe.connectorShortName)(t);if(typeof r!="string"||r==="")throw new wn.InvalidArgumentError("operationId must be a non-empty string.");return(0,sh.projectConnectorOperationSchema)(await this.swagger(n),r)}async listConnectorTables(t,r,n){uh(this.instanceUrl);let i=(0,wi.checkListTablesArguments)(t,r,n),o=(0,wi.tablesSuffix)(i.short,i.dataset);return(0,wi.projectConnectorTables)(await this.invokeTabular(i,o))}async getConnectorTableSchema(t,r,n,i){uh(this.instanceUrl);let o=(0,wi.checkTableSchemaArguments)(t,r,n,i),a=(0,wi.tableSchemaSuffix)(o.dataset,o.table);return(0,wi.projectConnectorTableSchema)(await this.invokeTabular(o,a),o.table)}async invokeTabular(t,r){let n=this.requireRuntime(),i=await this.resolveEnvironment(),o=await this.record(t.short),a=(0,wi.tabularRevision)(o,t.short),s=(0,wi.runtimeAuthority)(o,{cloud:i.cloud,name:i.name,origin:i.origin},t.short),l=`${i.origin}/connectivity/connectors/${encodeURIComponent(t.short)}/connections/${encodeURIComponent(t.connectionId)}?$filter=${(0,fe.environmentFilter)(i.name)}&api-version=${lh}`,u=(await this.send(this.client,"GET",l,[401,403])).body,c=(0,wi.checkTabularConnection)(u,t.connectionId,t.short,i.name),d=`${s.path}/${c}${a===""?"":`/${a}`}${r}`;return(s.transport==="invoke"?await this.send(n,"POST",`${s.origin}/invoke`,[401],{"X-Ms-Request-Url":d,"X-Ms-Request-Method":"GET"}):await this.send(n,"GET",`${s.origin}${d}`,[401])).body}requireRuntime(){if(!this.runtime)throw new wn.SdkError(fe.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a connectorRuntimeClient (MakerSdkOptions), so it cannot read connector tables: it needs an HttpClient that authenticates for API Hub (https://apihub.azure.com) and does not follow redirects. Nothing was requested.");return this.runtime}resolveEnvironment(){if(!this.environment){let t=this.readEnvironment();this.environment=t,t.catch(()=>{this.environment===t&&(this.environment=void 0)})}return this.environment}async readEnvironment(){let{cloud:t,category:r}=(0,oA.platformClusterOf)(this.instanceUrl),n=await(0,fe.readEnvironmentName)(this.org),{origin:i,guid:o}=(0,oA.platformEnvironment)(n,r),a=(0,fe.parseUrl)(i);if(!a)throw(0,fe.unreadable)("The Power Platform API origin",`'${(0,fe.bounded)(i)}' is not a URL`);return{cloud:t,origin:i,parsed:a,name:n,guid:o}}cached(t,r,n){let i=t.get(r);if(!i){let o=n();i=o,t.set(r,o),o.catch(()=>{t.get(r)===o&&t.delete(r)})}return i}record(t){return this.cached(this.records,t.toLowerCase(),()=>this.readRecord(t))}async readRecord(t){let r=await this.resolveEnvironment(),n=`${r.origin}/connectivity/connectors/${encodeURIComponent(t)}?$filter=${(0,fe.environmentFilter)(r.name)}&api-version=${lh}`,i=(await this.send(this.client,"GET",n,[401,403])).body,o=(0,fe.isObject)(i)?i.name:void 0;if(!(0,fe.isObject)(i)||typeof o!="string"||o.toLowerCase()!==t.toLowerCase())throw(0,fe.unreadable)(`The connector '${(0,fe.bounded)(t,80)}'`,`the record's name is ${typeof o=="string"?`'${(0,fe.bounded)(o,80)}'`:(0,fe.kindOf)(o)}, not the requested connector`);return i}swagger(t){return this.cached(this.swaggers,t.toLowerCase(),async()=>{let n=(await this.record(t)).properties,i=(0,fe.isObject)(n)?n.swagger:void 0;if(!(0,fe.isObject)(i))throw(0,fe.unreadable)(`The connector '${(0,fe.bounded)(t,80)}'`,`its properties.swagger is ${(0,fe.kindOf)(i)}, not an object`);return(0,sh.validateConnectorSwagger)(i),i})}assertSameOrigin(t,r){let n=(0,fe.parseUrl)(t);if(!n)throw new wn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${(0,fe.bounded)(t)}'`);if(!(0,fe.sameOrigin)(n,r))throw new wn.InvalidArgumentError(`Refusing to follow a cross-origin link ('${(0,fe.bounded)(n.origin,120)}' is not the environment's Power Platform API origin '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n,i,o){let a;try{a=r==="GET"?await t.get(n):await t.post(n,void 0,{headers:o})}catch(s){throw s instanceof wn.ConnectionError&&typeof s.statusCode=="number"&&s.statusCode>0?this.non2xx(n,s.statusCode,void 0,i,s):s instanceof wn.SdkError?s:new wn.ConnectionError(n,0,s instanceof Error?s.message:String(s),s)}if(!a||typeof a.status!="number")throw new wn.ConnectionError(n,0,"the transport returned no HTTP response");if(a.status>=200&&a.status<300)return a;throw this.non2xx(n,a.status,a.body,i)}non2xx(t,r,n,i,o){let a=o??new wn.ConnectionError(t,r,(0,fe.messageOf)(n),n);return i.includes(r)?(0,fe.connectivityUnauthorized)(r,n,a):a}};Ga.PlatformConnectivityApi=ch});var lA=v(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.ConnectivityRouter=void 0;var dh=Q(),U4=KE(),Wc=Bo(),sA=ih(),fh=aA(),ph=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.clients=n}async listConnections(){return this.route().listConnections()}async listConnectorOperations(t){return this.route().listConnectorOperations(t)}async getConnectorOperationSchema(t,r){return this.route().getConnectorOperationSchema(t,r)}async listConnectorTables(t,r,n){return(0,fh.assertTabularCloud)(this.instanceUrl),(0,sA.checkListTablesArguments)(t,r,n),this.tabularRoute().listConnectorTables(t,r,n)}async getConnectorTableSchema(t,r,n,i){return(0,fh.assertTabularCloud)(this.instanceUrl),(0,sA.checkTableSchemaArguments)(t,r,n,i),this.tabularRoute().getConnectorTableSchema(t,r,n,i)}route(){return this.delegate||(this.delegate=this.select()),this.delegate}platformRoute(t){return this.platform||(this.platform=new fh.PlatformConnectivityApi(this.org,this.instanceUrl,t,this.clients.connectorRuntimeClient)),this.platform}tabularRoute(){let{powerPlatformApiClient:t,connectorRuntimeClient:r}=this.clients,n=[t?void 0:"powerPlatformApiClient (the Power Platform API)",r?void 0:"connectorRuntimeClient (API Hub, https://apihub.azure.com)"].filter(i=>i!==void 0);if(n.length>0||!t)throw new dh.SdkError(Wc.CONNECTIVITY_NOT_CONFIGURED_CODE,`Connector tables are read through the Power Platform API and the connector runtime: this SDK was created without MakerSdkOptions.${n.join(" or MakerSdkOptions.")}, an HttpClient that does not follow redirects. Nothing was requested.`);return this.platformRoute(t)}select(){let t=(0,Wc.connectivityCloudOf)(this.instanceUrl),{powerAppsServiceClient:r,powerPlatformApiClient:n}=this.clients;if(t==="Unsupported")throw new dh.SdkError(Wc.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"This org's cloud has no connection/connector route: the Test and Public clouds are served (through the Power Platform API, or the classic route for Public); GCC, GCC High and DoD are pending. Nothing was requested.");if(n)return this.platformRoute(n);if(t==="Public"&&r)return new U4.ConnectivityApi(this.org,this.instanceUrl,r);throw new dh.SdkError(Wc.CONNECTIVITY_NOT_CONFIGURED_CODE,t==="Test"?"This org is in the Test cloud, whose connection and connector reads go through the Power Platform API: supply MakerSdkOptions.powerPlatformApiClient (an HttpClient that authenticates for the Power Platform API and does not follow redirects). Nothing was requested.":"This org is in the Public cloud: supply MakerSdkOptions.powerPlatformApiClient (the Power Platform API route) or powerAppsServiceClient (the classic route). Neither was given, so nothing was requested.")}};zc.ConnectivityRouter=ph});var Wa=v(Ci=>{"use strict";function B4(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 hh(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function q4(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 uA=hh({HTML:"text/html",isHTML:function(e){return e===uA.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),cA=hh({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===cA.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),jc=/[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]/,mh=new RegExp("[\\-\\.0-9"+jc.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),V4=new RegExp("^"+jc.source+mh.source+"*(?::"+jc.source+mh.source+"*)?$");Ci.assign=q4;Ci.find=B4;Ci.freeze=hh;Ci.MIME_TYPE=uA;Ci.NAMESPACE=cA;Ci.nameStartChar=jc;Ci.nameChar=mh;Ci.tagNamePattern=V4});var Th=v(Ni=>{var gh=Wa(),Wn=gh.find,Ol=gh.NAMESPACE,za=gh.tagNamePattern;function G4(e){return e!==""}function W4(e){return e?e.split(/[\t\n\f\r ]+/).filter(G4):[]}function z4(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function dA(e){if(!e)return[];var t=W4(e);return Object.keys(t.reduce(z4,{}))}function j4(e){return function(t){return e&&e.indexOf(t)!==-1}}function Rl(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function wr(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,Rl(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Cr={},Zr=Cr.ELEMENT_NODE=1,ja=Cr.ATTRIBUTE_NODE=2,Il=Cr.TEXT_NODE=3,vA=Cr.CDATA_SECTION_NODE=4,wA=Cr.ENTITY_REFERENCE_NODE=5,H4=Cr.ENTITY_NODE=6,yh=Cr.PROCESSING_INSTRUCTION_NODE=7,bh=Cr.COMMENT_NODE=8,CA=Cr.DOCUMENT_NODE=9,EA=Cr.DOCUMENT_TYPE_NODE=10,Ei=Cr.DOCUMENT_FRAGMENT_NODE=11,K4=Cr.NOTATION_NODE=12,zt={},St={},Ise=zt.INDEX_SIZE_ERR=(St[1]="Index size error",1),Ose=zt.DOMSTRING_SIZE_ERR=(St[2]="DOMString size error",2),vr=zt.HIERARCHY_REQUEST_ERR=(St[3]="Hierarchy request error",3),Pse=zt.WRONG_DOCUMENT_ERR=(St[4]="Wrong document",4),fA=zt.INVALID_CHARACTER_ERR=(St[5]="Invalid character",5),Rse=zt.NO_DATA_ALLOWED_ERR=(St[6]="No data allowed",6),Lse=zt.NO_MODIFICATION_ALLOWED_ERR=(St[7]="No modification allowed",7),AA=zt.NOT_FOUND_ERR=(St[8]="Not found",8),kse=zt.NOT_SUPPORTED_ERR=(St[9]="Not supported",9),pA=zt.INUSE_ATTRIBUTE_ERR=(St[10]="Attribute in use",10),Cn=zt.INVALID_STATE_ERR=(St[11]="Invalid state",11),$se=zt.SYNTAX_ERR=(St[12]="Syntax error",12),xse=zt.INVALID_MODIFICATION_ERR=(St[13]="Invalid modification",13),Fse=zt.NAMESPACE_ERR=(St[14]="Invalid namespace",14),Mse=zt.INVALID_ACCESS_ERR=(St[15]="Invalid access",15);function pe(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,St[e]),this.message=St[e],Error.captureStackTrace&&Error.captureStackTrace(this,pe);return r.code=e,t&&(this.message=this.message+": "+t),r}pe.prototype=Error.prototype;Rl(zt,pe);function Ai(){}Ai.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=[],o=0;o<this.length;o++)_h(this[o],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 Ha(e,t){this._node=e,this._refresh=t,vh(this)}function vh(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(xA(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];Rl(r,e),e._inc=t}}Ha.prototype.item=function(e){return vh(this),this[e]||null};wr(Ha,Ai);function Kc(){this._nameIndex=Object.create(null)}function SA(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function J4(e,t){e._nameIndex[t.nodeName]=t}function NA(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function mA(e,t,r,n){if(n?(t[SA(t,n)]=r,NA(t,n)):t[t.length++]=r,J4(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&DA(i,e,n),Y4(i,e,r))}}function hA(e,t,r){var n=SA(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,NA(t,r),e){var o=e.ownerDocument;o&&(DA(o,e,r),r.ownerElement=null)}}else throw new pe(AA,new Error(e.tagName+"@"+r))}Kc.prototype={length:0,item:Ai.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 pe(pA);var r=this._nameIndex[e.nodeName];return mA(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new pe(pA);return r=this.getNamedItemNS(e.namespaceURI,e.localName),mA(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return hA(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return hA(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 _A(){}_A.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new Ll;if(n.implementation=this,n.childNodes=new Ai,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 Zc;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function De(){}De.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(e,t){return Yc(this,e,t)},replaceChild:function(e,t){Yc(this,e,t,OA),t&&this.removeChild(t)},removeChild:function(e){return IA(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return $A(this.ownerDocument||this,this,e)},normalize:function(){At(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===Il&&t.nodeType===Il){for(var n=[],i=r;i!==null&&i.nodeType===Il;)n.push(i.data),i=i.nextSibling;for(var o=t.nextSibling;o!==i;){var a=o.nextSibling;o.parentNode=null,o.previousSibling=null,o.nextSibling=null,o=a}t.nextSibling=i,i!==null?i.previousSibling=t:e.lastChild=t,t.appendData(n.join("")),Xc(e.ownerDocument,e),t=i}else t=r}return!0}})},isSupported:function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(e){for(var t=this;t;){var r=t._nsMap;if(r){for(var n in r)if(Object.prototype.hasOwnProperty.call(r,n)&&r[n]===e)return n}t=t.nodeType==ja?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==ja?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function TA(e){return e=="<"&&"&lt;"||e==">"&&"&gt;"||e=="&"&&"&amp;"||e=='"'&&"&quot;"||"&#"+e.charCodeAt()+";"}Rl(Cr,De);Rl(Cr,De.prototype);function Jc(e,t){return At(e,null,{enter:function(r){return t(r)?At.STOP:!0}})===At.STOP}function At(e,t,r){for(var n=[{node:e,context:t,phase:At.ENTER}];n.length>0;){var i=n.pop();if(i.phase===At.ENTER){var o=r.enter(i.node,i.context);if(o===At.STOP)return At.STOP;if(n.push({node:i.node,context:o,phase:At.EXIT}),o==null)continue;for(var a=i.node.lastChild;a;)n.push({node:a,context:o,phase:At.ENTER}),a=a.previousSibling}else r.exit&&r.exit(i.node,i.context)}}At.STOP=Symbol("walkDOM.STOP");At.ENTER=0;At.EXIT=1;function Ll(){this.ownerDocument=this}function Y4(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Ol.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function DA(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Ol.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Xc(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,o=0;i;)n[o++]=i,i=i.nextSibling;n.length=o,delete n[n.length]}}}function IA(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,Xc(e.ownerDocument,e),t}function Q4(e){return e&&(e.nodeType===De.DOCUMENT_NODE||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.ELEMENT_NODE)}function X4(e){return e&&(zn(e)||wh(e)||Si(e)||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.COMMENT_NODE||e.nodeType===De.PROCESSING_INSTRUCTION_NODE)}function Si(e){return e&&e.nodeType===De.DOCUMENT_TYPE_NODE}function zn(e){return e&&e.nodeType===De.ELEMENT_NODE}function wh(e){return e&&e.nodeType===De.TEXT_NODE}function gA(e,t){var r=e.childNodes||[];if(Wn(r,zn)||Si(t))return!1;var n=Wn(r,Si);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function yA(e,t){var r=e.childNodes||[];function n(o){return zn(o)&&o!==t}if(Wn(r,n))return!1;var i=Wn(r,Si);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function Z4(e,t,r){if(!Q4(e))throw new pe(vr,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new pe(AA,"child not in parent");if(!X4(t)||Si(t)&&e.nodeType!==De.DOCUMENT_NODE)throw new pe(vr,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function eG(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(zn);if(o.length>1||Wn(i,wh))throw new pe(vr,"More than one element or text in fragment");if(o.length===1&&!gA(e,r))throw new pe(vr,"Element in fragment can not be inserted before doctype")}if(zn(t)&&!gA(e,r))throw new pe(vr,"Only one element can be added and only after doctype");if(Si(t)){if(Wn(n,Si))throw new pe(vr,"Only one doctype is allowed");var a=Wn(n,zn);if(r&&n.indexOf(a)<n.indexOf(r))throw new pe(vr,"Doctype can only be inserted before an element");if(!r&&a)throw new pe(vr,"Doctype can not be appended since element is present")}}function OA(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(zn);if(o.length>1||Wn(i,wh))throw new pe(vr,"More than one element or text in fragment");if(o.length===1&&!yA(e,r))throw new pe(vr,"Element in fragment can not be inserted before doctype")}if(zn(t)&&!yA(e,r))throw new pe(vr,"Only one element can be added and only after doctype");if(Si(t)){let l=function(u){return Si(u)&&u!==r};var s=l;if(Wn(n,l))throw new pe(vr,"Only one doctype is allowed");var a=Wn(n,zn);if(r&&n.indexOf(a)<n.indexOf(r))throw new pe(vr,"Doctype can only be inserted before an element")}}function Yc(e,t,r,n){Z4(e,t,r),e.nodeType===De.DOCUMENT_NODE&&(n||eG)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===Ei){var o=t.firstChild;if(o==null)return t;var a=t.lastChild}else o=a=t;var s=r?r.previousSibling:e.lastChild;o.previousSibling=s,a.nextSibling=r,s?s.nextSibling=o:e.firstChild=o,r==null?e.lastChild=a:r.previousSibling=a;do{o.parentNode=e;var l=e.ownerDocument||e;Pl(o,l)}while(o!==a&&(o=o.nextSibling));return Xc(e.ownerDocument||e,e),t.nodeType==Ei&&(t.firstChild=t.lastChild=null),t}function Pl(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===Zr&&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;)Pl(i,t),i=i.nextSibling}}function tG(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,Xc(e.ownerDocument,e,t);var r=e.ownerDocument||e;return Pl(t,r),t}Ll.prototype={nodeName:"#document",nodeType:CA,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==Ei){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return Yc(this,e,t),Pl(e,this),this.documentElement===null&&e.nodeType===Zr&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),IA(this,e)},replaceChild:function(e,t){Yc(this,e,t,OA),Pl(e,this),t&&this.removeChild(t),zn(e)&&(this.documentElement=e)},importNode:function(e,t){return rG(this,e,t)},getElementById:function(e){var t=null;return Jc(this.documentElement,function(r){if(r.nodeType==Zr&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=dA(e);return new Ha(this,function(r){var n=[];return t.length>0&&Jc(r.documentElement,function(i){if(i!==r&&i.nodeType===Zr){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=dA(o);a=t.every(j4(s))}a&&n.push(i)}}}),n})},createElement:function(e){var t=new Go;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new Ai;var r=t.attributes=new Kc;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new ed;return e.ownerDocument=this,e.childNodes=new Ai,e},createTextNode:function(e){var t=new Ch;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new Eh;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new pe(fA,'data contains "]]>"');var t=new Ah;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new Nh;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new Qc;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!za.test(e))throw new pe(fA,'not a valid xml name "'+e+'"');var t=new Sh;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new Go,n=t.split(":"),i=r.attributes=new Kc;return r.childNodes=new Ai,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 Qc,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}};wr(Ll,De);function Go(){this._nsMap={}}Go.prototype={nodeType:Zr,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===Ei?this.insertBefore(e,null):tG(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 Ha(this,function(t){var r=[];return Jc(t,function(n){n!==t&&n.nodeType==Zr&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new Ha(this,function(r){var n=[];return Jc(r,function(i){i!==r&&i.nodeType===Zr&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};Ll.prototype.getElementsByTagName=Go.prototype.getElementsByTagName;Ll.prototype.getElementsByTagNameNS=Go.prototype.getElementsByTagNameNS;wr(Go,De);function Qc(){}Qc.prototype.nodeType=ja;wr(Qc,De);function kl(){}kl.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(St[vr])},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}};wr(kl,De);function Ch(){}Ch.prototype={nodeName:"#text",nodeType:Il,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}};wr(Ch,kl);function Eh(){}Eh.prototype={nodeName:"#comment",nodeType:bh};wr(Eh,kl);function Ah(){}Ah.prototype={nodeName:"#cdata-section",nodeType:vA};wr(Ah,kl);function Zc(){}Zc.prototype.nodeType=EA;wr(Zc,De);function PA(){}PA.prototype.nodeType=K4;wr(PA,De);function RA(){}RA.prototype.nodeType=H4;wr(RA,De);function Sh(){}Sh.prototype.nodeType=wA;wr(Sh,De);function ed(){}ed.prototype.nodeName="#document-fragment";ed.prototype.nodeType=Ei;wr(ed,De);function Nh(){}Nh.prototype.nodeType=yh;wr(Nh,De);function LA(){}LA.prototype.serializeToString=function(e,t,r,n){return kA.call(e,t,r,n)};De.prototype.toString=kA;function kA(e,t,r){var n=!!r&&!!r.requireWellFormed,i=[],o=this.nodeType==9&&this.documentElement||this,a=o.prefix,s=o.namespaceURI;if(s&&a==null){var a=o.lookupPrefix(s);if(a==null)var l=[{namespace:s,prefix:null}]}return _h(this,i,e,t,l,n),i.join("")}function bA(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===Ol.XML||i===Ol.XMLNS)return!1;for(var o=r.length;o--;){var a=r[o];if(a.prefix===n)return a.namespace!==i}return!0}function Hc(e,t,r,n){if(n&&!za.test(t))throw new pe(Cn,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,TA),'"')}function _h(e,t,r,n,i,o){i||(i=[]),At(e,{ns:i,isHTML:r},{enter:function(a,s){var l=s.ns,u=s.isHTML;if(n)if(a=n(a),a){if(typeof a=="string")return t.push(a),null}else return null;switch(a.nodeType){case Zr:var c=a.attributes,d=c.length,f=a.tagName;u=Ol.isHTML(a.namespaceURI)||u;var m=f;if(!u&&!a.prefix&&a.namespaceURI){for(var p,h=0;h<c.length;h++)if(c.item(h).name==="xmlns"){p=c.item(h).value;break}if(!p)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.prefix===""&&b.namespace===a.namespaceURI){p=b.namespace;break}}if(p!==a.namespaceURI)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.namespace===a.namespaceURI){b.prefix&&(m=b.prefix+":"+f);break}}}if(o&&!za.test(m))throw new pe(Cn,'The element name "'+m+'" is not a valid XML QName');t.push("<",m);for(var w=l.slice(),E=0;E<d;E++){var S=c.item(E);S.prefix=="xmlns"?w.push({prefix:S.localName,namespace:S.value}):S.nodeName=="xmlns"&&w.push({prefix:"",namespace:S.value})}for(var E=0;E<d;E++){var S=c.item(E);if(bA(S,u,w)){var P=S.prefix||"",L=S.namespaceURI;Hc(t,P?"xmlns:"+P:"xmlns",L,o),w.push({prefix:P,namespace:L})}var I=n?n(S):S;I&&(typeof I=="string"?t.push(I):Hc(t,I.name,I.value,o))}if(f===m&&bA(a,u,w)){var D=a.prefix||"",L=a.namespaceURI;Hc(t,D?"xmlns:"+D:"xmlns",L,o),w.push({prefix:D,namespace:L})}var O=a.firstChild;if(O||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(f)){if(t.push(">"),u&&/^script$/i.test(f)){for(;O;)O.data?t.push(O.data):_h(O,t,u,n,w.slice(),o),O=O.nextSibling;return t.push("</",f,">"),null}return{ns:w,isHTML:u,tag:m}}else return t.push("/>"),null;case CA:case Ei:return{ns:l.slice(),isHTML:u,tag:null};case ja:return Hc(t,a.name,a.value,o),null;case Il:return t.push(a.data.replace(/[<&>]/g,TA)),null;case vA:if(o&&a.data.indexOf("]]>")!==-1)throw new pe(Cn,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case bh:if(o&&a.data.indexOf("-->")!==-1)throw new pe(Cn,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case EA:if(o){if(!za.test(a.name))throw new pe(Cn,'The doctype name "'+a.name+'" is not a valid XML Name');if(a.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(a.publicId))throw new pe(Cn,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new pe(Cn,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new pe(Cn,'DocumentType internalSubset contains "]>"')}var x=a.publicId,K=a.systemId;if(t.push("<!DOCTYPE ",a.name),x)t.push(" PUBLIC ",x),K&&K!="."&&t.push(" ",K),t.push(">");else if(K&&K!=".")t.push(" SYSTEM ",K,">");else{var Re=a.internalSubset;Re&&t.push(" [",Re,"]"),t.push(">")}return null;case yh:if(o){if(!za.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new pe(Cn,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new pe(Cn,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case wA:if(o&&!za.test(a.nodeName))throw new pe(Cn,'The entity reference name "'+a.nodeName+'" is not a valid XML Name');return t.push("&",a.nodeName,";"),null;default:return t.push("??",a.nodeName),null}},exit:function(a,s){s&&s.tag&&t.push("</",s.tag,">")}})}function rG(e,t,r){var n;return At(t,null,{enter:function(i,o){var a=i.cloneNode(!1);a.ownerDocument=e,a.parentNode=null,o===null?n=a:o.appendChild(a);var s=i.nodeType===ja||r;return s?a:null}}),n}function $A(e,t,r){var n;return At(t,null,{enter:function(i,o){var a=new i.constructor;for(var s in i)if(Object.prototype.hasOwnProperty.call(i,s)){var l=i[s];typeof l!="object"&&l!=a[s]&&(a[s]=l)}i.childNodes&&(a.childNodes=new Ai),a.ownerDocument=e;var u=r;switch(a.nodeType){case Zr:var c=i.attributes,d=a.attributes=new Kc,f=c.length;d._ownerElement=a;for(var m=0;m<f;m++)a.setAttributeNode($A(e,c.item(m),!0));break;case ja:u=!0}return o!==null?o.appendChild(a):n=a,u?a:null}}),n}function xA(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(Ha.prototype,"length",{get:function(){return vh(this),this.$$length}}),Object.defineProperty(De.prototype,"textContent",{get:function(){if(this.nodeType===Zr||this.nodeType===Ei){var e=[];return At(this,null,{enter:function(t){if(t.nodeType===Zr||t.nodeType===Ei)return!0;if(t.nodeType===yh||t.nodeType===bh)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case Zr:case Ei: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}}}),xA=function(e,t,r){e["$$"+t]=r})}catch{}Ni.DocumentType=Zc;Ni.DOMException=pe;Ni.DOMImplementation=_A;Ni.Element=Go;Ni.Node=De;Ni.NodeList=Ai;Ni.walkDOM=At;Ni.XMLSerializer=LA});var MA=v($l=>{"use strict";var FA=Wa().freeze;$l.XML_ENTITIES=FA({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});$l.HTML_ENTITIES=FA({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"});$l.entityMap=$l.HTML_ENTITIES});var GA=v(Ih=>{var Ml=Wa().NAMESPACE,Dh=Wa().tagNamePattern,Ka=0,ro=1,Ja=2,xl=3,Ya=4,Qa=5,Fl=6,td=7;function Xa(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,Xa)}Xa.prototype=new Error;Xa.prototype.name=Xa.name;function qA(){}qA.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),sG(t,t={}),nG(e,t,r,n,this.errorHandler),n.endDocument()}};function nG(e,t,r,n,i){function o(de){if(de>65535){de-=65536;var He=55296+(de>>10),bn=56320+(de&1023);return String.fromCharCode(He,bn)}else return String.fromCharCode(de)}function a(de){var He=de.slice(1,-1);return Object.hasOwnProperty.call(r,He)?r[He]:He.charAt(0)==="#"?o(parseInt(He.substr(1).replace("x","0x"))):(i.error("entity not found:"+de),de)}function s(de){if(de>h){var He=e.substring(h,de).replace(/&#?\w+;/g,a);f&&l(h),n.characters(He,0,de-h),h=de}}function l(de,He){for(;de>=c&&(He=d.exec(e));)u=He.index,c=u+He[0].length,f.lineNumber++;f.columnNumber=de-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,f=n.locator,m=[{currentNSMap:t}],p={},h=0;;){try{var g=e.indexOf("<",h);if(g<0){if(!e.substr(h).match(/^\s*$/)){var b=n.doc,w=b.createTextNode(e.substr(h));b.appendChild(w),n.currentElement=w}return}switch(g>h&&s(g),e.charAt(g+1)){case"/":var K=e.indexOf(">",g+3),E=e.substring(g+2,K).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),S=m.pop();K<0?(E=e.substring(g+2).replace(/[\s<].*/,""),i.error("end tag name: "+E+" is not complete:"+S.tagName),K=g+1+E.length):E.match(/\s</)?(E=E.replace(/[\s<].*/,""),i.error("end tag name: "+E+" maybe not complete"),K=g+1+E.length):/[ \t\n\r]/.test(E)&&Dh.test(E.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+E+'"');var P=S.localNSMap,L=S.tagName==E,I=L||S.tagName&&S.tagName.toLowerCase()==E.toLowerCase();if(I){if(n.endElement(S.uri,S.localName,E),P)for(var D in P)Object.prototype.hasOwnProperty.call(P,D)&&n.endPrefixMapping(D);L||i.fatalError("end tag name: "+E+" is not match the current start tagName:"+S.tagName)}else m.push(S);K++;break;case"?":f&&l(g),K=uG(e,g,n);break;case"!":f&&l(g),K=lG(e,g,n,i);break;default:f&&l(g);var O=new VA,x=m[m.length-1].currentNSMap,K=iG(e,g,O,x,a,i),Re=O.length;if(!O.closed&&aG(e,K,O.tagName,p)&&(O.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),f&&Re){for(var qt=UA(f,{}),ge=0;ge<Re;ge++){var je=O[ge];l(je.offset),je.locator=UA(f,{})}n.locator=qt,BA(O,n,x)&&m.push(O),n.locator=f}else BA(O,n,x)&&m.push(O);Ml.isHTML(O.uri)&&!O.closed?K=oG(e,K,O.tagName,a,n):K++}}catch(de){if(de instanceof Xa)throw de;i.error("element parse error: "+de),K=-1}K>h?h=K:s(Math.max(g,h)+1)}}function UA(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function iG(e,t,r,n,i,o){function a(m,p,h){r.attributeNames.hasOwnProperty(m)&&o.fatalError("Attribute "+m+" redefined"),r.addValue(m,p.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),h)}for(var s,l,u=++t,c=Ka;;){var d=e.charAt(u);if(c===Ka&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===ro)s=e.slice(t,u),c=xl;else if(c===Ja)c=xl;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===xl||c===ro)if(c===ro&&(o.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),a(s,l,t-1),c=Qa;else throw new Error("attribute value no end '"+d+"' match");else if(c==Ya)l=e.slice(t,u),a(s,l,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=Qa;else throw new Error('attribute value must after "="');break;case"/":switch(c){case Ka:r.setTagName(e.slice(t,u));case Qa:case Fl:case td:c=td,r.closed=!0;case Ya:case ro:break;case Ja:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==Ka&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case Ka:r.setTagName(e.slice(t,u));case Qa:case Fl:case td:break;case Ya:case ro:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case Ja:c===Ja&&(l=s),c==Ya?(o.warning('attribute "'+l+'" missed quot(")!'),a(s,l,t)):((!Ml.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),a(l,l,t));break;case xl:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case Ka:r.setTagName(e.slice(t,u)),c=Fl;break;case ro:s=e.slice(t,u),c=Ja;break;case Ya:var l=e.slice(t,u);o.warning('attribute "'+l+'" missed quot(")!!'),a(s,l,t);case Qa:c=Fl;break}else switch(c){case Ja:var f=r.tagName;(!Ml.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=u,c=ro;break;case Qa:o.warning('attribute space is required"'+s+'"!!');case Fl:c=ro,t=u;break;case xl:c=Ya,t=u;break;case td:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function BA(e,t,r){for(var n=e.tagName,i=null,d=e.length;d--;){var o=e[d],a=o.qName,s=o.value,f=a.indexOf(":");if(f>0)var l=o.prefix=a.slice(0,f),u=a.slice(f+1),c=l==="xmlns"&&u;else u=a,l=null,c=a==="xmlns"&&"";o.localName=u,c!==!1&&(i==null&&(i={},r=Object.create(r)),r[c]=i[c]=s,o.uri=Ml.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var l=o.prefix;l&&(l==="xml"&&(o.uri=Ml.XML),l!=="xmlns"&&(o.uri=r[l||""]))}var f=n.indexOf(":");f>0?(l=e.prefix=n.slice(0,f),u=e.localName=n.slice(f+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 oG(e,t,r,n,i){if(/^(?:script|textarea)$/i.test(r)){var o=e.indexOf("</"+r+">",t),a=e.substring(t+1,o);if(/[&<]/.test(a))return/^script$/i.test(r)?(i.characters(a,0,a.length),o):(a=a.replace(/&#?\w+;/g,n),i.characters(a,0,a.length),o)}return t+1}function aG(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 sG(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function lG(e,t,r,n){var i=e.charAt(t+2);switch(i){case"-":if(e.charAt(t+3)==="-"){var o=e.indexOf("-->",t+4);return o>t?(r.comment(e,t+4,o-t-4),o+3):(n.error("Unclosed comment"),-1)}else return-1;default:if(e.substr(t+3,6)=="CDATA["){var o=e.indexOf("]]>",t+9);return r.startCDATA(),r.characters(e,t+9,o-t-9),r.endCDATA(),o+3}var a=cG(e,t),s=a.length;if(s>1&&/!doctype/i.test(a[0][0])){var l=a[1][0],u=!1,c=!1;s>3&&(/^public$/i.test(a[2][0])?(u=a[3][0],c=s>4&&a[4][0]):/^system$/i.test(a[2][0])&&(c=a[3][0]));var d=a[s-1];return r.startDTD(l,u,c),r.endDTD(),d.index+d[0].length}}return-1}function uG(e,t,r){var n=e.indexOf("?>",t);if(n){var i=e.substring(t,n).match(/^<\?(\S*)\s*([\s\S]*?)$/);if(i){var o=i[0].length;return r.processingInstruction(i[1],i[2]),n+2}else return-1}return-1}function VA(){this.attributeNames={}}VA.prototype={setTagName:function(e){if(!Dh.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!Dh.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 cG(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}Ih.XMLReader=qA;Ih.ParseError=Xa});var YA=v(nd=>{var dG=Wa(),fG=Th(),WA=MA(),HA=GA(),pG=fG.DOMImplementation,zA=dG.NAMESPACE,mG=HA.ParseError,hG=HA.XMLReader;function KA(e){return e.replace(/\r[\n\u0085]/g,`
+`}});var $E=v(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.generateGenPageRuntimeTypes=void 0;var LE=rh(),Uo=Q(),kE=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),Bo="generateGenPageRuntimeTypes";async function IV(e,t,r){let n=OV(t),i=PV(r),o=[];for(let a of n){let s=await e(a);if(s.columnDetailComplete!==!0)throw new Uo.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${Bo}: the column metadata of data source '${a}' could not be read completely (a choice or lookup read failed, or returned options with no label), so its RuntimeTypes would lack enums a page can use. Retry.`);o.push(s)}return(0,LE.renderGenPageAuthoringTypes)(o,i)}Wc.generateGenPageRuntimeTypes=IV;function OV(e){if(!Array.isArray(e))throw new Uo.InvalidArgumentError(`${Bo}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!LE.TABLE_LOGICAL_NAME.test(r))throw new Uo.InvalidArgumentError(`${Bo}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new Uo.InvalidArgumentError(`${Bo}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function PV(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Uo.InvalidArgumentError(`${Bo}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new Uo.InvalidArgumentError(`${Bo}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!kE.has(r))throw new Uo.InvalidArgumentError(`${Bo}: detail must be one of ${[...kE].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var qE=v(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.getEnvironmentLanguages=qo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE=void 0;var RV=Q(),ME=ye();qo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE="ENVIRONMENT_LANGUAGES_UNREADABLE";var xE="/organizations?$select=languagecode",kV="/RetrieveProvisionedLanguages()",LV="/RetrieveAvailableLanguages()";function UE(e,t){return new RV.SdkError(qo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE,`The org's languages could not be read: ${e} ${t}. Nothing is assumed in its place \u2014 retry, or check the caller's access to the org.`)}function BE(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}async function FE(e,t,r,n){let i=(0,ME.ensureSuccess)(await e.get(t),e.apiUrl(t)).body,o=i?.[r];if(!Array.isArray(o)||o.length===0||!o.every(BE))throw UE(n,`answered no list of language codes in '${r}'`);return[...new Set(o)]}async function $V(e){var t;let r=(0,ME.ensureSuccess)(await e.get(xE),e.apiUrl(xE)).body,n=r?.value,i=Array.isArray(n)&&n.length===1?(t=n[0])===null||t===void 0?void 0:t.languagecode:void 0;if(!BE(i))throw UE("the organization read","did not answer one row with a language code");let o=await FE(e,kV,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages"),a=await FE(e,LV,"LocaleIds","RetrieveAvailableLanguages");return{baseLanguage:i,available:a,provisioned:o}}qo.getEnvironmentLanguages=$V});var Tl=v(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.projectConnectorOperationSchema=it.projectConnectorOperations=it.validateConnectorSwagger=it.CONNECTOR_SCHEMA_TOO_LARGE_CODE=it.CONNECTOR_OPERATION_NOT_FOUND_CODE=it.CONNECTOR_SWAGGER_UNSUPPORTED_CODE=it.CONNECTIVITY_RESPONSE_UNREADABLE_CODE=void 0;var _l=Q();it.CONNECTIVITY_RESPONSE_UNREADABLE_CODE="CONNECTIVITY_RESPONSE_UNREADABLE";it.CONNECTOR_SWAGGER_UNSUPPORTED_CODE="CONNECTOR_SWAGGER_UNSUPPORTED";it.CONNECTOR_OPERATION_NOT_FOUND_CODE="CONNECTOR_OPERATION_NOT_FOUND";it.CONNECTOR_SCHEMA_TOO_LARGE_CODE="CONNECTOR_SCHEMA_TOO_LARGE";var VE=64,GE=128,WE=2e5,zE=4e6,xV=new Set(["get","put","post","delete","patch","head","options"]),FV=new Set(["query","header","path","formData","body"]);function Zr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function At(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Ze(e){return e.length>80?`'${e.slice(0,80)}\u2026'`:`'${e}'`}function Le(e,t){return new _l.SdkError(it.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`The connector's swagger could not be read: ${e} ${t}. Nothing was skipped or assumed in its place.`)}function eo(e,t){return new _l.SdkError(it.CONNECTOR_SWAGGER_UNSUPPORTED_CODE,`The connector's swagger is outside the supported contract (Swagger 2.0 as the Power Apps API serves it): ${e} ${t}.`)}function MV(e,t){let r=e;for(let n of t.slice(2).split("/")){let i=n.replace(/~1/g,"/").replace(/~0/g,"~");if(typeof r!="object"||r===null||!wn(r,i))return{found:!1};r=r[i]}return{found:!0,value:r}}function oh(e,t,r){if(!t.startsWith("#/"))throw eo(r,`has a $ref that is not a local '#/\u2026' pointer (${Ze(t)})`);if(t.includes("%"))throw eo(r,`has a $ref with a percent-encoded character (${Ze(t)}), which is not decoded`);if(/~(?![01])/.test(t))throw Le(r,`has a $ref with a malformed escape (${Ze(t)}): a '~' not followed by 0 or 1`);let n=MV(e,t);if(!n.found)throw Le(r,`has a $ref that does not resolve (${Ze(t)})`);return n.value}function zc(e,t){if(wn(e,"$ref")){if(typeof e.$ref!="string")throw Le(t,`has a $ref that is ${At(e.$ref)}, not a string`);return e.$ref}}function UV(e,t,r){if(!Zr(t))throw Le(r,`is ${At(t)}, not a parameter object`);let n=t,i=zc(t,r);if(i!==void 0){let s=oh(e,i,r);if(!Zr(s))throw Le(r,`has a $ref (${Ze(i)}) that resolves to ${At(s)}, not a parameter object`);if(zc(s,`${r} \u2192 ${Ze(i)}`)!==void 0)throw eo(r,`has a $ref (${Ze(i)}) to a parameter that is itself a $ref`);n=s}if(typeof n.name!="string")throw Le(r,"has no string name");let o=n.in;if(typeof o!="string"||!FV.has(o))throw Le(r,`has an in that is ${typeof o=="string"?Ze(o):At(o)}, not one of query, header, path, formData or body`);if(wn(n,"required")&&typeof n.required!="boolean")throw Le(r,`has a required that is ${At(n.required)}, not a boolean`);let a=n["x-ms-visibility"];if(wn(n,"x-ms-visibility")&&typeof a!="string")throw Le(r,`has an x-ms-visibility that is ${At(a)}, not a string`);return{name:n.name,in:o,required:n.required===!0,internal:a==="internal"}}function nh(e){return`${e.in}:${e.name}`}function HE(e,t,r){if(!wn(t,"parameters"))return[];let n=t.parameters;if(!Array.isArray(n))throw Le(r,`has parameters that are ${At(n)}, not an array`);let i=new Set;return n.map((o,a)=>{let s=`${r} parameters[${a}]`,l=UV(e,o,s),u=nh(l);if(i.has(u))throw Le(s,`repeats the parameter ${Ze(l.name)} in ${Ze(l.in)}, which must be unique in its list`);return i.add(u),l})}function KE(e,t,r){let n=t.responses;if(!wn(n,"200"))return;let i=`${r} response 200`,o=n[200];if(!Zr(o))throw Le(i,`is ${At(o)}, not a response object`);let a=o,s=zc(o,i);if(s!==void 0){if(s.startsWith("#/")&&!/^#\/responses\/[^/]+$/.test(s))throw Le(i,`has a $ref (${Ze(s)}) that does not name a response ('#/responses/<name>')`);let l=oh(e,s,i);if(!Zr(l))throw Le(i,`has a $ref (${Ze(s)}) that resolves to ${At(l)}, not a response object`);if(zc(l,`${i} \u2192 ${Ze(s)}`)!==void 0)throw eo(i,`has a $ref (${Ze(s)}) to a response that is itself a $ref`);a=l}if(wn(a,"content"))throw eo(i,"is an OpenAPI 3 response (it has content), not a Swagger 2.0 one");if(wn(a,"schema")){if(!Zr(a.schema))throw Le(i,`has a schema that is ${At(a.schema)}, not an object`);return a.schema}}function jE(e,t,r){if(!wn(e,t))return;let n=e[t];if(typeof n!="string")throw Le(r,`has a ${t} that is ${At(n)}, not a string`);return n}function BV(e,t,r,n,i){if(!Zr(t))throw Le(r,`is ${At(t)}, not an operation object`);let o=t.operationId;if(typeof o!="string")throw Le(r,`has no string operationId (${At(o)})`);if(n.has(o))throw Le(r,`repeats the operationId ${Ze(o)}, which must be unique in the document`);n.add(o);let a=jE(t,"summary",r),s=jE(t,"description",r),l=HE(e,t,r);if(!Zr(t.responses))throw Le(r,`has no responses object (${At(t.responses)})`);return KE(e,t,r),{id:o,summary:a,description:s,node:t,where:r,parameters:l,pathParameters:i}}function ah(e){if(!Zr(e))throw Le("the document",`is ${At(e)}, not an object`);if(wn(e,"openapi"))throw eo("the document","is OpenAPI 3 (it has an openapi member), not Swagger 2.0");if(!wn(e,"swagger"))throw Le("the document","names no Swagger version");if(e.swagger!=="2.0")throw eo("the document",`declares swagger ${Ze(String(e.swagger))}, not 2.0`);let t=e.paths;if(!Zr(t))throw Le("the document",`has paths that are ${At(t)}, not an object`);let r=[],n=new Set;for(let i of Object.keys(t)){let o=t[i],a=`paths[${Ze(i)}]`;if(!Zr(o))throw Le(a,`is ${At(o)}, not a path item object`);let s=[];for(let l of Object.keys(o))if(xV.has(l.toLowerCase()))r.push(BV(e,o[l],`${a}.${l}`,n,s));else if(l==="parameters")for(let u of HE(e,o,a))s.push(u);else if(!l.startsWith("x-"))throw eo(a,`has a ${Ze(l)} member; a path item may hold only HTTP methods, parameters and x- extensions`)}return{document:e,operations:r}}function qV(e){ah(e)}it.validateConnectorSwagger=qV;var ih=class{constructor(t,r){this.root=t,this.where=r,this.nodes=0,this.characters=0,this.path=[]}run(t){return this.visit(t,0)}tooLarge(t){return new _l.SdkError(it.CONNECTOR_SCHEMA_TOO_LARGE_CODE,`The response schema of ${this.where} is too large to return: it has ${t}. That is far above any connector measured, so this one is not read.`)}node(){if(this.nodes+=1,this.nodes>WE)throw this.tooLarge(`more than ${WE} nodes`)}text(t){if(this.characters+=t,this.characters>zE)throw this.tooLarge(`more than ${zE} characters of strings and keys`)}checkDepth(t){if(t>GE)throw this.tooLarge(`nesting deeper than ${GE} levels`)}visit(t,r){if(this.checkDepth(r),Array.isArray(t)){this.node();let n=[];for(let i of t)n.push(this.visit(i,r+1));return n}if(Zr(t)){if(typeof t.$ref=="string")return this.reference(t.$ref,r);this.node();let n={};for(let i of Object.keys(t))this.text(i.length),Object.defineProperty(n,i,{value:this.visit(t[i],r+1),enumerable:!0,writable:!0,configurable:!0});return n}return this.node(),typeof t=="string"&&this.text(t.length),t}reference(t,r){if(this.path.includes(t)){this.checkDepth(r+1);let o=t.slice(t.lastIndexOf("/")+1);return this.node(),this.text(4),this.node(),this.text(o.length),{$ref:o}}if(this.path.length>=VE)throw this.tooLarge(`a $ref chain of more than ${VE} references`);let n=oh(this.root,t,this.where);if(!Zr(n))throw Le(this.where,`has a schema $ref (${Ze(t)}) that resolves to ${At(n)}, not a schema object`);this.path.push(t);let i=this.visit(n,r);return this.path.pop(),i}};function VV(e){let{operations:t}=ah(e);return{operations:t.map(r=>{var n,i;return{name:r.id,summary:(i=(n=r.summary)!==null&&n!==void 0?n:r.description)!==null&&i!==void 0?i:null}})}}it.projectConnectorOperations=VV;function GV(e,t){if(typeof t!="string"||t==="")throw new _l.InvalidArgumentError("operationId must be a non-empty string.");let{document:r,operations:n}=ah(e),i=n.find(u=>u.id===t);if(!i)throw new _l.SdkError(it.CONNECTOR_OPERATION_NOT_FOUND_CODE,`The connector has no operation with the id ${Ze(t)} (ids are matched exactly, case included). List the connector\u2019s operations to see its ids.`);let o=new Set(i.parameters.map(nh)),a=[...i.parameters,...i.pathParameters.filter(u=>!o.has(nh(u)))].filter(u=>!u.internal).map(({name:u,required:c})=>({name:u,required:c})),s=KE(r,i.node,i.where),l=s===void 0?{}:new ih(r,`${i.where} (${Ze(i.id)})`).run(s);return{operation:i.id,parameters:a,response:l}}it.projectConnectorOperationSchema=GV});var Vo=v(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.readEnvironmentName=J.readConnection=J.connectorShortName=J.CONNECTOR_PREFIX=J.connectivityUnauthorized=J.errorCodeOf=J.messageOf=J.environmentFilter=J.unreadable=J.connectivityCloudOf=J.sameOrigin=J.parseUrl=J.bounded=J.kindOf=J.isObject=J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE=J.CONNECTOR_NOT_TABULAR_CODE=J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=J.CONNECTIVITY_UNAUTHORIZED_CODE=J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=J.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var Dl=Q(),WV=ye(),zV=Tl();J.CONNECTIVITY_NOT_CONFIGURED_CODE="CONNECTIVITY_NOT_CONFIGURED";J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE="CONNECTIVITY_CLOUD_UNSUPPORTED";J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE="CONNECTIVITY_ENVIRONMENT_UNVERIFIED";J.CONNECTIVITY_UNAUTHORIZED_CODE="CONNECTIVITY_UNAUTHORIZED";J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE="CONNECTIVITY_ROUTE_DECOMMISSIONED";J.CONNECTOR_NOT_TABULAR_CODE="CONNECTOR_NOT_TABULAR";J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE="CONNECTOR_RUNTIME_UNSUPPORTED";function wr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}J.isObject=wr;function Ga(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}J.kindOf=Ga;function Wa(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}J.bounded=Wa;function YE(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}J.parseUrl=YE;function jV(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}J.sameOrigin=jV;var HV=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,KV=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/;function JV(e){let t=YE(e),r=t?t.host.toLowerCase():"";if(KV.test(r))return"Test";let n=HV.exec(r);return n&&n[1]!=="9"?"Public":"Unsupported"}J.connectivityCloudOf=JV;function Gn(e,t){return new Dl.SdkError(zV.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}J.unreadable=Gn;function YV(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}J.environmentFilter=YV;function QV(e){if(typeof e=="string"&&e.length>0)return Wa(e,500);if(wr(e)){let t=wr(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Wa(r,500)}return"request failed"}J.messageOf=QV;function QE(e){return wr(e)&&wr(e.error)?e.error.code:void 0}J.errorCodeOf=QE;function XV(e){if(wr(e)&&wr(e.error)&&wr(e.error.innererror))return e.error.innererror.code}function ZV(e,t,r){let n=[],i=QE(t);typeof i=="string"&&i.length>0&&n.push(Wa(i,80));let o=XV(t);typeof o=="string"&&o.length>0&&n.push(Wa(o,80));let a=n.length>0?` (${n.join("; ")})`:"";return(0,Dl.attachCause)(new Dl.SdkError(J.CONNECTIVITY_UNAUTHORIZED_CODE,`A connectivity request was refused with HTTP ${e}${a}: the token's audience, scopes, expiry, or access was rejected. Supply a valid token for this route, or fall back to pac.`),r)}J.connectivityUnauthorized=ZV;J.CONNECTOR_PREFIX="/providers/Microsoft.PowerApps/apis/";var e4=/^[A-Za-z0-9_.-]{1,128}$/,t4=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]);function r4(e){if(typeof e=="string"){let r=e.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()===J.CONNECTOR_PREFIX.toLowerCase()?e.slice(J.CONNECTOR_PREFIX.length):e;if(e4.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Dl.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${J.CONNECTOR_PREFIX}shared_office365users'); got ${typeof e=="string"?`'${Wa(e,80)}'`:Ga(e)}.`)}J.connectorShortName=r4;function n4(e,t,r){let n=`Connection row ${t}`;if(!wr(e))throw Gn(n,`it is ${Ga(e)}, not an object`);let i=e.properties;if(!wr(i))throw Gn(n,`its properties are ${Ga(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()!==J.CONNECTOR_PREFIX.toLowerCase())throw Gn(n,`its apiId is not '${J.CONNECTOR_PREFIX}<connector>'`);let a=o.slice(J.CONNECTOR_PREFIX.length);if(a===""||a.includes("/"))throw Gn(n,"its apiId names no single connector");if(t4.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Gn(n,"it has no name");let l=i.environment,u=wr(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Gn(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Gn(n,`its displayName is ${Ga(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Gn(n,`its statuses are ${Ga(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=wr(f)?f.status:void 0;if(typeof m!="string")throw Gn(n,"one of its statuses has no string status");return m})}}J.readConnection=n4;var JE="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'";async function i4(e){let t=(0,WV.ensureSuccess)(await e.get(JE),e.apiUrl(JE)).body,r=wr(t)?t.Detail:void 0,n=wr(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw new Dl.SdkError(J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,"The environment of this org could not be verified: the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId).");return n}J.readEnvironmentName=i4});var iA=v(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.ConnectivityApi=Cr.CONNECTIVITY_UNAUTHORIZED_CODE=Cr.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=Cr.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=Cr.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=Cr.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var zt=Q(),o4=ye(),Hc=Tl(),Ol=Vo(),Pl=Vo();Object.defineProperty(Cr,"CONNECTIVITY_NOT_CONFIGURED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_NOT_CONFIGURED_CODE}});Object.defineProperty(Cr,"CONNECTIVITY_CLOUD_UNSUPPORTED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE}});Object.defineProperty(Cr,"CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE}});Object.defineProperty(Cr,"CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE}});Object.defineProperty(Cr,"CONNECTIVITY_UNAUTHORIZED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_UNAUTHORIZED_CODE}});var XE="2016-11-01",a4="2021-04-01",s4="https://api.bap.microsoft.com",l4="https://test.api.bap.microsoft.com",u4=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,c4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,ZE="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'",vi="/providers/Microsoft.PowerApps/apis/",d4=/^[A-Za-z0-9_.-]{1,128}$/,f4=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]),p4="ServiceDecommissioned";function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function to(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Wn(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Il(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}function eA(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}function m4(e){return/^[a-z0-9][a-z0-9.-]*$/.test(e)&&(e==="api.powerapps.com"||e.endsWith(".api.powerapps.com"))}function en(e,t){return new zt.SdkError(Hc.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}function jc(e){return new zt.SdkError(Ol.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: ${e}. The Power Apps service was not asked about it.`)}function tA(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}function rA(e){if(typeof e=="string"&&e.length>0)return Wn(e,500);if(ft(e)){let t=ft(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Wn(r,500)}return"request failed"}function h4(e){return ft(e)&&ft(e.error)?e.error.code:void 0}function nA(e){if(typeof e=="string"){let r=e.slice(0,vi.length).toLowerCase()===vi.toLowerCase()?e.slice(vi.length):e;if(d4.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new zt.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${vi}shared_office365users'); got ${typeof e=="string"?`'${Wn(e,80)}'`:to(e)}.`)}function g4(e,t,r){let n=`Connection row ${t}`;if(!ft(e))throw en(n,`it is ${to(e)}, not an object`);let i=e.properties;if(!ft(i))throw en(n,`its properties are ${to(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,vi.length).toLowerCase()!==vi.toLowerCase())throw en(n,`its apiId is not '${vi}<connector>'`);let a=o.slice(vi.length);if(a===""||a.includes("/"))throw en(n,"its apiId names no single connector");if(f4.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw en(n,"it has no name");let l=i.environment,u=ft(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw en(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw en(n,`its displayName is ${to(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw en(n,`its statuses are ${to(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=ft(f)?f.status:void 0;if(typeof m!="string")throw en(n,"one of its statuses has no string status");return m})}}var sh=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.service=n,this.swaggers=new Map}async listConnections(){let t=this.requireService(),r=await this.resolveEnvironment(t),n=[],i=new Set,o=`${r.origin}/providers/Microsoft.PowerApps/connections?api-version=${XE}&$filter=${tA(r.id)}`,a=await this.send(t,o,!0),s=1,l=0;for(;;){let u=`Page ${s} of the connections`,c=a.body,d=c?.value;if(!Array.isArray(d))throw en(u,`its value is ${to(d)}, not an array`);for(let m of d){let p=g4(m,l,r.id);l+=1,p&&n.push(p)}let f=c?.nextLink;if(f==null)return n;if(typeof f!="string"||f.length===0)throw en(u,`its nextLink is ${f===""?"an empty string":to(f)}, not a non-empty string`);if(i.has(f))throw new zt.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${Wn(f)}'), which would loop indefinitely.`);i.add(f),this.assertSameOrigin(f,r.parsed),a=await this.send(t,f,!0),s+=1}}async listConnectorOperations(t){let r=this.requireService(),n=nA(t);return(0,Hc.projectConnectorOperations)(await this.swagger(r,n))}async getConnectorOperationSchema(t,r){let n=this.requireService(),i=nA(t);if(typeof r!="string"||r==="")throw new zt.InvalidArgumentError("operationId must be a non-empty string.");return(0,Hc.projectConnectorOperationSchema)(await this.swagger(n,i),r)}requireService(){if(!this.service)throw new zt.SdkError(Ol.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a powerAppsServiceClient (MakerSdkOptions), so it cannot read connections or connectors: it needs an HttpClient that authenticates for https://service.powerapps.com/ and does not follow redirects. Nothing was requested.");return this.service}resolveEnvironment(t){if(!this.environment){let r=this.verifyEnvironment(t);this.environment=r,r.catch(()=>{this.environment===r&&(this.environment=void 0)})}return this.environment}async verifyEnvironment(t){let r=this.candidateBapOrigin(),n=await this.readEnvironmentId(),i=`${r}/providers/Microsoft.BusinessAppPlatform/environments/${encodeURIComponent(n)}?api-version=${a4}`,o=(await this.send(t,i,!1)).body,a=ft(o)?o.properties:void 0,s=ft(o)?o.name:void 0;if(typeof s!="string"||s.toLowerCase()!==n.toLowerCase())throw jc(`BAP's environment row is not the one named '${Wn(n,80)}' (its name)`);let l=ft(a)&&ft(a.linkedEnvironmentMetadata)?a.linkedEnvironmentMetadata.instanceUrl:void 0,u=typeof l=="string"?Il(l):void 0,c=Il(this.instanceUrl);if(!u||!c||!eA(u,c))throw jc("BAP's row is not linked to this org (its linkedEnvironmentMetadata.instanceUrl is another origin)");let d=ft(a)?a.runtimeEndpoints:void 0,f=ft(d)?d["microsoft.PowerApps"]:void 0,m=typeof f=="string"?Il(f):void 0;if(!m||m.protocol!=="https:"||!m4(m.host.toLowerCase()))throw jc("BAP's Power Apps runtime endpoint is not an https host of api.powerapps.com (runtimeEndpoints['microsoft.PowerApps'])");return{id:n,origin:m.origin.toLowerCase(),parsed:m}}candidateBapOrigin(){let t=Il(this.instanceUrl),r=t?t.host.toLowerCase():"",n=u4.exec(r);if(n&&n[1]!=="9")return s4;if(c4.test(r))return l4;throw new zt.SdkError(Ol.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The org's host is not one of the clouds this reads in (${t?`'${Wn(t.host,80)}'`:`'${Wn(this.instanceUrl,80)}', which is not a URL`}): a Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are not supported. Nothing was requested.`)}async readEnvironmentId(){let t=(0,o4.ensureSuccess)(await this.org.get(ZE),this.org.apiUrl(ZE)).body,r=ft(t)?t.Detail:void 0,n=ft(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw jc("the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId)");return n}swagger(t,r){let n=r.toLowerCase(),i=this.swaggers.get(n);if(!i){let o=this.readSwagger(t,r);i=o,this.swaggers.set(n,o),o.catch(()=>{this.swaggers.get(n)===o&&this.swaggers.delete(n)})}return i}async readSwagger(t,r){let n=await this.resolveEnvironment(t),i=encodeURIComponent(r),o=`${n.origin}${vi}${i}?api-version=${XE}&$filter=${tA(n.id)}`,a=(await this.send(t,o,!0)).body,s=ft(a)?a.properties:void 0,l=ft(s)?s.swagger:void 0;if(!ft(l))throw en(`The connector '${Wn(r,80)}'`,`its properties.swagger is ${to(l)}, not an object`);return(0,Hc.validateConnectorSwagger)(l),l}assertSameOrigin(t,r){let n=Il(t);if(!n)throw new zt.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${Wn(t)}'`);if(!eA(n,r))throw new zt.InvalidArgumentError(`Refusing to follow a cross-origin link ('${Wn(n.origin,120)}' is not the environment's Power Apps endpoint '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n){let i;try{i=await t.get(r)}catch(o){throw o instanceof zt.ConnectionError&&typeof o.statusCode=="number"&&o.statusCode>0?this.mapNon2xx(r,o.statusCode,void 0,n,o):o instanceof zt.SdkError?o:new zt.ConnectionError(r,0,o instanceof Error?o.message:String(o),o)}if(!i||typeof i.status!="number")throw new zt.ConnectionError(r,0,"the transport returned no HTTP response");if(i.status>=200&&i.status<300)return i;throw this.mapNon2xx(r,i.status,i.body,n)}mapNon2xx(t,r,n,i,o){let a=o??new zt.ConnectionError(t,r,rA(n),n);return i&&r===410&&h4(n)===p4?(0,zt.attachCause)(new zt.SdkError(Ol.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE,`The Power Apps API this reads through is decommissioned for this environment: ${rA(n)} Fall back to pac, or to the Power Platform API when the host has a client for it; the SDK does not fall back.`),a):r===401||r===403?(0,Ol.connectivityUnauthorized)(r,n,a):a}};Cr.ConnectivityApi=sh});var fh=v(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.projectConnectorTableSchema=Me.projectConnectorTables=Me.tableSchemaSuffix=Me.tablesSuffix=Me.encodeTable=Me.encodeDataset=Me.checkTabularConnection=Me.runtimeAuthority=Me.tabularRevision=Me.checkTableSchemaArguments=Me.checkListTablesArguments=void 0;var Go=Q(),M=Vo(),y4=/^[A-Za-z0-9_.-]{1,128}$/,Wo=/^\.{1,2}$/,b4="shared_sharepointonline",v4=/^[0-9]{1,9}$/,w4=/^[A-Za-z0-9._~-]+$/,C4=/^\/apim\/([A-Za-z0-9._-]+)\/?$/,E4=/^\/connectors\/runtime\/invoke\/scalegroups\/([A-Za-z0-9._-]+)\/(scaleunits|shards)\/([A-Za-z0-9._-]+)\/apis\/([A-Za-z0-9._-]+)\/connections\/?$/,A4=/^[A-Za-z0-9._~!'()*-]$/,S4=/^[0-9A-Fa-f]{2}$/;function wi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Rl(e){return typeof e=="string"?`'${(0,M.bounded)(e,80)}'`:(0,M.kindOf)(e)}function lh(e,t){return new Go.SdkError(M.CONNECTOR_NOT_TABULAR_CODE,`The connector '${(0,M.bounded)(e,80)}' has no tables: ${t}.`)}function Kc(e,t){return new Go.SdkError(M.CONNECTOR_RUNTIME_UNSUPPORTED_CODE,`The connector '${(0,M.bounded)(e,80)}' runs where this SDK does not send a token: ${t}. Nothing was sent to it.`)}function N4(e){if(typeof e=="string"&&y4.test(e)&&!Wo.test(e))return e;throw new Go.InvalidArgumentError(`connectionId must be a connection's name (letters, digits, '_', '.', '-'; at most 128; not '.' or '..'); got ${Rl(e)}.`)}function _4(e){if(e!=null){if(typeof e=="string"&&e!==""&&e.split(",").find(r=>r===""||Wo.test(r))===void 0)return e;throw new Go.InvalidArgumentError(`dataset must be a non-empty string (a SharePoint site URL, a SQL 'server,database', \u2026) none of whose ','-separated parts is empty, '.' or '..', or absent for a connector without datasets; got ${Rl(e)}.`)}}function T4(e){if(typeof e=="string"&&e!==""&&!Wo.test(e))return e;throw new Go.InvalidArgumentError(`table must be a non-empty string other than '.' and '..'; got ${Rl(e)}.`)}function aA(e,t,r){return{short:(0,M.connectorShortName)(e),connectionId:N4(t),dataset:_4(r)}}Me.checkListTablesArguments=aA;function D4(e,t,r,n){return{...aA(e,t,r),table:T4(n)}}Me.checkTableSchemaArguments=D4;function I4(e,t){let r=`The connector '${(0,M.bounded)(t,80)}'`,n=e.properties;if(!(0,M.isObject)(n))throw(0,M.unreadable)(r,`its properties are ${(0,M.kindOf)(n)}, not an object`);if(!wi(n,"interfaces"))throw lh(t,"it declares no interfaces");let i=n.interfaces;if(!(0,M.isObject)(i))throw(0,M.unreadable)(r,`its properties.interfaces are ${(0,M.kindOf)(i)}, not an object`);if(!wi(i,"CDPTabular1"))throw lh(t,"it declares no CDPTabular1 interface");let o=i.CDPTabular1;if(!(0,M.isObject)(o))throw(0,M.unreadable)(r,`its CDPTabular1 interface is ${(0,M.kindOf)(o)}, not an object`);let a=o.revisions;if(!(0,M.isObject)(a))throw(0,M.unreadable)(r,`its CDPTabular1 revisions are ${(0,M.kindOf)(a)}, not an object`);let s,l=new Map;for(let u of Object.keys(a)){let c=a[u],d=`its CDPTabular1 revision '${(0,M.bounded)(u,40)}'`;if(!(0,M.isObject)(c)||typeof c.status!="string")throw(0,M.unreadable)(r,`${d} is not an object with a string status`);if(c.status!=="Production")continue;if(!v4.test(u))throw(0,M.unreadable)(r,`${d} is a Production revision whose key is not a decimal integer of 1\u20139 digits`);let f=O4(c.baseUrl);if(f===void 0)throw(0,M.unreadable)(r,`${d} has a baseUrl that is not '/' or '/'-separated [A-Za-z0-9._~-] segments`);let m=Number(u),p=l.get(m);if(p!==void 0)throw(0,M.unreadable)(r,`its Production revisions '${p}' and '${(0,M.bounded)(u,40)}' have the same number`);l.set(m,u),(!s||m>s.revisionNumber)&&(s={revisionNumber:m,revision:f})}if(!s)throw lh(t,"its CDPTabular1 interface has no Production revision");return s.revision}Me.tabularRevision=I4;function O4(e){if(typeof e!="string")return;let t=e.replace(/^\/+/,"").replace(/\/+$/,"");return t===""?"":t.split("/").every(i=>w4.test(i)&&!Wo.test(i))?t:void 0}function P4(e,t,r){let n=(0,M.isObject)(e.properties)?e.properties:void 0,i=n?n.primaryRuntimeUrl:void 0;if(typeof i!="string")throw Kc(r,`its primaryRuntimeUrl is ${(0,M.kindOf)(i)}, not a string`);let o=t.cloud==="Test",a=(o?`https://${t.name}.tip2-001.tip2.azure-apihub.net`:t.origin).toLowerCase(),s=(0,M.parseUrl)(i);if(!s||s.protocol!=="https:"||s.origin.toLowerCase()!==a)throw Kc(r,`its runtime ('${(0,M.bounded)(i,120)}') is not ${o?"this environment's measured API Hub host (<environment name>.tip2-001.tip2.azure-apihub.net)":"under this environment's own Power Platform API origin"} over https`);let l=i.slice(0,a.length).toLowerCase()===a?i.slice(a.length):void 0;if(o){let c=l===void 0?null:C4.exec(l);if(!c||Wo.test(c[1]))throw Kc(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <host>/apim/<connector>`);return{transport:"invoke",origin:a,path:`/apim/${c[1]}`}}let u=l===void 0?null:E4.exec(l);if(!u||[u[1],u[3],u[4]].some(c=>Wo.test(c)))throw Kc(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <origin>/connectors/runtime/invoke/scalegroups/<group>/(scaleunits|shards)/<unit>/apis/<api>/connections`);return{transport:"direct",origin:a,path:`/connectors/runtime/invoke/scalegroups/${u[1]}/${u[2]}/${u[3]}/apis/${u[4]}/connections`}}Me.runtimeAuthority=P4;function R4(e,t,r,n){let i=`The connection '${(0,M.bounded)(t,128)}'`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(i,`it is ${(0,M.kindOf)(e)}, not an object`);if(e.name!==t)throw(0,M.unreadable)(i,`its name is ${Rl(e.name)}, not the requested connection`);let o=e.properties;if(!(0,M.isObject)(o))throw(0,M.unreadable)(i,`its properties are ${(0,M.kindOf)(o)}, not an object`);let a=o.apiId;if(typeof a!="string"||a.toLowerCase()!==`${M.CONNECTOR_PREFIX}${r}`.toLowerCase())throw(0,M.unreadable)(i,`its apiId is ${Rl(a)}, not the connector '${(0,M.bounded)(r,80)}'`);let s=o.environment,l=(0,M.isObject)(s)?s.name:void 0;if(typeof l!="string"||l.toLowerCase()!==n.toLowerCase())throw(0,M.unreadable)(i,"it is not a connection of this environment (properties.environment.name)");return t}Me.checkTabularConnection=R4;function oA(e){return encodeURIComponent(e).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}function k4(e){if(e==="")return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="%"){if(!S4.test(e.slice(t+1,t+3)))return!1;t+=2}else if(!A4.test(e[t]))return!1;return!0}function sA(e,t){let r,n,i;try{r=oA(e),n=oA(r),i=decodeURIComponent(n)}catch{throw new Go.InvalidArgumentError(`${t} is not well-formed Unicode (it has a lone surrogate), so it cannot be sent.`)}if(!k4(n)||Wo.test(n)||i!==r)throw new Go.InvalidArgumentError(`${t} cannot be sent as one path segment.`);return n}function dh(e){return e.split(",").map((t,r)=>sA(t,`dataset part ${r}`)).join(",")}Me.encodeDataset=dh;function lA(e){return sA(e,"table")}Me.encodeTable=lA;function L4(e,t){if(t===void 0)return"/tables";let r=e.toLowerCase()===b4?"allTables":"tables";return`/datasets/${dh(t)}/${r}`}Me.tablesSuffix=L4;function $4(e,t){return`/$metadata.json${e===void 0?"":`/datasets/${dh(e)}`}/tables/${lA(t)}`}Me.tableSchemaSuffix=$4;function za(e,t){let r=t.toLowerCase();for(let n of Object.keys(e))if(n.toLowerCase()===r)return{found:!0,value:e[n]};return{found:!1}}function x4(e){let t="The table list",r;if(Array.isArray(e))r=e;else if((0,M.isObject)(e)){for(let o of["nextLink","@odata.nextLink"])if(za(e,o).found)throw(0,M.unreadable)(t,`it carries a ${o} \u2014 a paged answer is refused, never read as a partial list`);let n=za(e,"value"),i=n.found?n:za(e,"tables");if(!i.found)throw(0,M.unreadable)(t,"it is an object with neither a value nor a tables member");if(!Array.isArray(i.value))throw(0,M.unreadable)(t,`its ${n.found?"value":"tables"} is ${(0,M.kindOf)(i.value)}, not an array`);r=i.value}else throw(0,M.unreadable)(t,`it is ${(0,M.kindOf)(e)}, not an array or an object`);return{tables:r.map((n,i)=>F4(n,i))}}Me.projectConnectorTables=x4;function F4(e,t){let r=`Table row ${t}`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=za(e,"name");if(!n.found||typeof n.value!="string"||n.value==="")throw(0,M.unreadable)(r,"it has no non-empty string name");let i=za(e,"displayName");if(i.found&&typeof i.value!="string")throw(0,M.unreadable)(r,`its displayName is ${(0,M.kindOf)(i.value)}, not a string`);let o=za(e,"id");if(o.found&&(typeof o.value!="string"||o.value===""))throw(0,M.unreadable)(r,`its id is ${o.value===""?"an empty string":(0,M.kindOf)(o.value)}, not a non-empty string`);return{name:n.value,displayName:i.found?i.value:null,id:o.found?o.value:n.value}}function uh(e,t,r){if(!wi(e,t))return;let n=e[t];if(!(0,M.isObject)(n))throw(0,M.unreadable)("The table schema",`its ${r} is ${(0,M.kindOf)(n)}, not an object`);return n}function ch(e,t,r){if(!wi(e,t))return;let n=e[t];if(typeof n!="string")throw(0,M.unreadable)(r,`its ${t} is ${(0,M.kindOf)(n)}, not a string`);return n}function M4(e,t){var r,n;if(wi(e,"$ref"))throw(0,M.unreadable)(t,"it is a $ref, whose type is not guessed");let i=ch(e,"type",t),o=ch(e,"format",t),a=(r=i??o)!==null&&r!==void 0?r:"object";if(!wi(e,"items"))return a;let s=e.items;if(!(0,M.isObject)(s))throw(0,M.unreadable)(t,`its items are ${(0,M.kindOf)(s)}, not an object`);if(wi(s,"$ref"))throw(0,M.unreadable)(t,"its items are a $ref, whose type is not guessed");return`${a}<${(n=ch(s,"type",`${t} items`))!==null&&n!==void 0?n:"object"}>`}function U4(e,t){let r="The table schema";if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=uh(e,"items","items"),i=uh(e,"schema","schema"),o=i?uh(i,"items","schema.items"):void 0,a=[[e,"the answer"],[n,"items"],[i,"schema"],[o,"schema.items"]],s=new Set;for(let[c,d]of a)if(c&&wi(c,"required")){let f=c.required;if(!Array.isArray(f))throw(0,M.unreadable)(r,`the required of ${d} is ${(0,M.kindOf)(f)}, not an array`);f.forEach(m=>{if(typeof m!="string")throw(0,M.unreadable)(r,`the required of ${d} has an entry that is ${(0,M.kindOf)(m)}, not a string`);s.add(m.toLowerCase())})}let l;for(let[c,d]of a)if(c&&wi(c,"properties")){if(!(0,M.isObject)(c.properties))throw(0,M.unreadable)(r,`the properties of ${d} are ${(0,M.kindOf)(c.properties)}, not an object`);l=c.properties;break}if(!l)throw(0,M.unreadable)(r,"it has no properties, items.properties, schema.properties or schema.items.properties");let u=Object.keys(l).map(c=>{let d=`Column '${(0,M.bounded)(c,80)}'`,f=l[c];if(!(0,M.isObject)(f))throw(0,M.unreadable)(d,`it is ${(0,M.kindOf)(f)}, not an object`);return{name:c,type:M4(f,d),required:s.has(c.toLowerCase())}});return{table:t,columns:u}}Me.projectConnectorTableSchema=U4});var uA=v(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.PowerPlatformApiDiscovery=void 0;var ph=class{constructor(t){this.clusterCategory=t}getTokenAudience(){return`https://${this._getEnvironmentApiHostNameSuffix()}`}getTokenEndpointHost(){return this._getEnvironmentApiHostNameSuffix()}getTenantEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant")}getTenantIslandClusterEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant","il-")}getEnvironmentEndpoint(t){return this._generatePowerPlatformApiDomain(t,"environment")}_generatePowerPlatformApiDomain(t,r,n=""){if(!/^[a-zA-Z0-9\-]+$/g.test(t))throw new Error(`Cannot generate Power Platform API endpoint because the ${r} identifier contains invalid host name characters, only alphanumeric and dash characters are expected: ${t}`);let i=this._getHexApiSuffixLength(),o=t.toLowerCase().replace(/-/g,"");if(i>=o.length)throw new Error(`Cannot generate Power Platform API endpoint because the normalized ${r} identifier must be at least ${i+1} characters in length: ${o}`);let a=o.substring(o.length-i),s=o.substring(0,o.length-i),l=this._getEnvironmentApiHostNameSuffix();return`${n}${s}.${a}.${r}.${l}`}_getHexApiSuffixLength(){switch(this.clusterCategory){case"firstrelease":case"prod":return 2;default:return 1}}_getEnvironmentApiHostNameSuffix(){switch(this.clusterCategory){case"local":return"api.powerplatform.localhost";case"dev":return"api.dev.powerplatform.com";case"test":return"api.test.powerplatform.com";case"preprod":return"api.preprod.powerplatform.com";case"firstrelease":case"prod":return"api.powerplatform.com";case"gov":return"api.gov.powerplatform.microsoft.us";case"high":return"api.high.powerplatform.microsoft.us";case"dod":return"api.appsplatform.us";case"mooncake":return"api.powerplatform.partner.microsoftonline.cn";case"ex":return"api.powerplatform.eaglex.ic.gov";case"rx":return"api.powerplatform.microsoft.scloud";default:throw new Error(`Invalid ClusterCategory value: ${this.clusterCategory}`)}}};Jc.PowerPlatformApiDiscovery=ph});var cA=v(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.PowerPlatformApiDiscovery=void 0;var B4=uA();Object.defineProperty(Yc,"PowerPlatformApiDiscovery",{enumerable:!0,get:function(){return B4.PowerPlatformApiDiscovery}})});var mA=v(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.platformTokenAudience=ro.platformEnvironment=ro.platformClusterOf=void 0;var dA=cA(),fA=Q(),pA=Vo(),q4=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,V4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,G4=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,W4=/^default-/i;function mh(e,t=80){return e.length>t?`${e.slice(0,t)}\u2026`:e}function z4(e){try{return new URL(e).host.toLowerCase()}catch{return}}function j4(e){let t=z4(e);if(t){if(V4.test(t))return{cloud:"Test",category:"test"};let r=q4.exec(t);if(r&&r[1]!=="9")return{cloud:"Public",category:"prod"}}throw new fA.SdkError(pA.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The Power Platform API route is built for the Test and Public clouds; this org (${t?`'${mh(t)}'`:`'${mh(e)}', which is not a URL`}) is another cloud. A Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are pending or out of scope. Nothing was requested.`)}ro.platformClusterOf=j4;function H4(e,t){let r=W4.test(e)?e.slice(8):e;if(!G4.test(r))throw new fA.SdkError(pA.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: its name ('${mh(e)}') is neither a GUID nor 'Default-<GUID>', the forms this route is measured for. The Power Platform API was not asked about it.`);return{origin:`https://${new dA.PowerPlatformApiDiscovery(t).getEnvironmentEndpoint(e)}`,guid:r.toLowerCase()}}ro.platformEnvironment=H4;function K4(e){return new dA.PowerPlatformApiDiscovery(e).getTokenAudience()}ro.platformTokenAudience=K4});var gA=v(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.PlatformConnectivityApi=ja.assertTabularCloud=void 0;var Cn=Q(),hh=Tl(),me=Vo(),hA=mA(),Ci=fh(),gh="1";function yh(e){let t=(0,me.connectivityCloudOf)(e);if(t!=="Test"&&t!=="Public")throw new Cn.SdkError(me.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"Connector tables are read in the Test and Public clouds; this org's cloud is neither (GCC, GCC High and DoD are pending). Nothing was requested.")}ja.assertTabularCloud=yh;var bh=class{constructor(t,r,n,i){this.org=t,this.instanceUrl=r,this.client=n,this.runtime=i,this.records=new Map,this.swaggers=new Map}async listConnections(){let t=await this.resolveEnvironment(),r=[],n=new Set,i=await this.send(this.client,"GET",`${t.origin}/connectivity/connections?api-version=${gh}`,[401,403]),o=1,a=0;for(;;){let s=`Page ${o} of the connections`,l=i.body,u=l?.value;if(!Array.isArray(u))throw(0,me.unreadable)(s,`its value is ${(0,me.kindOf)(u)}, not an array`);for(let d of u){let f=(0,me.readConnection)(d,a,t.name);a+=1,f&&r.push(f)}let c=l?.nextLink;if(c==null)return r;if(typeof c!="string"||c.length===0)throw(0,me.unreadable)(s,`its nextLink is ${c===""?"an empty string":(0,me.kindOf)(c)}, not a non-empty string`);if(n.has(c))throw new Cn.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${(0,me.bounded)(c)}'), which would loop indefinitely.`);n.add(c),this.assertSameOrigin(c,t.parsed),i=await this.send(this.client,"GET",c,[401,403]),o+=1}}async listConnectorOperations(t){let r=(0,me.connectorShortName)(t);return(0,hh.projectConnectorOperations)(await this.swagger(r))}async getConnectorOperationSchema(t,r){let n=(0,me.connectorShortName)(t);if(typeof r!="string"||r==="")throw new Cn.InvalidArgumentError("operationId must be a non-empty string.");return(0,hh.projectConnectorOperationSchema)(await this.swagger(n),r)}async listConnectorTables(t,r,n){yh(this.instanceUrl);let i=(0,Ci.checkListTablesArguments)(t,r,n),o=(0,Ci.tablesSuffix)(i.short,i.dataset);return(0,Ci.projectConnectorTables)(await this.invokeTabular(i,o))}async getConnectorTableSchema(t,r,n,i){yh(this.instanceUrl);let o=(0,Ci.checkTableSchemaArguments)(t,r,n,i),a=(0,Ci.tableSchemaSuffix)(o.dataset,o.table);return(0,Ci.projectConnectorTableSchema)(await this.invokeTabular(o,a),o.table)}async invokeTabular(t,r){let n=this.requireRuntime(),i=await this.resolveEnvironment(),o=await this.record(t.short),a=(0,Ci.tabularRevision)(o,t.short),s=(0,Ci.runtimeAuthority)(o,{cloud:i.cloud,name:i.name,origin:i.origin},t.short),l=`${i.origin}/connectivity/connectors/${encodeURIComponent(t.short)}/connections/${encodeURIComponent(t.connectionId)}?$filter=${(0,me.environmentFilter)(i.name)}&api-version=${gh}`,u=(await this.send(this.client,"GET",l,[401,403])).body,c=(0,Ci.checkTabularConnection)(u,t.connectionId,t.short,i.name),d=`${s.path}/${c}${a===""?"":`/${a}`}${r}`;return(s.transport==="invoke"?await this.send(n,"POST",`${s.origin}/invoke`,[401],{"X-Ms-Request-Url":d,"X-Ms-Request-Method":"GET"}):await this.send(n,"GET",`${s.origin}${d}`,[401])).body}requireRuntime(){if(!this.runtime)throw new Cn.SdkError(me.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a connectorRuntimeClient (MakerSdkOptions), so it cannot read connector tables: it needs an HttpClient that authenticates for API Hub (https://apihub.azure.com) and does not follow redirects. Nothing was requested.");return this.runtime}resolveEnvironment(){if(!this.environment){let t=this.readEnvironment();this.environment=t,t.catch(()=>{this.environment===t&&(this.environment=void 0)})}return this.environment}async readEnvironment(){let{cloud:t,category:r}=(0,hA.platformClusterOf)(this.instanceUrl),n=await(0,me.readEnvironmentName)(this.org),{origin:i,guid:o}=(0,hA.platformEnvironment)(n,r),a=(0,me.parseUrl)(i);if(!a)throw(0,me.unreadable)("The Power Platform API origin",`'${(0,me.bounded)(i)}' is not a URL`);return{cloud:t,origin:i,parsed:a,name:n,guid:o}}cached(t,r,n){let i=t.get(r);if(!i){let o=n();i=o,t.set(r,o),o.catch(()=>{t.get(r)===o&&t.delete(r)})}return i}record(t){return this.cached(this.records,t.toLowerCase(),()=>this.readRecord(t))}async readRecord(t){let r=await this.resolveEnvironment(),n=`${r.origin}/connectivity/connectors/${encodeURIComponent(t)}?$filter=${(0,me.environmentFilter)(r.name)}&api-version=${gh}`,i=(await this.send(this.client,"GET",n,[401,403])).body,o=(0,me.isObject)(i)?i.name:void 0;if(!(0,me.isObject)(i)||typeof o!="string"||o.toLowerCase()!==t.toLowerCase())throw(0,me.unreadable)(`The connector '${(0,me.bounded)(t,80)}'`,`the record's name is ${typeof o=="string"?`'${(0,me.bounded)(o,80)}'`:(0,me.kindOf)(o)}, not the requested connector`);return i}swagger(t){return this.cached(this.swaggers,t.toLowerCase(),async()=>{let n=(await this.record(t)).properties,i=(0,me.isObject)(n)?n.swagger:void 0;if(!(0,me.isObject)(i))throw(0,me.unreadable)(`The connector '${(0,me.bounded)(t,80)}'`,`its properties.swagger is ${(0,me.kindOf)(i)}, not an object`);return(0,hh.validateConnectorSwagger)(i),i})}assertSameOrigin(t,r){let n=(0,me.parseUrl)(t);if(!n)throw new Cn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${(0,me.bounded)(t)}'`);if(!(0,me.sameOrigin)(n,r))throw new Cn.InvalidArgumentError(`Refusing to follow a cross-origin link ('${(0,me.bounded)(n.origin,120)}' is not the environment's Power Platform API origin '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n,i,o){let a;try{a=r==="GET"?await t.get(n):await t.post(n,void 0,{headers:o})}catch(s){throw s instanceof Cn.ConnectionError&&typeof s.statusCode=="number"&&s.statusCode>0?this.non2xx(n,s.statusCode,void 0,i,s):s instanceof Cn.SdkError?s:new Cn.ConnectionError(n,0,s instanceof Error?s.message:String(s),s)}if(!a||typeof a.status!="number")throw new Cn.ConnectionError(n,0,"the transport returned no HTTP response");if(a.status>=200&&a.status<300)return a;throw this.non2xx(n,a.status,a.body,i)}non2xx(t,r,n,i,o){let a=o??new Cn.ConnectionError(t,r,(0,me.messageOf)(n),n);return i.includes(r)?(0,me.connectivityUnauthorized)(r,n,a):a}};ja.PlatformConnectivityApi=bh});var bA=v(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});Xc.ConnectivityRouter=void 0;var vh=Q(),J4=iA(),Qc=Vo(),yA=fh(),wh=gA(),Ch=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.clients=n}async listConnections(){return this.route().listConnections()}async listConnectorOperations(t){return this.route().listConnectorOperations(t)}async getConnectorOperationSchema(t,r){return this.route().getConnectorOperationSchema(t,r)}async listConnectorTables(t,r,n){return(0,wh.assertTabularCloud)(this.instanceUrl),(0,yA.checkListTablesArguments)(t,r,n),this.tabularRoute().listConnectorTables(t,r,n)}async getConnectorTableSchema(t,r,n,i){return(0,wh.assertTabularCloud)(this.instanceUrl),(0,yA.checkTableSchemaArguments)(t,r,n,i),this.tabularRoute().getConnectorTableSchema(t,r,n,i)}route(){return this.delegate||(this.delegate=this.select()),this.delegate}platformRoute(t){return this.platform||(this.platform=new wh.PlatformConnectivityApi(this.org,this.instanceUrl,t,this.clients.connectorRuntimeClient)),this.platform}tabularRoute(){let{powerPlatformApiClient:t,connectorRuntimeClient:r}=this.clients,n=[t?void 0:"powerPlatformApiClient (the Power Platform API)",r?void 0:"connectorRuntimeClient (API Hub, https://apihub.azure.com)"].filter(i=>i!==void 0);if(n.length>0||!t)throw new vh.SdkError(Qc.CONNECTIVITY_NOT_CONFIGURED_CODE,`Connector tables are read through the Power Platform API and the connector runtime: this SDK was created without MakerSdkOptions.${n.join(" or MakerSdkOptions.")}, an HttpClient that does not follow redirects. Nothing was requested.`);return this.platformRoute(t)}select(){let t=(0,Qc.connectivityCloudOf)(this.instanceUrl),{powerAppsServiceClient:r,powerPlatformApiClient:n}=this.clients;if(t==="Unsupported")throw new vh.SdkError(Qc.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"This org's cloud has no connection/connector route: the Test and Public clouds are served (through the Power Platform API, or the classic route for Public); GCC, GCC High and DoD are pending. Nothing was requested.");if(n)return this.platformRoute(n);if(t==="Public"&&r)return new J4.ConnectivityApi(this.org,this.instanceUrl,r);throw new vh.SdkError(Qc.CONNECTIVITY_NOT_CONFIGURED_CODE,t==="Test"?"This org is in the Test cloud, whose connection and connector reads go through the Power Platform API: supply MakerSdkOptions.powerPlatformApiClient (an HttpClient that authenticates for the Power Platform API and does not follow redirects). Nothing was requested.":"This org is in the Public cloud: supply MakerSdkOptions.powerPlatformApiClient (the Power Platform API route) or powerAppsServiceClient (the classic route). Neither was given, so nothing was requested.")}};Xc.ConnectivityRouter=Ch});var Ha=v(Ei=>{"use strict";function Y4(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 Ah(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function Q4(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 vA=Ah({HTML:"text/html",isHTML:function(e){return e===vA.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),wA=Ah({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===wA.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),Zc=/[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]/,Eh=new RegExp("[\\-\\.0-9"+Zc.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),X4=new RegExp("^"+Zc.source+Eh.source+"*(?::"+Zc.source+Eh.source+"*)?$");Ei.assign=Q4;Ei.find=Y4;Ei.freeze=Ah;Ei.MIME_TYPE=vA;Ei.NAMESPACE=wA;Ei.nameStartChar=Zc;Ei.nameChar=Eh;Ei.tagNamePattern=X4});var $h=v(_i=>{var Sh=Ha(),zn=Sh.find,Ll=Sh.NAMESPACE,Ka=Sh.tagNamePattern;function Z4(e){return e!==""}function eG(e){return e?e.split(/[\t\n\f\r ]+/).filter(Z4):[]}function tG(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function CA(e){if(!e)return[];var t=eG(e);return Object.keys(t.reduce(tG,{}))}function rG(e){return function(t){return e&&e.indexOf(t)!==-1}}function xl(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function Ar(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,xl(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Sr={},tn=Sr.ELEMENT_NODE=1,Ja=Sr.ATTRIBUTE_NODE=2,kl=Sr.TEXT_NODE=3,IA=Sr.CDATA_SECTION_NODE=4,OA=Sr.ENTITY_REFERENCE_NODE=5,nG=Sr.ENTITY_NODE=6,Nh=Sr.PROCESSING_INSTRUCTION_NODE=7,_h=Sr.COMMENT_NODE=8,PA=Sr.DOCUMENT_NODE=9,RA=Sr.DOCUMENT_TYPE_NODE=10,Ai=Sr.DOCUMENT_FRAGMENT_NODE=11,iG=Sr.NOTATION_NODE=12,jt={},Nt={},qse=jt.INDEX_SIZE_ERR=(Nt[1]="Index size error",1),Vse=jt.DOMSTRING_SIZE_ERR=(Nt[2]="DOMString size error",2),Er=jt.HIERARCHY_REQUEST_ERR=(Nt[3]="Hierarchy request error",3),Gse=jt.WRONG_DOCUMENT_ERR=(Nt[4]="Wrong document",4),EA=jt.INVALID_CHARACTER_ERR=(Nt[5]="Invalid character",5),Wse=jt.NO_DATA_ALLOWED_ERR=(Nt[6]="No data allowed",6),zse=jt.NO_MODIFICATION_ALLOWED_ERR=(Nt[7]="No modification allowed",7),kA=jt.NOT_FOUND_ERR=(Nt[8]="Not found",8),jse=jt.NOT_SUPPORTED_ERR=(Nt[9]="Not supported",9),AA=jt.INUSE_ATTRIBUTE_ERR=(Nt[10]="Attribute in use",10),En=jt.INVALID_STATE_ERR=(Nt[11]="Invalid state",11),Hse=jt.SYNTAX_ERR=(Nt[12]="Syntax error",12),Kse=jt.INVALID_MODIFICATION_ERR=(Nt[13]="Invalid modification",13),Jse=jt.NAMESPACE_ERR=(Nt[14]="Invalid namespace",14),Yse=jt.INVALID_ACCESS_ERR=(Nt[15]="Invalid access",15);function he(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,Nt[e]),this.message=Nt[e],Error.captureStackTrace&&Error.captureStackTrace(this,he);return r.code=e,t&&(this.message=this.message+": "+t),r}he.prototype=Error.prototype;xl(jt,he);function Si(){}Si.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=[],o=0;o<this.length;o++)Lh(this[o],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 Ya(e,t){this._node=e,this._refresh=t,Th(this)}function Th(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(jA(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];xl(r,e),e._inc=t}}Ya.prototype.item=function(e){return Th(this),this[e]||null};Ar(Ya,Si);function td(){this._nameIndex=Object.create(null)}function LA(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function oG(e,t){e._nameIndex[t.nodeName]=t}function $A(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function SA(e,t,r,n){if(n?(t[LA(t,n)]=r,$A(t,n)):t[t.length++]=r,oG(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&MA(i,e,n),aG(i,e,r))}}function NA(e,t,r){var n=LA(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,$A(t,r),e){var o=e.ownerDocument;o&&(MA(o,e,r),r.ownerElement=null)}}else throw new he(kA,new Error(e.tagName+"@"+r))}td.prototype={length:0,item:Si.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 he(AA);var r=this._nameIndex[e.nodeName];return SA(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new he(AA);return r=this.getNamedItemNS(e.namespaceURI,e.localName),SA(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return NA(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return NA(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 xA(){}xA.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new Fl;if(n.implementation=this,n.childNodes=new Si,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 ad;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function De(){}De.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(e,t){return nd(this,e,t)},replaceChild:function(e,t){nd(this,e,t,BA),t&&this.removeChild(t)},removeChild:function(e){return UA(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return zA(this.ownerDocument||this,this,e)},normalize:function(){St(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===kl&&t.nodeType===kl){for(var n=[],i=r;i!==null&&i.nodeType===kl;)n.push(i.data),i=i.nextSibling;for(var o=t.nextSibling;o!==i;){var a=o.nextSibling;o.parentNode=null,o.previousSibling=null,o.nextSibling=null,o=a}t.nextSibling=i,i!==null?i.previousSibling=t:e.lastChild=t,t.appendData(n.join("")),od(e.ownerDocument,e),t=i}else t=r}return!0}})},isSupported:function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(e){for(var t=this;t;){var r=t._nsMap;if(r){for(var n in r)if(Object.prototype.hasOwnProperty.call(r,n)&&r[n]===e)return n}t=t.nodeType==Ja?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==Ja?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function FA(e){return e=="<"&&"&lt;"||e==">"&&"&gt;"||e=="&"&&"&amp;"||e=='"'&&"&quot;"||"&#"+e.charCodeAt()+";"}xl(Sr,De);xl(Sr,De.prototype);function rd(e,t){return St(e,null,{enter:function(r){return t(r)?St.STOP:!0}})===St.STOP}function St(e,t,r){for(var n=[{node:e,context:t,phase:St.ENTER}];n.length>0;){var i=n.pop();if(i.phase===St.ENTER){var o=r.enter(i.node,i.context);if(o===St.STOP)return St.STOP;if(n.push({node:i.node,context:o,phase:St.EXIT}),o==null)continue;for(var a=i.node.lastChild;a;)n.push({node:a,context:o,phase:St.ENTER}),a=a.previousSibling}else r.exit&&r.exit(i.node,i.context)}}St.STOP=Symbol("walkDOM.STOP");St.ENTER=0;St.EXIT=1;function Fl(){this.ownerDocument=this}function aG(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Ll.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function MA(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Ll.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function od(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,o=0;i;)n[o++]=i,i=i.nextSibling;n.length=o,delete n[n.length]}}}function UA(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,od(e.ownerDocument,e),t}function sG(e){return e&&(e.nodeType===De.DOCUMENT_NODE||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.ELEMENT_NODE)}function lG(e){return e&&(jn(e)||Dh(e)||Ni(e)||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.COMMENT_NODE||e.nodeType===De.PROCESSING_INSTRUCTION_NODE)}function Ni(e){return e&&e.nodeType===De.DOCUMENT_TYPE_NODE}function jn(e){return e&&e.nodeType===De.ELEMENT_NODE}function Dh(e){return e&&e.nodeType===De.TEXT_NODE}function _A(e,t){var r=e.childNodes||[];if(zn(r,jn)||Ni(t))return!1;var n=zn(r,Ni);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function TA(e,t){var r=e.childNodes||[];function n(o){return jn(o)&&o!==t}if(zn(r,n))return!1;var i=zn(r,Ni);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function uG(e,t,r){if(!sG(e))throw new he(Er,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new he(kA,"child not in parent");if(!lG(t)||Ni(t)&&e.nodeType!==De.DOCUMENT_NODE)throw new he(Er,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function cG(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(jn);if(o.length>1||zn(i,Dh))throw new he(Er,"More than one element or text in fragment");if(o.length===1&&!_A(e,r))throw new he(Er,"Element in fragment can not be inserted before doctype")}if(jn(t)&&!_A(e,r))throw new he(Er,"Only one element can be added and only after doctype");if(Ni(t)){if(zn(n,Ni))throw new he(Er,"Only one doctype is allowed");var a=zn(n,jn);if(r&&n.indexOf(a)<n.indexOf(r))throw new he(Er,"Doctype can only be inserted before an element");if(!r&&a)throw new he(Er,"Doctype can not be appended since element is present")}}function BA(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(jn);if(o.length>1||zn(i,Dh))throw new he(Er,"More than one element or text in fragment");if(o.length===1&&!TA(e,r))throw new he(Er,"Element in fragment can not be inserted before doctype")}if(jn(t)&&!TA(e,r))throw new he(Er,"Only one element can be added and only after doctype");if(Ni(t)){let l=function(u){return Ni(u)&&u!==r};var s=l;if(zn(n,l))throw new he(Er,"Only one doctype is allowed");var a=zn(n,jn);if(r&&n.indexOf(a)<n.indexOf(r))throw new he(Er,"Doctype can only be inserted before an element")}}function nd(e,t,r,n){uG(e,t,r),e.nodeType===De.DOCUMENT_NODE&&(n||cG)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===Ai){var o=t.firstChild;if(o==null)return t;var a=t.lastChild}else o=a=t;var s=r?r.previousSibling:e.lastChild;o.previousSibling=s,a.nextSibling=r,s?s.nextSibling=o:e.firstChild=o,r==null?e.lastChild=a:r.previousSibling=a;do{o.parentNode=e;var l=e.ownerDocument||e;$l(o,l)}while(o!==a&&(o=o.nextSibling));return od(e.ownerDocument||e,e),t.nodeType==Ai&&(t.firstChild=t.lastChild=null),t}function $l(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===tn&&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;)$l(i,t),i=i.nextSibling}}function dG(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,od(e.ownerDocument,e,t);var r=e.ownerDocument||e;return $l(t,r),t}Fl.prototype={nodeName:"#document",nodeType:PA,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==Ai){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return nd(this,e,t),$l(e,this),this.documentElement===null&&e.nodeType===tn&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),UA(this,e)},replaceChild:function(e,t){nd(this,e,t,BA),$l(e,this),t&&this.removeChild(t),jn(e)&&(this.documentElement=e)},importNode:function(e,t){return fG(this,e,t)},getElementById:function(e){var t=null;return rd(this.documentElement,function(r){if(r.nodeType==tn&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=CA(e);return new Ya(this,function(r){var n=[];return t.length>0&&rd(r.documentElement,function(i){if(i!==r&&i.nodeType===tn){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=CA(o);a=t.every(rG(s))}a&&n.push(i)}}}),n})},createElement:function(e){var t=new zo;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new Si;var r=t.attributes=new td;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new sd;return e.ownerDocument=this,e.childNodes=new Si,e},createTextNode:function(e){var t=new Ih;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new Oh;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new he(EA,'data contains "]]>"');var t=new Ph;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new kh;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new id;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!Ka.test(e))throw new he(EA,'not a valid xml name "'+e+'"');var t=new Rh;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new zo,n=t.split(":"),i=r.attributes=new td;return r.childNodes=new Si,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 id,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}};Ar(Fl,De);function zo(){this._nsMap={}}zo.prototype={nodeType:tn,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===Ai?this.insertBefore(e,null):dG(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 Ya(this,function(t){var r=[];return rd(t,function(n){n!==t&&n.nodeType==tn&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new Ya(this,function(r){var n=[];return rd(r,function(i){i!==r&&i.nodeType===tn&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};Fl.prototype.getElementsByTagName=zo.prototype.getElementsByTagName;Fl.prototype.getElementsByTagNameNS=zo.prototype.getElementsByTagNameNS;Ar(zo,De);function id(){}id.prototype.nodeType=Ja;Ar(id,De);function Ml(){}Ml.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(Nt[Er])},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}};Ar(Ml,De);function Ih(){}Ih.prototype={nodeName:"#text",nodeType:kl,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}};Ar(Ih,Ml);function Oh(){}Oh.prototype={nodeName:"#comment",nodeType:_h};Ar(Oh,Ml);function Ph(){}Ph.prototype={nodeName:"#cdata-section",nodeType:IA};Ar(Ph,Ml);function ad(){}ad.prototype.nodeType=RA;Ar(ad,De);function qA(){}qA.prototype.nodeType=iG;Ar(qA,De);function VA(){}VA.prototype.nodeType=nG;Ar(VA,De);function Rh(){}Rh.prototype.nodeType=OA;Ar(Rh,De);function sd(){}sd.prototype.nodeName="#document-fragment";sd.prototype.nodeType=Ai;Ar(sd,De);function kh(){}kh.prototype.nodeType=Nh;Ar(kh,De);function GA(){}GA.prototype.serializeToString=function(e,t,r,n){return WA.call(e,t,r,n)};De.prototype.toString=WA;function WA(e,t,r){var n=!!r&&!!r.requireWellFormed,i=[],o=this.nodeType==9&&this.documentElement||this,a=o.prefix,s=o.namespaceURI;if(s&&a==null){var a=o.lookupPrefix(s);if(a==null)var l=[{namespace:s,prefix:null}]}return Lh(this,i,e,t,l,n),i.join("")}function DA(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===Ll.XML||i===Ll.XMLNS)return!1;for(var o=r.length;o--;){var a=r[o];if(a.prefix===n)return a.namespace!==i}return!0}function ed(e,t,r,n){if(n&&!Ka.test(t))throw new he(En,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,FA),'"')}function Lh(e,t,r,n,i,o){i||(i=[]),St(e,{ns:i,isHTML:r},{enter:function(a,s){var l=s.ns,u=s.isHTML;if(n)if(a=n(a),a){if(typeof a=="string")return t.push(a),null}else return null;switch(a.nodeType){case tn:var c=a.attributes,d=c.length,f=a.tagName;u=Ll.isHTML(a.namespaceURI)||u;var m=f;if(!u&&!a.prefix&&a.namespaceURI){for(var p,h=0;h<c.length;h++)if(c.item(h).name==="xmlns"){p=c.item(h).value;break}if(!p)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.prefix===""&&b.namespace===a.namespaceURI){p=b.namespace;break}}if(p!==a.namespaceURI)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.namespace===a.namespaceURI){b.prefix&&(m=b.prefix+":"+f);break}}}if(o&&!Ka.test(m))throw new he(En,'The element name "'+m+'" is not a valid XML QName');t.push("<",m);for(var w=l.slice(),C=0;C<d;C++){var S=c.item(C);S.prefix=="xmlns"?w.push({prefix:S.localName,namespace:S.value}):S.nodeName=="xmlns"&&w.push({prefix:"",namespace:S.value})}for(var C=0;C<d;C++){var S=c.item(C);if(DA(S,u,w)){var O=S.prefix||"",k=S.namespaceURI;ed(t,O?"xmlns:"+O:"xmlns",k,o),w.push({prefix:O,namespace:k})}var I=n?n(S):S;I&&(typeof I=="string"?t.push(I):ed(t,I.name,I.value,o))}if(f===m&&DA(a,u,w)){var D=a.prefix||"",k=a.namespaceURI;ed(t,D?"xmlns:"+D:"xmlns",k,o),w.push({prefix:D,namespace:k})}var P=a.firstChild;if(P||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(f)){if(t.push(">"),u&&/^script$/i.test(f)){for(;P;)P.data?t.push(P.data):Lh(P,t,u,n,w.slice(),o),P=P.nextSibling;return t.push("</",f,">"),null}return{ns:w,isHTML:u,tag:m}}else return t.push("/>"),null;case PA:case Ai:return{ns:l.slice(),isHTML:u,tag:null};case Ja:return ed(t,a.name,a.value,o),null;case kl:return t.push(a.data.replace(/[<&>]/g,FA)),null;case IA:if(o&&a.data.indexOf("]]>")!==-1)throw new he(En,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case _h:if(o&&a.data.indexOf("-->")!==-1)throw new he(En,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case RA:if(o){if(!Ka.test(a.name))throw new he(En,'The doctype name "'+a.name+'" is not a valid XML Name');if(a.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(a.publicId))throw new he(En,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new he(En,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new he(En,'DocumentType internalSubset contains "]>"')}var x=a.publicId,K=a.systemId;if(t.push("<!DOCTYPE ",a.name),x)t.push(" PUBLIC ",x),K&&K!="."&&t.push(" ",K),t.push(">");else if(K&&K!=".")t.push(" SYSTEM ",K,">");else{var Oe=a.internalSubset;Oe&&t.push(" [",Oe,"]"),t.push(">")}return null;case Nh:if(o){if(!Ka.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new he(En,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new he(En,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case OA:if(o&&!Ka.test(a.nodeName))throw new he(En,'The entity reference name "'+a.nodeName+'" is not a valid XML Name');return t.push("&",a.nodeName,";"),null;default:return t.push("??",a.nodeName),null}},exit:function(a,s){s&&s.tag&&t.push("</",s.tag,">")}})}function fG(e,t,r){var n;return St(t,null,{enter:function(i,o){var a=i.cloneNode(!1);a.ownerDocument=e,a.parentNode=null,o===null?n=a:o.appendChild(a);var s=i.nodeType===Ja||r;return s?a:null}}),n}function zA(e,t,r){var n;return St(t,null,{enter:function(i,o){var a=new i.constructor;for(var s in i)if(Object.prototype.hasOwnProperty.call(i,s)){var l=i[s];typeof l!="object"&&l!=a[s]&&(a[s]=l)}i.childNodes&&(a.childNodes=new Si),a.ownerDocument=e;var u=r;switch(a.nodeType){case tn:var c=i.attributes,d=a.attributes=new td,f=c.length;d._ownerElement=a;for(var m=0;m<f;m++)a.setAttributeNode(zA(e,c.item(m),!0));break;case Ja:u=!0}return o!==null?o.appendChild(a):n=a,u?a:null}}),n}function jA(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(Ya.prototype,"length",{get:function(){return Th(this),this.$$length}}),Object.defineProperty(De.prototype,"textContent",{get:function(){if(this.nodeType===tn||this.nodeType===Ai){var e=[];return St(this,null,{enter:function(t){if(t.nodeType===tn||t.nodeType===Ai)return!0;if(t.nodeType===Nh||t.nodeType===_h)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case tn:case Ai: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}}}),jA=function(e,t,r){e["$$"+t]=r})}catch{}_i.DocumentType=ad;_i.DOMException=he;_i.DOMImplementation=xA;_i.Element=zo;_i.Node=De;_i.NodeList=Si;_i.walkDOM=St;_i.XMLSerializer=GA});var KA=v(Ul=>{"use strict";var HA=Ha().freeze;Ul.XML_ENTITIES=HA({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});Ul.HTML_ENTITIES=HA({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"});Ul.entityMap=Ul.HTML_ENTITIES});var ZA=v(Fh=>{var Vl=Ha().NAMESPACE,xh=Ha().tagNamePattern,Qa=0,no=1,Xa=2,Bl=3,Za=4,es=5,ql=6,ld=7;function ts(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,ts)}ts.prototype=new Error;ts.prototype.name=ts.name;function QA(){}QA.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),yG(t,t={}),pG(e,t,r,n,this.errorHandler),n.endDocument()}};function pG(e,t,r,n,i){function o(se){if(se>65535){se-=65536;var We=55296+(se>>10),ir=56320+(se&1023);return String.fromCharCode(We,ir)}else return String.fromCharCode(se)}function a(se){var We=se.slice(1,-1);return Object.hasOwnProperty.call(r,We)?r[We]:We.charAt(0)==="#"?o(parseInt(We.substr(1).replace("x","0x"))):(i.error("entity not found:"+se),se)}function s(se){if(se>h){var We=e.substring(h,se).replace(/&#?\w+;/g,a);f&&l(h),n.characters(We,0,se-h),h=se}}function l(se,We){for(;se>=c&&(We=d.exec(e));)u=We.index,c=u+We[0].length,f.lineNumber++;f.columnNumber=se-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,f=n.locator,m=[{currentNSMap:t}],p={},h=0;;){try{var g=e.indexOf("<",h);if(g<0){if(!e.substr(h).match(/^\s*$/)){var b=n.doc,w=b.createTextNode(e.substr(h));b.appendChild(w),n.currentElement=w}return}switch(g>h&&s(g),e.charAt(g+1)){case"/":var K=e.indexOf(">",g+3),C=e.substring(g+2,K).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),S=m.pop();K<0?(C=e.substring(g+2).replace(/[\s<].*/,""),i.error("end tag name: "+C+" is not complete:"+S.tagName),K=g+1+C.length):C.match(/\s</)?(C=C.replace(/[\s<].*/,""),i.error("end tag name: "+C+" maybe not complete"),K=g+1+C.length):/[ \t\n\r]/.test(C)&&xh.test(C.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+C+'"');var O=S.localNSMap,k=S.tagName==C,I=k||S.tagName&&S.tagName.toLowerCase()==C.toLowerCase();if(I){if(n.endElement(S.uri,S.localName,C),O)for(var D in O)Object.prototype.hasOwnProperty.call(O,D)&&n.endPrefixMapping(D);k||i.fatalError("end tag name: "+C+" is not match the current start tagName:"+S.tagName)}else m.push(S);K++;break;case"?":f&&l(g),K=vG(e,g,n);break;case"!":f&&l(g),K=bG(e,g,n,i);break;default:f&&l(g);var P=new XA,x=m[m.length-1].currentNSMap,K=mG(e,g,P,x,a,i),Oe=P.length;if(!P.closed&&gG(e,K,P.tagName,p)&&(P.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),f&&Oe){for(var Vt=JA(f,{}),Xe=0;Xe<Oe;Xe++){var Ne=P[Xe];l(Ne.offset),Ne.locator=JA(f,{})}n.locator=Vt,YA(P,n,x)&&m.push(P),n.locator=f}else YA(P,n,x)&&m.push(P);Vl.isHTML(P.uri)&&!P.closed?K=hG(e,K,P.tagName,a,n):K++}}catch(se){if(se instanceof ts)throw se;i.error("element parse error: "+se),K=-1}K>h?h=K:s(Math.max(g,h)+1)}}function JA(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function mG(e,t,r,n,i,o){function a(m,p,h){r.attributeNames.hasOwnProperty(m)&&o.fatalError("Attribute "+m+" redefined"),r.addValue(m,p.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),h)}for(var s,l,u=++t,c=Qa;;){var d=e.charAt(u);if(c===Qa&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===no)s=e.slice(t,u),c=Bl;else if(c===Xa)c=Bl;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===Bl||c===no)if(c===no&&(o.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),a(s,l,t-1),c=es;else throw new Error("attribute value no end '"+d+"' match");else if(c==Za)l=e.slice(t,u),a(s,l,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=es;else throw new Error('attribute value must after "="');break;case"/":switch(c){case Qa:r.setTagName(e.slice(t,u));case es:case ql:case ld:c=ld,r.closed=!0;case Za:case no:break;case Xa:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==Qa&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case Qa:r.setTagName(e.slice(t,u));case es:case ql:case ld:break;case Za:case no:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case Xa:c===Xa&&(l=s),c==Za?(o.warning('attribute "'+l+'" missed quot(")!'),a(s,l,t)):((!Vl.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),a(l,l,t));break;case Bl:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case Qa:r.setTagName(e.slice(t,u)),c=ql;break;case no:s=e.slice(t,u),c=Xa;break;case Za:var l=e.slice(t,u);o.warning('attribute "'+l+'" missed quot(")!!'),a(s,l,t);case es:c=ql;break}else switch(c){case Xa:var f=r.tagName;(!Vl.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=u,c=no;break;case es:o.warning('attribute space is required"'+s+'"!!');case ql:c=no,t=u;break;case Bl:c=Za,t=u;break;case ld:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function YA(e,t,r){for(var n=e.tagName,i=null,d=e.length;d--;){var o=e[d],a=o.qName,s=o.value,f=a.indexOf(":");if(f>0)var l=o.prefix=a.slice(0,f),u=a.slice(f+1),c=l==="xmlns"&&u;else u=a,l=null,c=a==="xmlns"&&"";o.localName=u,c!==!1&&(i==null&&(i={},r=Object.create(r)),r[c]=i[c]=s,o.uri=Vl.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var l=o.prefix;l&&(l==="xml"&&(o.uri=Vl.XML),l!=="xmlns"&&(o.uri=r[l||""]))}var f=n.indexOf(":");f>0?(l=e.prefix=n.slice(0,f),u=e.localName=n.slice(f+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 hG(e,t,r,n,i){if(/^(?:script|textarea)$/i.test(r)){var o=e.indexOf("</"+r+">",t),a=e.substring(t+1,o);if(/[&<]/.test(a))return/^script$/i.test(r)?(i.characters(a,0,a.length),o):(a=a.replace(/&#?\w+;/g,n),i.characters(a,0,a.length),o)}return t+1}function gG(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 yG(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function bG(e,t,r,n){var i=e.charAt(t+2);switch(i){case"-":if(e.charAt(t+3)==="-"){var o=e.indexOf("-->",t+4);return o>t?(r.comment(e,t+4,o-t-4),o+3):(n.error("Unclosed comment"),-1)}else return-1;default:if(e.substr(t+3,6)=="CDATA["){var o=e.indexOf("]]>",t+9);return r.startCDATA(),r.characters(e,t+9,o-t-9),r.endCDATA(),o+3}var a=wG(e,t),s=a.length;if(s>1&&/!doctype/i.test(a[0][0])){var l=a[1][0],u=!1,c=!1;s>3&&(/^public$/i.test(a[2][0])?(u=a[3][0],c=s>4&&a[4][0]):/^system$/i.test(a[2][0])&&(c=a[3][0]));var d=a[s-1];return r.startDTD(l,u,c),r.endDTD(),d.index+d[0].length}}return-1}function vG(e,t,r){var n=e.indexOf("?>",t);if(n){var i=e.substring(t,n).match(/^<\?(\S*)\s*([\s\S]*?)$/);if(i){var o=i[0].length;return r.processingInstruction(i[1],i[2]),n+2}else return-1}return-1}function XA(){this.attributeNames={}}XA.prototype={setTagName:function(e){if(!xh.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!xh.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 wG(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}Fh.XMLReader=QA;Fh.ParseError=ts});var aS=v(cd=>{var CG=Ha(),EG=$h(),eS=KA(),nS=ZA(),AG=EG.DOMImplementation,tS=CG.NAMESPACE,SG=nS.ParseError,NG=nS.XMLReader;function iS(e){return e.replace(/\r[\n\u0085]/g,`
`).replace(/[\r\u0085\u2028]/g,`
-`)}function JA(e){this.options=e||{locator:{}}}JA.prototype.parseFromString=function(e,t){var r=this.options,n=new hG,i=r.domBuilder||new Ul,o=r.errorHandler,a=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?WA.HTML_ENTITIES:WA.XML_ENTITIES;a&&i.setDocumentLocator(a),n.errorHandler=gG(o,i,a),n.domBuilder=r.domBuilder||i,l&&(s[""]=zA.HTML),s.xml=s.xml||zA.XML;var c=r.normalizeLineEndings||KA;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function gG(e,t,r){if(!e){if(t instanceof Ul)return t;e=t}var n={},i=e instanceof Function;r=r||{};function o(a){var s=e[a];!s&&i&&(s=e.length==2?function(l){e(a,l)}:e),n[a]=s&&function(l){s("[xmldom "+a+"] "+l+Oh(r))}||function(){}}return o("warning"),o("error"),o("fatalError"),n}function Ul(){this.cdata=!1}function Za(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}Ul.prototype={startDocument:function(){this.doc=new pG().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,r,n){var i=this.doc,o=i.createElementNS(e,r||t),a=n.length;rd(this,o),this.currentElement=o,this.locator&&Za(this.locator,o);for(var s=0;s<a;s++){var e=n.getURI(s),l=n.getValue(s),r=n.getQName(s),u=i.createAttributeNS(e,r);this.locator&&Za(n.getLocator(s),u),u.value=u.nodeValue=l,o.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&&Za(this.locator,r),rd(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=jA.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&&Za(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=jA.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&Za(this.locator,n),rd(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&&Za(this.locator,i),rd(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,Oh(this.locator))},error:function(e){console.error("[xmldom error] "+e,Oh(this.locator))},fatalError:function(e){throw new mG(e,this.locator)}};function Oh(e){if(e)return`
-@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function jA(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){Ul.prototype[e]=function(){return null}});function rd(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}nd.__DOMHandler=Ul;nd.normalizeLineEndings=KA;nd.DOMParser=JA});var es=v(id=>{var QA=Th();id.DOMImplementation=QA.DOMImplementation;id.XMLSerializer=QA.XMLSerializer;id.DOMParser=YA().DOMParser});var ZA={};Hr(ZA,{CCFControlConstants:()=>XA,CCFPropertyConstants:()=>Rh,CustomControlDataType:()=>F,CustomControlNames:()=>_i,DefaultControlNameKeys:()=>Ph,ICCModeEnum:()=>no,JSONParametersConstants:()=>Lh,LookUpType:()=>od,ManifestXMLConstants:()=>jt,NumberType:()=>ad,Usage:()=>Wo});var XA,Rh,Lh,jt,F,Ph,_i,no,Wo,od,ad,zo=k(()=>{"use strict";XA={CCID:"CustomControlId",CCName:"DisplayName",Properties:"Properties",Mode:"ControlMode",AvailableOn:"AvailableOn",CCDescription:"description-key",ImageURL:"preview-image",TypeGroup:"type-group",DataSets:"DataSets",EntityNameKey:"EntityNameKey",NameSpace:"Name",OfTypeKey:"OfType"},Rh={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"},Lh={GroupDefinition:"GroupDefinition"},jt={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"})(F||(F={}));(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"})(Ph||(Ph={}));(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"})(_i||(_i={}));(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"})(no||(no={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(Wo||(Wo={}));od=[F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.LookupSimple],ad=[F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.FP,F.Decimal]});var ts,nr,Bl=k(()=>{"use strict";ts=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}},nr=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 eS={};Hr(eS,{AttributeDataSourceType:()=>ql,AttributeDataSourceTypeMask:()=>sd,AttributePrecisionSource:()=>Vl,EntityAttributeDataSourceType:()=>jo,EntityAttributeDateTimeBehavior:()=>xh,EntityAttributeImeMode:()=>$h,EntityAttributePrecisionSource:()=>Fh,EntityAttributeRequiredLevel:()=>io,EntityAttributeType:()=>$,EntityAttributeTypeFormat:()=>W,EntityMetadataLookUpBase:()=>Ti,EntityResxKeyLookUp:()=>ld,SourceTypeMask:()=>kh});var Ti,$,W,io,jo,kh,ql,sd,$h,xh,Fh,Vl,ld,rs=k(()=>{"use strict";Bl();Ti=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return ld.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"})($||($={}));(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"})(W||(W={}));io=class extends Ti{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},jo=class e extends Ti{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?ql.Persistent:parseInt(ql[this.name])}},kh=class e extends Ti{constructor(t){super(t),t||(this.name=e.Undefined)}static get Undefined(){return"Undefined"}static get Simple(){return"Simple"}static get Related(){return"Related"}static get Logical(){return"Logical"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}static get Invalid(){return"Invalid"}GetValue(){return parseInt(sd[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(ql||(ql={}));(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"})(sd||(sd={}));$h=class e extends Ti{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Auto(){return"Auto"}static get Inactive(){return"Inactive"}static get Active(){return"Active"}static get Disabled(){return"Disabled"}},xh=class e extends Ti{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get UserLocal(){return"UserLocal"}static get DateOnly(){return"DateOnly"}static get TimeZoneIndependent(){return"TimeZoneIndependent"}},Fh=class e extends Ti{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Attribute(){return"Attribute"}static get Organization(){return"Organization"}static get Currency(){return"Currency"}GetValue(){return this.name===e.None?Vl.Currency:parseInt(Vl[this.name])}};(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(Vl||(Vl={}));ld=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new ts;return t.add($.TwoOptions,"SystemCustomization.type.bit.label"),t.add($.Customer,"SystemCustomization.type.customer.label"),t.add($.CustomerType,"SystemCustomization.type.customer.label"),t.add($.DateTime,"SystemCustomization.type.datetime.label"),t.add($.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add($.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add($.WholeNumber,"SystemCustomization.type.int.label"),t.add($.LookupType,"SystemCustomization.type.lookup.label"),t.add($.Lookup,"SystemCustomization.type.lookup.label"),t.add($.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add($.Currency,"SystemCustomization.type.money.label"),t.add($.Owner,"SystemCustomization.type.owner.label"),t.add($.OwnerType,"SystemCustomization.type.owner.label"),t.add($.PartyList,"SystemCustomization.type.partylist.label"),t.add($.PartyListType,"SystemCustomization.type.partylist.label"),t.add($.OptionSet,"SystemCustomization.type.picklist.label"),t.add($.State,"SystemCustomization.type.state.label"),t.add($.Status,"SystemCustomization.type.status.label"),t.add($.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add($.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add($.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add($.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add($.VirtualType,"SystemCustomization.type.virtual.label"),t.add($.BigInt,"SystemCustomization.type.bigint.label"),t.add($.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add($.EntityNameType,"SystemCustomization.type.entityname.label"),t.add($.Image,"SystemCustomization.type.image.label"),t.add($.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add($.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add($.LookupType,"SystemCustomization.type.lookuptype.label"),t.add($.Subject,"SystemCustomization.type.subject.label"),t.add(W.Email,"SystemCustomization.String.Format.email"),t.add(W.Text,"SystemCustomization.String.Format.text"),t.add(W.TextArea,"SystemCustomization.String.Format.textarea"),t.add(W.Url,"SystemCustomization.String.Format.url"),t.add(W.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(W.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(W.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(W.Phone,"SystemCustomization.String.Format.phone"),t.add(W.None,"SystemCustomization.Integer.Format."),t.add(W.Duration,"SystemCustomization.Integer.Format.duration"),t.add(W.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(W.Language,"SystemCustomization.Integer.Format.language"),t.add(W.Locale,"SystemCustomization.Integer.Format.language"),t.add(W.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(W.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(W.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(jo.Persistent,"SystemCustomization.String.Source.persistent"),t.add(jo.Calculated,"SystemCustomization.String.Source.calculated"),t.add(jo.Rollup,"SystemCustomization.String.Source.rollup"),t.add(jo.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var Uh=v(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.parsePcfManifest=it.parseControlElement=it.parseManifestRoot=it.firstLevel=it.attr=it.elementChildren=it.manifestTypesForColumn=it.DEFAULT_TYPE_GROUPS=void 0;var yG=es(),H=(zo(),Fr(ZA)),we=(rs(),Fr(eS));it.DEFAULT_TYPE_GROUPS={numbers:[H.CustomControlDataType.WholeNone,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.Currency],text:[H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.Multiple],lookup:[H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding],dates:[H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime],allFields:[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.WholeNone,H.CustomControlDataType.WholeDuration,H.CustomControlDataType.WholeTimeZone,H.CustomControlDataType.WholeLanguage,H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding,H.CustomControlDataType.Multiple,H.CustomControlDataType.OptionSet,H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.SingleLineEmail,H.CustomControlDataType.SingleLineURL,H.CustomControlDataType.SingleLineTickerSymbol,H.CustomControlDataType.SingleLinePhone]};var bG="Phone";function vG(e,t,r){switch(e){case we.EntityAttributeType.TwoOptions:return[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.Boolean];case we.EntityAttributeType.Customer:case we.EntityAttributeType.CustomerType:return[H.CustomControlDataType.LookupCustomer];case we.EntityAttributeType.DateTime:return t===we.EntityAttributeTypeFormat.DateAndTime?[H.CustomControlDataType.DateAndTimeDateAndTime]:[H.CustomControlDataType.DateAndTimeDateOnly];case we.EntityAttributeType.DecimalNumber:return[H.CustomControlDataType.Decimal];case we.EntityAttributeType.FloatingPointNumber:return[H.CustomControlDataType.FP];case we.EntityAttributeType.File:return[H.CustomControlDataType.File];case we.EntityAttributeType.Image:return[H.CustomControlDataType.Image];case we.EntityAttributeType.WholeNumber:return t===we.EntityAttributeTypeFormat.Duration?[H.CustomControlDataType.WholeDuration]:t===we.EntityAttributeTypeFormat.Language?[H.CustomControlDataType.WholeLanguage]:t===we.EntityAttributeTypeFormat.TimeZone?[H.CustomControlDataType.WholeTimeZone]:[H.CustomControlDataType.WholeNone];case we.EntityAttributeType.LookupType:case we.EntityAttributeType.Lookup:return t===we.EntityAttributeTypeFormat.Regarding?[H.CustomControlDataType.LookupRegarding]:[H.CustomControlDataType.LookupSimple];case we.EntityAttributeType.MultipleLineofText:return[H.CustomControlDataType.Multiple];case we.EntityAttributeType.Currency:return[H.CustomControlDataType.Currency];case we.EntityAttributeType.Owner:case we.EntityAttributeType.OwnerType:return[H.CustomControlDataType.LookupOwner];case we.EntityAttributeType.PartyList:case we.EntityAttributeType.PartyListType:return[H.CustomControlDataType.LookupPartyList];case we.EntityAttributeType.Status:case we.EntityAttributeType.OptionSet:return[H.CustomControlDataType.OptionSet];case we.EntityAttributeType.SingleLineofText:switch(t){case we.EntityAttributeTypeFormat.Email:return[H.CustomControlDataType.SingleLineEmail];case we.EntityAttributeTypeFormat.Phone:return[H.CustomControlDataType.SingleLinePhone];case we.EntityAttributeTypeFormat.Text:return r===bG?[H.CustomControlDataType.SingleLinePhone]:[H.CustomControlDataType.SingleLineText];case we.EntityAttributeTypeFormat.TextArea:return[H.CustomControlDataType.SingleLineTextArea];case we.EntityAttributeTypeFormat.TickerSymbol:return[H.CustomControlDataType.SingleLineTickerSymbol];case we.EntityAttributeTypeFormat.Url:return[H.CustomControlDataType.SingleLineURL];default:return[H.CustomControlDataType.SingleLineText]}case we.EntityAttributeType.MultiSelectOptionSet:return[H.CustomControlDataType.MultiSelectOptionSet];default:return null}}it.manifestTypesForColumn=vG;function Mh(e){let t=[],r=e.childNodes;for(let n=0;n<r.length;n+=1)r[n].nodeType===1&&t.push(r[n]);return t}it.elementChildren=Mh;function En(e,t){return e.hasAttribute(t)?e.getAttribute(t):null}it.attr=En;function jn(e,...t){return Mh(e).filter(r=>t.includes(r.tagName))}it.firstLevel=jn;function wG(e){let t=new Map;for(let r of jn(e,"type-group"))t.set(String(En(r,"name")),jn(r,"type").map(n=>String(n.textContent)));for(let[r,n]of t)t.set(r,n.sort());return t}function CG(e){let t=e.getElementsByTagName("AvailableOn")[0];if(!t)return{web:!0,phone:!0,tablet:!0};let r=new Set(Mh(t).map(n=>n.tagName));return{web:r.has("web"),phone:r.has("phone"),tablet:r.has("tablet")}}var EG={input:"input",bound:"bound",output:"output"};function AG(e,t,r){let n=En(e,"usage"),i=n!==null&&EG[n]||"input",o=En(e,"default-value"),a=jn(e,"value").map(m=>{let p={name:En(m,"name"),value:String(m.textContent),isDefault:En(m,"default")==="true"};return p.isDefault&&(o=p.value),p}),s=En(e,"of-type-group"),l=s!==null?t.get(s):void 0,u=s!==null&&Object.prototype.hasOwnProperty.call(it.DEFAULT_TYPE_GROUPS,s)?it.DEFAULT_TYPE_GROUPS[s]:void 0,c=l?[...l]:u?[...u]:[],d=En(e,"of-type"),f=d!==null?d:c.length>0?c[0]:null;return{name:En(e,"name"),usage:i,ofType:d,typeGroupName:s,ofTypeGroup:c,defaultType:f||void 0,required:En(e,"required")==="true",hidden:En(e,"hidden")==="true",defaultValue:o,enumValues:a,isPrimary:r&&i==="bound"}}function tS(e){var t;let r=[],n=a=>s=>r.push(`${a}: ${s}`),i=new yG.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the control manifest does not parse cleanly${r.length>0?` (${r[0]})`:""}`);return o}it.parseManifestRoot=tS;function rS(e){let t=jn(tS(e),"control")[0];if(!t)throw new Error("the control manifest has no <control> element");return t}it.parseControlElement=rS;function SG(e){let t=rS(e),r=wG(t),n=jn(t,"data-set"),i=jn(t,"property"),o=jn(t,"groups"),a=[],s=!1;for(let u of i){let c=AG(u,r,n.length===0&&!s);s=s||c.isPrimary,a.push(c)}let l=n.length>0||(a.length>0?a[0].usage==="bound":o.some(u=>jn(u,"group").some(c=>jn(c,"data-set","property").length>0)));return{properties:a,hasDataset:n.length>0,hasGroups:o.length>0,isBound:l,availableOn:CG(t)}}it.parsePcfManifest=SG});var iS=v(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});is.readPcfColumn=is.readControlManifest=void 0;var ns=se(),NG=Uh();function Bh(e,t,r){var n;let i=(n=r?.error)===null||n===void 0?void 0:n.message;return new Error(`${e}: HTTP ${t}${typeof i=="string"?` ${i}`:""}`)}async function _G(e,t){var r;let n="/customcontrols"+(0,ns.odataQuery)([["$select","name,manifest"],["$filter",`name eq '${(0,ns.odataLiteral)(t)}'`]]);try{let i=await e.get(n);if(i.status<200||i.status>=300)return{kind:"unavailable",error:Bh(`reading control "${t}"`,i.status,i.body)};let o=(r=i.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(o)||o.some(l=>l===null||typeof l!="object"))return{kind:"unavailable",error:new Error(`reading control "${t}": the answer is unreadable \u2014 expected an OData 'value' array of rows`)};let a=o;if(a.length===0)return{kind:"missing"};if(a.length>1)return{kind:"ambiguous"};let s=a[0].manifest;return typeof s!="string"?{kind:"unavailable",error:new Error(`control "${t}" has no manifest`)}:{kind:"found",value:(0,NG.parsePcfManifest)(s)}}catch(i){return{kind:"unavailable",error:i instanceof Error?i:new Error(String(i))}}}is.readControlManifest=_G;var TG=new Map([["StringType",{cast:"StringAttributeMetadata",select:"Format,FormatName"}],["MemoType",{cast:"MemoAttributeMetadata",select:"Format"}],["IntegerType",{cast:"IntegerAttributeMetadata",select:"Format"}],["DateTimeType",{cast:"DateTimeAttributeMetadata",select:"Format"}],["LookupType",{cast:"LookupAttributeMetadata",select:"Format"}]]);function nS(e){let t=e?.Value;return typeof t=="string"?t:void 0}async function DG(e,t,r,n){var i;let o=`/EntityDefinitions(LogicalName='${(0,ns.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,ns.odataPathLiteral)(r)}')`,a=n?.requireCreateEligibility===!0;try{let s=await e.get(o+(0,ns.odataQuery)([["$select",`LogicalName,AttributeType,AttributeTypeName,IsValidForForm,IsPrimaryId${a?",IsValidForCreate":""}`]]));if(s.status===404)return{kind:"missing"};if(s.status<200||s.status>=300)return{kind:"unavailable",error:Bh(`reading column "${r}"`,s.status,s.body)};let l=(i=s.body)!==null&&i!==void 0?i:{},u=nS(l.AttributeTypeName);if(!u)return{kind:"unavailable",error:new Error(`column "${r}" has no AttributeTypeName`)};if(a&&typeof l.IsValidForCreate!="boolean")return{kind:"unavailable",error:new Error(`column "${r}" has no IsValidForCreate`)};let c={logicalName:typeof l.LogicalName=="string"?l.LogicalName:r,attributeTypeName:u,isValidForForm:l.IsValidForForm===!0,isPrimaryId:l.IsPrimaryId===!0,...a?{isValidForCreate:l.IsValidForCreate}:{}},d=TG.get(u);if(d){let f=await e.get(`${o}/Microsoft.Dynamics.CRM.${d.cast}`+(0,ns.odataQuery)([["$select",d.select]]));if(f.status<200||f.status>=300)return{kind:"unavailable",error:Bh(`reading the format of column "${r}"`,f.status,f.body)};let m=f.body;if(m===null||typeof m!="object"||m.Format!==null&&typeof m.Format!="string")return{kind:"unavailable",error:new Error(`reading the format of column "${r}": the answer is unreadable \u2014 expected its Format (a string or null)`)};typeof m.Format=="string"&&(c.format=m.Format);let p=nS(m.FormatName);p&&(c.formatName=p)}return{kind:"found",value:c}}catch(s){return{kind:"unavailable",error:s instanceof Error?s:new Error(String(s))}}}is.readPcfColumn=DG});var Ho=v(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});ud.DEFAULT_LCID=void 0;ud.DEFAULT_LCID=1033});var dt=v(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.assignMissingIds=Hn.pointerTouchesValueMap=Hn.isValueMapKey=Hn.newId=void 0;var IG=$a();function oS(){return globalThis.crypto.randomUUID().toLowerCase()}Hn.newId=oS;function OG(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Vh=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData","customControl"]);function PG(e){return Vh.has(e)}Hn.isValueMapKey=PG;function RG(e){return IG.JsonPointer.parse(e).some(t=>Vh.has(t))}Hn.pointerTouchesValueMap=RG;function LG(e){return qh(e),e}Hn.assignMissingIds=LG;function qh(e){if(Array.isArray(e)){e.forEach(t=>qh(t));return}if(OG(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=oS());for(let t of Object.keys(e))t==="id"||Vh.has(t)||qh(e[t])}}});var Wl=v(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.sendChangeSet=Er.partResponse=Er.postChangeSet=Er.parseChangeSetParts=Er.parseChangeSetStatuses=Er.renderChangeSet=void 0;var oo=Q(),Gh=ye(),aS=dt(),Gl=se();function Wh(e,t){let r=`batch_${(0,aS.newId)()}`,n=`changeset_${(0,aS.newId)()}`,i=t.map((s,l)=>String(l+1)),o=t.map((s,l)=>{var u,c;if(s.rawBody!==void 0&&s.contentType===void 0)throw new oo.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a raw body but no Content-Type`);let d=(u=s.rawBody)!==null&&u!==void 0?u:s.body===void 0?void 0:JSON.stringify(s.body);if(d!==void 0&&(d.includes(`--${n}`)||d.includes(`--${r}`)))throw new oo.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,Gl.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,Gl.assertNoControlChars)(s.etag,"batch operation etag");let f=Object.entries((c=s.headers)!==null&&c!==void 0?c:{});for(let[m,p]of f)if((0,Gl.assertNoControlChars)(m,"batch operation header name"),(0,Gl.assertNoControlChars)(p,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(m))throw new oo.InvalidArgumentError(`batch operation header name '${m}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,Gl.assertNoControlChars)(s.contentType,"batch operation content type"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...d===void 0?[]:[`Content-Type: ${s.rawBody!==void 0?s.contentType:"application/json;type=entry"}`],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],...f.map(([m,p])=>`${m}: ${p}`),"",...d===void 0?[]:[d]].join(`\r
+`)}function oS(e){this.options=e||{locator:{}}}oS.prototype.parseFromString=function(e,t){var r=this.options,n=new NG,i=r.domBuilder||new Gl,o=r.errorHandler,a=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?eS.HTML_ENTITIES:eS.XML_ENTITIES;a&&i.setDocumentLocator(a),n.errorHandler=_G(o,i,a),n.domBuilder=r.domBuilder||i,l&&(s[""]=tS.HTML),s.xml=s.xml||tS.XML;var c=r.normalizeLineEndings||iS;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function _G(e,t,r){if(!e){if(t instanceof Gl)return t;e=t}var n={},i=e instanceof Function;r=r||{};function o(a){var s=e[a];!s&&i&&(s=e.length==2?function(l){e(a,l)}:e),n[a]=s&&function(l){s("[xmldom "+a+"] "+l+Mh(r))}||function(){}}return o("warning"),o("error"),o("fatalError"),n}function Gl(){this.cdata=!1}function rs(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}Gl.prototype={startDocument:function(){this.doc=new AG().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,r,n){var i=this.doc,o=i.createElementNS(e,r||t),a=n.length;ud(this,o),this.currentElement=o,this.locator&&rs(this.locator,o);for(var s=0;s<a;s++){var e=n.getURI(s),l=n.getValue(s),r=n.getQName(s),u=i.createAttributeNS(e,r);this.locator&&rs(n.getLocator(s),u),u.value=u.nodeValue=l,o.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&&rs(this.locator,r),ud(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=rS.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&&rs(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=rS.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&rs(this.locator,n),ud(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&&rs(this.locator,i),ud(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,Mh(this.locator))},error:function(e){console.error("[xmldom error] "+e,Mh(this.locator))},fatalError:function(e){throw new SG(e,this.locator)}};function Mh(e){if(e)return`
+@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function rS(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){Gl.prototype[e]=function(){return null}});function ud(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}cd.__DOMHandler=Gl;cd.normalizeLineEndings=iS;cd.DOMParser=oS});var ns=v(dd=>{var sS=$h();dd.DOMImplementation=sS.DOMImplementation;dd.XMLSerializer=sS.XMLSerializer;dd.DOMParser=aS().DOMParser});var uS={};Jr(uS,{CCFControlConstants:()=>lS,CCFPropertyConstants:()=>Bh,CustomControlDataType:()=>F,CustomControlNames:()=>Ti,DefaultControlNameKeys:()=>Uh,ICCModeEnum:()=>io,JSONParametersConstants:()=>qh,LookUpType:()=>fd,ManifestXMLConstants:()=>Ht,NumberType:()=>pd,Usage:()=>jo});var lS,Bh,qh,Ht,F,Uh,Ti,io,jo,fd,pd,Ho=L(()=>{"use strict";lS={CCID:"CustomControlId",CCName:"DisplayName",Properties:"Properties",Mode:"ControlMode",AvailableOn:"AvailableOn",CCDescription:"description-key",ImageURL:"preview-image",TypeGroup:"type-group",DataSets:"DataSets",EntityNameKey:"EntityNameKey",NameSpace:"Name",OfTypeKey:"OfType"},Bh={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"},qh={GroupDefinition:"GroupDefinition"},Ht={Control:"control",Resources:"resources",DisplayNameKey:"display-name-key",descriptionKey:"description-key",value:"value",name:"name",defaultKey:"default",groups:"groups",group:"group",property:"property",hidden:"hidden",required:"required",typeGroup:"type-group",type:"type",usage:"usage",ofType:"of-type",ofTypeGroup:"of-type-group",ImageURL:"preview-image",DefaultValue:"default-value",static:"static",dataset:"data-set",propertySet:"property-set",initialDatasetFetch:"initial-data-set-fetch",editable:"editable",cdsDatasetOptions:"cds-data-set-options",allowDefaultSelectedItems:"allow-default-selected-items",resettable:"resettable",isGroup:"isGroup",entityName:"entityname"};(function(e){e.Boolean="Boolean",e.Currency="Currency",e.DateAndTimeDateAndTime="DateAndTime.DateAndTime",e.DateAndTimeDateOnly="DateAndTime.DateOnly",e.Decimal="Decimal",e.Enum="Enum",e.FP="FP",e.File="File",e.Guid="Guid",e.Image="Image",e.LookupCustomer="Lookup.Customer",e.LookupOwner="Lookup.Owner",e.LookupPartyList="Lookup.PartyList",e.LookupRegarding="Lookup.Regarding",e.LookupSimple="Lookup.Simple",e.Multiple="Multiple",e.MultiSelectOptionSet="MultiSelectOptionSet",e.OptionSet="OptionSet",e.SingleLineEmail="SingleLine.Email",e.SingleLinePhone="SingleLine.Phone",e.SingleLineText="SingleLine.Text",e.SingleLineTextArea="SingleLine.TextArea",e.SingleLineTickerSymbol="SingleLine.Ticker",e.SingleLineURL="SingleLine.URL",e.TwoOptions="TwoOptions",e.WholeDuration="Whole.Duration",e.WholeLanguage="Whole.Language",e.WholeNone="Whole.None",e.WholeTimeZone="Whole.TimeZone",e.BusinessProcessFlow="BusinessProcessFlow",e.CardForm="Form.Card",e.Dashboard="Dashboard",e.FormMain="Form.Main",e.Grid="Grid",e.PowerBIReport="PowerBI.Report",e.QuickForm="Form.QuickForm",e.Search="Search",e.SearchWidget="SearchWidget",e.TimelineWall="TimelineWall",e.UnboundCustomControl="Unbound",e.WebResourceHtmlControl="WebResource.HTML"})(F||(F={}));(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"})(Uh||(Uh={}));(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"})(Ti||(Ti={}));(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"})(io||(io={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(jo||(jo={}));fd=[F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.LookupSimple],pd=[F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.FP,F.Decimal]});var is,ar,Wl=L(()=>{"use strict";is=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}},ar=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 cS={};Jr(cS,{AttributeDataSourceType:()=>zl,AttributeDataSourceTypeMask:()=>md,AttributePrecisionSource:()=>jl,EntityAttributeDataSourceType:()=>Ko,EntityAttributeDateTimeBehavior:()=>Wh,EntityAttributeImeMode:()=>Gh,EntityAttributePrecisionSource:()=>zh,EntityAttributeRequiredLevel:()=>oo,EntityAttributeType:()=>$,EntityAttributeTypeFormat:()=>W,EntityMetadataLookUpBase:()=>Di,EntityResxKeyLookUp:()=>hd,SourceTypeMask:()=>Vh});var Di,$,W,oo,Ko,Vh,zl,md,Gh,Wh,zh,jl,hd,os=L(()=>{"use strict";Wl();Di=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return hd.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"})($||($={}));(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"})(W||(W={}));oo=class extends Di{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},Ko=class e extends Di{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?zl.Persistent:parseInt(zl[this.name])}},Vh=class e extends Di{constructor(t){super(t),t||(this.name=e.Undefined)}static get Undefined(){return"Undefined"}static get Simple(){return"Simple"}static get Related(){return"Related"}static get Logical(){return"Logical"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}static get Invalid(){return"Invalid"}GetValue(){return parseInt(md[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(zl||(zl={}));(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"})(md||(md={}));Gh=class e extends Di{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Auto(){return"Auto"}static get Inactive(){return"Inactive"}static get Active(){return"Active"}static get Disabled(){return"Disabled"}},Wh=class e extends Di{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get UserLocal(){return"UserLocal"}static get DateOnly(){return"DateOnly"}static get TimeZoneIndependent(){return"TimeZoneIndependent"}},zh=class e extends Di{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Attribute(){return"Attribute"}static get Organization(){return"Organization"}static get Currency(){return"Currency"}GetValue(){return this.name===e.None?jl.Currency:parseInt(jl[this.name])}};(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(jl||(jl={}));hd=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new is;return t.add($.TwoOptions,"SystemCustomization.type.bit.label"),t.add($.Customer,"SystemCustomization.type.customer.label"),t.add($.CustomerType,"SystemCustomization.type.customer.label"),t.add($.DateTime,"SystemCustomization.type.datetime.label"),t.add($.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add($.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add($.WholeNumber,"SystemCustomization.type.int.label"),t.add($.LookupType,"SystemCustomization.type.lookup.label"),t.add($.Lookup,"SystemCustomization.type.lookup.label"),t.add($.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add($.Currency,"SystemCustomization.type.money.label"),t.add($.Owner,"SystemCustomization.type.owner.label"),t.add($.OwnerType,"SystemCustomization.type.owner.label"),t.add($.PartyList,"SystemCustomization.type.partylist.label"),t.add($.PartyListType,"SystemCustomization.type.partylist.label"),t.add($.OptionSet,"SystemCustomization.type.picklist.label"),t.add($.State,"SystemCustomization.type.state.label"),t.add($.Status,"SystemCustomization.type.status.label"),t.add($.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add($.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add($.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add($.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add($.VirtualType,"SystemCustomization.type.virtual.label"),t.add($.BigInt,"SystemCustomization.type.bigint.label"),t.add($.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add($.EntityNameType,"SystemCustomization.type.entityname.label"),t.add($.Image,"SystemCustomization.type.image.label"),t.add($.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add($.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add($.LookupType,"SystemCustomization.type.lookuptype.label"),t.add($.Subject,"SystemCustomization.type.subject.label"),t.add(W.Email,"SystemCustomization.String.Format.email"),t.add(W.Text,"SystemCustomization.String.Format.text"),t.add(W.TextArea,"SystemCustomization.String.Format.textarea"),t.add(W.Url,"SystemCustomization.String.Format.url"),t.add(W.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(W.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(W.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(W.Phone,"SystemCustomization.String.Format.phone"),t.add(W.None,"SystemCustomization.Integer.Format."),t.add(W.Duration,"SystemCustomization.Integer.Format.duration"),t.add(W.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(W.Language,"SystemCustomization.Integer.Format.language"),t.add(W.Locale,"SystemCustomization.Integer.Format.language"),t.add(W.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(W.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(W.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(Ko.Persistent,"SystemCustomization.String.Source.persistent"),t.add(Ko.Calculated,"SystemCustomization.String.Source.calculated"),t.add(Ko.Rollup,"SystemCustomization.String.Source.rollup"),t.add(Ko.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var Hh=v(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.parsePcfManifest=ot.parseControlElement=ot.parseManifestRoot=ot.firstLevel=ot.attr=ot.elementChildren=ot.manifestTypesForColumn=ot.DEFAULT_TYPE_GROUPS=void 0;var TG=ns(),H=(Ho(),Br(uS)),we=(os(),Br(cS));ot.DEFAULT_TYPE_GROUPS={numbers:[H.CustomControlDataType.WholeNone,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.Currency],text:[H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.Multiple],lookup:[H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding],dates:[H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime],allFields:[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.WholeNone,H.CustomControlDataType.WholeDuration,H.CustomControlDataType.WholeTimeZone,H.CustomControlDataType.WholeLanguage,H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding,H.CustomControlDataType.Multiple,H.CustomControlDataType.OptionSet,H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.SingleLineEmail,H.CustomControlDataType.SingleLineURL,H.CustomControlDataType.SingleLineTickerSymbol,H.CustomControlDataType.SingleLinePhone]};var DG="Phone";function IG(e,t,r){switch(e){case we.EntityAttributeType.TwoOptions:return[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.Boolean];case we.EntityAttributeType.Customer:case we.EntityAttributeType.CustomerType:return[H.CustomControlDataType.LookupCustomer];case we.EntityAttributeType.DateTime:return t===we.EntityAttributeTypeFormat.DateAndTime?[H.CustomControlDataType.DateAndTimeDateAndTime]:[H.CustomControlDataType.DateAndTimeDateOnly];case we.EntityAttributeType.DecimalNumber:return[H.CustomControlDataType.Decimal];case we.EntityAttributeType.FloatingPointNumber:return[H.CustomControlDataType.FP];case we.EntityAttributeType.File:return[H.CustomControlDataType.File];case we.EntityAttributeType.Image:return[H.CustomControlDataType.Image];case we.EntityAttributeType.WholeNumber:return t===we.EntityAttributeTypeFormat.Duration?[H.CustomControlDataType.WholeDuration]:t===we.EntityAttributeTypeFormat.Language?[H.CustomControlDataType.WholeLanguage]:t===we.EntityAttributeTypeFormat.TimeZone?[H.CustomControlDataType.WholeTimeZone]:[H.CustomControlDataType.WholeNone];case we.EntityAttributeType.LookupType:case we.EntityAttributeType.Lookup:return t===we.EntityAttributeTypeFormat.Regarding?[H.CustomControlDataType.LookupRegarding]:[H.CustomControlDataType.LookupSimple];case we.EntityAttributeType.MultipleLineofText:return[H.CustomControlDataType.Multiple];case we.EntityAttributeType.Currency:return[H.CustomControlDataType.Currency];case we.EntityAttributeType.Owner:case we.EntityAttributeType.OwnerType:return[H.CustomControlDataType.LookupOwner];case we.EntityAttributeType.PartyList:case we.EntityAttributeType.PartyListType:return[H.CustomControlDataType.LookupPartyList];case we.EntityAttributeType.Status:case we.EntityAttributeType.OptionSet:return[H.CustomControlDataType.OptionSet];case we.EntityAttributeType.SingleLineofText:switch(t){case we.EntityAttributeTypeFormat.Email:return[H.CustomControlDataType.SingleLineEmail];case we.EntityAttributeTypeFormat.Phone:return[H.CustomControlDataType.SingleLinePhone];case we.EntityAttributeTypeFormat.Text:return r===DG?[H.CustomControlDataType.SingleLinePhone]:[H.CustomControlDataType.SingleLineText];case we.EntityAttributeTypeFormat.TextArea:return[H.CustomControlDataType.SingleLineTextArea];case we.EntityAttributeTypeFormat.TickerSymbol:return[H.CustomControlDataType.SingleLineTickerSymbol];case we.EntityAttributeTypeFormat.Url:return[H.CustomControlDataType.SingleLineURL];default:return[H.CustomControlDataType.SingleLineText]}case we.EntityAttributeType.MultiSelectOptionSet:return[H.CustomControlDataType.MultiSelectOptionSet];default:return null}}ot.manifestTypesForColumn=IG;function jh(e){let t=[],r=e.childNodes;for(let n=0;n<r.length;n+=1)r[n].nodeType===1&&t.push(r[n]);return t}ot.elementChildren=jh;function An(e,t){return e.hasAttribute(t)?e.getAttribute(t):null}ot.attr=An;function Hn(e,...t){return jh(e).filter(r=>t.includes(r.tagName))}ot.firstLevel=Hn;function OG(e){let t=new Map;for(let r of Hn(e,"type-group"))t.set(String(An(r,"name")),Hn(r,"type").map(n=>String(n.textContent)));for(let[r,n]of t)t.set(r,n.sort());return t}function PG(e){let t=e.getElementsByTagName("AvailableOn")[0];if(!t)return{web:!0,phone:!0,tablet:!0};let r=new Set(jh(t).map(n=>n.tagName));return{web:r.has("web"),phone:r.has("phone"),tablet:r.has("tablet")}}var RG={input:"input",bound:"bound",output:"output"};function kG(e,t,r){let n=An(e,"usage"),i=n!==null&&RG[n]||"input",o=An(e,"default-value"),a=Hn(e,"value").map(m=>{let p={name:An(m,"name"),value:String(m.textContent),isDefault:An(m,"default")==="true"};return p.isDefault&&(o=p.value),p}),s=An(e,"of-type-group"),l=s!==null?t.get(s):void 0,u=s!==null&&Object.prototype.hasOwnProperty.call(ot.DEFAULT_TYPE_GROUPS,s)?ot.DEFAULT_TYPE_GROUPS[s]:void 0,c=l?[...l]:u?[...u]:[],d=An(e,"of-type"),f=d!==null?d:c.length>0?c[0]:null;return{name:An(e,"name"),usage:i,ofType:d,typeGroupName:s,ofTypeGroup:c,defaultType:f||void 0,required:An(e,"required")==="true",hidden:An(e,"hidden")==="true",defaultValue:o,enumValues:a,isPrimary:r&&i==="bound"}}function dS(e){var t;let r=[],n=a=>s=>r.push(`${a}: ${s}`),i=new TG.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the control manifest does not parse cleanly${r.length>0?` (${r[0]})`:""}`);return o}ot.parseManifestRoot=dS;function fS(e){let t=Hn(dS(e),"control")[0];if(!t)throw new Error("the control manifest has no <control> element");return t}ot.parseControlElement=fS;function LG(e){let t=fS(e),r=OG(t),n=Hn(t,"data-set"),i=Hn(t,"property"),o=Hn(t,"groups"),a=[],s=!1;for(let u of i){let c=kG(u,r,n.length===0&&!s);s=s||c.isPrimary,a.push(c)}let l=n.length>0||(a.length>0?a[0].usage==="bound":o.some(u=>Hn(u,"group").some(c=>Hn(c,"data-set","property").length>0)));return{properties:a,hasDataset:n.length>0,hasGroups:o.length>0,isBound:l,availableOn:PG(t)}}ot.parsePcfManifest=LG});var mS=v(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.readPcfColumn=ss.readControlManifest=void 0;var as=le(),$G=Hh();function Kh(e,t,r){var n;let i=(n=r?.error)===null||n===void 0?void 0:n.message;return new Error(`${e}: HTTP ${t}${typeof i=="string"?` ${i}`:""}`)}async function xG(e,t){var r;let n="/customcontrols"+(0,as.odataQuery)([["$select","name,manifest"],["$filter",`name eq '${(0,as.odataLiteral)(t)}'`]]);try{let i=await e.get(n);if(i.status<200||i.status>=300)return{kind:"unavailable",error:Kh(`reading control "${t}"`,i.status,i.body)};let o=(r=i.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(o)||o.some(l=>l===null||typeof l!="object"))return{kind:"unavailable",error:new Error(`reading control "${t}": the answer is unreadable \u2014 expected an OData 'value' array of rows`)};let a=o;if(a.length===0)return{kind:"missing"};if(a.length>1)return{kind:"ambiguous"};let s=a[0].manifest;return typeof s!="string"?{kind:"unavailable",error:new Error(`control "${t}" has no manifest`)}:{kind:"found",value:(0,$G.parsePcfManifest)(s)}}catch(i){return{kind:"unavailable",error:i instanceof Error?i:new Error(String(i))}}}ss.readControlManifest=xG;var FG=new Map([["StringType",{cast:"StringAttributeMetadata",select:"Format,FormatName"}],["MemoType",{cast:"MemoAttributeMetadata",select:"Format"}],["IntegerType",{cast:"IntegerAttributeMetadata",select:"Format"}],["DateTimeType",{cast:"DateTimeAttributeMetadata",select:"Format"}],["LookupType",{cast:"LookupAttributeMetadata",select:"Format"}]]);function pS(e){let t=e?.Value;return typeof t=="string"?t:void 0}async function MG(e,t,r,n){var i;let o=`/EntityDefinitions(LogicalName='${(0,as.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,as.odataPathLiteral)(r)}')`,a=n?.requireCreateEligibility===!0;try{let s=await e.get(o+(0,as.odataQuery)([["$select",`LogicalName,AttributeType,AttributeTypeName,IsValidForForm,IsPrimaryId${a?",IsValidForCreate":""}`]]));if(s.status===404)return{kind:"missing"};if(s.status<200||s.status>=300)return{kind:"unavailable",error:Kh(`reading column "${r}"`,s.status,s.body)};let l=(i=s.body)!==null&&i!==void 0?i:{},u=pS(l.AttributeTypeName);if(!u)return{kind:"unavailable",error:new Error(`column "${r}" has no AttributeTypeName`)};if(a&&typeof l.IsValidForCreate!="boolean")return{kind:"unavailable",error:new Error(`column "${r}" has no IsValidForCreate`)};let c={logicalName:typeof l.LogicalName=="string"?l.LogicalName:r,attributeTypeName:u,isValidForForm:l.IsValidForForm===!0,isPrimaryId:l.IsPrimaryId===!0,...a?{isValidForCreate:l.IsValidForCreate}:{}},d=FG.get(u);if(d){let f=await e.get(`${o}/Microsoft.Dynamics.CRM.${d.cast}`+(0,as.odataQuery)([["$select",d.select]]));if(f.status<200||f.status>=300)return{kind:"unavailable",error:Kh(`reading the format of column "${r}"`,f.status,f.body)};let m=f.body;if(m===null||typeof m!="object"||m.Format!==null&&typeof m.Format!="string")return{kind:"unavailable",error:new Error(`reading the format of column "${r}": the answer is unreadable \u2014 expected its Format (a string or null)`)};typeof m.Format=="string"&&(c.format=m.Format);let p=pS(m.FormatName);p&&(c.formatName=p)}return{kind:"found",value:c}}catch(s){return{kind:"unavailable",error:s instanceof Error?s:new Error(String(s))}}}ss.readPcfColumn=MG});var Jo=v(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});gd.DEFAULT_LCID=void 0;gd.DEFAULT_LCID=1033});var pt=v(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.assignMissingIds=Kn.pointerTouchesValueMap=Kn.isValueMapKey=Kn.newId=void 0;var UG=Ma();function hS(){return globalThis.crypto.randomUUID().toLowerCase()}Kn.newId=hS;function BG(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Yh=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData","customControl"]);function qG(e){return Yh.has(e)}Kn.isValueMapKey=qG;function VG(e){return UG.JsonPointer.parse(e).some(t=>Yh.has(t))}Kn.pointerTouchesValueMap=VG;function GG(e){return Jh(e),e}Kn.assignMissingIds=GG;function Jh(e){if(Array.isArray(e)){e.forEach(t=>Jh(t));return}if(BG(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=hS());for(let t of Object.keys(e))t==="id"||Yh.has(t)||Jh(e[t])}}});var Kl=v(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.sendChangeSet=Kt.isChangeSetLockRefusal=Kt.partResponse=Kt.postChangeSet=Kt.parseChangeSetParts=Kt.parseChangeSetStatuses=Kt.renderChangeSet=void 0;var Ii=Q(),Yo=ye(),gS=pt(),Hl=le();function Qh(e,t){let r=`batch_${(0,gS.newId)()}`,n=`changeset_${(0,gS.newId)()}`,i=t.map((s,l)=>String(l+1)),o=t.map((s,l)=>{var u,c;if(s.rawBody!==void 0&&s.contentType===void 0)throw new Ii.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a raw body but no Content-Type`);let d=(u=s.rawBody)!==null&&u!==void 0?u:s.body===void 0?void 0:JSON.stringify(s.body);if(d!==void 0&&(d.includes(`--${n}`)||d.includes(`--${r}`)))throw new Ii.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,Hl.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,Hl.assertNoControlChars)(s.etag,"batch operation etag");let f=Object.entries((c=s.headers)!==null&&c!==void 0?c:{});for(let[m,p]of f)if((0,Hl.assertNoControlChars)(m,"batch operation header name"),(0,Hl.assertNoControlChars)(p,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(m))throw new Ii.InvalidArgumentError(`batch operation header name '${m}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,Hl.assertNoControlChars)(s.contentType,"batch operation content type"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...d===void 0?[]:[`Content-Type: ${s.rawBody!==void 0?s.contentType:"application/json;type=entry"}`],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],...f.map(([m,p])=>`${m}: ${p}`),"",...d===void 0?[]:[d]].join(`\r
`)});return{body:[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...o,`--${n}--`,`--${r}--`,""].join(`\r
-`),batchId:r,contentIds:i}}Er.renderChangeSet=Wh;function sS(e,t){var r;return(r=zh(e,t))===null||r===void 0?void 0:r.map(n=>n.status)}Er.parseChangeSetStatuses=sS;function zh(e,t){var r,n,i,o;if(typeof e!="string"||e.length===0)return;let a=(r=/^--(\S+)\r?\n/.exec(e))===null||r===void 0?void 0:r[1];if(a===void 0||!e.trimEnd().endsWith(`--${a}--`))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===a)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 f of l.slice(1)){if(f.startsWith("--"))break;let m=f.indexOf(`\r
+`),batchId:r,contentIds:i}}Kt.renderChangeSet=Qh;function bS(e,t){var r;return(r=yd(e,t))===null||r===void 0?void 0:r.map(n=>n.status)}Kt.parseChangeSetStatuses=bS;function yd(e,t){var r,n,i,o;if(typeof e!="string"||e.length===0)return;let a=(r=/^--(\S+)\r?\n/.exec(e))===null||r===void 0?void 0:r[1];if(a===void 0||!e.trimEnd().endsWith(`--${a}--`))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===a)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 f of l.slice(1)){if(f.startsWith("--"))break;let m=f.indexOf(`\r
\r
-`);if(m===-1)return;let p=f.slice(0,m),h=f.slice(m+4);if(!/^Content-Type:\s*application\/http\b/im.test(p))return;let g=/^HTTP\/1\.[01] (\d{3})\b/.exec(h);if(!g||((i=h.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let b=(o=/^Content-ID:\s*(\S+)/im.exec(p))===null||o===void 0?void 0:o[1];if(b===void 0||d.has(b)||!u.has(b))return;d.add(b),c.push({status:Number(g[1]),text:h,contentId:b})}return c.length===0?void 0:c}Er.parseChangeSetParts=zh;async function kG(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:o}=Wh(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,Gh.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new oo.ConnectionError(s,a.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=sS(a.body,o);if(l===void 0)throw new oo.ConnectionError(s,a.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 oo.ConnectionError(s,a.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 oo.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}Er.postChangeSet=kG;function lS(e){let t=e.text.replace(/\r\n/g,`
+`);if(m===-1)return;let p=f.slice(0,m),h=f.slice(m+4);if(!/^Content-Type:\s*application\/http\b/im.test(p))return;let g=/^HTTP\/1\.[01] (\d{3})\b/.exec(h);if(!g||((i=h.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let b=(o=/^Content-ID:\s*(\S+)/im.exec(p))===null||o===void 0?void 0:o[1];if(b===void 0||d.has(b)||!u.has(b))return;d.add(b),c.push({status:Number(g[1]),text:h,contentId:b})}return c.length===0?void 0:c}Kt.parseChangeSetParts=yd;async function WG(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:o}=Qh(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,Yo.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new Ii.ConnectionError(s,a.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=bS(a.body,o);if(l===void 0)throw new Ii.ConnectionError(s,a.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 Ii.ConnectionError(s,a.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 Ii.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}Kt.postChangeSet=WG;function Xh(e){let t=e.text.replace(/\r\n/g,`
`),r=t.indexOf(`
`),n=r===-1?t:t.slice(0,r),i=(r===-1?"":t.slice(r+2)).trim(),o={};for(let s of n.split(`
-`).slice(1)){let l=s.indexOf(":");l>0&&(o[s.slice(0,l).trim()]=s.slice(l+1).trim())}let a=i===""?void 0:i;if(i!=="")try{a=JSON.parse(i)}catch{}return{status:e.status,headers:o,body:a}}Er.partResponse=lS;async function $G(e,t,r){let{body:n,batchId:i,contentIds:o}=Wh(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch"),l=zh(a.body,o),u=l?.find(c=>c.status<200||c.status>=300);if(u&&(0,Gh.ensureSuccess)(lS(u),e.apiUrl(t[o.indexOf(u.contentId)].path)),(0,Gh.ensureSuccess)(a,s),!l||l.length!==t.length)throw new oo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response ${l?`reported ${l.length} result(s) for ${t.length} operation(s)`:"could not be parsed"}, so the outcome is unknown`);return o.map(c=>l.find(d=>d.contentId===c))}Er.sendChangeSet=$G});var cd=v(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.updateTable=ie.deleteAlternateKey=ie.createAlternateKey=ie.deleteGlobalOptionSet=ie.createGlobalOptionSet=ie.deleteRelationship=ie.deleteColumn=ie.updateColumn=ie.deleteTable=ie.createRelationship=ie.insertStatusValue=ie.createCustomerColumn=ie.createColumns=ie.setColumnVisualization=ie.getColumnVisualization=ie.createColumn=ie.createTable=ie.resolveEntitySetName=ie.pluralFallback=void 0;var _e=ye(),te=se(),Kn=Ho(),me=Q(),xG=Wl(),FG={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 Ze(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:MG(e,t)}}var uS=65535;function MG(e,t){let r=(o,a)=>({"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:o,LanguageCode:a});if(typeof e=="string")return[r(e,t)];let n=Object.entries(e);if(!n.length)throw new me.InvalidArgumentError("a localized label must contain at least one language");let i=new Set;return n.map(([o,a])=>{if(!/^[1-9]\d*$/.test(o))throw new me.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>uS)throw new me.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${uS})`);if(i.has(s))throw new me.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new me.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(a,s)})}function mS(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new me.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}ie.pluralFallback=mS;function zl(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}var cS=["None","ApplicationRequired","Recommended"];function Kh(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function dS(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function jl(e){let t=(0,_e.readCreatedId)(e,"MetadataId");if(!t)throw new me.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function UG(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b,w,E,S,P,L,I,D,O,x;if(t.defaultValue!==void 0&&e!=="boolean")throw new me.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new me.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:(o=t.maxLength)!==null&&o!==void 0?o:2e3,Format:"TextArea"};case"integer":return{"@odata.type":"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",AttributeType:"Integer",AttributeTypeName:{Value:"IntegerType"},Format:(a=t.integerFormat)!==null&&a!==void 0?a:"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:(f=t.precision)!==null&&f!==void 0?f:2,MinValue:(m=t.minValue)!==null&&m!==void 0?m:-1e11,MaxValue:(p=t.maxValue)!==null&&p!==void 0?p:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(h=t.precision)!==null&&h!==void 0?h:2,PrecisionSource:2,MinValue:(g=t.minValue)!==null&&g!==void 0?g:0,MaxValue:(b=t.maxValue)!==null&&b!==void 0?b:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(w=t.defaultValue)!==null&&w!==void 0?w:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:Ze((E=t.trueLabel)!==null&&E!==void 0?E:"Yes",r)},FalseOption:{Value:0,Label:Ze((S=t.falseLabel)!==null&&S!==void 0?S:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(P=t.dateFormat)!==null&&P!==void 0?P:"DateAndTime"};case"choice":return fS(t,r,!1);case"multiChoice":return fS(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(L=t.maxSizeKb)!==null&&L!==void 0?L:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(I=t.isPrimaryImage)!==null&&I!==void 0?I:!1,MaxSizeInKB:(D=t.maxSizeKb)!==null&&D!==void 0?D:10240};case"autonumber":if(!(!((O=t.autoNumberFormat)===null||O===void 0)&&O.trim()))throw new me.InvalidArgumentError(`createColumn: an 'autonumber' column needs an 'autoNumberFormat' (e.g. 'CDS-{SEQNUM:5}'), but '${t.schemaName}' has none \u2014 without one Dataverse would create a plain text column.`);return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(x=t.maxLength)!==null&&x!==void 0?x:100,AutoNumberFormat:t.autoNumberFormat};default:throw new me.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function fS(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,te.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new me.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(o=>({Value:o.value,Label:Ze(o.label,t)}))},i}var jh=new WeakMap;async function BG(e,t){var r,n;let i=(r=jh.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')${(0,te.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new me.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,te.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=jh.get(e);return l||(l=new Map,jh.set(e,l)),l.set(t,s),s}ie.resolveEntitySetName=BG;async function qG(e,t){var r,n,i,o,a,s,l,u,c,d,f,m,p,h,g;let b=t.primaryColumnRequired;if(b!==void 0&&!cS.includes(b))throw new me.InvalidArgumentError(`createTable: 'primaryColumnRequired' must be one of ${cS.join(", ")}; got '${String(b)}'.`);let w=b!==void 0&&b!=="None";if(w&&!t.primaryColumnAutoNumberFormat&&!e.supportsPut)throw new me.InvalidArgumentError(`createTable: 'primaryColumnRequired: ${b}' on a plain text primary column needs an HttpClient that implements put(): the platform ignores the level in the create, so the SDK sets it with an update.`);let E=(r=t.languageCode)!==null&&r!==void 0?r:Kn.DEFAULT_LCID,S=Kh(t.schemaName),P=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${S}_Name`,L={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:P,RequiredLevel:zl(b??"None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:Ze((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",E),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(L.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&bS(t.columns,"createTable");let I={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:Ze(t.displayName,E),DisplayCollectionName:Ze((a=t.pluralName)!==null&&a!==void 0?a:mS(t.displayName),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:[L,...((c=t.columns)!==null&&c!==void 0?c:[]).map(bn=>Jh(bn,E))]};t.description&&(I.Description=Ze(t.description,E));let D="/EntityDefinitions",O=(0,_e.ensureSuccess)(await e.post(D,I),e.apiUrl(D)),x=jl(O),K=`/EntityDefinitions(${x})`+(0,te.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),Re=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),qt=Math.max(0,(f=t.readBackDelayMs)!==null&&f!==void 0?f:1e3),ge=w?` Its primary column's requirement level '${b}' was NOT applied or checked: once the table is readable, set it with updateColumn('${t.schemaName.toLowerCase()}', '${P.toLowerCase()}', { required: '${b}' }).`:"",je;try{je=await hS(e,K,Re,qt)}catch(bn){throw w?(0,me.attachCause)(new me.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}), but reading it back failed (${bn instanceof Error?bn.message:String(bn)}).${ge} Do NOT re-run the create \u2014 it will collide on the schema name.`),bn):bn}if(!je)throw new me.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}) but its metadata was still not readable after ${Re} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${x}) once the environment catches up, or raise 'readBackAttempts'.${ge}`);let de=je.body,He={logicalName:(m=de.LogicalName)!==null&&m!==void 0?m:t.schemaName.toLowerCase(),metadataId:x,entitySetName:(p=de.EntitySetName)!==null&&p!==void 0?p:"",primaryIdAttribute:(h=de.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=de.PrimaryNameAttribute)!==null&&g!==void 0?g:P.toLowerCase()};return w&&(He.primaryColumnRequired=await VG(e,t.schemaName,He,b,Re,qt)),He}ie.createTable=qG;async function hS(e,t,r,n){for(let i=1;i<=r;i+=1){let o=await e.get(t);if(o.status>=200&&o.status<300)return o;o.status!==404&&(0,_e.ensureSuccess)(o,e.apiUrl(t)),i<r&&n>0&&await new Promise(a=>setTimeout(a,n))}}async function VG(e,t,r,n,i,o){let a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(r.logicalName)}')/Attributes(LogicalName='${(0,te.odataPathLiteral)(r.primaryNameAttribute)}')`+(0,te.odataQuery)([["$select","RequiredLevel"]]),s=async()=>{var d,f;let m=await hS(e,a,i,o),p=(f=(d=m?.body)===null||d===void 0?void 0:d.RequiredLevel)===null||f===void 0?void 0:f.Value;return typeof p=="string"?p:void 0},l="read",u,c=d=>{let f=`its primary column '${r.primaryNameAttribute}'`,m=l==="read"?`${f} could not be read back`:l==="update"?`${f} read '${u??"(unreadable)"}' and the update to '${n}' failed, so it may or may not carry it`:u===void 0?`${f} was updated to '${n}' but could not be read back`:`${f} is still '${u}' after the update to '${n}'`;return new me.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t}' WAS CREATED (MetadataId ${r.metadataId}), but ${m}${d?` (${d})`:""}. Do NOT re-run the create \u2014 it will collide on the schema name. Check the level, and set it with updateColumn('${r.logicalName}', '${r.primaryNameAttribute}', { required: '${n}' }).`)};try{u=await s(),u!==n&&(l="update",await ES(e,r.logicalName,r.primaryNameAttribute,{required:n}),l="verify",u=await s())}catch(d){throw l==="verify"&&(u=void 0),(0,me.attachCause)(c(d instanceof Error?d.message:String(d)),d)}if(u!==n)throw c(u===void 0?"the answer had no RequiredLevel":void 0);return n}function Jh(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,o={...UG(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:zl((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:Ze(e.displayName,i)};return e.description&&(o.Description=Ze(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),gS(o,e),o}function gS(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 GG(e,t,r){var n;let i=Jh(r,(n=r.languageCode)!==null&&n!==void 0?n:Kn.DEFAULT_LCID),o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,a=(0,_e.ensureSuccess)(await e.post(o,i),e.apiUrl(o)),s={logicalName:r.schemaName.toLowerCase(),metadataId:jl(a)};if(r.visualization&&r.visualization!=="None")try{await CS(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new me.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(0,me.attachCause)(u,l),u}return s}ie.createColumn=GG;var os="/controlconfigurations",yS="CustomRenderersConfiguration",Hh={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 bS(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new me.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 vS(e){return JSON.stringify({type:Hh[e]})}function WG(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(Hh).find(i=>Hh[i]===r);return n??"None"}async function wS(e,t,r){var n,i;let o=`entitylogicalname eq '${(0,te.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,te.odataLiteral)(r)}'`,a=`${os}${(0,te.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",o]])}`,l=(i=(n=(0,_e.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],u=r.toLowerCase();return l.filter(c=>{var d,f;return((f=(d=c.Attribute)===null||d===void 0?void 0:d.logicalname)===null||f===void 0?void 0:f.toLowerCase())===u})}async function zG(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,a=(n=(0,_e.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!a)throw new me.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,te.normalizeGuid)(a,"MetadataId")}async function CS(e,t,r,n,i){let o={name:yS,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:vS(i),"[email protected]":`/attributes(${(0,te.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,_e.ensureSuccess)(await e.post(os,o),e.apiUrl(os))}async function jG(e,t,r){var n;let i=await wS(e,t,r);return WG((n=i[0])===null||n===void 0?void 0:n.metadatajson)}ie.getColumnVisualization=jG;async function HG(e,t,r,n){let o=(await wS(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of o){let c=`${os}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,_e.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,l=await zG(e,t,r);if(a){let u=`${os}(${(0,te.normalizeGuid)(a,"controlconfigurationid")})`,c={name:yS,metadatajson:vS(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,_e.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await CS(e,t,r,l,n);for(let u of s){let c=`${os}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,_e.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}ie.setColumnVisualization=HG;async function KG(e,t,r){if(r.length===0)return;if(bS(r,"createColumns"),!e.supportsAtomicBatch)throw new me.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,te.odataPathLiteral)(t)}')/Attributes`;await(0,xG.postChangeSet)(e,r.map(i=>{var o;return{method:"POST",path:n,body:Jh(i,(o=i.languageCode)!==null&&o!==void 0?o:Kn.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}ie.createColumns=KG;async function JG(e,t,r){var n,i,o,a;let s=(n=r.languageCode)!==null&&n!==void 0?n:Kn.DEFAULT_LCID,l=Kh(r.schemaName),u=(i=r.accountRelationshipName)!==null&&i!==void 0?i:`${l}_${t}_account`,c=(o=r.contactRelationshipName)!==null&&o!==void 0?o:`${l}_${t}_contact`,d={Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.ComplexLookupAttributeMetadata",SchemaName:r.schemaName,DisplayName:Ze(r.displayName,s),RequiredLevel:zl((a=r.required)!==null&&a!==void 0?a:"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,_e.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}ie.createCustomerColumn=JG;async function YG(e,t,r){var n,i,o,a,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:Kn.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:Ze(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,_e.ensureSuccess)(await e.post("/InsertStatusValue",u),e.apiUrl("/InsertStatusValue"));return Number((s=(a=(o=c.body)===null||o===void 0?void 0:o.NewOptionValue)!==null&&a!==void 0?a:r.value)!==null&&s!==void 0?s:0)}ie.insertStatusValue=YG;async function QG(e,t){var r,n,i,o,a;let s=(r=t.languageCode)!==null&&r!==void 0?r:Kn.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new me.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let f=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${Kh(t.schemaName)}_${t.referencedEntity}Id`;u=f.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:f,RequiredLevel:zl((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:Ze((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new me.InvalidArgumentError("ManyToMany relationship requires entity1 and entity2");l={"@odata.type":"Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata",SchemaName:t.schemaName,IntersectEntityName:(a=t.intersectEntityName)!==null&&a!==void 0?a:t.schemaName.toLowerCase(),Entity1LogicalName:t.entity1,Entity2LogicalName:t.entity2}}let c="/RelationshipDefinitions",d=(0,_e.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:jl(d),lookupLogicalName:u}}ie.createRelationship=QG;async function XG(e,t){let r=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`;(0,_e.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteTable=XG;async function ES(e,t,r,n){var i,o;let a=(i=n.languageCode)!==null&&i!==void 0?i:Kn.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,_e.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=FG[(o=c.AttributeType)!==null&&o!==void 0?o:""];if(!c.MetadataId||!d){let g=c.MetadataId?c.AttributeType?`type '${c.AttributeType}' not supported`:"the attribute read returned no AttributeType":"the attribute read returned no MetadataId";throw new me.InvalidArgumentError(`cannot update column '${r}' on '${t}' (${g})`)}let f=(0,te.normalizeGuid)(c.MetadataId,"MetadataId"),m=`${s}(${f})/${d}`,p=(0,_e.ensureSuccess)(await e.get(m),e.apiUrl(m)).body;for(let g of Object.keys(p))g.startsWith("@odata.")&&delete p[g];if(p["@odata.type"]=d,n.displayName!==void 0&&(p.DisplayName=Ze(n.displayName,a)),n.description!==void 0&&(p.Description=Ze(n.description,a)),n.required!==void 0&&(p.RequiredLevel=zl(n.required)),n.maxLength!==void 0&&(p.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(p.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new me.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 me.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(p.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(p.Format=n.integerFormat),gS(p,n);let h=`${s}(${f})`;(0,_e.ensureSuccess)(await e.put(h,p,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}ie.updateColumn=ES;async function ZG(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,o=`${i}(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new me.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,_e.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteColumn=ZG;async function e9(e,t){var r,n,i;let o=`/RelationshipDefinitions${(0,te.odataQuery)([["$filter",`SchemaName eq '${(0,te.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(n=(r=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).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 me.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,_e.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteRelationship=e9;async function pS(e,t){var r;let n=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(n);if(i.status===404)return;let a=(r=(0,_e.ensureSuccess)(i,e.apiUrl(n)).body)===null||r===void 0?void 0:r.MetadataId;return a?(0,te.normalizeGuid)(a,"MetadataId"):void 0}async function t9(e,t){var r;let n=t.name.toLowerCase(),i=await pS(e,n);if(i)return{name:n,metadataId:i};let o=(r=t.languageCode)!==null&&r!==void 0?r:Kn.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:Ze(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:Ze(l.label,o)}))};t.description&&(a.Description=Ze(t.description,o));let s="/GlobalOptionSetDefinitions";try{let l=(0,_e.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:n,metadataId:jl(l)}}catch(l){let u;try{u=await pS(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}ie.createGlobalOptionSet=t9;async function r9(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t.toLowerCase())}')`;(0,_e.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteGlobalOptionSet=r9;async function n9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Kn.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:Ze(r.displayName,i),KeyAttributes:r.keyAttributes},a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,s=(0,_e.ensureSuccess)(await e.post(a,o),e.apiUrl(a));return{logicalName:r.schemaName.toLowerCase(),metadataId:jl(s)}}ie.createAlternateKey=n9;async function i9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,o=`${i}(LogicalName='${(0,te.odataPathLiteral)(r.toLowerCase())}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new me.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,_e.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteAlternateKey=i9;async function o9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Kn.DEFAULT_LCID,o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`,s=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body,l=s.MetadataId;if(!l)throw new me.InvalidArgumentError(`table '${t}' not found`);let u=(0,te.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=Ze(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=Ze(r.pluralName,i)),r.description!==void 0&&(s.Description=Ze(r.description,i)),r.auditEnabled!==void 0&&dS(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&dS(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,_e.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}ie.updateTable=o9});var so=v(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.rebuildRaw=Ar.assembleChildren=Ar.spliceChildren=Ar.mergeAttrs=Ar.rawFromNode=Ar.emptyBag=void 0;var ao=Q(),AS=1e6,fd=512;function a9(){return{a:[],c:[]}}Ar.emptyBag=a9;function SS(e,t=0){if(t>fd)throw new ao.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${fd}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>SS(r,t+1))}}Ar.rawFromNode=SS;function s9(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))),o=new Set,a=[];for(let[s,l]of e)i.has(s)||(n.has(s)?a.push([s,n.get(s)]):a.push([s,l]),o.add(s));for(let[s,l]of t)o.has(s)||(a.push([s,l]),o.add(s));return a}Ar.mergeAttrs=s9;function dd(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>AS)throw new ao.InvalidArgumentError(`Bag child index must be an integer in [0, ${AS}] (got ${String(l)})`);if(r.has(l))throw new ao.InvalidArgumentError(`Duplicate bag child index ${l}`);r.add(l)}let n=[...e].sort((s,l)=>s.i-l.i),i=[],o=0,a=0;for(let s of n){for(;a<s.i&&o<t.length;)i.push(t[o]),o+=1,a+=1;a<s.i&&(a=s.i),i.push(s.node),a+=1}for(;o<t.length;)i.push(t[o]),o+=1;return i}Ar.spliceChildren=dd;function l9(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:dd(e.w.c,t)};return dd(e.c,[r])}return dd(e.c,t)}Ar.assembleChildren=l9;function NS(e,t,r,n=0){if(n>fd)throw new ao.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${fd}`);u9(e,n);let i=t.make(e.n,r);for(let[o,a]of e.a)t.setProp(i,o,a);for(let o of e.c)t.addChild(i,NS(o,t,i,n+1));return i}Ar.rebuildRaw=NS;function u9(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new ao.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new ao.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 ao.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 ao.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var lo=v(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});pd.installDomShim=void 0;var _S=es(),TS=!1,c9={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 d9(){if(TS)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=_S.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=_S.XMLSerializer),typeof e.Node>"u"&&(e.Node=c9),TS=!0}pd.installDomShim=d9});var uo=v(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.projectElementBag=et.serializeNode=et.domEngine=et.nodeLikeFromDom=et.parseXmlRoot=et.EMPTY_FORM_SENTINEL=et.TEXT_SENTINEL=void 0;var f9=so(),as=Q(),p9=lo();et.TEXT_SENTINEL="#text";et.EMPTY_FORM_SENTINEL="#empty";var hd=new WeakSet;function m9(e,t){(0,p9.installDomShim)();let r=e&&e.trim()!==""?e:t,n=new DOMParser().parseFromString(r,"text/xml"),i=n.documentElement;if(!i)throw new as.InvalidArgumentError("XML source has no root element (empty or malformed input)");return h9(r),y9(n),v9(i),w9(i),A9(i,r),i}et.parseXmlRoot=m9;function h9(e){let t=e.search(/\S/);if(t!==-1&&e[t]!=="<")throw IS(3)}var g9=["http://www.mozilla.org/newlayout/xml/parsererror.xml","http://www.w3.org/1999/xhtml"];function y9(e){var t;for(let r of g9){let n=e.getElementsByTagNameNS(r,"parsererror")[0];if(n){let i=((t=n.textContent)!==null&&t!==void 0?t:"").replace(/\s+/g," ").trim().slice(0,200);throw new as.InvalidArgumentError(`XML source is not well-formed (${i||"the XML parser reported an error"}), so it cannot be round-tripped`)}}}var b9=new Set([1,3]);function v9(e){let t=[e];for(;t.length>0;){let n=t.pop().childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];if(!b9.has(o.nodeType))throw new as.InvalidArgumentError(`Unsupported XML node type ${o.nodeType} (CDATA / comment / processing-instruction) is outside the hybrid projection's lossless grammar and cannot be round-tripped`);o.nodeType===1&&t.push(o)}}}function w9(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 o=0;o<i.length;o+=1){let a=i[o];if(a!==e&&!(a.nodeType===3&&((r=a.nodeValue)!==null&&r!==void 0?r:"").trim()===""))throw IS(a.nodeType)}}function IS(e){return new as.InvalidArgumentError(`Unsupported document-level XML node (type ${e}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}function C9(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 E9(e){let t=[],r=[e];for(;r.length>0;){let n=r.pop();t.push(n);let i=n.childNodes;for(let o=i.length-1;o>=0;o-=1){let a=i[o];a.nodeType===1&&r.push(a)}}return t}function OS(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 A9(e,t){let r=C9(t),n=E9(e),i=Math.min(r.length,n.length);for(let o=0;o<i;o+=1){if(r[o])continue;let a=n[o];OS(a)||hd.add(a)}}function Yh(e){let t=e.nodeType===3;return{getNodeName:()=>t?et.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:et.TEXT_SENTINEL,value:(r=e.nodeValue)!==null&&r!==void 0?r:""}];let n=e.attributes,i=[];for(let o=0;o<n.length;o+=1)i.push({key:n[o].name,value:n[o].value});return hd.has(e)&&!OS(e)&&i.push({key:et.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 o=n[i];(o.nodeType===1||o.nodeType===3)&&r.push(Yh(o))}return r}}}et.nodeLikeFromDom=Yh;function S9(e){return{make:t=>t===et.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===et.EMPTY_FORM_SENTINEL?hd.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}et.domEngine=S9;function PS(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 md(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw md(r);t+=1;continue}if(r>=56320&&r<=57343)throw md(r)}}function md(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new as.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 N9(e){return PS(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\r/g,"&#xD;").replace(/\n/g,"&#xA;").replace(/\t/g,"&#x9;")}function _9(e){return PS(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function T9(e){return RS(e,0)}et.serializeNode=T9;var DS=512;function RS(e,t){var r;if(t>DS)throw new as.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${DS}`);if(e.nodeType===3)return _9((r=e.nodeValue)!==null&&r!==void 0?r:"");let n=e,i="<"+n.tagName,o=n.attributes;for(let l=0;l<o.length;l+=1)i+=" "+o[l].name+'="'+N9(o[l].value)+'"';let a=[],s=n.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];(u.nodeType===1||u.nodeType===3)&&a.push(u)}if(a.length===0)return hd.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of a)i+=RS(l,t+1);return i+"</"+n.tagName+">"}function D9(e){let t=Yh(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,f9.rawFromNode)(r)}))}}et.projectElementBag=D9});var en=v(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.rejectUnknownKeys=Ht.childObjects=Ht.optionalGuidId=Ht.optionalEnum=Ht.eachObject=Ht.issue=Ht.isJsonObject=void 0;function LS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}Ht.isJsonObject=LS;function ss(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}Ht.issue=ss;function kS(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{LS(o)?i.push({node:o,index:a}):n.push(ss(`${t}/${a}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}Ht.eachObject=kS;function I9(e,t,r,n,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!r.includes(a))&&o.push(ss(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}Ht.optionalEnum=I9;var O9=/^(?:\{[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 P9(e,t,r,n,i){let o=e[t];typeof o=="string"&&o!==""&&!O9.test(o)&&i.push(ss(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${o}'`))}Ht.optionalGuidId=P9;function R9(e,t,r,n,i){let o=e[t],a=`${r}/${t}`;return o===void 0?[]:Array.isArray(o)?kS(o,a,n,i):(i.push(ss(a,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}Ht.childObjects=R9;function L9(e,t,r,n,i,o={}){var a,s;for(let l of Object.keys(e)){if(t.has(l))continue;let u=(a=o.elsewhere)===null||a===void 0?void 0:a[l],c=(s=o.unsupported)===null||s===void 0?void 0:s[l],d=u?` '${l}' is a ${u} key \u2014 set it on the ${u} instead.`:c?` ${c}`:` Put values the typed layer does not model in '${n}.bag', which round-trips them verbatim.`;i.push(ss(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}Ht.rejectUnknownKeys=L9});var wd=v(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.genPageEmbedIssues=B.setUniqueId=B.mintEmbedIdentity=B.authoredUniqueId=B.hasGenPage=B.applyEmbedCellDefaults=B.applyEmbedControlDefaults=B.mayCommitEmbedState=B.commitEmbedState=B.reconcileEmbedDescriptions=B.embedAppendIndex=B.activeEmbedBindings=B.projectGenPageEmbeds=B.isRecognizedEmbed=B.isUnbound=B.effectiveClassId=B.effectiveFormType=B.inputDataFrom=B.classifyBinding=B.isStaticParameter=B.entryParameter=B.pageEntries=B.descriptionFor=B.descriptionsRegion=B.controlUniqueIds=B.controlUniqueId=B.typedCellSites=B.typedCells=B.rawText=B.rawAttr=B.normGuid=B.GENPAGE_FORM_FACTORS=B.GENPAGE_EMBED_ROWSPAN=B.GENPAGE_CONTROL_NAME=B.CUSTOM_CONTROL_CLASS_ID=void 0;var k9=es(),$9=$a(),Qh=dt(),tn=en();B.CUSTOM_CONTROL_CLASS_ID="F9A8A302-114E-466A-B582-6771B2AE0D92";B.GENPAGE_CONTROL_NAME="MscrmControls.UxAgentControl";B.GENPAGE_EMBED_ROWSPAN=6;B.GENPAGE_FORM_FACTORS=["2","0","1"];var x9=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Sr(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),x9.test(t)?t:""}B.normGuid=Sr;function co(e,t){let r=Ae(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=co;function Kl(e){return Ae(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=Kl;function Ae(e){return Array.isArray(e)?e:[]}function ng(e,t){let r=Ae(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function FS(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function MS(e){return An(e).map(t=>t.cell)}B.typedCells=MS;function An(e){let t=[];return Ae(e?.tabs).forEach((r,n)=>{Ae(Pe(r)?r.columns:void 0).forEach((i,o)=>{Ae(Pe(i)?i.sections:void 0).forEach((a,s)=>{Ae(Pe(a)?a.rows:void 0).forEach((l,u)=>{Ae(Pe(l)?l.cells:void 0).forEach((c,d)=>{Pe(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${o}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}B.typedCellSites=An;function Di(e){return Pe(e)?Sr(ng(e.bag,"uniqueid")):""}B.controlUniqueId=Di;function F9(e){let t=new Set;for(let{cell:r}of An(e)){let n=Yo(r.control)?Di(r.control):"";n&&t.add(n)}return t}function M9(e){let t=new Map;for(let{cell:r}of An(e)){let n=Pe(r.control)?Di(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function U9(e){return e!==void 0&&e.genPage===void 0&&(ag(e)!==B.CUSTOM_CONTROL_CLASS_ID||!vd(e))}function Xh(e,t){if(Pe(e)){t(e);for(let r of Ae(e.c))Xh(r,t)}}function Ko(e,t){var r;if(Pe(e)){for(let n of Ae(e.c))Xh(n?.node,t);for(let n of Ae((r=e.w)===null||r===void 0?void 0:r.c))Xh(n?.node,t)}}function yd(e){let t=new Map,r=i=>{var o;i&&t.set(i,((o=t.get(i))!==null&&o!==void 0?o:0)+1)},n=i=>{i.n==="control"&&r(Sr(co(i,"uniqueid")))};return Ko(e?.bag,n),Ae(e?.tabs).forEach(i=>{Pe(i)&&(Ko(i.bag,n),Ae(i.columns).forEach(o=>{Pe(o)&&(Ko(o.bag,n),Ae(o.sections).forEach(a=>{Pe(a)&&(Ko(a.bag,n),Ae(a.rows).forEach(s=>{Pe(s)&&(Ko(s.bag,n),Ae(s.cells).forEach(l=>{Pe(l)&&(Ko(l.bag,n),Pe(l.control)&&(r(Di(l.control)),Ko(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=yd;function ls(e){return Ae(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=ls;function Jo(e,t){var r;let n=Sr(t);if(n)return Ae((r=ls(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&Sr(co(i,"forControl"))===n)}B.descriptionFor=Jo;function Jl(e){return Ae(e.c).filter(US)}B.pageEntries=Jl;function US(e){return e?.n==="customControl"&&co(e,"name")===B.GENPAGE_CONTROL_NAME}function Zh(e,t){let r=Ae(e.c).find(n=>n?.n==="parameters");return Ae(r?.c).find(n=>n?.n===t)}B.entryParameter=Zh;function eg(e){return co(e,"static")==="true"}B.isStaticParameter=eg;function Yl(e){let t=Jl(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let o=Zh(t[i],"RefId");if(!o||!eg(o))return{kind:"unsupported"};let a=Sr(Kl(o));if(!a)return{kind:"unsupported"};let s=Zh(t[i],"PageInput");if(s&&!eg(s))return{kind:"unsupported"};let l=s?Kl(s):void 0;if(i===0)r=a,n=l;else if(a!==r||l!==n)return{kind:"unsupported"}}return n===void 0?{kind:"projectable",pageId:r}:{kind:"projectable",pageId:r,pageInputRaw:n}}B.classifyBinding=Yl;function Pe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ig(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return Pe(t)&&Pe(t.data)?t.data:void 0}B.inputDataFrom=ig;function og(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=og;function ag(e){return FS(e.classId!==void 0?e.classId:ng(e.bag,"classid"))}B.effectiveClassId=ag;function vd(e){return!e.fieldName}B.isUnbound=vd;function sg(e,t){if(og(e)!=="Main"||!vd(t)||ag(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=Di(t),n=r?Jo(e.bag,r):void 0;return n!==void 0&&Yl(n).kind==="projectable"}B.isRecognizedEmbed=sg;function B9(e){for(let t of MS(e)){let r=t.control;if(!r||!sg(e,r))continue;let n=Yl(Jo(e.bag,Di(r)));if(n.kind!=="projectable")continue;let i=ig(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=B9;var q9=new Set(["pageId","inputData"]);function Hl(e){let t=[];for(let r=0;r<e.childNodes.length;r+=1){let n=e.childNodes[r];n.nodeType===1&&t.push(n)}return t}function V9(e){var t;let r=[],n=c=>d=>r.push(`${c}: ${d}`),i=new k9.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the formxml does not parse cleanly${r.length>0?` (${r[0]})`:""}`);let a=new Set,s=o.getElementsByTagName("control");for(let c=0;c<s.length;c+=1){let d=Sr(s[c].getAttribute("uniqueid"));d&&a.add(d)}let l=Hl(o).find(c=>c.nodeName==="controlDescriptions"),u=new Map;for(let c of l?Hl(l):[]){let d=Sr(c.getAttribute("forControl"));if(!(c.nodeName!=="controlDescription"||!d||!a.has(d)))for(let f of Hl(c)){if(f.nodeName!=="customControl"||f.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let m=Hl(f).find(g=>g.nodeName==="parameters"),p=m?Hl(m).find(g=>g.nodeName==="RefId"):void 0,h=p&&p.getAttribute("static")==="true"?Sr(p.textContent):"";h&&u.set(`${d}|${h}`,[d,h])}}return[...u.values()]}B.activeEmbedBindings=V9;function gd(e){return{n:`<${e}`,a:[],c:[]}}function tg(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[gd(t)]}}function rg(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);Pe(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function G9(e,t,r){return{n:"controlDescription",a:[["forControl",e]],c:B.GENPAGE_FORM_FACTORS.map(n=>({n:"customControl",a:[["name",B.GENPAGE_CONTROL_NAME],["formFactor",n]],c:[{n:"parameters",a:[],c:[tg("RefId",t),...r===void 0?[]:[tg("PageInput",rg(r))]]}]}))}}function bd(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>bd(r,t[n]));if(Pe(e)&&Pe(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&bd(e[n],t[n]))}return e===t}function W9(e,t,r){let n=Ae(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&Sr(Kl(i))!==t&&(i.c=[gd(t)]);let o=n.c.findIndex(u=>u?.n==="PageInput"),a=o>=0?n.c[o]:void 0,s=a?Kl(a):void 0;if(bd(ig(s),r))return;if(r!==void 0){a?a.c=[gd(rg(r,s))]:n.c.push(tg("PageInput",rg(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(o,1):a.c=[gd(JSON.stringify(l))]}function lg(e){let t=Ae(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=lg;function z9(e,t){var r;let n=e.bag,i=ls(n);if(i&&t){let o=yd(t),a=yd(e),s=F9(t),l=M9(e),u=Ae(i.node.c),c=[];for(let d of u){let f=d?.n==="controlDescription"&&Jl(d).length>0?Sr(co(d,"forControl")):"";if(!f||!o.has(f))c.push(d);else if(a.has(f))if(s.has(f)&&U9(l.get(f))&&bd(d,Jo(t.bag,f))){let m=Ae(d.c).filter(p=>!US(p));m.length>0&&c.push({...d,c:m})}else c.push(d)}(c.length!==u.length||c.some((d,f)=>d!==u[f]))&&(i.node.c=c)}for(let{cell:o}of An(e)){let a=o.control;if(!Yo(a)||!Pe(a.genPage))continue;let s=Sr(a.genPage.pageId),l=a.genPage.inputData,u=Di(a);if(!u){if(Ql(a)!==void 0)continue;u=ug(a)}let c=Jo(n,u);if(c){for(let m of Jl(c))W9(m,s,l);continue}i||(i={i:lg(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=ng(a.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),f=d.startsWith("{")?d:`{${u}}`;i.node.c.push(G9(f,s,l))}}B.reconcileEmbedDescriptions=z9;function j9(e,t){let r=ls(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=An(e).some(({cell:a})=>Yo(a.control)&&(a.rowspan===void 0||a.control.classId===void 0||a.control.showLabel===void 0||a.control.label===void 0||a.control.fieldName===void 0));if(!n&&!i)return e;let o=JSON.parse(JSON.stringify(e));if(n){let a=JSON.parse(JSON.stringify(t)),s=ls(o.bag);s?s.node=a:(o.bag=Pe(o.bag)?o.bag:{a:[],c:[]},o.bag.c=Ae(o.bag.c),o.bag.c.push({i:lg(e.bag),node:a}))}for(let{cell:a}of An(o))Yo(a.control)&&(BS(a.control),qS(a));return o}B.commitEmbedState=j9;function H9(e){if(An(e).some(({cell:r})=>Yo(r.control)))return!0;let t=ls(e.bag);return Ae(t?.node.c).some(r=>r?.n==="controlDescription"&&Jl(r).length>0)}B.mayCommitEmbedState=H9;function BS(e){e.classId===void 0&&(e.classId=B.CUSTOM_CONTROL_CLASS_ID),e.showLabel===void 0&&(e.showLabel=!1),e.label===void 0&&(e.label=""),e.fieldName===void 0&&(e.fieldName=null)}B.applyEmbedControlDefaults=BS;function qS(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=qS;function Yo(e){return Pe(e)&&e.genPage!==void 0}B.hasGenPage=Yo;function $S(e){return Yo(e.control)&&(!e.control.id||!e.id||Ql(e.control)===void 0)}function Ql(e){let t=Ae(Pe(e.bag)?e.bag.a:void 0).find(n=>Array.isArray(n)&&n[0]==="uniqueid");if(!t)return;let r=t[1];return typeof r=="string"&&r.trim()===""?void 0:r}B.authoredUniqueId=Ql;function K9(e){if(!An(e).some(({cell:r})=>$S(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of An(t)){if(!$S(r))continue;let n=r.control;n.id||(n.id=(0,Qh.newId)()),r.id||(r.id=(0,Qh.newId)()),Ql(n)===void 0&&ug(n)}return t}B.mintEmbedIdentity=K9;function ug(e){let t=(0,Qh.newId)(),r=`{${t}}`;if(!Pe(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=Ae(e.bag.a),i=n.find(o=>Array.isArray(o)&&o[0]==="uniqueid");return i?i[1]=r:n.push(["uniqueid",r]),e.bag.a=n,e.bag.c=Ae(e.bag.c),t}B.setUniqueId=ug;function xS(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function J9(e){let t=Ae(e.c).filter(r=>r?.n==="customControl").map(r=>{var n,i;return(i=(n=co(r,"name"))!==null&&n!==void 0?n:co(r,"id"))!==null&&i!==void 0?i:"unnamed"});return[...new Set(t)].join(", ")||"no custom control"}function Y9(e){let t=[],r;for(let{cell:n,pointer:i}of An(e)){let o=n.control;if(!Pe(o))continue;let a=`${i}/control`;if(o.genPage===void 0){Q9(e,o,a,t);continue}r=r??yd(e),X9(e,o,a,r,t)}return t}B.genPageEmbedIssues=Y9;function Q9(e,t,r,n){if(!sg(e,t))return;let i=Yl(Jo(e.bag,Di(t)));n.push((0,tn.issue)(r,"genpage-embed-removed",`this control still embeds generative page ${i.pageId}: removing genPage alone would leave that binding on the form. To remove the embed, remove the cell (or set the cell's control to null); to change the page, edit genPage/pageId. A copy fetched by an older SDK (projection 3) shows no genPage at all \u2014 re-fetch the form.`))}function X9(e,t,r,n,i){var o;let a=`${r}/genPage`,s=t.genPage;if(!Pe(s))i.push((0,tn.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${xS(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!Sr(s.pageId))&&i.push((0,tn.issue)(`${a}/pageId`,"genpage-embed-shape",`genPage.pageId must be the id (a GUID) of a generative page, got ${s.pageId===void 0?"nothing":JSON.stringify(s.pageId)}`)),s.inputData!==void 0&&!Pe(s.inputData)&&i.push((0,tn.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${xS(s.inputData)}`));for(let m of Object.keys(s))q9.has(m)||i.push((0,tn.issue)($9.JsonPointer.append(a,m),"genpage-embed-unknown-key",`'${m}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}vd(t)||i.push((0,tn.issue)(`${r}/fieldName`,"genpage-embed-bound",`a generative-page embed is an unbound control, but this one is bound to column '${t.fieldName}'. Set fieldName to null, or embed the page in a new cell.`)),t.classId!==void 0&&FS(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,tn.issue)(`${r}/classId`,"genpage-embed-class-id",`a generative-page embed is the custom control {${B.CUSTOM_CONTROL_CLASS_ID}}, but classId is ${JSON.stringify(t.classId)}. Omit classId (the SDK defaults it) or set it to that class.`));let l=og(e);l!=="Main"&&i.push((0,tn.issue)(a,"genpage-embed-main-form-only",`a generative page can be embedded only in a Main form, as in the maker portal; this is a ${l} form.`));let u=Ql(t);u!==void 0&&!Sr(u)&&i.push((0,tn.issue)(`${r}/bag`,"genpage-embed-unique-id",`this embed's uniqueid ${JSON.stringify(u)} is not a GUID, and its page binding is keyed by it. Remove it from the bag (the SDK mints one) or set a GUID.`));let c=Di(t);if(!c)return;let d=Jo(e.bag,c),f=d?Yl(d):void 0;d&&f?.kind==="none"?i.push((0,tn.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${J9(d)}). genPage would have to delete that binding to take its place, so embed the page in a new cell instead.`)):f?.kind==="unsupported"&&i.push((0,tn.issue)(a,"genpage-embed-unsupported-binding","this control already embeds a page through a binding genPage cannot represent exactly \u2014 a RefId or PageInput bound to a column, a RefId that is not a page id, or form factors that disagree. Taking it over would silently turn it into a static binding, so embed the page in a new cell instead.")),((o=n.get(c))!==null&&o!==void 0?o:0)>1&&i.push((0,tn.issue)(`${r}/bag`,"genpage-embed-duplicate-unique-id",`this embed's uniqueid {${c}} is also carried by another control on the form, so both would share one binding. Author the copy without its bag and the SDK mints a new identity for it.`))}});var dg=v(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.findMissingGenPages=fo.GENPAGE_LOOKUP_CHUNK=void 0;var Z9=Lt(),cg=se();fo.GENPAGE_LOOKUP_CHUNK=50;async function e5(e,t,r){let n=[...new Set(t.map(o=>(0,cg.normalizeGuid)(o,"uxagentprojectid")))],i=new Set;for(let o=0;o<n.length;o+=fo.GENPAGE_LOOKUP_CHUNK){let a=n.slice(o,o+fo.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,cg.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,Z9.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,cg.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(o=>!i.has(o))}fo.findMissingGenPages=e5});var Xl=v(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.assertSystemFormKind=Nt.readSystemFormType=Nt.decodeCode=Nt.assertSystemFormRecordKind=Nt.describeSystemFormType=Nt.systemFormKindOf=Nt.SYSTEMFORM_KIND_MISMATCH_CODE=void 0;var GS=Q(),t5=ye(),VS=se();Nt.SYSTEMFORM_KIND_MISMATCH_CODE="SYSTEMFORM_KIND_MISMATCH";var r5={0:"dashboard",10:"dashboard",2:"form",6:"form",7:"form",11:"form"},n5={0:"dashboard",1:"appointment book",2:"Main form",3:"mini campaign form",4:"preview form",5:"mobile express form",6:"Quick View form",7:"Quick Create form",8:"dialog",9:"task flow form",10:"interactive dashboard",11:"card form",12:"interactive Main form",13:"contextual dashboard",100:"other form",101:"Main form backup",102:"appointment book backup",103:"Power BI dashboard"};function Cd(e){return Number.isInteger(e)?r5[e]:void 0}Nt.systemFormKindOf=Cd;function WS(e){var t;return Number.isFinite(e)?`a ${(t=n5[e])!==null&&t!==void 0?t:"systemform"} (type ${e})`:"a systemform whose type could not be read"}Nt.describeSystemFormType=WS;function zS(e,t,r,n){let i=WS(r),o=Cd(r);switch(n){case"fetch":return`Refusing to fetch systemform '${e}' as a ${t}: it is ${i}. Nothing was read into the workspace. `+(o?`Fetch it as a ${o}.`:Number.isFinite(r)?"The SDK does not model that kind: check the id.":"Check the id.");case"write":return`Refusing to write systemform '${e}' as a ${t}: it is ${i}. Nothing was written. Check the id: a local copy fetched by an SDK that did not check the kind can name a row of another kind \u2014 discard it with deleteArtifact('${t}', '${e}').`;case"delete":return`Refusing to delete systemform '${e}' as a ${t}: it is ${i}. Nothing was changed. Check the id.`;default:return`Refusing to ${n} systemform '${e}': it is ${i}, not a ${t}.`+(n==="set the security roles of"?" Nothing was written.":"")+" Check the id."}}function i5(e,t,r,n){let i=fg(e?.type);if(Cd(i)!==r)throw new GS.SdkError(Nt.SYSTEMFORM_KIND_MISMATCH_CODE,zS(t,r,i,n));return i}Nt.assertSystemFormRecordKind=i5;function fg(e){if(typeof e=="number")return Number.isInteger(e)?e:NaN;if(typeof e!="string"||!/^\s*-?\d+\s*$/.test(e))return NaN;let t=Number(e);return Number.isInteger(t)?t:NaN}Nt.decodeCode=fg;async function o5(e,t){return await jS(e,t,!1)}Nt.readSystemFormType=o5;async function a5(e,t){return jS(e,t,!0)}async function jS(e,t,r){var n;let o=`/systemforms(${(0,VS.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,VS.odataQuery)([["$select","type"]]),a=await e.get(o);if(!(r&&a.status===404))return(0,t5.ensureSuccess)(a,e.apiUrl(o)),fg((n=a.body)===null||n===void 0?void 0:n.type)}async function s5(e,t,r){let n=await a5(e,t);if(!(n===void 0||Cd(n)===r))throw new GS.SdkError(Nt.SYSTEMFORM_KIND_MISMATCH_CODE,zS(t,r,n,"delete"))}Nt.assertSystemFormKind=s5});var mg=v(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.patchSystemForm=qr.assertSystemFormContentUnchanged=qr.readSystemFormRowEtag=qr.unpublishedSystemFormPath=qr.FORM_TYPE_IMMUTABLE_CODE=void 0;var rn=ye(),l5=se(),Ed=Q(),po=Xl();qr.FORM_TYPE_IMMUTABLE_CODE="FORM_TYPE_IMMUTABLE";function pg(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,l5.odataQuery)([["$select",t]])}qr.unpublishedSystemFormPath=pg;function HS(e,t){return(0,rn.readRowEtag)(e,"systemforms","formid",t)}qr.readSystemFormRowEtag=HS;async function KS(e,t,r,n,i){(0,rn.requireEtag)(i,r,t);let o=(0,rn.ensureSuccess)(await e.get(n),e.apiUrl(n)),a=(0,po.assertSystemFormRecordKind)(o.body,t,r,"write"),s=(0,rn.readEtag)(o);if(s===null)throw new Ed.SdkError(rn.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its current version could not be read, so the write could not be verified as conditional and would risk silently overwriting a concurrent edit.`);if(s!==i)throw new Ed.SdkError(rn.VERSION_CONFLICT_CODE,`Version conflict writing ${r} '${t}': its formxml changed on the server since it was read (held ${i}, server ${s}). Re-fetch the ${r} and re-apply the change.`);return a}qr.assertSystemFormContentUnchanged=KS;async function u5(e,t,r,n,i,o){(0,rn.requireEtag)(i,r,t);let a=await HS(e,t);if(a===null)throw new Ed.SdkError(rn.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its row version could not be read, so the write could not be made conditional and would risk silently overwriting a concurrent edit.`);let s=await KS(e,t,r,pg(t,"formid,type"),i);if(n.type!==void 0&&(0,po.decodeCode)(n.type)!==s)throw new Ed.SdkError(qr.FORM_TYPE_IMMUTABLE_CODE,`Refusing to push ${r} '${t}': it would change it from ${(0,po.describeSystemFormType)(s)} to ${(0,po.describeSystemFormType)((0,po.decodeCode)(n.type))}. The platform ignores a type change on an existing ${r}, so the push would report a change that did not happen. Nothing was written. Create a new ${r} of that type instead.`);let l=(0,rn.echoWrite)("formid",{"If-Match":a}),u=`/systemforms(${t})${l.query}`;return(0,rn.ensureSuccess)(await e.patch(u,n,l.options),e.apiUrl(u)),c5(e,t,r,o)}qr.patchSystemForm=u5;async function c5(e,t,r,n){let i;try{let o=pg(t,n.select),a=(0,rn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,l=(0,rn.readEtag)(a),u=typeof s?.formid=="string"&&s.formid.replace(/[{}]/g,"").toLowerCase()===t,c=typeof s?.formxml=="string"&&s.formxml.trim()!=="",d=n.required.filter(p=>s?.[p]===void 0||s?.[p]===null),f=(0,po.decodeCode)(s?.type),m=(0,po.systemFormKindOf)(f)===r;if(l&&u&&c&&d.length===0&&m)return{id:t,etag:l,readBack:s};i=l?!u||!c?`the read did not return this ${r}'s document`:d.length>0?`the read did not return its ${d.join(", ")}`:`the read returned ${(0,po.describeSystemFormType)(f)}, not a ${r}`:"the read returned no version"}catch(o){i=o instanceof Error?o.message:String(o)}return{id:t,etag:null,warnings:[`The ${r} was saved, but its new version could not be read (${i}). The SDK holds no version for it now, so the next push is refused: re-fetch the ${r} before editing it again.`]}}});var vg=v(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.getFormSecurityRoles=kt.setFormSecurityRoles=kt.formApi=kt.readPrimaryCreateRefusal=kt.FORM_GENPAGE_TARGET_UNVERIFIABLE=kt.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var d5=Lt(),_t=ye(),nn=se(),Qo=Q(),hg=uo(),YS=wd(),f5=dg(),gg=mg(),Zl=Xl();kt.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";kt.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var QS="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",p5={select:QS,required:["name","type","objecttypecode"]},m5="formid,name,type,objecttypecode",h5=2,g5={Main:h5,QuickView:6,QuickCreate:7,Card:11},XS=new WeakMap;function y5(e){return typeof e=="object"&&e!==null?XS.get(e):void 0}kt.readPrimaryCreateRefusal=y5;kt.formApi={async get(e,t){let r=(0,nn.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,nn.odataQuery)([["$select",QS]]),i=(0,_t.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,Zl.assertSystemFormRecordKind)(i.body,r,"form","fetch"),{raw:i.body,etag:(0,_t.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=>g5[u]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,nn.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,nn.odataQuery)([["$select",m5],["$filter",a.join(" and ")]])}`;return(await(0,d5.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=JS(t);n!==void 0&&await ZS(e,bg(n,"payload"),[]);let i=(0,_t.echoWrite)("formid"),o=`/systemforms${i.query}`,a=(0,_t.withClientMintedId)(t,"formid",r),s=Object.freeze({...a}),l=await(0,_t.resendDeadlockVictim)(()=>e.post(o,{...s},i.options));try{(0,_t.ensureSuccess)(l,e.apiUrl(o))}catch(u){throw typeof u=="object"&&u!==null&&XS.set(u,{status:l.status,sent:s,desiredId:r}),u}return{id:(0,_t.resolveCreatedId)(l,"formid","form",r),etag:(0,_t.readEtag)(l)}},async update(e,t,r,n){let i=(0,nn.normalizeGuid)(t,"id"),o=JS(r);return o!==void 0&&await v5(e,i,o,n),(0,gg.patchSystemForm)(e,i,"form",r,n,p5)},readContentThenToken(e,t){return kt.formApi.get(e,t)},async delete(e,t){let r=(0,nn.normalizeGuid)(t,"id");return await(0,Zl.assertSystemFormKind)(e,r,"form"),(0,_t.deleteRecord)(e,"systemforms",r)}};var yg="DisplayConditions";async function b5(e,t,r){var n,i,o,a;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new Qo.InvalidArgumentError("setFormSecurityRoles: `everyone` and `roleIds` are mutually exclusive \u2014 the platform models <Everyone /> as a replacement for the <Role> list, not an addition to it.");let s=(0,nn.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,nn.odataQuery)([["$select","formid,formxml,type"]]),u=(0,_t.ensureSuccess)(await e.get(l),e.apiUrl(l));(0,Zl.assertSystemFormRecordKind)(u.body,s,"form","set the security roles of");let c=(0,_t.readEtag)(u),d=u.body,f=d?.formxml;if(!f)throw new Qo.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let m=(0,hg.parseXmlRoot)(f,"<form/>"),p=m.ownerDocument;if(!p)throw new Qo.InvalidArgumentError(`form '${s}' produced no owner document`);let h=eN(m,yg),g=h?.hasAttribute("Order")&&(n=h.getAttribute("Order"))!==null&&n!==void 0?n:void 0,b=h?.getAttribute("FallbackForm")||void 0;h&&m.removeChild(h);let w=!!r.everyone||((o=(i=r.roleIds)===null||i===void 0?void 0:i.length)!==null&&o!==void 0?o:0)>0;if(!w&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!h)throw new Qo.InvalidArgumentError("setFormSecurityRoles: `order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to. Pass the roles as well.");r.order!==void 0&&h.setAttribute("Order",String(r.order)),r.fallbackForm!==void 0&&h.setAttribute("FallbackForm",String(r.fallbackForm)),m.appendChild(h)}else if(w){let I=p.createElement(yg),D=r.order!==void 0?String(r.order):g;D!==void 0&&I.setAttribute("Order",D);let O=r.fallbackForm!==void 0?String(r.fallbackForm):b??"false";if(I.setAttribute("FallbackForm",O),r.everyone)I.appendChild(p.createElement("Everyone"));else for(let x of(a=r.roleIds)!==null&&a!==void 0?a:[]){let K=p.createElement("Role");K.setAttribute("Id",`{${(0,nn.normalizeGuid)(x,"roleId")}}`),I.appendChild(K)}m.appendChild(I)}let S=(0,hg.serializeNode)(m);await(0,gg.assertSystemFormContentUnchanged)(e,s,"form",l,c);let P=await(0,gg.readSystemFormRowEtag)(e,s),L=`/systemforms(${s})`;(0,_t.ensureSuccess)(await e.patch(L,{formxml:S},{headers:{"Content-Type":"application/json","If-Match":(0,_t.requireEtag)(P,"form",s)}}),e.apiUrl(L))}kt.setFormSecurityRoles=b5;function JS(e){let t=e?.formxml;return typeof t=="string"&&t.includes(YS.GENPAGE_CONTROL_NAME)?t:void 0}function bg(e,t){try{return(0,YS.activeEmbedBindings)(e)}catch(r){throw new Qo.SdkError(kt.FORM_GENPAGE_TARGET_UNVERIFIABLE,`Refusing to push the form: the ${t} formxml could not be parsed, so the generative pages it embeds cannot be verified (${r instanceof Error?r.message:String(r)}).`)}}async function ZS(e,t,r){let n=new Set(r.map(([a,s])=>`${a}|${s}`)),i=t.filter(([a,s])=>!n.has(`${a}|${s}`)).map(([,a])=>a);if(i.length===0)return;let o=await(0,f5.findMissingGenPages)(e,i,"form generative-page preflight");if(o.length>0)throw new Qo.SdkError(kt.FORM_GENPAGE_TARGET_NOT_FOUND,`Refusing to push the form: it embeds generative page(s) ${o.map(a=>`'${a}'`).join(", ")} that do not exist in this environment. Push the page before the form that embeds it.`)}async function v5(e,t,r,n){var i;(0,_t.requireEtag)(n,"form",t);let o=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,nn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,_t.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,Zl.assertSystemFormRecordKind)(a.body,t,"form","write");let s=(0,_t.readEtag)(a);if(s===null||s!==n)throw new Qo.SdkError(_t.VERSION_CONFLICT_CODE,`Version conflict writing form '${t}': its formxml changed on the server since it was read (held ${n}, server ${s??"(unreadable)"}). Re-fetch the form and re-apply the change.`);let l=(i=a.body)===null||i===void 0?void 0:i.formxml,u=typeof l=="string"&&l!==""?bg(l,"server"):[];await ZS(e,bg(r,"payload"),u)}function eN(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 w5(e,t){var r,n;let i=(0,nn.normalizeGuid)(t,"formId"),o=`/systemforms(${i})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,nn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,_t.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,Zl.assertSystemFormRecordKind)(a.body,i,"form","read the security roles of");let s=(r=a.body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,hg.parseXmlRoot)(s,"<form/>"),u=eN(l,yg);if(!u)return;let c=[],d=!1,f=u.childNodes;for(let p=0;p<f.length;p+=1){let h=f[p];if(h.nodeType!==1)continue;let g=h;if(g.tagName==="Everyone")d=!0;else if(g.tagName==="Role"){let b=(n=g.getAttribute("Id"))!==null&&n!==void 0?n:"";b&&c.push(b.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)}:{}}}kt.getFormSecurityRoles=w5});var wg=v(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.deleteSolution=be.getDeploymentSettingsTemplate=be.importSolution=be.exportSolution=be.removeSolutionComponent=be.addSolutionComponent=be.setSolutionVersion=be.createSolution=be.createPublisher=be.getSolution=be.fetchSolutionComponents=be.resolveGenPageComponentType=be.SolutionComponentType=void 0;var C5=Lt(),xt=ye(),ar=se(),E5=dt(),Kt=Q();be.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80};var A5=[be.SolutionComponentType.SavedQuery,be.SolutionComponentType.Workflow,be.SolutionComponentType.SavedQueryVisualization,be.SolutionComponentType.SystemForm,be.SolutionComponentType.AppModule],tN="uxagentproject",rN=new WeakMap;async function lN(e){var t;let r=rN.get(e);if(r!==void 0)return r;let n=`/EntityDefinitions(LogicalName='${tN}')${(0,ar.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status===404)return;(0,xt.ensureSuccess)(i,e.apiUrl(n));let o=(t=i.body)===null||t===void 0?void 0:t.ObjectTypeCode;if(typeof o!="number"||!Number.isInteger(o)||o<=0)throw new Kt.SdkError("GENPAGE_COMPONENT_TYPE_UNRESOLVED",`A generative page's solution component type \u2014 the ObjectTypeCode of '${tN}' \u2014 could not be read: its metadata answered without a usable value (${JSON.stringify(o)}). Without it a solution's generative pages cannot be told apart from other components. Retry.`);return rN.set(e,o),o}be.resolveGenPageComponentType=lN;var nN=1,iN=0;async function S5(e,t){let r=(0,ar.normalizeGuid)(t,"solutionId"),n=await lN(e),o=[nN,...A5,...n===void 0?[]:[n]].map(c=>`componenttype eq ${c}`).join(" or "),a=`/solutioncomponents${(0,ar.odataQuery)([["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${r} and (${o})`]])}`,s=await(0,C5.collectPages)(e,a,"fetchSolutionComponents"),l=[];for(let c of s){if(typeof c.objectid!="string")continue;let d=Number(c.componenttype);if(d===nN){let f=c.rootcomponentbehavior;(f===iN||f===String(iN))&&l.push({objectId:c.objectid,componentType:d,includesAllSubcomponents:!0});continue}l.push({objectId:c.objectid,componentType:d,...n!==void 0&&d===n?{genPage:!0}:{}})}let u=c=>c.objectId.toLowerCase().replace(/^\{|\}$/g,"");return l.sort((c,d)=>c.componentType-d.componentType||(u(c)<u(d)?-1:u(c)>u(d)?1:0))}be.fetchSolutionComponents=S5;function N5(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 _5(e,t){var r,n,i,o,a,s,l,u,c,d;let f=String(t??"").trim();if(!f)throw new Kt.InvalidArgumentError("getSolution: a solution unique name or id is required.");let m=N5(f)?`solutionid eq ${(0,ar.normalizeGuid)(f,"solutionId")}`:`uniquename eq '${(0,ar.odataLiteral)(f)}'`,p=`/solutions${(0,ar.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",m]])}`,b=((n=(r=(0,xt.ensureSuccess)(await e.get(p),e.apiUrl(p)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!b?.solutionid)throw new Kt.InvalidArgumentError(`No solution found for '${t}'.`);let w=b.publisherid;if(!w?.publisherid)throw new Kt.InvalidArgumentError(`Solution '${(i=b.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in w))throw new Kt.InvalidArgumentError(`Solution '${(o=b.uniquename)!==null&&o!==void 0?o:t}' returned a publisher without a customizationprefix property (partial expansion), so its prefix cannot be determined.`);return{solutionId:(0,ar.normalizeGuid)(b.solutionid,"solutionId"),uniqueName:(a=b.uniquename)!==null&&a!==void 0?a:"",friendlyName:(s=b.friendlyname)!==null&&s!==void 0?s:"",version:(l=b.version)!==null&&l!==void 0?l:"",isManaged:!!b.ismanaged,publisherId:(0,ar.normalizeGuid)(w.publisherid,"publisherId"),publisherUniqueName:(u=w.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=w.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=w.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}be.getSolution=_5;async function T5(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,xt.ensureSuccess)(await(0,xt.resendDeadlockVictim)(()=>e.post("/publishers",{...n})),e.apiUrl("/publishers")),o=(0,xt.readCreatedId)(i,"publisherid");if(!o)throw new Kt.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}be.createPublisher=T5;async function D5(e,t){var r;let n=(0,ar.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 o=(0,xt.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,xt.readCreatedId)(o,"solutionid");if(!a)throw new Kt.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}be.createSolution=D5;async function I5(e,t,r){let i=`/solutions(${(0,ar.normalizeGuid)(t,"solutionId")})`;(0,xt.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}be.setSolutionVersion=I5;async function O5(e,t){var r;let i={ComponentId:(0,ar.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,xt.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}be.addSolutionComponent=O5;async function P5(e,t,r,n){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,ar.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,xt.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}be.removeSolutionComponent=P5;async function R5(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},a=(n=(0,xt.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!a)throw new Kt.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}be.exportSolution=R5;async function L5(e,t){let r=[["overwriteUnmanagedCustomizations","overwrote unmanaged customizations made over the solution's components"],["publishWorkflows","activated the solution's workflows"]];for(let[a,s]of r)if(typeof t?.[a]!="boolean")throw new Kt.InvalidArgumentError(`importSolution: '${a}' is required and must be true or false (it was ${String(t?.[a])}). It used to default to true, which ${s} unless the caller said otherwise. Nothing was imported.`);let n=t.deploymentSettings===void 0?void 0:W5(t.deploymentSettings),i={OverwriteUnmanagedCustomizations:t.overwriteUnmanagedCustomizations,PublishWorkflows:t.publishWorkflows,CustomizationFile:t.base64,ImportJobId:t.importJobId?(0,ar.normalizeGuid)(t.importJobId,"importJobId"):(0,E5.newId)()};if(!n)return(0,xt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{};if(n.variables.length===0&&n.references.length===0)return(0,xt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:{environmentVariables:[],connectionReferences:[]}};let o=[];try{let a=await uN(e,t.base64,eu,o),{parameters:s,applied:l}=z5(a,n);return i.ComponentParameters=s,(0,xt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:l,...o.length>0?{warnings:o}:{}}}catch(a){throw(0,Kt.withCleanupWarnings)(a,o)}}be.importSolution=L5;var eu="importSolution",oN="getDeploymentSettingsTemplate";async function k5(e,t){var r;let n=t?.base64;if(typeof n!="string"||n.length===0)throw new Kt.InvalidArgumentError(`${oN}: 'base64' must be the solution package \u2014 a non-empty base64 string, e.g. exportSolution's result (it was ${(r=JSON.stringify(n))!==null&&r!==void 0?r:String(n)})`);let i=[];try{let o=await uN(e,n,oN,i),a=Ad(o.variables,l=>l.SchemaName).map(({SchemaName:l,DefaultValue:u,TypeId:c,IsRequired:d})=>({SchemaName:l,Value:"",...u!==void 0?{DefaultValue:u}:{},...c!==void 0?{TypeId:c}:{},...d!==void 0?{IsRequired:d}:{}})),s=Ad(o.references,l=>l.LogicalName).map(({LogicalName:l,ConnectorId:u})=>({LogicalName:l,ConnectionId:"",...u!==void 0?{ConnectorId:u}:{}}));return{settings:{EnvironmentVariables:a,ConnectionReferences:s},...i.length>0?{warnings:i}:{}}}catch(o){throw(0,Kt.withCleanupWarnings)(o,i)}}be.getDeploymentSettingsTemplate=k5;function Ad(e,t){return[...e].sort((r,n)=>{let i=t(r).toLowerCase(),o=t(n).toLowerCase();return i<o?-1:i>o?1:0})}function Xo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $t(e,t=120){var r;let n=(r=JSON.stringify(e))!==null&&r!==void 0?r:String(e);return n.length>t?`${n.slice(0,t)}\u2026`:n}async function uN(e,t,r,n){var i;let a=(i=(0,xt.ensureSuccess)(await e.post("/StageSolution",{CustomizationFile:t}),e.apiUrl("/StageSolution")).body)===null||i===void 0?void 0:i.StageSolutionResults;try{return x5(a,r)}finally{await $5(e,Xo(a)?a.StageSolutionUploadId:void 0,n)}}async function $5(e,t,r){let n;try{n=(0,ar.normalizeGuid)(t,"StageSolutionUploadId")}catch{r.push(`StageSolution's reply named no usable staging upload id (${$t(t,60)}), so the staged copy of the package it may have stored (a stagesolutionupload row of yours) could not be deleted.`);return}let i=`/stagesolutionuploads(${n})`;try{let o=await e.delete(i);o.status!==404&&(0,xt.ensureSuccess)(o,e.apiUrl(i))}catch(o){r.push(`The staged copy of the package (stagesolutionupload ${n}) could not be deleted: ${o instanceof Error?o.message:String(o)}. It stays until it is deleted (DELETE ${i}).`)}}function or(e,t){return new Kt.SdkError("SOLUTION_STAGING_UNREADABLE",`${e}: StageSolution's reply could not be read \u2014 ${t}.${e===eu?" Nothing was imported.":""}`)}function aN(e){return!Array.isArray(e)||e.length===0?"none":`${e.slice(0,5).map(r=>Xo(r)&&typeof r.Message=="string"?r.Message:$t(r,200)).join("; ")}${e.length>5?` (+${e.length-5} more)`:""}`}function x5(e,t){if(!Xo(e))throw or(t,`it holds no StageSolutionResults (${$t(e,60)})`);let r=e.StageSolutionStatus;if(r==="Failed"||r===0)throw new Kt.SdkError("SOLUTION_STAGING_FAILED",`${t}: the package did not pass StageSolution in this environment (status ${$t(r)}). Missing dependencies: ${aN(e.MissingDependencies)}. Validation: ${aN(e.SolutionValidationResults)}.${t===eu?" Its components cannot be checked against deploymentSettings. Nothing was imported.":" Stage it in the environment it was exported from."}`);if(r!=="Passed"&&r!==1)throw or(t,`StageSolutionStatus is ${$t(r)}, neither "Passed" nor "Failed"`);let n=e.SolutionComponentsDetails;if(!Array.isArray(n))throw or(t,`SolutionComponentsDetails is not a list (${$t(n,60)})`);let i=[],o=[],a=new Set,s=new Set;return n.forEach((l,u)=>{let c=`SolutionComponentsDetails[${u}]`;if(!Xo(l))throw or(t,`${c} is not an object`);if(typeof l.ComponentTypeName!="string")throw or(t,`${c}.ComponentTypeName is not a string`);let d=l.ComponentTypeName.toLowerCase();if(d!=="environmentvariabledefinition"&&d!=="connectionreference")return;let f=F5(l.Attributes,`${c}.Attributes`,t),m=(p,h)=>{let g=f.get(p);if(g==null){if(h)throw or(t,`${c}.${p} is missing`);return}if(typeof g!="string"||h&&g.length===0)throw or(t,`${c}.${p} is not ${h?"a non-empty string":"a string"}`);return g};if(d==="environmentvariabledefinition"){let p=m("schemaname",!0);if(a.has(p.toLowerCase()))throw or(t,`${c}.schemaname '${p}' is listed twice`);a.add(p.toLowerCase());let h=m("defaultvalue",!1),g=M5(f.get("type"),`${c}.type`,t),b=U5(f.get("isrequired"),`${c}.isrequired`,t);i.push({SchemaName:p,...h!==void 0?{DefaultValue:h}:{},...g!==void 0?{TypeId:g}:{},...b!==void 0?{IsRequired:b}:{}})}else{let p=m("connectionreferencelogicalname",!0);if(s.has(p.toLowerCase()))throw or(t,`${c}.connectionreferencelogicalname '${p}' is listed twice`);s.add(p.toLowerCase());let h=m("connectorid",!1);o.push({LogicalName:p,...h!==void 0?{ConnectorId:h}:{}})}}),{variables:i,references:o}}function F5(e,t,r){if(!Xo(e)||!Array.isArray(e.Keys)||!Array.isArray(e.Values))throw or(r,`${t} is not { Keys: [...], Values: [...] }`);let{Keys:n,Values:i}=e;if(n.length!==i.length)throw or(r,`${t} has ${n.length} keys but ${i.length} values`);let o=new Map;return n.forEach((a,s)=>{if(typeof a!="string")throw or(r,`${t}.Keys[${s}] is not a string`);if(o.has(a))throw or(r,`${t}.Keys lists '${a}' twice`);o.set(a,i[s])}),o}function M5(e,t,r){if(e!=null){if(typeof e=="number"&&Number.isSafeInteger(e))return e;if(typeof e=="string"&&/^\d{1,15}$/.test(e))return Number(e);throw or(r,`${t} is not a whole number (${$t(e,40)})`)}}function U5(e,t,r){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"&&/^(true|false)$/i.test(e))return e.toLowerCase()==="true";throw or(r,`${t} is not true or false (${$t(e,40)})`)}}var B5=new Set(["EnvironmentVariables","ConnectionReferences","Workflows","CanvasApps","CopilotAgents","$schema"]),q5=["Workflows","CanvasApps","CopilotAgents"],V5=new Set(["SchemaName","Value","DefaultValue","TypeId","IsRequired","Name"]),G5=new Set(["LogicalName","ConnectionId","ConnectorId"]);function ir(e,t){return new Kt.InvalidArgumentError(`${eu}: deploymentSettings is not a deployment-settings file this SDK applies \u2014 ${e} ${t}. Nothing was imported.`)}function W5(e){let t="deploymentSettings";if(!Xo(e))throw ir(t,`must be an object \u2014 the settings file, parsed (it was ${$t(e,40)})`);for(let l of Object.keys(e))if(!B5.has(l))throw ir(`${t}.${l}`,"is not part of the format (EnvironmentVariables, ConnectionReferences; Workflows, CanvasApps and CopilotAgents only empty; $schema)");for(let l of q5){let u=e[l];if(u!==void 0&&!(Array.isArray(u)&&u.length===0))throw ir(`${t}.${l}`,"is a pac feature this SDK does not apply: only an empty list is accepted")}if(e.$schema!==void 0&&typeof e.$schema!="string")throw ir(`${t}.$schema`,"must be a string");let r=l=>{let u=e[l];if(u===void 0)return[];if(!Array.isArray(u))throw ir(`${t}.${l}`,`must be a list (it was ${$t(u,40)})`);return u.map((c,d)=>{if(!Xo(c))throw ir(`${t}.${l}[${d}]`,`must be an object (it was ${$t(c,40)})`);return c})},n=(l,u,c)=>{let d=l[u];if(typeof d!="string"||d.length===0)throw ir(c,`must be a non-empty string (it was ${$t(d,40)})`);if(d.trim()!==d)throw ir(c,`must not begin or end with whitespace (it was ${$t(d,60)})`);return d},i=(l,u,c)=>{if(l.has(u.toLowerCase()))throw ir(c,`names '${u}' a second time (names are case-insensitive)`);l.add(u.toLowerCase())},o={variables:[],references:[]},a=new Set;r("EnvironmentVariables").forEach((l,u)=>{let c=`${t}.EnvironmentVariables[${u}]`;for(let f of Object.keys(l))if(!V5.has(f))throw ir(`${c}.${f}`,"is not part of a variable (SchemaName, Value; DefaultValue, TypeId, IsRequired, Name)");let d=n(l,"SchemaName",`${c}.SchemaName`);if(i(a,d,`${c}.SchemaName`),typeof l.Value!="string")throw ir(`${c}.Value`,`must be a string \u2014 empty to override nothing (it was ${$t(l.Value,40)})`);l.Value.length>0&&o.variables.push({name:d,value:l.Value})});let s=new Set;return r("ConnectionReferences").forEach((l,u)=>{let c=`${t}.ConnectionReferences[${u}]`;for(let m of Object.keys(l))if(!G5.has(m))throw ir(`${c}.${m}`,m==="ConnectionInstance"?"is pac's connection-instance feature, which this SDK does not apply":"is not part of a connection reference (LogicalName, ConnectionId, ConnectorId)");let d=n(l,"LogicalName",`${c}.LogicalName`);i(s,d,`${c}.LogicalName`);let f=l.ConnectionId;if(typeof f!="string")throw ir(`${c}.ConnectionId`,`must be a string \u2014 empty to bind nothing (it was ${$t(f,40)})`);if(f.trim()!==f)throw ir(`${c}.ConnectionId`,`must not begin or end with whitespace (it was ${$t(f,60)})`);if(l.ConnectorId!==void 0&&typeof l.ConnectorId!="string")throw ir(`${c}.ConnectorId`,`must be a string (it was ${$t(l.ConnectorId,40)})`);f.length>0&&o.references.push({name:d,connectionId:f,...l.ConnectorId?{connectorId:l.ConnectorId}:{}})}),o}function sN(e,t=20){return e.length===0?"none":`${e.slice(0,t).join(", ")}${e.length>t?` (+${e.length-t} more)`:""}`}function z5(e,t){var r;let n=new Map(e.variables.map(l=>[l.SchemaName.toLowerCase(),l])),i=new Map(e.references.map(l=>[l.LogicalName.toLowerCase(),l])),o=[],a=[],s={environmentVariables:[],connectionReferences:[]};for(let l of t.variables){let u=n.get(l.name.toLowerCase());if(!u){o.push(`EnvironmentVariables: '${l.name}' is not a variable of the package`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.environmentvariablevalue",schemaname:u.SchemaName,value:l.value}),s.environmentVariables.push(u.SchemaName)}for(let l of t.references){let u=i.get(l.name.toLowerCase());if(!u){o.push(`ConnectionReferences: '${l.name}' is not a connection reference of the package`);continue}if(l.connectorId!==void 0&&l.connectorId.toLowerCase()!==((r=u.ConnectorId)===null||r===void 0?void 0:r.toLowerCase())){o.push(`ConnectionReferences: '${l.name}' names connector '${l.connectorId}', but the package's reference is for ${u.ConnectorId?`'${u.ConnectorId}'`:"no connector"}`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.connectionreference",connectionreferencelogicalname:u.LogicalName,connectionid:l.connectionId,...u.ConnectorId!==void 0?{connectorid:u.ConnectorId}:{}}),s.connectionReferences.push(u.LogicalName)}if(o.length>0){let l=o.join("; "),u=sN(Ad(e.variables,d=>d.SchemaName).map(d=>d.SchemaName)),c=sN(Ad(e.references,d=>d.LogicalName).map(d=>d.LogicalName));throw new Kt.InvalidArgumentError(`${eu}: deploymentSettings does not match the package \u2014 ${l}. The package's variables: ${u}; its connection references: ${c}. Nothing was imported.`)}return{parameters:a,applied:s}}async function j5(e,t){let n=`/solutions(${(0,ar.normalizeGuid)(t,"solutionId")})`;(0,xt.ensureSuccess)(await e.delete(n),e.apiUrl(n))}be.deleteSolution=j5});var hN=v(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.recoverFormCreate=ft.solutionMembershipProblem=ft.formWriteMismatches=ft.validateExistingForm=ft.formExistsAtId=ft.isFormRecordAt=ft.MAIN_FORM_TYPE=void 0;var us=se(),cN=Lt(),dN=wg();ft.MAIN_FORM_TYPE=2;function Sd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nd(e){return e instanceof Error?e.message:String(e)}function Cg(e,t){if(typeof e!="string"||typeof t!="string")return!1;try{return(0,us.normalizeGuid)(e,"a GUID")===(0,us.normalizeGuid)(t,"a GUID")}catch{return!1}}function Eg(e,t){return Sd(e)&&Cg(e.formid,t)}ft.isFormRecordAt=Eg;async function H5(e,t){try{return Eg((await e()).raw,t)}catch{return!1}}ft.formExistsAtId=H5;function fN(e,t){let r=e.raw;if(!Sd(r))return{problem:"it is not a record"};if(!Eg(r,t))return{problem:"its formid is not the id this create sent"};if(r.type!==ft.MAIN_FORM_TYPE)return{problem:`its type is not ${ft.MAIN_FORM_TYPE} (a Main form)`};if(typeof r.objecttypecode!="string")return{problem:"its objecttypecode is not a string"};if(typeof r.name!="string")return{problem:"its name is not a string"};if(typeof r.formxml!="string"||r.formxml.length===0)return{problem:"its formxml is not a non-empty string"};if(typeof r.formpresentation!="number")return{problem:"its formpresentation is not a number"};if(typeof r.formactivationstate!="number")return{problem:"its formactivationstate is not a number"};for(let o of["uniquename","description"]){let a=r[o];if(a!=null&&typeof a!="string")return{problem:`its ${o} is neither a string nor null`}}let n=r["@odata.etag"];if(n!==void 0&&typeof n!="string")return{problem:"its @odata.etag is not a string"};if(n!==void 0&&e.etag!==null&&e.etag!==n)return{problem:"the ETag header and the @odata.etag of the body disagree"};let i=e.etag;return i===null?{problem:"the read carries no concurrency token"}:i.trim()===""||i.trim()==="*"?{problem:"its concurrency token is blank or a wildcard"}:{record:r,etag:i}}ft.validateExistingForm=fN;function pN(e,t){let r=[];for(let i of["formxml","name","objecttypecode","type"])e[i]!==t[i]&&r.push(i);let n=t.description;if(n!==void 0){let i=e.description;typeof n=="string"&&(n===""?i==null||i==="":i===n)||r.push("description")}return r}ft.formWriteMismatches=pN;async function mN(e,t){let r=e.solutionName;if(r)try{let n=await(0,cN.collectPages)(e,`/solutions${(0,us.odataQuery)([["$select","solutionid,uniquename"],["$filter",`uniquename eq '${(0,us.odataLiteral)(r)}'`]])}`,"createRecovery solution lookup");if(n.length!==1)return`the configured solution '${r}' resolves to ${n.length} solutions, not exactly one`;let[i]=n,o;return Sd(i)&&typeof i.uniquename=="string"&&typeof i.solutionid=="string"&&i.uniquename.toLowerCase()===r.toLowerCase()&&(o=(0,us.normalizeGuid)(i.solutionid,"solutionid")),o===void 0?`the configured solution '${r}' did not resolve to a valid solution of that name`:(await(0,cN.collectPages)(e,`/solutioncomponents${(0,us.odataQuery)([["$select","objectid,componenttype,_solutionid_value"],["$filter",`_solutionid_value eq ${o} and componenttype eq ${dN.SolutionComponentType.SystemForm} and objectid eq ${t}`]])}`,"createRecovery solution membership")).some(l=>Sd(l)&&l.componenttype===dN.SolutionComponentType.SystemForm&&Cg(l.objectid,t)&&Cg(l._solutionid_value,o))?void 0:`the form is not a component of the configured solution '${r}'`}catch(n){return`membership in the configured solution '${r}' could not be established (${Nd(n)})`}}ft.solutionMembershipProblem=mN;async function K5(e){try{return await J5(e)}catch(t){return{refused:`the recovery could not be completed (${Nd(t)})`}}}ft.recoverFormCreate=K5;async function J5(e){let{client:t,read:r,sent:n,authoredFormType:i,project:o}=e;if(i!=="Main"||n.type!==ft.MAIN_FORM_TYPE)return{refused:`only a Main form is adopted (this one is authored as ${String(i)})`};let a=n.formid;if(typeof a!="string")return{refused:"the create sent no formid to look for"};let s;try{s=await r()}catch(f){return{refused:`the existing row could not be read (${Nd(f)})`}}let l=fN(s,a);if("problem"in l)return{refused:`the existing row cannot be trusted: ${l.problem}`};let u=pN(l.record,n);if(u.length>0)return{refused:`the existing row is not what this create wrote (it differs in ${u.join(", ")})`};let c;try{c=o(l.record)}catch(f){return{refused:`the existing row could not be read into a form (${Nd(f)})`}}let d=await mN(t,a);return d!==void 0?{refused:d}:{adopted:{artifact:c,etag:l.etag}}}});var Td=v(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.disassociateRecords=Je.associateRecords=Je.createRecordsBulk=Je.upsertRecord=Je.queryAllRecords=Je.queryRecords=Je.getRecord=Je.deleteRecord=Je.updateRecord=Je.createRecord=void 0;var Ag=Lt(),Sn=ye(),Jt=se(),cs=Q(),Jn=cd();function _d(e){let t=e,r=!1,n={};for(let i of Object.keys(t)){let o=t[i];Array.isArray(o)&&o.every(a=>typeof a=="number")?(n[i]=o.join(","),r=!0):n[i]=o}return r?n:e}async function Y5(e,t,r){let i=`/${await(0,Jn.resolveEntitySetName)(e,t)}`,o=(0,Sn.ensureSuccess)(await e.post(i,_d(r)),e.apiUrl(i)),a=(0,Sn.readCreatedId)(o,`${t}id`);if(!a)throw new cs.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}Je.createRecord=Y5;async function Q5(e,t,r,n){let i=(0,Jt.normalizeGuid)(r,"id"),a=`/${await(0,Jn.resolveEntitySetName)(e,t)}(${i})`;(0,Sn.ensureSuccess)(await e.patch(a,_d(n)),e.apiUrl(a))}Je.updateRecord=Q5;async function X5(e,t,r){let n=(0,Jt.normalizeGuid)(r,"id"),o=`/${await(0,Jn.resolveEntitySetName)(e,t)}(${n})`;(0,Sn.ensureSuccess)(await e.delete(o),e.apiUrl(o))}Je.deleteRecord=X5;async function Z5(e,t,r,n){let i=(0,Jt.normalizeGuid)(r,"id"),o=await(0,Jn.resolveEntitySetName)(e,t),a=(0,Jt.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),s=`/${o}(${i})${a}`,l=(0,Sn.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=l.body;if(u===null||typeof u!="object"||Array.isArray(u))throw new cs.ConnectionError(e.apiUrl(s),l.status,`getRecord: read returned a malformed row \u2014 expected an OData entity object but got ${Array.isArray(u)?"an array":(0,Ag.describeMalformedValue)(u)}; refusing to read it as a row.`);return u}Je.getRecord=Z5;function e8(e){return e?.fetchXml?(0,Jt.odataQuery)([["fetchXml",e.fetchXml]]):(0,Jt.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 gN(e,t,r){var n;if(r?.paginate){if(r.top!==void 0)throw new cs.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 cs.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,Jn.resolveEntitySetName)(e,t)}${e8(r)}`;if(r?.paginate)return(0,Ag.collectPages)(e,o,"queryRecords");let a=(0,Sn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new cs.ConnectionError(e.apiUrl(o),a.status,`queryRecords: read returned a malformed page \u2014 expected an OData 'value' array but got ${(0,Ag.describeMalformedValue)(s)}; refusing to read it as rows.`);return s}Je.queryRecords=gN;async function t8(e,t,r){return gN(e,t,{...r,paginate:!0})}Je.queryAllRecords=t8;function r8(e){if("id"in e)return`(${(0,Jt.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,Jt.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,Jt.assertODataName)(e.key,"alternate key name")}=${t})`}async function n8(e,t,r,n){let i=r8(r),a=`/${await(0,Jn.resolveEntitySetName)(e,t)}${i}`,s=(0,Sn.ensureSuccess)(await e.patch(a,_d(n)),e.apiUrl(a)),l=s.status===201,u=(0,Sn.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,Jt.normalizeGuid)(r.id,"id"):""),created:l}}Je.upsertRecord=n8;async function i8(e,t,r){var n,i;if(r.length===0)return[];let o=await(0,Jn.resolveEntitySetName)(e,t),a=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,..._d(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Sn.ensureSuccess)(await e.post(s,{Targets:a}),e.apiUrl(s)).body)===null||n===void 0?void 0:n.Ids)!==null&&i!==void 0?i:[];if(u.length!==r.length)throw new cs.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Je.createRecordsBulk=i8;async function o8(e,t,r,n){let i=(0,Jt.normalizeGuid)(r,"id"),o=(0,Jt.normalizeGuid)(n.targetId,"targetId"),a=await(0,Jn.resolveEntitySetName)(e,t),s=await(0,Jn.resolveEntitySetName)(e,n.targetEntity),l=(0,Jt.assertODataName)(n.relationshipName,"relationshipName"),u=`/${a}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,Sn.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Je.associateRecords=o8;async function a8(e,t,r,n,i){let o=(0,Jt.normalizeGuid)(r,"id"),a=(0,Jt.normalizeGuid)(i,"targetId"),s=await(0,Jn.resolveEntitySetName)(e,t),l=(0,Jt.assertODataName)(n,"relationshipName"),u=`/${s}(${o})/${l}(${a})/$ref`;(0,Sn.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Je.disassociateRecords=a8});var Dd=v(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.base64ToUtf8=on.base64ToBytes=on.bytesToBase64=on.utf8ToBase64=on.utf8ToBytes=void 0;var Sg=32768,Nr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function tu(){return globalThis}function yN(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=r+1<e.length?e.charCodeAt(r+1):0;i>=56320&&i<=57343?(n=(n-55296<<10)+(i-56320)+65536,r+=1):n=65533}else n>=56320&&n<=57343&&(n=65533);n<128?t.push(n):n<2048?t.push(192|n>>6,128|n&63):n<65536?t.push(224|n>>12,128|n>>6&63,128|n&63):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return Uint8Array.from(t)}function s8(e){let t="";for(let r=0;r<e.length;r+=Sg)t+=String.fromCharCode(...e.subarray(r,r+Sg));return t}function l8(e){let t="";for(let r=0;r<e.length;r+=1){let n=String.fromCharCode(e.charCodeAt(r)&255);if(n==="=")break;n==="-"?t+="+":n==="_"?t+="/":Nr.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function u8(e){let t="",r=0;for(;r+2<e.length;r+=3){let i=e[r]<<16|e[r+1]<<8|e[r+2];t+=Nr[i>>18&63]+Nr[i>>12&63]+Nr[i>>6&63]+Nr[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Nr[i>>18&63]}${Nr[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,o=Nr[i>>18&63],a=Nr[i>>12&63],s=Nr[i>>6&63];t+=`${o}${a}${s}=`}return t}function c8(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0,r=e.length/4*3-t,n=new Uint8Array(r>0?r:0),i=0;for(let o=0;o<e.length;o+=4){let a=Nr.indexOf(e[o])<<18|Nr.indexOf(e[o+1])<<12|(e[o+2]==="="?0:Nr.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:Nr.indexOf(e[o+3]));i<r&&(n[i++]=a>>16&255),i<r&&(n[i++]=a>>8&255),i<r&&(n[i++]=a&255)}return n}function d8(e){let t=tu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"utf8"));let r=t.TextEncoder;return r?new r().encode(e):yN(e)}on.utf8ToBytes=d8;function f8(e){let t=tu();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return bN(r?new r().encode(e):yN(e))}on.utf8ToBase64=f8;function bN(e){let t=tu();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(s8(e)):u8(e)}on.bytesToBase64=bN;function vN(e){let t=tu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=l8(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return c8(r)}on.base64ToBytes=vN;function p8(e){let t=[],r="",n=()=>{r+=String.fromCharCode(...t),t.length=0},i=a=>{if(a>65535){let s=a-65536;t.push(55296+(s>>10),56320+(s&1023))}else t.push(a);t.length>=Sg&&n()},o=0;for(;o<e.length;){let a=e[o],s=0,l=0,u=128,c=191;if(a<128){i(a),o+=1;continue}else if(a>=194&&a<=223)s=1,l=a&31;else if(a>=224&&a<=239)s=2,l=a&15,u=a===224?160:128,c=a===237?159:191;else if(a>=240&&a<=244)s=3,l=a&7,u=a===240?144:128,c=a===244?143:191;else{i(65533),o+=1;continue}let d=o+1,f=!0;for(let m=0;m<s;m+=1,d+=1){let p=d<e.length?e[d]:-1;if(p<u||p>c){f=!1;break}u=128,c=191,l=l<<6|p&63}f?(i(l),o=d):(i(65533),o=d)}return n(),r}function m8(e){let t=tu();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):p8(vN(e))}on.base64ToUtf8=m8});var AN=v(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.deleteWebResource=Yn.getWebResource=Yn.updateWebResource=Yn.createWebResource=void 0;var h8=Jr(),ru=ye(),Id=se(),g8=Dd(),wN=Q(),y8={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function CN(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,g8.utf8ToBase64)(e.content)}async function EN(e,t){return(0,h8.publishWebResourceById)(e,t)}async function b8(e,t){var r;let n=CN(t);if(n===void 0)throw new wN.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:y8[t.type],content:n};t.description&&(i.description=t.description);let o=(0,ru.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,ru.readCreatedId)(o,"webresourceid");if(!a)throw new wN.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await EN(e,a),{id:a,name:t.name}}Yn.createWebResource=b8;async function v8(e,t,r){let n=(0,Id.normalizeGuid)(t,"id"),i={},o=CN(r);o!==void 0&&(i.content=o),r.displayName!==void 0&&(i.displayname=r.displayName),r.description!==void 0&&(i.description=r.description);let a=`/webresourceset(${n})`;(0,ru.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),r.publish!==!1&&await EN(e,n)}Yn.updateWebResource=v8;async function w8(e,t){var r;let i=`/webresourceset(${(0,Id.normalizeGuid)(t,"id")})${(0,Id.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,ru.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}Yn.getWebResource=w8;async function C8(e,t){let n=`/webresourceset(${(0,Id.normalizeGuid)(t,"id")})`;(0,ru.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Yn.deleteWebResource=C8});var Od=v(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.applyAppSettings=Tt.setAppSetting=Tt.readAppSettings=Tt.resolveSettingDefinitions=Tt.APP_SETTING_UNSET=Tt.APP_SETTING_OFF=Tt.APP_SETTING_ON=Tt.HEADER_AND_NAVIGATION_REFRESH=void 0;var ds=ye(),Ii=se();Tt.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";Tt.APP_SETTING_ON="2";Tt.APP_SETTING_OFF="1";Tt.APP_SETTING_UNSET="0";function _N(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ii.odataQuery)([["$select",e],["$filter",t]])}async function TN(e,t){var r,n;let i=[...new Set(t.filter(Boolean))],o=new Map;if(i.length===0)return o;let a=i.map(c=>`uniquename eq '${(0,Ii.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,Ii.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",a]])}`,u=((n=(r=(0,ds.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&&o.set(c.uniquename,c);return o}Tt.resolveSettingDefinitions=TN;async function E8(e,t){var r,n,i,o;let a=(0,Ii.normalizeGuid)(t,"App id"),s=_N("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${a}`),u=((n=(r=(0,ds.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(f=>f._settingdefinitionid_value).filter(Boolean))],d=new Map;if(c.length>0){let f=c.map(h=>`settingdefinitionid eq ${(0,Ii.normalizeGuid)(h,"Setting definition id")}`).join(" or "),m=`/settingdefinitions${(0,Ii.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",f]])}`,p=(0,ds.ensureSuccess)(await e.get(m),e.apiUrl(m));for(let h of((o=(i=p.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[]).filter(Boolean))h.settingdefinitionid&&d.set(h.settingdefinitionid.toLowerCase(),h)}return u.map(f=>{var m,p,h,g,b;let w=d.get(((m=f._settingdefinitionid_value)!==null&&m!==void 0?m:"").toLowerCase());return{id:(p=f.appsettingid)!==null&&p!==void 0?p:"",name:(g=(h=w?.uniquename)!==null&&h!==void 0?h:f._settingdefinitionid_value)!==null&&g!==void 0?g:"",value:(b=f.value)!==null&&b!==void 0?b:"",...w?.displayname?{displayName:w.displayname}:{}}})}Tt.readAppSettings=E8;async function SN(e,t,r){var n,i,o;let a=_N("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,ds.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(Boolean)[0];return l?.appsettingid?{id:l.appsettingid,value:(o=l.value)!==null&&o!==void 0?o:""}:void 0}async function DN(e,t,r,n){let i=(0,Ii.normalizeGuid)(t,"App id"),a=(await TN(e,[r])).get(r),s=a?.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,Ii.normalizeGuid)(s,"Setting definition id"),u=await SN(e,i,l);if(u)return NN(e,u,n);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${l})`,value:n},f,m;try{if(f=await e.post(c,d),f.status>=200&&f.status<300)return"created"}catch(h){m=h}let p;try{p=await SN(e,i,l)}catch{p=void 0}if(p)return NN(e,p,n);throw f&&(0,ds.ensureSuccess)(f,e.apiUrl(c)),m}Tt.setAppSetting=DN;async function NN(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,Ii.normalizeGuid)(t.id,"App setting id")})`;return(0,ds.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function A8(e,t,r){var n;let i=[];for(let[o,a]of Object.entries(r??{}))try{await DN(e,t,o,a)}catch(s){i.push(`App setting '${o}' was not applied: ${(n=s?.message)!==null&&n!==void 0?n:String(s)} The app was created; set it later with setAppSetting().`)}return i}Tt.applyAppSettings=A8});var Rd=v(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});Pd.HEADER_NAV_BOOLEAN_RULE=void 0;Pd.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var Tg=v(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.compileGenPage=Le.legacyEnumsNeeded=Le.createGenPageTypeScriptLoader=Le.acceptGenPageTypeScript=Le.isLoadableGenPageOutput=Le.runtimeTypesImportSpans=Le.GENPAGE_RUNTIME_TYPES_END=Le.GENPAGE_RUNTIME_TYPES_BEGIN=Le.GENPAGE_TYPESCRIPT_VERSION=void 0;var fs=Q();Le.GENPAGE_TYPESCRIPT_VERSION="5.8.3";Le.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";Le.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var Nn="./RuntimeTypes",S8="'\"`",IN=/\s/;function N8(e){return e===10||e===13||e===8232||e===8233}function _8(e,t){let r=[];e.lastIndex=0;for(let n=e.exec(t);n!==null;n=e.exec(t))r.push(n.index);return r}function LN(e){let t=[],r=Nn.length;for(let l=e.indexOf(Nn);l!==-1;l=e.indexOf(Nn,l+1)){let u=l-1;u>=0&&S8.includes(e[u])&&e[u+1+r]===e[u]&&t.push(u)}let n=[];if(t.length===0)return n;let i=-1,o=l=>{if(i<l)for(i=l;i<e.length&&e[i]!=="'"&&e[i]!=='"';)i+=1;return i},a=-1,s=l=>{for(;a+1<t.length&&t[a+1]<=l;)a+=1;return a>=0?t[a]:-1/0};for(let l=e.indexOf("import");l!==-1;){let u=l+1;if(l+6<e.length&&IN.test(e[l+6])){let c=s(o(l+6));if(c>=l+8){let d=c+2+r;for(e[d]===";"&&(d+=1);d<e.length&&IN.test(e[d]);)d+=1;n.push({start:l,end:d}),u=d}}l=e.indexOf("import",u)}return n}Le.runtimeTypesImportSpans=LN;var T8=/\b(?:import\s*['"]|export\s)/;function D8(e){let t=_8(/from\s+['"]/g,e);if(t.length===0)return!1;let r=/\bimport\s/g,n=-1,i=0;for(let o=r.exec(e);o!==null;o=r.exec(e)){let a=o.index+7;if(a>n)for(n=a;n<e.length&&!N8(e.charCodeAt(n));)n+=1;for(;i<t.length&&t[i]<a+1;)i+=1;if(i<t.length&&t[i]<n)return!0}return!1}function I8(e){return e!==void 0&&e!==""&&(T8.test(e)||D8(e))}Le.isLoadableGenPageOutput=I8;var ON=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function kN(e){var t;let r=s=>s!==null&&(typeof s=="object"||typeof s=="function")?s:void 0,n=r(e);n&&typeof n.transpileModule!="function"&&(n=(t=r(n.default))!==null&&t!==void 0?t:n);let i=n?ON.filter(s=>typeof n?.[s]!="function"):[...ON];if(!n||i.length>0)throw new fs.SdkError("GENPAGE_COMPILER_INVALID",`The TypeScript compiler supplied as MakerSdkOptions.typescript is not the typescript module (missing ${i.join(", ")}). Pass the 'typescript' package's module object, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node', or \u2014 in a bare engine \u2014 globalThis.ts after evaluating typescript@${Le.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof n.version=="string"?n.version:"",a=Le.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new fs.SdkError("GENPAGE_COMPILER_VERSION",`The TypeScript compiler supplied as MakerSdkOptions.typescript is version '${o||"unknown"}', but generative pages are compiled with ${a}.x \u2014 the version the maker portal itself uses (${Le.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${Le.GENPAGE_TYPESCRIPT_VERSION}.`);return n}Le.acceptGenPageTypeScript=kN;function O8(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new fs.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`This push must compile a generative page, but no TypeScript compiler was supplied. Pass MakerSdkOptions.typescript \u2014 in Node, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node'; in a bare engine, globalThis.ts after evaluating typescript@${Le.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(kN).catch(r=>{throw t=void 0,r instanceof fs.SdkError?r:new fs.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`The TypeScript compiler could not be loaded, so a generative page cannot be compiled (${r instanceof Error?r.message:String(r)}). Nothing was written.`)})}return t}}Le.createGenPageTypeScriptLoader=O8;var $N=e=>`${e.kind}:${e.pos}:${e.end}`;function P8(e,t){return()=>r=>{let n=i=>{let o=e.getParseTreeNode(i);o&&t.add($N(o)),e.forEachChild(i,n)};return n(r),r}}function _g(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}var R8=2301;function PN(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:_g(e),reportDiagnostics:!0,...r?{transformers:{after:[P8(e,r)]}}:{}}),o=((n=i.diagnostics)!==null&&n!==void 0?n:[]).filter(a=>a.category===e.DiagnosticCategory.Error).map(a=>{let s=a.file&&typeof a.start=="number"?a.file.getLineAndCharacterOfPosition(a.start):{line:0,character:0};return{line:s.line+1,column:s.character+1,rule:"genpage-source-syntax",code:a.code,message:e.flattenDiagnosticMessageText(a.messageText,`
-`)}});return{code:i.outputText,diagnostics:o}}var RN=e=>e.startsWith(".")||e.startsWith("/"),Ld={line:1,column:1};function Ng(e,t){let r=o=>{let a=t.getLineAndCharacterOfPosition(o.getStart(t));return{line:a.line+1,column:a.character+1}},n=o=>(e.isImportDeclaration(o)||e.isExportDeclaration(o))&&o.moduleSpecifier&&e.isStringLiteral(o.moduleSpecifier)?o.moduleSpecifier.text:void 0,i=o=>t.statements.filter(a=>e.isImportDeclaration(a)&&n(a)===o);return{statement(o,a){let s=t.statements.find(l=>n(l)===o&&(a==="import"?e.isImportDeclaration(l):e.isExportDeclaration(l)));return s?r(s):Ld},element(o,a){var s;for(let l of i(o)){let u=(s=l.importClause)===null||s===void 0?void 0:s.namedBindings,c=u&&e.isNamedImports(u)?u.elements.find(d=>d.name.text===a):void 0;if(c)return r(c)}return this.statement(o,"import")},binding(o){var a,s;for(let l of t.statements)if(e.isImportDeclaration(l)&&l.importClause){let u=l.importClause,c=u.namedBindings,d=((a=u.name)===null||a===void 0?void 0:a.text)===o?u.name:c&&e.isNamespaceImport(c)&&c.name.text===o?c.name:c&&e.isNamedImports(c)?c.elements.find(f=>f.name.text===o):void 0;if(d)return r(d)}else{if((e.isFunctionDeclaration(l)||e.isClassDeclaration(l))&&((s=l.name)===null||s===void 0?void 0:s.text)===o)return r(l.name);if(e.isVariableStatement(l)){let u=l.declarationList.declarations.find(c=>e.isIdentifier(c.name)&&c.name.text===o);if(u)return r(u.name)}}return Ld}}}function L8(e,t,r,n){var i,o;let a=[],s=Ng(e,r),l=(p,h,g)=>{a.push({...p,rule:h,code:0,message:g})},u=(p,h)=>{var g;return(e.canHaveModifiers(p)?(g=e.getModifiers(p))!==null&&g!==void 0?g:[]:[]).some(b=>b.kind===h)},c=(p,h)=>l(p,"genpage-relative-import",`'${h}' cannot resolve at runtime: the page is loaded as a single module from a blob URL, so the only relative import it may have is './RuntimeTypes'`),d="genpage-runtime-types-import-form",f=!1,m=new Set;for(let p of t.statements){if(e.isExportAssignment(p)){f=f||!p.isExportEquals;continue}if(e.isFunctionDeclaration(p)||e.isClassDeclaration(p)){u(p,e.SyntaxKind.ExportKeyword)&&u(p,e.SyntaxKind.DefaultKeyword)&&(f=!0),p.name&&m.add(p.name.text);continue}if(e.isExportDeclaration(p)){let w=p.exportClause;w&&e.isNamedExports(w)&&w.elements.some(S=>S.name.text==="default")&&(f=!0);let E=p.moduleSpecifier&&e.isStringLiteral(p.moduleSpecifier)?p.moduleSpecifier.text:void 0;E===Nn?l(s.statement(E,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):E!==void 0&&RN(E)&&c(s.statement(E,"export"),E);continue}if(!e.isImportDeclaration(p)||!e.isStringLiteral(p.moduleSpecifier))continue;let h=p.moduleSpecifier.text,g=p.importClause;if(h!==Nn){RN(h)&&c(s.statement(h,"import"),h),g?.name&&m.add(g.name.text);let w=g?.namedBindings;w&&e.isNamespaceImport(w)?m.add(w.name.text):w&&e.isNamedImports(w)&&w.elements.forEach(E=>m.add(E.name.text));continue}if(!g){l(s.statement(h,"import"),d,"a side-effect import of './RuntimeTypes' cannot resolve at runtime; import the names it declares");continue}g.name&&l(s.binding(g.name.text),d,"'./RuntimeTypes' has no default export at runtime; import its names");let b=g.namedBindings;if(b&&e.isNamespaceImport(b))l(s.binding(b.name.text),d,"a namespace import of './RuntimeTypes' is undefined at runtime \u2014 its enums are inlined under their own names; import the names instead");else if(b&&e.isNamedImports(b))for(let w of b.elements){let E=w.name.text,S=(o=(i=w.propertyName)===null||i===void 0?void 0:i.text)!==null&&o!==void 0?o:E,P=s.element(h,E);S!==E?l(P,d,`'${S} as ${E}' would be undefined at runtime: the enum is inlined as '${S}', so import it under its own name`):n?.text?n.enums.has(E)||l(P,"genpage-runtime-types-unresolved",`'${E}' is imported from './RuntimeTypes' as a VALUE, but the runtime types define no value of that name \u2014 only the choice enums of the page's data sources are values. Import a type with 'import type'.`):l(P,"genpage-runtime-types-unresolved",`'${E}' is imported from './RuntimeTypes' as a VALUE, but the page has no data sources, so no runtime types are inlined and the import reaches the runtime, which cannot load it. Import it with 'import type', or add the table it belongs to to dataSources.`)}}if(f||l(Ld,"genpage-no-default-export","the page has no default export \u2014 the runtime renders the module's default export as the page component"),n?.text)for(let p of m)n.enums.has(p)&&l(s.binding(p),"genpage-runtime-types-collision",`'${p}' is declared at the page's module scope and is also one of its inlined choice enums, so the compiled page would declare it twice and fail to load. Rename the page's binding, or import the enum from './RuntimeTypes'.`);return a}function xN(e,t,r){let n,i=()=>{if(!n){let p={getSourceFile:g=>g===t.fileName?t:void 0,getDefaultLibFileName:()=>"lib.d.ts",writeFile:()=>{},getCurrentDirectory:()=>"",getCanonicalFileName:g=>g,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>`
-`,fileExists:g=>g===t.fileName,readFile:()=>{},directoryExists:()=>!0,getDirectories:()=>[]},h={...r,noLib:!0,noResolve:!0,allowJs:!0,types:[],alwaysStrict:!0,moduleDetection:e.ModuleDetectionKind.Force};n=e.createProgram({rootNames:[t.fileName],options:h,host:p})}return n},o,a=()=>(o||(o=i().getTypeChecker()),o),s,l=()=>{if(!s){s=new Map;try{for(let p of i().getSemanticDiagnostics(t))p.code===R8&&typeof p.start=="number"&&s.set(p.start,e.flattenDiagnosticMessageText(p.messageText," "))}catch{}}return s},u=p=>e.isImportSpecifier(p)?p.parent.parent.parent:e.isImportClause(p)?p.parent:e.isNamespaceImport(p)?p.parent.parent:void 0,c=p=>{let h=u(p);return h!==void 0&&e.isImportDeclaration(h)&&e.isStringLiteral(h.moduleSpecifier)&&h.moduleSpecifier.text===Nn},d=p=>{var h;for(let g=p;g;g=g.parent)if(e.canHaveModifiers(g)&&((h=e.getModifiers(g))!==null&&h!==void 0?h:[]).some(b=>b.kind===e.SyntaxKind.DeclareKeyword))return!0;return!1},f=p=>d(p)||e.isImportEqualsDeclaration(p)&&(p.isTypeOnly||e.isExternalModuleReference(p.moduleReference))||e.isImportClause(p)&&p.isTypeOnly||e.isNamespaceImport(p)&&p.parent.isTypeOnly||e.isImportSpecifier(p)&&(p.isTypeOnly||p.parent.parent.isTypeOnly),m=p=>{var h;return((h=p?.declarations)!==null&&h!==void 0?h:[]).some(g=>!c(g)&&!f(g))};return{pageOwns:p=>{let h=p.parent;return m(e.isShorthandPropertyAssignment(h)&&h.name===p?a().getShorthandAssignmentValueSymbol(h):a().getSymbolAtLocation(p))},pageOwnsLocalExport:p=>m(a().getExportSpecifierLocalTargetSymbol(p)),initializerShadow:p=>l().get(p.getStart(t))}}function k8(e,t,r,n){let i=[],o=r?.enums;if(!o||o.size===0)return i;let a=(u,c,d)=>{let f=t.getLineAndCharacterOfPosition(u.getStart(t));i.push({line:f.line+1,column:f.character+1,rule:c,code:0,message:d})},s=xN(e,t,_g(e)),l=u=>{let c,d;if(e.isPropertyAccessExpression(u)&&e.isIdentifier(u.expression))c=u.expression,d=u.name.text;else if(e.isElementAccessExpression(u)&&e.isIdentifier(u.expression)){let m=u.argumentExpression;e.isStringLiteral(m)||e.isNoSubstitutionTemplateLiteral(m)?(c=u.expression,d=m.text):e.isNumericLiteral(m)&&(c=u.expression,d=String(Number(m.text)))}let f=c&&o.has(c.text)&&n.has($N(u))&&!s.pageOwns(c)?o.get(c.text):void 0;if(c&&f&&d!==void 0){let m=e.isPropertyAccessExpression(u)?`${f.name}.${d}`:`${f.name}[${JSON.stringify(d)}]`,p=Object.prototype.hasOwnProperty.call(f.runtime,d)?f.runtime[d]:void 0,h=f.labels.get(d),g;p===void 0?g={rule:"genpage-enum-member-unknown",message:`${m} is undefined at runtime: '${f.name}' has no member '${d}' in this environment's metadata \u2014 members are the column's choice labels, so a renamed or differently localized label no longer matches. Known: ${[...f.labels.keys()].map(w=>`'${w}'`).join(", ")}`}:h&&typeof p!="number"?g={rule:"genpage-enum-member-clobbered",message:`${m} is the string '${String(p)}' at runtime, not a choice value: the label '${d}' looks like a number, and another option's reverse mapping overwrites it. Use the choice's numeric value instead.`}:h&&h.length>1&&(g={rule:"genpage-enum-member-ambiguous",message:`${m} labels more than one choice (${h.join(", ")}); the compiled value is whichever option comes last. Use the choice's numeric value instead.`});let b=g?s.initializerShadow(c):void 0;g&&b!==void 0?a(u,"genpage-enum-initializer-shadowed",`${m} does not read the choice enum at runtime. ${b} (TS2301): the ES5 emit moves an instance field's initializer into the constructor, where that parameter or local shadows '${c.text}'. If you meant the constructor's '${c.text}', move the assignment into the constructor body, or make it a parameter property and read \`this.${c.text}\`. If you meant the choice enum, rename the constructor's parameter or local.`):g&&a(u,g.rule,g.message)}e.forEachChild(u,l)};return l(t),i}function $8(e,t){return e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!1,e.ScriptKind.JS).statements.some(n=>(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier!==void 0&&e.isStringLiteral(n.moduleSpecifier)&&n.moduleSpecifier.text===Nn)}function FN(e,t){return t.statements.filter(r=>e.isImportDeclaration(r)&&e.isStringLiteral(r.moduleSpecifier)&&r.moduleSpecifier.text===Nn).map(r=>r.getStart(t))}function x8(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=FN(e,r),i=new Set(n),o,a="",s=0;for(let l of LN(t))!o&&!i.has(l.start)&&(o={swallows:n.some(u=>u>l.start&&u<l.end),text:t.slice(l.start,l.end).trimEnd()}),a+=t.slice(s,l.start),s=l.end;return a+=t.slice(s),{code:a,inexact:o}}function F8(e,t,r){let n=new Set(FN(e,t));for(let i=t.text.indexOf(r);i!==-1;i=t.text.indexOf(r,i+1))if(!n.has(i)){let o=t.getLineAndCharacterOfPosition(i);return{line:o.line+1,column:o.character+1}}return Ld}function MN(e,t,r){if(!r||r.size===0)return[];let n=xN(e,t,{..._g(e),target:e.ScriptTarget.ESNext}),i=new Set,o=s=>{var l,u;let c=s.parent;if(e.isImportSpecifier(c)){let d=c.parent.parent.parent;e.isImportDeclaration(d)&&e.isStringLiteral(d.moduleSpecifier)&&d.moduleSpecifier.text===Nn&&((l=c.propertyName)!==null&&l!==void 0?l:c.name)===s&&i.add(s.text);return}if(e.isExportSpecifier(c)){!(c.parent.parent.moduleSpecifier!==void 0)&&((u=c.propertyName)!==null&&u!==void 0?u:c.name)===s&&!n.pageOwnsLocalExport(c)&&i.add(s.text);return}e.isPropertyAccessExpression(c)&&c.name===s||e.isBindingElement(c)&&c.propertyName===s||e.isLabeledStatement(c)||e.isBreakOrContinueStatement(c)||n.pageOwns(s)||i.add(s.text)},a=s=>{e.isIdentifier(s)&&r.has(s.text)&&o(s),e.forEachChild(s,a)};return a(t),[...r.keys()].filter(s=>i.has(s))}Le.legacyEnumsNeeded=MN;function M8(e,t,r){if(!e?.text||!t||r.length===0)return e;let n=new Map(e.enums),i=e.text;for(let o of r){let a=t.get(o);a&&(i+=a.declaration,n.set(o,a.model))}return{text:i,enums:n}}function U8(e,t,r,n){var i;let o=new Set,a=PN(e,t,o);if(a.diagnostics.length>0)return a;let s=e.createSourceFile("page.tsx",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.TSX),l=e.createSourceFile("page.js",a.code,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),u=M8(r,n,MN(e,l,n)),c=[...L8(e,l,s,u),...k8(e,s,u,o)];if(!u?.text)return{code:a.code,diagnostics:c};let d=PN(e,u.text);if(d.diagnostics.length>0)throw new fs.SdkError("GENPAGE_RUNTIME_TYPES_INVALID",`The generated runtime types do not compile (${d.diagnostics.map(h=>`${h.line}:${h.column} ${h.message}`).join("; ")}). This is an SDK defect: the page was not written.`);let f=x8(e,a.code),m=f.code;if(c.length===0&&(!((i=f.inexact)===null||i===void 0)&&i.swallows))c.push({...Ng(e,s).statement(Nn,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"the maker portal's patch would remove more than this './RuntimeTypes' import: a comment or other text before it contains the word 'import', and the pattern would delete from there \u2014 taking the code in between with it. Reword or move that text."});else if(c.length===0&&f.inexact){let{text:h}=f.inexact;c.push({...F8(e,s,h),rule:"genpage-runtime-types-import-form",code:0,message:`the maker portal's patch would delete \`${h.length>80?`${h.slice(0,79)}\u2026`:h}\` from text that only looks like an import of './RuntimeTypes' \u2014 in a string, a template or a comment \u2014 so the page it ships would differ from this source. Reword that text so it no longer reads as such an import.`})}else c.length===0&&$8(e,m)&&c.push({...Ng(e,s).statement(Nn,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"this './RuntimeTypes' import is not one the maker portal's patch can remove (a comment holding a quote inside it stops the pattern), so it would reach the runtime, which cannot load it. Write it on one line, as 'import { name } from './RuntimeTypes';'."});return{code:[Le.GENPAGE_RUNTIME_TYPES_BEGIN,d.code,Le.GENPAGE_RUNTIME_TYPES_END,m].join(`
+`).slice(1)){let l=s.indexOf(":");l>0&&(o[s.slice(0,l).trim()]=s.slice(l+1).trim())}let a=i===""?void 0:i;if(i!=="")try{a=JSON.parse(i)}catch{}return{status:e.status,headers:o,body:a}}Kt.partResponse=Xh;function yS(e){let t=e.path.indexOf("?");return t===-1?e.path:e.path.slice(0,t)}function zG(e,t){let r=e.find(n=>(0,Yo.isVersionToken)(n.etag));if(!r||e.some(n=>yS(n)!==yS(r)))throw new Ii.InvalidArgumentError(`the change set writing ${t} cannot be re-sent under the customization lock: it needs an operation conditioned on a version token and every operation writing that operation's row`)}function vS(e,t){var r;if(e.status!==429&&(e.status<200||e.status>=300))return!1;let n=(r=yd(e.body,t))===null||r===void 0?void 0:r.filter(i=>i.status<200||i.status>=300);return n!==void 0&&n.length>0&&n.every(i=>(0,Yo.isConcurrencyLockRefusal)(Xh(i)))}Kt.isChangeSetLockRefusal=vS;async function jG(e,t,r,n={}){n.resendWhileLockRefused&&zG(t,r);let{body:i,batchId:o,contentIds:a}=Qh(e,t),s=()=>e.postBatch(i,o),l=n.resendWhileLockRefused?await(0,Yo.resendWhile)(f=>vS(f,a),s,Yo.LOCK_BACKOFF_MS):await s(),u=e.apiUrl("/$batch"),c=yd(l.body,a),d=c?.find(f=>f.status<200||f.status>=300);if(d&&(0,Yo.ensureSuccess)(Xh(d),e.apiUrl(t[a.indexOf(d.contentId)].path)),(0,Yo.ensureSuccess)(l,u),!c||c.length!==t.length)throw new Ii.ConnectionError(u,l.status,`atomic write of ${r} cannot be confirmed: the $batch response ${c?`reported ${c.length} result(s) for ${t.length} operation(s)`:"could not be parsed"}, so the outcome is unknown`);return a.map(f=>c.find(m=>m.contentId===f))}Kt.sendChangeSet=jG});var bd=v(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.updateTable=ie.deleteAlternateKey=ie.createAlternateKey=ie.deleteGlobalOptionSet=ie.createGlobalOptionSet=ie.deleteRelationship=ie.deleteColumn=ie.updateColumn=ie.deleteTable=ie.createRelationship=ie.insertStatusValue=ie.createCustomerColumn=ie.createColumns=ie.setColumnVisualization=ie.getColumnVisualization=ie.createColumn=ie.createTable=ie.resolveEntitySetName=ie.pluralFallback=void 0;var _e=ye(),te=le(),Jn=Jo(),ge=Q(),HG=Kl(),KG={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 et(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:JG(e,t)}}var wS=65535;function JG(e,t){let r=(o,a)=>({"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:o,LanguageCode:a});if(typeof e=="string")return[r(e,t)];let n=Object.entries(e);if(!n.length)throw new ge.InvalidArgumentError("a localized label must contain at least one language");let i=new Set;return n.map(([o,a])=>{if(!/^[1-9]\d*$/.test(o))throw new ge.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>wS)throw new ge.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${wS})`);if(i.has(s))throw new ge.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new ge.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(a,s)})}function NS(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new ge.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}ie.pluralFallback=NS;function Jl(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}var CS=["None","ApplicationRequired","Recommended"];function tg(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function ES(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function Yl(e){let t=(0,_e.readCreatedId)(e,"MetadataId");if(!t)throw new ge.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function YG(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b,w,C,S,O,k,I,D,P,x;if(t.defaultValue!==void 0&&e!=="boolean")throw new ge.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new ge.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:(o=t.maxLength)!==null&&o!==void 0?o:2e3,Format:"TextArea"};case"integer":return{"@odata.type":"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",AttributeType:"Integer",AttributeTypeName:{Value:"IntegerType"},Format:(a=t.integerFormat)!==null&&a!==void 0?a:"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:(f=t.precision)!==null&&f!==void 0?f:2,MinValue:(m=t.minValue)!==null&&m!==void 0?m:-1e11,MaxValue:(p=t.maxValue)!==null&&p!==void 0?p:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(h=t.precision)!==null&&h!==void 0?h:2,PrecisionSource:2,MinValue:(g=t.minValue)!==null&&g!==void 0?g:0,MaxValue:(b=t.maxValue)!==null&&b!==void 0?b:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(w=t.defaultValue)!==null&&w!==void 0?w:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:et((C=t.trueLabel)!==null&&C!==void 0?C:"Yes",r)},FalseOption:{Value:0,Label:et((S=t.falseLabel)!==null&&S!==void 0?S:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(O=t.dateFormat)!==null&&O!==void 0?O:"DateAndTime"};case"choice":return AS(t,r,!1);case"multiChoice":return AS(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(k=t.maxSizeKb)!==null&&k!==void 0?k:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(I=t.isPrimaryImage)!==null&&I!==void 0?I:!1,MaxSizeInKB:(D=t.maxSizeKb)!==null&&D!==void 0?D:10240};case"autonumber":if(!(!((P=t.autoNumberFormat)===null||P===void 0)&&P.trim()))throw new ge.InvalidArgumentError(`createColumn: an 'autonumber' column needs an 'autoNumberFormat' (e.g. 'CDS-{SEQNUM:5}'), but '${t.schemaName}' has none \u2014 without one Dataverse would create a plain text column.`);return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(x=t.maxLength)!==null&&x!==void 0?x:100,AutoNumberFormat:t.autoNumberFormat};default:throw new ge.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function AS(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,te.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new ge.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(o=>({Value:o.value,Label:et(o.label,t)}))},i}var Zh=new WeakMap;async function QG(e,t){var r,n;let i=(r=Zh.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')${(0,te.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new ge.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,te.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=Zh.get(e);return l||(l=new Map,Zh.set(e,l)),l.set(t,s),s}ie.resolveEntitySetName=QG;async function XG(e,t){var r,n,i,o,a,s,l,u,c,d,f,m,p,h,g;let b=t.primaryColumnRequired;if(b!==void 0&&!CS.includes(b))throw new ge.InvalidArgumentError(`createTable: 'primaryColumnRequired' must be one of ${CS.join(", ")}; got '${String(b)}'.`);let w=b!==void 0&&b!=="None";if(w&&!t.primaryColumnAutoNumberFormat&&!e.supportsPut)throw new ge.InvalidArgumentError(`createTable: 'primaryColumnRequired: ${b}' on a plain text primary column needs an HttpClient that implements put(): the platform ignores the level in the create, so the SDK sets it with an update.`);let C=(r=t.languageCode)!==null&&r!==void 0?r:Jn.DEFAULT_LCID,S=tg(t.schemaName),O=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${S}_Name`,k={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:O,RequiredLevel:Jl(b??"None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:et((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",C),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(k.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&IS(t.columns,"createTable");let I={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:et(t.displayName,C),DisplayCollectionName:et((a=t.pluralName)!==null&&a!==void 0?a:NS(t.displayName),C),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:[k,...((c=t.columns)!==null&&c!==void 0?c:[]).map(ir=>rg(ir,C))]};t.description&&(I.Description=et(t.description,C));let D="/EntityDefinitions",P=(0,_e.ensureSuccess)(await e.post(D,I),e.apiUrl(D)),x=Yl(P),K=`/EntityDefinitions(${x})`+(0,te.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),Oe=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),Vt=Math.max(0,(f=t.readBackDelayMs)!==null&&f!==void 0?f:1e3),Xe=w?` Its primary column's requirement level '${b}' was NOT applied or checked: once the table is readable, set it with updateColumn('${t.schemaName.toLowerCase()}', '${O.toLowerCase()}', { required: '${b}' }).`:"",Ne;try{Ne=await _S(e,K,Oe,Vt)}catch(ir){throw w?(0,ge.attachCause)(new ge.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}), but reading it back failed (${ir instanceof Error?ir.message:String(ir)}).${Xe} Do NOT re-run the create \u2014 it will collide on the schema name.`),ir):ir}if(!Ne)throw new ge.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}) but its metadata was still not readable after ${Oe} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${x}) once the environment catches up, or raise 'readBackAttempts'.${Xe}`);let se=Ne.body,We={logicalName:(m=se.LogicalName)!==null&&m!==void 0?m:t.schemaName.toLowerCase(),metadataId:x,entitySetName:(p=se.EntitySetName)!==null&&p!==void 0?p:"",primaryIdAttribute:(h=se.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=se.PrimaryNameAttribute)!==null&&g!==void 0?g:O.toLowerCase()};return w&&(We.primaryColumnRequired=await ZG(e,t.schemaName,We,b,Oe,Vt)),We}ie.createTable=XG;async function _S(e,t,r,n){for(let i=1;i<=r;i+=1){let o=await e.get(t);if(o.status>=200&&o.status<300)return o;o.status!==404&&(0,_e.ensureSuccess)(o,e.apiUrl(t)),i<r&&n>0&&await new Promise(a=>setTimeout(a,n))}}async function ZG(e,t,r,n,i,o){let a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(r.logicalName)}')/Attributes(LogicalName='${(0,te.odataPathLiteral)(r.primaryNameAttribute)}')`+(0,te.odataQuery)([["$select","RequiredLevel"]]),s=async()=>{var d,f;let m=await _S(e,a,i,o),p=(f=(d=m?.body)===null||d===void 0?void 0:d.RequiredLevel)===null||f===void 0?void 0:f.Value;return typeof p=="string"?p:void 0},l="read",u,c=d=>{let f=`its primary column '${r.primaryNameAttribute}'`,m=l==="read"?`${f} could not be read back`:l==="update"?`${f} read '${u??"(unreadable)"}' and the update to '${n}' failed, so it may or may not carry it`:u===void 0?`${f} was updated to '${n}' but could not be read back`:`${f} is still '${u}' after the update to '${n}'`;return new ge.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t}' WAS CREATED (MetadataId ${r.metadataId}), but ${m}${d?` (${d})`:""}. Do NOT re-run the create \u2014 it will collide on the schema name. Check the level, and set it with updateColumn('${r.logicalName}', '${r.primaryNameAttribute}', { required: '${n}' }).`)};try{u=await s(),u!==n&&(l="update",await kS(e,r.logicalName,r.primaryNameAttribute,{required:n}),l="verify",u=await s())}catch(d){throw l==="verify"&&(u=void 0),(0,ge.attachCause)(c(d instanceof Error?d.message:String(d)),d)}if(u!==n)throw c(u===void 0?"the answer had no RequiredLevel":void 0);return n}function rg(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,o={...YG(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:Jl((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:et(e.displayName,i)};return e.description&&(o.Description=et(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),TS(o,e),o}function TS(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 e9(e,t,r){var n;let i=rg(r,(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID),o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,a=(0,_e.ensureSuccess)(await e.post(o,i),e.apiUrl(o)),s={logicalName:r.schemaName.toLowerCase(),metadataId:Yl(a)};if(r.visualization&&r.visualization!=="None")try{await RS(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new ge.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(0,ge.attachCause)(u,l),u}return s}ie.createColumn=e9;var ls="/controlconfigurations",DS="CustomRenderersConfiguration",eg={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 IS(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new ge.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 OS(e){return JSON.stringify({type:eg[e]})}function t9(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(eg).find(i=>eg[i]===r);return n??"None"}async function PS(e,t,r){var n,i;let o=`entitylogicalname eq '${(0,te.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,te.odataLiteral)(r)}'`,a=`${ls}${(0,te.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",o]])}`,l=(i=(n=(0,_e.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],u=r.toLowerCase();return l.filter(c=>{var d,f;return((f=(d=c.Attribute)===null||d===void 0?void 0:d.logicalname)===null||f===void 0?void 0:f.toLowerCase())===u})}async function r9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,a=(n=(0,_e.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!a)throw new ge.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,te.normalizeGuid)(a,"MetadataId")}async function RS(e,t,r,n,i){let o={name:DS,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:OS(i),"[email protected]":`/attributes(${(0,te.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,_e.ensureSuccess)(await e.post(ls,o),e.apiUrl(ls))}async function n9(e,t,r){var n;let i=await PS(e,t,r);return t9((n=i[0])===null||n===void 0?void 0:n.metadatajson)}ie.getColumnVisualization=n9;async function i9(e,t,r,n){let o=(await PS(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of o){let c=`${ls}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,_e.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,l=await r9(e,t,r);if(a){let u=`${ls}(${(0,te.normalizeGuid)(a,"controlconfigurationid")})`,c={name:DS,metadatajson:OS(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,_e.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await RS(e,t,r,l,n);for(let u of s){let c=`${ls}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,_e.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}ie.setColumnVisualization=i9;async function o9(e,t,r){if(r.length===0)return;if(IS(r,"createColumns"),!e.supportsAtomicBatch)throw new ge.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,te.odataPathLiteral)(t)}')/Attributes`;await(0,HG.postChangeSet)(e,r.map(i=>{var o;return{method:"POST",path:n,body:rg(i,(o=i.languageCode)!==null&&o!==void 0?o:Jn.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}ie.createColumns=o9;async function a9(e,t,r){var n,i,o,a;let s=(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID,l=tg(r.schemaName),u=(i=r.accountRelationshipName)!==null&&i!==void 0?i:`${l}_${t}_account`,c=(o=r.contactRelationshipName)!==null&&o!==void 0?o:`${l}_${t}_contact`,d={Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.ComplexLookupAttributeMetadata",SchemaName:r.schemaName,DisplayName:et(r.displayName,s),RequiredLevel:Jl((a=r.required)!==null&&a!==void 0?a:"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,_e.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}ie.createCustomerColumn=a9;async function s9(e,t,r){var n,i,o,a,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:et(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,_e.ensureSuccess)(await e.post("/InsertStatusValue",u),e.apiUrl("/InsertStatusValue"));return Number((s=(a=(o=c.body)===null||o===void 0?void 0:o.NewOptionValue)!==null&&a!==void 0?a:r.value)!==null&&s!==void 0?s:0)}ie.insertStatusValue=s9;async function l9(e,t){var r,n,i,o,a;let s=(r=t.languageCode)!==null&&r!==void 0?r:Jn.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new ge.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let f=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${tg(t.schemaName)}_${t.referencedEntity}Id`;u=f.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:f,RequiredLevel:Jl((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:et((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new ge.InvalidArgumentError("ManyToMany relationship requires entity1 and entity2");l={"@odata.type":"Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata",SchemaName:t.schemaName,IntersectEntityName:(a=t.intersectEntityName)!==null&&a!==void 0?a:t.schemaName.toLowerCase(),Entity1LogicalName:t.entity1,Entity2LogicalName:t.entity2}}let c="/RelationshipDefinitions",d=(0,_e.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:Yl(d),lookupLogicalName:u}}ie.createRelationship=l9;async function u9(e,t){let r=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`;(0,_e.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteTable=u9;async function kS(e,t,r,n){var i,o;let a=(i=n.languageCode)!==null&&i!==void 0?i:Jn.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,_e.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=KG[(o=c.AttributeType)!==null&&o!==void 0?o:""];if(!c.MetadataId||!d){let g=c.MetadataId?c.AttributeType?`type '${c.AttributeType}' not supported`:"the attribute read returned no AttributeType":"the attribute read returned no MetadataId";throw new ge.InvalidArgumentError(`cannot update column '${r}' on '${t}' (${g})`)}let f=(0,te.normalizeGuid)(c.MetadataId,"MetadataId"),m=`${s}(${f})/${d}`,p=(0,_e.ensureSuccess)(await e.get(m),e.apiUrl(m)).body;for(let g of Object.keys(p))g.startsWith("@odata.")&&delete p[g];if(p["@odata.type"]=d,n.displayName!==void 0&&(p.DisplayName=et(n.displayName,a)),n.description!==void 0&&(p.Description=et(n.description,a)),n.required!==void 0&&(p.RequiredLevel=Jl(n.required)),n.maxLength!==void 0&&(p.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(p.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new ge.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 ge.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(p.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(p.Format=n.integerFormat),TS(p,n);let h=`${s}(${f})`;(0,_e.ensureSuccess)(await e.put(h,p,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}ie.updateColumn=kS;async function c9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,o=`${i}(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new ge.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,_e.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteColumn=c9;async function d9(e,t){var r,n,i;let o=`/RelationshipDefinitions${(0,te.odataQuery)([["$filter",`SchemaName eq '${(0,te.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(n=(r=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).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 ge.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,_e.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteRelationship=d9;async function SS(e,t){var r;let n=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(n);if(i.status===404)return;let a=(r=(0,_e.ensureSuccess)(i,e.apiUrl(n)).body)===null||r===void 0?void 0:r.MetadataId;return a?(0,te.normalizeGuid)(a,"MetadataId"):void 0}async function f9(e,t){var r;let n=t.name.toLowerCase(),i=await SS(e,n);if(i)return{name:n,metadataId:i};let o=(r=t.languageCode)!==null&&r!==void 0?r:Jn.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:et(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:et(l.label,o)}))};t.description&&(a.Description=et(t.description,o));let s="/GlobalOptionSetDefinitions";try{let l=(0,_e.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:n,metadataId:Yl(l)}}catch(l){let u;try{u=await SS(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}ie.createGlobalOptionSet=f9;async function p9(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t.toLowerCase())}')`;(0,_e.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteGlobalOptionSet=p9;async function m9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:et(r.displayName,i),KeyAttributes:r.keyAttributes},a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,s=(0,_e.ensureSuccess)(await e.post(a,o),e.apiUrl(a));return{logicalName:r.schemaName.toLowerCase(),metadataId:Yl(s)}}ie.createAlternateKey=m9;async function h9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,o=`${i}(LogicalName='${(0,te.odataPathLiteral)(r.toLowerCase())}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new ge.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,_e.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteAlternateKey=h9;async function g9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID,o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`,s=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body,l=s.MetadataId;if(!l)throw new ge.InvalidArgumentError(`table '${t}' not found`);let u=(0,te.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=et(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=et(r.pluralName,i)),r.description!==void 0&&(s.Description=et(r.description,i)),r.auditEnabled!==void 0&&ES(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&ES(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,_e.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}ie.updateTable=g9});var so=v(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.rebuildRaw=Nr.assembleChildren=Nr.spliceChildren=Nr.mergeAttrs=Nr.rawFromNode=Nr.emptyBag=void 0;var ao=Q(),LS=1e6,wd=512;function y9(){return{a:[],c:[]}}Nr.emptyBag=y9;function $S(e,t=0){if(t>wd)throw new ao.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${wd}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>$S(r,t+1))}}Nr.rawFromNode=$S;function b9(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))),o=new Set,a=[];for(let[s,l]of e)i.has(s)||(n.has(s)?a.push([s,n.get(s)]):a.push([s,l]),o.add(s));for(let[s,l]of t)o.has(s)||(a.push([s,l]),o.add(s));return a}Nr.mergeAttrs=b9;function vd(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>LS)throw new ao.InvalidArgumentError(`Bag child index must be an integer in [0, ${LS}] (got ${String(l)})`);if(r.has(l))throw new ao.InvalidArgumentError(`Duplicate bag child index ${l}`);r.add(l)}let n=[...e].sort((s,l)=>s.i-l.i),i=[],o=0,a=0;for(let s of n){for(;a<s.i&&o<t.length;)i.push(t[o]),o+=1,a+=1;a<s.i&&(a=s.i),i.push(s.node),a+=1}for(;o<t.length;)i.push(t[o]),o+=1;return i}Nr.spliceChildren=vd;function v9(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:vd(e.w.c,t)};return vd(e.c,[r])}return vd(e.c,t)}Nr.assembleChildren=v9;function xS(e,t,r,n=0){if(n>wd)throw new ao.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${wd}`);w9(e,n);let i=t.make(e.n,r);for(let[o,a]of e.a)t.setProp(i,o,a);for(let o of e.c)t.addChild(i,xS(o,t,i,n+1));return i}Nr.rebuildRaw=xS;function w9(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new ao.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new ao.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 ao.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 ao.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var lo=v(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});Cd.installDomShim=void 0;var FS=ns(),MS=!1,C9={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 E9(){if(MS)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=FS.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=FS.XMLSerializer),typeof e.Node>"u"&&(e.Node=C9),MS=!0}Cd.installDomShim=E9});var uo=v(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.projectElementBag=tt.serializeNode=tt.domEngine=tt.nodeLikeFromDom=tt.parseXmlRoot=tt.EMPTY_FORM_SENTINEL=tt.TEXT_SENTINEL=void 0;var A9=so(),us=Q(),S9=lo();tt.TEXT_SENTINEL="#text";tt.EMPTY_FORM_SENTINEL="#empty";var Ad=new WeakSet;function N9(e,t){(0,S9.installDomShim)();let r=e&&e.trim()!==""?e:t,n=new DOMParser().parseFromString(r,"text/xml"),i=n.documentElement;if(!i)throw new us.InvalidArgumentError("XML source has no root element (empty or malformed input)");return _9(r),D9(n),O9(i),P9(i),L9(i,r),i}tt.parseXmlRoot=N9;function _9(e){let t=e.search(/\S/);if(t!==-1&&e[t]!=="<")throw BS(3)}var T9=["http://www.mozilla.org/newlayout/xml/parsererror.xml","http://www.w3.org/1999/xhtml"];function D9(e){var t;for(let r of T9){let n=e.getElementsByTagNameNS(r,"parsererror")[0];if(n){let i=((t=n.textContent)!==null&&t!==void 0?t:"").replace(/\s+/g," ").trim().slice(0,200);throw new us.InvalidArgumentError(`XML source is not well-formed (${i||"the XML parser reported an error"}), so it cannot be round-tripped`)}}}var I9=new Set([1,3]);function O9(e){let t=[e];for(;t.length>0;){let n=t.pop().childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];if(!I9.has(o.nodeType))throw new us.InvalidArgumentError(`Unsupported XML node type ${o.nodeType} (CDATA / comment / processing-instruction) is outside the hybrid projection's lossless grammar and cannot be round-tripped`);o.nodeType===1&&t.push(o)}}}function P9(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 o=0;o<i.length;o+=1){let a=i[o];if(a!==e&&!(a.nodeType===3&&((r=a.nodeValue)!==null&&r!==void 0?r:"").trim()===""))throw BS(a.nodeType)}}function BS(e){return new us.InvalidArgumentError(`Unsupported document-level XML node (type ${e}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}function R9(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 k9(e){let t=[],r=[e];for(;r.length>0;){let n=r.pop();t.push(n);let i=n.childNodes;for(let o=i.length-1;o>=0;o-=1){let a=i[o];a.nodeType===1&&r.push(a)}}return t}function qS(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 L9(e,t){let r=R9(t),n=k9(e),i=Math.min(r.length,n.length);for(let o=0;o<i;o+=1){if(r[o])continue;let a=n[o];qS(a)||Ad.add(a)}}function ng(e){let t=e.nodeType===3;return{getNodeName:()=>t?tt.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:tt.TEXT_SENTINEL,value:(r=e.nodeValue)!==null&&r!==void 0?r:""}];let n=e.attributes,i=[];for(let o=0;o<n.length;o+=1)i.push({key:n[o].name,value:n[o].value});return Ad.has(e)&&!qS(e)&&i.push({key:tt.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 o=n[i];(o.nodeType===1||o.nodeType===3)&&r.push(ng(o))}return r}}}tt.nodeLikeFromDom=ng;function $9(e){return{make:t=>t===tt.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===tt.EMPTY_FORM_SENTINEL?Ad.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}tt.domEngine=$9;function VS(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 Ed(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw Ed(r);t+=1;continue}if(r>=56320&&r<=57343)throw Ed(r)}}function Ed(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new us.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 x9(e){return VS(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\r/g,"&#xD;").replace(/\n/g,"&#xA;").replace(/\t/g,"&#x9;")}function F9(e){return VS(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function M9(e){return GS(e,0)}tt.serializeNode=M9;var US=512;function GS(e,t){var r;if(t>US)throw new us.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${US}`);if(e.nodeType===3)return F9((r=e.nodeValue)!==null&&r!==void 0?r:"");let n=e,i="<"+n.tagName,o=n.attributes;for(let l=0;l<o.length;l+=1)i+=" "+o[l].name+'="'+x9(o[l].value)+'"';let a=[],s=n.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];(u.nodeType===1||u.nodeType===3)&&a.push(u)}if(a.length===0)return Ad.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of a)i+=GS(l,t+1);return i+"</"+n.tagName+">"}function U9(e){let t=ng(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,A9.rawFromNode)(r)}))}}tt.projectElementBag=U9});var rn=v(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.rejectUnknownKeys=Jt.childObjects=Jt.optionalGuidId=Jt.optionalEnum=Jt.eachObject=Jt.issue=Jt.isJsonObject=void 0;function WS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}Jt.isJsonObject=WS;function cs(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}Jt.issue=cs;function zS(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{WS(o)?i.push({node:o,index:a}):n.push(cs(`${t}/${a}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}Jt.eachObject=zS;function B9(e,t,r,n,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!r.includes(a))&&o.push(cs(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}Jt.optionalEnum=B9;var q9=/^(?:\{[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 V9(e,t,r,n,i){let o=e[t];typeof o=="string"&&o!==""&&!q9.test(o)&&i.push(cs(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${o}'`))}Jt.optionalGuidId=V9;function G9(e,t,r,n,i){let o=e[t],a=`${r}/${t}`;return o===void 0?[]:Array.isArray(o)?zS(o,a,n,i):(i.push(cs(a,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}Jt.childObjects=G9;function W9(e,t,r,n,i,o={}){var a,s;for(let l of Object.keys(e)){if(t.has(l))continue;let u=(a=o.elsewhere)===null||a===void 0?void 0:a[l],c=(s=o.unsupported)===null||s===void 0?void 0:s[l],d=u?` '${l}' is a ${u} key \u2014 set it on the ${u} instead.`:c?` ${c}`:` Put values the typed layer does not model in '${n}.bag', which round-trips them verbatim.`;i.push(cs(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}Jt.rejectUnknownKeys=W9});var Dd=v(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.genPageEmbedIssues=B.setUniqueId=B.mintEmbedIdentity=B.authoredUniqueId=B.hasGenPage=B.applyEmbedCellDefaults=B.applyEmbedControlDefaults=B.mayCommitEmbedState=B.commitEmbedState=B.reconcileEmbedDescriptions=B.embedAppendIndex=B.activeEmbedBindings=B.projectGenPageEmbeds=B.isRecognizedEmbed=B.isUnbound=B.effectiveClassId=B.effectiveFormType=B.inputDataFrom=B.classifyBinding=B.isStaticParameter=B.entryParameter=B.pageEntries=B.descriptionFor=B.descriptionsRegion=B.controlUniqueIds=B.controlUniqueId=B.typedCellSites=B.typedCells=B.rawText=B.rawAttr=B.normGuid=B.GENPAGE_FORM_FACTORS=B.GENPAGE_EMBED_ROWSPAN=B.GENPAGE_CONTROL_NAME=B.CUSTOM_CONTROL_CLASS_ID=void 0;var z9=ns(),j9=Ma(),ig=pt(),nn=rn();B.CUSTOM_CONTROL_CLASS_ID="F9A8A302-114E-466A-B582-6771B2AE0D92";B.GENPAGE_CONTROL_NAME="MscrmControls.UxAgentControl";B.GENPAGE_EMBED_ROWSPAN=6;B.GENPAGE_FORM_FACTORS=["2","0","1"];var H9=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function _r(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),H9.test(t)?t:""}B.normGuid=_r;function co(e,t){let r=Se(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=co;function Xl(e){return Se(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=Xl;function Se(e){return Array.isArray(e)?e:[]}function cg(e,t){let r=Se(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function KS(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function JS(e){return Sn(e).map(t=>t.cell)}B.typedCells=JS;function Sn(e){let t=[];return Se(e?.tabs).forEach((r,n)=>{Se(Re(r)?r.columns:void 0).forEach((i,o)=>{Se(Re(i)?i.sections:void 0).forEach((a,s)=>{Se(Re(a)?a.rows:void 0).forEach((l,u)=>{Se(Re(l)?l.cells:void 0).forEach((c,d)=>{Re(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${o}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}B.typedCellSites=Sn;function Oi(e){return Re(e)?_r(cg(e.bag,"uniqueid")):""}B.controlUniqueId=Oi;function K9(e){let t=new Set;for(let{cell:r}of Sn(e)){let n=Zo(r.control)?Oi(r.control):"";n&&t.add(n)}return t}function J9(e){let t=new Map;for(let{cell:r}of Sn(e)){let n=Re(r.control)?Oi(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function Y9(e){return e!==void 0&&e.genPage===void 0&&(pg(e)!==B.CUSTOM_CONTROL_CLASS_ID||!Td(e))}function og(e,t){if(Re(e)){t(e);for(let r of Se(e.c))og(r,t)}}function Qo(e,t){var r;if(Re(e)){for(let n of Se(e.c))og(n?.node,t);for(let n of Se((r=e.w)===null||r===void 0?void 0:r.c))og(n?.node,t)}}function Nd(e){let t=new Map,r=i=>{var o;i&&t.set(i,((o=t.get(i))!==null&&o!==void 0?o:0)+1)},n=i=>{i.n==="control"&&r(_r(co(i,"uniqueid")))};return Qo(e?.bag,n),Se(e?.tabs).forEach(i=>{Re(i)&&(Qo(i.bag,n),Se(i.columns).forEach(o=>{Re(o)&&(Qo(o.bag,n),Se(o.sections).forEach(a=>{Re(a)&&(Qo(a.bag,n),Se(a.rows).forEach(s=>{Re(s)&&(Qo(s.bag,n),Se(s.cells).forEach(l=>{Re(l)&&(Qo(l.bag,n),Re(l.control)&&(r(Oi(l.control)),Qo(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=Nd;function ds(e){return Se(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=ds;function Xo(e,t){var r;let n=_r(t);if(n)return Se((r=ds(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&_r(co(i,"forControl"))===n)}B.descriptionFor=Xo;function Zl(e){return Se(e.c).filter(YS)}B.pageEntries=Zl;function YS(e){return e?.n==="customControl"&&co(e,"name")===B.GENPAGE_CONTROL_NAME}function ag(e,t){let r=Se(e.c).find(n=>n?.n==="parameters");return Se(r?.c).find(n=>n?.n===t)}B.entryParameter=ag;function sg(e){return co(e,"static")==="true"}B.isStaticParameter=sg;function eu(e){let t=Zl(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let o=ag(t[i],"RefId");if(!o||!sg(o))return{kind:"unsupported"};let a=_r(Xl(o));if(!a)return{kind:"unsupported"};let s=ag(t[i],"PageInput");if(s&&!sg(s))return{kind:"unsupported"};let l=s?Xl(s):void 0;if(i===0)r=a,n=l;else if(a!==r||l!==n)return{kind:"unsupported"}}return n===void 0?{kind:"projectable",pageId:r}:{kind:"projectable",pageId:r,pageInputRaw:n}}B.classifyBinding=eu;function Re(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dg(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return Re(t)&&Re(t.data)?t.data:void 0}B.inputDataFrom=dg;function fg(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=fg;function pg(e){return KS(e.classId!==void 0?e.classId:cg(e.bag,"classid"))}B.effectiveClassId=pg;function Td(e){return!e.fieldName}B.isUnbound=Td;function mg(e,t){if(fg(e)!=="Main"||!Td(t)||pg(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=Oi(t),n=r?Xo(e.bag,r):void 0;return n!==void 0&&eu(n).kind==="projectable"}B.isRecognizedEmbed=mg;function Q9(e){for(let t of JS(e)){let r=t.control;if(!r||!mg(e,r))continue;let n=eu(Xo(e.bag,Oi(r)));if(n.kind!=="projectable")continue;let i=dg(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=Q9;var X9=new Set(["pageId","inputData"]);function Ql(e){let t=[];for(let r=0;r<e.childNodes.length;r+=1){let n=e.childNodes[r];n.nodeType===1&&t.push(n)}return t}function Z9(e){var t;let r=[],n=c=>d=>r.push(`${c}: ${d}`),i=new z9.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the formxml does not parse cleanly${r.length>0?` (${r[0]})`:""}`);let a=new Set,s=o.getElementsByTagName("control");for(let c=0;c<s.length;c+=1){let d=_r(s[c].getAttribute("uniqueid"));d&&a.add(d)}let l=Ql(o).find(c=>c.nodeName==="controlDescriptions"),u=new Map;for(let c of l?Ql(l):[]){let d=_r(c.getAttribute("forControl"));if(!(c.nodeName!=="controlDescription"||!d||!a.has(d)))for(let f of Ql(c)){if(f.nodeName!=="customControl"||f.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let m=Ql(f).find(g=>g.nodeName==="parameters"),p=m?Ql(m).find(g=>g.nodeName==="RefId"):void 0,h=p&&p.getAttribute("static")==="true"?_r(p.textContent):"";h&&u.set(`${d}|${h}`,[d,h])}}return[...u.values()]}B.activeEmbedBindings=Z9;function Sd(e){return{n:`<${e}`,a:[],c:[]}}function lg(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[Sd(t)]}}function ug(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);Re(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function eW(e,t,r){return{n:"controlDescription",a:[["forControl",e]],c:B.GENPAGE_FORM_FACTORS.map(n=>({n:"customControl",a:[["name",B.GENPAGE_CONTROL_NAME],["formFactor",n]],c:[{n:"parameters",a:[],c:[lg("RefId",t),...r===void 0?[]:[lg("PageInput",ug(r))]]}]}))}}function _d(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>_d(r,t[n]));if(Re(e)&&Re(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&_d(e[n],t[n]))}return e===t}function tW(e,t,r){let n=Se(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&_r(Xl(i))!==t&&(i.c=[Sd(t)]);let o=n.c.findIndex(u=>u?.n==="PageInput"),a=o>=0?n.c[o]:void 0,s=a?Xl(a):void 0;if(_d(dg(s),r))return;if(r!==void 0){a?a.c=[Sd(ug(r,s))]:n.c.push(lg("PageInput",ug(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(o,1):a.c=[Sd(JSON.stringify(l))]}function hg(e){let t=Se(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=hg;function rW(e,t){var r;let n=e.bag,i=ds(n);if(i&&t){let o=Nd(t),a=Nd(e),s=K9(t),l=J9(e),u=Se(i.node.c),c=[];for(let d of u){let f=d?.n==="controlDescription"&&Zl(d).length>0?_r(co(d,"forControl")):"";if(!f||!o.has(f))c.push(d);else if(a.has(f))if(s.has(f)&&Y9(l.get(f))&&_d(d,Xo(t.bag,f))){let m=Se(d.c).filter(p=>!YS(p));m.length>0&&c.push({...d,c:m})}else c.push(d)}(c.length!==u.length||c.some((d,f)=>d!==u[f]))&&(i.node.c=c)}for(let{cell:o}of Sn(e)){let a=o.control;if(!Zo(a)||!Re(a.genPage))continue;let s=_r(a.genPage.pageId),l=a.genPage.inputData,u=Oi(a);if(!u){if(tu(a)!==void 0)continue;u=gg(a)}let c=Xo(n,u);if(c){for(let m of Zl(c))tW(m,s,l);continue}i||(i={i:hg(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=cg(a.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),f=d.startsWith("{")?d:`{${u}}`;i.node.c.push(eW(f,s,l))}}B.reconcileEmbedDescriptions=rW;function nW(e,t){let r=ds(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=Sn(e).some(({cell:a})=>Zo(a.control)&&(a.rowspan===void 0||a.control.classId===void 0||a.control.showLabel===void 0||a.control.label===void 0||a.control.fieldName===void 0));if(!n&&!i)return e;let o=JSON.parse(JSON.stringify(e));if(n){let a=JSON.parse(JSON.stringify(t)),s=ds(o.bag);s?s.node=a:(o.bag=Re(o.bag)?o.bag:{a:[],c:[]},o.bag.c=Se(o.bag.c),o.bag.c.push({i:hg(e.bag),node:a}))}for(let{cell:a}of Sn(o))Zo(a.control)&&(QS(a.control),XS(a));return o}B.commitEmbedState=nW;function iW(e){if(Sn(e).some(({cell:r})=>Zo(r.control)))return!0;let t=ds(e.bag);return Se(t?.node.c).some(r=>r?.n==="controlDescription"&&Zl(r).length>0)}B.mayCommitEmbedState=iW;function QS(e){e.classId===void 0&&(e.classId=B.CUSTOM_CONTROL_CLASS_ID),e.showLabel===void 0&&(e.showLabel=!1),e.label===void 0&&(e.label=""),e.fieldName===void 0&&(e.fieldName=null)}B.applyEmbedControlDefaults=QS;function XS(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=XS;function Zo(e){return Re(e)&&e.genPage!==void 0}B.hasGenPage=Zo;function jS(e){return Zo(e.control)&&(!e.control.id||!e.id||tu(e.control)===void 0)}function tu(e){let t=Se(Re(e.bag)?e.bag.a:void 0).find(n=>Array.isArray(n)&&n[0]==="uniqueid");if(!t)return;let r=t[1];return typeof r=="string"&&r.trim()===""?void 0:r}B.authoredUniqueId=tu;function oW(e){if(!Sn(e).some(({cell:r})=>jS(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of Sn(t)){if(!jS(r))continue;let n=r.control;n.id||(n.id=(0,ig.newId)()),r.id||(r.id=(0,ig.newId)()),tu(n)===void 0&&gg(n)}return t}B.mintEmbedIdentity=oW;function gg(e){let t=(0,ig.newId)(),r=`{${t}}`;if(!Re(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=Se(e.bag.a),i=n.find(o=>Array.isArray(o)&&o[0]==="uniqueid");return i?i[1]=r:n.push(["uniqueid",r]),e.bag.a=n,e.bag.c=Se(e.bag.c),t}B.setUniqueId=gg;function HS(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function aW(e){let t=Se(e.c).filter(r=>r?.n==="customControl").map(r=>{var n,i;return(i=(n=co(r,"name"))!==null&&n!==void 0?n:co(r,"id"))!==null&&i!==void 0?i:"unnamed"});return[...new Set(t)].join(", ")||"no custom control"}function sW(e){let t=[],r;for(let{cell:n,pointer:i}of Sn(e)){let o=n.control;if(!Re(o))continue;let a=`${i}/control`;if(o.genPage===void 0){lW(e,o,a,t);continue}r=r??Nd(e),uW(e,o,a,r,t)}return t}B.genPageEmbedIssues=sW;function lW(e,t,r,n){if(!mg(e,t))return;let i=eu(Xo(e.bag,Oi(t)));n.push((0,nn.issue)(r,"genpage-embed-removed",`this control still embeds generative page ${i.pageId}: removing genPage alone would leave that binding on the form. To remove the embed, remove the cell (or set the cell's control to null); to change the page, edit genPage/pageId. A copy fetched by an older SDK (projection 3) shows no genPage at all \u2014 re-fetch the form.`))}function uW(e,t,r,n,i){var o;let a=`${r}/genPage`,s=t.genPage;if(!Re(s))i.push((0,nn.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${HS(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!_r(s.pageId))&&i.push((0,nn.issue)(`${a}/pageId`,"genpage-embed-shape",`genPage.pageId must be the id (a GUID) of a generative page, got ${s.pageId===void 0?"nothing":JSON.stringify(s.pageId)}`)),s.inputData!==void 0&&!Re(s.inputData)&&i.push((0,nn.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${HS(s.inputData)}`));for(let m of Object.keys(s))X9.has(m)||i.push((0,nn.issue)(j9.JsonPointer.append(a,m),"genpage-embed-unknown-key",`'${m}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}Td(t)||i.push((0,nn.issue)(`${r}/fieldName`,"genpage-embed-bound",`a generative-page embed is an unbound control, but this one is bound to column '${t.fieldName}'. Set fieldName to null, or embed the page in a new cell.`)),t.classId!==void 0&&KS(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,nn.issue)(`${r}/classId`,"genpage-embed-class-id",`a generative-page embed is the custom control {${B.CUSTOM_CONTROL_CLASS_ID}}, but classId is ${JSON.stringify(t.classId)}. Omit classId (the SDK defaults it) or set it to that class.`));let l=fg(e);l!=="Main"&&i.push((0,nn.issue)(a,"genpage-embed-main-form-only",`a generative page can be embedded only in a Main form, as in the maker portal; this is a ${l} form.`));let u=tu(t);u!==void 0&&!_r(u)&&i.push((0,nn.issue)(`${r}/bag`,"genpage-embed-unique-id",`this embed's uniqueid ${JSON.stringify(u)} is not a GUID, and its page binding is keyed by it. Remove it from the bag (the SDK mints one) or set a GUID.`));let c=Oi(t);if(!c)return;let d=Xo(e.bag,c),f=d?eu(d):void 0;d&&f?.kind==="none"?i.push((0,nn.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${aW(d)}). genPage would have to delete that binding to take its place, so embed the page in a new cell instead.`)):f?.kind==="unsupported"&&i.push((0,nn.issue)(a,"genpage-embed-unsupported-binding","this control already embeds a page through a binding genPage cannot represent exactly \u2014 a RefId or PageInput bound to a column, a RefId that is not a page id, or form factors that disagree. Taking it over would silently turn it into a static binding, so embed the page in a new cell instead.")),((o=n.get(c))!==null&&o!==void 0?o:0)>1&&i.push((0,nn.issue)(`${r}/bag`,"genpage-embed-duplicate-unique-id",`this embed's uniqueid {${c}} is also carried by another control on the form, so both would share one binding. Author the copy without its bag and the SDK mints a new identity for it.`))}});var bg=v(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.findMissingGenPages=fo.GENPAGE_LOOKUP_CHUNK=void 0;var cW=Lt(),yg=le();fo.GENPAGE_LOOKUP_CHUNK=50;async function dW(e,t,r){let n=[...new Set(t.map(o=>(0,yg.normalizeGuid)(o,"uxagentprojectid")))],i=new Set;for(let o=0;o<n.length;o+=fo.GENPAGE_LOOKUP_CHUNK){let a=n.slice(o,o+fo.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,yg.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,cW.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,yg.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(o=>!i.has(o))}fo.findMissingGenPages=dW});var ru=v(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.assertSystemFormKind=_t.readSystemFormType=_t.decodeCode=_t.assertSystemFormRecordKind=_t.describeSystemFormType=_t.systemFormKindOf=_t.SYSTEMFORM_KIND_MISMATCH_CODE=void 0;var eN=Q(),fW=ye(),ZS=le();_t.SYSTEMFORM_KIND_MISMATCH_CODE="SYSTEMFORM_KIND_MISMATCH";var pW={0:"dashboard",10:"dashboard",2:"form",6:"form",7:"form",11:"form"},mW={0:"dashboard",1:"appointment book",2:"Main form",3:"mini campaign form",4:"preview form",5:"mobile express form",6:"Quick View form",7:"Quick Create form",8:"dialog",9:"task flow form",10:"interactive dashboard",11:"card form",12:"interactive Main form",13:"contextual dashboard",100:"other form",101:"Main form backup",102:"appointment book backup",103:"Power BI dashboard"};function Id(e){return Number.isInteger(e)?pW[e]:void 0}_t.systemFormKindOf=Id;function tN(e){var t;return Number.isFinite(e)?`a ${(t=mW[e])!==null&&t!==void 0?t:"systemform"} (type ${e})`:"a systemform whose type could not be read"}_t.describeSystemFormType=tN;function rN(e,t,r,n){let i=tN(r),o=Id(r);switch(n){case"fetch":return`Refusing to fetch systemform '${e}' as a ${t}: it is ${i}. Nothing was read into the workspace. `+(o?`Fetch it as a ${o}.`:Number.isFinite(r)?"The SDK does not model that kind: check the id.":"Check the id.");case"write":return`Refusing to write systemform '${e}' as a ${t}: it is ${i}. Nothing was written. Check the id: a local copy fetched by an SDK that did not check the kind can name a row of another kind \u2014 discard it with deleteArtifact('${t}', '${e}').`;case"delete":return`Refusing to delete systemform '${e}' as a ${t}: it is ${i}. Nothing was changed. Check the id.`;default:return`Refusing to ${n} systemform '${e}': it is ${i}, not a ${t}.`+(n==="set the security roles of"?" Nothing was written.":"")+" Check the id."}}function hW(e,t,r,n){let i=vg(e?.type);if(Id(i)!==r)throw new eN.SdkError(_t.SYSTEMFORM_KIND_MISMATCH_CODE,rN(t,r,i,n));return i}_t.assertSystemFormRecordKind=hW;function vg(e){if(typeof e=="number")return Number.isInteger(e)?e:NaN;if(typeof e!="string"||!/^\s*-?\d+\s*$/.test(e))return NaN;let t=Number(e);return Number.isInteger(t)?t:NaN}_t.decodeCode=vg;async function gW(e,t){return await nN(e,t,!1)}_t.readSystemFormType=gW;async function yW(e,t){return nN(e,t,!0)}async function nN(e,t,r){var n;let o=`/systemforms(${(0,ZS.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,ZS.odataQuery)([["$select","type"]]),a=await e.get(o);if(!(r&&a.status===404))return(0,fW.ensureSuccess)(a,e.apiUrl(o)),vg((n=a.body)===null||n===void 0?void 0:n.type)}async function bW(e,t,r){let n=await yW(e,t);if(!(n===void 0||Id(n)===r))throw new eN.SdkError(_t.SYSTEMFORM_KIND_MISMATCH_CODE,rN(t,r,n,"delete"))}_t.assertSystemFormKind=bW});var Cg=v(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.patchSystemForm=Wr.assertSystemFormContentUnchanged=Wr.readSystemFormRowEtag=Wr.unpublishedSystemFormPath=Wr.FORM_TYPE_IMMUTABLE_CODE=void 0;var on=ye(),vW=le(),Od=Q(),po=ru();Wr.FORM_TYPE_IMMUTABLE_CODE="FORM_TYPE_IMMUTABLE";function wg(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,vW.odataQuery)([["$select",t]])}Wr.unpublishedSystemFormPath=wg;function iN(e,t){return(0,on.readRowEtag)(e,"systemforms","formid",t)}Wr.readSystemFormRowEtag=iN;async function oN(e,t,r,n,i){(0,on.requireEtag)(i,r,t);let o=(0,on.ensureSuccess)(await e.get(n),e.apiUrl(n)),a=(0,po.assertSystemFormRecordKind)(o.body,t,r,"write"),s=(0,on.readEtag)(o);if(s===null)throw new Od.SdkError(on.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its current version could not be read, so the write could not be verified as conditional and would risk silently overwriting a concurrent edit.`);if(s!==i)throw new Od.SdkError(on.VERSION_CONFLICT_CODE,`Version conflict writing ${r} '${t}': its formxml changed on the server since it was read (held ${i}, server ${s}). Re-fetch the ${r} and re-apply the change.`);return a}Wr.assertSystemFormContentUnchanged=oN;async function wW(e,t,r,n,i,o){(0,on.requireEtag)(i,r,t);let a=await iN(e,t);if(a===null)throw new Od.SdkError(on.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its row version could not be read, so the write could not be made conditional and would risk silently overwriting a concurrent edit.`);let s=await oN(e,t,r,wg(t,"formid,type"),i);if(n.type!==void 0&&(0,po.decodeCode)(n.type)!==s)throw new Od.SdkError(Wr.FORM_TYPE_IMMUTABLE_CODE,`Refusing to push ${r} '${t}': it would change it from ${(0,po.describeSystemFormType)(s)} to ${(0,po.describeSystemFormType)((0,po.decodeCode)(n.type))}. The platform ignores a type change on an existing ${r}, so the push would report a change that did not happen. Nothing was written. Create a new ${r} of that type instead.`);let l=(0,on.echoWrite)("formid",{"If-Match":a}),u=`/systemforms(${t})${l.query}`;return(0,on.ensureSuccess)(await e.patch(u,n,l.options),e.apiUrl(u)),CW(e,t,r,o)}Wr.patchSystemForm=wW;async function CW(e,t,r,n){let i;try{let o=wg(t,n.select),a=(0,on.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,l=(0,on.readEtag)(a),u=typeof s?.formid=="string"&&s.formid.replace(/[{}]/g,"").toLowerCase()===t,c=typeof s?.formxml=="string"&&s.formxml.trim()!=="",d=n.required.filter(p=>s?.[p]===void 0||s?.[p]===null),f=(0,po.decodeCode)(s?.type),m=(0,po.systemFormKindOf)(f)===r;if(l&&u&&c&&d.length===0&&m)return{id:t,etag:l,readBack:s};i=l?!u||!c?`the read did not return this ${r}'s document`:d.length>0?`the read did not return its ${d.join(", ")}`:`the read returned ${(0,po.describeSystemFormType)(f)}, not a ${r}`:"the read returned no version"}catch(o){i=o instanceof Error?o.message:String(o)}return{id:t,etag:null,warnings:[`The ${r} was saved, but its new version could not be read (${i}). The SDK holds no version for it now, so the next push is refused: re-fetch the ${r} before editing it again.`]}}});var _g=v($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.getFormSecurityRoles=$t.setFormSecurityRoles=$t.formApi=$t.readPrimaryCreateRefusal=$t.FORM_GENPAGE_TARGET_UNVERIFIABLE=$t.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var EW=Lt(),Tt=ye(),an=le(),ea=Q(),Eg=uo(),sN=Dd(),AW=bg(),Ag=Cg(),nu=ru();$t.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";$t.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var lN="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",SW={select:lN,required:["name","type","objecttypecode"]},NW="formid,name,type,objecttypecode",_W=2,TW={Main:_W,QuickView:6,QuickCreate:7,Card:11},uN=new WeakMap;function DW(e){return typeof e=="object"&&e!==null?uN.get(e):void 0}$t.readPrimaryCreateRefusal=DW;$t.formApi={async get(e,t){let r=(0,an.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,an.odataQuery)([["$select",lN]]),i=(0,Tt.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,nu.assertSystemFormRecordKind)(i.body,r,"form","fetch"),{raw:i.body,etag:(0,Tt.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=>TW[u]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,an.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,an.odataQuery)([["$select",NW],["$filter",a.join(" and ")]])}`;return(await(0,EW.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=aN(t);n!==void 0&&await cN(e,Ng(n,"payload"),[]);let i=(0,Tt.echoWrite)("formid"),o=`/systemforms${i.query}`,a=(0,Tt.withClientMintedId)(t,"formid",r),s=Object.freeze({...a}),l=await(0,Tt.resendDeadlockVictim)(()=>e.post(o,{...s},i.options));try{(0,Tt.ensureSuccess)(l,e.apiUrl(o))}catch(u){throw typeof u=="object"&&u!==null&&uN.set(u,{status:l.status,sent:s,desiredId:r}),u}return{id:(0,Tt.resolveCreatedId)(l,"formid","form",r),etag:(0,Tt.readEtag)(l)}},async update(e,t,r,n){let i=(0,an.normalizeGuid)(t,"id"),o=aN(r);return o!==void 0&&await OW(e,i,o,n),(0,Ag.patchSystemForm)(e,i,"form",r,n,SW)},readContentThenToken(e,t){return $t.formApi.get(e,t)},async delete(e,t){let r=(0,an.normalizeGuid)(t,"id");return await(0,nu.assertSystemFormKind)(e,r,"form"),(0,Tt.deleteRecord)(e,"systemforms",r)}};var Sg="DisplayConditions";async function IW(e,t,r){var n,i,o,a;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new ea.InvalidArgumentError("setFormSecurityRoles: `everyone` and `roleIds` are mutually exclusive \u2014 the platform models <Everyone /> as a replacement for the <Role> list, not an addition to it.");let s=(0,an.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,an.odataQuery)([["$select","formid,formxml,type"]]),u=(0,Tt.ensureSuccess)(await e.get(l),e.apiUrl(l));(0,nu.assertSystemFormRecordKind)(u.body,s,"form","set the security roles of");let c=(0,Tt.readEtag)(u),d=u.body,f=d?.formxml;if(!f)throw new ea.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let m=(0,Eg.parseXmlRoot)(f,"<form/>"),p=m.ownerDocument;if(!p)throw new ea.InvalidArgumentError(`form '${s}' produced no owner document`);let h=dN(m,Sg),g=h?.hasAttribute("Order")&&(n=h.getAttribute("Order"))!==null&&n!==void 0?n:void 0,b=h?.getAttribute("FallbackForm")||void 0;h&&m.removeChild(h);let w=!!r.everyone||((o=(i=r.roleIds)===null||i===void 0?void 0:i.length)!==null&&o!==void 0?o:0)>0;if(!w&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!h)throw new ea.InvalidArgumentError("setFormSecurityRoles: `order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to. Pass the roles as well.");r.order!==void 0&&h.setAttribute("Order",String(r.order)),r.fallbackForm!==void 0&&h.setAttribute("FallbackForm",String(r.fallbackForm)),m.appendChild(h)}else if(w){let I=p.createElement(Sg),D=r.order!==void 0?String(r.order):g;D!==void 0&&I.setAttribute("Order",D);let P=r.fallbackForm!==void 0?String(r.fallbackForm):b??"false";if(I.setAttribute("FallbackForm",P),r.everyone)I.appendChild(p.createElement("Everyone"));else for(let x of(a=r.roleIds)!==null&&a!==void 0?a:[]){let K=p.createElement("Role");K.setAttribute("Id",`{${(0,an.normalizeGuid)(x,"roleId")}}`),I.appendChild(K)}m.appendChild(I)}let S=(0,Eg.serializeNode)(m);await(0,Ag.assertSystemFormContentUnchanged)(e,s,"form",l,c);let O=await(0,Ag.readSystemFormRowEtag)(e,s),k=`/systemforms(${s})`;(0,Tt.ensureSuccess)(await e.patch(k,{formxml:S},{headers:{"Content-Type":"application/json","If-Match":(0,Tt.requireEtag)(O,"form",s)}}),e.apiUrl(k))}$t.setFormSecurityRoles=IW;function aN(e){let t=e?.formxml;return typeof t=="string"&&t.includes(sN.GENPAGE_CONTROL_NAME)?t:void 0}function Ng(e,t){try{return(0,sN.activeEmbedBindings)(e)}catch(r){throw new ea.SdkError($t.FORM_GENPAGE_TARGET_UNVERIFIABLE,`Refusing to push the form: the ${t} formxml could not be parsed, so the generative pages it embeds cannot be verified (${r instanceof Error?r.message:String(r)}).`)}}async function cN(e,t,r){let n=new Set(r.map(([a,s])=>`${a}|${s}`)),i=t.filter(([a,s])=>!n.has(`${a}|${s}`)).map(([,a])=>a);if(i.length===0)return;let o=await(0,AW.findMissingGenPages)(e,i,"form generative-page preflight");if(o.length>0)throw new ea.SdkError($t.FORM_GENPAGE_TARGET_NOT_FOUND,`Refusing to push the form: it embeds generative page(s) ${o.map(a=>`'${a}'`).join(", ")} that do not exist in this environment. Push the page before the form that embeds it.`)}async function OW(e,t,r,n){var i;(0,Tt.requireEtag)(n,"form",t);let o=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,an.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Tt.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,nu.assertSystemFormRecordKind)(a.body,t,"form","write");let s=(0,Tt.readEtag)(a);if(s===null||s!==n)throw new ea.SdkError(Tt.VERSION_CONFLICT_CODE,`Version conflict writing form '${t}': its formxml changed on the server since it was read (held ${n}, server ${s??"(unreadable)"}). Re-fetch the form and re-apply the change.`);let l=(i=a.body)===null||i===void 0?void 0:i.formxml,u=typeof l=="string"&&l!==""?Ng(l,"server"):[];await cN(e,Ng(r,"payload"),u)}function dN(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 PW(e,t){var r,n;let i=(0,an.normalizeGuid)(t,"formId"),o=`/systemforms(${i})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,an.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Tt.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,nu.assertSystemFormRecordKind)(a.body,i,"form","read the security roles of");let s=(r=a.body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,Eg.parseXmlRoot)(s,"<form/>"),u=dN(l,Sg);if(!u)return;let c=[],d=!1,f=u.childNodes;for(let p=0;p<f.length;p+=1){let h=f[p];if(h.nodeType!==1)continue;let g=h;if(g.tagName==="Everyone")d=!0;else if(g.tagName==="Role"){let b=(n=g.getAttribute("Id"))!==null&&n!==void 0?n:"";b&&c.push(b.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)}:{}}}$t.getFormSecurityRoles=PW});var Tg=v(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.deleteSolution=be.getDeploymentSettingsTemplate=be.importSolution=be.exportSolution=be.removeSolutionComponent=be.addSolutionComponent=be.setSolutionVersion=be.createSolution=be.createPublisher=be.getSolution=be.fetchSolutionComponents=be.resolveGenPageComponentType=be.SolutionComponentType=void 0;var RW=Lt(),Ft=ye(),ur=le(),kW=pt(),Yt=Q();be.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80};var LW=[be.SolutionComponentType.SavedQuery,be.SolutionComponentType.Workflow,be.SolutionComponentType.SavedQueryVisualization,be.SolutionComponentType.SystemForm,be.SolutionComponentType.AppModule],fN="uxagentproject",pN=new WeakMap;async function vN(e){var t;let r=pN.get(e);if(r!==void 0)return r;let n=`/EntityDefinitions(LogicalName='${fN}')${(0,ur.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status===404)return;(0,Ft.ensureSuccess)(i,e.apiUrl(n));let o=(t=i.body)===null||t===void 0?void 0:t.ObjectTypeCode;if(typeof o!="number"||!Number.isInteger(o)||o<=0)throw new Yt.SdkError("GENPAGE_COMPONENT_TYPE_UNRESOLVED",`A generative page's solution component type \u2014 the ObjectTypeCode of '${fN}' \u2014 could not be read: its metadata answered without a usable value (${JSON.stringify(o)}). Without it a solution's generative pages cannot be told apart from other components. Retry.`);return pN.set(e,o),o}be.resolveGenPageComponentType=vN;var mN=1,hN=0;async function $W(e,t){let r=(0,ur.normalizeGuid)(t,"solutionId"),n=await vN(e),o=[mN,...LW,...n===void 0?[]:[n]].map(c=>`componenttype eq ${c}`).join(" or "),a=`/solutioncomponents${(0,ur.odataQuery)([["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${r} and (${o})`]])}`,s=await(0,RW.collectPages)(e,a,"fetchSolutionComponents"),l=[];for(let c of s){if(typeof c.objectid!="string")continue;let d=Number(c.componenttype);if(d===mN){let f=c.rootcomponentbehavior;(f===hN||f===String(hN))&&l.push({objectId:c.objectid,componentType:d,includesAllSubcomponents:!0});continue}l.push({objectId:c.objectid,componentType:d,...n!==void 0&&d===n?{genPage:!0}:{}})}let u=c=>c.objectId.toLowerCase().replace(/^\{|\}$/g,"");return l.sort((c,d)=>c.componentType-d.componentType||(u(c)<u(d)?-1:u(c)>u(d)?1:0))}be.fetchSolutionComponents=$W;function xW(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 FW(e,t){var r,n,i,o,a,s,l,u,c,d;let f=String(t??"").trim();if(!f)throw new Yt.InvalidArgumentError("getSolution: a solution unique name or id is required.");let m=xW(f)?`solutionid eq ${(0,ur.normalizeGuid)(f,"solutionId")}`:`uniquename eq '${(0,ur.odataLiteral)(f)}'`,p=`/solutions${(0,ur.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",m]])}`,b=((n=(r=(0,Ft.ensureSuccess)(await e.get(p),e.apiUrl(p)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!b?.solutionid)throw new Yt.InvalidArgumentError(`No solution found for '${t}'.`);let w=b.publisherid;if(!w?.publisherid)throw new Yt.InvalidArgumentError(`Solution '${(i=b.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in w))throw new Yt.InvalidArgumentError(`Solution '${(o=b.uniquename)!==null&&o!==void 0?o:t}' returned a publisher without a customizationprefix property (partial expansion), so its prefix cannot be determined.`);return{solutionId:(0,ur.normalizeGuid)(b.solutionid,"solutionId"),uniqueName:(a=b.uniquename)!==null&&a!==void 0?a:"",friendlyName:(s=b.friendlyname)!==null&&s!==void 0?s:"",version:(l=b.version)!==null&&l!==void 0?l:"",isManaged:!!b.ismanaged,publisherId:(0,ur.normalizeGuid)(w.publisherid,"publisherId"),publisherUniqueName:(u=w.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=w.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=w.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}be.getSolution=FW;async function MW(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,Ft.ensureSuccess)(await(0,Ft.resendDeadlockVictim)(()=>e.post("/publishers",{...n})),e.apiUrl("/publishers")),o=(0,Ft.readCreatedId)(i,"publisherid");if(!o)throw new Yt.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}be.createPublisher=MW;async function UW(e,t){var r;let n=(0,ur.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 o=(0,Ft.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,Ft.readCreatedId)(o,"solutionid");if(!a)throw new Yt.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}be.createSolution=UW;async function BW(e,t,r){let i=`/solutions(${(0,ur.normalizeGuid)(t,"solutionId")})`;(0,Ft.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}be.setSolutionVersion=BW;async function qW(e,t){var r;let i={ComponentId:(0,ur.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,Ft.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}be.addSolutionComponent=qW;async function VW(e,t,r,n){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,ur.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,Ft.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}be.removeSolutionComponent=VW;async function GW(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},a=(n=(0,Ft.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!a)throw new Yt.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}be.exportSolution=GW;async function WW(e,t){let r=[["overwriteUnmanagedCustomizations","overwrote unmanaged customizations made over the solution's components"],["publishWorkflows","activated the solution's workflows"]];for(let[a,s]of r)if(typeof t?.[a]!="boolean")throw new Yt.InvalidArgumentError(`importSolution: '${a}' is required and must be true or false (it was ${String(t?.[a])}). It used to default to true, which ${s} unless the caller said otherwise. Nothing was imported.`);let n=t.deploymentSettings===void 0?void 0:t5(t.deploymentSettings),i={OverwriteUnmanagedCustomizations:t.overwriteUnmanagedCustomizations,PublishWorkflows:t.publishWorkflows,CustomizationFile:t.base64,ImportJobId:t.importJobId?(0,ur.normalizeGuid)(t.importJobId,"importJobId"):(0,kW.newId)()};if(!n)return(0,Ft.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{};if(n.variables.length===0&&n.references.length===0)return(0,Ft.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:{environmentVariables:[],connectionReferences:[]}};let o=[];try{let a=await wN(e,t.base64,iu,o),{parameters:s,applied:l}=r5(a,n);return i.ComponentParameters=s,(0,Ft.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:l,...o.length>0?{warnings:o}:{}}}catch(a){throw(0,Yt.withCleanupWarnings)(a,o)}}be.importSolution=WW;var iu="importSolution",gN="getDeploymentSettingsTemplate";async function zW(e,t){var r;let n=t?.base64;if(typeof n!="string"||n.length===0)throw new Yt.InvalidArgumentError(`${gN}: 'base64' must be the solution package \u2014 a non-empty base64 string, e.g. exportSolution's result (it was ${(r=JSON.stringify(n))!==null&&r!==void 0?r:String(n)})`);let i=[];try{let o=await wN(e,n,gN,i),a=Pd(o.variables,l=>l.SchemaName).map(({SchemaName:l,DefaultValue:u,TypeId:c,IsRequired:d})=>({SchemaName:l,Value:"",...u!==void 0?{DefaultValue:u}:{},...c!==void 0?{TypeId:c}:{},...d!==void 0?{IsRequired:d}:{}})),s=Pd(o.references,l=>l.LogicalName).map(({LogicalName:l,ConnectorId:u})=>({LogicalName:l,ConnectionId:"",...u!==void 0?{ConnectorId:u}:{}}));return{settings:{EnvironmentVariables:a,ConnectionReferences:s},...i.length>0?{warnings:i}:{}}}catch(o){throw(0,Yt.withCleanupWarnings)(o,i)}}be.getDeploymentSettingsTemplate=zW;function Pd(e,t){return[...e].sort((r,n)=>{let i=t(r).toLowerCase(),o=t(n).toLowerCase();return i<o?-1:i>o?1:0})}function ta(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xt(e,t=120){var r;let n=(r=JSON.stringify(e))!==null&&r!==void 0?r:String(e);return n.length>t?`${n.slice(0,t)}\u2026`:n}async function wN(e,t,r,n){var i;let a=(i=(0,Ft.ensureSuccess)(await e.post("/StageSolution",{CustomizationFile:t}),e.apiUrl("/StageSolution")).body)===null||i===void 0?void 0:i.StageSolutionResults;try{return HW(a,r)}finally{await jW(e,ta(a)?a.StageSolutionUploadId:void 0,n)}}async function jW(e,t,r){let n;try{n=(0,ur.normalizeGuid)(t,"StageSolutionUploadId")}catch{r.push(`StageSolution's reply named no usable staging upload id (${xt(t,60)}), so the staged copy of the package it may have stored (a stagesolutionupload row of yours) could not be deleted.`);return}let i=`/stagesolutionuploads(${n})`;try{let o=await e.delete(i);o.status!==404&&(0,Ft.ensureSuccess)(o,e.apiUrl(i))}catch(o){r.push(`The staged copy of the package (stagesolutionupload ${n}) could not be deleted: ${o instanceof Error?o.message:String(o)}. It stays until it is deleted (DELETE ${i}).`)}}function lr(e,t){return new Yt.SdkError("SOLUTION_STAGING_UNREADABLE",`${e}: StageSolution's reply could not be read \u2014 ${t}.${e===iu?" Nothing was imported.":""}`)}function yN(e){return!Array.isArray(e)||e.length===0?"none":`${e.slice(0,5).map(r=>ta(r)&&typeof r.Message=="string"?r.Message:xt(r,200)).join("; ")}${e.length>5?` (+${e.length-5} more)`:""}`}function HW(e,t){if(!ta(e))throw lr(t,`it holds no StageSolutionResults (${xt(e,60)})`);let r=e.StageSolutionStatus;if(r==="Failed"||r===0)throw new Yt.SdkError("SOLUTION_STAGING_FAILED",`${t}: the package did not pass StageSolution in this environment (status ${xt(r)}). Missing dependencies: ${yN(e.MissingDependencies)}. Validation: ${yN(e.SolutionValidationResults)}.${t===iu?" Its components cannot be checked against deploymentSettings. Nothing was imported.":" Stage it in the environment it was exported from."}`);if(r!=="Passed"&&r!==1)throw lr(t,`StageSolutionStatus is ${xt(r)}, neither "Passed" nor "Failed"`);let n=e.SolutionComponentsDetails;if(!Array.isArray(n))throw lr(t,`SolutionComponentsDetails is not a list (${xt(n,60)})`);let i=[],o=[],a=new Set,s=new Set;return n.forEach((l,u)=>{let c=`SolutionComponentsDetails[${u}]`;if(!ta(l))throw lr(t,`${c} is not an object`);if(typeof l.ComponentTypeName!="string")throw lr(t,`${c}.ComponentTypeName is not a string`);let d=l.ComponentTypeName.toLowerCase();if(d!=="environmentvariabledefinition"&&d!=="connectionreference")return;let f=KW(l.Attributes,`${c}.Attributes`,t),m=(p,h)=>{let g=f.get(p);if(g==null){if(h)throw lr(t,`${c}.${p} is missing`);return}if(typeof g!="string"||h&&g.length===0)throw lr(t,`${c}.${p} is not ${h?"a non-empty string":"a string"}`);return g};if(d==="environmentvariabledefinition"){let p=m("schemaname",!0);if(a.has(p.toLowerCase()))throw lr(t,`${c}.schemaname '${p}' is listed twice`);a.add(p.toLowerCase());let h=m("defaultvalue",!1),g=JW(f.get("type"),`${c}.type`,t),b=YW(f.get("isrequired"),`${c}.isrequired`,t);i.push({SchemaName:p,...h!==void 0?{DefaultValue:h}:{},...g!==void 0?{TypeId:g}:{},...b!==void 0?{IsRequired:b}:{}})}else{let p=m("connectionreferencelogicalname",!0);if(s.has(p.toLowerCase()))throw lr(t,`${c}.connectionreferencelogicalname '${p}' is listed twice`);s.add(p.toLowerCase());let h=m("connectorid",!1);o.push({LogicalName:p,...h!==void 0?{ConnectorId:h}:{}})}}),{variables:i,references:o}}function KW(e,t,r){if(!ta(e)||!Array.isArray(e.Keys)||!Array.isArray(e.Values))throw lr(r,`${t} is not { Keys: [...], Values: [...] }`);let{Keys:n,Values:i}=e;if(n.length!==i.length)throw lr(r,`${t} has ${n.length} keys but ${i.length} values`);let o=new Map;return n.forEach((a,s)=>{if(typeof a!="string")throw lr(r,`${t}.Keys[${s}] is not a string`);if(o.has(a))throw lr(r,`${t}.Keys lists '${a}' twice`);o.set(a,i[s])}),o}function JW(e,t,r){if(e!=null){if(typeof e=="number"&&Number.isSafeInteger(e))return e;if(typeof e=="string"&&/^\d{1,15}$/.test(e))return Number(e);throw lr(r,`${t} is not a whole number (${xt(e,40)})`)}}function YW(e,t,r){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"&&/^(true|false)$/i.test(e))return e.toLowerCase()==="true";throw lr(r,`${t} is not true or false (${xt(e,40)})`)}}var QW=new Set(["EnvironmentVariables","ConnectionReferences","Workflows","CanvasApps","CopilotAgents","$schema"]),XW=["Workflows","CanvasApps","CopilotAgents"],ZW=new Set(["SchemaName","Value","DefaultValue","TypeId","IsRequired","Name"]),e5=new Set(["LogicalName","ConnectionId","ConnectorId"]);function sr(e,t){return new Yt.InvalidArgumentError(`${iu}: deploymentSettings is not a deployment-settings file this SDK applies \u2014 ${e} ${t}. Nothing was imported.`)}function t5(e){let t="deploymentSettings";if(!ta(e))throw sr(t,`must be an object \u2014 the settings file, parsed (it was ${xt(e,40)})`);for(let l of Object.keys(e))if(!QW.has(l))throw sr(`${t}.${l}`,"is not part of the format (EnvironmentVariables, ConnectionReferences; Workflows, CanvasApps and CopilotAgents only empty; $schema)");for(let l of XW){let u=e[l];if(u!==void 0&&!(Array.isArray(u)&&u.length===0))throw sr(`${t}.${l}`,"is a pac feature this SDK does not apply: only an empty list is accepted")}if(e.$schema!==void 0&&typeof e.$schema!="string")throw sr(`${t}.$schema`,"must be a string");let r=l=>{let u=e[l];if(u===void 0)return[];if(!Array.isArray(u))throw sr(`${t}.${l}`,`must be a list (it was ${xt(u,40)})`);return u.map((c,d)=>{if(!ta(c))throw sr(`${t}.${l}[${d}]`,`must be an object (it was ${xt(c,40)})`);return c})},n=(l,u,c)=>{let d=l[u];if(typeof d!="string"||d.length===0)throw sr(c,`must be a non-empty string (it was ${xt(d,40)})`);if(d.trim()!==d)throw sr(c,`must not begin or end with whitespace (it was ${xt(d,60)})`);return d},i=(l,u,c)=>{if(l.has(u.toLowerCase()))throw sr(c,`names '${u}' a second time (names are case-insensitive)`);l.add(u.toLowerCase())},o={variables:[],references:[]},a=new Set;r("EnvironmentVariables").forEach((l,u)=>{let c=`${t}.EnvironmentVariables[${u}]`;for(let f of Object.keys(l))if(!ZW.has(f))throw sr(`${c}.${f}`,"is not part of a variable (SchemaName, Value; DefaultValue, TypeId, IsRequired, Name)");let d=n(l,"SchemaName",`${c}.SchemaName`);if(i(a,d,`${c}.SchemaName`),typeof l.Value!="string")throw sr(`${c}.Value`,`must be a string \u2014 empty to override nothing (it was ${xt(l.Value,40)})`);l.Value.length>0&&o.variables.push({name:d,value:l.Value})});let s=new Set;return r("ConnectionReferences").forEach((l,u)=>{let c=`${t}.ConnectionReferences[${u}]`;for(let m of Object.keys(l))if(!e5.has(m))throw sr(`${c}.${m}`,m==="ConnectionInstance"?"is pac's connection-instance feature, which this SDK does not apply":"is not part of a connection reference (LogicalName, ConnectionId, ConnectorId)");let d=n(l,"LogicalName",`${c}.LogicalName`);i(s,d,`${c}.LogicalName`);let f=l.ConnectionId;if(typeof f!="string")throw sr(`${c}.ConnectionId`,`must be a string \u2014 empty to bind nothing (it was ${xt(f,40)})`);if(f.trim()!==f)throw sr(`${c}.ConnectionId`,`must not begin or end with whitespace (it was ${xt(f,60)})`);if(l.ConnectorId!==void 0&&typeof l.ConnectorId!="string")throw sr(`${c}.ConnectorId`,`must be a string (it was ${xt(l.ConnectorId,40)})`);f.length>0&&o.references.push({name:d,connectionId:f,...l.ConnectorId?{connectorId:l.ConnectorId}:{}})}),o}function bN(e,t=20){return e.length===0?"none":`${e.slice(0,t).join(", ")}${e.length>t?` (+${e.length-t} more)`:""}`}function r5(e,t){var r;let n=new Map(e.variables.map(l=>[l.SchemaName.toLowerCase(),l])),i=new Map(e.references.map(l=>[l.LogicalName.toLowerCase(),l])),o=[],a=[],s={environmentVariables:[],connectionReferences:[]};for(let l of t.variables){let u=n.get(l.name.toLowerCase());if(!u){o.push(`EnvironmentVariables: '${l.name}' is not a variable of the package`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.environmentvariablevalue",schemaname:u.SchemaName,value:l.value}),s.environmentVariables.push(u.SchemaName)}for(let l of t.references){let u=i.get(l.name.toLowerCase());if(!u){o.push(`ConnectionReferences: '${l.name}' is not a connection reference of the package`);continue}if(l.connectorId!==void 0&&l.connectorId.toLowerCase()!==((r=u.ConnectorId)===null||r===void 0?void 0:r.toLowerCase())){o.push(`ConnectionReferences: '${l.name}' names connector '${l.connectorId}', but the package's reference is for ${u.ConnectorId?`'${u.ConnectorId}'`:"no connector"}`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.connectionreference",connectionreferencelogicalname:u.LogicalName,connectionid:l.connectionId,...u.ConnectorId!==void 0?{connectorid:u.ConnectorId}:{}}),s.connectionReferences.push(u.LogicalName)}if(o.length>0){let l=o.join("; "),u=bN(Pd(e.variables,d=>d.SchemaName).map(d=>d.SchemaName)),c=bN(Pd(e.references,d=>d.LogicalName).map(d=>d.LogicalName));throw new Yt.InvalidArgumentError(`${iu}: deploymentSettings does not match the package \u2014 ${l}. The package's variables: ${u}; its connection references: ${c}. Nothing was imported.`)}return{parameters:a,applied:s}}async function n5(e,t){let n=`/solutions(${(0,ur.normalizeGuid)(t,"solutionId")})`;(0,Ft.ensureSuccess)(await e.delete(n),e.apiUrl(n))}be.deleteSolution=n5});var _N=v(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.recoverFormCreate=mt.solutionMembershipProblem=mt.formWriteMismatches=mt.validateExistingForm=mt.formExistsAtId=mt.isFormRecordAt=mt.MAIN_FORM_TYPE=void 0;var fs=le(),CN=Lt(),EN=Tg();mt.MAIN_FORM_TYPE=2;function Rd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kd(e){return e instanceof Error?e.message:String(e)}function Dg(e,t){if(typeof e!="string"||typeof t!="string")return!1;try{return(0,fs.normalizeGuid)(e,"a GUID")===(0,fs.normalizeGuid)(t,"a GUID")}catch{return!1}}function Ig(e,t){return Rd(e)&&Dg(e.formid,t)}mt.isFormRecordAt=Ig;async function i5(e,t){try{return Ig((await e()).raw,t)}catch{return!1}}mt.formExistsAtId=i5;function AN(e,t){let r=e.raw;if(!Rd(r))return{problem:"it is not a record"};if(!Ig(r,t))return{problem:"its formid is not the id this create sent"};if(r.type!==mt.MAIN_FORM_TYPE)return{problem:`its type is not ${mt.MAIN_FORM_TYPE} (a Main form)`};if(typeof r.objecttypecode!="string")return{problem:"its objecttypecode is not a string"};if(typeof r.name!="string")return{problem:"its name is not a string"};if(typeof r.formxml!="string"||r.formxml.length===0)return{problem:"its formxml is not a non-empty string"};if(typeof r.formpresentation!="number")return{problem:"its formpresentation is not a number"};if(typeof r.formactivationstate!="number")return{problem:"its formactivationstate is not a number"};for(let o of["uniquename","description"]){let a=r[o];if(a!=null&&typeof a!="string")return{problem:`its ${o} is neither a string nor null`}}let n=r["@odata.etag"];if(n!==void 0&&typeof n!="string")return{problem:"its @odata.etag is not a string"};if(n!==void 0&&e.etag!==null&&e.etag!==n)return{problem:"the ETag header and the @odata.etag of the body disagree"};let i=e.etag;return i===null?{problem:"the read carries no concurrency token"}:i.trim()===""||i.trim()==="*"?{problem:"its concurrency token is blank or a wildcard"}:{record:r,etag:i}}mt.validateExistingForm=AN;function SN(e,t){let r=[];for(let i of["formxml","name","objecttypecode","type"])e[i]!==t[i]&&r.push(i);let n=t.description;if(n!==void 0){let i=e.description;typeof n=="string"&&(n===""?i==null||i==="":i===n)||r.push("description")}return r}mt.formWriteMismatches=SN;async function NN(e,t){let r=e.solutionName;if(r)try{let n=await(0,CN.collectPages)(e,`/solutions${(0,fs.odataQuery)([["$select","solutionid,uniquename"],["$filter",`uniquename eq '${(0,fs.odataLiteral)(r)}'`]])}`,"createRecovery solution lookup");if(n.length!==1)return`the configured solution '${r}' resolves to ${n.length} solutions, not exactly one`;let[i]=n,o;return Rd(i)&&typeof i.uniquename=="string"&&typeof i.solutionid=="string"&&i.uniquename.toLowerCase()===r.toLowerCase()&&(o=(0,fs.normalizeGuid)(i.solutionid,"solutionid")),o===void 0?`the configured solution '${r}' did not resolve to a valid solution of that name`:(await(0,CN.collectPages)(e,`/solutioncomponents${(0,fs.odataQuery)([["$select","objectid,componenttype,_solutionid_value"],["$filter",`_solutionid_value eq ${o} and componenttype eq ${EN.SolutionComponentType.SystemForm} and objectid eq ${t}`]])}`,"createRecovery solution membership")).some(l=>Rd(l)&&l.componenttype===EN.SolutionComponentType.SystemForm&&Dg(l.objectid,t)&&Dg(l._solutionid_value,o))?void 0:`the form is not a component of the configured solution '${r}'`}catch(n){return`membership in the configured solution '${r}' could not be established (${kd(n)})`}}mt.solutionMembershipProblem=NN;async function o5(e){try{return await a5(e)}catch(t){return{refused:`the recovery could not be completed (${kd(t)})`}}}mt.recoverFormCreate=o5;async function a5(e){let{client:t,read:r,sent:n,authoredFormType:i,project:o}=e;if(i!=="Main"||n.type!==mt.MAIN_FORM_TYPE)return{refused:`only a Main form is adopted (this one is authored as ${String(i)})`};let a=n.formid;if(typeof a!="string")return{refused:"the create sent no formid to look for"};let s;try{s=await r()}catch(f){return{refused:`the existing row could not be read (${kd(f)})`}}let l=AN(s,a);if("problem"in l)return{refused:`the existing row cannot be trusted: ${l.problem}`};let u=SN(l.record,n);if(u.length>0)return{refused:`the existing row is not what this create wrote (it differs in ${u.join(", ")})`};let c;try{c=o(l.record)}catch(f){return{refused:`the existing row could not be read into a form (${kd(f)})`}}let d=await NN(t,a);return d!==void 0?{refused:d}:{adopted:{artifact:c,etag:l.etag}}}});var $d=v(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.disassociateRecords=Ke.associateRecords=Ke.createRecordsBulk=Ke.upsertRecord=Ke.queryAllRecords=Ke.queryRecords=Ke.getRecord=Ke.deleteRecord=Ke.updateRecord=Ke.createRecord=void 0;var Og=Lt(),Nn=ye(),Qt=le(),ps=Q(),Yn=bd();function Ld(e){let t=e,r=!1,n={};for(let i of Object.keys(t)){let o=t[i];Array.isArray(o)&&o.every(a=>typeof a=="number")?(n[i]=o.join(","),r=!0):n[i]=o}return r?n:e}async function s5(e,t,r){let i=`/${await(0,Yn.resolveEntitySetName)(e,t)}`,o=(0,Nn.ensureSuccess)(await e.post(i,Ld(r)),e.apiUrl(i)),a=(0,Nn.readCreatedId)(o,`${t}id`);if(!a)throw new ps.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}Ke.createRecord=s5;async function l5(e,t,r,n){let i=(0,Qt.normalizeGuid)(r,"id"),a=`/${await(0,Yn.resolveEntitySetName)(e,t)}(${i})`;(0,Nn.ensureSuccess)(await e.patch(a,Ld(n)),e.apiUrl(a))}Ke.updateRecord=l5;async function u5(e,t,r){let n=(0,Qt.normalizeGuid)(r,"id"),o=`/${await(0,Yn.resolveEntitySetName)(e,t)}(${n})`;(0,Nn.ensureSuccess)(await e.delete(o),e.apiUrl(o))}Ke.deleteRecord=u5;async function c5(e,t,r,n){let i=(0,Qt.normalizeGuid)(r,"id"),o=await(0,Yn.resolveEntitySetName)(e,t),a=(0,Qt.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),s=`/${o}(${i})${a}`,l=(0,Nn.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=l.body;if(u===null||typeof u!="object"||Array.isArray(u))throw new ps.ConnectionError(e.apiUrl(s),l.status,`getRecord: read returned a malformed row \u2014 expected an OData entity object but got ${Array.isArray(u)?"an array":(0,Og.describeMalformedValue)(u)}; refusing to read it as a row.`);return u}Ke.getRecord=c5;function d5(e){return e?.fetchXml?(0,Qt.odataQuery)([["fetchXml",e.fetchXml]]):(0,Qt.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 TN(e,t,r){var n;if(r?.paginate){if(r.top!==void 0)throw new ps.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 ps.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,Yn.resolveEntitySetName)(e,t)}${d5(r)}`;if(r?.paginate)return(0,Og.collectPages)(e,o,"queryRecords");let a=(0,Nn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new ps.ConnectionError(e.apiUrl(o),a.status,`queryRecords: read returned a malformed page \u2014 expected an OData 'value' array but got ${(0,Og.describeMalformedValue)(s)}; refusing to read it as rows.`);return s}Ke.queryRecords=TN;async function f5(e,t,r){return TN(e,t,{...r,paginate:!0})}Ke.queryAllRecords=f5;function p5(e){if("id"in e)return`(${(0,Qt.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,Qt.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,Qt.assertODataName)(e.key,"alternate key name")}=${t})`}async function m5(e,t,r,n){let i=p5(r),a=`/${await(0,Yn.resolveEntitySetName)(e,t)}${i}`,s=(0,Nn.ensureSuccess)(await e.patch(a,Ld(n)),e.apiUrl(a)),l=s.status===201,u=(0,Nn.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,Qt.normalizeGuid)(r.id,"id"):""),created:l}}Ke.upsertRecord=m5;async function h5(e,t,r){var n,i;if(r.length===0)return[];let o=await(0,Yn.resolveEntitySetName)(e,t),a=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...Ld(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Nn.ensureSuccess)(await e.post(s,{Targets:a}),e.apiUrl(s)).body)===null||n===void 0?void 0:n.Ids)!==null&&i!==void 0?i:[];if(u.length!==r.length)throw new ps.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Ke.createRecordsBulk=h5;async function g5(e,t,r,n){let i=(0,Qt.normalizeGuid)(r,"id"),o=(0,Qt.normalizeGuid)(n.targetId,"targetId"),a=await(0,Yn.resolveEntitySetName)(e,t),s=await(0,Yn.resolveEntitySetName)(e,n.targetEntity),l=(0,Qt.assertODataName)(n.relationshipName,"relationshipName"),u=`/${a}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,Nn.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Ke.associateRecords=g5;async function y5(e,t,r,n,i){let o=(0,Qt.normalizeGuid)(r,"id"),a=(0,Qt.normalizeGuid)(i,"targetId"),s=await(0,Yn.resolveEntitySetName)(e,t),l=(0,Qt.assertODataName)(n,"relationshipName"),u=`/${s}(${o})/${l}(${a})/$ref`;(0,Nn.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Ke.disassociateRecords=y5});var xd=v(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.base64ToUtf8=sn.base64ToBytes=sn.bytesToBase64=sn.utf8ToBase64=sn.utf8ToBytes=void 0;var Pg=32768,Tr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function ou(){return globalThis}function DN(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=r+1<e.length?e.charCodeAt(r+1):0;i>=56320&&i<=57343?(n=(n-55296<<10)+(i-56320)+65536,r+=1):n=65533}else n>=56320&&n<=57343&&(n=65533);n<128?t.push(n):n<2048?t.push(192|n>>6,128|n&63):n<65536?t.push(224|n>>12,128|n>>6&63,128|n&63):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return Uint8Array.from(t)}function b5(e){let t="";for(let r=0;r<e.length;r+=Pg)t+=String.fromCharCode(...e.subarray(r,r+Pg));return t}function v5(e){let t="";for(let r=0;r<e.length;r+=1){let n=String.fromCharCode(e.charCodeAt(r)&255);if(n==="=")break;n==="-"?t+="+":n==="_"?t+="/":Tr.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function w5(e){let t="",r=0;for(;r+2<e.length;r+=3){let i=e[r]<<16|e[r+1]<<8|e[r+2];t+=Tr[i>>18&63]+Tr[i>>12&63]+Tr[i>>6&63]+Tr[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Tr[i>>18&63]}${Tr[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,o=Tr[i>>18&63],a=Tr[i>>12&63],s=Tr[i>>6&63];t+=`${o}${a}${s}=`}return t}function C5(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0,r=e.length/4*3-t,n=new Uint8Array(r>0?r:0),i=0;for(let o=0;o<e.length;o+=4){let a=Tr.indexOf(e[o])<<18|Tr.indexOf(e[o+1])<<12|(e[o+2]==="="?0:Tr.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:Tr.indexOf(e[o+3]));i<r&&(n[i++]=a>>16&255),i<r&&(n[i++]=a>>8&255),i<r&&(n[i++]=a&255)}return n}function E5(e){let t=ou();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"utf8"));let r=t.TextEncoder;return r?new r().encode(e):DN(e)}sn.utf8ToBytes=E5;function A5(e){let t=ou();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return IN(r?new r().encode(e):DN(e))}sn.utf8ToBase64=A5;function IN(e){let t=ou();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(b5(e)):w5(e)}sn.bytesToBase64=IN;function ON(e){let t=ou();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=v5(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return C5(r)}sn.base64ToBytes=ON;function S5(e){let t=[],r="",n=()=>{r+=String.fromCharCode(...t),t.length=0},i=a=>{if(a>65535){let s=a-65536;t.push(55296+(s>>10),56320+(s&1023))}else t.push(a);t.length>=Pg&&n()},o=0;for(;o<e.length;){let a=e[o],s=0,l=0,u=128,c=191;if(a<128){i(a),o+=1;continue}else if(a>=194&&a<=223)s=1,l=a&31;else if(a>=224&&a<=239)s=2,l=a&15,u=a===224?160:128,c=a===237?159:191;else if(a>=240&&a<=244)s=3,l=a&7,u=a===240?144:128,c=a===244?143:191;else{i(65533),o+=1;continue}let d=o+1,f=!0;for(let m=0;m<s;m+=1,d+=1){let p=d<e.length?e[d]:-1;if(p<u||p>c){f=!1;break}u=128,c=191,l=l<<6|p&63}f?(i(l),o=d):(i(65533),o=d)}return n(),r}function N5(e){let t=ou();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):S5(ON(e))}sn.base64ToUtf8=N5});var $N=v(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.deleteWebResource=Qn.getWebResource=Qn.updateWebResource=Qn.createWebResource=void 0;var _5=Qr(),ra=ye(),au=le(),Rg=xd(),ms=Q(),T5={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function PN(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,Rg.utf8ToBase64)(e.content)}async function RN(e,t){return(0,_5.publishWebResourceById)(e,t)}async function kN(e,t,r){try{await RN(e,t)}catch(n){let i=r?`Web resource '${r.name}' (${t})`:`Web resource ${t}`,o=`write its content again with updateWebResource('${t}', \u2026), which publishes and verifies again`+(r?" \u2014 it exists, and a second create of this name is refused":""),a=(0,ra.isConcurrencyLockRefusalError)(n)?`Another customization operation holds the environment's lock, and content has been observed missing after a publish the lock refused, so publishing again alone may not recover it: once the lock frees, ${o}.`:`Resolve that failure first, then ${o}.`;throw(0,ms.attachCause)(new ms.WebResourceUnverifiedError(t,r?.name,`${i} was written, but publishing it failed, so whether its published content is what was sent is unconfirmed (${n instanceof Error?n.message:String(n)}). ${a}`),n)}}function D5(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}async function LN(e,t,r,n){var i;let o=n?`Web resource '${n.name}' (${t})`:`Web resource ${t}`,a=n?`It exists: write its content again with updateWebResource('${t}', \u2026), which publishes and verifies again \u2014 a second create of this name is refused.`:"Writing it again is safe.",s=c=>new ms.WebResourceUnverifiedError(t,n?.name,`${o} ${c} ${a}`),l=`/webresourceset(${t})${(0,au.odataQuery)([["$select","content"]])}`,u;try{u=(i=(0,ra.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)===null||i===void 0?void 0:i.content}catch(c){throw(0,ms.attachCause)(s("was written and published, but reading its published content back failed, so whether the write applied is unknown."),c)}if(typeof u!="string")throw s("was written and published, but the read-back carried no content, so whether the write applied is unknown.");if(!D5((0,Rg.base64ToBytes)(u),(0,Rg.base64ToBytes)(r)))throw s("was written and published, but the published content is not what was sent, so the write did not apply.")}async function I5(e,t){var r;let n=PN(t);if(n===void 0)throw new ms.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:T5[t.type],content:n};t.description&&(i.description=t.description);let o=(0,ra.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,ra.readCreatedId)(o,"webresourceid");if(!a)throw new ms.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&(await kN(e,a,{name:t.name}),await LN(e,a,n,{name:t.name})),{id:a,name:t.name}}Qn.createWebResource=I5;async function O5(e,t,r){let n=(0,au.normalizeGuid)(t,"id"),i={},o=PN(r);o!==void 0&&(i.content=o),r.displayName!==void 0&&(i.displayname=r.displayName),r.description!==void 0&&(i.description=r.description);let a=`/webresourceset(${n})`;(0,ra.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),r.publish!==!1&&(o!==void 0?(await kN(e,n,void 0),await LN(e,n,o,void 0)):await RN(e,n))}Qn.updateWebResource=O5;async function P5(e,t){var r;let i=`/webresourceset(${(0,au.normalizeGuid)(t,"id")})${(0,au.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,ra.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}Qn.getWebResource=P5;async function R5(e,t){let n=`/webresourceset(${(0,au.normalizeGuid)(t,"id")})`;(0,ra.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Qn.deleteWebResource=R5});var Fd=v(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.applyAppSettings=Dt.setAppSetting=Dt.readAppSettings=Dt.resolveSettingDefinitions=Dt.APP_SETTING_UNSET=Dt.APP_SETTING_OFF=Dt.APP_SETTING_ON=Dt.HEADER_AND_NAVIGATION_REFRESH=void 0;var hs=ye(),Pi=le();Dt.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";Dt.APP_SETTING_ON="2";Dt.APP_SETTING_OFF="1";Dt.APP_SETTING_UNSET="0";function MN(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Pi.odataQuery)([["$select",e],["$filter",t]])}async function UN(e,t){var r,n;let i=[...new Set(t.filter(Boolean))],o=new Map;if(i.length===0)return o;let a=i.map(c=>`uniquename eq '${(0,Pi.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,Pi.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",a]])}`,u=((n=(r=(0,hs.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&&o.set(c.uniquename,c);return o}Dt.resolveSettingDefinitions=UN;async function k5(e,t){var r,n,i,o;let a=(0,Pi.normalizeGuid)(t,"App id"),s=MN("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${a}`),u=((n=(r=(0,hs.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(f=>f._settingdefinitionid_value).filter(Boolean))],d=new Map;if(c.length>0){let f=c.map(h=>`settingdefinitionid eq ${(0,Pi.normalizeGuid)(h,"Setting definition id")}`).join(" or "),m=`/settingdefinitions${(0,Pi.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",f]])}`,p=(0,hs.ensureSuccess)(await e.get(m),e.apiUrl(m));for(let h of((o=(i=p.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[]).filter(Boolean))h.settingdefinitionid&&d.set(h.settingdefinitionid.toLowerCase(),h)}return u.map(f=>{var m,p,h,g,b;let w=d.get(((m=f._settingdefinitionid_value)!==null&&m!==void 0?m:"").toLowerCase());return{id:(p=f.appsettingid)!==null&&p!==void 0?p:"",name:(g=(h=w?.uniquename)!==null&&h!==void 0?h:f._settingdefinitionid_value)!==null&&g!==void 0?g:"",value:(b=f.value)!==null&&b!==void 0?b:"",...w?.displayname?{displayName:w.displayname}:{}}})}Dt.readAppSettings=k5;async function xN(e,t,r){var n,i,o;let a=MN("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,hs.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(Boolean)[0];return l?.appsettingid?{id:l.appsettingid,value:(o=l.value)!==null&&o!==void 0?o:""}:void 0}async function BN(e,t,r,n){let i=(0,Pi.normalizeGuid)(t,"App id"),a=(await UN(e,[r])).get(r),s=a?.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,Pi.normalizeGuid)(s,"Setting definition id"),u=await xN(e,i,l);if(u)return FN(e,u,n);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${l})`,value:n},f,m;try{if(f=await e.post(c,d),f.status>=200&&f.status<300)return"created"}catch(h){m=h}let p;try{p=await xN(e,i,l)}catch{p=void 0}if(p)return FN(e,p,n);throw f&&(0,hs.ensureSuccess)(f,e.apiUrl(c)),m}Dt.setAppSetting=BN;async function FN(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,Pi.normalizeGuid)(t.id,"App setting id")})`;return(0,hs.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function L5(e,t,r){var n;let i=[];for(let[o,a]of Object.entries(r??{}))try{await BN(e,t,o,a)}catch(s){i.push(`App setting '${o}' was not applied: ${(n=s?.message)!==null&&n!==void 0?n:String(s)} The app was created; set it later with setAppSetting().`)}return i}Dt.applyAppSettings=L5});var Ud=v(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});Md.HEADER_NAV_BOOLEAN_RULE=void 0;Md.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var $g=v(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.compileGenPage=ke.legacyEnumsNeeded=ke.createGenPageTypeScriptLoader=ke.acceptGenPageTypeScript=ke.isLoadableGenPageOutput=ke.runtimeTypesImportSpans=ke.GENPAGE_RUNTIME_TYPES_END=ke.GENPAGE_RUNTIME_TYPES_BEGIN=ke.GENPAGE_TYPESCRIPT_VERSION=void 0;var gs=Q();ke.GENPAGE_TYPESCRIPT_VERSION="5.8.3";ke.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";ke.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var _n="./RuntimeTypes",$5="'\"`",qN=/\s/;function x5(e){return e===10||e===13||e===8232||e===8233}function F5(e,t){let r=[];e.lastIndex=0;for(let n=e.exec(t);n!==null;n=e.exec(t))r.push(n.index);return r}function zN(e){let t=[],r=_n.length;for(let l=e.indexOf(_n);l!==-1;l=e.indexOf(_n,l+1)){let u=l-1;u>=0&&$5.includes(e[u])&&e[u+1+r]===e[u]&&t.push(u)}let n=[];if(t.length===0)return n;let i=-1,o=l=>{if(i<l)for(i=l;i<e.length&&e[i]!=="'"&&e[i]!=='"';)i+=1;return i},a=-1,s=l=>{for(;a+1<t.length&&t[a+1]<=l;)a+=1;return a>=0?t[a]:-1/0};for(let l=e.indexOf("import");l!==-1;){let u=l+1;if(l+6<e.length&&qN.test(e[l+6])){let c=s(o(l+6));if(c>=l+8){let d=c+2+r;for(e[d]===";"&&(d+=1);d<e.length&&qN.test(e[d]);)d+=1;n.push({start:l,end:d}),u=d}}l=e.indexOf("import",u)}return n}ke.runtimeTypesImportSpans=zN;var M5=/\b(?:import\s*['"]|export\s)/;function U5(e){let t=F5(/from\s+['"]/g,e);if(t.length===0)return!1;let r=/\bimport\s/g,n=-1,i=0;for(let o=r.exec(e);o!==null;o=r.exec(e)){let a=o.index+7;if(a>n)for(n=a;n<e.length&&!x5(e.charCodeAt(n));)n+=1;for(;i<t.length&&t[i]<a+1;)i+=1;if(i<t.length&&t[i]<n)return!0}return!1}function B5(e){return e!==void 0&&e!==""&&(M5.test(e)||U5(e))}ke.isLoadableGenPageOutput=B5;var VN=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function jN(e){var t;let r=s=>s!==null&&(typeof s=="object"||typeof s=="function")?s:void 0,n=r(e);n&&typeof n.transpileModule!="function"&&(n=(t=r(n.default))!==null&&t!==void 0?t:n);let i=n?VN.filter(s=>typeof n?.[s]!="function"):[...VN];if(!n||i.length>0)throw new gs.SdkError("GENPAGE_COMPILER_INVALID",`The TypeScript compiler supplied as MakerSdkOptions.typescript is not the typescript module (missing ${i.join(", ")}). Pass the 'typescript' package's module object, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node', or \u2014 in a bare engine \u2014 globalThis.ts after evaluating typescript@${ke.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof n.version=="string"?n.version:"",a=ke.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new gs.SdkError("GENPAGE_COMPILER_VERSION",`The TypeScript compiler supplied as MakerSdkOptions.typescript is version '${o||"unknown"}', but generative pages are compiled with ${a}.x \u2014 the version the maker portal itself uses (${ke.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${ke.GENPAGE_TYPESCRIPT_VERSION}.`);return n}ke.acceptGenPageTypeScript=jN;function q5(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new gs.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`This push must compile a generative page, but no TypeScript compiler was supplied. Pass MakerSdkOptions.typescript \u2014 in Node, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node'; in a bare engine, globalThis.ts after evaluating typescript@${ke.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(jN).catch(r=>{throw t=void 0,r instanceof gs.SdkError?r:new gs.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`The TypeScript compiler could not be loaded, so a generative page cannot be compiled (${r instanceof Error?r.message:String(r)}). Nothing was written.`)})}return t}}ke.createGenPageTypeScriptLoader=q5;var HN=e=>`${e.kind}:${e.pos}:${e.end}`;function V5(e,t){return()=>r=>{let n=i=>{let o=e.getParseTreeNode(i);o&&t.add(HN(o)),e.forEachChild(i,n)};return n(r),r}}function Lg(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}var G5=2301;function GN(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:Lg(e),reportDiagnostics:!0,...r?{transformers:{after:[V5(e,r)]}}:{}}),o=((n=i.diagnostics)!==null&&n!==void 0?n:[]).filter(a=>a.category===e.DiagnosticCategory.Error).map(a=>{let s=a.file&&typeof a.start=="number"?a.file.getLineAndCharacterOfPosition(a.start):{line:0,character:0};return{line:s.line+1,column:s.character+1,rule:"genpage-source-syntax",code:a.code,message:e.flattenDiagnosticMessageText(a.messageText,`
+`)}});return{code:i.outputText,diagnostics:o}}var WN=e=>e.startsWith(".")||e.startsWith("/"),Bd={line:1,column:1};function kg(e,t){let r=o=>{let a=t.getLineAndCharacterOfPosition(o.getStart(t));return{line:a.line+1,column:a.character+1}},n=o=>(e.isImportDeclaration(o)||e.isExportDeclaration(o))&&o.moduleSpecifier&&e.isStringLiteral(o.moduleSpecifier)?o.moduleSpecifier.text:void 0,i=o=>t.statements.filter(a=>e.isImportDeclaration(a)&&n(a)===o);return{statement(o,a){let s=t.statements.find(l=>n(l)===o&&(a==="import"?e.isImportDeclaration(l):e.isExportDeclaration(l)));return s?r(s):Bd},element(o,a){var s;for(let l of i(o)){let u=(s=l.importClause)===null||s===void 0?void 0:s.namedBindings,c=u&&e.isNamedImports(u)?u.elements.find(d=>d.name.text===a):void 0;if(c)return r(c)}return this.statement(o,"import")},binding(o){var a,s;for(let l of t.statements)if(e.isImportDeclaration(l)&&l.importClause){let u=l.importClause,c=u.namedBindings,d=((a=u.name)===null||a===void 0?void 0:a.text)===o?u.name:c&&e.isNamespaceImport(c)&&c.name.text===o?c.name:c&&e.isNamedImports(c)?c.elements.find(f=>f.name.text===o):void 0;if(d)return r(d)}else{if((e.isFunctionDeclaration(l)||e.isClassDeclaration(l))&&((s=l.name)===null||s===void 0?void 0:s.text)===o)return r(l.name);if(e.isVariableStatement(l)){let u=l.declarationList.declarations.find(c=>e.isIdentifier(c.name)&&c.name.text===o);if(u)return r(u.name)}}return Bd}}}function W5(e,t,r,n){var i,o;let a=[],s=kg(e,r),l=(p,h,g)=>{a.push({...p,rule:h,code:0,message:g})},u=(p,h)=>{var g;return(e.canHaveModifiers(p)?(g=e.getModifiers(p))!==null&&g!==void 0?g:[]:[]).some(b=>b.kind===h)},c=(p,h)=>l(p,"genpage-relative-import",`'${h}' cannot resolve at runtime: the page is loaded as a single module from a blob URL, so the only relative import it may have is './RuntimeTypes'`),d="genpage-runtime-types-import-form",f=!1,m=new Set;for(let p of t.statements){if(e.isExportAssignment(p)){f=f||!p.isExportEquals;continue}if(e.isFunctionDeclaration(p)||e.isClassDeclaration(p)){u(p,e.SyntaxKind.ExportKeyword)&&u(p,e.SyntaxKind.DefaultKeyword)&&(f=!0),p.name&&m.add(p.name.text);continue}if(e.isExportDeclaration(p)){let w=p.exportClause;w&&e.isNamedExports(w)&&w.elements.some(S=>S.name.text==="default")&&(f=!0);let C=p.moduleSpecifier&&e.isStringLiteral(p.moduleSpecifier)?p.moduleSpecifier.text:void 0;C===_n?l(s.statement(C,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):C!==void 0&&WN(C)&&c(s.statement(C,"export"),C);continue}if(!e.isImportDeclaration(p)||!e.isStringLiteral(p.moduleSpecifier))continue;let h=p.moduleSpecifier.text,g=p.importClause;if(h!==_n){WN(h)&&c(s.statement(h,"import"),h),g?.name&&m.add(g.name.text);let w=g?.namedBindings;w&&e.isNamespaceImport(w)?m.add(w.name.text):w&&e.isNamedImports(w)&&w.elements.forEach(C=>m.add(C.name.text));continue}if(!g){l(s.statement(h,"import"),d,"a side-effect import of './RuntimeTypes' cannot resolve at runtime; import the names it declares");continue}g.name&&l(s.binding(g.name.text),d,"'./RuntimeTypes' has no default export at runtime; import its names");let b=g.namedBindings;if(b&&e.isNamespaceImport(b))l(s.binding(b.name.text),d,"a namespace import of './RuntimeTypes' is undefined at runtime \u2014 its enums are inlined under their own names; import the names instead");else if(b&&e.isNamedImports(b))for(let w of b.elements){let C=w.name.text,S=(o=(i=w.propertyName)===null||i===void 0?void 0:i.text)!==null&&o!==void 0?o:C,O=s.element(h,C);S!==C?l(O,d,`'${S} as ${C}' would be undefined at runtime: the enum is inlined as '${S}', so import it under its own name`):n?.text?n.enums.has(C)||l(O,"genpage-runtime-types-unresolved",`'${C}' is imported from './RuntimeTypes' as a VALUE, but the runtime types define no value of that name \u2014 only the choice enums of the page's data sources are values. Import a type with 'import type'.`):l(O,"genpage-runtime-types-unresolved",`'${C}' is imported from './RuntimeTypes' as a VALUE, but the page has no data sources, so no runtime types are inlined and the import reaches the runtime, which cannot load it. Import it with 'import type', or add the table it belongs to to dataSources.`)}}if(f||l(Bd,"genpage-no-default-export","the page has no default export \u2014 the runtime renders the module's default export as the page component"),n?.text)for(let p of m)n.enums.has(p)&&l(s.binding(p),"genpage-runtime-types-collision",`'${p}' is declared at the page's module scope and is also one of its inlined choice enums, so the compiled page would declare it twice and fail to load. Rename the page's binding, or import the enum from './RuntimeTypes'.`);return a}function KN(e,t,r){let n,i=()=>{if(!n){let p={getSourceFile:g=>g===t.fileName?t:void 0,getDefaultLibFileName:()=>"lib.d.ts",writeFile:()=>{},getCurrentDirectory:()=>"",getCanonicalFileName:g=>g,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>`
+`,fileExists:g=>g===t.fileName,readFile:()=>{},directoryExists:()=>!0,getDirectories:()=>[]},h={...r,noLib:!0,noResolve:!0,allowJs:!0,types:[],alwaysStrict:!0,moduleDetection:e.ModuleDetectionKind.Force};n=e.createProgram({rootNames:[t.fileName],options:h,host:p})}return n},o,a=()=>(o||(o=i().getTypeChecker()),o),s,l=()=>{if(!s){s=new Map;try{for(let p of i().getSemanticDiagnostics(t))p.code===G5&&typeof p.start=="number"&&s.set(p.start,e.flattenDiagnosticMessageText(p.messageText," "))}catch{}}return s},u=p=>e.isImportSpecifier(p)?p.parent.parent.parent:e.isImportClause(p)?p.parent:e.isNamespaceImport(p)?p.parent.parent:void 0,c=p=>{let h=u(p);return h!==void 0&&e.isImportDeclaration(h)&&e.isStringLiteral(h.moduleSpecifier)&&h.moduleSpecifier.text===_n},d=p=>{var h;for(let g=p;g;g=g.parent)if(e.canHaveModifiers(g)&&((h=e.getModifiers(g))!==null&&h!==void 0?h:[]).some(b=>b.kind===e.SyntaxKind.DeclareKeyword))return!0;return!1},f=p=>d(p)||e.isImportEqualsDeclaration(p)&&(p.isTypeOnly||e.isExternalModuleReference(p.moduleReference))||e.isImportClause(p)&&p.isTypeOnly||e.isNamespaceImport(p)&&p.parent.isTypeOnly||e.isImportSpecifier(p)&&(p.isTypeOnly||p.parent.parent.isTypeOnly),m=p=>{var h;return((h=p?.declarations)!==null&&h!==void 0?h:[]).some(g=>!c(g)&&!f(g))};return{pageOwns:p=>{let h=p.parent;return m(e.isShorthandPropertyAssignment(h)&&h.name===p?a().getShorthandAssignmentValueSymbol(h):a().getSymbolAtLocation(p))},pageOwnsLocalExport:p=>m(a().getExportSpecifierLocalTargetSymbol(p)),initializerShadow:p=>l().get(p.getStart(t))}}function z5(e,t,r,n){let i=[],o=r?.enums;if(!o||o.size===0)return i;let a=(u,c,d)=>{let f=t.getLineAndCharacterOfPosition(u.getStart(t));i.push({line:f.line+1,column:f.character+1,rule:c,code:0,message:d})},s=KN(e,t,Lg(e)),l=u=>{let c,d;if(e.isPropertyAccessExpression(u)&&e.isIdentifier(u.expression))c=u.expression,d=u.name.text;else if(e.isElementAccessExpression(u)&&e.isIdentifier(u.expression)){let m=u.argumentExpression;e.isStringLiteral(m)||e.isNoSubstitutionTemplateLiteral(m)?(c=u.expression,d=m.text):e.isNumericLiteral(m)&&(c=u.expression,d=String(Number(m.text)))}let f=c&&o.has(c.text)&&n.has(HN(u))&&!s.pageOwns(c)?o.get(c.text):void 0;if(c&&f&&d!==void 0){let m=e.isPropertyAccessExpression(u)?`${f.name}.${d}`:`${f.name}[${JSON.stringify(d)}]`,p=Object.prototype.hasOwnProperty.call(f.runtime,d)?f.runtime[d]:void 0,h=f.labels.get(d),g;p===void 0?g={rule:"genpage-enum-member-unknown",message:`${m} is undefined at runtime: '${f.name}' has no member '${d}' in this environment's metadata \u2014 members are the column's choice labels, so a renamed or differently localized label no longer matches. Known: ${[...f.labels.keys()].map(w=>`'${w}'`).join(", ")}`}:h&&typeof p!="number"?g={rule:"genpage-enum-member-clobbered",message:`${m} is the string '${String(p)}' at runtime, not a choice value: the label '${d}' looks like a number, and another option's reverse mapping overwrites it. Use the choice's numeric value instead.`}:h&&h.length>1&&(g={rule:"genpage-enum-member-ambiguous",message:`${m} labels more than one choice (${h.join(", ")}); the compiled value is whichever option comes last. Use the choice's numeric value instead.`});let b=g?s.initializerShadow(c):void 0;g&&b!==void 0?a(u,"genpage-enum-initializer-shadowed",`${m} does not read the choice enum at runtime. ${b} (TS2301): the ES5 emit moves an instance field's initializer into the constructor, where that parameter or local shadows '${c.text}'. If you meant the constructor's '${c.text}', move the assignment into the constructor body, or make it a parameter property and read \`this.${c.text}\`. If you meant the choice enum, rename the constructor's parameter or local.`):g&&a(u,g.rule,g.message)}e.forEachChild(u,l)};return l(t),i}function j5(e,t){return e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!1,e.ScriptKind.JS).statements.some(n=>(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier!==void 0&&e.isStringLiteral(n.moduleSpecifier)&&n.moduleSpecifier.text===_n)}function JN(e,t){return t.statements.filter(r=>e.isImportDeclaration(r)&&e.isStringLiteral(r.moduleSpecifier)&&r.moduleSpecifier.text===_n).map(r=>r.getStart(t))}function H5(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=JN(e,r),i=new Set(n),o,a="",s=0;for(let l of zN(t))!o&&!i.has(l.start)&&(o={swallows:n.some(u=>u>l.start&&u<l.end),text:t.slice(l.start,l.end).trimEnd()}),a+=t.slice(s,l.start),s=l.end;return a+=t.slice(s),{code:a,inexact:o}}function K5(e,t,r){let n=new Set(JN(e,t));for(let i=t.text.indexOf(r);i!==-1;i=t.text.indexOf(r,i+1))if(!n.has(i)){let o=t.getLineAndCharacterOfPosition(i);return{line:o.line+1,column:o.character+1}}return Bd}function YN(e,t,r){if(!r||r.size===0)return[];let n=KN(e,t,{...Lg(e),target:e.ScriptTarget.ESNext}),i=new Set,o=s=>{var l,u;let c=s.parent;if(e.isImportSpecifier(c)){let d=c.parent.parent.parent;e.isImportDeclaration(d)&&e.isStringLiteral(d.moduleSpecifier)&&d.moduleSpecifier.text===_n&&((l=c.propertyName)!==null&&l!==void 0?l:c.name)===s&&i.add(s.text);return}if(e.isExportSpecifier(c)){!(c.parent.parent.moduleSpecifier!==void 0)&&((u=c.propertyName)!==null&&u!==void 0?u:c.name)===s&&!n.pageOwnsLocalExport(c)&&i.add(s.text);return}e.isPropertyAccessExpression(c)&&c.name===s||e.isBindingElement(c)&&c.propertyName===s||e.isLabeledStatement(c)||e.isBreakOrContinueStatement(c)||n.pageOwns(s)||i.add(s.text)},a=s=>{e.isIdentifier(s)&&r.has(s.text)&&o(s),e.forEachChild(s,a)};return a(t),[...r.keys()].filter(s=>i.has(s))}ke.legacyEnumsNeeded=YN;function J5(e,t,r){if(!e?.text||!t||r.length===0)return e;let n=new Map(e.enums),i=e.text;for(let o of r){let a=t.get(o);a&&(i+=a.declaration,n.set(o,a.model))}return{text:i,enums:n}}function Y5(e,t,r,n){var i;let o=new Set,a=GN(e,t,o);if(a.diagnostics.length>0)return a;let s=e.createSourceFile("page.tsx",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.TSX),l=e.createSourceFile("page.js",a.code,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),u=J5(r,n,YN(e,l,n)),c=[...W5(e,l,s,u),...z5(e,s,u,o)];if(!u?.text)return{code:a.code,diagnostics:c};let d=GN(e,u.text);if(d.diagnostics.length>0)throw new gs.SdkError("GENPAGE_RUNTIME_TYPES_INVALID",`The generated runtime types do not compile (${d.diagnostics.map(h=>`${h.line}:${h.column} ${h.message}`).join("; ")}). This is an SDK defect: the page was not written.`);let f=H5(e,a.code),m=f.code;if(c.length===0&&(!((i=f.inexact)===null||i===void 0)&&i.swallows))c.push({...kg(e,s).statement(_n,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"the maker portal's patch would remove more than this './RuntimeTypes' import: a comment or other text before it contains the word 'import', and the pattern would delete from there \u2014 taking the code in between with it. Reword or move that text."});else if(c.length===0&&f.inexact){let{text:h}=f.inexact;c.push({...K5(e,s,h),rule:"genpage-runtime-types-import-form",code:0,message:`the maker portal's patch would delete \`${h.length>80?`${h.slice(0,79)}\u2026`:h}\` from text that only looks like an import of './RuntimeTypes' \u2014 in a string, a template or a comment \u2014 so the page it ships would differ from this source. Reword that text so it no longer reads as such an import.`})}else c.length===0&&j5(e,m)&&c.push({...kg(e,s).statement(_n,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"this './RuntimeTypes' import is not one the maker portal's patch can remove (a comment holding a quote inside it stops the pattern), so it would reach the runtime, which cannot load it. Write it on one line, as 'import { name } from './RuntimeTypes';'."});return{code:[ke.GENPAGE_RUNTIME_TYPES_BEGIN,d.code,ke.GENPAGE_RUNTIME_TYPES_END,m].join(`
-`),diagnostics:c}}Le.compileGenPage=U8});var Dg=v(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.isFailureAfterPrimaryWrite=ps.failedAfterPrimaryWrite=void 0;var UN=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function B8(e){return typeof e=="object"&&e!==null&&(e[UN]=!0),e}ps.failedAfterPrimaryWrite=B8;function q8(e){return typeof e=="object"&&e!==null&&e[UN]===!0}ps.isFailureAfterPrimaryWrite=q8});var Ud=v(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.appApi=Qn.deleteAppResolvingOnce=Qn.mainFormSetShapeIssues=Qn.unpublishedAppModulesQuery=void 0;var ms=Lt(),V8=$g(),G8=dg(),BN=Jr(),W8=Od(),z8=Dg(),he=ye(),Ne=se(),Og=dt(),e_=Wl(),Se=Q(),j8=(0,Ne.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),Pg="appmoduleid,name,uniquename,description,aiappdescription";function xd(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ne.odataQuery)([["$select",e],["$filter",t],["$top",r]])}Qn.unpublishedAppModulesQuery=xd;function Rg(e,t){return xd(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function Fd(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ne.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function nu(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function H8(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Md(e,t){if(typeof e!="string")return!1;try{return(0,Ne.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function Zo(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function K8(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function t_(e,t){var r,n;let i=u=>{throw new Se.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 o=`/sitemaps${(0,Ne.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,Ne.odataLiteral)(t)}'`],["$top",1]])}`,a;try{a=await e.get(o)}catch(u){return i(`failed (${u.message})`)}if(a.status<200||a.status>=300)return i(`returned HTTP ${a.status}`);let s=(r=a.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 J8(e){let t=s=>{var l,u,c;return(c=(u=(l=s.body)===null||l===void 0?void 0:l.value)===null||u===void 0?void 0:u[0])===null||c===void 0?void 0:c.webresourceid},r=s=>`/webresourceset${(0,Ne.odataQuery)([["$select","webresourceid"],["$top",1],["$filter",s]])}`,n="(webresourcetype eq 5 or webresourcetype eq 6 or webresourcetype eq 7 or webresourcetype eq 10 or webresourcetype eq 11)",i=t(await e.get(r("webresourcetype eq 5 and ismanaged eq false and contains(name,'icon')")));if(i)return{id:i,managed:!1};let o=t(await e.get(r(`${n} and ismanaged eq false`)));if(o)return{id:o,managed:!1};let a=t(await e.get(r(n)));return a?{id:a,managed:!0}:void 0}var qN="627090ff-40a3-4053-8790-584edc5be201";function Oi(e){return e instanceof Error?e.message:String(e)}async function Y8(e,t){var r;try{let n=`/roles${(0,Ne.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${qN}`]])}`,i=await(0,ms.collectPages)(e,n,"the System Administrator role"),o=i.find(l=>typeof l.roleid=="string"&&typeof l._parentrootroleid_value=="string"&&l.roleid.toLowerCase()===l._parentrootroleid_value.toLowerCase()),a=(r=o??i.find(l=>typeof l.roleid=="string"))===null||r===void 0?void 0:r.roleid;if(!a)return`App roles: no 'System Administrator' role (template ${qN}) was found in this environment, so the SDK did not associate one with the app \u2014 it may not be visible or playable until a role is granted access to it.`;let s=`/appmodules(${t})/appmoduleroles_association/$ref`;return(0,he.ensureSuccess)(await e.post(s,{"@odata.id":e.apiUrl(`/roles(${a})`)}),e.apiUrl(s)),null}catch(n){return`App roles: could not associate the 'System Administrator' role with the app (${Oi(n)}); it will not be visible or playable until a role is granted access to it.`}}async function Q8(e,t,r=!0){let n=[];async function i(l,u,c){try{return(await(0,ms.collectPages)(e,l,`app assets (${c} for '${t}')`)).map(f=>String(f[u])).filter(f=>f&&f!=="undefined")}catch(d){return n.push(`App components: could not enumerate ${c} for table '${t}' (${Oi(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([r?i(`/systemforms${(0,Ne.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,Ne.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,Ne.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,Ne.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,Ne.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,Ne.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:n}}var VN=new WeakMap;async function X8(e,t){let r=VN.get(e);r||(r=new Map,VN.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await Z8(e,t);return i&&r.set(t,i),i}async function GN(e,t,r){let n=new Array(e.length),i=0;async function o(){for(let a=i;a<e.length;a=i)i=a+1,n[a]=await r(e[a])}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),n}async function Z8(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Ne.odataPathLiteral)(t)}')${(0,Ne.odataQuery)([["$select","MetadataId,EntitySetName"]])}`,n=await e.get(r);if(n.status>=200&&n.status<300){let i=n.body;if(i?.MetadataId&&i.EntitySetName)return{logicalName:t,metadataId:i.MetadataId,entitySetName:i.EntitySetName}}}async function WN(e,t,r){let n=[],i=Zo(t.entities),o=4,a=await GN(i,o,g=>X8(e,g)),s=i.filter((g,b)=>!a[b]);if(s.length>0)throw new Se.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${s.map(g=>`'${g}'`).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 l=a.filter(g=>!!g);for(let g of l)n.push({"@odata.id":`${g.entitySetName}(${g.metadataId})`});for(let g of Zo(t.components.forms))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of Zo(t.components.views))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of Zo(t.components.charts))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of Zo(t.components.dashboards))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});let u=new Set(t.components.forms),c=new Set(t.components.views),d=new Set(t.components.charts),f=new Map((r??[]).map(g=>[g.table,g])),m=await GN(i,o,g=>Q8(e,g,!f.has(g.toLowerCase()))),p=m.flatMap(g=>g.warnings),h=new Set([...Zo(t.components.forms),...Zo(t.components.dashboards)].map(Vr));return m.forEach((g,b)=>{let w=f.get(i[b].toLowerCase());if(w)for(let E of w.allowed)h.has(E)||(h.add(E),u.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:E}));else for(let E of g.forms)u.has(E)||(u.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:E}));for(let E of g.views)c.has(E)||(c.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:E}));for(let E of g.charts)d.has(E)||(d.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:E}))}),{components:n,tables:l,warnings:p}}function Vr(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var kg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Lg="/components/mainFormsByTable",zN=50;function r_(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function n_(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:Lg,rule:"app-main-form-set-shape",message:"must be an object mapping a table logical name to its Main form ids"}];let r=[],n=new Set(t.map(o=>o.toLowerCase())),i=new Set;for(let[o,a]of Object.entries(e)){let s=o.toLowerCase(),l=`${Lg}/${r_(o)}`;if(i.has(s)){r.push({pointer:l,rule:"app-main-form-set-shape",message:`table '${o}' is listed twice (logical names compare case-insensitively)`});continue}if(i.add(s),n.has(s)||r.push({pointer:l,rule:"app-main-form-set-table",message:`'${o}' is not a table this app's sitemap navigates to (Entity subareas: ${[...n].join(", ")||"none"})`}),!Array.isArray(a)){r.push({pointer:l,rule:"app-main-form-set-shape",message:"must be an array of Main form ids"});continue}if(a.length===0){r.push({pointer:l,rule:"app-main-form-set-empty",message:`an empty list is refused: an app with no Main form of '${o}' offers every form of the table`});continue}let u=new Set;a.forEach((c,d)=>{let f=`${l}/${d}`;typeof c!="string"||!kg.test(Vr(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):u.has(Vr(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):u.add(Vr(c))})}return r}Qn.mainFormSetShapeIssues=n_;async function jN(e,t,r){let n=t.components.mainFormsByTable;if(n===void 0)return;let i=n_(n,t.entities);if(i.length>0)throw new Se.ValidationError("app",r,i);if(Object.keys(n).length===0)return;let o=[],a=[];for(let[l,u]of Object.entries(n)){let c=l.toLowerCase(),d=await(0,ms.collectPages)(e,`/systemforms${(0,Ne.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,Ne.odataLiteral)(c)}' and type eq 2`]])}`,`app Main-form allow-list ('${c}')`),f=new Set,m=new Set;for(let h of d)typeof h.formid=="string"&&(f.add(Vr(h.formid)),Number(h.formactivationstate)===1&&m.add(Vr(h.formid)));let p=u.map(Vr);p.forEach((h,g)=>{let b=`${Lg}/${r_(l)}/${g}`;f.has(h)?m.has(h)||o.push({pointer:b,rule:"app-main-form-set-inactive",message:`Main form '${u[g]}' of '${c}' is inactive, so no app can offer it`}):o.push({pointer:b,rule:"app-main-form-set-not-main-form",message:`'${u[g]}' is not a Main form of '${c}'`})}),a.push({table:c,allowed:p,catalog:f})}let s=[...t.components.forms.map((l,u)=>({id:l,pointer:`/components/forms/${u}`})),...t.components.dashboards.map((l,u)=>({id:l,pointer:`/components/dashboards/${u}`}))];for(let l of s){let u=Vr(l.id);for(let c of a)c.catalog.has(u)&&!c.allowed.includes(u)&&o.push({pointer:l.pointer,rule:"app-main-form-set-conflict",message:`'${l.id}' is a Main form of '${c.table}' outside its allow-list, and this pin (an explicit form or dashboard, or a sitemap DashBoard subarea) would add it. Remove the pin, or list the form.`})}if(o.length>0)throw new Se.ValidationError("app",r,o);return a}async function eW(e,t){var r,n;let i=u=>({kind:"inconclusive",reason:u}),o=await e.get(xd("appmoduleid,appmoduleidunique,componentstate",`appmoduleid eq ${t}`));if(o.status<200||o.status>=300)return i(`reading the app returned HTTP ${o.status}`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a)||a.length===0)return i("reading the app returned no row");let s=a.length===1?a:a.filter(u=>Number(u?.componentstate)===1),l=s.length===1?(n=s[0])===null||n===void 0?void 0:n.appmoduleidunique:"";return typeof l!="string"||!kg.test(Vr(l))?i(`no single current layer among ${a.length} app row(s)`):{kind:"read",unique:Vr(l)}}function kd(e,t){let r;return()=>r??(r=eW(e,t))}async function i_(e,t,r,n=kd(e,t)){let i=m=>({kind:"inconclusive",reason:m}),o=await n();if(o.kind==="inconclusive")return o;let a=o.unique,s;try{let m=await(0,ms.collectPages)(e,`/appmodulecomponents${(0,Ne.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${Vr(a)} and componenttype eq 60`]])}`,`app Main-form membership ('${t}')`);if(m.some(p=>typeof p.objectid!="string"))return i("a form component carries no object id");s=m.map(p=>Vr(String(p.objectid)))}catch(m){return i(`reading its form components failed (${Oi(m)})`)}let l=new Map,u=[];for(let m of new Set(s)){let p=r.find(h=>h.catalog.has(m));p?l.set(m,p.table):u.push(m)}if(u.some(m=>!kg.test(m)))return i("a form component carries an object id that is not a GUID");let c=new Set(r.map(m=>m.table)),d=new Set;for(let m=0;m<u.length;m+=zN){let p=u.slice(m,m+zN);try{let h=await(0,ms.collectPages)(e,`/systemforms${(0,Ne.odataQuery)([["$select","formid,type,objecttypecode"],["$filter",p.map(g=>`formid eq ${g}`).join(" or ")]])}`,`app Main-form membership ('${t}': classifying components)`);for(let g of h){if(typeof g.formid!="string"||typeof g.type!="number"||g.type===2&&(typeof g.objecttypecode!="string"||g.objecttypecode===""))continue;let b=Vr(g.formid);d.add(b);let w=g.type===2?String(g.objecttypecode).toLowerCase():"";c.has(w)&&l.set(b,w)}}catch(h){return i(`classifying its form components failed (${Oi(h)})`)}}let f=u.filter(m=>!d.has(m));return f.length>0?i(`form component(s) ${f.join(", ")} could not be classified`):{kind:"read",tables:r.map(m=>{let p=[...l].filter(([,h])=>h===m.table).map(([h])=>h);return{table:m.table,members:p,extras:p.filter(h=>!m.allowed.includes(h)),missing:m.allowed.filter(h=>!p.includes(h))}})}}async function tW(e,t,r,n){let i=await i_(e,t,r,n);if(i.kind==="inconclusive")throw new Se.SdkError("APP_MAIN_FORM_SET_UNVERIFIED",`App '${t}': its Main-form allow-list was written but could not be verified \u2014 ${i.reason}.`);let o=i.tables.filter(a=>a.extras.length>0||a.missing.length>0);if(o.length>0)throw new Se.SdkError("APP_MAIN_FORM_SET_NOT_APPLIED",`App '${t}': its Main forms do not match the allow-list after the write \u2014 ${o.map(a=>`'${a.table}': unexpected [${a.extras.join(", ")}], missing [${a.missing.join(", ")}]`).join("; ")}.`)}async function rW(e,t,r,n){let i;try{i=await i_(e,t,r,n)}catch(a){i={kind:"inconclusive",reason:Oi(a)}}if(i.kind==="inconclusive")return[`Main-form membership of app '${t}' could not be verified (${i.reason}).`];let o=[];for(let a of i.tables)a.extras.length>0&&o.push(`Main-form components outside the allow-list remain for table '${a.table}': [${a.extras.join(", ")}]. This option controls additions only; it does not remove existing components. Runtime form availability has not been verified.`),a.missing.length>0&&o.push(`Allow-listed Main forms are not in app '${t}' after the push for table '${a.table}': [${a.missing.join(", ")}]; re-push to retry.`);return o}async function HN(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,he.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}async function KN(e,t,r,n=kd(e,t)){var i;if(r.length===0)return;let o=await n();if(o.kind==="inconclusive")throw new Se.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 ${o.reason}. Re-push to retry.`);let a=`/appmodulecomponents${(0,Ne.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${o.unique} and componenttype eq 1`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)throw new Se.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 reading them back returned HTTP ${s.status}. Re-push to retry.`);let l=(i=s.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(l))throw new Se.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 u=new Set(l.map(d=>d.objectid).filter(d=>typeof d=="string").map(d=>d.toLowerCase())),c=r.filter(d=>!u.has(d.metadataId.toLowerCase()));if(c.length>0)throw new Se.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${c.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${c.map(d=>`'${d.logicalName}' (expected objectid ${d.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function nW(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`,o;try{o=await oW(e,r.sitemapId,r.sitemapNameUnique)}catch(l){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${Oi(l)})`}}let a=o==="foreign",s=l=>l.kind==="deleted"?{outcome:"removed",foreignSitemap:a}:l.kind==="refused"?{outcome:"kept",foreignSitemap:a,reason:`its delete was refused (${Oi(l.error)})`}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${Oi(l.error)})`};try{if(o==="absent"||o==="foreign"){if(!r.serverRefusedSitemap)return{outcome:"kept",foreignSitemap:a,reason:"the sitemap write's outcome was never observed, so its row may still appear"};let l=await(0,he.resendAppSearchIndexRace)(()=>e.delete(n));return s(l.status===404?{kind:"deleted"}:a_(l,e.apiUrl(n)))}return e.supportsAtomicBatch?r.sitemapWriteToken?s(await s_(e,[{path:n},{path:i,etag:r.sitemapWriteToken}])):{outcome:"kept",reason:"the sitemap write returned no token of its own, and deleting the row without one could destroy another writer's change"}:{outcome:"kept",reason:"the HttpClient cannot send an atomic change set (no `postRaw`), and deleting the two rows one at a time could strand the sitemap"}}catch(l){return s({kind:"unknown",error:l})}}function iW(e,t,r){if(!(e instanceof Error))return e;let n=t.foreignSitemap?` Sitemap id '${r.sitemapId}' already belongs to ANOTHER app's sitemap, which was left untouched and must not be deleted: supply a sitemapId no other app uses, or omit it so one is minted.`:"";if(t.outcome==="removed")return e.message+=` The partial app this create wrote was removed.${n}`,e;let i=t.foreignSitemap?`appmodule '${r.appId}' (unique name '${r.uniqueName}')`:`appmodule '${r.appId}' (unique name '${r.uniqueName}') and, if it was written, sitemap '${r.sitemapId}'`,a=`a create with that unique name is refused \u2014 remove it in the maker portal, or, once you have confirmed the rows are this create's own, with ${t.foreignSitemap?`deleteRecord('appmodule', '${r.appId}')`:`deleteRecord('appmodule', '${r.appId}') and deleteRecord('sitemap', '${r.sitemapId}')`}.`;return e.message+=t.outcome==="kept"?` The partial app this create wrote was KEPT, because ${t.reason}: ${i}. While it exists, ${a}`:` Whether the partial app this create wrote was removed could not be confirmed, because ${t.reason}. Check for ${i}: while any of it exists, ${a}`,e.message+=n,e}async function oW(e,t,r){var n,i,o;let a=Fd(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);return l.length===0?"absent":String((o=(i=l[0])===null||i===void 0?void 0:i.sitemapnameunique)!==null&&o!==void 0?o:"")===r?"ours":"foreign"}async function aW(e,t){var r;let n;try{n=await e.get(xd("appmoduleid,uniquename,componentstate",`appmoduleid eq ${t}`))}catch(s){return{kind:"unsettled",why:`its unpublished read failed (${s.message})`}}if(n.status<200||n.status>=300)return{kind:"unsettled",why:`its unpublished read returned HTTP ${n.status}`};let i=(r=n.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(i)||i.length!==1)return{kind:"unsettled",why:`its unpublished read returned ${Array.isArray(i)?i.length:"no"} row(s), not exactly one`};let o=i[0],a=o?.uniquename;return!Md(o?.appmoduleid,t)||o?.componentstate!==1||typeof a!="string"||!a?{kind:"unsettled",why:"its unpublished row is not this app as a never-published draft"}:{kind:"draft",uniquename:a}}async function o_(e,t){var r;let n=(0,Ne.normalizeGuid)(t,"id"),i=b=>{throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${b} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`)},o=`/appmodules(${n})${j8}`,a;try{a=await e.get(o)}catch(b){return i(`reading the app failed (${b.message}).`)}let s,l=!1;if(a.status===404){let b=await aW(e,n);if(b.kind!=="draft")return i(`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; ${b.why}.`);s=b.uniquename,l=!0}else{if(a.status<200||a.status>=300)return i(`reading the app returned HTTP ${a.status}.`);s=(r=a.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 u=l?{draft:!0}:{appEtag:(0,he.readEtag)(a)},c=await t_(e,s);if(!c)return{uniquename:s,...u};let d=(0,Ne.normalizeGuid)(c,"sitemapId"),f=await $d(e,d),m=Fd(d,"sitemapid,sitemapnameunique,sitemapxml"),p;try{p=await e.get(m)}catch(b){return i(`reading sitemap '${d}' failed (${b.message}).`)}if(p.status<200||p.status>=300)return i(`reading sitemap '${d}' returned HTTP ${p.status}.`);let h=nu(p);if(!h)return i(`sitemap '${d}' was not returned by the unpublished-aware read.`);if(h.sitemapnameunique!==s)return i(`sitemap '${d}' now carries sitemapnameunique '${String(h.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);if(!Md(h.sitemapid,d))return i(`sitemap '${d}' was read back as a row carrying sitemapid '${String(h.sitemapid)}'.`);let g=h.sitemapxml;return typeof g!="string"?i(`sitemap '${d}' returned no sitemapxml.`):{sitemapId:d,uniquename:s,sitemapXml:g,...u,sitemapEtag:f}}async function sW(e,t,r){let n=(0,Ne.normalizeGuid)(t,"id"),i=await o_(e,n);await r?.(i.sitemapXml),await u_(e,n,i)}Qn.deleteAppResolvingOnce=sW;async function lW(e,t){let r=await s_(e,t);if(r.kind!=="deleted")throw r.error}function a_(e,t){try{return(0,he.ensureSuccess)(e,t),{kind:"deleted"}}catch(r){return l_(e.status)?{kind:"refused",error:r}:{kind:"unknown",error:r}}}function uW(e,t){var r;if(e.status!==400&&(e.status<200||e.status>=300))return!1;let n=(r=(0,e_.parseChangeSetParts)(e.body,t))===null||r===void 0?void 0:r.filter(i=>i.status<200||i.status>=300);return n!==void 0&&n.length>0&&n.every(i=>i.status===400&&(0,he.namesAppSearchIndexRace)(i.text))}async function s_(e,t){let r=`batch_${(0,Og.newId)()}`,n=`changeset_${(0,Og.newId)()}`,i=t.map((m,p)=>[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${p+1}`,"",`DELETE ${e.apiUrl(m.path)} HTTP/1.1`,...m.etag?[`If-Match: ${m.etag}`]:[],""].join(`\r
-`)),o=[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...i,`--${n}--`,`--${r}--`,""].join(`\r
-`),a=e.apiUrl("/$batch"),s=i.map((m,p)=>String(p+1)),l;try{l=await(0,he.resendWhile)(m=>uW(m,s),()=>e.postBatch(o,r),he.DEADLOCK_BACKOFF_MS)}catch(m){return{kind:"unknown",error:m}}let u=a_(l,a);if(u.kind!=="deleted")return u;let c=`app '${t[0].path}'`;if(typeof l.body!="string"||l.body.length===0)return{kind:"unknown",error:new Se.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`)};let d=(0,e_.parseChangeSetStatuses)(l.body,s);if(d===void 0)return{kind:"unknown",error:new Se.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let f=d.find(m=>m<200||m>=300);return f!==void 0?{kind:"refused",error:new Se.ConnectionError(a,f,`atomic delete of ${c} was rolled back: the change set reported HTTP ${f}`)}:d.length!==i.length?{kind:"unknown",error:new Se.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response reported ${d.length} operation result(s), expected exactly ${i.length}`)}:{kind:"deleted"}}async function $d(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,he.readEtag)(r)}catch{return null}}async function JN(e,t){let r=`/appmodules(${t})?$select=appmoduleid`,n=await e.get(r);if(n.status!==404)return(0,he.ensureSuccess)(n,e.apiUrl(r)),(0,he.readEtag)(n)}function YN(e){return{sitemapxml:e.sitemapxml,...e.sitemapname!==void 0?{sitemapname:e.sitemapname}:{}}}async function Ig(e,t,r,n){if(!n)return null;let i=await $d(e,t);if(!i)return null;try{let o=await e.get(Fd(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=nu(o);return!a||!Md(a.sitemapid,t)||a.sitemapnameunique!==n||a.sitemapxml!==r.sitemapxml||r.sitemapname!==void 0&&a.sitemapname!==r.sitemapname?null:i}catch{return null}}function l_(e){return e>=400&&e<500&&e!==408&&e!==429}function QN(e,t,r){if(!e)throw new Se.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 u_(e,t,r){let n=`/appmodules(${t})`,i=r.draft?void 0:QN(r.appEtag,t,"app");if(!r.sitemapId){if(r.draft){(0,he.ensureSuccess)(await(0,he.resendAppSearchIndexRace)(()=>e.delete(n)),e.apiUrl(n));return}await cW(e,n,i);return}if(!e.supportsAtomicBatch)throw new Se.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 lW(e,[{path:n,etag:i},{path:`/sitemaps(${r.sitemapId})`,etag:QN(r.sitemapEtag,t,"sitemap")}])}async function cW(e,t,r){(0,he.ensureSuccess)(await(0,he.resendAppSearchIndexRace)(()=>e.delete(t,{headers:{"If-Match":r}})),e.apiUrl(t))}async function XN(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,V8.collectGenPageIds)(t))]}catch(i){throw new Se.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 (${Oi(i)}).`)}if(r.length===0)return;let n=await(0,G8.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new Se.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${n.map(i=>`'${i}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function dW(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")}function fW(e,t){var r;let n=[["name",e.appModuleName],["description",e.appModuleDescription],["aiappdescription",e.appModuleAiDescription]],i={};for(let[o,a]of n)a!==void 0&&(t!==void 0&&String((r=t[o])!==null&&r!==void 0?r:"")===String(a??"")||(i[o]=a));return i}async function ZN(e,t,r){var n;let i=(0,Ne.normalizeGuid)(t,"id"),o=r==="tokens-first",a=o?await JN(e,i):null,s=Rg(Pg,i),l=(0,he.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=(n=nu(l))!==null&&n!==void 0?n:{};if(!u.appmoduleid)throw new Se.SdkError("APP_NOT_FOUND",`App '${i}' was not found (checked the unpublished-aware projection, which includes drafts).`);let c=await t_(e,u.uniquename),d=c?(0,Ne.normalizeGuid)(c,"sitemapId"):void 0,f=null;if(d){o&&(f=await $d(e,d));let p=Fd(d,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),h=(0,he.ensureSuccess)(await e.get(p),e.apiUrl(p)),g=nu(h),b=w=>{throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap '${d}' was located by unique name, but ${w}, so the sitemap cannot be read. Persisting the app without it would misreport it as having no sitemap, or write an empty one over its navigation. Retry.`)};if(!g)return b("the by-id read returned no row");if(g.sitemapnameunique!==u.uniquename)throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': sitemap '${d}' now carries sitemapnameunique '${String(g.sitemapnameunique)}', not '${String(u.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!Md(g.sitemapid,d))return b(`the by-id read returned a row carrying sitemapid '${String(g.sitemapid)}'`);if(typeof g.sitemapxml!="string")return b("the by-id read returned no sitemapxml");u.$sitemap=g,o||(f=await $d(e,d))}o||(a=await JN(e,i));let m=a??H8(u);return{raw:u,etag:f,...u.appmoduleid?{siblingEtags:{[(0,Ne.normalizeGuid)(u.appmoduleid,"appmoduleid")]:m}}:{}}}Qn.appApi={get(e,t){return ZN(e,t,"tokens-first")},readContentThenToken(e,t){return ZN(e,t,"content-first")},async list(e,t){let r=Rg(Pg);return(await(0,ms.collectPages)(e,r,"listArtifacts('app')")).map(i=>{var o,a;return{type:"app",id:(o=i.appmoduleid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",isDirty:!1}})},async create(e,t,r){let n=t;if(typeof n.appModuleName!="string"||n.appModuleName.trim()==="")throw new Se.ValidationError("app",n.appModuleId,[{pointer:"/name",rule:"app-name-required",message:"an app needs a name to be created, and its 'name' is missing or blank \u2014 set it (updateElement('app', id, '/name', \u2026), or addElement when the key was removed) and push again. Nothing was written."}]);await XN(e,n.sitemapxml);let i=await jN(e,n,n.appModuleId),o=n.iconWebResourceId?void 0:await J8(e),a=n.iconWebResourceId||o?.id;if(!a)throw new Se.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 s=null;o?.managed&&(s=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${o.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 l=n.appModuleUniqueName||K8(n.appModuleId),u={name:n.appModuleName,uniquename:l,clienttype:4,formfactor:1,navigationtype:0};n.appModuleDescription&&(u.description=n.appModuleDescription),n.appModuleAiDescription&&(u.aiappdescription=n.appModuleAiDescription),a&&(u.webresourceid=a);let c="/appmodules",d=(0,he.ensureSuccess)(await(0,he.resendDeadlockVictim)(()=>e.post(c,(0,he.withClientMintedId)(u,"appmoduleid",r))),e.apiUrl(c)),f=(0,he.resolveCreatedId)(d,"appmoduleid","app module",r),m=null,p=null,h=[];s&&h.push(s);let g={kind:"notRequested"},b=n.sitemapId?(0,Ne.normalizeGuid)(n.sitemapId,"sitemapId"):(0,Og.newId)(),w=!1,E=YN(n);try{let P="/sitemaps",L=(0,he.echoWrite)("sitemapid"),I=await e.post(`${P}${L.query}`,{sitemapid:b,sitemapnameunique:l,...E},L.options);w=l_(I.status);let D=(0,he.ensureSuccess)(I,e.apiUrl(P));p=(0,he.readEtag)(D),m=p??await Ig(e,b,E,l);let O=await WN(e,n,i);h.push(...O.warnings);let x=O.components;x.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:b}),await HN(e,f,x);let K=kd(e,f);await KN(e,f,O.tables,K),i&&await tW(e,f,i,K);let Re=await Y8(e,f);Re&&h.push(Re),n.appSettings&&Object.keys(n.appSettings).length>0&&h.push(...await(0,W8.applyAppSettings)(e,f,n.appSettings)),n.published!==!1&&(await(0,BN.publishAppModule)(e,f),g={kind:"submitted"})}catch(P){let L=await nW(e,f,{sitemapId:b,sitemapNameUnique:l,serverRefusedSitemap:w,sitemapWriteToken:p});throw(0,z8.failedAfterPrimaryWrite)(iW(P,L,{appId:f,sitemapId:b,uniqueName:l}))}let S=null;if(g.kind==="submitted")try{let P=await e.get(`/appmodules(${f})?$select=appmoduleid`);P.status>=200&&P.status<300&&(S=(0,he.readEtag)(P))}catch{}return{id:f,etag:m,serverIdentity:{sitemapId:b},siblingEtags:{[f]:S},publish:g,...h.length>0?{warnings:h}:{}}},async update(e,t,r,n,i,o){var a,s,l;let u=r,c=(0,Ne.normalizeGuid)(t,"id");if(await XN(e,u.sitemapxml),!u.sitemapId)throw new Se.ValidationError("app",c,[{pointer:"/sitemapId",rule:"app-sitemap-identity-missing",message:`missing sitemap identity \u2014 re-fetch the app before pushing edits: fetchArtifact('app', '${c}', { overwrite: true }) (it REPLACES the local copy \u2014 keep outstanding changes aside), push that refreshed copy UNTOUCHED, then re-apply your changes and push again. If the untouched push is refused with this same rule, the app has NO sitemap on the server \u2014 an earlier create committed its appmodule but not its sitemap \u2014 and it can be neither updated, published nor removed with deleteRemoteArtifact (an unpublished app reads back 404). Only for an app you have confirmed is your own abandoned partial create, with nothing else provisioning it: remove its appmodule row with deleteRecord('appmodule', '${c}'), clear the local copy with deleteArtifact('app', '${c}'), then author the app again and push.`}]);let d=(0,Ne.normalizeGuid)(u.sitemapId,"sitemapId");if(!(0,he.isVersionToken)(n))throw new Se.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${c}': ${n?`the concurrency token held for its sitemap row ('${n}') is not a version`:"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 f=await jN(e,u,c),m=await WN(e,u,f),p=`/appmodules(${c})`,h=(a=o?.[c])!==null&&a!==void 0?a:null,g,b;try{let ge=Rg(Pg,c),je=await e.get(ge);if(je.status>=200&&je.status<300){let de=nu(je);if(typeof de=="object"&&de!==null&&!Array.isArray(de)){g=de;let He=g.uniquename;b=typeof He=="string"&&He?He:void 0}}}catch{}let w=fW(u,g),E=h;if(Object.keys(w).length>0){if(!(0,he.isVersionToken)(h))throw new Se.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${c}': ${h?`the concurrency token held for its appmodule header ('${h}') is not a version`:"no concurrency token is held for its appmodule header"}, so its header edit could not be made conditional and would silently overwrite a concurrent edit. Nothing was modified. Re-fetch the app (fetchArtifact('app', '${c}', { overwrite: true })) and re-apply the change.`);let ge=(0,he.echoWrite)("appmoduleid",{"If-Match":h}),je=await e.patch(`${p}${ge.query}`,w,ge.options);if(dW(je))throw new Se.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${c}': 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,he.ensureSuccess)(je,e.apiUrl(p)),E=(0,he.readEtag)(je)}let S=YN(u),P=b||u.appModuleUniqueName||void 0,L=(0,he.echoWrite)("sitemapid",{"If-Match":n}),I=`/sitemaps(${d})`,D;try{D=(0,he.ensureSuccess)(await e.patch(`${I}${L.query}`,{...S},L.options),e.apiUrl(I))}catch(ge){throw(0,Se.withPartialTokens)(ge,{siblingEtags:{[c]:E}})}let O=[...m.warnings],x=kd(e,c);try{await HN(e,c,m.components),await KN(e,c,m.tables,x)}catch(ge){O.push(`App '${c}': one or more components were not pinned (${ge.message}). Navigation may reference content not included in the app; re-push to retry.`)}f&&O.push(...await rW(e,c,f,x));let K={kind:"notRequested"},Re=E,qt=(s=(0,he.readEtag)(D))!==null&&s!==void 0?s:await Ig(e,d,S,P);if(u.published===!0){try{await(0,BN.publishAppModule)(e,c),K={kind:"submitted"}}catch(ge){K={kind:"failed",error:ge},O.push(`App '${c}': saved, but publishing failed (${ge.message}). The app remains unpublished; re-push to retry.`)}if(K.kind==="submitted"){Re=null;try{let ge=await e.get(`/appmodules(${c})?$select=appmoduleid`);ge.status>=200&&ge.status<300&&(Re=(0,he.readEtag)(ge)),qt=(l=await Ig(e,d,S,P))!==null&&l!==void 0?l:qt}catch{}}}return{id:c,etag:qt,siblingEtags:{[c]:Re},publish:K,...O.length>0?{warnings:O}:{}}},async delete(e,t){let r=(0,Ne.normalizeGuid)(t,"id");await u_(e,r,await o_(e,r))}}});var $g=v(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.deleteAppCascade=hs.collectGenPageIds=void 0;var pW=Ud(),mW=Q(),xg=se(),hW=es();function c_(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),n=new hW.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml"),i=n?.documentElement;if(!i||t.length>0)throw new mW.InvalidArgumentError(`The app sitemap xml could not be parsed cleanly, so its generative-page children cannot be determined${t.length>0?` (${t[0]})`:""}`);let o=[],a=s=>{if(s.nodeName==="SubArea"){let u=s.getAttribute("GenPageId");u&&o.push((0,xg.normalizeGuid)(u,"GenPageId"))}let l=s.childNodes;for(let u=0;u<l.length;u+=1){let c=l[u];c.nodeType===1&&a(c)}};return a(i),o}hs.collectGenPageIds=c_;async function gW(e,t,r){let n=(0,xg.normalizeGuid)(t,"appModuleId");(0,xg.normalizeGuid)(r,"appModuleIdUnique");let i=[],o=[],a=[];await(0,pW.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&a.push(...c_(l))}),i.push({type:"app",id:n});let s=[...new Set(a)].map(l=>({type:"genPage",id:l}));return{success:o.length===0,deleted:i,failures:o,retained:s}}hs.deleteAppCascade=gW});var d_={};Hr(d_,{Guid:()=>U});var U,pt=k(()=>{"use strict";U=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 q,Yt=k(()=>{"use strict";ot();q=class e{static get EmptyString(){return""}static IsTrue(t){let r=!1;return r=t&&(this.IsStrictTrue(t)||this.IsYes(t)),r}static IsStrictTrue(t){let r=!1;return t&&(r=t.toLowerCase()==="true"),r}static IsYes(t){return t.toLowerCase()==="yes"||t.toLowerCase()==="y"}static get WhiteSpace(){return/ /g}static get EnglishAndNumericCharacters(){return/([a-z0-9A-Z]+)/g}static get ValidIdExpression(){return/([a-z0-9A-Z_]+)/g}static IsNullOrEmpty(t){return t==null||t==null||t==""}static Format(t,r){return e.IsNullOrEmpty(t)?t:t.replace(/\{\{|\}\}|\{(\d+)\}/g,function(n,i){return n=="{{"?"{":n=="}}"?"}":r[i]})}static EndsWithString(t,r){return t.indexOf(r,t.length-r.length)!==-1}static IsBlankString(t){return t.replace(/\s/g,"").length==0}static EscapeXml(t,r){let n=t;return this.IsNullOrEmpty(n)||(n=n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),r&&(n=n.replace(/"/g,"&quot;").replace(/'/g,"&apos;"))),n}static EscapeDomId(t){return t.replace(".","\\.")}static ToSnakeCase(t){let r=e.EmptyString;for(let n=0;n<t.length;n++)n!==0&&t[n]==t[n].toUpperCase()&&(r+="-"),r+=t[n].toLowerCase();return r}static GetSnakeCaseMarkup(t,r){let n="<"+this.ToSnakeCase(t);if(!R.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 R.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 f_={};Hr(f_,{ScriptUtilities:()=>R});var R,ot=k(()=>{"use strict";pt();Yt();R=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return q.IsNullOrEmpty(t.ToString())?!0:U.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:q.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 Bd,qd,ea,Vd,Fg,Gd,Mg=k(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(Bd||(Bd={}));qd=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},ea=class extends qd{key;oldValue;newValue;constructor(t,r,n,i){super(Bd.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)}},Vd=class extends qd{property;oldValue;newValue;constructor(t,r,n,i){super(Bd.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)}},Fg=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()})}},Gd=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 Fg(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 p_={};Hr(p_,{ChartGridMode:()=>an,ColumnLayoutWidths:()=>CW,ComponentCategory:()=>zd,ComponentType:()=>Ug,ControlLayoutTypes:()=>jg,DisplayConditionsInfo:()=>vW,ElementNames:()=>C,ElementProperties:()=>y,ElementType:()=>qg,EntityAttributeProperty:()=>Vg,EventType:()=>iu,FormActivationState:()=>zg,FormCanvasServiceScope:()=>LW,FormDesignerSideBarTab:()=>Bg,FormPresentation:()=>Gg,FormState:()=>Wd,FormType:()=>mt,HeaderDensityType:()=>mo,LookUpTable:()=>Xn,MORE_TAB_PREFIX:()=>AW,NavBarChildElementType:()=>Wg,PREVIEW_ID_HEADER_FLYOUT:()=>TW,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>IW,PREVIEW_ID_NAVIGATION_AREA:()=>NW,PREVIEW_ID_QUICKCREATE_ROOT:()=>PW,PREVIEW_ID_TAB:()=>OW,PREVIEW_ID_TAB_LIST:()=>DW,PREVIEW_ID_TAB_PANEL:()=>_W,PropertyModelKeys:()=>Jg,PropertyModelSectionKeys:()=>EW,RELATED_TAB_ID:()=>Yg,RELATED_TAB_PREFIX:()=>SW,SectionDefaultProperties:()=>wW,SectionLayoutTypes:()=>ze,TabContentType:()=>Hg,TabDefaultProperties:()=>ho,TabLayoutTypes:()=>We,TelemetryPropertyNames:()=>RW,UnboundControlPropertyKeys:()=>Kg,compositeAddressFields:()=>bW,compositeFieldNames:()=>Gr,compositeFields:()=>yW});var mt,Ug,Bg,C,y,qg,Gr,yW,bW,Vg,Xn,Wd,mo,Gg,vW,Wg,zg,We,wW,ho,ze,jg,Hg,CW,Kg,Jg,EW,iu,an,Yg,AW,SW,NW,_W,TW,DW,IW,OW,PW,RW,zd,LW,le=k(()=>{"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"})(mt||(mt={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(Ug||(Ug={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(Bg||(Bg={}));(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"})(C||(C={}));y={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"})(qg||(qg={}));Gr={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},yW=[Gr.fullname,Gr.yomifullname,Gr.address1_composite,Gr.address2_composite,Gr.address3_composite,Gr.billto,Gr.shipto],bW=[Gr.address1_composite,Gr.address2_composite,Gr.address3_composite,Gr.billto,Gr.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(Vg||(Vg={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(Xn||(Xn={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Wd||(Wd={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(mo||(mo={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Gg||(Gg={}));vW={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(Wg||(Wg={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(zg||(zg={}));(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"})(We||(We={}));wW={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},ho={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"})(ze||(ze={}));(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"})(jg||(jg={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(Hg||(Hg={}));CW={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"})(Kg||(Kg={}));(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"})(Jg||(Jg={}));EW={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"})(iu||(iu={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(an||(an={}));Yg="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",AW="more_tab_",SW="related_tab_",NW="preview_id_navigation_area",_W="tab-section",TW="headerFieldsFlyout",DW="tablist",IW="header_overflowButton",OW="tab",PW="quickCreateRoot",RW={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"})(zd||(zd={}));LW="CellCanvasServiceScope"});var m_={};Hr(m_,{Attribute:()=>jd,FormElementNode:()=>re});var jd,re,Dt=k(()=>{"use strict";ot();Yt();Mg();le();pt();jd=class{key;value;constructor(t,r){this.key=t,this.value=r}},re=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-${U.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(C.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new jd(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 ea(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 ea(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 ea(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 Vd(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 ea(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){R.IsNullOrUndefined(t)||(t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,0,t)}))}moveChild(t,r){let n=this.childrenNodes.indexOf(t);if(n<0)return!1;let i=Math.min(Math.max(0,n+r),this.childrenNodes.length-1);return n!==i&&this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(i,0,this.childrenNodes.splice(n,1)[0])}),!0}getChildren(t){let r=[];for(let n of this.childrenNodes)n.nodeName===t&&r.push(n);return r}getFirstChild(t){for(let r of this.childrenNodes)if(r.nodeName===t)return r;return null}getAllGrandChildren(t){let r=this.getChildren(t),n=null;return r.length===0?new Array:(n=r[0],n.childrenNodes)}deleteChild(t){if(R.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:q.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=R.IsNullOrUndefined(r)?this.childrenNodes.length:r,this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(t,r)})}deleteGrandChildren(t,r,n){this.getChildren(t)[0].deleteChildren(r,n)}addGrandChild(t,r){let n=this.getChildren(t),i=null;n.length===0?(i=new e(t,this),this.addChild(i)):i=n[0],i.addChild(r)}addGrandChildAtIndex(t,r,n){let i=this.getChildren(t),o=null;i.length===0?(o=new e(t,this),this.addChild(o)):o=i[0],o.insertChildAtIndex(r,n)}GetPropertyByParameter(t){return this.getProperty(t)}getSemanticParent(){switch(this.getNodeName()){case C.formCell:let t=this.getAncestor(C.formSection);return t||(t=this.getAncestor(C.formHeader),t)||(t=this.getAncestor(C.formFooter),t)?t:null;case C.formSection:return this.getAncestor(C.formTab);case C.formTab:return this.getAncestor(C.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(C.form);return t?t.changeTracker():null}}});var h_={};Hr(h_,{ControlClassId:()=>N,ControlNamePrefixes:()=>Hd,getControlDisplayNames:()=>kW});function kW(e){return{[N.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[N.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[N.ACIControl]:e("controls.controlNames.aci"),[N.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[N.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[N.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[N.ArticleContentControl]:e("controls.controlNames.articleContent"),[N.BooleanControl]:e("controls.controlNames.twoOption"),[N.ButtonControl]:e("controls.controlNames.button"),[N.CheckboxControl]:e("controls.controlNames.checkbox"),[N.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[N.ConnectionControl]:e("controls.controlNames.connection"),[N.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[N.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[N.DashboardControl]:e("controls.controlNames.dashboard"),[N.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[N.EditFilterControl]:e("controls.controlNames.editFilter"),[N.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[N.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[N.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[N.KBViewerControl]:e("controls.controlNames.kbViewer"),[N.LabelControl]:e("controls.controlNames.label"),[N.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[N.MapLinkControl]:e("controls.controlNames.mapLink"),[N.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[N.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[N.PowerBIControl]:e("controls.controlNames.powerBI"),[N.ProcessControl]:e("controls.controlNames.process"),[N.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[N.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[N.ReportControl]:e("controls.controlNames.report"),[N.StreamsControl]:e("controls.controlNames.streams"),[N.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[N.CurrencyControl]:e("controls.controlNames.currency"),[N.DateTimeControl]:e("controls.controlNames.dateAndTime"),[N.DecimalControl]:e("controls.controlNames.decimal"),[N.DurationControl]:e("controls.controlNames.duration"),[N.EmailAddressControl]:e("controls.controlNames.email"),[N.FileControl]:e("controls.controlNames.file"),[N.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[N.IframeControl]:e("controls.controlNames.iframe"),[N.ImageControl]:e("controls.controlNames.image"),[N.LookupControl]:e("controls.controlNames.lookup"),[N.MapsControl]:e("controls.controlNames.maps"),[N.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[N.ChoiceControl]:e("controls.controlNames.choice"),[N.QuickViewControl]:e("controls.controlNames.quickView"),[N.QuickFormControl]:e("controls.controlNames.quickForm"),[N.CustomControl]:e("controls.controlNames.customControl"),[N.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[N.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[N.SubgridControl]:e("controls.controlNames.subgrid"),[N.TextAreaControl]:e("controls.controlNames.textArea"),[N.TextboxControl]:e("controls.controlNames.textBox"),[N.TickerControl]:e("controls.controlNames.ticker"),[N.UrlControl]:e("controls.controlNames.url"),[N.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[N.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[N.IntegerControl]:e("controls.controlNames.integer"),[N.TimerControl]:e("controls.controlNames.timer"),[N.TimelineControl]:e("controls.controlNames.timeline"),[N.EmailBodyControl]:e("controls.controlNames.emailBody"),[N.PartyListControl]:e("controls.controlNames.partyList"),[N.TimezoneControl]:e("controls.controlNames.timezone"),[N.LanguageControl]:e("controls.controlNames.language"),[N.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[N.ChoicesControl]:e("controls.controlNames.choices"),[N.RegardingControl]:e("controls.controlNames.regarding"),[N.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[N.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[N.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[N.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[N.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[N.KBEditorControl]:e("controls.controlNames.KBEditor"),[N.LinkControl]:e("controls.controlNames.link")}}var N,Hd,ta=k(()=>{"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"})(N||(N={}));Hd={[N.WebResourceHTMLControl]:"WebResource",[N.WebResourceImageControl]:"WebResource",[N.IframeControl]:"IFRAME",[N.SearchWidgetControl]:"Search widget",[N.SubgridControl]:"Subgrid",[N.TimelineControl]:"Timeline",[N.QuickViewControl]:"QuickviewControl"}});var ra=v((Dle,y_)=>{var ou=new Proxy(function(){return ou},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:ou},apply:function(){return ou},construct:function(){return{}}}),g_=function(){return ou};Object.setPrototypeOf(g_,ou);y_.exports=g_});var sr,Pi,b_,v_,gs=k(()=>{"use strict";sr="cds-designer-models",Pi="FormCustomControl",b_="FormCell",v_="Form"});var na,Qg=k(()=>{"use strict";Bl();le();na=class e{static lockedFieldCount=new nr;static dependencyFieldCount=new nr;static getNecessaryLookUpTable(t){switch(t){case Xn.DependencyFieldTable:return e.dependencyFieldCount;case Xn.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case Xn.DependencyFieldTable:e.dependencyFieldCount=new nr;case Xn.LockedFieldTable:e.lockedFieldCount=new nr}}}});var Kd,w_=k(()=>{"use strict";pt();ot();le();Dt();Kd=class extends re{constructor(t){super(C.controlDescription,t)}get forControl(){let t=this.getProperty(y.ForControl);return R.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set forControl(t){this.setProperty(y.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(C.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!R.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!R.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)R.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}}});function Ri(){return Zn||(Zn=window._makerConfig,Zn&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(Zn={...Zn,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),Zn?.region==="prod"&&(Zn={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/"}}},...Zn}),Zn||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var Zn,Jd=k(()=>{"use strict";});function C_(e,t,r){if(!e)return Yd.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),Yd.add("")),!1;if(e){if(e=e.toLowerCase(),Yd.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}}),Yd.add(e),!1}return!0}function $W(e){return C_(e,Xg,"Location dictionary")?Xg[e.toLowerCase()]:"us"}function xW(){let e=Ri().location.toLowerCase();return C_(e,Xg,"Current location dictionary")?e:"us"}var Yd,Xg,qle,E_=k(()=>{"use strict";Jd();Yd=new Set,Xg={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"};qle=$W(xW())});var Y,Gle,A_=k(()=>{"use strict";Y={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"},Gle={[Y.USWest]:{geoName:"us",regionShortName:"wus"},[Y.USCentral]:{geoName:"us",regionShortName:"cus"},[Y.USEast]:{geoName:"us",regionShortName:"eus"},[Y.USEast2]:{geoName:"us",regionShortName:"eus2"},[Y.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[Y.USWest2]:{geoName:"us",regionShortName:"wus2"},[Y.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[Y.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[Y.UKSouth]:{geoName:"uk",regionShortName:"suk"},[Y.UKWest]:{geoName:"uk",regionShortName:"wuk"},[Y.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[Y.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[Y.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[Y.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[Y.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[Y.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[Y.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[Y.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[Y.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[Y.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[Y.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[Y.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[Y.AsiaEast]:{geoName:"as",regionShortName:"eas"},[Y.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[Y.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[Y.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[Y.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[Y.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[Y.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[Y.UAENorth]:{geoName:"ae",regionShortName:"nae"},[Y.UAECentral]:{geoName:"ae",regionShortName:"cae"},[Y.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[Y.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[Y.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[Y.NorwayEast]:{geoName:"no",regionShortName:"eno"},[Y.NorwayWest]:{geoName:"no",regionShortName:"wno"},[Y.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[Y.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[Y.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[Y.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[Y.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[Y.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[Y.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[Y.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[Y.GovernmentUSDodCentral]:{regionShortName:"udc"},[Y.GovernmentUSDodEast]:{regionShortName:"ude"},[Y.ChinaEast]:{regionShortName:"cne"},[Y.ChinaEast2]:{regionShortName:"cne2"},[Y.ChinaEast3]:{regionShortName:"cne3"},[Y.ChinaNorth]:{regionShortName:"cnn"},[Y.ChinaNorth2]:{regionShortName:"cnn2"},[Y.ChinaNorth3]:{regionShortName:"cnn3"},[Y.UssecEast]:{geoName:"us",regionShortName:"erx"},[Y.UssecWest]:{geoName:"us",regionShortName:"wrx"},[Y.UsnatEast]:{geoName:"us",regionShortName:"eex"},[Y.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var S_=k(()=>{"use strict";Jd();});var au=k(()=>{"use strict";Jd();E_();A_();S_();});function su(e,t){return N_?N_.isOverridden(e,t):{overridden:!1}}var N_,lu=k(()=>{"use strict";});var Zg=k(()=>{"use strict";au();lu();});function FW(e,t){let{region:r}=Ri();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=su(e.packageName,t);if(s.overridden)return typeof s.value=="string"?MW(s.value):s.value}let o=n.values,a=process.env.SETTINGS_FALLBACK_REGION?.[r];return o[r]!==void 0?o[r]:a&&o[a]!==void 0?o[a]:o.default}}function MW(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function UW(e){let t=e.packageName;if(Qd.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=>t0(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=>!Zd(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function uu(e){UW(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:FW(e,r)}}),Qd.set(e.packageName,e),Object.defineProperties({},t)}function e0(e,t){return Qd.has(e)?!!Qd.get(e).settings[t]:!1}var Qd,Xd=k(()=>{"use strict";au();lu();r0();cu();Qd=new Map});function __(e,t){let{region:r}=Ri();return()=>{let n=su(e.packageName,t);if(n.overridden)return n.value.toString()==="true";let i=e.features[t].enabledFor,o=process.env.SETTINGS_FALLBACK_REGION?.[r];return i[r]!==void 0?!!i[r]:o&&i[o]!==void 0?!!i[o]:!1}}function BW(e){let t=e.packageName;if(ef.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=>e0(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=>!Zd(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function n0(e){BW(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:__(e,i)}});let r={},n=new Set;return t.dangerouslySet={enumerable:!1,value:(i,o)=>{n.add(i),Object.defineProperty(r,i,{enumerable:!0,configurable:!0,value:o})}},t.dangerouslyReset={enumerable:!1,value:()=>{let i={};n.forEach(o=>{i[o.toString()]={enumerable:!0,configurable:!0,get:__(e,o.toString())}}),Object.defineProperties(r,i),n.clear()}},ef.set(e.packageName,e),Object.defineProperties(r,t)}function t0(e,t){return ef.has(e)?!!ef.get(e).features[t]:!1}var ef,r0=k(()=>{"use strict";au();cu();lu();Xd();ef=new Map});var D_=v((mue,T_)=>{"use strict";T_.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 P_=v(i0=>{"use strict";var qW=Object.prototype.hasOwnProperty,VW;function I_(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function O_(e){try{return encodeURIComponent(e)}catch{return null}}function GW(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=I_(n[1]),o=I_(n[2]);i===null||o===null||i in r||(r[i]=o)}return r}function WW(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(qW.call(e,i)){if(n=e[i],!n&&(n===null||n===VW||isNaN(n))&&(n=""),i=O_(i),n=O_(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}i0.stringify=WW;i0.parse=GW});var s0=v((gue,F_)=>{"use strict";var L_=D_(),tf=P_(),k_=/[\n\r\t]/g,zW=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,jW=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,HW=/^[a-zA-Z]:/,KW=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function a0(e){return(e||"").toString().replace(KW,"")}var o0=[["#","hash"],["?","query"],function(t,r){return ei(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]],R_={hash:1,query:1};function $_(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,o;if(e.protocol==="blob:")n=new ti(unescape(e.pathname),{});else if(i==="string"){n=new ti(e,{});for(o in R_)delete n[o]}else if(i==="object"){for(o in e)o in R_||(n[o]=e[o]);n.slashes===void 0&&(n.slashes=zW.test(e.href))}return n}function ei(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function x_(e,t){e=a0(e),e=e.replace(k_,""),t=t||{};var r=jW.exec(e),n=r[1]?r[1].toLowerCase():"",i=!!r[2],o=!!r[3],a=0,s;return i?o?(s=r[2]+r[3]+r[4],a=r[2].length+r[3].length):(s=r[2]+r[4],a=r[2].length):o?(s=r[3]+r[4],a=r[3].length):s=r[4],n==="file:"?a>=2&&(s=s.slice(2)):ei(n)?s=r[4]:n?i&&(s=s.slice(2)):a>=2&&ei(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||ei(n),slashesCount:a,rest:s}}function JW(e,t){if(e==="")return t;for(var r=(t||"/").split("/").slice(0,-1).concat(e.split("/")),n=r.length,i=r[n-1],o=!1,a=0;n--;)r[n]==="."?r.splice(n,1):r[n]===".."?(r.splice(n,1),a++):a&&(n===0&&(o=!0),r.splice(n,1),a--);return o&&r.unshift(""),(i==="."||i==="..")&&r.push(""),r.join("/")}function ti(e,t,r){if(e=a0(e),e=e.replace(k_,""),!(this instanceof ti))return new ti(e,t,r);var n,i,o,a,s,l,u=o0.slice(),c=typeof t,d=this,f=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=tf.parse),t=$_(t),i=x_(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||HW.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!ei(d.protocol)))&&(u[3]=[/(.*)/,"pathname"]);f<u.length;f++){if(a=u[f],typeof a=="function"){e=a(e,d);continue}o=a[0],l=a[1],o!==o?d[l]=e:typeof o=="string"?(s=o==="@"?e.lastIndexOf(o):e.indexOf(o),~s&&(typeof a[2]=="number"?(d[l]=e.slice(0,s),e=e.slice(s+a[2])):(d[l]=e.slice(s),e=e.slice(0,s)))):(s=o.exec(e))&&(d[l]=s[1],e=e.slice(0,s.index)),d[l]=d[l]||n&&a[3]&&t[l]||"",a[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=JW(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&ei(d.protocol)&&(d.pathname="/"+d.pathname),L_(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:"&&ei(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function YW(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||tf.parse)(t)),n[e]=t;break;case"port":n[e]=t,L_(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 o=t.indexOf(":");~o?(n.username=t.slice(0,o),n.username=encodeURIComponent(decodeURIComponent(n.username)),n.password=t.slice(o+1),n.password=encodeURIComponent(decodeURIComponent(n.password))):n.username=encodeURIComponent(decodeURIComponent(t))}for(var a=0;a<o0.length;a++){var s=o0[a];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:"&&ei(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function QW(e){(!e||typeof e!="function")&&(e=tf.stringify);var t,r=this,n=r.host,i=r.protocol;i&&i.charAt(i.length-1)!==":"&&(i+=":");var o=i+(r.protocol&&r.slashes||ei(r.protocol)?"//":"");return r.username?(o+=r.username,r.password&&(o+=":"+r.password),o+="@"):r.password?(o+=":"+r.password,o+="@"):r.protocol!=="file:"&&ei(r.protocol)&&!n&&r.pathname!=="/"&&(o+="@"),n[n.length-1]===":"&&(n+=":"),o+=n+r.pathname,t=typeof r.query=="object"?e(r.query):r.query,t&&(o+=t.charAt(0)!=="?"?"?"+t:t),r.hash&&(o+=r.hash),o}ti.prototype={set:YW,toString:QW};ti.extractProtocol=x_;ti.location=$_;ti.trimLeft=a0;ti.qs=tf;F_.exports=ti});var XW,M_=k(()=>{"use strict";XW=Ee(s0());});function l0(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 rf=k(()=>{"use strict";});var u0,c0,d0=k(()=>{"use strict";rf();u0=class{features=new Map;register(t,r){let n=l0(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()}},c0=new u0});var f0=k(()=>{"use strict";});function Zd(e){return ZW.has(e)}var ZW,cu=k(()=>{"use strict";Zg();r0();Xd();lu();Zg();M_();d0();rf();f0();ZW=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var e6,U_=k(()=>{"use strict";cu();e6=uu({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 G_,m0,ys,ia,p0,nf,bs,Li,Ue,B_,q_,V_,_n=k(()=>{"use strict";G_={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},m0={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"})(ys||(ys={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(ia||(ia={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(p0||(p0={}));nf=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"})(bs||(bs={}));Li=class{static StartTag="<"},Ue={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:ia.Left,labelPosition:bs.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"})(B_||(B_={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(q_||(q_={}));(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"})(V_||(V_={}))});var h0,W_=k(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(h0||(h0={}))});var H_,t6,z_,dce,fce,du,j_,pce,mce,K_=k(()=>{"use strict";H_=Ee(ra());ot();gs();U_();rs();_n();zo();le();t6=Ee(Yi());W_();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(z_||(z_={}));dce={Read:no.Read,Edit:no.Edit,Both:no.Both,Container:no.Container},fce={input:Wo.Input,bound:Wo.Bound,output:Wo.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(du||(du={}));(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"})(j_||(j_={}));pce=new Set([F.Currency,F.Decimal,F.FP,F.Multiple,F.SingleLineEmail,F.SingleLinePhone,F.SingleLineText,F.SingleLineTextArea,F.SingleLineURL,F.SingleLineTickerSymbol,F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.Enum,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.TwoOptions,F.Boolean,F.PowerBIReport,F.DateAndTimeDateAndTime,F.DateAndTimeDateOnly,F.OptionSet,F.MultiSelectOptionSet,F.CardForm]),mce={numbers:[F.WholeNone,F.FP,F.Decimal,F.Currency],text:[F.SingleLineText,F.SingleLineTextArea,F.Multiple],lookup:[F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding],dates:[F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime],allFields:[F.TwoOptions,F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime,F.FP,F.Decimal,F.WholeNone,F.WholeDuration,F.WholeTimeZone,F.WholeLanguage,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.Multiple,F.OptionSet,F.SingleLineText,F.SingleLineTextArea,F.SingleLineEmail,F.SingleLineURL,F.SingleLineTickerSymbol,F.SingleLinePhone]}});var Tn,of,J_=k(()=>{"use strict";Tn=Ee(ra());pt();ot();Yt();gs();zo();K_();rs();le();Dt();_n();of=class extends re{constructor(t){super(C.customControl,t)}customControlId;get id(){let t=this.getProperty(y.id);return R.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(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 o=i.getNodeName();t.get(o)?t.get(o).push(i):t.set(o,[i])}}}return t}getFormComponentValueByParameterName(t){let r=this.getParameters()?.get(jt.value);if(r?.length>0){let n=r[0],i=n?.getAllChildren()?.length>0?n.getAllChildren().find(a=>a.getNodeName()===t):null,o=i?.getAllChildren()?.length>0?i.getAllChildren()[0].getNodeName():"";return this.normalizePropertyValue(o)}}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===jt.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===jt.name)?.value,o={Name:i,Type:F.Grid,Columns:[]},l=this.getParameters().get(jt.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());o[c]=d}}return o}}getParameterIsStatic(t){let r=!1,n=this.getParameters().get(t)[0],i=n&&n.getAllProperties();if(i){for(let o of i)if(o.key===y.static&&o.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(y.Name)}get formFactor(){return this.getProperty(y.formFactor)}set formFactor(t){this.setProperty(y.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(Li.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,o=this.getParameters();for(let[a,s]of o)if(this.isDataSet(a))for(let l of o.get(a)){let u=l.getAllProperties(),c=this.getDatasetName(l),d=i.get(c),f=await this.parameterJSON(a,u,d,t);r.push({Name:c,Value:f})}else if(this.isGroups(s))r.push({Name:a,Value:{Type:Lh.GroupDefinition,Value:this.normalizePropertyValue(this.getParameterNodeChild(s[0].NodeName).NodeName)}}),i.get(a).groupSet?.forEach(u=>{u.groupConfigurableProperties.forEach(async c=>{let d=c.name;c.propertyType===du.dataset?o.get(jt.dataset)?.some(m=>this.getDatasetName(m)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:F.Grid}}):c.propertyType===du.property&&(o.has(d)||r.push({Name:d,Value:{Usage:c.usage}}))})});else{let l=s[0].getAllProperties(),u=i.get(a),c=await this.parameterJSON(a,l,u,t);if(c)r.push({Name:a,Value:c});else{(0,Tn.trackInfoTrace)(sr,{eventName:`${Pi}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/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,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/parametersToJSON`,eventData:{message:"parameters to json failed"}},n)}return r}async parameterJSON(t,r,n,i){if(this.isDataSet(t)){let o=n,a=r.find(s=>s.key===jt.name)?.value;if(o)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${a}`);(0,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let o=n,a=r&&r.find(l=>l.key===y.Type),s=o&&!o.ofTypeGroup.every(l=>!od.includes(l));if(this.isLookupType(a?.value)||this.isLookupType(o?.ofType)||s)if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=o.isPrimary;if(this.name===_i.FormComponent){let d=this.getFormComponentValueByParameterName(y.bindAttribute),f=await i.formModelService.loadLookupModel(d),m=f.lookupColumn,p=this.getLookupDataTypeFromAttributeMetadata(m);return{Name:t,Type:p,Usage:l,Static:u,Primary:c,EntityName:f.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(Rh.DefaultViewId),TargetEntityType:m.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(y.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(y.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(y.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(y.DependentAttributeType),AllowFilterOff:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.AllowFilterOff)),DisableQuickFind:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.DisableQuickFind)),EnableViewPicker:!q.IsStrictTrue(this.getFormComponentValueByParameterName(y.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,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/parameterJSON`,eventData:{message:"Missing custom control manifest lookup property info"}},l)}if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=this.getParameterValue(t),d=o.isPrimary;if(a){let m=a.value;return{Type:m,Static:u,Usage:l,Value:this.isNumberTypeProperty(o,m)&&Number(c)?Number(c):c,Primary:d}}if(o.ofType)return{Type:o.ofType,Static:u,Usage:l,Value:c,Primary:!0};if(o.ofTypeGroup)return{Static:u,Usage:l,Value:c,Primary:!0};let f=new Error(`No property type info for ${t}`);(0,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/parameterJSON`,eventData:{message:"Missing property type info"}},f)}else{let l=new Error(`No property manifest info for ${t}`);(0,Tn.trackWarningTrace)(sr,{eventName:`${Pi}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case $.Customer:return F.LookupCustomer;case $.Owner:return F.LookupOwner;case $.PartyList:return F.LookupPartyList;default:return n===W.Regarding?F.LookupRegarding:F.LookupSimple}}isLookupType(t){return od.includes(t)}isNumberTypeProperty(t,r){return ad.includes(r)||t.ofTypeGroup.some(n=>ad.includes(n))}isDataSet(t){return jt.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var ee,g0=k(()=>{"use strict";ee=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 Y_={};Hr(Y_,{CustomControlUniqueId:()=>oa,DeprecatedControlClassIds:()=>G,FieldControlTypes:()=>at,mapFieldTypeToControl:()=>r6});function r6(e,t){switch(e){case $.TwoOptions:return N.BooleanControl;case $.Customer:case $.CustomerType:return N.LookupControl;case $.DateTime:return t===W.DateAndTime?N.DateTimeControl:N.DateTimeControl;case $.DecimalNumber:return N.DecimalControl;case $.FloatingPointNumber:return N.FloatingNumberControl;case $.WholeNumber:return t===W.Duration?N.DurationControl:t===W.Language?N.LanguageControl:t===W.TimeZone?N.TimezoneControl:N.IntegerControl;case $.CustomerType:case $.Lookup:case $.LookupType:return t===W.Regarding?N.RegardingControl:N.LookupControl;case $.MultipleLineofText:return t===W.Email?N.EmailBodyControl:N.TextAreaControl;case $.Currency:return N.CurrencyControl;case $.Owner:case $.OwnerType:return N.LookupControl;case $.PartyList:case $.PartyListType:return N.PartyListControl;case $.Status:case $.OptionSet:return N.ChoiceControl;case $.SingleLineofText:return t===W.Email?N.EmailAddressControl:t===W.Phone?N.PhoneNumberControl:t===W.Text?N.TextboxControl:t===W.TextArea?N.TextAreaControl:t===W.TickerSymbol?N.TickerControl:t===W.Url?N.UrlControl:t===W.PhoneticGuide?N.TextboxControl:N.TextboxControl;case $.MultiSelectOptionSet:return N.ChoicesControl;case $.Image:return N.ImageControl;case $.File:return N.FileControl;case $.State:return N.ChoiceControl;case $.Status:return N.ChoiceStatusControl;default:throw new Error(`Cannot get base control for ${e} field type`)}}var G,oa,at,fu=k(()=>{"use strict";pt();Bl();ot();Yt();rs();ta();g0();_n();G=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"}};oa=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},at=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new nr;static initializeFieldControls(){let t=new nr,r=e.getControlName($.SingleLineofText,W.Phone);t.add(r,new U(G.PhoneNumberControl));let n=e.getControlName($.SingleLineofText,W.TextArea);t.add(n,new U(G.TextAreaControl));let i=e.getControlName($.SingleLineofText,W.Text);t.add(i,new U(G.TextBoxControl));let o=e.getControlName($.SingleLineofText,W.Email);t.add(o,new U(G.EmailAddressControl));let a=e.getControlName($.SingleLineofText,W.Url);t.add(a,new U(G.UrlControl));let s=e.getControlName($.SingleLineofText,W.TickerSymbol);t.add(s,new U(G.TickerControl));let l=e.getControlName($.SingleLineofText,W.PhoneticGuide);t.add(l,new U(G.TextBoxControl));let u=e.getControlName($.WholeNumber,W.Duration);t.add(u,new U(G.DurationControl));let c=e.getControlName($.WholeNumber,W.Language);t.add(c,new U(G.LanguagePickerControl));let d=e.getControlName($.WholeNumber,W.TimeZone);t.add(d,new U(G.TimeZonePicklistControl));let f=e.getControlName($.WholeNumber,W.None);t.add(f,new U(G.IntegerControl));let m=e.getControlName($.DateTime,W.DateOnly);t.add(m,new U(G.DateTimeControl));let p=e.getControlName($.DateTime,W.DateAndTime);t.add(p,new U(G.DateTimeControl));let h=e.getControlName($.LookupType,W.None);t.add(h,new U(G.LookupControl));let g=e.getControlName($.CustomerType,W.None);t.add(g,new U(G.LookupControl));let b=e.getControlName($.FloatingPointNumber,W.None);t.add(b,new U(G.FloatControl));let w=e.getControlName($.DecimalNumber,W.None);t.add(w,new U(G.DecimalControl));let E=e.getControlName($.Currency,W.None);t.add(E,new U(G.MoneyControl));let S=e.getControlName($.MultipleLineofText,W.None);t.add(S,new U(G.TextAreaControl));let P=e.getControlName($.MultipleLineofText,W.Text);t.add(P,new U(G.TextAreaControl));let L=e.getControlName($.MultipleLineofText,W.TextArea);t.add(L,new U(G.TextAreaControl));let I=e.getControlName($.MultipleLineofText,W.Email);t.add(I,new U(G.EmailBodyControl));let D=e.getControlName($.OptionSet,W.None);t.add(D,new U(G.PicklistControl));let O=e.getControlName($.TwoOptions,W.None);t.add(O,new U(G.RadioControl));let x=e.getControlName($.Image,W.None);t.add(x,new U(G.WebResourceImageControl));let K=e.getControlName($.Image,W.None);t.add(K,new U(G.WebResourceHtmlControl));let Re=e.getControlName($.TwoOptions,"Radio");t.add(Re,new U(G.RadioControl));let qt=e.getControlName($.TwoOptions,"CheckBox");t.add(qt,new U(G.CheckBoxControl));let ge=e.getControlName($.TwoOptions,"List");t.add(ge,new U(G.PicklistControl));let je=e.getControlName($.State,W.None);t.add(je,new U(G.PicklistControl));let de=e.getControlName($.Status,W.None);t.add(de,new U(G.PicklistStatusControl));let He=e.getControlName($.OwnerType,W.None);t.add(He,new U(G.LookupControl));let bn=e.getControlName($.PartyListType,W.None);t.add(bn,new U(G.PartyListControl));let CU=e.getControlName($.LookupType,W.Regarding);t.add(CU,new U(G.RegardingControl));let EU=e.getControlName($.MultiSelectOptionSet,W.None);return t.add(EU,new U(G.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(!R.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=R.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===G.CustomControl}static initializeUnboundControls(){let t=new nr;return t.add(G.ACIControl,ee.ACIControl),t.add(G.IframeControl,ee.IframeControl),t.add(G.SearchWidgetControl,ee.SearchWidgetControl),t.add(G.MapsControl,ee.MapsControl),t.add(G.QuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.GridControl,ee.SubGridControl),t.add(G.WebResourceImageControl,ee.WebResourceImageControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.TimerControl,ee.TimerControl),t.add(G.TimeLineControl,ee.NotesControl),t.add(G.TimeLineControlUC,ee.NotesControl),t.add(G.SocialInsightControl,ee.SocialInsightControl),t.add(oa.RelationshipAssistant,ee.CustomControl),t}static initializeReferencePanelControls(){let t=new nr;return t.add(G.IframeControl,ee.IframeControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.WebResourceImageControl,ee.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new ts;return t.add(ys.IFRAME,!0),t.add(ys.SPACER,!0),t.add(ys.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!R.IsNullOrUndefined(t)&&!R.IsNullOrUndefined(t.Name)&&t.Name.indexOf(Ue.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=q.EmptyString;if(R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.guidString)?q.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===G.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!R.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case ee.IframeControl:case ee.ACIControl:case ee.SocialInsightControl:return 6;case ee.SubGridControl:case ee.CustomControl:return 4;case ee.WebResourceImageControl:return 15;case ee.WebResourceHtmlControl:return 15;case ee.MapsControl:return 8;case ee.SearchWidgetControl:return 10;case ee.NotesControl:case ee.TimeLineControl:return 15;case ee.TimerControl:return 2;default:}}static isLookUpControl(t){return!R.IsNullOrUndefined(t)&&t.ClassId.guidString===G.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!R.IsNullOrUndefined(t)&&(t.guidString===oa.RelationshipAssistant||t.guidString===oa.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!R.IsNullOrUndefined(t)&&t.guidString===oa.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(R.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!R.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var af,Q_=k(()=>{"use strict";af=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 aa,vs,X_,Z_,go,eT,tT,y0=k(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(aa||(aa={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(vs||(vs={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(X_||(X_={}));(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"})(Z_||(Z_={}));(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"})(go||(go={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(eT||(eT={}));(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"})(tT||(tT={}))});var ws,rT=k(()=>{"use strict";cu();ws=n0({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 nT(e){return{...e,extractConfig:t=>n6(t,Object.keys(e.fallback))}}function n6(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var b0=k(()=>{"use strict";});var v0=v((qce,oT)=>{var pu=new Proxy(function(){return pu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:pu},apply:function(){return pu},construct:function(){return{}}}),iT=function(){return pu};Object.setPrototypeOf(iT,pu);oT.exports=iT});var lT=v((Vce,sT)=>{var mu=new Proxy(function(){return mu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:mu},apply:function(){return mu},construct:function(){return{}}}),aT=function(){return mu};Object.setPrototypeOf(aT,mu);sT.exports=aT});var w0=v((Gce,cT)=>{var hu=new Proxy(function(){return hu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:hu},apply:function(){return hu},construct:function(){return{}}}),uT=function(){return hu};Object.setPrototypeOf(uT,hu);cT.exports=uT});var fT=v((Wce,dT)=>{function i6(){this.__data__=[],this.size=0}dT.exports=i6});var Cs=v((zce,pT)=>{function o6(e,t){return e===t||e!==e&&t!==t}pT.exports=o6});var gu=v((jce,mT)=>{var a6=Cs();function s6(e,t){for(var r=e.length;r--;)if(a6(e[r][0],t))return r;return-1}mT.exports=s6});var gT=v((Hce,hT)=>{var l6=gu(),u6=Array.prototype,c6=u6.splice;function d6(e){var t=this.__data__,r=l6(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():c6.call(t,r,1),--this.size,!0}hT.exports=d6});var bT=v((Kce,yT)=>{var f6=gu();function p6(e){var t=this.__data__,r=f6(t,e);return r<0?void 0:t[r][1]}yT.exports=p6});var wT=v((Jce,vT)=>{var m6=gu();function h6(e){return m6(this.__data__,e)>-1}vT.exports=h6});var ET=v((Yce,CT)=>{var g6=gu();function y6(e,t){var r=this.__data__,n=g6(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}CT.exports=y6});var yu=v((Qce,AT)=>{var b6=fT(),v6=gT(),w6=bT(),C6=wT(),E6=ET();function Es(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])}}Es.prototype.clear=b6;Es.prototype.delete=v6;Es.prototype.get=w6;Es.prototype.has=C6;Es.prototype.set=E6;AT.exports=Es});var NT=v((Xce,ST)=>{var A6=yu();function S6(){this.__data__=new A6,this.size=0}ST.exports=S6});var TT=v((Zce,_T)=>{function N6(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}_T.exports=N6});var IT=v((ede,DT)=>{function _6(e){return this.__data__.get(e)}DT.exports=_6});var PT=v((tde,OT)=>{function T6(e){return this.__data__.has(e)}OT.exports=T6});var C0=v((rde,RT)=>{var D6=typeof global=="object"&&global&&global.Object===Object&&global;RT.exports=D6});var Dn=v((nde,LT)=>{var I6=C0(),O6=typeof self=="object"&&self&&self.Object===Object&&self,P6=I6||O6||Function("return this")();LT.exports=P6});var bu=v((ide,kT)=>{var R6=Dn(),L6=R6.Symbol;kT.exports=L6});var MT=v((ode,FT)=>{var $T=bu(),xT=Object.prototype,k6=xT.hasOwnProperty,$6=xT.toString,vu=$T?$T.toStringTag:void 0;function x6(e){var t=k6.call(e,vu),r=e[vu];try{e[vu]=void 0;var n=!0}catch{}var i=$6.call(e);return n&&(t?e[vu]=r:delete e[vu]),i}FT.exports=x6});var BT=v((ade,UT)=>{var F6=Object.prototype,M6=F6.toString;function U6(e){return M6.call(e)}UT.exports=U6});var sa=v((sde,GT)=>{var qT=bu(),B6=MT(),q6=BT(),V6="[object Null]",G6="[object Undefined]",VT=qT?qT.toStringTag:void 0;function W6(e){return e==null?e===void 0?G6:V6:VT&&VT in Object(e)?B6(e):q6(e)}GT.exports=W6});var ki=v((lde,WT)=>{function z6(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}WT.exports=z6});var sf=v((ude,zT)=>{var j6=sa(),H6=ki(),K6="[object AsyncFunction]",J6="[object Function]",Y6="[object GeneratorFunction]",Q6="[object Proxy]";function X6(e){if(!H6(e))return!1;var t=j6(e);return t==J6||t==Y6||t==K6||t==Q6}zT.exports=X6});var HT=v((cde,jT)=>{var Z6=Dn(),ez=Z6["__core-js_shared__"];jT.exports=ez});var YT=v((dde,JT)=>{var E0=HT(),KT=(function(){var e=/[^.]+$/.exec(E0&&E0.keys&&E0.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function tz(e){return!!KT&&KT in e}JT.exports=tz});var A0=v((fde,QT)=>{var rz=Function.prototype,nz=rz.toString;function iz(e){if(e!=null){try{return nz.call(e)}catch{}try{return e+""}catch{}}return""}QT.exports=iz});var ZT=v((pde,XT)=>{var oz=sf(),az=YT(),sz=ki(),lz=A0(),uz=/[\\^$.*+?()[\]{}|]/g,cz=/^\[object .+?Constructor\]$/,dz=Function.prototype,fz=Object.prototype,pz=dz.toString,mz=fz.hasOwnProperty,hz=RegExp("^"+pz.call(mz).replace(uz,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function gz(e){if(!sz(e)||az(e))return!1;var t=oz(e)?hz:cz;return t.test(lz(e))}XT.exports=gz});var tD=v((mde,eD)=>{function yz(e,t){return e?.[t]}eD.exports=yz});var yo=v((hde,rD)=>{var bz=ZT(),vz=tD();function wz(e,t){var r=vz(e,t);return bz(r)?r:void 0}rD.exports=wz});var lf=v((gde,nD)=>{var Cz=yo(),Ez=Dn(),Az=Cz(Ez,"Map");nD.exports=Az});var wu=v((yde,iD)=>{var Sz=yo(),Nz=Sz(Object,"create");iD.exports=Nz});var sD=v((bde,aD)=>{var oD=wu();function _z(){this.__data__=oD?oD(null):{},this.size=0}aD.exports=_z});var uD=v((vde,lD)=>{function Tz(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}lD.exports=Tz});var dD=v((wde,cD)=>{var Dz=wu(),Iz="__lodash_hash_undefined__",Oz=Object.prototype,Pz=Oz.hasOwnProperty;function Rz(e){var t=this.__data__;if(Dz){var r=t[e];return r===Iz?void 0:r}return Pz.call(t,e)?t[e]:void 0}cD.exports=Rz});var pD=v((Cde,fD)=>{var Lz=wu(),kz=Object.prototype,$z=kz.hasOwnProperty;function xz(e){var t=this.__data__;return Lz?t[e]!==void 0:$z.call(t,e)}fD.exports=xz});var hD=v((Ede,mD)=>{var Fz=wu(),Mz="__lodash_hash_undefined__";function Uz(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Fz&&t===void 0?Mz:t,this}mD.exports=Uz});var yD=v((Ade,gD)=>{var Bz=sD(),qz=uD(),Vz=dD(),Gz=pD(),Wz=hD();function As(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])}}As.prototype.clear=Bz;As.prototype.delete=qz;As.prototype.get=Vz;As.prototype.has=Gz;As.prototype.set=Wz;gD.exports=As});var wD=v((Sde,vD)=>{var bD=yD(),zz=yu(),jz=lf();function Hz(){this.size=0,this.__data__={hash:new bD,map:new(jz||zz),string:new bD}}vD.exports=Hz});var ED=v((Nde,CD)=>{function Kz(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}CD.exports=Kz});var Cu=v((_de,AD)=>{var Jz=ED();function Yz(e,t){var r=e.__data__;return Jz(t)?r[typeof t=="string"?"string":"hash"]:r.map}AD.exports=Yz});var ND=v((Tde,SD)=>{var Qz=Cu();function Xz(e){var t=Qz(this,e).delete(e);return this.size-=t?1:0,t}SD.exports=Xz});var TD=v((Dde,_D)=>{var Zz=Cu();function ej(e){return Zz(this,e).get(e)}_D.exports=ej});var ID=v((Ide,DD)=>{var tj=Cu();function rj(e){return tj(this,e).has(e)}DD.exports=rj});var PD=v((Ode,OD)=>{var nj=Cu();function ij(e,t){var r=nj(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}OD.exports=ij});var uf=v((Pde,RD)=>{var oj=wD(),aj=ND(),sj=TD(),lj=ID(),uj=PD();function Ss(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])}}Ss.prototype.clear=oj;Ss.prototype.delete=aj;Ss.prototype.get=sj;Ss.prototype.has=lj;Ss.prototype.set=uj;RD.exports=Ss});var kD=v((Rde,LD)=>{var cj=yu(),dj=lf(),fj=uf(),pj=200;function mj(e,t){var r=this.__data__;if(r instanceof cj){var n=r.__data__;if(!dj||n.length<pj-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new fj(n)}return r.set(e,t),this.size=r.size,this}LD.exports=mj});var S0=v((Lde,$D)=>{var hj=yu(),gj=NT(),yj=TT(),bj=IT(),vj=PT(),wj=kD();function Ns(e){var t=this.__data__=new hj(e);this.size=t.size}Ns.prototype.clear=gj;Ns.prototype.delete=yj;Ns.prototype.get=bj;Ns.prototype.has=vj;Ns.prototype.set=wj;$D.exports=Ns});var FD=v((kde,xD)=>{var Cj="__lodash_hash_undefined__";function Ej(e){return this.__data__.set(e,Cj),this}xD.exports=Ej});var UD=v(($de,MD)=>{function Aj(e){return this.__data__.has(e)}MD.exports=Aj});var qD=v((xde,BD)=>{var Sj=uf(),Nj=FD(),_j=UD();function cf(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Sj;++t<r;)this.add(e[t])}cf.prototype.add=cf.prototype.push=Nj;cf.prototype.has=_j;BD.exports=cf});var GD=v((Fde,VD)=>{function Tj(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}VD.exports=Tj});var zD=v((Mde,WD)=>{function Dj(e,t){return e.has(t)}WD.exports=Dj});var N0=v((Ude,jD)=>{var Ij=qD(),Oj=GD(),Pj=zD(),Rj=1,Lj=2;function kj(e,t,r,n,i,o){var a=r&Rj,s=e.length,l=t.length;if(s!=l&&!(a&&l>s))return!1;var u=o.get(e),c=o.get(t);if(u&&c)return u==t&&c==e;var d=-1,f=!0,m=r&Lj?new Ij:void 0;for(o.set(e,t),o.set(t,e);++d<s;){var p=e[d],h=t[d];if(n)var g=a?n(h,p,d,t,e,o):n(p,h,d,e,t,o);if(g!==void 0){if(g)continue;f=!1;break}if(m){if(!Oj(t,function(b,w){if(!Pj(m,w)&&(p===b||i(p,b,r,n,o)))return m.push(w)})){f=!1;break}}else if(!(p===h||i(p,h,r,n,o))){f=!1;break}}return o.delete(e),o.delete(t),f}jD.exports=kj});var _0=v((Bde,HD)=>{var $j=Dn(),xj=$j.Uint8Array;HD.exports=xj});var JD=v((qde,KD)=>{function Fj(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}KD.exports=Fj});var QD=v((Vde,YD)=>{function Mj(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}YD.exports=Mj});var rI=v((Gde,tI)=>{var XD=bu(),ZD=_0(),Uj=Cs(),Bj=N0(),qj=JD(),Vj=QD(),Gj=1,Wj=2,zj="[object Boolean]",jj="[object Date]",Hj="[object Error]",Kj="[object Map]",Jj="[object Number]",Yj="[object RegExp]",Qj="[object Set]",Xj="[object String]",Zj="[object Symbol]",e7="[object ArrayBuffer]",t7="[object DataView]",eI=XD?XD.prototype:void 0,T0=eI?eI.valueOf:void 0;function r7(e,t,r,n,i,o,a){switch(r){case t7:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case e7:return!(e.byteLength!=t.byteLength||!o(new ZD(e),new ZD(t)));case zj:case jj:case Jj:return Uj(+e,+t);case Hj:return e.name==t.name&&e.message==t.message;case Yj:case Xj:return e==t+"";case Kj:var s=qj;case Qj:var l=n&Gj;if(s||(s=Vj),e.size!=t.size&&!l)return!1;var u=a.get(e);if(u)return u==t;n|=Wj,a.set(e,t);var c=Bj(s(e),s(t),n,i,o,a);return a.delete(e),c;case Zj:if(T0)return T0.call(e)==T0.call(t)}return!1}tI.exports=r7});var iI=v((Wde,nI)=>{function n7(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}nI.exports=n7});var bo=v((zde,oI)=>{var i7=Array.isArray;oI.exports=i7});var sI=v((jde,aI)=>{var o7=iI(),a7=bo();function s7(e,t,r){var n=t(e);return a7(e)?n:o7(n,r(e))}aI.exports=s7});var uI=v((Hde,lI)=>{function l7(e,t){for(var r=-1,n=e==null?0:e.length,i=0,o=[];++r<n;){var a=e[r];t(a,r,e)&&(o[i++]=a)}return o}lI.exports=l7});var dI=v((Kde,cI)=>{function u7(){return[]}cI.exports=u7});var mI=v((Jde,pI)=>{var c7=uI(),d7=dI(),f7=Object.prototype,p7=f7.propertyIsEnumerable,fI=Object.getOwnPropertySymbols,m7=fI?function(e){return e==null?[]:(e=Object(e),c7(fI(e),function(t){return p7.call(e,t)}))}:d7;pI.exports=m7});var gI=v((Yde,hI)=>{function h7(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}hI.exports=h7});var vo=v((Qde,yI)=>{function g7(e){return e!=null&&typeof e=="object"}yI.exports=g7});var vI=v((Xde,bI)=>{var y7=sa(),b7=vo(),v7="[object Arguments]";function w7(e){return b7(e)&&y7(e)==v7}bI.exports=w7});var D0=v((Zde,EI)=>{var wI=vI(),C7=vo(),CI=Object.prototype,E7=CI.hasOwnProperty,A7=CI.propertyIsEnumerable,S7=wI((function(){return arguments})())?wI:function(e){return C7(e)&&E7.call(e,"callee")&&!A7.call(e,"callee")};EI.exports=S7});var SI=v((efe,AI)=>{function N7(){return!1}AI.exports=N7});var df=v((Eu,_s)=>{var _7=Dn(),T7=SI(),TI=typeof Eu=="object"&&Eu&&!Eu.nodeType&&Eu,NI=TI&&typeof _s=="object"&&_s&&!_s.nodeType&&_s,D7=NI&&NI.exports===TI,_I=D7?_7.Buffer:void 0,I7=_I?_I.isBuffer:void 0,O7=I7||T7;_s.exports=O7});var ff=v((tfe,DI)=>{var P7=9007199254740991,R7=/^(?:0|[1-9]\d*)$/;function L7(e,t){var r=typeof e;return t=t??P7,!!t&&(r=="number"||r!="symbol"&&R7.test(e))&&e>-1&&e%1==0&&e<t}DI.exports=L7});var I0=v((rfe,II)=>{var k7=9007199254740991;function $7(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=k7}II.exports=$7});var PI=v((nfe,OI)=>{var x7=sa(),F7=I0(),M7=vo(),U7="[object Arguments]",B7="[object Array]",q7="[object Boolean]",V7="[object Date]",G7="[object Error]",W7="[object Function]",z7="[object Map]",j7="[object Number]",H7="[object Object]",K7="[object RegExp]",J7="[object Set]",Y7="[object String]",Q7="[object WeakMap]",X7="[object ArrayBuffer]",Z7="[object DataView]",eH="[object Float32Array]",tH="[object Float64Array]",rH="[object Int8Array]",nH="[object Int16Array]",iH="[object Int32Array]",oH="[object Uint8Array]",aH="[object Uint8ClampedArray]",sH="[object Uint16Array]",lH="[object Uint32Array]",$e={};$e[eH]=$e[tH]=$e[rH]=$e[nH]=$e[iH]=$e[oH]=$e[aH]=$e[sH]=$e[lH]=!0;$e[U7]=$e[B7]=$e[X7]=$e[q7]=$e[Z7]=$e[V7]=$e[G7]=$e[W7]=$e[z7]=$e[j7]=$e[H7]=$e[K7]=$e[J7]=$e[Y7]=$e[Q7]=!1;function uH(e){return M7(e)&&F7(e.length)&&!!$e[x7(e)]}OI.exports=uH});var LI=v((ife,RI)=>{function cH(e){return function(t){return e(t)}}RI.exports=cH});var $I=v((Au,Ts)=>{var dH=C0(),kI=typeof Au=="object"&&Au&&!Au.nodeType&&Au,Su=kI&&typeof Ts=="object"&&Ts&&!Ts.nodeType&&Ts,fH=Su&&Su.exports===kI,O0=fH&&dH.process,pH=(function(){try{var e=Su&&Su.require&&Su.require("util").types;return e||O0&&O0.binding&&O0.binding("util")}catch{}})();Ts.exports=pH});var pf=v((ofe,MI)=>{var mH=PI(),hH=LI(),xI=$I(),FI=xI&&xI.isTypedArray,gH=FI?hH(FI):mH;MI.exports=gH});var P0=v((afe,UI)=>{var yH=gI(),bH=D0(),vH=bo(),wH=df(),CH=ff(),EH=pf(),AH=Object.prototype,SH=AH.hasOwnProperty;function NH(e,t){var r=vH(e),n=!r&&bH(e),i=!r&&!n&&wH(e),o=!r&&!n&&!i&&EH(e),a=r||n||i||o,s=a?yH(e.length,String):[],l=s.length;for(var u in e)(t||SH.call(e,u))&&!(a&&(u=="length"||i&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||CH(u,l)))&&s.push(u);return s}UI.exports=NH});var mf=v((sfe,BI)=>{var _H=Object.prototype;function TH(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||_H;return e===r}BI.exports=TH});var R0=v((lfe,qI)=>{function DH(e,t){return function(r){return e(t(r))}}qI.exports=DH});var GI=v((ufe,VI)=>{var IH=R0(),OH=IH(Object.keys,Object);VI.exports=OH});var zI=v((cfe,WI)=>{var PH=mf(),RH=GI(),LH=Object.prototype,kH=LH.hasOwnProperty;function $H(e){if(!PH(e))return RH(e);var t=[];for(var r in Object(e))kH.call(e,r)&&r!="constructor"&&t.push(r);return t}WI.exports=$H});var Nu=v((dfe,jI)=>{var xH=sf(),FH=I0();function MH(e){return e!=null&&FH(e.length)&&!xH(e)}jI.exports=MH});var KI=v((ffe,HI)=>{var UH=P0(),BH=zI(),qH=Nu();function VH(e){return qH(e)?UH(e):BH(e)}HI.exports=VH});var YI=v((pfe,JI)=>{var GH=sI(),WH=mI(),zH=KI();function jH(e){return GH(e,zH,WH)}JI.exports=jH});var ZI=v((mfe,XI)=>{var QI=YI(),HH=1,KH=Object.prototype,JH=KH.hasOwnProperty;function YH(e,t,r,n,i,o){var a=r&HH,s=QI(e),l=s.length,u=QI(t),c=u.length;if(l!=c&&!a)return!1;for(var d=l;d--;){var f=s[d];if(!(a?f in t:JH.call(t,f)))return!1}var m=o.get(e),p=o.get(t);if(m&&p)return m==t&&p==e;var h=!0;o.set(e,t),o.set(t,e);for(var g=a;++d<l;){f=s[d];var b=e[f],w=t[f];if(n)var E=a?n(w,b,f,t,e,o):n(b,w,f,e,t,o);if(!(E===void 0?b===w||i(b,w,r,n,o):E)){h=!1;break}g||(g=f=="constructor")}if(h&&!g){var S=e.constructor,P=t.constructor;S!=P&&"constructor"in e&&"constructor"in t&&!(typeof S=="function"&&S instanceof S&&typeof P=="function"&&P instanceof P)&&(h=!1)}return o.delete(e),o.delete(t),h}XI.exports=YH});var tO=v((hfe,eO)=>{var QH=yo(),XH=Dn(),ZH=QH(XH,"DataView");eO.exports=ZH});var nO=v((gfe,rO)=>{var eK=yo(),tK=Dn(),rK=eK(tK,"Promise");rO.exports=rK});var oO=v((yfe,iO)=>{var nK=yo(),iK=Dn(),oK=nK(iK,"Set");iO.exports=oK});var sO=v((bfe,aO)=>{var aK=yo(),sK=Dn(),lK=aK(sK,"WeakMap");aO.exports=lK});var hO=v((vfe,mO)=>{var L0=tO(),k0=lf(),$0=nO(),x0=oO(),F0=sO(),pO=sa(),Ds=A0(),lO="[object Map]",uK="[object Object]",uO="[object Promise]",cO="[object Set]",dO="[object WeakMap]",fO="[object DataView]",cK=Ds(L0),dK=Ds(k0),fK=Ds($0),pK=Ds(x0),mK=Ds(F0),la=pO;(L0&&la(new L0(new ArrayBuffer(1)))!=fO||k0&&la(new k0)!=lO||$0&&la($0.resolve())!=uO||x0&&la(new x0)!=cO||F0&&la(new F0)!=dO)&&(la=function(e){var t=pO(e),r=t==uK?e.constructor:void 0,n=r?Ds(r):"";if(n)switch(n){case cK:return fO;case dK:return lO;case fK:return uO;case pK:return cO;case mK:return dO}return t});mO.exports=la});var AO=v((wfe,EO)=>{var M0=S0(),hK=N0(),gK=rI(),yK=ZI(),gO=hO(),yO=bo(),bO=df(),bK=pf(),vK=1,vO="[object Arguments]",wO="[object Array]",hf="[object Object]",wK=Object.prototype,CO=wK.hasOwnProperty;function CK(e,t,r,n,i,o){var a=yO(e),s=yO(t),l=a?wO:gO(e),u=s?wO:gO(t);l=l==vO?hf:l,u=u==vO?hf:u;var c=l==hf,d=u==hf,f=l==u;if(f&&bO(e)){if(!bO(t))return!1;a=!0,c=!1}if(f&&!c)return o||(o=new M0),a||bK(e)?hK(e,t,r,n,i,o):gK(e,t,l,r,n,i,o);if(!(r&vK)){var m=c&&CO.call(e,"__wrapped__"),p=d&&CO.call(t,"__wrapped__");if(m||p){var h=m?e.value():e,g=p?t.value():t;return o||(o=new M0),i(h,g,r,n,o)}}return f?(o||(o=new M0),yK(e,t,r,n,i,o)):!1}EO.exports=CK});var TO=v((Cfe,_O)=>{var EK=AO(),SO=vo();function NO(e,t,r,n,i){return e===t?!0:e==null||t==null||!SO(e)&&!SO(t)?e!==e&&t!==t:EK(e,t,r,n,NO,i)}_O.exports=NO});var IO=v((Efe,DO)=>{var AK=TO();function SK(e,t){return AK(e,t)}DO.exports=SK});var U0=v((Afe,OO)=>{var NK=yo(),_K=(function(){try{var e=NK(Object,"defineProperty");return e({},"",{}),e}catch{}})();OO.exports=_K});var gf=v((Sfe,RO)=>{var PO=U0();function TK(e,t,r){t=="__proto__"&&PO?PO(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}RO.exports=TK});var B0=v((Nfe,LO)=>{var DK=gf(),IK=Cs();function OK(e,t,r){(r!==void 0&&!IK(e[t],r)||r===void 0&&!(t in e))&&DK(e,t,r)}LO.exports=OK});var $O=v((_fe,kO)=>{function PK(e){return function(t,r,n){for(var i=-1,o=Object(t),a=n(t),s=a.length;s--;){var l=a[e?s:++i];if(r(o[l],l,o)===!1)break}return t}}kO.exports=PK});var FO=v((Tfe,xO)=>{var RK=$O(),LK=RK();xO.exports=LK});var VO=v((_u,Is)=>{var kK=Dn(),qO=typeof _u=="object"&&_u&&!_u.nodeType&&_u,MO=qO&&typeof Is=="object"&&Is&&!Is.nodeType&&Is,$K=MO&&MO.exports===qO,UO=$K?kK.Buffer:void 0,BO=UO?UO.allocUnsafe:void 0;function xK(e,t){if(t)return e.slice();var r=e.length,n=BO?BO(r):new e.constructor(r);return e.copy(n),n}Is.exports=xK});var zO=v((Dfe,WO)=>{var GO=_0();function FK(e){var t=new e.constructor(e.byteLength);return new GO(t).set(new GO(e)),t}WO.exports=FK});var HO=v((Ife,jO)=>{var MK=zO();function UK(e,t){var r=t?MK(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}jO.exports=UK});var JO=v((Ofe,KO)=>{function BK(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}KO.exports=BK});var XO=v((Pfe,QO)=>{var qK=ki(),YO=Object.create,VK=(function(){function e(){}return function(t){if(!qK(t))return{};if(YO)return YO(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();QO.exports=VK});var q0=v((Rfe,ZO)=>{var GK=R0(),WK=GK(Object.getPrototypeOf,Object);ZO.exports=WK});var tP=v((Lfe,eP)=>{var zK=XO(),jK=q0(),HK=mf();function KK(e){return typeof e.constructor=="function"&&!HK(e)?zK(jK(e)):{}}eP.exports=KK});var nP=v((kfe,rP)=>{var JK=Nu(),YK=vo();function QK(e){return YK(e)&&JK(e)}rP.exports=QK});var aP=v(($fe,oP)=>{var XK=sa(),ZK=q0(),eJ=vo(),tJ="[object Object]",rJ=Function.prototype,nJ=Object.prototype,iP=rJ.toString,iJ=nJ.hasOwnProperty,oJ=iP.call(Object);function aJ(e){if(!eJ(e)||XK(e)!=tJ)return!1;var t=ZK(e);if(t===null)return!0;var r=iJ.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&iP.call(r)==oJ}oP.exports=aJ});var V0=v((xfe,sP)=>{function sJ(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}sP.exports=sJ});var G0=v((Ffe,lP)=>{var lJ=gf(),uJ=Cs(),cJ=Object.prototype,dJ=cJ.hasOwnProperty;function fJ(e,t,r){var n=e[t];(!(dJ.call(e,t)&&uJ(n,r))||r===void 0&&!(t in e))&&lJ(e,t,r)}lP.exports=fJ});var cP=v((Mfe,uP)=>{var pJ=G0(),mJ=gf();function hJ(e,t,r,n){var i=!r;r||(r={});for(var o=-1,a=t.length;++o<a;){var s=t[o],l=n?n(r[s],e[s],s,r,e):void 0;l===void 0&&(l=e[s]),i?mJ(r,s,l):pJ(r,s,l)}return r}uP.exports=hJ});var fP=v((Ufe,dP)=>{function gJ(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}dP.exports=gJ});var mP=v((Bfe,pP)=>{var yJ=ki(),bJ=mf(),vJ=fP(),wJ=Object.prototype,CJ=wJ.hasOwnProperty;function EJ(e){if(!yJ(e))return vJ(e);var t=bJ(e),r=[];for(var n in e)n=="constructor"&&(t||!CJ.call(e,n))||r.push(n);return r}pP.exports=EJ});var W0=v((qfe,hP)=>{var AJ=P0(),SJ=mP(),NJ=Nu();function _J(e){return NJ(e)?AJ(e,!0):SJ(e)}hP.exports=_J});var yP=v((Vfe,gP)=>{var TJ=cP(),DJ=W0();function IJ(e){return TJ(e,DJ(e))}gP.exports=IJ});var AP=v((Gfe,EP)=>{var bP=B0(),OJ=VO(),PJ=HO(),RJ=JO(),LJ=tP(),vP=D0(),wP=bo(),kJ=nP(),$J=df(),xJ=sf(),FJ=ki(),MJ=aP(),UJ=pf(),CP=V0(),BJ=yP();function qJ(e,t,r,n,i,o,a){var s=CP(e,r),l=CP(t,r),u=a.get(l);if(u){bP(e,r,u);return}var c=o?o(s,l,r+"",e,t,a):void 0,d=c===void 0;if(d){var f=wP(l),m=!f&&$J(l),p=!f&&!m&&UJ(l);c=l,f||m||p?wP(s)?c=s:kJ(s)?c=RJ(s):m?(d=!1,c=OJ(l,!0)):p?(d=!1,c=PJ(l,!0)):c=[]:MJ(l)||vP(l)?(c=s,vP(s)?c=BJ(s):(!FJ(s)||xJ(s))&&(c=LJ(l))):d=!1}d&&(a.set(l,c),i(c,l,n,o,a),a.delete(l)),bP(e,r,c)}EP.exports=qJ});var z0=v((Wfe,NP)=>{var VJ=S0(),GJ=B0(),WJ=FO(),zJ=AP(),jJ=ki(),HJ=W0(),KJ=V0();function SP(e,t,r,n,i){e!==t&&WJ(t,function(o,a){if(i||(i=new VJ),jJ(o))zJ(e,t,a,r,SP,n,i);else{var s=n?n(KJ(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),GJ(e,a,s)}},HJ)}NP.exports=SP});var j0=v((zfe,_P)=>{function JJ(e){return e}_P.exports=JJ});var DP=v((jfe,TP)=>{function YJ(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)}TP.exports=YJ});var PP=v((Hfe,OP)=>{var QJ=DP(),IP=Math.max;function XJ(e,t,r){return t=IP(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,o=IP(n.length-t,0),a=Array(o);++i<o;)a[i]=n[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=n[i];return s[t]=r(a),QJ(e,this,s)}}OP.exports=XJ});var LP=v((Kfe,RP)=>{function ZJ(e){return function(){return e}}RP.exports=ZJ});var xP=v((Jfe,$P)=>{var eY=LP(),kP=U0(),tY=j0(),rY=kP?function(e,t){return kP(e,"toString",{configurable:!0,enumerable:!1,value:eY(t),writable:!0})}:tY;$P.exports=rY});var MP=v((Yfe,FP)=>{var nY=800,iY=16,oY=Date.now;function aY(e){var t=0,r=0;return function(){var n=oY(),i=iY-(n-r);if(r=n,i>0){if(++t>=nY)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}FP.exports=aY});var BP=v((Qfe,UP)=>{var sY=xP(),lY=MP(),uY=lY(sY);UP.exports=uY});var VP=v((Xfe,qP)=>{var cY=j0(),dY=PP(),fY=BP();function pY(e,t){return fY(dY(e,t,cY),e+"")}qP.exports=pY});var WP=v((Zfe,GP)=>{var mY=Cs(),hY=Nu(),gY=ff(),yY=ki();function bY(e,t,r){if(!yY(r))return!1;var n=typeof t;return(n=="number"?hY(r)&&gY(t,r.length):n=="string"&&t in r)?mY(r[t],e):!1}GP.exports=bY});var H0=v((epe,zP)=>{var vY=VP(),wY=WP();function CY(e){return vY(function(t,r){var n=-1,i=r.length,o=i>1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(o=e.length>3&&typeof o=="function"?(i--,o):void 0,a&&wY(r[0],r[1],a)&&(o=i<3?void 0:o,i=1),t=Object(t);++n<i;){var s=r[n];s&&e(t,s,n,o)}return t})}zP.exports=CY});var HP=v((tpe,jP)=>{var EY=z0(),AY=H0(),SY=AY(function(e,t,r,n){EY(e,t,r,n)});jP.exports=SY});var sn,Tu=k(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(sn||(sn={}))});function JP(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${KP.EcsConfigType[i]}_${r}`;return{getData:i=>{let o=t.getItem(n(i));return Promise.resolve(o?JSON.parse(o):void 0)},putData:(i,o)=>(t.setItem(n(i),JSON.stringify(o)),Promise.resolve())}}var KP,NY,YP=k(()=>{"use strict";KP=Ee(w0()),NY=Ee(v0());});var K0,QP=k(()=>{"use strict";Xd();K0=uu({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 ZP,eR,tR,rR,J0,_Y,yf,XP,Y0=k(()=>{"use strict";ZP=Ee(v0()),eR=Ee(lT()),tR=Ee(w0()),rR=Ee(IO()),J0=Ee(HP());Tu();YP();QP();_Y=60*1e3,yf=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=sn.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"?K0.prodEcsEndpoint:K0.integrationEcsEndpoint}client=new eR.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=ZP.StorageHelper.transientWithGlobalFallback,updateIntervalInMinutes:i,overrideEcsInitParams:o})=>{this.client.telemetryEventAdded.subscribe(this.logger.logEvent),this.client.configUpdated.subscribe(this.handleConfigUpdated);let a=(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:[tR.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:JP(this.clientName,n,this.endpointType),...o}),this.client.requestUpdate(),this._status===sn.NotLoaded&&(this._status=sn.Initialized)}catch(s){this._status=sn.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*_Y)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,J0.default)({},t.fallback,n,t.override,XP)};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 o=this.getConfig(t);(0,rR.default)(o,n)||(n={...o},r(o))});return{unsubscribe:()=>i.unsubscribe()}};waitUntilLoaded=async t=>{if(t!==void 0){let r,n=new Promise((i,o)=>{r=window.setTimeout(()=>{o(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,J0.default)({},this.client.getConfig()?.config,this.clientConfigOverride,XP);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=sn.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})}},XP=(e,t)=>{if(Array.isArray(t))return t}});var iR=v((cpe,nR)=>{"use strict";var TY=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};nR.exports=TY});var Q0=v((dpe,aR)=>{var Du=new Proxy(function(){return Du},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Du},apply:function(){return Du},construct:function(){return{}}}),oR=function(){return Du};Object.setPrototypeOf(oR,Du);aR.exports=oR});var uR=v((fpe,lR)=>{var Iu=new Proxy(function(){return Iu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Iu},apply:function(){return Iu},construct:function(){return{}}}),sR=function(){return Iu};Object.setPrototypeOf(sR,Iu);lR.exports=sR});var gR=v((ppe,hR)=>{"use strict";var X0=uR(),DY={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},IY={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},OY={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},pR={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},Z0={};Z0[X0.ForwardRef]=OY;Z0[X0.Memo]=pR;function cR(e){return X0.isMemo(e)?pR:Z0[e.$$typeof]||DY}var PY=Object.defineProperty,RY=Object.getOwnPropertyNames,dR=Object.getOwnPropertySymbols,LY=Object.getOwnPropertyDescriptor,kY=Object.getPrototypeOf,fR=Object.prototype;function mR(e,t,r){if(typeof t!="string"){if(fR){var n=kY(t);n&&n!==fR&&mR(e,n,r)}var i=RY(t);dR&&(i=i.concat(dR(t)));for(var o=cR(e),a=cR(t),s=0;s<i.length;++s){var l=i[s];if(!IY[l]&&!(r&&r[l])&&!(a&&a[l])&&!(o&&o[l])){var u=LY(t,l);try{PY(e,l,u)}catch{}}}}return e}hR.exports=mR});function bR(e,t,r){let[n,i]=(0,Os.useState)(e.getConfig(t));return(0,Os.useEffect)(()=>{if(!r?.subscribe&&e.status===sn.ConfigsLoaded)return;let o=e.subscribe(t,a=>{i(a),r?.subscribe||o.unsubscribe()});return o?.unsubscribe},[]),n}function vR(e){return function(t,r){return bR(e,t,r)}}function wR(e,t,r,n){let i=o=>{let a=bR(e,t,n),s={...o,...a};return Os.default.createElement(r,{...s})};return(0,yR.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function CR(e,t,r,n){return t.reduce((i,o)=>wR(e,o,i,n),r)}function ER(e){return function(t,r,n){return wR(e,t,r,n)}}var yR,Os,ey=k(()=>{"use strict";yR=Ee(gR()),Os=Ee(Q0());Tu();});var SR=v((gpe,AR)=>{var $Y=z0(),xY=H0(),FY=xY(function(e,t,r){$Y(e,t,r)});AR.exports=FY});var bf=v((ype,NR)=>{var MY=sa(),UY=vo(),BY="[object Symbol]";function qY(e){return typeof e=="symbol"||UY(e)&&MY(e)==BY}NR.exports=qY});var TR=v((bpe,_R)=>{var VY=bo(),GY=bf(),WY=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,zY=/^\w*$/;function jY(e,t){if(VY(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||GY(e)?!0:zY.test(e)||!WY.test(e)||t!=null&&e in Object(t)}_R.exports=jY});var OR=v((vpe,IR)=>{var DR=uf(),HY="Expected a function";function ty(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(HY);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],o=r.cache;if(o.has(i))return o.get(i);var a=e.apply(this,n);return r.cache=o.set(i,a)||o,a};return r.cache=new(ty.Cache||DR),r}ty.Cache=DR;IR.exports=ty});var RR=v((wpe,PR)=>{var KY=OR(),JY=500;function YY(e){var t=KY(e,function(n){return r.size===JY&&r.clear(),n}),r=t.cache;return t}PR.exports=YY});var kR=v((Cpe,LR)=>{var QY=RR(),XY=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ZY=/\\(\\)?/g,eQ=QY(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(XY,function(r,n,i,o){t.push(i?o.replace(ZY,"$1"):n||r)}),t});LR.exports=eQ});var xR=v((Epe,$R)=>{function tQ(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}$R.exports=tQ});var VR=v((Ape,qR)=>{var FR=bu(),rQ=xR(),nQ=bo(),iQ=bf(),oQ=1/0,MR=FR?FR.prototype:void 0,UR=MR?MR.toString:void 0;function BR(e){if(typeof e=="string")return e;if(nQ(e))return rQ(e,BR)+"";if(iQ(e))return UR?UR.call(e):"";var t=e+"";return t=="0"&&1/e==-oQ?"-0":t}qR.exports=BR});var WR=v((Spe,GR)=>{var aQ=VR();function sQ(e){return e==null?"":aQ(e)}GR.exports=sQ});var jR=v((Npe,zR)=>{var lQ=bo(),uQ=TR(),cQ=kR(),dQ=WR();function fQ(e,t){return lQ(e)?e:uQ(e,t)?[e]:cQ(dQ(e))}zR.exports=fQ});var KR=v((_pe,HR)=>{var pQ=bf(),mQ=1/0;function hQ(e){if(typeof e=="string"||pQ(e))return e;var t=e+"";return t=="0"&&1/e==-mQ?"-0":t}HR.exports=hQ});var QR=v((Tpe,YR)=>{var gQ=G0(),yQ=jR(),bQ=ff(),JR=ki(),vQ=KR();function wQ(e,t,r,n){if(!JR(e))return e;t=yQ(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var l=vQ(t[i]),u=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(i!=a){var c=s[l];u=n?n(c,l,s):void 0,u===void 0&&(u=JR(c)?c:bQ(t[i+1])?[]:{})}gQ(s,l,u),s=s[l]}return e}YR.exports=wQ});var ZR=v((Dpe,XR)=>{var CQ=QR();function EQ(e,t,r){return e==null?e:CQ(e,t,r)}XR.exports=EQ});function n2(e){let{query:t}=(0,r2.default)(window.location.href,!0);return SQ(e,t),e}function SQ(e,t){let r=AQ+e.clientName,n=Object.keys(t).filter(o=>o.startsWith(r));if(!n)return;let i={};n.forEach(o=>{let a=t[o];if(a)try{let s=JSON.parse(a),l=r+i2,u={};if(o===r)u=s;else if(o.startsWith(l)){let c=o.substring(l.length);(0,t2.default)(u,c,s)}(0,e2.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var e2,t2,r2,i2,AQ,o2=k(()=>{"use strict";e2=Ee(SR()),t2=Ee(ZR()),r2=Ee(s0());i2=".",AQ="ecs"+i2});function wf(e,t,r){let n=n2(new yf(e,t,r));function i(o){(0,vf.useEffect)(()=>{n.init(o)},[])}return{featuresClient:n,createFeature:_Q(n),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>CR(n,o,a,s)}}function _Q(e){let t=vR(e),r=ER(e);return function(i){let o=nT(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===sn.ConfigsLoaded,c0.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>r(o,a,s),feature:o}}}var NQ,vf,ry=k(()=>{"use strict";NQ=Ee(iR()),vf=Ee(Q0());b0();Y0();Tu();ey();o2();d0();});var a2=k(()=>{"use strict";b0();Y0();ry();Tu();ey();rf();f0();});function Cf(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,Ps.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,Ps.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,Ps.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var Ps,ny=k(()=>{"use strict";Ps=Ee(ra());});var Kpe,Jpe,Ype,s2=k(()=>{"use strict";a2();ny();({featuresClient:Kpe,createFeature:Jpe,useFeaturesClientInitParams:Ype}=wf("PowerApps-Shell-Test",Cf("shell-features")))});var c2=v((Xpe,u2)=>{var Ou=new Proxy(function(){return Ou},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ou},apply:function(){return Ou},construct:function(){return{}}}),l2=function(){return Ou};Object.setPrototypeOf(l2,Ou);u2.exports=l2});var TQ,DQ,d2=k(()=>{"use strict";au();TQ=Ee(c2()),DQ=Ee(ra());});var f2=k(()=>{"use strict";s2();ny();d2();});var sme,Rs,lme,p2=k(()=>{"use strict";f2();ry();({featuresClient:sme,createFeature:Rs,useFeaturesClientInitParams:lme}=wf("PowerApps-MakerPortal",Cf("powerapps-features")))});var m2,h2,fme,pme,mme,hme,iy=k(()=>{"use strict";rT();p2();({feature:m2}=Rs({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:ws.enableAutoInsertionOfCellInRow}})),{feature:h2}=Rs({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:ws.enableOneGridEvents}}),{feature:fme}=Rs({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:ws.disablePBIComponents}}),{feature:pme}=Rs({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:ws.enableAgentResponse}}),{feature:mme,useFeature:hme}=Rs({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:ws.enableDelayedLocalizationForCustomControls}})});var b2=v((yme,y2)=>{var Pu=new Proxy(function(){return Pu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Pu},apply:function(){return Pu},construct:function(){return{}}}),g2=function(){return Pu};Object.setPrototypeOf(g2,Pu);y2.exports=g2});var Qt,wo=k(()=>{"use strict";pt();ot();Yt();fu();le();Dt();Qt=class extends re{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(y.colspan);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){R.IsNullOrUndefined(t)||this.setProperty(y.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(y.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}set id(t){this.setProperty(y.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(y.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(y.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}get Name(){return this.getProperty(y.Name)}set Name(t){this.setProperty(y.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(y.languagecode)===r){i.setProperty(y.description,t);return}let n=new re(C.formLabel,null);n.setProperty(y.description,t),n.setProperty(y.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(y.languagecode)===t)return r.getProperty(y.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(y.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(y.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(y.availableforphone)}set availableforphone(t){R.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(y.availableforphone,String(t))}get visible(){return this.getProcessedValue(y.visible)}set visible(t){R.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(y.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(y.showlabel)}set showlabel(t){R.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return R.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(C.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(C.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.DefaultViewId):q.EmptyString}set defaultviewid(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.DependentAttributeName):q.EmptyString}set dependentattributename(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.DependentAttributeType):q.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.FilterRelationshipName):q.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.AvailableViewIds):q.EmptyString}set availableviewids(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(C.formControl);if(t&&t.ClassId){let r=at.getUniqueIdentifierForControl(t);return!R.IsNullOrUndefined(r)&&at.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(C.formControl);if(t){let n=at.getUniqueIdentifierForControl(t).guidString,i=n===G.GridControl||n===G.TimeLineControl||n===G.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===C.formSection||this.NodeName===C.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(C.formControl);if(t){let n=at.getUniqueIdentifierForControl(t).guidString,i=n===G.MapsControl||n===G.WebResourceHtmlControl||n===G.WebResourceImageControl||n===G.IframeControl||n===G.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(C.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(C.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var Ls,oy=k(()=>{"use strict";Yt();le();Dt();Ls=class extends re{constructor(t,r){super(C.dependency,t),q.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}setDefaultProperties(t){this.id=t}}});var v2,ks,ay=k(()=>{"use strict";ot();oy();le();Dt();wo();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(v2||(v2={}));ks=class extends Qt{constructor(t,r){super(C.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(y.Name,t)}get eventName(){return this.getProperty(y.Name)}set application(t){this.setProperty(y.application,t)}get application(){return this.getProperty(y.application)}set attribute(t){this.setProperty(y.EventAttribute,t)}get attribute(){return this.getProperty(y.EventAttribute)}set relationship(t){this.setProperty(y.Relationship,t)}get relationship(){return this.getProperty(y.Relationship)}set control(t){this.setProperty(y.Control,t)}get control(){return this.getProperty(y.Control)}set active(t){this.setProperty(y.EventActive,t)}get active(){return this.getProperty(y.EventActive)}getAllHandlers(){let t=this.getChildren(C.EventHandlers);return t&&t.length?t[0].getChildren(C.handler):[]}getAllDependencies(){let t=this.getChildren(C.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(C.formDependencies);if(R.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new re(C.formDependencies,this)),r=this.getFirstChild(C.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new Ls(r,n.toString()))}}}});var In,Ru=k(()=>{"use strict";pt();Bl();ot();ta();le();Dt();_n();In=class extends re{previewVersion;constructor(t){super(C.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(y.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t)}set ClassId(t){this.setProperty(y.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(y.datafieldname)}set dataFieldName(t){this.setProperty(y.datafieldname,t)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}get UniqueId(){let t=this.getProperty(y.uniqueid);return R.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set UniqueId(t){this.setProperty(y.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(y.isRequired)==="true"}set isRequired(t){R.IsNullOrUndefined(t)||this.setProperty(y.isRequired,String(t))}get disableMru(){return this.getParam(y.DisableMru)==="true"}set disableMru(t){R.IsNullOrUndefined(t)||this.setParameter(y.DisableMru,t)}get useMFDForCreate(){return this.getParam(y.UseMFDForCreate)==="true"}set useMFDForCreate(t){R.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(y.UseMFDForEdit)==="true"}set useMFDForEdit(t){R.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForEdit,t)}get disabled(){return this.getProperty(y.disabled)==="true"}set disabled(t){R.IsNullOrUndefined(t)||this.setProperty(y.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(y.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(y.indicationOfSubgrid,String(t))}getAllParameters(){let t=new nr,r=this.getFirstChild(y.parameters);return r&&r.getAllChildren().forEach(n=>{if(n){let i=n.getAllChildren(),o=i&&i.length>0&&i[0];o&&t.add(n.getNodeName(),o.getNodeName())}}),t}setParameter(t,r){let n=!1;r===null&&(n=!0);let i=(Li.StartTag+r).toString(),o=this.parametersNode;if(o){let a=o.findFirst(s=>s&&s.getNodeName()===t);if(a)if(n){this.deleteFirstGrandChildOfName(C.controlParameters,a);return}else{let s=a.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):a.addChild(new re(i,a))}else n||(a=new re(t,o),a.addChild(new re(i,a)),o.addChild(a))}else if(!n){o=new re("parameters",this);let a=new re(t,o);a.addChild(new re(i,a)),o.addChild(a),this.addChild(o)}}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 o=i.getNodeName();return o.charAt(0)===Li.StartTag?o.substring(1):o}}}return null}get parametersNode(){let t=this.getChildren(y.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new nr;switch(this.ClassId.guidString.toUpperCase()){case N.LookupControl:if(t&&t.getKeys())if(t.getKeys().forEach(a=>{n.add(a,this.getParam(a))}),t&&t.containsKey("DefaultViewId")){let a=this.getParam("DefaultViewId").replace("{","").replace("}","");n.upsert("DefaultViewId",a)}else{let a=this.getParent(),s=await r.formModelService.lookupControlService.populateDefaultView(this,a.getParentForm().entityName);s&&s.id&&n.upsert("DefaultViewId",s.id.replace("{","").replace("}",""))}break;default:t&&t.getKeys()&&t.getKeys().forEach(a=>{n.add(a,this.getParam(a))});break}let i=n.getInternalObject(),o=[];for(let a in i)i.hasOwnProperty(a)&&o.push({Name:a,Value:i[a]});return o}getIsUnbound(){return this.getProperty(y.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case N.BooleanControl:case N.CheckboxControl:return 0;case N.DateTimeControl:return 2;case N.DecimalControl:return 3;case N.FloatingNumberControl:return 4;case N.IntegerControl:case N.DurationControl:case N.LanguageControl:case N.TimezoneControl:return 5;case N.LookupControl:return 6;case N.CurrencyControl:return 8;case N.PartyListControl:return 10;case N.ChoiceControl:case N.RelationshipRoleChoiceControl:return 11;case N.ChoiceStatusControl:return 13;case N.TextAreaControl:case N.TextboxControl:case N.LabelControl:case N.EmailAddressControl:case N.UrlControl:case N.TickerControl:case N.ButtonControl:case N.PhoneNumberControl:return 14;case N.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===mt.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 $s,sy=k(()=>{"use strict";Yt();zo();Ru();le();Dt();$s=class extends In{constructor(t){super(t)}get targetEntityType(){return this.getParam(y.targetEntityType)||q.EmptyString}set targetEntityType(t){this.setParameter(y.targetEntityType,t)}get viewId(){return q.StripBraces(this.getParam(y.viewId))||q.EmptyString}set viewId(t){this.setParameter(y.viewId,q.AddBraces(t))}get viewIds(){return this.getParam(y.viewIds)||q.EmptyString}set viewIds(t){this.setParameter(y.viewIds,t)}get relationshipName(){return this.getParam(y.RelationshipName)||q.EmptyString}set relationshipName(t){this.setParameter(y.RelationshipName,t)}get isUserView(){return q.IsStrictTrue(this.getParam(y.isUserView))}set isUserView(t){this.setParameter(y.isUserView,t.toString())}get enableViewPicker(){return q.IsStrictTrue(this.getParam(y.enableViewPicker))}set enableViewPicker(t){this.setParameter(y.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(y.autoExpand)===y.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(y.autoExpand,t?y.Auto:y.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(y.recordsPerPage)?Number(this.getParam(y.recordsPerPage)):Number(y.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(y.recordsPerPage,String(t))}get enableQuickFind(){return q.IsStrictTrue(this.getParam(y.enableQuickFind))}set enableQuickFind(t){this.setParameter(y.enableQuickFind,t)}get teamTemplateId(){return q.StripBraces(this.getParam(y.teamTemplateId))||q.EmptyString}set teamTemplateId(t){this.setParameter(y.teamTemplateId,q.AddBraces(t))}get chartId(){return this.getParam(y.visualizationId)||q.EmptyString}set chartId(t){this.setParameter(y.visualizationId,t)}get enableChartPicker(){return q.IsStrictTrue(this.getParam(y.enableChartPicker))}set enableChartPicker(t){this.setParameter(y.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(y.chartGridMode)){case an.Chart:return an.Chart;case an.Grid:return an.Grid;default:return an.All}}set chartGridMode(t){this.setParameter(y.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=an.Chart:this.chartGridMode=this.enableChartPicker?an.All:an.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case y.viewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.viewId));break;case y.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case y.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case y.RelationshipName:let i=n.getAllChildren(),o="<"+r.relationshipName;i.length?n.getAllChildren()[0].setNodeName(o):n.addChild(new re(o,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 o=n[i].getParameters().get(jt.dataset)?n[i].getParameters().get(jt.dataset)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var xs,ly=k(()=>{"use strict";Yt();zo();Ru();le();xs=class extends In{constructor(t){super(t)}get defaultViewId(){return q.StripBraces(this.getParam(y.DefaultViewId))||q.EmptyString}set defaultViewId(t){this.setParameter(y.DefaultViewId,q.AddBraces(t))}get autoResolve(){return q.IsStrictTrue(this.getParam(y.AutoResolve))}set autoResolve(t){this.setParameter(y.AutoResolve,t)}get disableQuickFind(){return q.IsStrictTrue(this.getParam(y.DisableQuickFind))}set disableQuickFind(t){this.setParameter(y.DisableQuickFind,t)}get disableViewPicker(){return q.IsStrictTrue(this.getParam(y.DisableViewPicker))}set disableViewPicker(t){this.setParameter(y.DisableViewPicker,t)}get allowFilterOff(){return q.IsStrictTrue(this.getParam(y.AllowFilterOff))}set allowFilterOff(t){this.setParameter(y.AllowFilterOff,t)}get disableMru(){return q.IsStrictTrue(this.getParam(y.DisableMru))}set disableMru(t){this.setParameter(y.DisableMru,t)}get dependentAttributeName(){return this.getParam(y.DependentAttributeName)||q.EmptyString}set dependentAttributeName(t){this.setParameter(y.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(y.DependentAttributeType)||q.EmptyString}set dependentAttributeType(t){this.setParameter(y.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(y.FilterRelationshipName)||q.EmptyString}set filterRelationshipName(t){this.setParameter(y.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(y.AvailableViewIds)||q.EmptyString}set availableViewIds(t){this.setParameter(y.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.datafieldname:case y.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case y.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.defaultViewId));break;case y.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case y.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case y.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case y.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case y.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case y.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case y.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case y.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case y.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 o=n[i].getParameters().get(jt.value)?n[i].getParameters().get(jt.value)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var w2,uy,_r,Lu=k(()=>{"use strict";w2=Ee(b2());wo();le();ot();pt();ay();Ru();fu();g0();Qg();_n();ta();gs();sy();ly();cy();rs();uy="_",_r=class e extends Qt{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(C.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,R.IsNullOrUndefined(this.getProperty(y.id))&&(this.id=new U(U.NewGuid()))}addControl(t,r,n,i,o,a,s){n instanceof In?this.addChild(n):n instanceof U&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,o,a,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!R.IsNullOrUndefined(this.control))return R.IsNullOrUndefined(this.control.dataFieldName)?R.IsNullOrUndefined(this.control.id)?!0:!na.dependencyFieldCount.containsKey(this.control.id):!na.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new ks(this,iu.onLoad))}get dependencies(){let t=this.getChildren(C.formEvents);for(let r of t){let n=r.getChildren(C.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let o;if(i&&Hd[i])o=Hd[i].replace(/ /g,uy)+uy;else{o="Control_";let u=new Error("Control class id does not exist or is undefined");(0,w2.trackErrorTrace)(sr,{eventName:`${b_}/getNextAvailableControlName`},u)}let a="new_",s=this.getHighestIndexById(t,i)+1,l=`${o}${a}${s}`;for(;n.has(l);)s++,l=`${o}${a}${s}`;return l}getUnboundControlProperties(t){e.prototype.setProperty.call(t,y.isUnbound,"true"),e.prototype.setProperty.call(t,y.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,o,a,s){let l;o===ln.Grid?(l=new $s(this),l.indicationOfSubgrid=!0):o===ln.Lookup?l=new xs(this):l=new In(this);let u=n.guidString,c=a||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,y.id,c),l.ClassId=n,!R.IsNullOrUndefined(s)&&(l.UniqueId=s),!a&&r)this.getUnboundControlProperties(l);else{let d=at.getUniqueIdentifierForControl(l);R.IsNullOrUndefined(d)||(at.getControlDataTypeByControlOrUniqueId(d)===ee.QuickFormCollectionControl||!at.isUnboundFormControlByIdentifier(d)?o!==ln.Grid&&a&&u!==N.IframeControl&&u!==N.SubgridControl&&u!==N.ReferencePanelSubgridControl&&(l.dataFieldName=a,e.prototype.setProperty.call(l,y.disabled,"false")):(this.rowspan=at.GetRowSpan(l),(at.getControlDataTypeByControlOrUniqueId(d)===ee.NotesControl||at.getControlDataTypeByControlOrUniqueId(d)===ee.TimeLineControl)&&(e.prototype.setProperty.call(l,y.disabled,"false"),l.id=ee.NotesControl)),(at.getUnboundControlNameFromIdentifier(n)===ee.SubGridControl||at.getUnboundControlNameFromIdentifier(n)===ee.NotesControl||at.getUnboundControlNameFromIdentifier(n)===ee.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(R.IsNullOrUndefined(t))return;let n=t.getAllChildren();for(let i of n){let o=i.getAllChildren();for(let a of o){let s=a.GetPropertyByParameter(y.id);a.getNodeName()===C.dependency&&s?r.push(s):this.buildDependencyList(a,r)}}}get control(){return this.getFirstChild(C.formControl)}set rowspan(t){this.setProperty(y.rowspan,String(t))}get rowspan(){let t=this.getProperty(y.rowspan);return R.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(y.auto,String(t))}get autoexpand(){return this.getProperty(y.auto)==="true"}set colspan(t){let r=Number(m0.ONE_COLUMN),n=Number(m0.FOUR_COLUMN);R.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(y.colspan,String(t))}get colspan(){let t=this.getProperty(y.colspan);return R.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(C.formRow)}getParentSection(){return this.getAncestor(C.formSection)}getParentTab(){return this.getAncestor(C.formTab)}getParentForm(){return this.getAncestor(C.form)}isInHeader(){let t=this.getAncestor(C.formHeader);return!R.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(C.formFooter);return!R.IsNullOrUndefined(t)}isEmpty(){return R.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(C.formHeader):this.isInFooter()?this.getAncestor(C.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(y.userspacer);return R.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(y.userspacer,"true")}ClearUserSpacer(){this.setProperty(y.userspacer,"false")}get columns(){let t=this.getProperty(y.columnName);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case ze.TWO_COLUMN:r="11";break;case ze.THREE_COLUMN:r="111";break;case ze.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(!R.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();R.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 o=i.isDuplicateCell(this,n),a=this.getRequiredLevel(t);if((a===io.ApplicationRequired||a===io.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?io.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??io.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()===C.formCell){let i=n;i.control&&i!==this&&r.add(n.control.id)}return!1}),r}getHighestIndexById(t,r){let n=t.findAll(o=>o.getNodeName()===C.formCell&&o.control&&o.control.ClassId.guidString===r),i=0;return n.forEach(o=>{i=Math.max(this.parseControlNameIndex(o.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)===uy&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var Fs,dy=k(()=>{"use strict";Yt();le();Dt();Fs=class extends re{isInternal;constructor(t,r,n,i){super(C.library,t),this.isInternal=!!i,q.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(y.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(y.libraryUniqueId,t)}get name(){return this.getProperty(y.libraryName)}set name(t){this.setProperty(y.libraryName,t)}get displayName(){return this.getProperty(y.displayName)}set displayName(t){this.setProperty(y.displayName,t)}get description(){return this.getProperty(y.description)}set description(t){this.setProperty(y.description,t)}}});var ua,fy=k(()=>{"use strict";ot();Lu();le();Dt();ua=class extends re{isRowAddedOnDragOver;constructor(t){super(C.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 R.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return R.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(C.formSection)}insertPaddingCellAtIndex(t){let r=new _r(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(C.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 IQ(e){switch(e){case ia.Left:return aa.Left;case ia.Right:return aa.Right;case ia.Center:return aa.Center;default:return aa.Left}}function OQ(e){switch(e){case bs.Left:return vs.Left;case bs.Top:return vs.Top;default:return vs.Left}}function C2(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var PQ,ri,ku=k(()=>{"use strict";y0();pt();ot();Yt();iy();Lu();le();_n();wo();fy();PQ=115,ri=class e extends Qt{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=ze.ONE_COLUMN;break;case 11:t=ze.TWO_COLUMN;break;case 111:t=ze.THREE_COLUMN;break;case 1111:t=ze.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=Ue.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+Ue.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(y.Name,r)}initializeDefaultProperties(t,r,n){if(n===ze.REFERENCE_PANEL){this.addProperty(y.rowheight,"25");let i=`${Ue.referencePanelNamePrefix}${U.NewGuid()}${Ue.namePrefix}`;this.addProperty(y.Name,i)}else this.setUniqueName();if(this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,Ue.IsUserDefined),this.addProperty(y.locklevel,Ue.LockLevel),this.addProperty(y.showlabel,Ue.ShowLabel),this.addProperty(y.showbar,Ue.ShowBar),this.addProperty(y.layout,Ue.Layout),this.addProperty(y.Fieldlabelalignment,Ue.labelAlignment),this.addProperty(y.Fieldlabelposition,Ue.labelPosition),R.IsNullOrUndefined(n))this.addProperty(y.columnName,Ue.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(y.columnName,i)}this.addProperty(y.LabelWidth,Ue.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case ze.TWO_COLUMN:r="11";break;case ze.THREE_COLUMN:r="111";break;case ze.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 R.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(q.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new ua(null);if(this.addGrandChild(C.formRows,r),m2.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new _r(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===ze.REFERENCE_PANEL&&(n=ze.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(C.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(C.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(C.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(C.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(C.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(C.formRows);return t.length===0?[]:t[0].getChildren(C.formRow)}get columns(){let t=this.getProperty(y.columnName),r=R.IsNullOrUndefined(t)?NaN:parseInt(t,10);if(isNaN(r)){let n=1;for(let i of this.rows)n=Math.max(n,i.cells.length);return C2(n)}return r}set columns(t){R.IsNullOrUndefined(t)||this.setProperty(y.columnName,String(t))}get rowHeight(){let t=this.getProperty(y.rowheight);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(y.rowheight,String(t))}set autoexpand(t){this.setProperty(y.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(y.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(y.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(y.IsUserDefined,"1"):this.setProperty(y.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(C.formColumn)}getParentTab(){return this.getAncestor(C.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(y.showlabel)==="true"}set showlabel(t){R.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}get fieldLabelAlignment(){let t=Ue.labelAlignment,r=this.getProperty(y.Fieldlabelalignment);return R.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){R.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(y.Fieldlabelposition);return R.IsNullOrUndefined(t)?Ue.labelPosition:t}set fieldLabelPosition(t){R.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(y.showbar)==="true"}set showbar(t){R.IsNullOrUndefined(t)||this.setProperty(y.showbar,String(t))}get labelwidth(){let t=+this.getProperty(y.LabelWidth);return t===0?PQ:t}set labelwidth(t){R.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(y.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:IQ(this.fieldLabelAlignment),Position:OQ(this.fieldLabelPosition)},Columns:C2(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()===C.formSection){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!R.IsNullOrUndefined(this)&&!R.IsNullOrUndefined(this.Name)&&this.Name.indexOf(Ue.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===C.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===C.formFooter||this.NodeName===C.formHeader}}});var Co,Ef=k(()=>{"use strict";le();Dt();ku();Co=class e extends re{constructor(t){super(C.formColumn,t)}initializeDefaultProperties(t){this.addProperty(y.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(C.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new ri(C.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(C.formSections,t,r)}initialize(t,r,n,i=ze.ONE_COLUMN){this.initializeDefaultProperties(t);let o=e.createAndInitNewSection(r,n,i);this.addSectionAtIndex(o,this.sections.length),o.setUniqueName()}get parentTab(){return this.getAncestor(C.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(C.formSection)}get width(){return this.getProperty(y.width)}set width(t){this.setProperty(y.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(C.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(y.Name),Id:this.getProperty(y.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(y.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var Af,E2=k(()=>{"use strict";pt();le();_n();ku();Af=class extends ri{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(y.Name,n),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.columnName,Ue.columns),this.setDisplayName(r,t)}}});var Sf,A2=k(()=>{"use strict";Ef();le();E2();Sf=class extends Co{addAndIntializeNavBarSection(t,r,n,i){let o=new Af(C.formSection,null);return o.initializeNavArea(t,r,i),this.addGrandChildAtIndex(C.formSections,o,n),o}}});var $i,Nf=k(()=>{"use strict";pt();ot();Yt();Ef();le();Dt();wo();$i=class extends Qt{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(C.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(C.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=We.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=We.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=We.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=We.TWO_COLUMN_WIDER_RIGHT;break}t=We.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=We.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=We.THREE_COLUMN_WIDER_MID;break}t=We.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(y.Name,ho.namePrefix+t.toString()),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,ho.IsUserDefined),this.addProperty(y.locklevel,ho.LockLevel),this.addProperty(y.showlabel,ho.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=ze.ONE_COLUMN,o=!0,a){let s=this.getChildren(C.formColumns)[0],l=[];switch(t){case We.ONE_COLUMN:l.push(100);break;case We.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case We.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case We.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case We.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case We.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new Co(s);c.initialize(u,r,n,i),this.addGrandChild(C.formColumns,c)}}initialize(t,r,n,i,o,a=ze.ONE_COLUMN,s=!0,l){this.addChild(new re(C.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,o,a,s,l)}get columns(){let t=this.getChildren(C.formColumns);return t.length!==1?[]:t[0].getChildren(C.formColumn)}get expanded(){return this.getProcessedValue(y.expanded)}set expanded(t){R.IsNullOrUndefined(t)||this.setProperty(y.expanded,String(t))}get groupName(){return this.getProperty(y.groupName)}get contentType(){return this.getProperty(y.contentType)}set contentType(t){this.setProperty(y.contentType,t)}insertNewColumnAtIndex(t,r,n,i,o){t.initialize(n,i,o),this.addGrandChildAtIndex(C.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(C.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(C.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()===C.formTab){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var ca,py=k(()=>{"use strict";pt();le();Dt();_n();A2();Nf();ca=class extends $i{constructor(t,r,n){super(t,We.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new U(U.NewGuid())}initializeDefaultProps(){this.addChild(new re(C.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(C.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 o of i.cells)if(o.NavId===t)return o;return null}initializeFiveColumns(){for(let t=0;t<nf.FIVE_COLUMN;t++){let r=new Sf(this.getChildren(C.formColumns)[0]);r.initializeDefaultProperties(G_.FiveEqColumn),this.addGrandChild(C.formColumns,r)}}}});function LQ(e){switch(e){case mt.Main:return go.Main;case mt.QuickCreate:return go.QuickCreate;case mt.QuickViewForm:return go.Quick;case mt.Dialog:return go.Dialog;default:return go.None}}function kQ(e,t){if(t===mt.Main){if(e)switch(e.toLowerCase()){case"low":return mo.Low;case"highreadonlyvalues":return mo.HighReadOnlyValues;default:return mo.HighWithControls}return mo.Low}}var Tf,RQ,_f,S2=k(()=>{"use strict";Q_();Tf=Ee(ra());y0();ot();Yt();gs();iy();le();zo();Mg();ta();Lu();le();wo();dy();py();Nf();RQ="1920";_f=class e extends Qt{_formUniqueName;isHeaderDefaulted;consistencyStrong=!1;_formId;_rawFormXml;_entityName;_entityDisplayName;_status;_formName;_langCode;_description;_formType;_formPresentation;parameters=[];_formactivationstate;_changeTracker;_metadataChangeEvent;_etag;constructor(t,r,n,i,o,a,s,l,u){super(C.form,null),this._formUniqueName=o,this._formId=t,this._entityName=r,this._status=n,this._formName=i,this._description=l,this._formType=a,this._formPresentation=s,this._formactivationstate=u,this._changeTracker=new Gd,this._metadataChangeEvent=new af}get FormLibraries(){let t=this.getFirstChild(C.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(o=>o instanceof _r).forEach(o=>{let a=o.events;a&&(t=t.concat(a))})}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 _r){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()===C.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let o=i.GetPropertyByParameter(n).replace("$webresource:",""),a=new Fs(void 0,void 0,"",!0);return a.name=o,a.displayName=o,a})),r}getDependentFields(){let t=this.getAllEvents(),r=new Set;return t.forEach(n=>{try{n.getAllDependencies().forEach(o=>{r.add(o.id)})}catch(i){throw(0,Tf.trackErrorTrace)(v_,{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 q.IsNullOrEmpty(this.getProperty(y.ShowImage))?!0:this.getProperty(y.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(y.ShowImage,String(t)):this.setProperty(y.ShowImage,"false")}get ShowNavigation(){return q.IsNullOrEmpty(this.getProperty(y.ShowNavigationbar))?!0:this.getProperty(y.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(y.ShowNavigationbar,String(t)):this.setProperty(y.ShowNavigationbar,"false")}get MaxWidth(){return q.IsNullOrEmpty(this.getProperty(y.MaxWidth))?RQ:this.getProperty(y.MaxWidth)}set MaxWidth(t){this.setProperty(y.MaxWidth,t)}get headerDensityType(){return this.getProperty(y.HeaderDensityType)}set headerDensityType(t){t&&this.formType===mt.Main?this.setProperty(y.HeaderDensityType,t):this.formType!==mt.Main&&this.headerDensityType&&this.removeProperty(y.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===mt.Main||this.formType===mt.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(C.formHeader);return t.length!==1?null:t[0]}set header(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(C.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(C.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return R.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(C.formFooter);return t.length!==1?null:t[0]}set footer(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new $i(null,t),o=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,o,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(C.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,o){let a=new $i(null,We.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);a.initialize(We.ONE_COLUMN,s,this.LanguageCode,r,n,o,!1),this.addGrandChildAtIndex(C.formTabs,a,i);let l=a.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===ho.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(C.formTabs);return t.length!==1?[]:t[0].getChildren(C.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof ca)return t}return null}get NavigationNode(){let t=this.getChildren(C.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(C.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(C.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(C.formTabs);if(!R.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(C.formFooter).length>0}get displayCondition(){let t=this.getChildren(C.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(C.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(C.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(C.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);R.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(C.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 _r))return!1;let o=!0;return r==="Tab"?o=i.getParentTab()!==t.getParentTab():r==="Section"?o=i.getParentSection()!==t.getParentSection():o=i!==t,i instanceof _r&&i.control&&t.control&&o&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==N.CustomControl?!1:this.cellHasCustomControlWithName(t,_i.EditableGridControl)||h2.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,_i.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===N.CustomControl&&this.cellHasCustomControlWithName(t,_i.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()===C.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 o of r)if(!(o instanceof ca)){let a=o.toJSON(t);n.push(a)}for(let o of n)i.push(await o)}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,Tf.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===mt.Main?{HeaderDensity:kQ(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:LQ(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 Df,my,N2=k(()=>{"use strict";pt();ot();le();Dt();wo();Df=class extends Qt{constructor(t){super(C.formDisplayConditions,t)}get Order(){let t=this.getProperty(y.Order);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(y.Order,t.toString())}get FallbackForm(){return this.getProperty(y.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(y.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(C.formEveryOne)&&this.getChildren(C.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new my(this))}},my=class extends re{constructor(t){super(C.formEveryOne,t)}}});var If,_2=k(()=>{"use strict";le();Dt();If=class extends re{constructor(t,r){super(C.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(y.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(y.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(y.functionName)}set FunctionName(t){this.setProperty(y.functionName,t)}get LibraryName(){return this.getProperty(y.libraryNameEventHandler)}set LibraryName(t){this.setProperty(y.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(y.enabledForField)}set Enabled(t){this.setProperty(y.enabledForField,t)}get PassExecutionContext(){return this.getProperty(y.passExecutionContext)}set PassExecutionContext(t){this.setProperty(y.passExecutionContext,t)}get Parameters(){return this.getProperty(y.parameters)}set Parameters(t){this.setProperty(y.parameters,t)}}});var Ms,hy=k(()=>{"use strict";le();ku();Ms=class extends ri{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(C.formCell);for(let o of i)r.push(o)}}return r}get occupiedCells(){return this.cells.filter(t=>!t.isEmpty())}get maxColumns(){return super.getColumnCountValue()}}});var $u,T2=k(()=>{"use strict";le();hy();$u=class extends Ms{_customFooter;constructor(t,r){super(C.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 xu,D2=k(()=>{"use strict";le();hy();xu=class extends Ms{_customHeader;constructor(t,r){super(C.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(y.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(y.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(y.showBody)}set showBody(t){t!=null&&this.setProperty(y.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(y.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(y.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 Tr,da=k(()=>{"use strict";pt();Yt();le();wo();Tr=class e extends Qt{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(y.LCID)===t)return r.getProperty(y.text);return null}getAllTitles(){let t=this.getChildren(C.Titles);return t.length===0?[]:t[0].getChildren(C.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(y.LCID)===r){i.setProperty(y.text,t);return}let n=new e(C.Title,null);n.setProperty(y.text,t),n.setProperty(y.LCID,String(r)),this.addGrandChild(C.Titles,n)}get Sequence(){return+this.getProperty(y.Sequence)}set Sequence(t){this.setProperty(y.Sequence,t.toString())}get Area(){return this.getProperty(y.Area)}set Area(t){this.setProperty(y.Area,t)}set Id(t){this.setProperty(y.Id,t)}get Id(){return this.getProperty(y.Id)}get id(){return new U(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(y.icon)}set Icon(t){t=t||q.EmptyString,this.setProperty(y.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var Fu,I2=k(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(Fu||(Fu={}))});var Of,O2=k(()=>{"use strict";ot();le();da();I2();Of=class extends Tr{constructor(t){super(C.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 R.IsNullOrUndefined(r)?Fu.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):Fu.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 xe,$Q,P2,a0e,Us,gy=k(()=>{"use strict";pt();le();da();(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"})(xe||(xe={}));$Q=new Map([[xe.Info,"Info"],[xe.Sales,"Sales"],[xe.Service,"Service"],[xe.Marketing,"Marketing"],[xe.ProcessCenter,"ProcessCenter"]]),P2=new Map([["Info",xe.Info],["Sales",xe.Sales],["Service",xe.Service],["Marketing",xe.Marketing],["ProcessCenter",xe.ProcessCenter]]),a0e=new Map([[xe.Info,9e3],[xe.Sales,9200],[xe.Service,9400],[xe.Marketing,9600],[xe.ProcessCenter,9800],[xe.InternetMarketing,1e4],[xe.Async,10200]]),Us=class extends Tr{constructor(t,r){super(C.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=$Q.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(C.formNavigation)}get AreaId(){return this.getProperty(y.Id)}set AreaId(t){this.setProperty(y.Id,t)}get id(){return new U(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 Bs,yy=k(()=>{"use strict";le();da();Bs=class extends Tr{constructor(t,r){super(C.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(C.formNavBarArea)}get ParentNavigation(){return this.getAncestor(C.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var Pf,R2=k(()=>{"use strict";ot();le();da();Pf=class extends Tr{RelationshipNameUCIRuntime;constructor(t){super(C.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(y.RelationshipName)}set RelationshipName(t){this.setProperty(y.RelationshipName,t)}set Show(t){this.setProperty(y.Show,String(t))}get Show(){let t=this.getProperty(y.Show);return R.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(y.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 Rf,L2=k(()=>{"use strict";le();da();Rf=class extends Tr{constructor(t){super(C.formNavBarItem,t)}get Url(){return this.getProperty(y.url)}set Url(t){this.setProperty(y.url,t)}}});var Lf,k2=k(()=>{"use strict";pt();le();gy();yy();da();Lf=class extends Tr{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(C.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[xe.Info,xe.Sales,xe.Service,xe.Marketing,xe.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let o=new Set(i.map(a=>P2.get(a.AreaId)));n=n.filter(a=>!o.has(a))}}else{let i=new Bs(C.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let o=new Us(C.formNavBarArea,this.navBarAreas);o.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(o)}),!0):!1}get navBar(){return this.getFirstChild(C.formNavBar)}get id(){return new U(Yg,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(C.formNavBarAreas,r),this.addGrandChildAtIndex(C.formNavBarAreas,r,t))}async getNavBarAreasJSON(t){let r=[],n=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let o of this.navBarAreas.AllNavBarAreaItems)n.push(o.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 $2={};Hr($2,{ControlType:()=>ln,DeserializationService:()=>wy,DeserializationServiceScope:()=>vy,DeserializedFormElementNode:()=>Dr});var by,Dr,vy,ln,wy,cy=k(()=>{"use strict";by=Ee(ra());pt();ot();Yt();gs();Qg();ta();w_();J_();fu();S2();Lu();Ef();Ru();oy();le();le();N2();Dt();_n();ay();_2();T2();sy();ly();D2();dy();fy();ku();Nf();O2();gy();yy();R2();L2();k2();Dr=class extends re{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},vy="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(ln||(ln={}));wy=class{lcid;constructor(t){this.lcid=t}deSerializeFormXml(t,r,n,i,o,a,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,by.trackErrorTrace)(sr,{eventName:vy,eventData:{error:m}}),new Error(m)}let f=this.createFormModel(d.item(0),r,n,i,o,a,s,l,u,c);return R.IsNullOrUndefined(f.displayCondition)&&s!==mt.Dialog&&this.appendDefaultDisplayCondition(f),f}upsertFieldCount(t,r){let n=na.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(!R.IsNullOrUndefined(t)){let n=R.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,o,a,s,l,u,c){let d=new _f(r,n,i,o,a,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===mt.Main&&(this.insertHeaderFooterElementProperties(C.formHeader,d,d.header),this.insertHeaderFooterElementProperties(C.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(R.IsNullOrUndefined(n)){let i=t===C.formHeader?new xu(r,!0):new $u(r,!0);Dr.prototype.insertProperty.call(i,y.id,"{"+U.NewGuid()+"}"),Dr.prototype.insertProperty.call(i,y.Fieldlabelposition,"Top"),Dr.prototype.insertProperty.call(i,y.columnName,Ue.MarginalControlColumns),Dr.prototype.insertProperty.call(i,y.LabelWidth,Ue.LabelWidth),Dr.prototype.insertProperty.call(i,y.Fieldlabelalignment,"Left");let o=null,a=new ua(o);for(let s=0;s<i.maxColumns;s++){let l=new _r(a);Dr.prototype.insertProperty.call(l,y.id,"{"+U.NewGuid()+"}"),l.setDisplayName(q.EmptyString,this.lcid),Dr.prototype.insertProperty.call(l,y.showlabel,"false"),a.addCell(l)}i.appendRow(a),t===C.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 Dr(`<${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,by.trackErrorTrace)(sr,{eventName:vy,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(Dr.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===C.formCell&&i.name===y.auto&&i.value==="true"&&t.setAutoExpandDetailsForTab())}}populateElementChildren(t,r){for(let n=0;n<r.length;n++){let i=r.item(n),o=this.deSerializeFormXmlNode(i,t);o&&Dr.prototype.insertChild.call(t,o)}}createModelNode(t,r){switch(t.nodeName){case C.form:throw new Error("Form node shouldn't be created using this method");case C.formTab:return new $i(r);case C.formColumn:return new Co(r);case C.formHeader:return new xu(r,!1);case C.formFooter:return new $u(r,!1);case C.formSection:return new ri(C.formSection,r);case C.formRow:return new ua(r);case C.formCell:return new _r(r);case C.formControl:let n=t.attributes,i=t.childNodes.length>0?t.childNodes[0].childNodes:null,o;for(let s=0;s<n.length;s++){let l=n.item(s);if(l.name===y.indicationOfSubgrid&&l.value==="true"||l.name===y.classid&&(l.value?.toLocaleUpperCase()===`{${N.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${N.ReferencePanelSubgridControl}}`))o=ln.Grid;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.LookupControl}}`)o=ln.Lookup;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===y.DefaultViewId&&(o=ln.Lookup)}return o===ln.Grid?new $s(r):o===ln.Lookup?new xs(r):new In(r);case C.formEvent:return new ks(r,q.EmptyString);case C.dependency:return this.populateDependencyTable(t),new Ls(r,q.EmptyString);case C.Handler:let a=[];return new If(a,r);case C.formNavigation:return new Lf(t.nodeName,r);case C.formNavBarArea:return new Us(t.nodeName,r);case C.formNavBarAreas:return new Bs(t.nodeName,r);case C.formNavBar:return new Of(r);case C.formNavBarByRelationshipItem:return new Pf(r);case C.formNavBarItem:return new Rf(r);case C.formDisplayConditions:return new Df(r);case C.library:return new Fs(r,q.EmptyString,q.EmptyString);case C.controlDescription:return new Kd(r);case C.customControl:return this.populateCustomControlConfigurationId(t),new of(r);default:return new Dr(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===y.id&&this.upsertFieldCount(i.value,Xn.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===y.id){let o=new U(i.value.substr(1,i.value.length-2));for(let a=0;a<t.parentNode.attributes.length;a++){let s=t.parentNode.attributes.item(a);if(s.name===y.ForControl){let l=s.value.substr(1,i.value.length-2);at.CustomControlIdMap.upsert(l,o);break}}break}}}}});var x2={};Hr(x2,{SerializationService:()=>Cy,SerializationServiceScope:()=>xQ,SerializedFormElementNode:()=>qs});var xQ,qs,Cy,F2=k(()=>{"use strict";Yt();Dt();_n();py();xQ="SerializationService",qs=class extends re{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},Cy=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=qs.prototype.fetchNodeName.call(t);if(r.charAt(0)===Li.StartTag)return q.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return q.EmptyString;let n=qs.prototype.enumerateProperties.call(t),i=qs.prototype.enumerateChildren.call(t);if(!(t instanceof ca)){let o=`<${r}`;if(n.length!==0&&(o+=` ${this.getPropertiesString(n)}`),i.length===0)o+=" />";else{let a=q.EmptyString;for(let s of i)a+=this.serializeFormXmlNode(s);o+=`>${a}</${r}>`}return o}return q.EmptyString}getPropertiesString(t){let r=q.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${q.EscapeXml(n.value,!0)}"`}),r}}});var Ny=v(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.completeRecordAsStored=Vs.completeLabelsAsStored=void 0;var Ey=uo(),FQ="E7A81278-8635-4D9E-8D4D-59480B391C5B",MQ=new Set(["tab","section","cell"]);function On(e){let t=[];for(let r=e.firstChild;r;r=r.nextSibling)r.nodeType===1&&t.push(r);return t}function Eo(e,t){return On(e).find(r=>r.tagName===t)}function U2(e,t){return e.length===t.length&&e.every((r,n)=>r.tagName===t[n].tagName)}function Ay(e){let t=Eo(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===FQ:!1}function Sy(e,t){var r,n;let i=((r=Eo(e,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"";return i!==""&&i===(((n=Eo(t,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"")}function UQ(e,t){if(Eo(e,"labels"))return;let r=On(e),n=On(t),i=n[0];if(!i||i.tagName!=="labels"||n.length!==r.length+1||!U2(r,n.slice(1)))return;let o=On(i);if(!(o.length===0||o.some(s=>s.tagName!=="label"||!s.hasAttribute("description")||!s.hasAttribute("languagecode"))||!(e.tagName==="cell"&&Ay(e)&&Sy(e,t))&&o.some(s=>s.getAttribute("description")!=="")))return i}function BQ(e,t){let r=qQ(e.ownerDocument,t),n=On(e)[0];n?e.insertBefore(r,n):e.appendChild(r)}function qQ(e,t){let r=e.createElement("labels");for(let n of On(t))r.appendChild(B2(e,n));return r}function B2(e,t){let r=e.createElement("label");for(let n=0;n<t.attributes.length;n+=1){let{name:i,value:o}=t.attributes[n];(i==="description"||i==="languagecode")&&r.setAttribute(i,o)}return r}function M2(e,t){let r=Eo(e,"labels");return r?On(r).find(n=>n.tagName==="label"&&n.getAttribute("languagecode")===String(t)):void 0}function VQ(e,t,r){if(e.tagName!=="cell"||!Ay(e)||!Sy(e,t))return!1;let n=M2(e,r),i=M2(t,r),o=i?.getAttribute("description")||"";return!n||!n.hasAttribute("description")||(n.getAttribute("description")||"")!==""||o===""?!1:(n.setAttribute("description",o),!0)}function GQ(e,t){if(e.tagName!=="cell"||!Ay(e)||!Sy(e,t))return;let r=Eo(e,"labels"),n=Eo(t,"labels");if(!r||!n)return;let i=On(r),o=On(n),a=f=>f.tagName==="label"&&f.hasAttribute("description")&&f.hasAttribute("languagecode");if(o.length<=i.length||!i.every(a)||!o.every(a))return;let s=new Map(i.map(f=>[f.getAttribute("languagecode")||"",f]));if(s.size!==i.length)return;let l=new Set,u=0,c=[],d=[];for(let f of o){let m=f.getAttribute("languagecode")||"";if(l.has(m))return;l.add(m);let p=s.get(m);if(!p){d.push(f);continue}if((p.getAttribute("description")||"")!==(f.getAttribute("description")||""))return;u+=1,c.push(...d.map(h=>({label:h,before:p}))),d=[]}return c.push(...d.map(f=>({label:f}))),u===i.length?c:void 0}function q2(e,t,r,n){if(e.tagName!==t.tagName)return;if(MQ.has(e.tagName)){let a=UQ(e,t);a&&(BQ(e,a),n.changed=!0),VQ(e,t,r)&&(n.changed=!0);let s=GQ(e,t),l=Eo(e,"labels");if(s&&l){for(let{label:u,before:c}of s){let d=B2(e.ownerDocument,u);c?l.insertBefore(d,c):l.appendChild(d)}n.changed=!0}}let i=On(e),o=On(t);U2(i,o)&&i.forEach((a,s)=>q2(a,o[s],r,n))}function V2(e,t,r){if(e===t)return e;let n,i;try{n=(0,Ey.parseXmlRoot)(e,""),i=(0,Ey.parseXmlRoot)(t,"")}catch{return e}let o={changed:!1};return q2(n,i,r,o),o.changed?(0,Ey.serializeNode)(n):e}Vs.completeLabelsAsStored=V2;function WQ(e,t,r){let n=e?.formxml,i=t?.formxml;if(typeof n!="string"||typeof i!="string")return e;let o=V2(n,i,r);return o===n?e:{...e,formxml:o}}Vs.completeRecordAsStored=WQ});var lL=v(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.pcfReadIssues=ue.pcfBindingIssues=ue.commitPcfState=ue.mayCommitPcfState=ue.reconcilePcfDescriptions=ue.customControlNeeds=ue.mintPcfIdentity=ue.planPcfBinding=ue.projectPcfBindings=ue.supportsPcfFormType=ue.storedBindingOf=ue.hasCustomControl=ue.sameAsStored=ue.readPcfDescription=ue.newPcfDescription=ue.editorText=ue.nativeClassFor=ue.pcfEntryLayout=void 0;var zQ=(fu(),Fr(Y_)),jQ=Q(),G2=dt(),V=wd(),HQ=Uh(),Ce=en(),Mi=["web","phone","tablet"],Mu={web:"2",phone:"0",tablet:"1"},K2=new Map([["2","web"],["0","phone"],["1","tablet"]]),KQ=["phone","web","tablet"];function $f(e){let t=new Set(e),r=KQ.filter(n=>!t.has(n));return{defaults:r.length===0?[null]:r,named:Mi.filter(n=>t.has(n))}}ue.pcfEntryLayout=$f;function lr(e){return Array.isArray(e)?e:[]}function st(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Uu(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ty(e){return{n:`<${e}`,a:[],c:[]}}function J2(e){return typeof e?.n=="string"&&e.n.startsWith("<")}function W2(e){let t=lr(e.c);return t.length===1&&J2(t[0])&&(0,V.rawText)(e)!==""?(0,V.rawText)(e):void 0}function cn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Y2(e){return`{${e.replace(/^\{|\}$/g,"").toUpperCase()}}`}function Dy(e){try{let t=(0,zQ.mapFieldTypeToControl)(e.attributeTypeName,e.format);return t?Y2(String(t)):void 0}catch{return}}ue.nativeClassFor=Dy;var Iy=new Map([["Whole.None",{digits:0,min:-2147483648,max:2147483647}],["Whole.Duration",{digits:0,min:0,max:2147483647}],["Decimal",{digits:7,min:-922337203685477,max:922337203685477}],["FP",{digits:5,min:-1e11,max:1e11}],["Currency",{digits:4,min:-1e11,max:1e11}]]),Q2=new Set(["TwoOptions","Boolean"]),X2=new Set(["SingleLine.Text","SingleLine.TextArea","SingleLine.Email","SingleLine.Phone","SingleLine.URL","SingleLine.Ticker","Multiple"]),JQ=new Map([...[...X2].map(e=>[e,100]),["SingleLine.TextArea",2e3],["Multiple",1048576]]),YQ=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function Z2(e){return YQ.test(e)&&e!=="__proto__"}function Oy(e){return e!==void 0&&(e==="Enum"||Iy.has(e)||Q2.has(e)||X2.has(e))}function eL(e){return typeof e=="number"?e:e!==""&&!Number.isNaN(Number(e))?Number(e):void 0}function Bu(e,t){let r=e!==void 0?Iy.get(e):void 0;if(r&&typeof t!="boolean"){let n=eL(t);if(n!==void 0)return n.toFixed(r.digits)}return typeof t=="boolean"?t?"true":"false":String(t)}ue.editorText=Bu;function QQ(e,t,r){var n;let i=[];for(let o of e.properties){let a=o.name,s;if(o.isPrimary?s=t:o.usage==="input"&&Uu(r,a)?s=Bu(o.defaultType,r[a]):s=(n=o.defaultValue)!==null&&n!==void 0?n:"",s==="")continue;let l=[];o.defaultType&&l.push(["type",o.defaultType]),!o.isPrimary&&(o.defaultType==="Enum"||o.usage==="input")&&l.push(["static","true"]),i.push({n:a,a:l,c:[Ty(s)]})}return i}function tL(e,t,r,n,i){var o,a;let s=(o=n.formFactors)!==null&&o!==void 0?o:Mi.filter(d=>Py(i).has(d)),l=$f(s),u=QQ(i,t,(a=n.parameters)!==null&&a!==void 0?a:{}),c=d=>JSON.parse(JSON.stringify(d));return{n:"controlDescription",a:[["forControl",e]],c:[...l.defaults.map(d=>({n:"customControl",a:d===null?[["id",r]]:[["id",r],["formFactor",Mu[d]]],c:[{n:"parameters",a:[],c:[{n:"datafieldname",a:[],c:[Ty(t)]}]}]})),...l.named.map(d=>({n:"customControl",a:[["name",n.name],["formFactor",Mu[d]]],c:[{n:"parameters",a:[],c:c(u)}]}))]}}ue.newPcfDescription=tL;function Py(e){return new Set(Mi.filter(t=>e.availableOn[t]))}function kf(e){var t;let r=lr(e.c);if(r.length!==1||((t=r[0])===null||t===void 0?void 0:t.n)!=="parameters"||lr(r[0].a).length>0)return;let n=lr(r[0].c);return n.every(i=>st(i)&&!J2(i))?n:void 0}function fa(e){let t=lr(e?.c);if(t.length===0||!t.every(p=>st(p)&&p.n==="customControl"))return;let r=t.findIndex(p=>(0,V.rawAttr)(p,"name")!==void 0);if(r<=0)return;let n=t.slice(r),i=(0,V.rawAttr)(n[0],"name"),o=[];for(let p of n){let h=lr(p.a),g=h.length===2?K2.get(h[1][1]):void 0;if(!g||h[0][0]!=="name"||h[0][1]!==i||h[1][0]!=="formFactor"||o.includes(g))return;o.push(g)}let a=$f(o);if(!cn(a.named,o)||i==="")return;let s=kf(n[0]);if(!s||!n.every(p=>cn(kf(p),s)))return;let l=t.slice(0,r);if(l.length!==a.defaults.length)return;let u=(0,V.rawAttr)(l[0],"id"),c;for(let p=0;p<l.length;p+=1){let h=a.defaults[p],g=h===null?[["id",u??""]]:[["id",u??""],["formFactor",Mu[h]]],b=kf(l[p]),w=b?.length===1&&b[0].n==="datafieldname"&&lr(b[0].a).length===0?W2(b[0]):void 0;if(!u||!cn(lr(l[p].a),g)||w===void 0||c!==void 0&&w!==c)return;c=w}let d={},f={},m;for(let p of s){let h=lr(p.a),g=W2(p),b=h.map(w=>w[0]);if(g===void 0||!Z2(p.n)||Uu(d,p.n)||p.n===m)return;if((0,V.rawAttr)(p,"static")===void 0){if(m!==void 0||g!==c||!(b.length===0||cn(b,["type"])))return;m=p.n;continue}if((0,V.rawAttr)(p,"static")!=="true"||!(cn(b,["static"])||cn(b,["type","static"])))return;d[p.n]=g,f[p.n]=(0,V.rawAttr)(p,"type")}if(!(m===void 0||c===void 0||u===void 0))return{binding:{name:i,...Object.keys(d).length>0?{parameters:d}:{},...o.length===Mi.length?{}:{formFactors:o}},fieldName:c,nativeClass:u,parameterTypes:f,boundProperty:m}}ue.readPcfDescription=fa;function rL(e,t,r){return e===t?!0:typeof e!="string"&&(t===String(e)||t===Bu(r,e))}function nL(e){let t=e.formFactors;return t===void 0?[...Mi]:Array.isArray(t)?Mi.filter(r=>t.includes(r)):[]}function _y(e,t){var r,n,i;if(e.name!==t.binding.name||!cn(nL(e),(r=t.binding.formFactors)!==null&&r!==void 0?r:Mi))return!1;let o=(n=e.parameters)!==null&&n!==void 0?n:{},a=(i=t.binding.parameters)!==null&&i!==void 0?i:{},s=Object.keys(o);return s.length!==Object.keys(a).length?!1:s.every(l=>Uu(a,l)&&rL(o[l],a[l],t.parameterTypes[l]))}ue.sameAsStored=_y;function ht(e){return st(e)&&e.customControl!==void 0}ue.hasCustomControl=ht;function Fi(e,t){var r;return t?lr((r=(0,V.descriptionsRegion)(e))===null||r===void 0?void 0:r.node.c).filter(n=>n?.n==="controlDescription"&&(0,V.normGuid)((0,V.rawAttr)(n,"forControl"))===t):[]}function Ry(e,t){let r=Fi(e.bag,(0,V.controlUniqueId)(t));return r.length===1?fa(r[0]):void 0}ue.storedBindingOf=Ry;function Ly(e){let t=(0,V.effectiveFormType)(e);return t==="Main"||t==="QuickCreate"}ue.supportsPcfFormType=Ly;function XQ(e){if(!Ly(e))return;let t=(0,V.controlUniqueIds)(e);for(let{cell:r}of(0,V.typedCellSites)(e)){let n=r.control;if(!st(n)||!n.fieldName||!xi(n.classId)||t.get((0,V.controlUniqueId)(n))!==1)continue;let i=Ry(e,n);i&&i.fieldName===n.fieldName&&(n.customControl=JSON.parse(JSON.stringify(i.binding)))}}ue.projectPcfBindings=XQ;function xi(e){return typeof e=="string"&&e.replace(/^\{|\}$/g,"").toUpperCase()===V.CUSTOM_CONTROL_CLASS_ID}var un=(e,t)=>({kind:"refused",rule:e,message:t});function ZQ(e){let t=e.replace(/^\{|\}$/g,"");return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)&&!xi(e)}function z2(e,t,r){var n,i;let o=fa(r);if(!o)return un("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");if(o.fieldName!==e.fieldName)return un("pcf-binding-rebind",`the binding is filed for "${o.fieldName}": remove it, push, then bind the new column`);if(t.name!==o.binding.name)return un("pcf-binding-control-swap",`the binding uses "${o.binding.name}": to use another control, remove customControl, push, then add it`);let a=st(t.parameters)?t.parameters:{},s=(n=o.binding.parameters)!==null&&n!==void 0?n:{},l=Object.keys(a).sort();if(!cn(l,Object.keys(s).sort()))return un("pcf-binding-edit-parameter-set",`an edit changes parameter values only \u2014 the binding stores exactly ${Object.keys(s).sort().map(g=>`"${g}"`).join(", ")||"none"}: to add or remove one, remove the binding, push, then add it`);let u=l.filter(g=>!rL(a[g],s[g],o.parameterTypes[g])),c=u.find(g=>Bu(o.parameterTypes[g],a[g]).trim()==="");if(c!==void 0)return un("pcf-binding-edit-parameter-set",`"${c}" cannot be cleared in place \u2014 an empty value is not written, which removes the parameter: remove the binding, push, then add it`);let d=nL(t),f=(i=o.binding.formFactors)!==null&&i!==void 0?i:[...Mi],m=d.filter(g=>!f.includes(g)),p=f.filter(g=>!d.includes(g));if(u.length===0&&m.length===0&&p.length===0)return{kind:"unchanged"};let h=u.find(g=>!Oy(o.parameterTypes[g]));if(h!==void 0){let g=o.parameterTypes[h];return un("pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which the property editor does not write: remove the binding, push, then add it`)}return(m.length>0||p.length>0)&&!ZQ(o.nativeClass)?un("pcf-binding-edit-fallback",`the factors the control leaves fall back to "${o.nativeClass}", which is not a native control class: remove the binding, push, then add it`):{kind:"edit",description:r,stored:o,changed:u,factors:d,added:m,removed:p}}function eX(e,t){return t&&(0,V.typedCellSites)(e).find(({cell:n})=>ht(n.control)&&(0,V.controlUniqueId)(n.control)===t)?{descriptions:Fi(e.bag,t)}:void 0}function iL(e,t){let r=new Map,n=tX(e),i=new Set,o=new Map,a=u=>{let c=o.get(u);return c||(c={before:[],now:[]},o.set(u,c)),c},s=(u,c)=>({cell:iX(u),uid:(0,V.controlUniqueId)(c),bound:ht(c)});for(let{cell:u}of(0,V.typedCellSites)(e)){let c=u.control;st(c)&&typeof c.id=="string"&&c.id&&a(c.id).now.push({...s(u,c),control:c})}for(let{cell:u}of(0,V.typedCellSites)(t)){let c=u.control;if(!st(c))continue;let d=s(u,c);d.bound&&d.uid&&i.add(d.uid),typeof c.id=="string"&&c.id&&a(c.id).before.push(d)}let l=(u,c)=>{let d=u.filter(f=>f.cell===c);return d.length===1?d[0]:void 0};for(let[u,{before:c,now:d}]of o){let f=c.filter(D=>D.bound&&D.uid!==""&&!n.has(D.uid));if(f.length===0||d.length===0)continue;let m=[...c],p=D=>{let O=m.findIndex(D);return O<0?void 0:m.splice(O,1)[0]},g=d.filter(D=>!D.bound||D.uid===""?!0:p(O=>O.bound&&O.uid===D.uid)!==void 0?!1:!i.has(D.uid)).filter(D=>{let O=D.cell?l(c,D.cell):void 0;return!O||!l(d,D.cell)||!m.includes(O)?!0:(m.splice(m.indexOf(O),1),f.includes(O)&&D.uid!==O.uid&&j2(D.control)&&r.set(D.control,H2(O.uid)),!1)}),b=[],w=(D,O)=>{let x=D.uid===""?void 0:p(K=>K.uid===D.uid&&(!O||K.bound===D.bound));return x&&f.includes(x)&&b.push(x),x!==void 0},S=g.filter(D=>!w(D,!0)).filter(D=>!w(D,!1)&&j2(D.control)),P=f.filter(D=>m.includes(D));if(S.length===0||P.length===0&&b.length===0)continue;let L=[...P,...b],I=P.length===1&&S.length===1&&m.length===1?H2(P[0].uid):`the controls with id "${u}" cannot all be matched to those last synced \u2014 their cells do not tell them apart \u2014 and ${L.map(D=>`{${D.uid}}`).join(", ")} no longer ${L.length===1?"names":"name"} a control: which control held ${L.length===1?"that binding":"those bindings"} is ambiguous. Re-fetch the form; to drop a bound control, remove its customControl and push before removing the control`;for(let D of S)r.set(D.control,I)}return r}function tX(e){let t=(0,V.controlUniqueIds)(e),r=new Map;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=st(i.control)?(0,V.controlUniqueId)(i.control):"";o&&!r.has(o)&&r.set(o,i.control)}let n=new Set;for(let[i,o]of t){let a=r.get(i);(a===void 0||ht(a)||o>1)&&n.add(i)}return n}function j2(e){return ht(e)||e.genPage===void 0&&xi((0,V.effectiveClassId)(e))}function rX(e,t){let r=o=>(0,V.typedCellSites)(o).flatMap(({cell:a,pointer:s})=>{let l=a.control;if(!st(l)||ht(l)||l.genPage!==void 0||!xi((0,V.effectiveClassId)(l)))return[];let u=(0,V.controlUniqueId)(l);return u===""||Fi(o.bag,u).length===0?[{control:l,pointer:`${s}/control`}]:[]}),n=o=>`${String(o.id)}\0${(0,V.controlUniqueId)(o)}`,i=r(t).map(({control:o})=>n(o));return r(e).filter(({control:o})=>{let a=i.indexOf(n(o));return a<0?!0:(i.splice(a,1),!1)})}var nX="this control would keep the custom-control class with no binding (its customControl and uniqueid are gone): remove the binding from an unchanged copy \u2014 keep its uniqueid, and the native control comes back \u2014 or set classId to the column's native control";function H2(e){return`this control's uniqueid changed since it was last synced (it was {${e}}), and a binding is linked to its description by it: restore it (re-fetch the form), or remove the binding, push, then add the new one`}function iX(e){let t=typeof e.id=="string"?e.id.trim():"";return(0,V.normGuid)(t)||t.toLowerCase()}function qu(e,t,r,n){let i=t.customControl,o=(0,V.controlUniqueId)(t),a=Fi(e.bag,o),s=r?iL(e,r).get(t):void 0;if(s!==void 0)return un("pcf-binding-unique-id",s);let l=r?eX(r,o):void 0;if(l){let c=l.descriptions,d=c.length===1?fa(c[0]):void 0;if(d&&d.fieldName!==t.fieldName)return un("pcf-binding-rebind",`the binding is filed for "${d.fieldName}": remove it, push, then bind the new column`);if(c.length===1&&a.length===1&&cn(c[0],a[0]))return z2(t,i,a[0]);let f=a.length===1?fa(a[0]):void 0;return d&&f&&f.fieldName===t.fieldName&&_y(i,d)&&_y(i,f)?{kind:"unchanged"}:un("pcf-binding-edit-changed-description","the binding\u2019s description changed since it was last synced (edited in the bag, re-keyed or deleted): re-fetch the form before changing the binding")}if(a.length===0)return{kind:"new"};if(a.length>1)return un("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");let u=z2(t,i,a[0]);return n&&(u.kind==="edit"||u.kind==="unchanged")?u.kind==="unchanged"?u:un("pcf-binding-edit","this binding\u2019s description was never synced from the server (no baseline): changing it in place is not supported \u2014 remove customControl, push, then add the new one"):u}ue.planPcfBinding=qu;function oL(e){return e.kind==="edit"&&(e.changed.length>0||e.added.length>0)}function oX(e){let t=n=>ht(n.control)&&(!n.control.id||!n.id||(0,V.authoredUniqueId)(n.control)===void 0);if(!(0,V.typedCellSites)(e).some(({cell:n})=>t(n)))return e;let r=JSON.parse(JSON.stringify(e));for(let{cell:n}of(0,V.typedCellSites)(r)){if(!t(n))continue;let i=n.control;i.id||(i.id=(0,G2.newId)()),n.id||(n.id=(0,G2.newId)()),(0,V.authoredUniqueId)(i)===void 0&&(0,V.setUniqueId)(i)}return r}ue.mintPcfIdentity=oX;function aX(e,t){let r=new Set,n=new Set;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=i.control;if(!ht(o)||!st(o.customControl))continue;let a=o.customControl.name;if(typeof a!="string"||a===""||typeof o.fieldName!="string"||!o.fieldName)continue;let s=qu(e,o,t,!0);s.kind==="new"?(r.add(a),n.add(o.fieldName)):oL(s)&&r.add(a)}return{controls:[...r],columns:[...n],...n.size>0&&(0,V.effectiveFormType)(e)==="QuickCreate"?{requireCreateEligibility:!0}:{}}}ue.customControlNeeds=aX;function sX(e,t,r){var n,i,o,a,s,l;let u=e.bag,c=new Map;for(let{cell:f,pointer:m}of(0,V.typedCellSites)(e)){let p=f.control;if(!ht(p)||!st(p.customControl))continue;let h=(0,V.controlUniqueId)(p);h&&Fi(u,h).length>0&&c.set(p,{plan:qu(e,p,t,!0),pointer:`${m}/control/customControl`})}let d=(0,V.descriptionsRegion)(u);if(d&&t){let f=(0,V.controlUniqueIds)(e),m=new Set,p=new Map;for(let{cell:h}of(0,V.typedCellSites)(e)){let g=st(h.control)?(0,V.controlUniqueId)(h.control):"";g&&!p.has(g)&&p.set(g,h.control)}for(let{cell:h}of(0,V.typedCellSites)(t)){let g=h.control;if(!ht(g))continue;let b=(0,V.controlUniqueId)(g),w=Fi(t.bag,b),E=Fi(u,b);if(w.length!==1||E.length!==1||!cn(w[0],E[0])||!fa(E[0]))continue;let S=p.get(b);if(S&&!ht(S)){if(((n=f.get(b))!==null&&n!==void 0?n:0)>1)continue;let P=(o=(i=fa(E[0]))===null||i===void 0?void 0:i.nativeClass)!==null&&o!==void 0?o:"";S.classId=P.replace(/^\{|\}$/g,"").toUpperCase(),lX(S,"uniqueid"),m.add(b)}else!S&&!f.has(b)&&m.add(b)}m.size>0&&(d.node.c=lr(d.node.c).filter(h=>!(h?.n==="controlDescription"&&m.has((0,V.normGuid)((0,V.rawAttr)(h,"forControl"))))))}for(let{cell:f}of(0,V.typedCellSites)(e)){let m=f.control;if(!ht(m)||!st(m.customControl))continue;xi(m.classId)||(m.classId=V.CUSTOM_CONTROL_CLASS_ID);let p=(0,V.controlUniqueId)(m);if(!p){if((0,V.authoredUniqueId)(m)!==void 0)continue;p=(0,V.setUniqueId)(m)}let h=c.get(m);if(h){if(h.plan.kind==="refused")throw new jQ.ValidationError("form",e.id,[(0,Ce.issue)(h.pointer,h.plan.rule,h.plan.message)]);h.plan.kind==="edit"&&uX(h.plan,m.customControl);continue}let g=r?.control(m.customControl.name),b=r?.column(e.entityLogicalName,m.fieldName),w=b?.kind==="found"?Dy(b.value):void 0;if(g?.kind!=="found"||!w)continue;d||(d={i:(0,V.embedAppendIndex)(u),node:{n:"controlDescriptions",a:[],c:[]}},u.c.push(d));let E=((l=(s=lr((a=m.bag)===null||a===void 0?void 0:a.a).find(P=>P[0]==="uniqueid"))===null||s===void 0?void 0:s[1])!==null&&l!==void 0?l:"").trim(),S=E.startsWith("{")?E:`{${p}}`;d.node.c.push(tL(S,m.fieldName,w,m.customControl,g.value))}}ue.reconcilePcfDescriptions=sX;function lX(e,t){st(e.bag)&&(e.bag.a=lr(e.bag.a).filter(r=>r[0]!==t))}function uX(e,t){var r,n;let i=lr(e.description.c),o=i.findIndex(g=>(0,V.rawAttr)(g,"name")!==void 0),a=i.slice(0,o),s=i.slice(o),l=(r=t.parameters)!==null&&r!==void 0?r:{};for(let g of s)for(let b of(n=kf(g))!==null&&n!==void 0?n:[])e.changed.includes(b.n)&&(b.c=[Ty(Bu(e.stored.parameterTypes[b.n],l[b.n]))]);if(e.added.length===0&&e.removed.length===0)return;let u=g=>JSON.parse(JSON.stringify(g)),c=g=>{var b;let w=(0,V.rawAttr)(g,"formFactor");return w===void 0?null:(b=K2.get(w))!==null&&b!==void 0?b:null},d=(0,V.rawAttr)(a[0],"id"),f=(0,V.rawAttr)(s[0],"name"),m=$f(e.factors),p=m.defaults.map(g=>{let b=a.find(E=>c(E)===g);if(b)return b;let w=u(a[0]);return w.a=g===null?[["id",d]]:[["id",d],["formFactor",Mu[g]]],w}),h=m.named.map(g=>{let b=s.find(E=>c(E)===g);if(b)return b;let w=u(s[0]);return w.a=[["name",f],["formFactor",Mu[g]]],w});e.description.c=[...p,...h]}function cX(e){return(0,V.typedCellSites)(e).some(({cell:t})=>ht(t.control))}ue.mayCommitPcfState=cX;function dX(e,t){var r;let n=JSON.parse(JSON.stringify(e)),i=!1;for(let{cell:o}of(0,V.typedCellSites)(n)){let a=o.control;if(!ht(a))continue;let s=Ry(n,a);if(!s||s.fieldName!==a.fieldName)continue;let l=t(V.CUSTOM_CONTROL_CLASS_ID),u=lr((r=a.bag)===null||r===void 0?void 0:r.a).find(c=>c[0]==="classid");(!xi(a.classId)||a.type!==l||u!==void 0&&!xi(u[1])||!cn(a.customControl,s.binding))&&(xi(a.classId)||(a.classId=V.CUSTOM_CONTROL_CLASS_ID),a.type=l,u&&!xi(u[1])&&(u[1]=Y2(V.CUSTOM_CONTROL_CLASS_ID)),a.customControl=JSON.parse(JSON.stringify(s.binding)),i=!0)}return i?n:e}ue.commitPcfState=dX;var fX=new Set(["name","parameters","formFactors"]);function pX(e,t,r){let n=[],i=(0,V.controlUniqueIds)(e);for(let{cell:o,pointer:a}of(0,V.typedCellSites)(e)){let s=o.control;ht(s)&&hX(e,s,`${a}/control`,i,n,t,r?.atPush===!0)}return t&&gX(e,t,n),n}ue.pcfBindingIssues=pX;function mX(e,t,r){let n=r.length;if(!st(e))return r.push((0,Ce.issue)(t,"pcf-binding-shape","customControl must be an object")),!1;for(let i of Object.keys(e))fX.has(i)||r.push((0,Ce.issue)(`${t}/${i}`,"pcf-binding-unknown-key",`customControl has no "${i}"`));if((typeof e.name!="string"||e.name.trim()==="")&&r.push((0,Ce.issue)(`${t}/name`,"pcf-binding-shape","name must be the control's non-empty customcontrols name")),e.parameters!==void 0)if(!st(e.parameters))r.push((0,Ce.issue)(`${t}/parameters`,"pcf-binding-shape","parameters must be an object"));else for(let[i,o]of Object.entries(e.parameters))typeof o=="string"||typeof o=="boolean"||typeof o=="number"&&Number.isFinite(o)||r.push((0,Ce.issue)(`${t}/parameters/${i}`,"pcf-binding-shape","a parameter must be a string, a finite number or a boolean"));if(e.formFactors!==void 0){let i=e.formFactors;Array.isArray(i)&&i.length>0&&i.every(a=>typeof a=="string"&&Mi.includes(a))&&new Set(i).size===i.length||r.push((0,Ce.issue)(`${t}/formFactors`,"pcf-binding-shape","formFactors must be distinct 'web', 'phone' and 'tablet', at least one"))}return r.length===n}function hX(e,t,r,n,i,o,a){var s;let l=`${r}/customControl`,u=mX(t.customControl,l,i);t.fieldName||i.push((0,Ce.issue)(l,"pcf-binding-unbound","a PCF binding needs a control bound to a column (fieldName)")),t.genPage!==void 0&&i.push((0,Ce.issue)(l,"pcf-binding-with-genpage","a control cannot embed a page and bind a PCF control")),Ly(e)||i.push((0,Ce.issue)(l,"pcf-binding-form-type","PCF bindings are supported on Main and Quick Create forms only (not Quick View or Card)")),t.classId!==void 0&&typeof t.classId!="string"&&i.push((0,Ce.issue)(`${r}/classId`,"pcf-binding-class-id","classId must be a string"));let c=(0,V.authoredUniqueId)(t),d=(0,V.controlUniqueId)(t);if(c!==void 0&&!d?i.push((0,Ce.issue)(`${r}/bag`,"pcf-binding-unique-id","the control's uniqueid must be a GUID")):d&&((s=n.get(d))!==null&&s!==void 0?s:0)>1&&i.push((0,Ce.issue)(`${r}/bag`,"pcf-binding-unique-id","another control carries the same uniqueid")),!u)return;let f=qu(e,t,o,a);f.kind==="refused"&&i.push((0,Ce.issue)(l,f.rule,f.message))}function gX(e,t,r){var n;let i=new Map,o=iL(e,t);for(let{cell:l,pointer:u}of(0,V.typedCellSites)(e)){let c=st(l.control)?(0,V.controlUniqueId)(l.control):"";if(c&&!i.has(c)&&i.set(c,{control:l.control,pointer:`${u}/control`}),st(l.control)&&!ht(l.control)){let d=o.get(l.control);d!==void 0&&r.push((0,Ce.issue)(`${u}/control`,"pcf-binding-unique-id",d))}}let a=(0,V.controlUniqueIds)(e);for(let{cell:l}of(0,V.typedCellSites)(t)){if(!ht(l.control))continue;let u=(0,V.controlUniqueId)(l.control),c=i.get(u);!c||ht(c.control)||(((n=a.get(u))!==null&&n!==void 0?n:0)>1?r.push((0,Ce.issue)(c.pointer,"pcf-binding-unique-id","another control carries this binding\u2019s uniqueid; removing the binding would delete its description too")):cn(Fi(t.bag,u),Fi(e.bag,u))?c.control.fieldName!==l.control.fieldName&&r.push((0,Ce.issue)(c.pointer,"pcf-binding-rebind","remove the binding, push, then bind the new column")):r.push((0,Ce.issue)(c.pointer,"pcf-binding-removed-changed","the binding changed since it was last pushed; remove it from an unchanged copy (re-fetch)")))}let s=new Set(r.map(l=>l.pointer));for(let{pointer:l}of rX(e,t))s.has(l)||r.push((0,Ce.issue)(l,"pcf-binding-unique-id",nX))}var yX=new Set(["Form.Card"]),bX="MscrmControls.ModelForm.ModelFormControl";function aL(e,t){var r;if(e.hasDataset||e.hasGroups)return"it has a data-set or groups";if(!e.isBound)return"its first property is not bound to a column";let n=e.properties;if(n.filter(s=>s.usage==="bound").length!==1)return"it has more than one bound property";let i=n.map(s=>s.name);if(i.some(s=>!s)||new Set(i).size!==i.length)return"a property has no name, or two share one";let o=i.find(s=>!Z2(s));if(o!==void 0)return`the property name "${o}" cannot be written as an element`;if(t===bX||n.some(s=>s.defaultType!==void 0&&yX.has(s.defaultType)))return"a property needs a special encoding";if(n.some(s=>s.usage==="output"&&s.defaultValue!==null&&s.defaultValue!==""))return"an output property has a default";let a=n.find(s=>s.usage==="input"&&!Oy(s.defaultType));return a?`input "${a.name}" has a type the property editor does not write as text (${(r=a.defaultType)!==null&&r!==void 0?r:"none"})`:void 0}function vX(e){return e.ofType!==null?[e.ofType]:e.ofTypeGroup}function sL(e,t,r=e.defaultType){if(r==="Enum")return e.enumValues.some(o=>o.value===String(t))?void 0:`must be one of ${e.enumValues.map(o=>`"${o.value}"`).join(", ")}`;let n=r!==void 0?Iy.get(r):void 0;if(n){let o=typeof t=="boolean"?void 0:eL(t);return o===void 0||o<n.min||o>n.max?`must be a number from ${n.min.toFixed(n.digits)} through ${n.max.toFixed(n.digits)}`:void 0}if(r!==void 0&&Q2.has(r))return t===!0||t===!1||t==="true"||t==="false"?void 0:"must be true or false";let i=r!==void 0?JQ.get(r):void 0;return i!==void 0&&String(t).length>i?`must be at most ${i} characters`:e.required&&String(t)===""?"is required":void 0}function wX(e,t,r){var n,i,o,a;let s={issues:[]},l=s.issues;for(let{cell:u,pointer:c}of(0,V.typedCellSites)(e)){let d=u.control;if(!ht(d)||!d.fieldName)continue;let f=d.customControl;if(!st(f)||typeof f.name!="string")continue;let m=`${c}/control/customControl`,p=qu(e,d,r,!0);if(p.kind==="edit"){oL(p)&&AX(p,f,m,t,s);continue}if(p.kind!=="new")continue;let h=t?.control(f.name),g=t?.column((n=e.entityLogicalName)!==null&&n!==void 0?n:"",d.fieldName);if(!h||h.kind==="unavailable"){(i=s.unavailable)!==null&&i!==void 0||(s.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${f.name}" could not be read`,...h?.kind==="unavailable"?{cause:h.error}:{}});continue}if(h.kind!=="found"){l.push((0,Ce.issue)(`${m}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${f.name}" (${h.kind})`));continue}if(!g||g.kind==="unavailable"){(o=s.unavailable)!==null&&o!==void 0||(s.unavailable={code:"PCF_COLUMN_UNAVAILABLE",message:`the column "${d.fieldName}" could not be read`,...g?.kind==="unavailable"?{cause:g.error}:{}});continue}let b=aL(h.value,f.name);if(b){l.push((0,Ce.issue)(`${m}/name`,"pcf-binding-unsupported-control",`"${f.name}" is not supported: ${b}`));continue}let w=h.value.properties.find(x=>x.isPrimary),E=g.kind==="found"?g.value:void 0,S=E?(a=(0,HQ.manifestTypesForColumn)(E.attributeTypeName,E.format,E.formatName))!==null&&a!==void 0?a:[]:[];E!==void 0&&!E.isPrimaryId&&E.isValidForForm&&Dy(E)!==void 0&&vX(w).some(x=>S.includes(x))?(0,V.effectiveFormType)(e)==="QuickCreate"&&E?.isValidForCreate!==!0&&l.push((0,Ce.issue)(m,"pcf-binding-quick-create-column",`"${d.fieldName}" cannot be set when a record is created, so a Quick Create form cannot bind it`)):l.push((0,Ce.issue)(m,"pcf-binding-incompatible-column",`"${f.name}" cannot be bound to "${d.fieldName}"`));let L=new Map(h.value.properties.filter(x=>x.usage==="input").map(x=>[x.name,x])),I=st(f.parameters)?f.parameters:{};for(let[x,K]of Object.entries(I)){let Re=L.get(x);if(!Re){l.push((0,Ce.issue)(`${m}/parameters/${x}`,"pcf-binding-unknown-parameter",`"${f.name}" has no input "${x}"`));continue}let qt=sL(Re,K);qt&&l.push((0,Ce.issue)(`${m}/parameters/${x}`,"pcf-binding-parameter-value",`"${x}" ${qt}`))}for(let x of L.values())x.required&&!Uu(I,x.name)&&!x.defaultValue&&l.push((0,Ce.issue)(`${m}/parameters`,"pcf-binding-missing-parameter",`"${x.name}" is required`));let D=Py(h.value),O=Array.isArray(f.formFactors)?f.formFactors:void 0;(O?O.some(x=>!D.has(x)):D.size===0)&&l.push((0,Ce.issue)(`${m}/formFactors`,"pcf-binding-form-factor",`"${f.name}" is available on ${D.size===0?"no form factor":[...D].join(", ")}`))}return s}ue.pcfReadIssues=wX;function CX(e,t){return t===void 0||!Oy(t)?!1:e.ofType!==null?e.ofType===t:e.ofTypeGroup.includes(t)}function EX(e,t,r){var n,i;let o=aL(e,t);if(o)return`it is no longer supported (${o})`;let a=e.properties.find(d=>d.isPrimary);if(a?.name!==r.boundProperty)return`its bound property is now "${(n=a?.name)!==null&&n!==void 0?n:"none"}", not "${r.boundProperty}"`;let s=(i=r.binding.parameters)!==null&&i!==void 0?i:{},l=new Set(e.properties.filter(d=>d.usage==="input").map(d=>d.name)),u=Object.keys(s).find(d=>!l.has(d));if(u!==void 0)return`"${u}" is no longer one of its inputs`;let c=e.properties.find(d=>d.usage==="input"&&d.required&&!d.defaultValue&&!Uu(s,d.name));return c?`it now requires "${c.name}", which the binding does not store`:void 0}function AX(e,t,r,n,i){var o,a,s;let l=i.issues,u=n?.control(t.name);if(!u||u.kind==="unavailable"){(o=i.unavailable)!==null&&o!==void 0||(i.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${t.name}" could not be read`,...u?.kind==="unavailable"?{cause:u.error}:{}});return}if(u.kind!=="found"){l.push((0,Ce.issue)(`${r}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${t.name}" (${u.kind})`));return}let c=EX(u.value,t.name,e.stored);if(c){l.push((0,Ce.issue)(r,"pcf-binding-edit-manifest-changed",`"${t.name}" changed since this binding was written: ${c} \u2014 remove the binding, push, then add it`));return}let d=new Map(u.value.properties.filter(h=>h.usage==="input").map(h=>[h.name,h])),f=l.length;for(let h of Object.keys((a=e.stored.binding.parameters)!==null&&a!==void 0?a:{})){let g=e.stored.parameterTypes[h];CX(d.get(h),g)||l.push((0,Ce.issue)(`${r}/parameters/${h}`,"pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which "${t.name}" does not take for it now: remove the binding, push, then add it`))}if(l.length>f)return;let m=(s=t.parameters)!==null&&s!==void 0?s:{};for(let h of e.changed){let g=sL(d.get(h),m[h],e.stored.parameterTypes[h]);g&&l.push((0,Ce.issue)(`${r}/parameters/${h}`,"pcf-binding-parameter-value",`"${h}" ${g}`))}let p=Py(u.value);e.added.some(h=>!p.has(h))&&l.push((0,Ce.issue)(`${r}/formFactors`,"pcf-binding-form-factor",`"${t.name}" is available on ${p.size===0?"no form factor":[...p].join(", ")}`))}});var SL=v(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.classIdForAttributeType=Or.QUICK_VIEW_CLASS_ID=Or.NOTES_CLASS_ID=Or.SUBGRID_CLASS_ID=Or.formRegistration=Or.FormAdapter=void 0;var Ui=(pt(),Fr(d_)),uL=(ot(),Fr(f_)),SX=(Dt(),Fr(m_)),gt=(le(),Fr(p_)),tt=(ta(),Fr(h_)),NX=(cy(),Fr($2)),_X=(F2(),Fr(x2)),yt=so(),cL=Jr(),Ir=en(),TX=vg(),Ws=dt(),DX=Ny(),Xt=wd(),ni=lL(),Gs=Q(),Uy=se(),ky=lo(),gL=Ho(),IX={[gt.FormType.Main]:"Main",[gt.FormType.QuickCreate]:"QuickCreate",[gt.FormType.QuickViewForm]:"QuickView",[gt.FormType.Card]:"Card"},xf={Main:gt.FormType.Main,QuickCreate:gt.FormType.QuickCreate,QuickView:gt.FormType.QuickViewForm,Card:gt.FormType.Card},OX=new Map(Object.entries(tt.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function By(e){var t;return e&&(t=OX.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function Vu(e){return e.getAllProperties().map(t=>[t.key,t.value])}function pa(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function yL(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function qy(e,t){var r,n;let i=yL(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(r=o.find(s=>pa(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return a&&(n=pa(a).get("description"))!==null&&n!==void 0?n:""}function PX(e){let t=yL(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 o=n.getAllChildren()[0],a=o?o.getNodeName():"";a.charAt(0)==="<"&&(a=a.substring(1)),r[i]=a}return r}function bL(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function $y(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function Gu(e){return String(e??"").replace(/[{}]/g,"")}function xy(e){return`{${Gu(e)}}`}function Fy(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function Mf(e,t,r){let n=e.getAllChildren(),i=n.findIndex(u=>u.getNodeName()===t),o=[];if(n.forEach((u,c)=>{c!==i&&o.push({i:c,node:(0,yt.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:Vu(e),c:o}};let a=n[i],s=[],l=[];return a.getAllChildren().forEach((u,c)=>{u.getNodeName()===r?s.push(u):l.push({i:c,node:(0,yt.rawFromNode)(u)})}),{modeled:s,bag:{a:Vu(e),c:o,w:{n:a.getNodeName(),a:Vu(a),c:l}}}}function vL(e,t,r){let n=[],i=[];return e.getAllChildren().forEach((o,a)=>{o.getNodeName()===t&&(!r||n.length===0)?n.push(o):i.push({i:a,node:(0,yt.rawFromNode)(o)})}),{modeled:n,bag:{a:Vu(e),c:i}}}function dL(e,t){let{modeled:r,bag:n}=Mf(e,"tabs","tab");return{tabs:r.map(i=>RX(i,t)),bag:n}}function RX(e,t){var r,n;let i=pa(e),{modeled:o,bag:a}=Mf(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:qy(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:o.map(s=>LX(s,t)),bag:a}}function LX(e,t){let r=pa(e),{modeled:n,bag:i}=Mf(e,"sections","section");return{width:r.get("width"),sections:n.map(o=>kX(o,t)),bag:i}}function kX(e,t){var r,n,i;let o=pa(e),{modeled:a,bag:s}=Mf(e,"rows","row");return{id:(r=o.get("id"))!==null&&r!==void 0?r:"",name:(n=o.get("name"))!==null&&n!==void 0?n:"",label:qy(e,t),visible:o.has("visible")?o.get("visible")==="true":!0,showLabel:o.get("showlabel")==="true",columns:bL((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(l=>$X(l,t)),bag:s}}function $X(e,t){let{modeled:r,bag:n}=vL(e,"cell",!1);return{cells:r.map(i=>xX(i,t)),bag:n}}function xX(e,t){var r;let n=pa(e),{modeled:i,bag:o}=vL(e,"control",!0),a=qy(e,t),s=n.get("showlabel")==="true",l=i[0]?FX(i[0],a,s):null;return{id:(r=n.get("id"))!==null&&r!==void 0?r:"",visible:n.has("visible")?n.get("visible")==="true":!0,colspan:Fy(n.get("colspan"),1),rowspan:Fy(n.get("rowspan"),1),control:l,bag:o}}function FX(e,t,r){var n,i;let o=pa(e),a=Gu((n=o.get("classid"))!==null&&n!==void 0?n:""),s=o.get("datafieldname");return{id:(i=o.get("id"))!==null&&i!==void 0?i:"",classId:a,fieldName:s||null,type:By(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:r,parameters:PX(e),bag:{a:Vu(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,yt.rawFromNode)(l)}))}}}function No(e){return e.a.length===0&&e.c.length===0&&!e.w}function wL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function ma(e,t){var r;let n=new Set(e.a.map(a=>a[0])),i=No(e),o=[];for(let a of t)if(n.has(a.key)){let s=(r=wL(e,a.key))!==null&&r!==void 0?r:"";a.matches(s)||o.push([a.key,a.render()])}else i?o.push([a.key,a.render()]):a.matches(a.absentDefault)||o.push([a.key,a.render()]);return(0,yt.mergeAttrs)(e.a,o)}var Ao=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),So=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),fL=(e,t,r=1)=>({key:e,matches:n=>Fy(n,r)===t,render:()=>String(t),absentDefault:String(r)});function Vy(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function My(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>{var r;return{n:(0,Uy.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${(r=e[t])!==null&&r!==void 0?r:""}`,a:[],c:[]}]}})}}function MX(e,t){var r,n;let i=e.c.find(a=>a.n==="label"&&a.a.some(s=>s[0]==="languagecode"&&s[1]===String(t))),o=i??e.c.find(a=>a.n==="label");return(n=(r=o?.a.find(a=>a[0]==="description"))===null||r===void 0?void 0:r[1])!==null&&n!==void 0?n:""}function UX(e,t,r){let n=!1,i=e.c.map(o=>o.n!=="label"||!o.a.some(s=>s[0]==="languagecode"&&s[1]===String(r))?o:(n=!0,{...o,a:o.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 Gy(e,t,r){let n=e.c.findIndex(o=>o.node.n==="labels");if(n<0){if(!t||No(e))return e;let a=e.c.some(s=>s.i===0)?e.c.map(s=>({...s,i:s.i+1})):e.c;return{...e,c:[{i:0,node:Vy(t,r)},...a]}}if(MX(e.c[n].node,r)===t)return e;let i=UX(e.c[n].node,t,r);return{...e,c:e.c.map((o,a)=>a===n?{...o,node:i}:o)}}function BX(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],o=i?i.n:"";o.charAt(0)==="<"&&(o=o.substring(1)),t[n]=o}return t}function qX(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function VX(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function GX(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||No(e))return e;let i=e.c.reduce((o,a)=>a.i>o?a.i:o,-1);return{...e,c:[...e.c,{i:i+1,node:My(t)}]}}if(qX(BX(e.c[r].node),t))return e;let n=My(t);return{...e,c:e.c.map((i,o)=>o===r?{...i,node:n}:i)}}function Uf(e,t,r,n){if(e.w){let a={n:e.w.n,a:e.w.a.map(s=>[s[0],s[1]]),c:(0,yt.spliceChildren)(e.w.c,r)};return(0,yt.spliceChildren)(e.c,[a])}let i=n(),o={n:t,a:[],c:r};return e.c.length===0?[...i,o]:(0,yt.spliceChildren)(e.c,[...i,o])}function WX(e,t){let r=e.tabs.map(n=>zX(n,t));return{n:"form",a:ma(e.bag,[]),c:e.tabs.length===0&&No(e.bag)?[]:Uf(e.bag,"tabs",r,()=>[])}}function CL(e,t,r){return t&&!e.c.some(n=>n.node.n==="labels")?[Vy(t,r)]:[]}function zX(e,t){let r=[Ao("id",e.id),Ao("name",e.name),So("expanded",e.expanded),So("visible",e.visible,!0)],n=e.columns.map(o=>jX(o,t)),i=Gy(e.bag,e.label,t);return{n:"tab",a:ma(i,r),c:Uf(i,"columns",n,()=>CL(i,e.label,t))}}function jX(e,t){let r=e.width!==void 0?[Ao("width",e.width)]:[],n=e.sections.map(i=>HX(i,t));return{n:"column",a:ma(e.bag,r),c:Uf(e.bag,"sections",n,()=>[])}}function HX(e,t){let r=[Ao("id",e.id),Ao("name",e.name),So("showlabel",e.showLabel),So("visible",e.visible,!0),{key:"columns",matches:o=>bL(o)===e.columns,render:()=>$y(e.columns),absentDefault:$y(1)}],n=e.rows.map(o=>KX(o,t)),i=Gy(e.bag,e.label,t);return{n:"section",a:ma(i,r),c:Uf(i,"rows",n,()=>CL(i,e.label,t))}}function KX(e,t){let r=e.cells.map(n=>JX(n,t));return{n:"row",a:ma(e.bag,[]),c:No(e.bag)?r:(0,yt.assembleChildren)(e.bag,r)}}function JX(e,t){let r=e.control?e.control.showLabel:wL(e.bag,"showlabel")==="true",n=[Ao("id",e.id),So("showlabel",r),So("visible",e.visible,!0),fL("colspan",e.colspan),fL("rowspan",e.rowspan)],i=e.control?[YX(e.control)]:[],o;if(No(e.bag))o=[...e.control&&e.control.label?[Vy(e.control.label,t)]:[],...i];else{let a=e.control?Gy(e.bag,e.control.label,t):e.bag;o=(0,yt.assembleChildren)(a,i)}return{n:"cell",a:ma(e.bag,n),c:o}}function YX(e){let t=[Ao("id",e.id),{key:"classid",matches:i=>Gu(i)===e.classId,render:()=>xy(e.classId||String(tt.ControlClassId.TextboxControl)),absentDefault:""}];e.fieldName!==null&&t.push(Ao("datafieldname",e.fieldName)),t.push(So("disabled",e.isReadOnly)),t.push(So("isrequired",e.isRequired));let r=e.fieldName===null?VX(e.bag,"datafieldname"):e.bag,n;return No(r)?n=Object.keys(e.parameters).length>0?[My(e.parameters)]:[]:n=(0,yt.assembleChildren)(GX(r,e.parameters),[]),{n:"control",a:ma(r,t),c:n}}var QX={make:(e,t)=>new SX.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function pL(e,t,r,n){(0,ky.installDomShim)();let i=ZX(e,r);(0,Xt.reconcileEmbedDescriptions)(i,n),(0,ni.reconcilePcfDescriptions)(i,n,r?.pcf);let o=(0,yt.rebuildRaw)(WX(i,t),QX,null);return new _X.SerializationService(t).serializeFormXmlNode(o)}function XX(e){return JSON.parse(JSON.stringify(e))}function ZX(e,t){let r=XX(e);r.bag||(r.bag=(0,yt.emptyBag)()),r.tabs||(r.tabs=[]),sZ(r.bag),t&&eZ(r,t);for(let n of r.tabs)tZ(n);return r}function eZ(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";Wy(e,i=>{let o=i.fieldName,a=i;if(!o||a.label!==void 0&&a.classId!==void 0)return;let s=t.resolveField(n,o);s&&(a.label===void 0&&s.displayName&&(a.label=s.displayName),a.classId===void 0&&s.attributeType&&(a.classId=AL(s.attributeType)))})}function mL(e){let t=[];return Wy(e,r=>t.push(r)),t}function Wy(e,t){var r,n,i,o,a;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(o=u.rows)!==null&&o!==void 0?o:[])for(let d of(a=c.cells)!==null&&a!==void 0?a:[])d.control&&t(d.control)}function tZ(e){e.id||(e.id=Ui.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)rZ(t);e.bag||(e.bag=(0,yt.emptyBag)())}function rZ(e){e.sections||(e.sections=[]);for(let t of e.sections)nZ(t);e.bag||(e.bag=(0,yt.emptyBag)()),e.width===void 0&&No(e.bag)&&(e.width="100%")}function nZ(e){e.id||(e.id=Ui.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)iZ(t);e.bag||(e.bag=(0,yt.emptyBag)())}function iZ(e){e.cells||(e.cells=[]);for(let t of e.cells)oZ(t);e.bag||(e.bag=(0,yt.emptyBag)())}function oZ(e){(0,Xt.hasGenPage)(e.control)&&(0,Xt.applyEmbedCellDefaults)(e),e.id||(e.id=Ui.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&&aZ(e.control),e.bag||(e.bag=(0,yt.emptyBag)())}function aZ(e){var t;(0,Xt.hasGenPage)(e)&&(0,Xt.applyEmbedControlDefaults)(e),e.id||(e.id=Ui.Guid.NewGuid()),(e.classId===void 0||e.classId===null)&&(e.classId=String(tt.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":By(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,Uy.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,yt.emptyBag)())}function sZ(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 o of i.c)o.n==="Handler"&&!hL(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",xy(Ui.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!hL(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",xy(Ui.Guid.NewGuid())])}}var Ff=class{constructor(t=gL.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,o;let{tabs:a,bag:s}=dL(t,this.lcid),l={id:t.formId?t.formId.guidString:"",name:(n=t.formName)!==null&&n!==void 0?n:"",entityLogicalName:(i=t.entityName)!==null&&i!==void 0?i:"",formType:(o=IX[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:a,bag:s};return(0,Xt.projectGenPageEmbeds)(l),(0,ni.projectPcfBindings)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:pL(t,this.lcid),formid:t.id||(0,Ws.newId)(),objecttypecode:t.entityLogicalName,type:xf[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:gt.FormPresentation.AirForm,formactivationstate:t.status==="Active"?gt.FormActivationState.Active:gt.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,o,a,s,l;let u=t,c=(r=u.formxml)!==null&&r!==void 0?r:"",d={formxml:c,formid:(n=u.formid)!==null&&n!==void 0?n:(0,Ws.newId)(),objecttypecode:(i=u.objecttypecode)!==null&&i!==void 0?i:"",type:u.type,name:(o=u.name)!==null&&o!==void 0?o:"",uniquename:(a=u.uniquename)!==null&&a!==void 0?a:"",description:(s=u.description)!==null&&s!==void 0?s:"",formpresentation:u.formpresentation,formactivationstate:u.formactivationstate};(0,ky.installDomShim)();let f=uL.ScriptUtilities.ParseXml(c),m=lZ(f),p=this.deserializeDocument(d,f);return uZ(this.toArtifact(p,(l=u.description)!==null&&l!==void 0?l:void 0),m)}toApiPayload(t,r,n){let i=(0,Xt.genPageEmbedIssues)(t);if(i.length>0)throw new Gs.ValidationError("form",t.id,i);let o=(0,ni.pcfBindingIssues)(t,r,{atPush:!0});if(o.length>0)throw new Gs.ValidationError("form",t.id,o);let a=(0,ni.pcfReadIssues)(t,n?.pcf,r);if(a.unavailable)throw(0,Gs.attachCause)(new Gs.SdkError(a.unavailable.code,a.unavailable.message),a.unavailable.cause);if(a.issues.length>0)throw new Gs.ValidationError("form",t.id,a.issues);return{formxml:pL(t,this.lcid,n,r),name:t.name,type:xf[t.formType],objecttypecode:t.entityLogicalName,...t.description!==void 0?{description:t.description}:{}}}metadataNeeds(t){let r=t.entityLogicalName;if(!r)return[];let n=new Map;return Wy(t,i=>{var o;let a=i.fieldName,s=i;if(!a||s.label!==void 0&&s.classId!==void 0)return;let l=(o=n.get(a))!==null&&o!==void 0?o:{entityLogicalName:r,fieldName:a};s.label===void 0&&(l.needsLabel=!0),n.set(a,l)}),[...n.values()]}customControlNeeds(t,r){var n;return{entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",...(0,ni.customControlNeeds)(t,r)}}createDefault(t){var r,n,i,o,a,s,l,u,c,d,f,m;let p=[...(0,Xt.genPageEmbedIssues)(t),...(0,ni.pcfBindingIssues)(t)];if(p.length>0)throw new Gs.ValidationError("form",t.id||"(new)",p);let h=t.tabs&&t.tabs.length>0?void 0:vZ(this.lcid),g=h!==void 0?h:t.tabs.map(E=>cZ(E,this.lcid)).join(""),b=this.deserialize({formxml:`<form><tabs>${g}</tabs></form>`,formid:t.id||(0,Ws.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:xf[(n=t.formType)!==null&&n!==void 0?n:"Main"],name:(i=t.name)!==null&&i!==void 0?i:"New Form",uniquename:(o=t.name)!==null&&o!==void 0?o:"New Form",description:(a=t.description)!==null&&a!==void 0?a:"",formpresentation:gt.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?gt.FormActivationState.Active:gt.FormActivationState.InActive});(l=b.displayCondition)===null||l===void 0||l.removeProperty(gt.ElementProperties.Order);let w=this.toArtifact(b,t.description);if(t.tabs&&t.tabs.length>0){let E=mL(t);mL(w).forEach((S,P)=>{E[P]&&E[P].label===void 0&&delete S.label,E[P]&&E[P].genPage!==void 0&&(S.genPage=JSON.parse(JSON.stringify(E[P].genPage))),E[P]&&E[P].customControl!==void 0&&(S.customControl=JSON.parse(JSON.stringify(E[P].customControl)))})}return{id:(u=t.id)!==null&&u!==void 0?u:w.id,name:(c=t.name)!==null&&c!==void 0?c:"New Form",entityLogicalName:(d=t.entityLogicalName)!==null&&d!==void 0?d:"",formType:(f=t.formType)!==null&&f!==void 0?f:"Main",status:(m=t.status)!==null&&m!==void 0?m:"Active",...t.description!==void 0?{description:t.description}:{},tabs:w.tabs,bag:w.bag}}assignMissingIds(t){return(0,Ws.assignMissingIds)(t)}completeAsStored(t,r){return(0,DX.completeRecordAsStored)(t,r,this.lcid)}normalize(t){return(0,ni.mintPcfIdentity)((0,Xt.mintEmbedIdentity)(t))}committed(t,r){var n,i,o,a,s,l;let u=r?.formxml;if(typeof u!="string"||!((0,Xt.mayCommitEmbedState)(t)||(0,ni.mayCommitPcfState)(t)))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,Ws.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:xf[(i=t.formType)!==null&&i!==void 0?i:"Main"],name:(o=t.name)!==null&&o!==void 0?o:"",uniquename:(a=t.name)!==null&&a!==void 0?a:"",description:(s=t.description)!==null&&s!==void 0?s:"",formpresentation:gt.FormPresentation.AirForm,formactivationstate:gt.FormActivationState.Active}),{bag:d}=dL(c,this.lcid),f=(0,ni.commitPcfState)((0,Xt.commitEmbedState)(t,(l=(0,Xt.descriptionsRegion)(d))===null||l===void 0?void 0:l.node),By);return{artifact:f,baseline:f}}validate(t){return DZ(t)}deserialize(t){return(0,ky.installDomShim)(),this.deserializeDocument(t,uL.ScriptUtilities.ParseXml(t.formxml))}deserializeDocument(t,r){let n=new NX.DeserializationService(this.lcid).deSerializeFormXml(r,new Ui.Guid(t.formid),t.objecttypecode,gt.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===gt.FormActivationState.InActive?"Inactive":"Active"}};Or.FormAdapter=Ff;var EL=["header","footer","DisplayConditions"];function lZ(e){var t;let r=e?.getElementsByTagName("form")[0],n=new Set;for(let i=(t=r?.firstChild)!==null&&t!==void 0?t:null;i;i=i.nextSibling)i.nodeType===1&&EL.includes(i.nodeName)&&n.add(i.nodeName);return n}function uZ(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=EL.filter(o=>!t.has(o)),i=e.bag.c.filter(o=>{var a;return n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>o.i);return i.length>0&&(e.bag.c=e.bag.c.filter(o=>{var a;return!n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>({...o,i:o.i-i.filter(a=>a<o.i).length}))),e}function Pn(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function zy(e,t){return e?`<labels><label description="${Pn(e)}" languagecode="${t}" /></labels>`:""}function jy(e){return e&&e.length>0?Gu(e):(0,Ws.newId)()}function cZ(e,t){var r,n,i,o;let a=(r=e.columns)!==null&&r!==void 0?r:[],s=(a.length>0?a:[bZ()]).map(l=>dZ(l,t)).join("");return`<tab id="{${Pn(jy(e.id))}}" name="${Pn((n=e.name)!==null&&n!==void 0?n:"")}" expanded="${(i=e.expanded)!==null&&i!==void 0?i:!0}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}">${zy(e.label,t)}<columns>${s}</columns></tab>`}function dZ(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(o=>fZ(o,t)).join("");return`<column width="${Pn((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function fZ(e,t){var r,n,i,o,a;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>pZ(l,t)).join("");return`<section id="{${Pn(jy(e.id))}}" name="${Pn((n=e.name)!==null&&n!==void 0?n:"")}" showlabel="${(i=e.showLabel)!==null&&i!==void 0?i:!1}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}" columns="${$y((a=e.columns)!==null&&a!==void 0?a:1)}">${zy(e.label,t)}<rows>${s}</rows></section>`}function pZ(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>mZ(n,t)).join("")}</row>`}function mZ(e,t){var r,n,i,o,a;let s=hZ(e),l=s.control,u=l?zy((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?gZ(l):"";return`<cell id="{${Pn(jy(s.id))}}" showlabel="${l?(n=l.showLabel)!==null&&n!==void 0?n:!0:!1}" visible="${(i=s.visible)!==null&&i!==void 0?i:!0}" colspan="${(o=s.colspan)!==null&&o!==void 0?o:1}" rowspan="${(a=s.rowspan)!==null&&a!==void 0?a:1}">${u}${c}</cell>`}function hZ(e){if(!(0,Xt.hasGenPage)(e.control))return e;let t={...e.control};(0,Xt.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,Xt.applyEmbedCellDefaults)(r),r}function gZ(e){var t,r,n;let i=e.fieldName?` datafieldname="${Pn(e.fieldName)}"`:"",o=yZ(e.parameters),a=e.classId?Gu(e.classId):String(tt.ControlClassId.TextboxControl);return`<control id="${Pn((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Pn(a)}}"${i} disabled="${(r=e.isReadOnly)!==null&&r!==void 0?r:!1}" isrequired="${(n=e.isRequired)!==null&&n!==void 0?n:!1}">${o}</control>`}function yZ(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,Uy.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Pn(e[n])}</${n}>`).join("")}</parameters>`)}function bZ(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function vZ(e){return`<tab id="{${Ui.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${Ui.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 wZ(e=gL.DEFAULT_LCID){return{adapter:new Ff(e),api:TX.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,cL.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,cL.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}Or.formRegistration=wZ;var CZ=new Set(["id","name","label","expanded","visible","columns","bag"]),EZ=new Set(["id","width","sections","bag"]),AZ=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),SZ=new Set(["id","cells","bag"]),NZ=new Set(["id","visible","colspan","rowspan","control","bag"]),_Z=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","customControl","bag"]),TZ={elsewhere:{isReadOnly:"control",isRequired:"control",fieldName:"control",classId:"control",label:"control",showLabel:"control",parameters:"control"},unsupported:{createOnly:"FormXml has no create-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled.",updateOnly:"FormXml has no update-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled."}};function DZ(e){let t=[];return(0,Ir.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let o=`/tabs/${i}`;(0,Ir.rejectUnknownKeys)(n,CZ,o,"tab",t),(0,Ir.childObjects)(n,"columns",o,"column",t).forEach(({node:s,index:l})=>{let u=`${o}/columns/${l}`;(0,Ir.rejectUnknownKeys)(s,EZ,u,"column",t),(0,Ir.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:f})=>{let m=`${u}/sections/${f}`;(0,Ir.rejectUnknownKeys)(d,AZ,m,"section",t),(0,Ir.childObjects)(d,"rows",m,"row",t).forEach(({node:h,index:g})=>{let b=`${m}/rows/${g}`;(0,Ir.rejectUnknownKeys)(h,SZ,b,"row",t),(0,Ir.childObjects)(h,"cells",b,"cell",t).forEach(({node:E,index:S})=>{let P=`${b}/cells/${S}`;(0,Ir.rejectUnknownKeys)(E,NZ,P,"cell",t,TZ);let L=E.control;L!=null&&!(0,Ir.isJsonObject)(L)?t.push((0,Ir.issue)(`${P}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof L}`)):(0,Ir.isJsonObject)(L)&&(0,Ir.rejectUnknownKeys)(L,_Z,`${P}/control`,"control",t)})})})})}),t.push(...(0,Xt.genPageEmbedIssues)(e)),t.push(...(0,ni.pcfBindingIssues)(e)),t}Or.SUBGRID_CLASS_ID=tt.ControlClassId.SubgridControl;Or.NOTES_CLASS_ID=tt.ControlClassId.TimelineControl;Or.QUICK_VIEW_CLASS_ID=tt.ControlClassId.QuickViewControl;var IZ={Lookup:String(tt.ControlClassId.LookupControl),Customer:String(tt.ControlClassId.LookupControl),Owner:String(tt.ControlClassId.LookupControl),PartyList:String(tt.ControlClassId.PartyListControl),Boolean:String(tt.ControlClassId.BooleanControl),DateTime:String(tt.ControlClassId.DateTimeControl),Decimal:String(tt.ControlClassId.DecimalControl),Double:String(tt.ControlClassId.FloatingNumberControl),Money:String(tt.ControlClassId.CurrencyControl),Integer:String(tt.ControlClassId.IntegerControl),BigInt:String(tt.ControlClassId.IntegerControl),Memo:String(tt.ControlClassId.TextAreaControl),String:String(tt.ControlClassId.TextboxControl)},OZ="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function AL(e){return e==="Picklist"||e==="State"||e==="Status"?OZ:e&&IZ[e]||String(tt.ControlClassId.TextboxControl)}Or.classIdForAttributeType=AL;function hL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var Hy=v(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.viewApi=zs.findDefaultViews=void 0;var DL=Lt(),ur=ye(),Rn=se(),PZ=es(),NL="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",RZ="savedqueryid,name,returnedtypecode,querytype,isdefault",LZ=60*1e3;function Bf(e){return(e.localName||e.nodeName).toLowerCase()}function Wu(e,t){let r;for(let n=0;n<e.attributes.length;n+=1){let i=e.attributes[n];i.nodeName.toLowerCase()===t&&(r=r===void 0?i.value:null)}return r}function kZ(e){if(!e)return;let t=!0,r=()=>{t=!1},n=new PZ.DOMParser({errorHandler:{warning:r,error:r,fatalError:r}}).parseFromString(e,"text/xml").documentElement;return t&&n&&Bf(n)==="fetch"?n:void 0}function $Z(e){for(let t=e.parentNode;t;t=t.parentNode)if(Bf(t)==="link-entity")return!0;return!1}function _L(e,t){var r,n,i;if(((r=e.canbedeleted)===null||r===void 0?void 0:r.Value)!==!1)return!1;let o=kZ(e.fetchxml);if(!o)return!1;let a=Array.from(o.getElementsByTagName("*")),s=a.filter(u=>Bf(u)==="condition"),l=s.length===1?s[0]:void 0;return l!==void 0&&a.filter(u=>Bf(u)==="link-entity").every(u=>{var c;return((c=Wu(u,"link-type"))===null||c===void 0?void 0:c.toLowerCase())==="outer"})&&!$Z(l)&&Wu(l,"entityname")===void 0&&((n=Wu(l,"attribute"))===null||n===void 0?void 0:n.toLowerCase())==="statecode"&&((i=Wu(l,"operator"))===null||i===void 0?void 0:i.toLowerCase())==="eq"&&Wu(l,"value")===String(t)}function xZ(e,t){let r=String(e??"").trim().toLowerCase().split(/\s+/).filter(i=>i!==""),n=String(t??"").trim().toLowerCase().split(/\s+/).filter(i=>i!=="");return r.length===n.length&&r.filter((i,o)=>i!==n[o]).length===1}function FZ(e){var t,r;let n=e.filter(a=>_L(a,0)),i=e.filter(a=>_L(a,1)),o=[];for(let a of n)for(let s of i)Math.abs(Date.parse(String((t=s.createdon)!==null&&t!==void 0?t:""))-Date.parse(String((r=a.createdon)!==null&&r!==void 0?r:"")))<=LZ&&xZ(a.name,s.name)&&o.push({active:a,inactive:s});return o.length===1?o[0]:void 0}async function MZ(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,Rn.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,Rn.odataQuery)([["$select","savedqueryid,name,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,DL.collectPages)(e,a,`findDefaultViews('${t}')`),l=FZ(s),u=new Set(l?[l.active,l.inactive]:[]);return s.filter(c=>c.savedqueryid&&!i.has(c.savedqueryid)&&u.has(c)).map(c=>{var d;return{id:String(c.savedqueryid),name:String((d=c.name)!==null&&d!==void 0?d:"")}})}zs.findDefaultViews=MZ;async function UZ(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,Rn.odataPathLiteral)(t)}')${(0,Rn.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status>=200&&i.status<300){let o=(r=i.body)===null||r===void 0?void 0:r.ObjectTypeCode;return typeof o=="number"?o:void 0}}async function TL(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await UZ(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}zs.viewApi={async get(e,t){let r=(0,Rn.normalizeGuid)(t,"id"),n=await(0,ur.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Rn.odataQuery)([["$select",NL]]);return{raw:(0,ur.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,Rn.normalizeGuid)(t,"id"),n=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Rn.odataQuery)([["$select",NL]]),i=(0,ur.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,ur.readRowEtag)(e,"savedqueries","savedqueryid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueries${(0,Rn.odataQuery)([["$select",RZ],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,Rn.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,DL.collectPages)(e,r,"listArtifacts('view')")).map(i=>{var o,a;return{type:"view",id:(o=i.savedqueryid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.returnedtypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,ur.echoWrite)("savedqueryid"),o=`/savedqueries${i.query}`,a=await TL(e,n.layoutxml,n.returnedtypecode),s=Object.freeze((0,ur.withClientMintedId)({name:n.name,description:n.description,fetchxml:n.fetchxml,layoutxml:a,returnedtypecode:n.returnedtypecode,querytype:n.querytype,isdefault:n.isdefault},"savedqueryid",r)),l=(0,ur.ensureSuccess)(await(0,ur.resendDeadlockVictim)(()=>e.post(o,{...s},i.options)),e.apiUrl(o));return{id:(0,ur.resolveCreatedId)(l,"savedqueryid","view",r),etag:(0,ur.readEtag)(l)}},async update(e,t,r,n){let i=r,o=(0,Rn.normalizeGuid)(t,"id"),a=(0,ur.echoWrite)("savedqueryid",{"If-Match":(0,ur.requireEtag)(n,"view",o)}),s=`/savedqueries(${o})${a.query}`,l=await TL(e,i.layoutxml,i.returnedtypecode),u=(0,ur.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,fetchxml:i.fetchxml,layoutxml:l},a.options),e.apiUrl(s));return{id:o,etag:(0,ur.readEtag)(u)}},delete(e,t){return(0,ur.deleteRecord)(e,"savedqueries",t)}}});var WL=v(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.viewRegistration=js.ViewAdapter=void 0;var $L=Q(),Wr=en(),Ky=so(),ha=uo(),IL=Jr(),BZ=Hy(),Jy=lo(),qZ=dt(),xL=100,Vf=class{toArtifact(t){var r,n,i,o,a,s,l,u;(0,Jy.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",f=(0,ha.parseXmlRoot)(c,"<fetch/>"),m=(0,ha.parseXmlRoot)(d,"<grid/>"),p=ML(f);return{id:(i=t.savedqueryid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.returnedtypecode)!==null&&s!==void 0?s:GZ(f),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:FL(m,f),filters:BL(f),sort:UL(f),...p.length>0?{linkEntities:p}:{},fetchBag:c?(0,ha.projectElementBag)(f):void 0,layoutBag:d?(0,ha.projectElementBag)(m):void 0}}fromArtifact(t){(0,Jy.installDomShim)();let{fetchxml:r,layoutxml:n}=OL(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,o,a;(0,Jy.installDomShim)();let{fetchxml:s,layoutxml:l}=OL(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:(o=t.queryType)!==null&&o!==void 0?o:0,isdefault:(a=t.isDefault)!==null&&a!==void 0?a:!1}}createDefault(t){var r,n,i,o,a,s,l,u;let c=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,qZ.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New View",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:c,queryType:(a=t.queryType)!==null&&a!==void 0?a:0,isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,columns:t.columns&&t.columns.length>0?t.columns:[{name:`${c}id`,width:300,order:0}],filters:(l=t.filters)!==null&&l!==void 0?l:{type:"and",conditions:[],groups:[]},sort:(u=t.sort)!==null&&u!==void 0?u:[],...t.linkEntities&&t.linkEntities.length>0?{linkEntities:t.linkEntities}:{}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;(0,Wr.childObjects)(n,"columns","","column",r),(0,Wr.childObjects)(n,"sort","","sort",r),(0,Wr.childObjects)(n,"linkEntities","","linkEntity",r),VZ(n.linkEntities,r);let i=n.filters;return i!=null&&((0,Wr.isJsonObject)(i)?Yy(i,"/filters",r):r.push((0,Wr.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};js.ViewAdapter=Vf;function VZ(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,Wr.isJsonObject)(r))return;for(let o of["name","from","to"]){let a=r[o];(typeof a!="string"||a.trim()==="")&&t.push((0,Wr.issue)(`/linkEntities/${n}/${o}`,"linkentity-needs-keys",`a join needs a non-empty '${o}' \u2014 'from'/'to' are what DEFINE the relationship, and a link without them is unresolvable. Got ${JSON.stringify(a)}.`))}let i=r.filters;i!=null&&((0,Wr.isJsonObject)(i)?Yy(i,`/linkEntities/${n}/filters`,t):t.push((0,Wr.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function Yy(e,t,r){(0,Wr.childObjects)(e,"conditions",t,"condition",r),(0,Wr.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:o})=>Yy(i,`${t}/groups/${o}`,r))}function GZ(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function FL(e,t){var r;let n=Gf(t),i=e.getElementsByTagName("cell"),o=[],a=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)?xL:c,order:a},f=n.get(u);f&&(d.relatedEntity=f.linkKey,f.attributeName&&f.attributeName!==u&&(d.sourceAttribute=f.attributeName)),a+=1,o.push(d)}return o}function Gf(e){let t=new Map,r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("name")||"",c=l.getAttribute("alias")||u;c&&t.set(c,{linkKey:i.getAttribute("alias")||o,linkName:o,attributeName:u,link:i})}}return t}function ML(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of Ft(t,"link-entity")){let i=n.getAttribute("name"),o=n.getAttribute("from"),a=n.getAttribute("to");if(!i||!o||!a)continue;let s=n.getAttribute("alias"),l=n.getAttribute("link-type"),u=Ft(n,"filter").find(c=>!Wf(c));r.push({name:i,from:o,to:a,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:Qy(u)}:{}})}return r}function UL(e){var t;let r=e.getElementsByTagName("entity")[0];if(!r)return[];let n=[],i=r.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a.nodeType===1&&a.tagName==="order"){let s=a.getAttribute("attribute");s&&n.push({attribute:s,descending:((t=a.getAttribute("descending"))!==null&&t!==void 0?t:"").toLowerCase()==="true",entityname:a.getAttribute("entityname")||""})}}return n}function BL(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=Ft(t,"filter").filter(i=>!Wf(i)).map(Qy);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function Wf(e){if(e.getAttribute("isquickfindfields")==="1"||qL(e))return!0;if(Ft(e,"filter").length>0)return!1;let t=Ft(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||Ft(r,"value").length>0||zZ(r))}function qL(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&(n.tagName==="filter"?qL(n):n.tagName!=="condition"))return!0}return!1}var WZ=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function zZ(e){var t;let r=e.attributes;for(let n=0;n<r.length;n+=1){let i=(t=r[n])===null||t===void 0?void 0:t.name;if(i&&!WZ.has(i))return!0}return!1}function Qy(e){var t,r;let n=((t=e.getAttribute("type"))!==null&&t!==void 0?t:"and").toLowerCase()==="or"?"or":"and",i=[],o=[],a=e.childNodes;for(let s=0;s<a.length;s+=1){let l=a[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:""};l.hasAttribute("value")&&(c.value=l.getAttribute("value")||"");let d=l.getAttribute("entityname")||"";d&&(c.entityname=d),i.push(c)}else l.tagName==="filter"&&o.push(Qy(l))}return{type:n,conditions:i,groups:o}}function Ft(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}var Xy=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function jZ(e,t){let r=Gf(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=r.get(i.name);if(o){let a=Xy(i),s=n.get(a);s?s.push(o.link):n.set(a,[o.link])}}return n}function HZ(e,t,r,n){if(!n||n.size===0)return;let i=new Set,o=t.getElementsByTagName("link-entity");for(let s=0;s<o.length;s+=1)i.add(o[s]);let a=r.filter(s=>{if(!s.relatedEntity)return!1;let l=n.get(Xy(s));return!!l&&l.some(u=>!i.has(u))});if(a.length!==0)throw new $L.ValidationError("view",e.id,a.map(s=>(0,Wr.issue)(`/columns/${r.indexOf(s)}`,"view-column-orphaned-by-join-removal",`column '${s.name}' came from a join this push REMOVED. Another join matching '${s.relatedEntity}' still exists, but nothing can say whether it is the one the column belonged to \u2014 re-attaching it there would silently change the data the column shows. Remove the column too, keep the join it came from, or point the column at the join you want by setting relatedEntity to that join's alias.`)))}function OL(e){var t,r;let n=KZ(e.columns),i=(t=e.sort)!==null&&t!==void 0?t:[],o=(r=e.filters)!==null&&r!==void 0?r:{type:"and",conditions:[],groups:[]};if(!PL(e.fetchBag)||!PL(e.layoutBag))return{fetchxml:see({...e,columns:n,sort:i,filters:o}),layoutxml:lee({...e,columns:n},`${e.entityLogicalName}id`)};let a=new DOMParser().parseFromString("<root/>","text/xml"),s=RL(e.fetchBag,"fetch",a),l=RL(e.layoutBag,"grid",a),u=FL(l,s),c=!qf(n,u),d=!qf(i,UL(s)),f=!qf(o,BL(s)),m=e.linkEntities,p=m!==void 0&&!qf(m,ML(s)),h=p?jZ(s,u):void 0;return p&&iee(a,s,m),p&&(aee(e,s,n,h),HZ(e,s,n,h)),c?(LL(a,s,n,u),ZZ(a,l,n)):p&&LL(a,s,n,u),d&&ree(a,s,i),f&&nee(a,s,o),{fetchxml:(0,ha.serializeNode)(s),layoutxml:(0,ha.serializeNode)(l)}}function KZ(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:xL,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function PL(e){return!!e&&(e.c.length>0||e.a.length>0)}function RL(e,t,r){let n={n:t,a:(0,Ky.mergeAttrs)(e.a,[]),c:(0,Ky.spliceChildren)(e.c,[])};return(0,Ky.rebuildRaw)(n,(0,ha.domEngine)(r),null)}function LL(e,t,r,n){var i,o,a;let s=t.getElementsByTagName("entity")[0];if(!s)return;let l=p=>{var h,g;return`${(h=p.relatedEntity)!==null&&h!==void 0?h:""}:${p.name}:${(g=p.sourceAttribute)!==null&&g!==void 0?g:p.name}`},u=new Set(r.map(l)),c=new Set(r.map(p=>p.name)),d=Gf(t);for(let p of n)u.has(l(p))||(YZ(s,p),p.relatedEntity&&c.has(p.name)&&JZ((i=d.get(p.name))===null||i===void 0?void 0:i.link,p.name));let f=Gf(t),m=new Set(Ft(s,"attribute").map(p=>p.getAttribute("name")).filter(p=>!!p));for(let p of[...r].sort((h,g)=>h.order-g.order))if(p.relatedEntity){let h=f.get(p.name);if(h&&h.attributeName===((o=p.sourceAttribute)!==null&&o!==void 0?o:p.name)&&(h.linkKey===p.relatedEntity||h.linkName===p.relatedEntity||!GL(s,p.relatedEntity)))continue;let g=QZ(e,s,p.relatedEntity),b=e.createElement("attribute");VL(b,p),g.appendChild(b),f.set(p.name,{linkKey:p.relatedEntity,linkName:g.getAttribute("name")||p.relatedEntity,attributeName:(a=p.sourceAttribute)!==null&&a!==void 0?a:p.name,link:g})}else{if(m.has(p.name))continue;let h=e.createElement("attribute");h.setAttribute("name",p.name),XZ(s,h),m.add(p.name)}}function VL(e,t){if(t.sourceAttribute&&t.sourceAttribute!==t.name){e.setAttribute("name",t.sourceAttribute),e.setAttribute("alias",t.name);return}e.setAttribute("name",t.name)}function JZ(e,t){if(e){for(let r of Ft(e,"attribute"))if((r.getAttribute("alias")||r.getAttribute("name"))===t){e.removeChild(r);return}}}function YZ(e,t){if(t.relatedEntity){for(let r of Ft(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of Ft(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of Ft(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function GL(e,t,r=!1){let n=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of Ft(e,"link-entity"))if(n(o))return o;if(r)return;let i=e.getElementsByTagName("link-entity");for(let o=0;o<i.length;o+=1)if(n(i[o]))return i[o]}function QZ(e,t,r){let n=GL(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function XZ(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 ZZ(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),o=eee(n);if(tee(o,i)){for(let s=0;s<i.length;s+=1){let l=String(i[s].width);o[s].getAttribute("width")!==l&&o[s].setAttribute("width",l)}return}let a=new Map;for(let s of o){let l=s.getAttribute("name");l&&a.set(l,s),n.removeChild(s)}for(let s of i){let l=a.get(s.name);l||(l=e.createElement("cell"),l.setAttribute("name",s.name)),l.setAttribute("width",String(s.width)),n.appendChild(l)}}function eee(e){return Ft(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function tee(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 ree(e,t,r){let n=t.getElementsByTagName("entity")[0];if(!n)return;let i=(m,p)=>`${m.toLowerCase()}\0${p.toLowerCase()}`,o=new Map,a=new Map,s=(m,p,h)=>{let g=m.get(p);g?g.push(h):m.set(p,[h])},l=null;for(let m of Ft(n,"order")){let p=m.getAttribute("attribute")||"";p&&(l||(l=e.createTextNode(""),n.insertBefore(l,m)),s(o,i(m.getAttribute("entityname")||"",p),m),s(a,p.toLowerCase(),m),n.removeChild(m))}let u=new Set,c=(m,p)=>{let h=m.get(p);for(;h&&h.length>0;){let g=h.shift();if(!u.has(g))return u.add(g),g}},d=m=>{var p;let h=a.get(m.toLowerCase());if(!h)return;let g=h.filter(w=>!u.has(w)),b=(p=g.find(w=>!w.getAttribute("entityname")))!==null&&p!==void 0?p:g[0];return b&&u.add(b),b},f=r.map(m=>{let p=String(m.attribute);return m.entityname===void 0?{expression:m,element:void 0}:{expression:m,element:c(o,i(m.entityname,p))}});for(let m of f)m.expression.entityname===void 0&&(m.element=d(String(m.expression.attribute)));for(let{expression:m,element:p}of f){let h=p??e.createElement("order");h.setAttribute("attribute",m.attribute),h.setAttribute("descending",String(m.descending)),m.entityname?h.setAttribute("entityname",m.entityname):m.entityname===""&&h.removeAttribute("entityname"),n.insertBefore(h,l)}l&&n.removeChild(l)}function nee(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Ft(n,"filter"))Wf(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(zu(e,r))}}function qf(e,t){return JSON.stringify(e)===JSON.stringify(t)}function iee(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=Ft(i,"link-entity").filter(p=>p.getAttribute("name")&&p.getAttribute("from")&&p.getAttribute("to")),a=(p,h)=>p.getAttribute(h)||"",s=new Array(r.length),l=new Set,u=p=>{r.forEach((h,g)=>{if(s[g])return;let b=o.filter(S=>!l.has(S)&&p(S,h));if(b.length!==1)return;let w=b[0];r.some((S,P)=>P!==g&&!s[P]&&p(w,S))||(s[g]=w,l.add(w))})};u((p,h)=>!!h.alias&&a(p,"name")===h.name&&a(p,"alias")===h.alias),u((p,h)=>a(p,"name")===h.name&&a(p,"from")===h.from&&a(p,"to")===h.to),u((p,h)=>a(p,"name")===h.name&&a(p,"from")===h.from),u((p,h)=>a(p,"name")===h.name&&a(p,"to")===h.to),u((p,h)=>a(p,"name")===h.name);let c=r.map((p,h)=>h).filter(p=>!s[p]),d=o.filter(p=>!l.has(p)),f=new Map;for(let p of d){let h=f.get(a(p,"name"));h?h.push(p):f.set(a(p,"name"),[p])}let m=new Map;for(let p of c){let h=m.get(r[p].name);h?h.push(p):m.set(r[p].name,[p])}for(let[p,h]of m){let g=(n=f.get(p))!==null&&n!==void 0?n:[];g.length===h.length&&h.forEach((b,w)=>{s[b]=g[w],l.add(g[w])})}r.forEach((p,h)=>{let g=s[h];if(g){kL(e,g,p);return}let b=e.createElement("link-entity");kL(e,b,p),i.appendChild(b)});for(let p of o)l.has(p)||i.removeChild(p)}var oee=new Set(["inner","outer"]);function aee(e,t,r,n){if(!t.getElementsByTagName("entity")[0])return;let o=new Set,a=t.getElementsByTagName("link-entity");for(let c=0;c<a.length;c+=1){let d=a[c],f=d.getAttribute("name"),m=d.getAttribute("alias");f&&o.add(f),m&&o.add(m)}let s=new Set;for(let c=0;c<a.length;c+=1)s.add(a[c]);let l=c=>{let d=n?.get(Xy(c));return!!d&&d.every(f=>s.has(f))},u=r.filter(c=>c.relatedEntity&&!o.has(c.relatedEntity)&&!l(c));if(u.length!==0)throw new $L.ValidationError("view",e.id,u.map(c=>{var d;let f=((d=e.linkEntities)!==null&&d!==void 0?d:[]).some(m=>m.name===c.relatedEntity||m.alias===c.relatedEntity);return(0,Wr.issue)(`/columns/${r.indexOf(c)}`,"view-column-dangling-link",`column '${c.name}' has relatedEntity '${c.relatedEntity}', but no matching join remains in linkEntities. `+(f?"Remove the column too, or keep the join.":"That join is NESTED (a join off a join), which the typed layer does not model, so it cannot be re-declared in linkEntities \u2014 it only survives while the join above it does. Remove the column, or restore the parent join this push replaced."))}))}function kL(e,t,r){t.setAttribute("name",r.name),t.setAttribute("from",r.from),t.setAttribute("to",r.to),r.alias?t.setAttribute("alias",r.alias):t.removeAttribute("alias"),r.linkType?t.setAttribute("link-type",r.linkType):oee.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=Ft(t,"filter").find(o=>!Wf(o)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?zu(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function see(e){var t;let r=new DOMParser().parseFromString("<fetch/>","text/xml"),n=r.documentElement;n.setAttribute("version","1.0"),n.setAttribute("mapping","logical");let i=r.createElement("entity");i.setAttribute("name",e.entityLogicalName),n.appendChild(i);let o=new Map;for(let a of(t=e.linkEntities)!==null&&t!==void 0?t:[]){let s=r.createElement("link-entity");s.setAttribute("name",a.name),s.setAttribute("from",a.from),s.setAttribute("to",a.to),a.alias&&s.setAttribute("alias",a.alias),a.linkType&&s.setAttribute("link-type",a.linkType),a.filters&&(a.filters.conditions.length>0||a.filters.groups.length>0)&&s.appendChild(zu(r,a.filters)),i.appendChild(s);for(let l of[a.alias||a.name,a.name])o.has(l)||o.set(l,s)}for(let a of[...e.columns].sort((s,l)=>s.order-l.order)){let s=r.createElement("attribute");if(a.relatedEntity){VL(s,a);let l=o.get(a.relatedEntity);l||(l=r.createElement("link-entity"),l.setAttribute("name",a.relatedEntity),i.appendChild(l),o.set(a.relatedEntity,l)),l.appendChild(s)}else s.setAttribute("name",a.name),i.appendChild(s)}for(let a of e.sort){let s=r.createElement("order");s.setAttribute("attribute",a.attribute),s.setAttribute("descending",String(a.descending)),a.entityname&&s.setAttribute("entityname",a.entityname),i.appendChild(s)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&i.appendChild(zu(r,e.filters)),new XMLSerializer().serializeToString(r)}function zu(e,t){let r=e.createElement("filter");r.setAttribute("type",t.type);for(let n of t.conditions){let i=e.createElement("condition");i.setAttribute("attribute",n.attribute),i.setAttribute("operator",n.operator),n.entityname&&i.setAttribute("entityname",n.entityname),n.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(zu(e,n));return r}function lee(e,t){var r;let n=new DOMParser().parseFromString("<grid/>","text/xml"),i=n.documentElement,o=[...e.columns].sort((s,l)=>s.order-l.order);i.setAttribute("name","resultset"),i.setAttribute("jump",((r=o[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 a=n.createElement("row");a.setAttribute("name","result"),a.setAttribute("id",t||`${e.entityLogicalName}id`),i.appendChild(a);for(let s of o){let l=n.createElement("cell");l.setAttribute("name",s.name),l.setAttribute("width",String(s.width)),a.appendChild(l)}return new XMLSerializer().serializeToString(n)}function uee(){return{adapter:new Vf,api:BZ.viewApi,publish:(e,t,r)=>(0,IL.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,IL.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}js.viewRegistration=uee});function zf(e,t){return e==="SetFieldValue"&&t!==void 0&&cee.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var cee,Zy=k(()=>{"use strict";cee=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function zL(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function eb(e){return e==="AllForms"||zL(e)?1:2}function tb(e){return zL(e)?e:null}function jL(e,t){return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:e.name,description:e.description,workflowid:t,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:Hs.WorkflowCategory.BusinessRule,type:Hs.WorkflowTypeCode.Definition,mode:1,scope:Hs.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:eb(e.scope),processtriggerformid:tb(e.scope)}}var Hs,HL=k(()=>{"use strict";Hs=Ee(Yi());});function KL(e,t=0){return(Mt[e[t+0]]+Mt[e[t+1]]+Mt[e[t+2]]+Mt[e[t+3]]+"-"+Mt[e[t+4]]+Mt[e[t+5]]+"-"+Mt[e[t+6]]+Mt[e[t+7]]+"-"+Mt[e[t+8]]+Mt[e[t+9]]+"-"+Mt[e[t+10]]+Mt[e[t+11]]+Mt[e[t+12]]+Mt[e[t+13]]+Mt[e[t+14]]+Mt[e[t+15]]).toLowerCase()}var Mt,JL=k(()=>{Mt=[];for(let e=0;e<256;++e)Mt.push((e+256).toString(16).slice(1))});function rb(){return jf>Hf.length-16&&((0,YL.randomFillSync)(Hf),jf=0),Hf.slice(jf,jf+=16)}var YL,Hf,jf,QL=k(()=>{YL=require("crypto"),Hf=new Uint8Array(256),jf=Hf.length});var XL,nb,ZL=k(()=>{XL=require("crypto"),nb={randomUUID:XL.randomUUID}});function dee(e,t,r){if(nb.randomUUID&&!t&&!e)return nb.randomUUID();e=e||{};let n=e.random??e.rng?.()??rb();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 KL(n)}var cr,ek=k(()=>{ZL();QL();JL();cr=dee});var ib=k(()=>{ek()});var tk=k(()=>{"use strict";});function rk(e){return e!=null&&fee.has(e)}function Kf(e){if(e==null)return!1;let t=e.trim();if(!/^[+-]?\d+$/.test(t))return!1;let r=Number(t);return Number.isInteger(r)&&r>=-2147483648&&r<=2147483647}var fee,ob=k(()=>{"use strict";fee=new Set(["Picklist","State","Status"])});var Jf=v(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.WorkflowConditionOperator=dn.WorkflowAttributeType=dn.SystemStep=dn.FieldRequiredLevelTypes=dn.AttributeDateTimeBehavior=void 0;dn.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};dn.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};dn.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};dn.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"};dn.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 Yf(e){return e!=null&&ik.includes(e)}function ab(e){return e===oe.WorkflowAttributeType.Integer}function sb(e,t){return t===oe.WorkflowConditionOperator.Equal||t===oe.WorkflowConditionOperator.NotEqual?e:pee.includes(t)?ik.includes(e)||e===oe.WorkflowAttributeType.DateTime?e:oe.WorkflowAttributeType.String:t===oe.WorkflowConditionOperator.On||t===oe.WorkflowConditionOperator.NotOn?e===oe.WorkflowAttributeType.DateTime?e:oe.WorkflowAttributeType.String:oe.WorkflowAttributeType.String}function ok(e){let t=e.leftWorkflowType??e.valueWorkflowType??oe.WorkflowAttributeType.String,r=ju[e.operator]??oe.WorkflowConditionOperator.Equal;return sb(t,r)}function ak(e,t){let r=e.trim(),i=(r.startsWith("+")||r.startsWith("-")?r.slice(1):r).split(".");if(i.length>2)return!1;let[o,a=""]=i;return o.length===0&&a.length===0||!nk.test(o)||!nk.test(a)||o.length>1&&o.startsWith("0")||o.length>mee?!1:t!==oe.WorkflowAttributeType.Integer||i.length===1}var oe,ju,ik,pee,nk,mee,lb=k(()=>{"use strict";oe=Ee(Jf());ju={Equals:oe.WorkflowConditionOperator.Equal,DoesNotEqual:oe.WorkflowConditionOperator.NotEqual,IsGreaterThan:oe.WorkflowConditionOperator.GreaterThan,IsLessThan:oe.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:oe.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:oe.WorkflowConditionOperator.LessThanOrEqual,Contains:oe.WorkflowConditionOperator.Contains,DoesNotContain:oe.WorkflowConditionOperator.DoesNotContain,BeginsWith:oe.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:oe.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:oe.WorkflowConditionOperator.EndsWith,DoesNotEndWith:oe.WorkflowConditionOperator.DoesNotEndWith,On:oe.WorkflowConditionOperator.On,NotOn:oe.WorkflowConditionOperator.NotOn,ContainsData:oe.WorkflowConditionOperator.NotNull,DoesNotContainData:oe.WorkflowConditionOperator.IsNull},ik=[oe.WorkflowAttributeType.Decimal,oe.WorkflowAttributeType.Float,oe.WorkflowAttributeType.Integer,oe.WorkflowAttributeType.Money],pee=[oe.WorkflowConditionOperator.GreaterThan,oe.WorkflowConditionOperator.GreaterThanOrEqual,oe.WorkflowConditionOperator.LessThan,oe.WorkflowConditionOperator.LessThanOrEqual];nk=/^\d*$/,mee=28});var sk=k(()=>{"use strict";});function Ln(e){return!hee.has(e)}function ub(e){return e==="Equals"||e==="DoesNotEqual"}function Qf(e){return uk.has(e)?gee:Cee.has(e)?yee:ck.has(e)?bee:Aee.has(e)?wee:vee}function dk(e){return Qf(e)[0]}function fk(e,t){return Qf(t).includes(e)}function lk(e){return uk.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":ck.has(e)?"date":Eee.has(e)?"boolean":"other"}function Xf(e,t){let r=lk(e),n=lk(t);return r==="other"||n==="other"?e===t:r===n}var hee,gee,yee,bee,vee,wee,uk,Cee,ck,Eee,Aee,Zf=k(()=>{"use strict";sk();hee=new Set(["ContainsData","DoesNotContainData"]);gee=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],yee=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],bee=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],vee=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],wee=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],uk=new Set(["String","Memo","EntityName"]),Cee=new Set(["Integer","BigInt","Money","Decimal","Double"]),ck=new Set(["DateTime"]),Eee=new Set(["Boolean"]),Aee=new Set(["Lookup","Owner","Customer"])});function gk(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 Ak(e){return e&&e!==Fe.WorkflowAttributeType.String?e:void 0}function _ee(e){return{__class:Ek,parameterName:"primaryEntity",entityName:e}}function pk(e){return{__class:db,type:cb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:yk,parameters:[e]}}function mk(e,t,r=Fe.WorkflowAttributeType.String){return{__class:vk,type:r,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,entity:_ee(t),attributeName:e}}function Tee(e,t=Fe.WorkflowAttributeType.String){return{__class:wk,type:t,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function Dee(e){return{__class:Ck,type:cb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function Sk(e,t){let r=See[e.operator],n=pk(mk(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=Dee(e.right.value??"0"):e.right.kind==="field"?i=mk(e.right.field??"",t,e.right.workflowType):i=Tee(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=pk(i);return{__class:db,type:cb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:bk,parameters:[r,n,o]}}function Nk(e){return typeof e=="object"&&e.__class===db}function Iee(e){return typeof e=="object"&&e.__class===Ck}function ep(e){return Nk(e)&&e.method===yk&&e.parameters.length>0?ep(e.parameters[0]):e}function hk(e){if(typeof e!="object"||e.__class!==vk)return null;let t=e.entity;if(t&&t.__class&&t.__class!==Ek)return null;let r=e.attributeName;return r?{field:r,workflowType:Ak(e.type)}:null}function _k(e){if(!e)return null;let t=ep(e);if(!Nk(t)||t.method!==bk||t.parameters.length!==3)return null;let r=t.parameters[0],n=Nee[String(r)];if(!n)return null;let i=hk(ep(t.parameters[1]));if(!i)return null;let o=ep(t.parameters[2]);if(Iee(o))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=hk(o);if(a)return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"field",field:a.field,workflowType:a.workflowType}};if(typeof o=="object"&&o.__class===wk){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:Ak(o.type)}}}return null}function pb(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=fb&&r<=Ks}function ga(e){if(!e||!e.leftField)return"incomplete";if(e.right.kind==="field")return e.right.field&&e.right.field.trim()?null:"incomplete";let t=e.right.value;return!t||!t.trim()?"incomplete":e.dateArithmetic&&!pb(t)?"invalidDayCount":null}function Js(e){return ga(e)===null}var Fe,yk,bk,cb,vk,wk,db,Ck,Ek,See,Nee,fb,Ks,Hu=k(()=>{"use strict";Fe=Ee(Jf());Zf();yk="0",bk="3",cb="0",vk="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",wk="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",db="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",Ck="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",Ek="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";See={"+":0,"-":1,"*":2,"/":3},Nee={0:"+",1:"-",2:"*",3:"/"};fb=0,Ks=2147483647});function Pee(e){return e.startsWith("__")&&!Oee.has(e)}function Ree(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{Pee(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function Bk(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function ba(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function tp(e){return Bk(e)||ba(e)}function Lee(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function Ku(){return{list:[]}}function mb(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:cr(),languageCode:r,description:t}]}}function gb(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function op(e,t,r,n=z.AttributeDateTimeBehavior.None){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:n,typeSet:!1,entity:gb(t),attributeName:e}}function ya(e,t,r=z.AttributeDateTimeBehavior.None){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:r,typeSet:!1,primitiveValue:e}}function xee(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?Gk:Vk:qk}function Wk(e){return e.bpfField==="StageCategory"?z.WorkflowAttributeType.BpfStageCategory:z.WorkflowAttributeType.BpfProcess}function Fee(e,t){let r=Wk(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${Dk}_${Tk}`,entityName:Tk,relatedAttributeName:Dk},attributeName:$ee}:op(kee,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,method:vb,parameters:[xee(e),n]}}function zk(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==vb)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===Vk?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===Gk?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===qk?{bpfField:"ProcessName"}:null}function rp(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===vb){let r=(t.parameters??[])[0];if(typeof r=="string"&&Mee.has(r.replace(/^"+|"+$/g,"")))return!0}return ba(e)?rp(e.operand):Bk(e)?rp(e.left)||(e.right??[]).some(rp):!1}function jk(e){if(e?.__class!=="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.entity;return t==null||t.__class==="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions"}function Uee(e){if(e?.__class!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.primitiveValue;return t===!0||typeof t=="string"&&t.toLowerCase()==="true"}function Ik(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return jk(e);case"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions":return e.primitiveValue!=null||e.type!==void 0;case"LookupExpression:#Microsoft.Crm.Workflow.Expressions":case"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions":return!0;default:return!1}}function Bee(e){let t=bb[e.conditionOperatoroperator];if(!t)return!1;let r=t==="ContainsData"||t==="DoesNotContainData";if(ba(e))return r&&Ok(e.operand,!0);let n=e.right??[];return n.length!==(r?0:1)?!1:Ok(e.left,r,n[0])}function Ok(e,t,r){return zk(e)||jk(e)?t||Ik(r):!1}function yb(e){if(!e||!tp(e))return!1;let t=e.conditionOperatoroperator;if(!ba(e)&&(t===z.WorkflowConditionOperator.LogicalAnd||t===z.WorkflowConditionOperator.LogicalOr)){let r=e.right??[];return r.length>0&&yb(e.left)&&r.every(yb)}return Bee(e)}function Pk(e){return!e||Uee(e)?!1:rp(e)||!yb(e)}function Hk(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:ya(e.id.replace(/[{}]/g,""),z.WorkflowAttributeType.UniqueIdentifier)}}function Vee(e){return e===z.WorkflowAttributeType.DateTime?z.AttributeDateTimeBehavior.DateOnly:z.AttributeDateTimeBehavior.None}function Gee(e,t){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let r=e.leftDateTimeBehavior;return r!==void 0&&r!==z.AttributeDateTimeBehavior.None?r:Vee(t)}function Wee(e,t,r){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let n=e.valueFieldDateTimeBehavior;return n!==void 0&&n!==z.AttributeDateTimeBehavior.None?n:r}function jee(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return"1";if(t==="false"||t==="0")return"0"}function ete(e){let t=Zee.exec(e);if(t)return`${t[1]}T${t[2]}`;let r=Xee.exec(e);if(!r)return;let[,n,i,o,a,s,l]=r,u=Qee.indexOf(i.toLowerCase());if(u<0)return;let c=String(u+1).padStart(2,"0");return`${o}-${c}-${n}T${a}:${s}:${l}`}function tte(e){let t=ete(e.trim());return t!==void 0&&Kk(t)?t:e}function Kk(e){let t=e.trim(),r=t.indexOf("T")>=0?"T":" ",n=t.indexOf(r),i=n>=0?t.slice(0,n):t,o=n>=0?t.slice(n+1):"";if(!Hee.test(i)||o.length>0&&!Kee.test(o)&&!Jee.test(o)&&!Yee.test(o))return!1;let[a,s,l]=i.split("-"),u=new Date(`${a}-${s}-${l}T00:00:00Z`);return!Number.isNaN(u.getTime())&&u.getUTCFullYear()===Number(a)&&u.getUTCMonth()+1===Number(s)&&u.getUTCDate()===Number(l)}function rte(e,t){let r={value:e,type:z.WorkflowAttributeType.String};if(t===z.WorkflowAttributeType.String||zee.includes(t)||e.trim().length===0)return r;if(t===z.WorkflowAttributeType.Boolean){let n=jee(e);return n==null?r:{value:n,type:t}}return qee.includes(t)?Kf(e)?{value:e.trim(),type:t}:r:Yf(t)?{value:e.trim(),type:t}:t===z.WorkflowAttributeType.DateTime&&Kk(e)?{value:e.trim(),type:t}:r}function Rk(e){return e==="ContainsData"||e==="DoesNotContainData"}function Lk(e){return nte.has(e)}function kk(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function $k(e,t){let r=e.leftWorkflowType??e.valueWorkflowType??z.WorkflowAttributeType.String,n=ju[e.operator]??z.WorkflowConditionOperator.Equal,i=Gee(e,r),o=sb(r,n);if(e.source==="BusinessProcess"){let l=Fee(e,t);if(Rk(e.operator))return kk(l,n);let u=Wk(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:l,right:[ya(e.value??"",u)]}}let a=op(e.field,t,r,i);if(Rk(e.operator))return kk(a,n);let s;if(e.valueType==="Field"&&e.valueField){let l=Lk(o)&&Lk(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:o;s=[op(e.valueField,t,l,Wee(e,l,i))]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[Hk(e.lookupValue)]}else if(e.valueType==="Clear")s=[ya(null,z.WorkflowAttributeType.String,i)];else if(e.valueType==="Expression")s=[ip(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)];else{let l=rte(e.value??"",o);s=[ya(l.value,l.type,i)]}return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:a,right:s}}function ite(){return ya(!0,z.WorkflowAttributeType.Boolean)}function ote(e,t,r){if(e.length===0)return null;let n=$k(e[0],r);for(let i=1;i<e.length;i++){let o=e[i].connector??t;n={__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?z.WorkflowConditionOperator.LogicalAnd:z.WorkflowConditionOperator.LogicalOr,left:n,right:[$k(e[i],r)]}}return n}function np(e){if(!e)return{valueType:"Value",value:""};if(e.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return{valueType:"Field",valueField:e.attributeName,valueFieldWorkflowType:e.type};if(e.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"){if(e.primitiveValue==null)return{valueType:"Clear",valueWorkflowType:e.type};let t=String(e.primitiveValue);if(e.type===z.WorkflowAttributeType.Boolean){let r=t.trim().toLowerCase();if(r==="1"||r==="true")return{valueType:"Value",value:"true",valueWorkflowType:e.type};if(r==="0"||r==="false")return{valueType:"Value",value:"false",valueWorkflowType:e.type}}return e.type===z.WorkflowAttributeType.DateTime?{valueType:"Value",value:tte(t),valueWorkflowType:e.type}:{valueType:"Value",value:t,valueWorkflowType:e.type}}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=_k(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function ate(e){let t=bb[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=ba(e)?e.operand:e.left,i=ba(e)?[]:e.right??[],o=zk(n);if(o){let g=i[0];return{id:cr(),field:"",fieldDisplayName:"",source:"BusinessProcess",bpfField:o.bpfField,...o.stageType?{stageType:o.stageType}:{},operator:t,valueType:"Value",value:g?.primitiveValue!=null&&!r?String(g.primitiveValue):""}}let a=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",s=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?n.attributeName:"",l=a?n.type:void 0,u=r?{valueType:"Value"}:np(i[0]),c=l,d=a&&n.type===z.WorkflowAttributeType.DateTime&&n.behavior!==z.AttributeDateTimeBehavior.None?n.behavior:void 0,f=u.valueWorkflowType??l,m=r?void 0:i[0],h=m?.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"&&m.type===z.WorkflowAttributeType.DateTime&&m.behavior!==z.AttributeDateTimeBehavior.None?m.behavior:void 0;return{id:cr(),field:s,fieldDisplayName:s,operator:t,...u,...f?{valueWorkflowType:f}:{},...c?{leftWorkflowType:c}:{},...d!==void 0?{leftDateTimeBehavior:d}:{},...h!==void 0?{valueFieldDateTimeBehavior:h}:{}}}function xk(e){if(!e||!tp(e))return{clauses:[],logic:"AND"};let t=[],r=(o,a)=>{let s=o.conditionOperatoroperator;if(ba(o)||s!==z.WorkflowConditionOperator.LogicalAnd&&s!==z.WorkflowConditionOperator.LogicalOr){t.push({...ate(o),...a?{connector:a}:{}});return}let l=s===z.WorkflowConditionOperator.LogicalAnd?"AND":"OR";tp(o.left)&&r(o.left,a),(o.right??[]).filter(tp).forEach(u=>r(u,l))};r(e,void 0);let i=t.slice(1).map(o=>o.connector??"AND")[0]??"AND";return{clauses:t,logic:i}}function ip(e,t,r,n,i,o,a,s){if(e==="Field"&&r)return op(r,n,z.WorkflowAttributeType.String);if(e==="Expression"){if(i)return Sk(i,n);if(o!=null)return o}return e==="Lookup"&&a?Hk(a):e==="Clear"?ya(null,s??z.WorkflowAttributeType.String):ya(t??"",z.WorkflowAttributeType.String)}function hb(e,t){return{propertyName:e,propertyValueExpr:t}}function Ys(e){return`Step_${e.value++}`}function fn(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 Fk(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):fn(t,r)}function ste(e){return e===Uk.StateCode.Activated?"Active":"Draft"}function lte(e){let t={},r=e;typeof r.ismanaged=="boolean"&&(t.isManaged=r.ismanaged);let n=r.iscustomizable;return typeof n=="boolean"?t.isCustomizable=n:n!==null&&typeof n=="object"&&typeof n.Value=="boolean"&&(t.isCustomizable=n.Value),t}function ute(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function Jk(e,t=1033){return new Qs({languageCode:t}).serialize(e)}function Yk(e){return new Qs().deserialize(e)}var Uk,z,Oee,bb,vb,qk,Vk,Gk,kee,$ee,Tk,Dk,Mee,qee,zee,Hee,Kee,Jee,Yee,Qee,Xee,Zee,nte,wb,Qs,Cb=k(()=>{"use strict";ib();Uk=Ee(Yi());tk();ob();lb();Hu();z=Ee(Jf());Oee=new Set(["__class"]);bb={};for(let e of Object.keys(ju))bb[ju[e]]=e;vb="23",qk="BpfProcess",Vk="ActiveStageCategory",Gk="SelectedStageCategory",kee="processid",$ee="stagecategory",Tk="processstage",Dk="stageid";Mee=new Set(["ActiveStage","SelectedStage","Stage"]);qee=[z.WorkflowAttributeType.Picklist,z.WorkflowAttributeType.State,z.WorkflowAttributeType.Status];zee=[z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Customer,z.WorkflowAttributeType.Owner];Hee=/^\d{4}-\d{2}-\d{2}$/,Kee=/^\d{2}:\d{2}$/,Jee=/^\d{2}:\d{2}:\d{2}$/,Yee=/^\d{2}:\d{2}:\d{2}\.\d{1,7}$/,Qee=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],Xee=/^[A-Za-z]{3}, (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/,Zee=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2}\.\d{1,7}|\d{2}:\d{2}:\d{2}|\d{2}:\d{2})Z$/;nte=new Set([z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Owner,z.WorkflowAttributeType.Customer]);wb={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"};Qs=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>wb[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)]:[],o={...r?.reservedProperties??{},__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:r?.id??t.ruleId??cr(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:Ku(),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(o)}makeApplyActionStep(t){return{__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",id:fn("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??Ys(this.stepCounter),stepLabels:{list:[]},specification:hb(t.field,ip(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:gb(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),o=t??"",a=n?.stepLabels,s=mb(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:Fk(n?.id,"ActionStep",this.idCounter),name:n?.name??Ys(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??cr(),uniqueName:n?.uniqueName??`id_${cr().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=gb(this.entityName),n=t.stepName??Ys(this.stepCounter),i=t.stepLabels??Ku(),o={name:n,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:fn("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:hb(t.field,ip(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:fn("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:hb(t.field,ip(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:fn("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...o,id:fn("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{...o,id:fn("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=mb(t.stepLabels,s,this.languageCode);return{...o,id:fn("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=mb(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:fn("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: ${a}`)}}serializeConditionNode(t){let r=t.stepName??Ys(this.stepCounter),n=fn("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??ote(o.clauses,o.logic,this.entityName),l=a?o.branchName??Ys(this.stepCounter):Ys(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?Fk(o.branchId,"ConditionBranchStep",this.idCounter):fn("ConditionBranchStep",this.idCounter),name:l,description:o.displayName,stepLabels:Ku(),conditionExpression:s??(a?ite():void 0),steps:{list:o.trueBranch.map(f=>this.serializeBranchItem(f))}};i.push(c);let d=o.falseBranch;if(d.length===1&&d[0].kind==="condition"){o=d[0],a=!1;continue}d.length>0&&i.push(this.makeTerminalElseBranch(d)),o=void 0}return{__class:"ConditionStep:#Microsoft.Crm.Workflow.ObjectModel",id:n,name:r,description:"",stepLabels:Ku(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:fn("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:Ku(),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 o=JSON.parse(t.wfomJson);i={id:o.id==="WorkflowStep0"||!o.id?t.workflowid??cr():o.id,name:o.name,description:o.description,nextStepIndex:o.nextStepIndex,category:o.category==="0"||o.category===0?"2":o.category,businessProcessType:o.businessProcessType,mode:o.mode,title:o.title||t.name||"",primaryEntityName:o.primaryEntityName==="1"||!o.primaryEntityName?t.primaryentity??"":o.primaryEntityName,workflowEntityId:o.workflowEntityId==="00000000-0000-0000-0000-000000000000"||!o.workflowEntityId?t.workflowid??"":o.workflowEntityId,formId:o.formId,variables:o.variables,inputs:o.inputs,reservedProperties:Ree(o)};let s=(o.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:ute(r,i?.formId),status:ste(t.statecode),rootCondition:n,wfomRoot:i,...lte(t)}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(Lee);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...o]=t,{clauses:a,logic:s}=xk(i?.conditionExpression),l=this.deserializeBranch(i?.steps?.list??[]),u=this.deserializeElseChain(o,r),c=i?.description||i?.name||r.description||r.name||this.label("condition");return{kind:"condition",id:(n?r.id:i?.id)??cr(),displayName:c,clauses:a,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,...Pk(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=xk(n.conditionExpression);return i.length===0&&!Pk(n.conditionExpression)?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},o=n.stepLabels?.list,a=o&&o.length>0?o[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||cr(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...np(u?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=np(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=np(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:o,acceptanceText:a}=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:a,applyActions:i,recommendationActionStepMeta:o}}return{kind:"action",id:t.id,type:"ShowErrorMessage",displayName:t.description||this.label("showErrorMessage"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,errorMessage:n||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:r,meta:n,acceptanceText:i}=this.parseRecommendationApplyActions({list:[t]});return{kind:"action",id:t.id,type:"Recommendation",displayName:t.name||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.actionControl?.controlId??"",recommendationTitle:t.name||"",messageText:t.description||"",acceptanceText:i,applyActions:r,recommendationActionStepMeta:n}}default:return null}}}});var Qk=k(()=>{"use strict";});function mte(e){return typeof e=="object"&&e!==null?e:null}function Xs(e){let t=mte(e);if(!t)return!1;if(t.__class===fte){let r=t;return String(r.method)===pte?!0:Array.isArray(r.parameters)&&r.parameters.some(Xs)}if(t.__class===dte)return Xs(t.operand);if(t.__class===cte){let r=t;return Xs(r.left)||Array.isArray(r.right)&&r.right.some(Xs)}return!1}var cte,dte,fte,pte,Xk=k(()=>{"use strict";Qk();cte="BinaryExpression:#Microsoft.Crm.Workflow.Expressions",dte="UnaryExpression:#Microsoft.Crm.Workflow.Expressions",fte="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",pte="23"});function Nb(e){return hte.has(e.type)}function Eb(e,t,r,n,i,o,a){let s=i.get(r);!s||!t1.has(s.attributeType)||n!=="Value"||a?.operator&&!ub(a.operator)||o.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:a?.target,itemId:a?.itemId,messageKey:"Validation.InvalidValueTypeForField",messageParams:{label:t}})}function gte(e,t){let r=t.get(e.field);return!!r&&t1.has(r.attributeType)&&ub(e.operator)}function Ab(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function Sb(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${Ks}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:Ks}}}function Zk(e,t,r,n,i,o,a,s){if(i!=="Clear")return;let l=o.get(n);zf(r,l)||a.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 sp(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(Nb(t))return!0}else if(sp(t))return!0;return!1}function _b(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=_b(r,t);if(n)return n}}return null}function yte(e){if(!e||typeof e!="object")return!1;let{__class:t,primitiveValue:r}=e;return t!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?!1:r===!0||typeof r=="string"&&r.toLowerCase()==="true"}function bte(e){return e.clauses.length===0&&(e.rawConditionExpression===void 0||yte(e.rawConditionExpression))}function wte(e){return!!e.clauses?.some(t=>t.source==="BusinessProcess")||Xs(e.rawConditionExpression)}function Zs(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=Zs(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=Zs(n,t);if(i)return i}}return null}function Tb(e,t){return{...e,trueBranch:e1(e.trueBranch,t),falseBranch:e1(e.falseBranch,t)}}function e1(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?Tb(r,t):r)}function _o(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?_o(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?_o(n,t,r):n)}}function ap(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?ap(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?ap(n,t,r):n)}}function r1(e,t,r,n){return _o(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function Db(e){return e.length===1&&e[0].kind==="condition"}function Ete(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(Db(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function Ate(e){return!!e&&Ete(e)<Cte}function Ste(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let o=[];if(Db(n.falseBranch)){let a=r(n.falseBranch[0],i);if(a)return a}else o.push(...n.falseBranch.filter(a=>a.kind==="condition"));o.push(...n.trueBranch.filter(a=>a.kind==="condition"));for(let a of o){let s=r(a,a);if(s)return s}};return r(e,e)}function n1(e,t,r){let n=Ste(e,t);return!n||!Ate(n)?e:_o(e,t,i=>i1(i,r))}function i1(e,t){if(Db(e.falseBranch))return{...e,falseBranch:[i1(e.falseBranch[0],t)]};let r=Ib(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function o1(e,t){let r=Zs(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 _o(e,r.node.id,o=>({...o,falseBranch:i}))}function a1(e,t,r){let n=Zs(e,t);if(!n)return e;let i=o=>{let a=[...o],s=a[n.index+r];return s?(a[n.index+r]=a[n.index],a[n.index]=s,a):o};return _o(e,n.node.id,o=>({...o,trueBranch:n.branch==="true"?i(o.trueBranch):o.trueBranch,falseBranch:n.branch==="false"?i(o.falseBranch):o.falseBranch}))}function Ib(e){return{kind:"condition",id:cr(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function s1(e,t){let r={kind:"action",id:cr(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:cr(),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 l1(e){if(!e)return[];let t=[];return u1(e,t),[...new Set(t)]}function u1(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?u1(r,t):"field"in r&&r.field&&t.push(r.field)})}function c1(e,t=[],r){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition.",target:"node"}];let n=[],i=new Map(t.map(o=>[o.logicalName,o]));return f1(e,n,i,!0),r==="Entity"&&d1(e,n),sp(e)||n.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),n}function d1(e,t){wte(e)&&t.push({nodeId:e.id,kind:"BPF_IN_ENTITY_SCOPE",message:"Process based conditions are not allowed in Entity scope.",target:"node",messageKey:"Validation.ProcessConditionNotAllowedInEntityScope"}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"&&d1(r,t)})}function f1(e,t,r,n=!1){let i=n&&bte(e),o=!!e.rawConditionExpression;e.clauses.length===0&&!n&&!o&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition.",target:"node",messageKey:"Validation.AddClause"}),i&&e.falseBranch.length>0&&t.push({nodeId:e.id,kind:"UNREACHABLE_ELSE",message:"Add a condition to the IF clause, or delete the ELSE clause it can never reach.",target:"node",messageKey:"Validation.UnreachableElse"}),e.clauses.forEach(a=>{if(o)return;if(a.source==="BusinessProcess"){a.bpfField?a.value||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id}):t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a business process field for this clause.",target:"clauseField",itemId:a.id,messageKey:"Validation.SelectBusinessProcessField"});return}let s=a.valueType==="Expression"&&!a.rawExpression?ga(a.expression):null;if(!a.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause.",target:"clauseField",itemId:a.id});else if(Ln(a.operator)&&a.valueType==="Value"&&!a.value&&!gte(a,r))t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id});else if(Ln(a.operator)&&a.valueType==="Value"&&a.value){let u=r.get(a.field);u?.maxLength&&a.value.length>u.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${u.maxLength} characters.`,target:"clauseValue",itemId:a.id,messageParams:{maxLength:u.maxLength}})}else Ln(a.operator)&&a.valueType==="Expression"&&!a.rawExpression&&!Js(a.expression)?t.push(s==="invalidDayCount"?Sb(e.id,"clauseValue",a.id):{nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.CompleteClauseFormula"}):Ln(a.operator)&&a.valueType==="Field"&&!a.valueField&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a field to compare to for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseCompareField"});Ln(a.operator)&&a.valueType==="Value"&&a.value&&rk(r.get(a.field)?.attributeType)&&!Kf(a.value)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_OPTION_VALUE",message:"Please enter a whole number option value for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.InvalidClauseOptionValue"});let l=ok(a);Ln(a.operator)&&a.valueType==="Value"&&a.value&&Yf(l)&&!ak(a.value,l)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_NUMERIC_VALUE",message:ab(l)?"Please enter a whole number for this clause.":"Please enter a valid number for this clause.",target:"clauseValue",itemId:a.id,messageKey:ab(l)?"Validation.InvalidClauseWholeNumberValue":"Validation.InvalidClauseNumericValue"}),Ln(a.operator)&&a.valueType==="Lookup"&&(Ab(a.lookupValue)||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseLookupValue"})),Ln(a.operator)&&Eb(e.id,"Condition",a.field,a.valueType,r,t,{operator:a.operator,target:"clauseValue",itemId:a.id})}),i&&e.trueBranch.forEach(a=>{a.kind==="action"&&vte.has(a.type)&&t.push({nodeId:a.id,kind:"ACTION_REQUIRES_CONDITION",message:"Set field value, Show error message, and Recommendation actions require a condition. Add a condition to the IF clause, or use a different action.",target:"node",messageKey:"Validation.ActionRequiresCondition",messageParams:{actionType:a.type}})}),[...e.trueBranch,...e.falseBranch].forEach(a=>{if(a.kind==="condition")f1(a,t,r);else{if(!("field"in a)||!a.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:`${a.type}: a target field is required.`,target:"actionField",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&(a.valueType??"Value")==="Value"&&!a.value?.trim())t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please provide a value.`,target:"actionValue",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Value"&&a.value){let s=r.get(a.field);s?.maxLength&&a.value.length>s.maxLength&&t.push({nodeId:a.id,kind:"ACTION_VALUE_TOO_LONG",message:`${a.type}: value exceeds the field's maximum length of ${s.maxLength} characters.`,target:"actionValue",messageParams:{actionType:a.type,maxLength:s.maxLength}})}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Field"){if(!a.valueField)t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please select a field to copy from.`,target:"actionValue",messageKey:"Validation.SelectActionSourceField",messageParams:{actionType:a.type}});else if(r.size>0){let s=r.get(a.field),l=r.get(a.valueField);s&&l&&!Xf(s.attributeType,l.attributeType)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: the source field's type is not compatible with the target field.`,target:"actionValue",messageKey:"Validation.IncompatibleActionSourceField",messageParams:{actionType:a.type}})}}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Expression"){let s=a.rawExpression?null:ga(a.expression);!a.rawExpression&&!Js(a.expression)&&t.push(s==="invalidDayCount"?Sb(a.id,"actionValue"):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the formula.`,target:"actionValue",messageKey:"Validation.CompleteActionFormula",messageParams:{actionType:a.type}})}else(a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Lookup"&&!Ab(a.lookupValue)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the lookup record.`,target:"actionValue",messageKey:"Validation.EmptyActionLookupValue",messageParams:{actionType:a.type}});if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.field&&(Eb(a.id,a.type,a.field,a.valueType,r,t,{target:"actionValue"}),Zk(a.id,a.type,a.type,a.field,a.valueType,r,t,{target:"actionValue"})),a.type==="ShowErrorMessage"&&!a.errorMessage?.trim()&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_MESSAGE",message:"Show error message: please enter an error message.",target:"actionMessage"}),a.type==="Recommendation"){let s=a.applyActions??[];a.recommendationTitle?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_TITLE",message:"Recommendation: please enter a recommendation title.",target:"recommendationTitle"}),a.messageText?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_MESSAGE",message:"Recommendation: please enter a recommendation message.",target:"recommendationMessage"}),s.length===0&&t.push({nodeId:a.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply.",target:"node"}),s.forEach(l=>{if(!l.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply.",target:"applyActionField",itemId:l.id,messageKey:"Validation.RecommendationApplyField"});else if(l.valueType==="Field")l.valueField||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplySourceField"});else if(l.valueType==="Expression"){let u=l.rawExpression?null:ga(l.expression);!l.rawExpression&&!Js(l.expression)&&t.push(u==="invalidDayCount"?Sb(a.id,"applyActionValue",l.id):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyFormula"})}else l.valueType==="Lookup"?Ab(l.lookupValue)||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyLookupValue"}):l.valueType==="Clear"||l.value?.trim()||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyValue"});l.field&&(Eb(a.id,"Recommendation",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}),Zk(a.id,"Recommendation","SetFieldValue",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}))})}}})}var hte,t1,vte,Cte,Ob=k(()=>{"use strict";ib();Zy();Zf();Hu();Xk();lb();ob();hte=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);t1=new Set(["Lookup","Customer","Owner"]);vte=new Set(["SetFieldValue","ShowErrorMessage","Recommendation"]);Cte=10});var p1={};Hr(p1,{DAY_COUNT_MAX:()=>Ks,DAY_COUNT_MIN:()=>fb,DEFAULT_DESERIALIZE_LABELS:()=>wb,WorkflowJsonMapper:()=>Qs,addElseIfInTree:()=>n1,appendToBranch:()=>r1,areFieldKindsCompatible:()=>Xf,attributeTypeToWorkflowType:()=>gk,buildWorkflowEntity:()=>jL,collectUsedFields:()=>l1,createEmptyAction:()=>s1,createEmptyCondition:()=>Ib,deserializeWorkflowJson:()=>Yk,findNode:()=>_b,findParent:()=>Zs,getDefaultOperatorForFieldType:()=>dk,getExpressionModelIssue:()=>ga,getOperatorsForFieldType:()=>Qf,hasAnyTriggerGeneratingAction:()=>sp,isDayCountValid:()=>pb,isExpressionModelComplete:()=>Js,isOperatorCompatible:()=>fk,isTriggerGeneratingAction:()=>Nb,moveBranchItemInTree:()=>a1,operatorNeedsValue:()=>Ln,processTriggerFormIdFromScope:()=>tb,processTriggerScopeFromScope:()=>eb,removeElseIfInTree:()=>o1,removeNodeFromTree:()=>Tb,serializeToWorkflowJson:()=>Jk,supportsClearForActionType:()=>zf,updateActionInTree:()=>ap,updateConditionInTree:()=>_o,validateBusinessRule:()=>c1});var m1=k(()=>{"use strict";Zy();HL();Cb();Cb();Ob();Ob();Zf();Hu();Hu();});var Pb=v(lp=>{"use strict";Object.defineProperty(lp,"__esModule",{value:!0});lp.cloneJson=void 0;function Nte(e){return JSON.parse(JSON.stringify(e))}lp.cloneJson=Nte});var _1=v(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});To.BUSINESS_RULE_NULL_GUID=To.businessRuleRegistration=To.BusinessRuleAdapter=void 0;var h1=dt(),Ju=(m1(),Fr(p1)),g1=Jr(),y1=Q(),_te=Pb(),ii=en(),Tte=Im(),Dte=dt(),Ite=Ho(),Ote=new Set(["ShowErrorMessage","Recommendation"]);function C1(e){var t,r;return e?[...(t=e.trueBranch)!==null&&t!==void 0?t:[],...(r=e.falseBranch)!==null&&r!==void 0?r:[]].some(n=>Array.isArray(n.trueBranch)||Array.isArray(n.falseBranch)?C1(n):Ote.has(String(n.type))):!1}function Pte(e){return E1((0,_te.cloneJson)(e))}function E1(e){var t,r;let n=i=>(i??[]).map(o=>Rte(o)?E1(o):o);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 Rte(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 Lte(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new y1.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 y1.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 kte="00000000-0000-0000-0000-000000000000";To.BUSINESS_RULE_NULL_GUID=kte;var $te=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),xte=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],Fte=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],Mte=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function kn(e,t){return e===void 0?t:{...e,...t}}var va=["kind","id","type","displayName","field","stepName","stepLabels"],b1=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],Ute={Recommendation:[...va,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...va,"lock"],ShowErrorMessage:[...va,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...va,...b1],SetDefaultValue:[...va,...b1],SetBusinessRequired:[...va,"required"],SetVisibility:[...va,"visible"]};function ne(e,t){return t===void 0?{}:{[e]:t}}function A1(e){var t;return e==null?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function Rb(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",A1(e.lookupValue)),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function S1(e,t){let r=new Set(t),n={};for(let[i,o]of Object.entries(e))r.has(i)||o!==void 0&&(n[i]=o);return Object.keys(n).length>0?n:void 0}var Bte=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function qte(e){return kn(e.bag,{id:e.id,field:e.field,...Rb(e),...ne("stepName",e.stepName),...ne("displayName",e.displayName)})}function Vte(e){let t=S1(e,Bte);return{id:e.id,field:e.field,valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",e.lookupValue),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression),...ne("stepName",e.stepName),...ne("displayName",e.displayName),...ne("bag",t)}}function v1(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",e.lookupValue),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function w1(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var Gte=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),Wte=new Set,zte="INVALID_CLEAR_FOR_FIELD";function jte(e){let t=n=>{var i;return(0,ii.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,ii.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 o of["clauses","trueBranch","falseBranch"])Array.isArray(i[o])&&(i[o]=i[o].map(r));return i};return r(e)}var up=class{toArtifact(t){let r=this.residualBag(t,xte),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 kn(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},o=(0,Ju.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return C1(t.rootCondition)}toApiPayload(t,r,n){var i,o;let a=this.fromArtifact(t);a.wfomRoot&&(a.wfomRoot={...a.wfomRoot,name:t.name,title:t.name,primaryEntityName:t.entityLogicalName||a.wfomRoot.primaryEntityName},a.entityLogicalName=a.wfomRoot.primaryEntityName);let s=(0,Ju.serializeToWorkflowJson)(a,(i=n?.baseLanguageCode)!==null&&i!==void 0?i:Ite.DEFAULT_LCID),l=(o=a.ruleId)!==null&&o!==void 0?o:(0,h1.newId)();return{Entity:this.buildWorkflowEntity(a,l),WfomJson:s,status:t.status}}createDefault(t){var r,n,i,o,a,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:(o=t.entityLogicalName)!==null&&o!==void 0?o:"",scope:(a=t.scope)!==null&&a!==void 0?a:"Entity",status:(s=t.status)!==null&&s!==void 0?s:"Draft",rootCondition:t.rootCondition===void 0?(0,Ju.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(Pte(Lte(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,h1.newId)()),u}assignMissingIds(t){return(0,Dte.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,ii.isJsonObject)(n)?(N1(n,"/rootCondition",r),r):(r.push((0,ii.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(a){return[(0,ii.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=n.rootCondition===null?null:jte(n.rootCondition),o;return r.length===0?o=Gte:r.some(a=>a.requiredLevel!==void 0)?o=Wte:o=new Set([zte]),(0,Ju.validateBusinessRule)(i,r).filter(a=>!o.has(a.kind)).map(a=>(0,ii.issue)(`/rootCondition (${a.nodeId})`,`business-rule-${a.kind}`,a.message))}issuesBlockingPush(t,r=[],n){return this.semanticIssues(t,r)}columnsCheckedAtPush(t){let r;try{r=this.fromArtifact(t)}catch{return[]}let n=new Set,i=a=>{a&&n.add(a)},o=a=>{var s;for(let l of a.clauses)i(l.field),i(l.valueField);for(let l of[...a.trueBranch,...a.falseBranch]){if(l.kind==="condition"){o(l);continue}if(i(l.field),l.type==="SetFieldValue"||l.type==="SetDefaultValue")i(l.valueField);else if(l.type==="Recommendation")for(let u of(s=l.applyActions)!==null&&s!==void 0?s:[])i(u.field),i(u.valueField)}};return r.rootCondition&&o(r.rootCondition),[...n]}residualBag(t,r){return S1(t,r)}buildWorkflowEntity(t,r){return(0,Ju.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,Fte),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,Mte),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,Ute[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...ne("stepName",t.stepName),...ne("stepLabels",t.stepLabels),...ne("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(Vte),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",...v1(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...v1(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return w1(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return kn(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 kn(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,...ne("value",t.value),...ne("valueField",t.valueField),...ne("lookupValue",A1(t.lookupValue)),...ne("expression",t.expression),...ne("rawExpression",t.rawExpression),...ne("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!$te.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);Kte(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...ne("stepName",t.stepName),...ne("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return kn(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(qte),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return kn(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return kn(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return kn(t.bag,{...r,type:"SetFieldValue",...Rb(t)});case"SetDefaultValue":return kn(t.bag,{...r,type:"SetDefaultValue",...Rb(t)});case"SetBusinessRequired":return kn(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return kn(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return w1(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};To.BusinessRuleAdapter=up;function N1(e,t,r){(0,ii.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,ii.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,ii.childObjects)(e,n,t,"branchItem",r).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?N1(o,`${t}/${n}/${a}`,r):Hte(o,`${t}/${n}/${a}`,r)})}function Hte(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,ii.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function Kte(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function Jte(){return{adapter:new up,api:Tte.businessRuleApi,publish:(e,t,r)=>(0,g1.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,g1.boundEntityPublishScope)(t)}}To.businessRuleRegistration=Jte});var W1=v(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.appRegistration=Do.AppAdapter=Do.HEADER_NAV_BOOLEAN_RULE=void 0;var Bi=en(),It=so(),Qu=uo(),Yte=Jr(),x1=Ud(),Lb=Od(),kb=lo(),Qte=dt(),Xte=se(),F1=Ho(),M1=Q(),U1=Rd();Object.defineProperty(Do,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return U1.HEADER_NAV_BOOLEAN_RULE}});var pp="7.0.0.0",T1=`<SiteMap IntroducedVersion="${pp}"></SiteMap>`,D1="/_imgs/imagestrips/transparent_spacer.gif",I1="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",B1=["Entity","Url","DefaultDashboard","Page","GenPageId"],Yu="sitemapId",O1="sitemapName",Zte="sitemapNameUnique",P1="aiDescription",R1="[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}",ere=new RegExp(`^(?:\\{${R1}\\}|${R1})$`);function L1(e,t){if(!ere.test(e.trim()))throw new M1.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function k1(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new M1.ValidationError("app",t,[q1(e)]);return e}function q1(e){return(0,Bi.issue)("/headerAndNavigationRefresh",U1.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function tre(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,Xte.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}}function rre(e){var t,r,n,i;let o=[];for(let a of(r=(t=e.siteMap)===null||t===void 0?void 0:t.areas)!==null&&r!==void 0?r:[])for(let s of(n=a.groups)!==null&&n!==void 0?n:[])for(let l of(i=s.subAreas)!==null&&i!==void 0?i:[])l.type==="Entity"&&l.entity&&o.push(l.entity);return o}var mp=class{constructor(t=F1.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=cp(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,It.emptyBag)()}}fromArtifact(t){(0,kb.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,It.rebuildRaw)(i,(0,Qu.domEngine)(n),null)}fromApiResponse(t){var r,n,i,o,a,s,l,u,c,d,f;(0,kb.installDomShim)();let m=t??{},p=(r=m.$sitemap)!==null&&r!==void 0?r:m,h=(0,Qu.parseXmlRoot)((n=p.sitemapxml)!==null&&n!==void 0?n:T1,T1),g=this.toArtifact(h);return g.id=(i=m.appmoduleid)!==null&&i!==void 0?i:"",g.name=(o=m.name)!==null&&o!==void 0?o:"",g.uniqueName=(a=m.uniquename)!==null&&a!==void 0?a:"",g.description=(s=m.description)!==null&&s!==void 0?s:"",m.aiappdescription&&(g.aiDescription=m.aiappdescription),g.bag={a:[[Yu,(u=(l=p.sitemapid)!==null&&l!==void 0?l:m._sitemapid_value)!==null&&u!==void 0?u:""],[O1,(c=p.sitemapname)!==null&&c!==void 0?c:""],[Zte,(d=p.sitemapnameunique)!==null&&d!==void 0?d:""],[P1,(f=m.aiappdescription)!==null&&f!==void 0?f:""]],c:[]},g}toApiPayload(t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b;(0,kb.installDomShim)();let w=(0,Qu.serializeNode)(this.fromArtifact(t)),E=[],S=[];for(let L of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let I of(o=L.groups)!==null&&o!==void 0?o:[])for(let D of(a=I.subAreas)!==null&&a!==void 0?a:[])D.type==="Entity"&&D.entity?E.push(D.entity):D.type==="DashBoard"&&D.dashboardId&&S.push(D.dashboardId);let P=(s=t.bag)!==null&&s!==void 0?s:(0,It.emptyBag)();return{sitemapId:xb(P,Yu)||(t.sitemapId?L1(t.sitemapId,t.id):""),sitemapxml:w,sitemapname:xb(P,O1)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:xb(P,P1))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[Lb.HEADER_AND_NAVIGATION_REFRESH]:k1(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?Lb.APP_SETTING_ON:Lb.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:E,components:{forms:(c=(u=t.components)===null||u===void 0?void 0:u.forms)!==null&&c!==void 0?c:[],views:(f=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&f!==void 0?f:[],charts:(p=(m=t.components)===null||m===void 0?void 0:m.charts)!==null&&p!==void 0?p:[],dashboards:[...(g=(h=t.components)===null||h===void 0?void 0:h.dashboards)!==null&&g!==void 0?g:[],...S],...((b=t.components)===null||b===void 0?void 0:b.mainFormsByTable)!==void 0?{mainFormsByTable:t.components.mainFormsByTable}:{}}}}createDefault(t){var r,n,i,o,a,s;let l=!((r=t.siteMap)===null||r===void 0)&&r.areas&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}],u=(n=t.id)!==null&&n!==void 0?n:(0,Qte.newId)();return{id:u,name:(i=t.name)!==null&&i!==void 0?i:"New App",uniqueName:(o=t.uniqueName)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",...t.aiDescription?{aiDescription:t.aiDescription}:{},siteMap:{areas:l},...t.sitemapId?{sitemapId:L1(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:k1(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(Mb):Array.isArray(r.areas)?r.areas.forEach(Mb):Array.isArray(r.groups)?Mb(r):Array.isArray(r.subAreas)?G1(r):"type"in r&&hp(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,Bi.issue)("/published","published-must-be-boolean",`published must be a boolean, got ${typeof n}`));let i=t.siteMap,o=t.headerAndNavigationRefresh;if(o!==void 0&&typeof o!="boolean"&&r.push(q1(o)),i==null)return r;if(!(0,Bi.isJsonObject)(i))return r.push((0,Bi.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let a=(0,Bi.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return a.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,Bi.childObjects)(l,"groups",c,"group",r).forEach(({node:f,index:m})=>{let p=`${c}/groups/${m}`;(0,Bi.childObjects)(f,"subAreas",p,"subArea",r).forEach(({node:g,index:b})=>{let w=`${p}/subAreas/${b}`;(0,Bi.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],w,"subarea-type-invalid",r);let E=tre(g);if(!E)return;let S=s.get(E);if(S===void 0){s.set(E,w);return}r.push((0,Bi.issue)(w,"subarea-duplicate-target",`the sitemap already navigates to this target at ${S}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}issuesBlockingPush(t){var r;return(0,x1.mainFormSetShapeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsByTable,rre(t))}applyServerIdentity(t,r){let n=r[Yu];if(!n)return;t.bag||(t.bag=(0,It.emptyBag)());let i=t.bag.a.find(o=>o[0]===Yu);i?i[1]=n:t.bag.a.push([Yu,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=cp(t,"Group"),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:$b(t,this.lcid),groups:i.map(l=>this.groupToJson(l)),bag:n},a=t.getAttribute("Icon");a&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}groupToJson(t){var r;let{bag:n,modeledEls:i}=cp(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:$b(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:n}}subAreaToJson(t){var r;let{bag:n}=cp(t,null),i=nre(t),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:$b(t,this.lcid),bag:n};if(i==="Entity"){let l=t.getAttribute("Entity");l&&(o.entity=l)}else if(i==="DashBoard"){let l=t.getAttribute("DefaultDashboard");l&&(o.dashboardId=l);let u=t.getAttribute("Url");u&&(o.dashboardUrl=u)}else if(i==="CustomPage"){let l=t.getAttribute("Page");l&&(o.page=l)}else if(i==="GenPage"){let l=t.getAttribute("GenPageId");l&&(o.genPageId=l)}else{let l=t.getAttribute("Url");l&&(o.url=l)}let a=t.getAttribute("Icon");a&&a!==D1&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}rootToRaw(t){var r,n,i,o;let a=(n=(r=t.siteMap)===null||r===void 0?void 0:r.bag)!==null&&n!==void 0?n:(0,It.emptyBag)(),l=dp(a)?[["IntroducedVersion",pp]]:[],u=((o=(i=t.siteMap)===null||i===void 0?void 0:i.areas)!==null&&o!==void 0?o:[]).map(c=>this.areaToRaw(c));return{n:"SiteMap",a:(0,It.mergeAttrs)(a.a,l),c:(0,It.spliceChildren)(a.c,u)}}areaToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,It.emptyBag)(),o=dp(i),a=[],s=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",pp]),t.icon!==void 0?a.push(["Icon",t.icon]):fp(i.a,"Icon")&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):fp(i.a,"VectorIcon")&&s.push("VectorIcon");let l=((n=t.groups)!==null&&n!==void 0?n:[]).map(c=>this.groupToRaw(c)),u=Fb((0,It.spliceChildren)(i.c,l),t.title,o,this.lcid);return{n:"Area",a:(0,It.mergeAttrs)(i.a,a,s),c:u}}groupToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,It.emptyBag)(),o=dp(i),a=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",pp],["IsProfile","false"]);let s=((n=t.subAreas)!==null&&n!==void 0?n:[]).map(u=>this.subAreaToRaw(u)),l=Fb((0,It.spliceChildren)(i.c,s),t.title,o,this.lcid);return{n:"Group",a:(0,It.mergeAttrs)(i.a,a),c:l}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,It.emptyBag)(),i=dp(n),o=ore(n.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]);let l=!i&&!n.a.some(([c])=>B1.includes(c));sre(a,t,l),i?(a.push(["ResourceId","SitemapDesigner.NewSubArea"],["Client","All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web"],["Sku","All,OnPremise,Live,SPLA"],["AvailableOffline","true"],["PassParams","false"]),t.icon&&a.push(["Icon",t.icon])):t.icon!==void 0?a.push(["Icon",t.icon]):fp(o,"Icon",D1)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):fp(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",I1]):s.push("VectorIcon"):t.type==="GenPage"&&!ire(o,"VectorIcon")&&a.push(["VectorIcon",I1]);let u=Fb((0,It.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,It.mergeAttrs)(o,a,s),c:u}}};Do.AppAdapter=mp;function cp(e,t){let r=(0,Qu.nodeLikeFromDom)(e).getAllProperties().map(s=>[s.key,s.value]),n=[],i=[],o=e.childNodes,a=0;for(let s=0;s<o.length;s+=1){let l=o[s];l.nodeType!==1&&l.nodeType!==3||(l.nodeType===1&&t!==null&&l.tagName===t?i.push(l):n.push({i:a,node:(0,It.rawFromNode)((0,Qu.nodeLikeFromDom)(l))}),a+=1)}return{bag:{a:r,c:n},modeledEls:i}}function $1(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}function $b(e,t){var r;let n=$1(e,"Titles")[0];if(!n)return"";let o=$1(n,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(r=o.getAttribute("Title"))!==null&&r!==void 0?r:""}function nre(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function dp(e){return e.a.length===0&&e.c.length===0}function ire(e,t){return e.some(([r])=>r===t)}function fp(e,t,r){let n=e.find(([o])=>o===t),i=n?.[1];return!!i&&i!==r}function xb(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function ore(e,t){let r=are(t);return e.filter(([n])=>!B1.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function are(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 sre(e,t,r){var n,i,o,a,s;switch(t.type){case"Entity":e.push(["Entity",(n=t.entity)!==null&&n!==void 0?n:""]);break;case"URL":(t.url!==void 0||!r)&&e.push(["Url",(i=t.url)!==null&&i!==void 0?i:""]);break;case"DashBoard":e.push(["DefaultDashboard",(o=t.dashboardId)!==null&&o!==void 0?o:""]),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",(s=t.genPageId)!==null&&s!==void 0?s:""]);break;default:break}}function Fb(e,t,r,n){if(!t)return e;let i=e.findIndex(o=>o.n==="Titles");if(i>=0){let o=e.slice();return o[i]=lre(e[i],t,n),o}return r?[ure(t,n),...e]:e}function lre(e,t,r){let n=!1,i=e.c.map(o=>!n&&o.n==="Title"&&cre(o,"LCID")===String(r)?(n=!0,{n:o.n,a:(0,It.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return n||i.unshift(V1(t,r)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function ure(e,t){return{n:"Titles",a:[],c:[V1(e,t)]}}function V1(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function cre(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function dre(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function hp(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${dre(8)}`)}function Mb(e){var t;hp(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])G1(r)}function G1(e){var t;hp(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])hp(r,"subarea")}function fre(e=F1.DEFAULT_LCID){return{adapter:new mp(e),api:x1.appApi,languageSensitive:!0,publish:(t,r)=>(0,Yte.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]}),rebaselineAfterPublish:"bracket"}}Do.appRegistration=fre});var z1={};Hr(z1,{ActionType:()=>Bb,AppActionOrigin:()=>Kb,AppActionVisibilityType:()=>Hb,ButtonType:()=>Vb,CannotUpdateAppActionColumns:()=>pre,Context:()=>Wb,IconType:()=>qb,Location:()=>Gb,OnClickEventType:()=>jb,Scope:()=>zb,VisibilityType:()=>Ub});var Ub,Bb,qb,Vb,Gb,Wb,zb,jb,Hb,Kb,pre,j1=k(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(Ub||(Ub={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(Bb||(Bb={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(qb||(qb={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(Vb||(Vb={}));(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"})(Gb||(Gb={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(Wb||(Wb={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(zb||(zb={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(jb||(jb={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(Hb||(Hb={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(Kb||(Kb={}));pre=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var Z1=v(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.assertOneWritePerRow=Ot.commandApi=Ot.COMMAND_DUPLICATE_ROW_CODE=Ot.COMMAND_ROW_NOT_IN_BAR_CODE=Ot.COMMAND_TABLE_MISMATCH_CODE=void 0;var Jb=Lt(),Pr=ye(),qi=Q(),Rr=se();Ot.COMMAND_TABLE_MISMATCH_CODE="COMMAND_TABLE_MISMATCH";Ot.COMMAND_ROW_NOT_IN_BAR_CODE="COMMAND_ROW_NOT_IN_BAR";Ot.COMMAND_DUPLICATE_ROW_CODE="COMMAND_DUPLICATE_ROW";var mre="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function Yb(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Rr.odataPathLiteral)(t)}')${(0,Rr.odataQuery)([["$select","MetadataId"]])}`,i=(0,Pr.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,o=i?.MetadataId;return o?(0,Rr.normalizeGuid)(o,"entityMetadataId"):""}function Qb(e,t){return t?`_contextentity_value eq ${t}`:`contextvalue eq '${(0,Rr.odataLiteral)(e)}'`}function Xu(e){return`Nothing was written. Re-fetch the command with fetchArtifact('command', '${e}', { overwrite: true }) \u2014 this discards local edits \u2014 and re-apply the change.`}function H1(e,t){let r=e.entityLogicalName;if(t===void 0)return r;if(typeof r!="string"||r.toLowerCase()!==t.toLowerCase())throw new qi.SdkError(Ot.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': its JSON names table '${String(r)}'. A command's id is its table, so the push would write another table's command bar. Nothing was written. Fix its entityLogicalName, or push it under that table's id.`);return t}async function K1(e,t,r){let n=await Yb(e,t);if(r){let i=(0,Rr.normalizeGuid)(r,"entityMetadataId");if(i!==n)throw new qi.SdkError(Ot.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': it was fetched for table id ${i}, but table '${t}' is ${n||"not resolvable"} on the server \u2014 the table was re-created, or the local copy edited. `+Xu(t))}return n}Ot.commandApi={async get(e,t){let r=t,n=await Yb(e,r),i=Qb(r,n),o=`/appactions${(0,Rr.odataQuery)([["$expand",mre],["$filter",i]])}`,a,s=await(0,Jb.collectPages)(e,o,"fetchArtifact('command')",c=>{a=c}),l={entityLogicalName:r,entityMetadataId:n,appActions:s},u={};for(let c of s){let d=typeof c.appactionid=="string"?c.appactionid:void 0;if(d){let f=c["@odata.etag"];u[(0,Rr.normalizeGuid)(d,"appactionid")]=typeof f=="string"?f:null}}return{raw:l,etag:a?(0,Pr.readEtag)(a):null,memberEtags:u}},async list(e,t){let r=t?.entityLogicalName;return r?[{type:"command",id:r,name:`${r} commands`,entityLogicalName:r,isDirty:!1}]:[]},async create(e,t,r){let n=t,i=H1(n,r),o=await K1(e,i,n.entityMetadataId);return J1(e,i,{...n,entityMetadataId:o},!1)},async update(e,t,r,n,i){let o=r,a=H1(o,t),s=await K1(e,a,o.entityMetadataId);return J1(e,a,{...o,entityMetadataId:s},!0,i)},async delete(e,t){let r=await Yb(e,t),n=`/appactions${(0,Rr.odataQuery)([["$select","appactionid"],["$filter",Qb(t,r)]])}`,i=await(0,Jb.collectPages)(e,n,"deleteArtifact('command')");for(let o of i)o.appactionid&&await(0,Pr.deleteRecord)(e,"appactions",o.appactionid)}};async function J1(e,t,r,n,i){let o=r.entityMetadataId?(0,Rr.normalizeGuid)(r.entityMetadataId,"entityMetadataId"):"",a=await gre(e,t,r,o,n,i),s={};try{await bre(e,a,o,s)}catch(l){throw(0,qi.withPartialTokens)(l,{memberEtags:s})}return{id:r.entityLogicalName,etag:null,memberEtags:s}}function Xb(e){return e.replace(/[{}]/g,"").toLowerCase()}function X1(e,t){var r;let n=new Map,i=[...t.rows.map(o=>[o.appactionid,"written"]),...((r=t.deletedRowIds)!==null&&r!==void 0?r:[]).map(o=>[o,"deleted"])];for(let[o,a]of i){let s=Xb(o),l=n.get(s);if(l===void 0){n.set(s,a);continue}throw new qi.SdkError(Ot.COMMAND_DUPLICATE_ROW_CODE,l===a?`Refusing to push command '${e}': app action '${s}' appears twice in it \u2014 two of its controls or groups carry that id, as one copied together with its id or bag does \u2014 so one would silently replace or remove the other. Nothing was written. Remove the id and the bag from the copy, so it is created as a new one, and push again.`:`Refusing to push command '${e}': app action '${s}' would be both written and deleted \u2014 one of its controls or groups spells that id differently (case or braces) than the copy last fetched or pushed \u2014 so the delete would remove what the write saved. Nothing was written. Spell the id as it was, and push again.`)}}Ot.assertOneWritePerRow=X1;var hre={entities:/^\/entities\(([^()]+)\)$/,appactions:/^\/appactions\(([^()]+)\)$/};function Y1(e,t){let r=hre[t].exec(e);return r?Xb(r[1]):void 0}async function gre(e,t,r,n,i,o){var a,s;X1(t,r);let l=vre(r.rows),u=new Set(l.map(f=>Xb(f.appactionid))),c={writes:[],deletes:[]};for(let f of l){let m=f.body["[email protected]"];if(m!==void 0&&!(typeof m=="string"&&n!==""&&Y1(m,"entities")===n))throw new qi.SdkError(Ot.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' binds to ${typeof m=="string"?`'${m}'`:String(m)}, not to table '${t}' (${n?`/entities(${n})`:"whose id is not resolvable"}). `+Xu(t));let p=f.body["[email protected]"];if(typeof p=="string"){let h=Y1(p,"appactions");if(h===void 0||!u.has(h))throw new qi.SdkError(Ot.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' would be placed under '${p}', which is not a row of this command. `+Xu(t))}if(i&&f.exists){let h=(0,Rr.normalizeGuid)(f.appactionid,"id"),g=(a=o?.[h])!==null&&a!==void 0?a:f.etag;if(!(0,Pr.isVersionToken)(g))throw Q1(t,h,"update",g);c.writes.push({kind:"patch",row:f,id:h,token:g})}else{if(m===void 0&&!n)throw new qi.SdkError("COMMAND_CONTEXT_ENTITY_UNRESOLVED",`Cannot create app action '${f.appactionid}' for entity '${r.entityLogicalName}': the entity MetadataId could not be resolved, so the required ContextEntity bind cannot be set. A row written without it is created but is permanently unreadable \u2014 commandApi.get filters on _contextentity_value. Verify the entity logical name exists and is readable, then retry.`);c.writes.push({kind:"post",row:f})}}for(let f of(s=r.deletedRowIds)!==null&&s!==void 0?s:[]){let m=(0,Rr.normalizeGuid)(f,"id"),p=o?.[m];if(!(0,Pr.isVersionToken)(p))throw Q1(t,m,"delete",p);c.deletes.push({id:m,token:p})}let d=[...c.writes.flatMap(f=>f.kind==="patch"?[{id:f.id,verb:"update"}]:[]),...c.deletes.map(f=>({id:f.id,verb:"delete"}))];if(d.length>0){let f=await yre(e,t,n),m=d.find(p=>!f.has(p.id));if(m)throw new qi.SdkError(Ot.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': it would ${m.verb} app action '${m.id}', which is not in table '${t}''s command bar on the server \u2014 a row of another table, or one deleted since the fetch. `+Xu(t))}return c}function Q1(e,t,r,n){return new qi.SdkError(Pr.UPDATE_NO_ETAG_CODE,`Refusing to push command '${e}': ${typeof n=="string"&&n!==""?`the token held for app action '${t}' ('${n}') is not a version`:`no token is held for app action '${t}'`}, so its ${r} could not be made conditional and would overwrite or remove a concurrent edit. `+Xu(e))}async function yre(e,t,r){let n=`/appactions${(0,Rr.odataQuery)([["$select","appactionid"],["$filter",Qb(t,r)]])}`,i=await(0,Jb.collectPages)(e,n,"pushArtifact('command') bar membership"),o=new Set;for(let a of i)typeof a.appactionid=="string"&&o.add((0,Rr.normalizeGuid)(a.appactionid,"appactionid"));return o}async function bre(e,t,r,n){for(let i of t.writes)if(i.kind==="patch"){let o=(0,Pr.echoWrite)("appactionid",{"If-Match":i.token}),a=`/appactions(${i.id})${o.query}`,s=(0,Pr.ensureSuccess)(await e.patch(a,i.row.body,o.options),e.apiUrl(a));n[i.id]=(0,Pr.readEtag)(s)}else{let o=(0,Pr.echoWrite)("appactionid"),a=`/appactions${o.query}`,s={...i.row.body};s["[email protected]"]===void 0&&(s["[email protected]"]=`/entities(${r})`);let l=(0,Pr.ensureSuccess)(await e.post(a,s,o.options),e.apiUrl(a)),u=(0,Pr.readCreatedId)(l,"appactionid");u&&(n[(0,Rr.normalizeGuid)(u,"appactionid")]=(0,Pr.readEtag)(l))}for(let{id:i,token:o}of[...t.deletes].reverse())await(0,Pr.deleteRecord)(e,"appactions",i,o),delete n[i]}function vre(e){let t=new Map(e.map(o=>[o.appactionid,o])),r=new Set,n=[],i=o=>{if(r.has(o.appactionid))return;let a=o.body["[email protected]"];if(typeof a=="string"){let s=/\(([^)]+)\)/.exec(a),l=s?t.get(s[1]):void 0;l&&i(l)}r.add(o.appactionid),n.push(o)};return e.forEach(i),n}});var h$=v(el=>{"use strict";Object.defineProperty(el,"__esModule",{value:!0});el.commandRegistration=el.CommandAdapter=void 0;var lt=(j1(),Fr(z1)),e$=Jr(),bt=en(),n$=Z1(),i$=dt(),tl=se(),o$=Q(),tv="$ClientSvg:",rv=".svg",wre=2,Cre=1,Ere=1,a$="entityMetadataId",Are=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"]),gp=class{toArtifact(t){var r,n,i,o,a,s,l;let u=(r=t.appActions)!==null&&r!==void 0?r:[],c=(n=t.entityLogicalName)!==null&&n!==void 0?n:"",d=u.find(h=>typeof h.appactionid!="string"||h.appactionid==="");if(d)throw new o$.InvalidArgumentError(`Cannot read the command bar of '${c}': app action row '${String((i=d.name)!==null&&i!==void 0?i:"")}' has no appactionid (its primary key), so it cannot be placed in the bar or written back.`);let f=new Map;for(let h of u){let g=typeof h._parentappactionid_value=="string"&&h._parentappactionid_value?h._parentappactionid_value:"",b=(o=f.get(g))!==null&&o!==void 0?o:[];b.push(h),f.set(g,b)}let m=new Map;for(let h of(a=f.get(""))!==null&&a!==void 0?a:[]){let g=Dre(h.location),b=(s=m.get(g))!==null&&s!==void 0?s:[];b.push(h),m.set(g,b)}let p=[];for(let[h,g]of m)p.push({location:h,groups:Nre(g,f,c$(h),c)});return{id:c,entityLogicalName:c,commandBars:Tre(p),bag:{a:[[a$,(l=t.entityMetadataId)!==null&&l!==void 0?l:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:iv(t),appActions:Zb(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?Zb(r).map(l=>l.appactionid):[]),i=Zb(t,new Set([...n].map(l=>l.toLowerCase()))),o=new Set(i.map(l=>l.appactionid)),a=i.map(l=>{let u=l.exists||n.has(l.appactionid);return{appactionid:l.appactionid,exists:u,etag:l.etag,body:u?qre(l.row):m$(l.row)}}),s=[...n].filter(l=>!o.has(l));return(0,n$.assertOneWritePerRow)(t.entityLogicalName,{rows:a,deletedRowIds:s}),{entityLogicalName:t.entityLogicalName,entityMetadataId:iv(t),rows:a,...s.length>0?{deletedRowIds:s}:{}}}createDefault(t){var r,n,i,o;let a=(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:a,entityLogicalName:a,commandBars:(o=t.commandBars)!==null&&o!==void 0?o:[]}}assignMissingIds(t){return(0,i$.assignMissingIds)(t)}normalize(t){let r=Rre(t),n=!1,i=(Array.isArray(t.commandBars)?t.commandBars:[]).map(o=>{let a=(0,bt.isJsonObject)(o)&&Array.isArray(o.groups)?o.groups:void 0;if(!a)return o;let s=!1,l=a.map(u=>{let c=(0,bt.isJsonObject)(u)&&Array.isArray(u.controls)?u.controls:void 0;if(!c)return u;let d=c.map(f=>f$(f,r));return d.every((f,m)=>f===c[m])?u:(s=!0,{...u,controls:d})});return s?(n=!0,{...o,groups:l}):o});return n?{...t,commandBars:i}:t}validate(t){let r=[];return(0,bt.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,bt.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",r),(0,bt.childObjects)(i,"groups",a,"group",r).forEach(({node:l,index:u})=>{let c=`${a}/groups/${u}`;vp(l.bag)||((0,bt.optionalGuidId)(l,"id",c,"group-id-invalid",r),typeof l.title=="string"&&l.title.length>0&&r.push({pointer:`${c}/title`,rule:"group-toplevel-title-unsupported",message:"a new top-level command group cannot have a title: Dataverse rejects a Group row with no parent (0x80040265). Leave the title empty to hold the commands without creating a group row, or nest them under a FlyoutAnchor control, which supplies the parent a group needs."})),s$((0,bt.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};el.CommandAdapter=gp;function vp(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function s$(e,t,r){e.forEach(({node:n,index:i})=>{let o=`${t}/${i}`;vp(n.bag)||(0,bt.optionalGuidId)(n,"id",o,"control-id-invalid",r),(0,bt.optionalEnum)(n,"type",["Button","FlyoutAnchor","SplitButton"],o,"control-type-invalid",r);let a=n.location;a!==void 0&&(typeof a!="number"||!Number.isInteger(a)||a<0||a>6)&&r.push((0,bt.issue)(`${o}/location`,"control-location-invalid",`location must be an integer 0-6 when present, got ${JSON.stringify(a)}`)),n.action!==void 0&&n.action!==null&&((0,bt.isJsonObject)(n.action)?(0,bt.optionalEnum)(n.action,"type",["javascript"],`${o}/action`,"action-type-invalid",r):r.push((0,bt.issue)(`${o}/action`,"control-action-must-be-object",`a control action must be a JSON object when present, got ${typeof n.action}`)));let s=(0,bt.childObjects)(n,"children",o,"control",r);s.length>0&&s$(s,`${o}/children`,r)})}function nv(e){return{a:Object.entries(e)}}function Sre(e){return Object.fromEntries(e.a)}function Zu(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function iv(e){let t=Zu(e.bag,a$);return typeof t=="string"?t:""}function Nre(e,t,r,n){var i,o;let a=[],s=[];for(let l of bp(e))l.type===lt.ButtonType.Group?a.push({id:u$(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:bp((o=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(u=>yp(u,t,r,n)),bag:nv(l)}):s.push(yp(l,t,r,n));return s.length>0&&a.unshift({id:Bre(n,r),title:"",controls:s}),a}function ov(e){let t=e.bag?Zu(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function yp(e,t,r,n){var i,o,a,s,l;let u=u$(e.name,n),c={id:u,type:Ire(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:nv(e)},d=l$(e);d&&(c.icon=d);let f=_re(e);f&&(c.action=f),typeof e.hidden=="boolean"&&(c.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(c.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(c.location=e.location);let m=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(m&&m.length>0){let p=[],h=[];for(let g of bp(m))if(g.type===lt.ButtonType.Group){let b=(o=g.appactionid)!==null&&o!==void 0?o:"",w=nv(g);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(a=g.appactionid)!==null&&a!==void 0?a:void 0,c.flyoutGroupBag=w);let E=[];for(let S of bp((l=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let P=yp(S,t,r,n);p.push(P),E.push(ov(P))}h.push({id:b,bag:w,childIds:E})}else p.push(yp(g,t,r,n));c.children=p,h.length>1&&(c.flyoutGroups=h)}return c}function l$(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(tv)?e.fonticon.slice(tv.length)+rv:e.fonticon}function _re(e){var t;let r=e.onclickeventjavascriptfunctionname;if(typeof r!="string"||!r)return;let n=e.OnClickEventJavaScriptWebResourceId,i=e._onclickeventjavascriptwebresourceid_value,o={type:"javascript",webResourceId:(t=typeof i=="string"?i:n?.webresourceid)!==null&&t!==void 0?t:"",functionName:r};n?.name&&(o.libraryName=n.name);let a=e.onclickeventjavascriptparameters;return typeof a=="string"&&a&&(o.parameters=a),o}function t$(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function bp(e){return[...e].sort((t,r)=>t$(t)-t$(r))}function Tre(e){let t={MainTab:0,ContextualTab:1,HomeTab:2};return[...e].sort((r,n)=>{var i,o;return((i=t[r.location])!==null&&i!==void 0?i:9)-((o=t[n.location])!==null&&o!==void 0?o:9)})}function u$(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 Dre(e){switch(e){case lt.Location.Form:case lt.Location.QuickForm:return"MainTab";case lt.Location.HomePageGrid:case lt.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function c$(e){switch(e){case"MainTab":return lt.Location.Form;case"HomeTab":return lt.Location.HomePageGrid;default:return lt.Location.SubGridStandard}}function Ire(e){switch(e){case lt.ButtonType.Dropdown:return"FlyoutAnchor";case lt.ButtonType.Split:return"SplitButton";default:return"Button"}}function Ore(e){switch(e){case"FlyoutAnchor":return lt.ButtonType.Dropdown;case"SplitButton":return lt.ButtonType.Split;default:return lt.ButtonType.Standard}}function Pre(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function d$(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 Zb(e,t=new Set){var r,n,i,o;let a=[],s=iv(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=c$(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(m=>{var p;return(p=m.controls)!==null&&p!==void 0?p:[]}),d=c.length>0&&c.every(m=>!d$(m,t)),f=0;for(let m of(i=l.groups)!==null&&i!==void 0?i:[]){let p;if(Pre(m)){let h=kre(m,u,void 0,e,s);a.push(h),p=h.appactionid}for(let h of(o=m.controls)!==null&&o!==void 0?o:[])p$(h,u,p,e,s,a,d?f:void 0,t),f+=1}}return a}function f$(e,t){if(!(0,bt.isJsonObject)(e))return e;let r=e.children,n=r,i=!1;Array.isArray(r)&&(n=r.map(s=>f$(s,t)),i=n.some((s,l)=>s!==r[l]));let o=!vp(e.bag)&&(typeof e.id!="string"||e.id.trim()==="");if(!o&&!i)return e;let a;if(o){do a=(0,i$.newId)();while(t.has(a));t.add(a)}return{...e,...a!==void 0?{id:a}:{},...i?{children:n}:{}}}function Rre(e){let t=new Set,r=(o,...a)=>{if((0,bt.isJsonObject)(o))for(let s of[...a.map(l=>o[l]),vp(o.bag)?Zu(o.bag,"appactionid"):void 0])typeof s=="string"&&s.trim()!==""&&t.add(s.toLowerCase())},n=o=>{(0,bt.isJsonObject)(o)&&(r(o,"id","flyoutGroupId"),r({bag:o.flyoutGroupBag}),(Array.isArray(o.flyoutGroups)?o.flyoutGroups:[]).forEach(a=>r(a,"id")),(Array.isArray(o.children)?o.children:[]).forEach(n))},i=e.commandBars;return(Array.isArray(i)?i:[]).forEach(o=>{let a=(0,bt.isJsonObject)(o)?o.groups:void 0;(Array.isArray(a)?a:[]).forEach(s=>{r(s,"id");let l=(0,bt.isJsonObject)(s)?s.controls:void 0;(Array.isArray(l)?l:[]).forEach(n)})}),t}function p$(e,t,r,n,i,o,a,s=new Set){var l;let u=Lre(e,t,r,n,i,a);o.push(u);let c=(l=e.children)!==null&&l!==void 0?l:[];if(c.length===0&&!(e.flyoutGroups&&e.flyoutGroups.length>0))return;let d=c.every(h=>!d$(h,s)),f=(h,g,b)=>{p$(h,t,g,n,i,o,d?b:void 0,s)},m=e.flyoutGroups;if(m&&m.length>0){let h=new Map(c.map(S=>[ov(S),S])),g=new Set,b=0,w;for(let[S,P]of m.entries()){let L=P.id||(S===0?ev(u.appactionid):sv("flyout-group",`${u.appactionid}#${S}`)),I=r$(L,t,u.appactionid,n,i,P.bag);o.push(I);let D=I.appactionid;w===void 0&&(w=D);for(let O of P.childIds){let x=h.get(O);!x||g.has(O)||(g.add(O),f(x,D,b),b+=1)}}let E=w??ev(u.appactionid);for(let S of c){let P=ov(S);g.has(P)||(g.add(P),f(S,E,b),b+=1)}return}let p=e.flyoutGroupId||ev(u.appactionid);o.push(r$(p,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,g]of c.entries())f(g,p,h)}function Lre(e,t,r,n,i,o){let a=av(e,t,r,n,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let l=l$(s);return e.location!==void 0&&(s.location=e.location),s.type=Ore(e.type),s.buttonlabeltext=e.label,xre(s,e.icon,l),Mre(s,e.action),Fre(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function kre(e,t,r,n,i){let o=av(e,t,r,n,i);return o.row.type=lt.ButtonType.Group,o.row.grouptitle=e.title,o}function r$(e,t,r,n,i,o){let a=av({id:e,bag:o},t,r,n,i),s=a.row;return s["[email protected]"]=`/appactions(${(0,tl.normalizeGuid)(r,"Command flyout group id")})`,s.type=lt.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),a}function av(e,t,r,n,i){let o,a,s,l;if(e.bag&&e.bag.a.length>0){o=Sre(e.bag),a=!0;let u=Zu(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=Zu(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else{if(typeof e.id!="string"||e.id.trim()==="")throw new o$.InvalidArgumentError(`Cannot serialize command '${n.entityLogicalName}': a new control has no id. Its primary key is minted once, before the first push, by normalize() \u2014 serialize the normalized artifact.`);l=e.id,o=$re(l,t,n,i),a=!1,s=null}return r?o["[email protected]"]=`/appactions(${(0,tl.normalizeGuid)(r,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==lt.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:l,exists:a,etag:s,row:o}}function $re(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:lt.Context.Entity,contextvalue:r.entityLogicalName,scope:lt.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,tl.normalizeGuid)(n,"Command context entity metadata id")})`),i}function xre(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,tl.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(rv)?tv+t.slice(0,t.length-rv.length):t,e.IconWebResourceId=null}function Fre(e){let t=(n,i)=>{let o=e[n];if(typeof o!="string"||o.length===0||e[`${i}@odata.bind`]!==void 0)return;let a=(0,tl.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===Cre&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===Ere)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function Mre(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=wre,t.webResourceId){let r=(0,tl.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 Ure(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 sv(e,t){let r="";for(let n=0;n<4;n+=1)r+=Ure(`${n}:${e}:${t}`).toString(16).padStart(8,"0");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function ev(e){return sv("flyout-group",e)}function Bre(e,t){return sv("loose-group",`${e}|${t}`)}function m$(e){let t={...e};for(let r of Are)delete t[r];return t}function qre(e){let t=m$(e);for(let r of lt.CannotUpdateAppActionColumns)delete t[r];return t}function Vre(){return{adapter:new gp,api:n$.commandApi,publish:(e,t,r)=>(0,e$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,e$.boundEntityPublishScope)(t)}}el.commandRegistration=Vre});var y$=v(wp=>{"use strict";Object.defineProperty(wp,"__esModule",{value:!0});wp.chartApi=void 0;var Gre=Lt(),Lr=ye(),wa=se(),g$="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",Wre="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";wp.chartApi={async get(e,t){let r=(0,wa.normalizeGuid)(t,"id"),n=await(0,Lr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,wa.odataQuery)([["$select",g$]]);return{raw:(0,Lr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,wa.normalizeGuid)(t,"id"),n=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,wa.odataQuery)([["$select",g$]]),i=(0,Lr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,Lr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueryvisualizations${(0,wa.odataQuery)([["$select",Wre],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,wa.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,Gre.collectPages)(e,r,"listArtifacts('chart')")).map(i=>{var o,a;return{type:"chart",id:(o=i.savedqueryvisualizationid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.primaryentitytypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Lr.echoWrite)("savedqueryvisualizationid"),o=`/savedqueryvisualizations${i.query}`,a=(0,Lr.ensureSuccess)(await e.post(o,(0,Lr.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(o));return{id:(0,Lr.resolveCreatedId)(a,"savedqueryvisualizationid","chart",r),etag:(0,Lr.readEtag)(a)}},async update(e,t,r,n){let i=r,o=(0,wa.normalizeGuid)(t,"id"),a=(0,Lr.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,Lr.requireEtag)(n,"chart",o)}),s=`/savedqueryvisualizations(${o})${a.query}`,l=(0,Lr.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,datadescription:i.datadescription,presentationdescription:i.presentationdescription},a.options),e.apiUrl(s));return{id:o,etag:(0,Lr.readEtag)(l)}},delete(e,t){return(0,Lr.deleteRecord)(e,"savedqueryvisualizations",t)}}});var k$=v(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});nl.chartRegistration=nl.ChartAdapter=void 0;var lv=so(),b$=en(),oi=uo(),v$=Jr(),zre=y$(),uv=lo(),jre=dt(),Hre=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],Kre=new Map(Hre.map(e=>[e.toLowerCase(),e]));function S$(e){var t;return e&&(t=Kre.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function Jre(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function Yre(e){var t,r;let n=e.entityLogicalName,i=e.series.map((h,g)=>({alias:`agg_${g}`,series:h})),o=e.categories.map((h,g)=>({alias:`grp_${g}`,category:h})),a=h=>`<attribute alias="${h.alias}" name="${rl(h.series.attribute)}" aggregate="${rl(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${rl(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${rl(h.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(h,g)=>{if(!h){l.push(g);return}let b=u.get(h);b?b.push(g):u.set(h,[g])};i.forEach(h=>c(h.series.relatedEntity,a(h))),o.forEach(h=>c(h.category.relatedEntity,s(h)));let d=[...u.entries()].map(([h,g])=>`<link-entity name="${rl(h)}">${g.join("")}</link-entity>`).join(""),f=l.join("")+d,m=i.map(h=>`<measurecollection><measure alias="${h.alias}" /></measurecollection>`).join(""),p=(r=(t=o[0])===null||t===void 0?void 0:t.alias)!==null&&r!==void 0?r:"";return`<datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="${rl(n)}">${f}</entity></fetch></fetchcollection><categorycollection><category alias="${p}">${m}</category></categorycollection></datadefinition>`}var Cp=class{toArtifact(t){var r,n,i,o,a,s,l;(0,uv.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,oi.parseXmlRoot)(u,"<datadefinition/>"),f=(0,oi.parseXmlRoot)(c,"<Chart/>");return{id:(i=t.savedqueryvisualizationid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.primaryentitytypecode)!==null&&s!==void 0?s:"",chartType:Ep(f),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:T$(d),categories:D$(d),presentation:N$(f),dataBag:u?(0,oi.projectElementBag)(d):void 0,presentationBag:c?(0,oi.projectElementBag)(f):void 0,rowBag:Qre(t.charttype,t.type)}}fromArtifact(t){(0,uv.installDomShim)();let{datadescription:r,presentationdescription:n}=Xre(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:w$(t.rowBag,"charttype"),type:w$(t.rowBag,"type"),isdefault:t.isDefault}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,o,a,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:(o=u.presentationdescription)!==null&&o!==void 0?o:"",primaryentitytypecode:(a=u.primaryentitytypecode)!==null&&a!==void 0?a:"",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,o,a,s,l;(0,uv.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,jre.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New Chart",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:u,chartType:(a=t.chartType)!==null&&a!==void 0?a:"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,b$.childObjects)(n,"series","","series",r),(0,b$.childObjects)(n,"categories","","category",r),r}};nl.ChartAdapter=Cp;function Qre(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 w$(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 Ep(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return S$(t[r].getAttribute("ChartType"));return"Column"}function N$(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],o=((t=i?.textContent)!==null&&t!==void 0?t:"").trim();return o&&(r.title=o),r}function Ap(e){return e.getElementsByTagName("fetch")[0]}function _$(e){let t=new Map;if(!e)return t;let r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("alias")||l.getAttribute("name");u&&t.set(u,o)}}return t}function T$(e){let t=Ap(e);if(!t)return[];let r=_$(t),n=t.getElementsByTagName("attribute"),i=[];for(let o=0;o<n.length;o+=1){let a=n[o],s=a.getAttribute("aggregate");if(!s)continue;let l=a.getAttribute("name");if(!l)continue;let u={attribute:l,aggregate:s},c=a.getAttribute("charttype");c&&(u.seriesType=S$(c));let d=a.getAttribute("alias");d&&(u.alias=d);let f=d||l,m=r.get(f);m&&(u.relatedEntity=m),i.push(u)}return i}function D$(e){var t;let r=Ap(e);if(!r)return[];let n=_$(r),i=r.getElementsByTagName("attribute"),o=[];for(let a=0;a<i.length;a+=1){let s=i[a];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 f=d||l,m=n.get(f);m&&(u.relatedEntity=m),o.push(u)}return o}function Xre(e){var t,r;let n=(t=e.series)!==null&&t!==void 0?t:[],i=(r=e.categories)!==null&&r!==void 0?r:[];if(!C$(e.dataBag)||!C$(e.presentationBag)){let c=Yre({...e,series:n,categories:i});return{datadescription:c,presentationdescription:yne(e,c)}}let o=new DOMParser().parseFromString("<root/>","text/xml"),a=E$(e.dataBag,"datadefinition",o),s=E$(e.presentationBag,"Chart",o),l=e.chartType||Ep(s),u=T$(a);if(!cv(n,u)){let c=dv(a);Zre(o,a,n);let d=dv(a),f=d.length>0?d:n.map(()=>"");I$(o,s,f,c,l)}return cv(i,D$(a))||ene(o,a,i),e.chartType&&e.chartType!==Ep(s)&&R$(s,e.chartType),e.presentation&&!cv(e.presentation,N$(s))&&L$(s,e.presentation),{datadescription:(0,oi.serializeNode)(a),presentationdescription:(0,oi.serializeNode)(s)}}function C$(e){return!!e&&(e.c.length>0||e.a.length>0)}function I$(e,t,r,n,i){let o,a=t.childNodes;for(let d=0;d<a.length;d+=1)if(a[d].nodeType===1&&a[d].tagName==="Series"){o=a[d];break}o||(o=e.createElement("Series"),t.insertBefore(o,t.firstChild));let s=[],l=o.childNodes;for(let d=0;d<l.length;d+=1)l[d].nodeType===1&&l[d].tagName==="Series"&&s.push(l[d]);let u=new Map;n.forEach((d,f)=>{let m=s[f];if(!m)return;let p=u.get(d);p?p.push(m):u.set(d,[m])});let c=r.map(d=>{let f=u.get(d),m=f&&f.length>0?f.shift():void 0;if(m)return m;let p=e.createElement("Series");p.setAttribute("ChartType",i);let h=s.length>0?s[0].getAttribute("ChartArea"):null;return h&&p.setAttribute("ChartArea",h),p});for(let d of s)o.removeChild(d);for(let d of c)o.appendChild(d)}function dv(e){let t=[],r=e.getElementsByTagName("measure");for(let n=0;n<r.length;n+=1)t.push(r[n].getAttribute("alias")||"");return t}function E$(e,t,r){let n={n:t,a:(0,lv.mergeAttrs)(e.a,[]),c:(0,lv.spliceChildren)(e.c,[])};return(0,lv.rebuildRaw)(n,(0,oi.domEngine)(r),null)}function Zre(e,t,r){let n=Ap(t),i=n?.getElementsByTagName("entity")[0];!n||!i||O$(e,t,i,sne(n),r,une,{aliasPrefix:"aggregate_column",addRef:nne,removeRef:ane})}function ene(e,t,r){let n=Ap(t),i=n?.getElementsByTagName("entity")[0];!n||!i||O$(e,t,i,lne(n),r,cne,{aliasPrefix:"groupby_column",addRef:ine,removeRef:one})}function O$(e,t,r,n,i,o,a){let s=new Map;for(let m of n){let p=m.getAttribute("alias");p&&s.set(p,m)}let l=new Set,u=[],c=(m,p)=>{var h;let g=dne(r,m),b=p.relatedEntity;(g??void 0)!==(b??void 0)&&((h=m.parentNode)===null||h===void 0||h.removeChild(m),A$(e,r,m,b))};for(let m of i){let p=m.alias?s.get(m.alias):void 0;p&&!l.has(p)?(o(p,m),c(p,m),l.add(p)):u.push(m)}let d=n.filter(m=>!l.has(m)),f=0;for(let m of u)if(f<d.length){let p=d[f];o(p,m),c(p,m),l.add(p),f+=1}else{let p=e.createElement("attribute"),h=m.alias||rne(t,a.aliasPrefix);p.setAttribute("alias",h),o(p,m),A$(e,r,p,m.relatedEntity),a.addRef(e,t,h)}for(let m of n)if(!l.has(m)){let p=m.getAttribute("alias");p&&a.removeRef(t,p),pne(m)}}function tne(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 o=n[i].getAttribute("alias");o&&t.add(o)}}return t}function rne(e,t){let r=tne(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function P$(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function nne(e,t,r){let n=P$(e,t),i=n.getElementsByTagName("category")[0];i||(i=e.createElement("category"),n.appendChild(i));let o=e.createElement("measurecollection"),a=e.createElement("measure");a.setAttribute("alias",r),o.appendChild(a),i.appendChild(o)}function ine(e,t,r){let n=P$(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function one(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 ane(e,t){var r;let n=e.getElementsByTagName("measure"),i=[];for(let o=0;o<n.length;o+=1)n[o].getAttribute("alias")===t&&i.push(n[o]);for(let o of i){let a=o.parentNode;a?.removeChild(o),a&&a.tagName==="measurecollection"&&!hne(a)&&((r=a.parentNode)===null||r===void 0||r.removeChild(a))}}function sne(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 lne(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 une(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function cne(e,t){e.setAttribute("name",t.attribute),e.setAttribute("groupby","true"),t.dateGrouping?e.setAttribute("dategrouping",t.dateGrouping):e.hasAttribute("dategrouping")&&e.removeAttribute("dategrouping")}function dne(e,t){let r=t.parentNode;for(;r&&r!==e;){let n=r;if(n.nodeType===1&&n.tagName==="link-entity")return n.getAttribute("name")||void 0;r=n.parentNode}}function A$(e,t,r,n){n?fne(e,t,n).appendChild(r):t.appendChild(r)}function fne(e,t,r){let n=t.getElementsByTagName("link-entity");for(let o=0;o<n.length;o+=1)if(n[o].getAttribute("name")===r)return n[o];let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function pne(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!mne(t))){let r=t.parentNode;r&&r.removeChild(t)}}function mne(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 hne(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function R$(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(!gne(r[i])){r[i].setAttribute("ChartType",t);return}}}function gne(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 L$(e,t){var r;let n=e.ownerDocument;if(t.palette!==void 0&&e.setAttribute("Palette",t.palette),t.showLegend!==void 0){let i=e.getElementsByTagName("Legend").length>0;if(t.showLegend&&!i){let o=e.getElementsByTagName("Legends")[0];o||(o=n.createElement("Legends"),e.appendChild(o));let a=n.createElement("Legend");a.setAttribute("Name","Default"),o.appendChild(a)}else if(!t.showLegend)for(let o of["Legends","Legend"]){let a=[],s=e.getElementsByTagName(o);for(let l=0;l<s.length;l+=1)a.push(s[l]);for(let l of a)(r=l.parentNode)===null||r===void 0||r.removeChild(l)}}if(t.title!==void 0){let i=e.getElementsByTagName("Title")[0];i&&(i.textContent=t.title)}}function yne(e,t){let r=(0,oi.parseXmlRoot)(Jre(),"<Chart/>"),n=e.chartType||Ep(r);R$(r,n),e.presentation&&L$(r,e.presentation);let i=dv((0,oi.parseXmlRoot)(t,"<datadefinition/>"));return i.length>0&&I$(r.ownerDocument,r,i,i.slice(0,1),n),(0,oi.serializeNode)(r)}function cv(e,t){return JSON.stringify(e)===JSON.stringify(t)}function rl(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function bne(){return{adapter:new Cp,api:zre.chartApi,publish:(e,t,r)=>(0,v$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,v$.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}nl.chartRegistration=bne});var M$=v(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.dashboardApi=Ca.dashboardEntity=void 0;var vne=Lt(),Io=ye(),il=se(),wne=mg(),$$=Xl();function x$(e){return e&&e.toLowerCase()!=="none"?e:void 0}Ca.dashboardEntity=x$;var F$="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",Cne={select:F$,required:["name","type","objecttypecode","istabletenabled"]},Ene="formid,name,type,objecttypecode",Ane=0,Sne=10;Ca.dashboardApi={async get(e,t){let r=(0,il.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,il.odataQuery)([["$select",F$]]),i=(0,Io.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,$$.assertSystemFormRecordKind)(i.body,r,"dashboard","fetch"),{raw:i.body,etag:(0,Io.readEtag)(i)}},async list(e,t){let r=[`(type eq ${Ane} or type eq ${Sne})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,il.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,il.odataQuery)([["$select",Ene],["$filter",r.join(" and ")]])}`;return(await(0,vne.collectPages)(e,n,"listArtifacts('dashboard')")).map(o=>{var a,s;let l=x$(o.objecttypecode);return{type:"dashboard",id:(a=o.formid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",...l?{entityLogicalName:l}:{},isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Io.echoWrite)("formid"),o=`/systemforms${i.query}`,a={name:n.name,description:n.description,formxml:n.formxml,istabletenabled:n.istabletenabled,type:n.type};n.objecttypecode&&(a.objecttypecode=n.objecttypecode);let s=(0,Io.ensureSuccess)(await e.post(o,(0,Io.withClientMintedId)(a,"formid",r),i.options),e.apiUrl(o));return{id:(0,Io.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Io.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,wne.patchSystemForm)(e,(0,il.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,Cne)},readContentThenToken(e,t){return Ca.dashboardApi.get(e,t)},async delete(e,t){let r=(0,il.normalizeGuid)(t,"id");return await(0,$$.assertSystemFormKind)(e,r,"dashboard"),(0,Io.deleteRecord)(e,"systemforms",r)}}});var Q$=v(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});ai.dashboardRegistration=ai.TILE_CLASS_ID=ai.DashboardAdapter=void 0;var tc=so(),pn=uo(),fv=Jr(),ec=en(),W$=M$(),pv=lo(),Ea=dt(),z$=se(),j$=Ho(),Nne=Ny(),U$="0",mv="10",_ne=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"]]),Tne="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",Np=class{constructor(t=j$.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,o,a;(0,pv.installDomShim)();let s=(r=t.formxml)!==null&&r!==void 0?r:"",l=(0,pn.parseXmlRoot)(s,"<form/>");return{id:(n=t.formid)!==null&&n!==void 0?n:"",name:(i=t.name)!==null&&i!==void 0?i:"",description:(o=t.description)!==null&&o!==void 0?o:"",dashboardType:Dne(t.type),entityLogicalName:(a=(0,W$.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:Ine(l),components:B$(l,this.lcid),bag:(0,pn.projectElementBag)(l)}}fromArtifact(t){var r;return(0,pv.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?mv:U$,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:q$(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}completeAsStored(t,r){return(0,Nne.completeRecordAsStored)(t,r,this.lcid)}toApiPayload(t){return{name:t.name,description:t.description,formxml:q$(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?mv:U$,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,o,a,s,l,u;(0,pv.installDomShim)();let c=(0,pn.parseXmlRoot)(Vne(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,Ea.newId)(),name:(n=t.name)!==null&&n!==void 0?n:"New Dashboard",description:(i=t.description)!==null&&i!==void 0?i:"",dashboardType:(o=t.dashboardType)!==null&&o!==void 0?o:"Standard",entityLogicalName:(a=t.entityLogicalName)!==null&&a!==void 0?a: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:B$(c,this.lcid),bag:(0,pn.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,Ea.newId)())}return t}validate(t){let r=[],n=(0,ec.childObjects)(t,"components","","component",r),i=new Set;return n.forEach(({node:o,index:a})=>{let s=`/components/${a}`;for(let l of["position","parameters"]){let u=o[l];u!==void 0&&!(0,ec.isJsonObject)(u)&&r.push((0,ec.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,ec.isJsonObject)(o.position)){let l=rc(o.position);i.has(l)?r.push((0,ec.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};ai.DashboardAdapter=Np;function Dne(e){return String(e??"")===mv?"Interactive":"Standard"}function Ine(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),r=parseInt(t??"",10);return Number.isNaN(r)?0:r}function ae(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName.toLowerCase()===t&&r.push(o)}return r}function B$(e,t){let r=[];return ae(e,"tabs").flatMap(i=>ae(i,"tab")).forEach((i,o)=>{ae(i,"columns").flatMap(s=>ae(s,"column")).forEach((s,l)=>{ae(s,"sections").flatMap(c=>ae(c,"section")).forEach((c,d)=>{One(c,{tabIndex:o,columnIndex:l,sectionIndex:d},r,t)})})}),r}function One(e,t,r,n){ae(e,"rows").flatMap(o=>ae(o,"row")).forEach((o,a)=>{ae(o,"cell").forEach((s,l)=>{let u=Pne(s,{...t,rowIndex:a,cellIndex:l},n);u&&r.push(u)})})}function Pne(e,t,r){var n,i;let o=J$((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(o.toLowerCase().startsWith("spacer"))return null;let a=ae(e,"control")[0];if(!a)return null;let s=(i=a.getAttribute("classid"))!==null&&i!==void 0?i:"",l=kne(a),u=$ne(s,l,a),c=Rne(a);return{id:a.getAttribute("id")||o,type:u,name:K$(e,r),classId:s,position:t,colspan:_p(e,"colspan",1),rowspan:_p(e,"rowspan",1),parameters:l,bag:(0,pn.projectElementBag)(e),...c?{icProperties:c}:{}}}function H$(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 Rne(e){let t=H$(e);return t?(0,pn.serializeNode)(t):void 0}function Lne(e,t,r){let n=H$(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,o=(0,tc.rebuildRaw)((0,tc.rawFromNode)((0,pn.nodeLikeFromDom)(i)),(0,pn.domEngine)(e),null);n&&(0,pn.serializeNode)(n)===(0,pn.serializeNode)(o)||(n?t.replaceChild(o,n):t.appendChild(o))}function K$(e,t){var r,n;let i=ae(e,"labels")[0];if(!i)return"";let o=ae(i,"label"),a=(r=o.find(s=>s.getAttribute("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return(n=a?.getAttribute("description"))!==null&&n!==void 0?n:""}function kne(e){var t;let r={},n=ae(e,"parameters")[0];if(!n)return r;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];a.nodeType===1&&(r[a.tagName]=((t=a.textContent)!==null&&t!==void 0?t:"").trim())}return r}function $ne(e,t,r){var n;let i=_ne.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"?((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===Tne?"assistant":t.ChartGridMode!==void 0||r.getAttribute("indicationOfSubgrid")==="true"?t.ChartGridMode==="Chart"?"chart":"list":"unknown":i:"unknown"}function _p(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 J$(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function xne(e,t){let r={n:"form",a:(0,tc.mergeAttrs)(e.bag.a,[]),c:(0,tc.spliceChildren)(e.bag.c,[])};return(0,tc.rebuildRaw)(r,(0,pn.domEngine)(t),null)}function q$(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=xne(e,r);return Une(r,n,e.components,t),Fne(r,n,e.components,t),(0,pn.serializeNode)(n)}function Fne(e,t,r,n){let i=Y$(t);for(let o of r)i.has(rc(o.position))||Mne(e,t,o,n)}function Mne(e,t,r,n){var i,o,a,s;let l=(o=(i=r.position)===null||i===void 0?void 0:i.sectionIndex)!==null&&o!==void 0?o:0,u=Gne(t,e,l);for(let x of ae(u,"row"))ae(x,"cell").some(K=>ae(K,"control").length>0)||u.removeChild(x);let c=r.classId||ai.TILE_CLASS_ID[r.type]||ai.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,f=r.bag&&V$(r.bag,"id")?String(V$(r.bag,"id")):Sp((0,Ea.newId)()),m=r.id?Sp(r.id):Sp((0,Ea.newId)()),p=u.parentNode,h=Math.max(1,parseInt(p&&p.getAttribute&&p.getAttribute("columns")||"1",10)||1),g=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),h),b=ae(u,"row"),w=b[b.length-1],E=w?ae(w,"cell").reduce((x,K)=>x+_p(K,"colspan",1),0):0;(!w||E+g>h)&&(w=e.createElement("row"),u.appendChild(w));let S=e.createElement("cell");S.setAttribute("id",f),S.setAttribute("colspan",String(g)),S.setAttribute("rowspan",String(d)),S.setAttribute("showlabel","true");let P=e.createElement("labels"),L=e.createElement("label");L.setAttribute("description",(a=r.name)!==null&&a!==void 0?a:""),L.setAttribute("languagecode",String(n)),P.appendChild(L),S.appendChild(P);let I=e.createElement("control");I.setAttribute("id",m),I.setAttribute("classid",Sp(c));let D=e.createElement("parameters"),O=(s=r.parameters)!==null&&s!==void 0?s:{};for(let x of Object.keys(O)){let K=(0,z$.createSafeXmlElement)(e,x,"dashboard tile parameter");K.textContent=O[x],D.appendChild(K)}I.appendChild(D),S.appendChild(I),w.appendChild(S)}function V$(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Une(e,t,r,n){var i;let o=Y$(t),a=new Set(r.map(s=>rc(s.position)));for(let s of r){let l=o.get(rc(s.position));if(!l)continue;let u=ae(l,"control")[0];u&&(Bne(e,l,s.name,n),qne(e,u,s.parameters),G$(l,"colspan",s.colspan),G$(l,"rowspan",s.rowspan),s.icProperties!==void 0&&Lne(e,u,s.icProperties))}for(let[s,l]of o)a.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function Y$(e){let t=new Map;return ae(e,"tabs").flatMap(n=>ae(n,"tab")).forEach((n,i)=>{ae(n,"columns").flatMap(a=>ae(a,"column")).forEach((a,s)=>{ae(a,"sections").flatMap(u=>ae(u,"section")).forEach((u,c)=>{ae(u,"rows").flatMap(f=>ae(f,"row")).forEach((f,m)=>{ae(f,"cell").forEach((p,h)=>{var g;J$((g=p.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||ae(p,"control")[0]&&t.set(rc({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:m,cellIndex:h}),p)})})})})}),t}function rc(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function Bne(e,t,r,n){if(r===K$(t,n))return;let i=ae(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let o=ae(i,"label").find(a=>a.getAttribute("languagecode")===String(n));o||(o=e.createElement("label"),o.setAttribute("languagecode",String(n)),i.appendChild(o)),o.setAttribute("description",r)}function qne(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let o=ae(t,"parameters")[0];o||(o=e.createElement("parameters"),t.appendChild(o));let a=new Map,s=o.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];u.nodeType===1&&a.set(u.tagName,u)}for(let l of i){let u=r[l],c=a.get(l);if(c)((n=c.textContent)!==null&&n!==void 0?n:"")!==u&&(c.textContent=u);else{let d=(0,z$.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,o.appendChild(d)}}}function G$(e,t,r){_p(e,t,1)!==r&&e.setAttribute(t,String(r))}function Vne(e=2){let t=`{${(0,Ea.newId)()}}`,r=`{${(0,Ea.newId)()}}`,n=`{${(0,Ea.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>`}ai.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 Sp(e){return`{${e.replace(/[{}]/g,"")}}`}function Gne(e,t,r){var n;let i=ae(e,"tabs").flatMap(u=>ae(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let o=ae(i,"columns").flatMap(u=>ae(u,"column"))[0];if(!o)throw new Error("addDashboardTile: dashboard formxml has no <column>");let a=ae(o,"sections").flatMap(u=>ae(u,"section")),s=(n=a[r])!==null&&n!==void 0?n:a[0];if(!s)throw new Error("addDashboardTile: dashboard formxml has no <section>");let l=ae(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function Wne(e=j$.DEFAULT_LCID){return{adapter:new Np(e),api:W$.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,fv.publishBoundEntity)(t,n):(0,fv.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,fv.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}ai.dashboardRegistration=Wne});var gv=v(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.readEveryInOrder=kr.readInOrder=kr.plainRead=kr.resolveReadConcurrency=kr.MAX_READ_CONCURRENCY=void 0;var X$=Q();kr.MAX_READ_CONCURRENCY=8;function zne(e){if(e===void 0)return 1;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>kr.MAX_READ_CONCURRENCY)throw new X$.InvalidArgumentError(`readConcurrency must be a whole number from 1 to ${kr.MAX_READ_CONCURRENCY} (got ${typeof e=="string"?`'${e}'`:String(e)})`);return e}kr.resolveReadConcurrency=zne;var jne=e=>({ok:!0,value:e}),hv=e=>({ok:!1,error:e});function Hne(e){let t=(async()=>e())().then(jne,hv);return{outcome:t,finish:async r=>{await r()},discard:async()=>{await t}}}kr.plainRead=Hne;async function Z$(e,t,r,n,i){if(!Number.isInteger(t)||t<1)throw new X$.InvalidArgumentError(`a read window holds a whole number of reads, at least 1 (got ${String(t)})`);let o=new Map,a=0,s=Promise.resolve(),l=!1,u=0,c,d=async f=>{if(l)return{refusal:new Error("The read was not started: an earlier read had already failed.")};try{let m=await r(e[f],f),p=m.outcome.catch(hv);return i==="stop"&&p.then(h=>{l=l||!h.ok}),{read:m,outcome:p}}catch(m){return l=l||i==="stop",{refusal:m}}};try{for(let f=0;f<e.length;f+=1){for(;a<e.length&&a<f+t;){let g=a;a+=1;let b=s.then(()=>d(g));o.set(g,b),s=b}let m=await o.get(f),p="read"in m?await m.outcome:hv(m.refusal);if(!p.ok&&i==="stop"){c={error:p.error};break}u=f+1,o.delete(f);let h=()=>n(p,e[f],f);"read"in m?await m.read.finish(h):await h()}}finally{l=!0;for(let f=u;f<a;f+=1){let m=await o.get(f);"read"in m&&await m.read.discard().catch(()=>{})}}if(c)throw c.error}function Kne(e,t,r,n){return Z$(e,t,r,(i,o,a)=>n(i.value,o,a),"stop")}kr.readInOrder=Kne;function Jne(e,t,r,n){return Z$(e,t,r,n,"continue")}kr.readEveryInOrder=Jne});var gx=v(Dp=>{"use strict";Object.defineProperty(Dp,"__esModule",{value:!0});Dp.genPageApi=void 0;var Tp=Lt(),dx=Wl(),Be=ye(),ve=se(),$n=Dd(),Ye=Q(),fx=dt(),ex=gv();function Yne(e){if(ArrayBuffer.isView(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(Object.prototype.toString.call(e)==="[object ArrayBuffer]")return new Uint8Array(e);let t=globalThis;if(t.Buffer&&t.Buffer.isBuffer(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}}var si="uxagentprojects",Sa="uxagentprojectfiles",oc="agentconversationmessages",ac="uxagentprojectid",Ut="uxagentprojectfileid",Na="agentconversationmessageid",nc=`${ac},name`,Qne=`${Ut},filename,filetype`,px=2e8,mx=200000001,_a={"MSCRM.IncludeUnpublished":"true"},yv={};function Aa(e,t){return{"MSCRM.VersioningChangeset":e,..._a,...t}}async function wv(e,t,r,n){var i;let o=`/${t}(${r})`+(0,ve.odataQuery)([["$select",n]]),a=(0,Be.ensureSuccess)(await e.get(o,{headers:{..._a}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,Be.readEtag)(a)}}async function sc(e,t,r=_a){let n=`/${Sa}(${t})/filecontent/$value`,i=await e.get(n,{headers:{...r}});if(i.status===404)return{status:"unavailable",reason:"missing"};(0,Be.ensureSuccess)(i,e.apiUrl(n));let o=i.body,a=Yne(o);if(a)return{status:"available",data:(0,$n.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,$n.utf8ToBase64)(o)};throw new Ye.SdkError("GENPAGE_CONTENT_UNREADABLE",`Read the content of file '${t}' but the injected HttpClient returned a body this SDK cannot encode (${typeof o}). Return the response as a string, Uint8Array, Buffer, or ArrayBuffer; a byte-returning transport is required to round-trip non-UTF8 assets.`)}function hx(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function Xne(e,t,r,n,i,o){if(!e.supportsBinaryPatch)throw new Ye.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 a=`/${Sa}(${t})/filecontent`,s=(0,$n.base64ToBytes)(n);(0,ve.assertNoControlChars)(r,"generative-page file name"),(0,Be.ensureSuccess)(await e.patchRaw(a,s,{headers:Aa(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":hx(r),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function ic(e,t,r=_a){let n=`/${Sa}`+(0,ve.odataQuery)([["$select",Qne],["$filter",`_${ac}_value eq ${t}`]]);return(await(0,Tp.collectPages)(e,n,"fetchArtifact('genPage')",void 0,{headers:{...r}})).map(o=>({row:o,etag:typeof o["@odata.etag"]=="string"?o["@odata.etag"]:null}))}async function bv(e,t){let r=`/${oc}`+(0,ve.odataQuery)([["$select",`${Na},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,Tp.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{..._a}})}async function tx(e,t){var r,n,i;let{row:o,etag:a}=await wv(e,si,t,nc),s=new Map;for(let{row:l,etag:u}of await ic(e,t))s.set((0,ve.normalizeGuid)(String((r=l[Ut])!==null&&r!==void 0?r:""),Ut),{filename:String((n=l.filename)!==null&&n!==void 0?n:""),filetype:Number(l.filetype),etag:u});return{name:String((i=o.name)!==null&&i!==void 0?i:""),etag:a,rows:s}}function rx(e,t,r){var n,i,o,a,s;let l=[];r||l.push({kind:"createProject",name:t.name});let u=new Set;for(let c of(n=t.files)!==null&&n!==void 0?n:[]){let d=(0,ve.normalizeGuid)(c.id,"file id");u.add(d);let f=r?.rows.get(d);if(c.content.status==="retain"){if(!r)throw new Ye.SdkError("GENPAGE_RETAIN_ON_CREATE",`Refusing to create generative page '${e}': file '${c.name}' asks to keep content the page does not have yet. This is an SDK defect \u2014 the page's rows were not written.`);if(!f)throw new Ye.SdkError("GENPAGE_RETAINED_ROW_MISSING",`Refusing to write generative page '${e}': file '${c.name}' was to be kept unchanged but is not on the server. Re-fetch the page and retry.`);continue}f&&c.unchanged||(f?(f.filename!==c.name||f.filetype!==c.fileType)&&l.push({kind:"renameRow",file:c}):l.push({kind:"createRow",file:c}),c.content.status==="available"&&l.push({kind:"content",file:c,data:c.content.data,existing:f!==void 0}))}for(let c of(i=r?.rows.keys())!==null&&i!==void 0?i:[])u.has(c)||l.push({kind:"deleteRow",fileId:c});(!r||l.length>0||r.name!==t.name||((a=(o=t.messages)===null||o===void 0?void 0:o.length)!==null&&a!==void 0?a:0)>0)&&l.push({kind:"patchProject",name:t.name});for(let c of(s=t.messages)!==null&&s!==void 0?s:[])l.push({kind:"message",turn:c});return l}function Cv(e){let t=(0,$n.base64ToUtf8)(e);return(0,$n.utf8ToBase64)(t)===(0,$n.bytesToBase64)((0,$n.base64ToBytes)(e))?t:void 0}function Zne(e,t,r,n){var i,o,a,s,l,u,c,d;let f=t.sender==="user"?{changeSet:n,dataSources:(o=(i=r.messageContext)===null||i===void 0?void 0:i.dataSources)!==null&&o!==void 0?o:[],model:(s=(a=r.messageContext)===null||a===void 0?void 0:a.model)!==null&&s!==void 0?s:"",enabledTools:(u=(l=r.messageContext)===null||l===void 0?void 0:l.enabledTools)!==null&&u!==void 0?u:[],configurableTools:(d=(c=r.messageContext)===null||c===void 0?void 0:c.configurableTools)!==null&&d!==void 0?d:[]}:{changeSet:n};return{...t.id?{[Na]:(0,ve.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${si}(${e})`,message:t.message,messagecontext:JSON.stringify(f),messagesender:t.sender==="user"?px:mx}}async function eie(e,t,r){var n,i,o,a;let s=((n=r.messages)!==null&&n!==void 0?n:[]).map(f=>f.id).filter(f=>typeof f=="string"&&f!=="").map(f=>(0,ve.normalizeGuid)(f,"message id"));if(s.length===0)return r;let l=`/${oc}`+(0,ve.odataQuery)([["$select",`${Na},message,messagesender,_regardingobjectid_value`],["$filter",s.map(f=>`${Na} eq ${f}`).join(" or ")]]),u=await(0,Tp.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{..._a}});if(u.length===0)return r;let c=new Map(u.map(f=>{var m;return[String((m=f[Na])!==null&&m!==void 0?m:"").toLowerCase(),f]})),d=[];for(let f of(i=r.messages)!==null&&i!==void 0?i:[]){let m=f.id?c.get((0,ve.normalizeGuid)(f.id,"message id")):void 0;if(!m){d.push(f);continue}if(!(String((o=m.message)!==null&&o!==void 0?o:"")===f.message&&Number(m.messagesender)===(f.sender==="user"?px:mx)&&String((a=m._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new Ye.SdkError("GENPAGE_TURN_CONFLICT",`Refusing to push generative page '${t}': its pending turn's identity is already recorded \u2014 as a DIFFERENT ${f.sender} message. An earlier push of this turn did commit (its response was lost), and the turn was changed since. Nothing was written, and the turn is still pending. To record it as a new turn, remove '/newTurn/id' (a new identity is minted on the next push); to keep only what was recorded, remove '/newTurn'.`)}return{...r,messages:d}}function vv(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${si}`,body:(0,Be.withClientMintedId)({name:t.name},ac,e),headers:Aa(n)};case"createRow":return{method:"POST",path:`/${Sa}`,body:(0,Be.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${ac}@odata.bind`]:`/${si}(${e})`},Ut,(0,ve.normalizeGuid)(t.file.id,"file id")),headers:Aa(n)};case"renameRow":return{method:"PATCH",path:`/${Sa}(${(0,ve.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Aa(n,{"If-Match":"*"})};case"content":{let i=Cv(t.data);if(i===void 0)throw new Ye.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,ve.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${Sa}(${(0,ve.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Aa(n,{"x-ms-file-name":hx(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${Sa}(${t.fileId})`,headers:Aa(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${si}(${e})`,body:{name:t.name},headers:Aa(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${oc}`,body:Zne(e,t.turn,r,n)};default:{let i=t;throw new Ye.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function nx(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||Cv(r.data)!==void 0)}async function ix(e,t,r,n,i){await(0,dx.postChangeSet)(e,r.map(o=>vv(t,o,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function ox(e,t,r,n,i){var o;let a=[];for(let s of r){if(s.kind==="message"){a.push(s);continue}if(s.kind==="content"){await Xne(e,(0,ve.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=vv(t,s,n,i),u={headers:(o=l.headers)!==null&&o!==void 0?o:{}},c=l.method==="POST"?await e.post(l.path,l.body,u):l.method==="PATCH"?await e.patch(l.path,l.body,u):await e.delete(l.path,u);(0,Be.ensureSuccess)(c,e.apiUrl(l.path))}if(a.length===0)return{warnings:[],turnRecorded:!0};try{let s=a.map(l=>vv(t,l,n,i));if(e.supportsAtomicBatch)await(0,dx.postChangeSet)(e,s,`the conversation turn of generative page '${t}'`);else for(let l of s)(0,Be.ensureSuccess)(await e.post(l.path,l.body),e.apiUrl(l.path));return{warnings:[],turnRecorded:!0}}catch(s){return{warnings:[`Generative page '${t}' was saved, but its conversation turn could not be recorded (${s instanceof Error?s.message:String(s)}). The turn is kept: the next push of the page records it.`],turnRecorded:!1}}}async function ax(e,t,r,n,i,o,a){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...a,u]});try{let u=await tx(e,t),c=new Map;for(let E of r)(E.kind==="createRow"||E.kind==="renameRow"||E.kind==="content")&&c.set((0,ve.normalizeGuid)(E.file.id,"file id"),E.file);let d=[];u.name!==n.name&&d.push(`the page is named '${u.name}', not '${n.name}'`);for(let[E,S]of c){let P=u.rows.get(E);P&&(P.filename!==S.name||P.filetype!==S.fileType)&&d.push(`file '${S.name}' is stored as '${P.filename}' (type ${P.filetype})`)}for(let E of r){if(E.kind!=="content")continue;let S=await sc(e,(0,ve.normalizeGuid)(E.file.id,"file id")),P=(0,$n.bytesToBase64)((0,$n.base64ToBytes)(E.data));(S.status!=="available"||S.data!==P)&&d.push(S.status==="available"?`file '${E.file.name}' holds ${(0,$n.base64ToBytes)(S.data).byteLength} byte(s) that differ from the ${(0,$n.base64ToBytes)(P).byteLength} written`:`file '${E.file.name}' holds no content`)}let f=new Set(r.filter(E=>E.kind==="content").map(E=>(0,ve.normalizeGuid)(E.file.id,"file id")));for(let[E,S]of c)!f.has(E)&&(await sc(e,E)).status==="available"&&d.push(`file '${S.name}' holds content this push did not write`);if(d.length>0)return l(`Generative page '${t}' was written, but reading it back does not match what was sent: ${d.join("; ")}. The local baseline is now unusable: re-fetch the page to see what the server holds \u2014 the next push will refuse rather than overwrite blind.`);let m=await tx(e,t),p=[...m.rows.keys()],h=m.etag!==u.etag||m.rows.size!==u.rows.size||p.some(E=>{var S,P;return((S=u.rows.get(E))===null||S===void 0?void 0:S.etag)!==((P=m.rows.get(E))===null||P===void 0?void 0:P.etag)}),g=p.length!==i.size||p.some(E=>!i.has(E)),b={},w=[];for(let[E,S]of m.rows){let P=c.has(E)||!o?S.etag:(s=o.get(E))!==null&&s!==void 0?s:null;b[E]=P,P!==S.etag&&w.push(S.filename)}return h||g||!m.etag||Object.values(b).some(E=>!E)?l(`Generative page '${t}' was written, but its files changed on the server while the write was in progress, so the new concurrency tokens cannot be trusted. The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`):tie({id:t,etag:m.etag,memberEtags:b},[...a,...w.map(E=>`Generative page '${t}' was written, but its file '${E}' changed on the server while this push ran \u2014 another writer edited it. This push did not touch that file, so the next one refuses until you re-fetch the page and see their change.`)])}catch(u){return l(`The generative page was written, but reading it back failed (${u instanceof Error?u.message:String(u)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`)}}async function sx(e,t,r,n=e.readConcurrency){var i;let o=(0,ve.normalizeGuid)(t,"id"),{row:a,etag:s}=await wv(e,si,o,nc),l=await ic(e,o),u={},c=[];if(n>1)await(0,ex.readInOrder)(l,n,({row:f})=>{var m;let p=(0,ve.normalizeGuid)(String((m=f[Ut])!==null&&m!==void 0?m:""),Ut);return(0,ex.plainRead)(async()=>({fileId:p,content:await sc(e,p)}))},({fileId:f,content:m},{row:p,etag:h})=>{u[f]=h,c.push({...p,content:m})});else for(let{row:f,etag:m}of l){let p=(0,ve.normalizeGuid)(String((i=f[Ut])!==null&&i!==void 0?i:""),Ut);u[p]=m;let h=await sc(e,p);c.push({...f,content:h})}return{raw:r?{project:a,files:c,conversation:await bv(e,o)}:{project:a,files:c},etag:s,memberEtags:u}}Dp.genPageApi={get(e,t,r){return sx(e,t,!0,r?.fileConcurrency)},getForRebaseline(e,t){return sx(e,t,!1)},async getPublished(e,t){var r,n;let i=(0,ve.normalizeGuid)(t,"id"),o=`/${si}(${i})`+(0,ve.odataQuery)([["$select",nc]]),a=await e.get(o);if(a.status===404)return null;(0,Be.ensureSuccess)(a,e.apiUrl(o));let s=(r=a.body)!==null&&r!==void 0?r:{},l={},u=[],c=await ic(e,i,yv);for(let{row:g,etag:b}of c){let w=(0,ve.normalizeGuid)(String((n=g[Ut])!==null&&n!==void 0?n:""),Ut);l[w]=b,u.push({...g,content:await sc(e,w,yv)})}let d=g=>g.map(({row:b,etag:w})=>`${String(b[Ut])}@${String(w)}`).sort().join("|"),f=()=>new Ye.SdkError("GENPAGE_PUBLISHED_READ_MOVED",`The published projection of generative page '${i}' changed while it was being read, so what was read is not one published state. PublishXml is asynchronous \u2014 re-read shortly.`),m=await e.get(o);if(m.status===404)throw f();(0,Be.ensureSuccess)(m,e.apiUrl(o));let p=await ic(e,i,yv);if([(0,Be.readEtag)(a),(0,Be.readEtag)(m),...[...c,...p].map(g=>g.etag)].some(g=>!g))throw new Ye.SdkError("GENPAGE_PUBLISHED_READ_UNVERSIONED",`The published projection of generative page '${i}' answered without a version token for the page or one of its rows, so what was read cannot be proven to be one published state.`);if((0,Be.readEtag)(m)!==(0,Be.readEtag)(a)||d(p)!==d(c))throw f();return{raw:{project:s,files:u,conversation:[]},etag:(0,Be.readEtag)(a),memberEtags:l}},async list(e,t){let r=`/${si}`+(0,ve.odataQuery)([["$select",nc]]);return(await(0,Tp.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{..._a}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[ac])!==null&&o!==void 0?o:""),name:String((a=i.name)!==null&&a!==void 0?a:""),isDirty:!1}})},async create(e,t,r){var n;let i=t,o=r?(0,ve.normalizeGuid)(r,"id"):(0,fx.newId)(),a=rx(o,i,void 0);cx(e,a),ux(e,o,i);let s=lx(),l=[],u=!0;nx(e,a)?await ix(e,o,a,i,s):{warnings:l,turnRecorded:u}=await ox(e,o,a,i,s);let c=new Set(((n=i.files)!==null&&n!==void 0?n:[]).map(f=>(0,ve.normalizeGuid)(f.id,"file id"))),d=await ax(e,o,a,i,c,void 0,l);return u?d:{...d,intentPending:!0}},async update(e,t,r,n,i){var o,a;let s=r,l=(0,ve.normalizeGuid)(t,"id");if(!Array.isArray(s.files))throw new Ye.SdkError("GENPAGE_FILES_REQUIRED",`Refusing to update generative page '${l}': its payload has no files list. A page's files are its complete set of rows \u2014 a row the list omits is deleted \u2014 so an omitted list would delete every row of the page. Nothing was written.`);let u=await eie(e,l,s);ux(e,l,u);let c=await ic(e,l),{row:d,etag:f}=await wv(e,si,l,nc);if(n&&f&&n!==f)throw new Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Generative page '${l}' changed on the server after it was fetched (baseline ${n}, server ${f}) \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||!f)throw new Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify generative page '${l}' before writing: ${n?"the server did not return the page's current token":"no baseline token was recorded"}. This entity accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let m=new Map(c.map(({row:I})=>{var D,O;return[(0,ve.normalizeGuid)(String((D=I[Ut])!==null&&D!==void 0?D:""),Ut),{filename:String((O=I.filename)!==null&&O!==void 0?O:""),filetype:Number(I.filetype)}]})),p=new Set(m.keys()),h=new Set(((o=u.files)!==null&&o!==void 0?o:[]).map(I=>(0,ve.normalizeGuid)(I.id,"file id")));if(!i)throw new Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${l}' before writing: no child baseline was recorded. These rows accept no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let g=new Set(Object.keys(i).map(I=>I.toLowerCase()));for(let I of h)if(!p.has(I)&&g.has(I))throw new Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${I}' existed when this page was fetched but is gone from the server now \u2014 another writer deleted it. Refusing to recreate it, because a blind re-create would undo that delete. Re-fetch the page and re-apply the edit.`);for(let I of p)if(!g.has(I))throw new Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${I}' is on the server but absent from this page's baseline \u2014 another writer added it after the page was fetched, so its contents cannot be verified. Refusing to write over or delete it. Re-fetch the page so the addition is part of your baseline.`);let b=new Map(c.map(({row:I,etag:D})=>{var O;return[(0,ve.normalizeGuid)(String((O=I[Ut])!==null&&O!==void 0?O:""),Ut),D]}));for(let[I,D]of Object.entries(i)){let O=I.toLowerCase();if(!p.has(O))continue;let x=b.get(O);if(!D||!x)throw new Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${O}' before writing: ${D?"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(D!==x)throw new Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${O}' changed on the server after this page was fetched (baseline ${D}, server ${x}) \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 w=rx(l,u,{rows:m,name:String((a=d.name)!==null&&a!==void 0?a:"")});if(cx(e,w),w.length===0)return{id:l,etag:f,memberEtags:Object.fromEntries(c.map(({row:I,etag:D})=>{var O;return[(0,ve.normalizeGuid)(String((O=I[Ut])!==null&&O!==void 0?O:""),Ut),D]}))};let E=lx(),S=[],P=!0;nx(e,w)?await ix(e,l,w,u,E):{warnings:S,turnRecorded:P}=await ox(e,l,w,u,E);let L=await ax(e,l,w,u,h,b,S);return P?L:{...L,intentPending:!0}},async delete(e,t){var r;let n=(0,ve.normalizeGuid)(t,"id"),i=await bv(e,n);await(0,Be.deleteRecord)(e,si,n);let o=new Set(i.map(l=>{var u;return String((u=l[Na])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),a=!1;try{for(let l of await bv(e,n)){let u=String((r=l[Na])!==null&&r!==void 0?r:"");u!==""&&o.add(u)}}catch{a=!0}let s=[];for(let l of o)try{await(0,Be.deleteRecord)(e,oc,l)}catch(u){u instanceof Ye.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||a)throw new Ye.SdkError("GENPAGE_HISTORY_NOT_DELETED",`Generative page '${n}' was deleted, but its conversation history was not fully removed`+(s.length>0?` \u2014 ${s.length} of ${o.size} message(s) could not be (${s.join(", ")})`:"")+(a?" \u2014 and re-reading it after the delete failed, so a late turn may remain":"")+`. They no longer belong to any page; delete them as ${oc} rows regarding '${n}'.`)}};function lx(){return`uxagentproject_${(0,fx.newId)()}`}function tie(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function ux(e,t,r){var n,i;if(((i=(n=r.messages)===null||n===void 0?void 0:n.length)!==null&&i!==void 0?i:0)>1&&!e.supportsAtomicBatch)throw new Ye.SdkError("GENPAGE_TURN_NOT_ATOMIC",`Refusing to write generative page '${t}': its new turn has a prompt AND a reply, which must be recorded together, and the injected HttpClient does not implement postRaw() \u2014 one request at a time, a failure between the two would leave half a turn. Implement postRaw(), or record the prompt alone (omit newTurn.agentMessage). Nothing was written.`)}function cx(e,t){let r=t.filter(i=>i.kind==="content");if(r.length>0&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new Ye.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient implements neither patchRaw() nor postRaw(). A Dataverse File column is not writable through a JSON body, so proceeding would create the page and its rows and then fail, leaving a page whose source never uploaded.");if(r.some(i=>Cv(i.data)===void 0)&&!e.supportsBinaryPatch)throw new Ye.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: a file's content is not UTF-8 text, which only the binary channel can carry, and the injected HttpClient does not implement patchRaw().")}});var Lx=v(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});al.genPageRegistration=al.GenPageAdapter=void 0;var rie=gx(),nie=Jr(),Ie=en(),Lp=dt(),kp=Dd(),iie=se(),Ta=Q(),Tx=Tg(),Ev=Km(),Oo=2e8,Dx=200000001,Gi={source:{name:"src/pages/page.tsx",fileType:Oo},output:{name:"src/pages/page.compiled",fileType:Dx},config:{name:"config.json",fileType:Oo},prompt:{name:"firstPrompt.json",fileType:Oo}},Ix=Object.keys(Gi),oie=["dataSources","model","connectorBindings","actionBindings"],aie=["userMessage","agentMessage"],yx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,sie={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},lie="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function Ox(e,t,r){let n=(0,iie.normalizeGuid)(e,r).replace(/-/g,""),i=[];for(let a=0;a<32;a+=1)i.push(parseInt(n[a],16)^parseInt(t[a],16));i[12]=4,i[16]=i[16]&3|8;let o=i.map(a=>a.toString(16)).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function Ip(e,t){return Ox(e,sie[t],"id")}function uie(e,t){let r=Ox(e,lie,"newTurn.id"),n=parseInt(r.slice(24),16)%2**47+(t==="agent"?1:0);return`${r.slice(0,24)}${n.toString(16).padStart(12,"0")}`}function bx(e){return typeof e=="string"&&e.trim()!==""?e:(0,Lp.newId)()}function Vi(e){return(0,Ie.isJsonObject)(e)?e:{}}function ol(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function Op(e){return JSON.parse(JSON.stringify(e))}function cie(e){let t=Vi(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function uc(e){if(!e||e.status!=="available")return;let t=(0,kp.base64ToUtf8)(e.data);return(0,kp.utf8ToBase64)(t)===e.data?t:void 0}function Px(e,t,r){var n,i,o,a;return e.source!==void 0&&t!==void 0&&t?.source===e.source&&ol((n=t?.dataSources)!==null&&n!==void 0?n:[],(i=e.dataSources)!==null&&i!==void 0?i:[])&&((a=(o=e.bag)===null||o===void 0?void 0:o.rows)!==null&&a!==void 0?a:{}).output!==void 0&&(0,Tx.isLoadableGenPageOutput)(r)}function die(e,t){var r;try{return Px(e,t,uc((r=e.bag)===null||r===void 0?void 0:r.output))}catch{return!1}}function Pp(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,Ie.isJsonObject)(t)?t:void 0}catch{return}}function vx(e,t){if(t===Oo&&e.includes("page.tsx"))return"source";if(t===Dx&&e.includes(".compiled"))return"output";if(t===Oo&&e===Gi.config.name)return"config";if(t===Oo&&e===Gi.prompt.name)return"prompt"}function wx(e){let t=e.toLowerCase();return Ix.some(r=>Gi[r].name.toLowerCase()===t)}function Av(e){return Object.fromEntries(e)}function Rx(e,t,r,n){let i=[],o=new Set,a=new Set(t),s=l=>{if(o.has(l))return;let u=a.has(l)?e[l]:r&&Object.prototype.hasOwnProperty.call(r,l)?r[l]:void 0;u!==void 0&&(o.add(l),i.push([l,u]))};return(n??[]).forEach(s),t.forEach(s),Object.keys(r??{}).forEach(s),Av(i)}function Cx(e){var t,r,n;return Rx({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},oie,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function Ex(e){var t,r;return Rx({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},aie,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function Ax(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="dataSources"){if(!Array.isArray(o)||!o.every(a=>typeof a=="string"))return!1;e.dataSources=o}else if(i==="model"){if(typeof o!="string")return!1;e.model=o}else i==="connectorBindings"?e.connectorBindings=o:i==="actionBindings"?e.actionBindings=o:n.push([i,o]);return t.configKeys=Object.keys(r),n.length>0&&(t.config=Av(n)),!0}function Sx(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="userMessage"||i==="agentMessage"){if(typeof o!="string")return!1;i==="userMessage"?e.firstPrompt=o:e.firstAgentMessage=o}else n.push([i,o]);return t.promptKeys=Object.keys(r),n.length>0&&(t.prompt=Av(n)),!0}function cc(e){var t,r;return e.source!==void 0||Object.keys((r=(t=e.bag)===null||t===void 0?void 0:t.rows)!==null&&r!==void 0?r:{}).length>0}var fie=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function Nx(e){return cc(e)?[]:fie.filter(t=>e[t]!==void 0).map(t=>(0,Ie.issue)(`/${t}`,"genpage-raw-structured-field",`${t} cannot be applied: this page is in raw-file mode \u2014 it has no source and no managed rows, so a push writes its files[] exactly as they are, and ${t} nowhere. Set source to make the page managed (the SDK then writes config.json and firstPrompt.json from the typed fields; a file in files[] holding one of those names must be removed first), or change the file that stores the value in files[] directly.`))}function _x(){return(0,Ie.issue)("/source","genpage-source-required","the page's source cannot be removed: its source row still exists, and a page without one cannot run. Set a new source, or delete the page with deleteRemoteArtifact.")}function Rp(e){return{status:"available",data:(0,kp.utf8ToBase64)(e)}}function lc(e,t){var r,n;return{id:String((r=e.uxagentprojectid)!==null&&r!==void 0?r:""),name:String((n=e.name)!==null&&n!==void 0?n:""),files:t}}var $p=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=Vi(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(g=>{var b,w,E;let S=Vi(g);return{id:String((b=S.uxagentprojectfileid)!==null&&b!==void 0?b:""),name:String((w=S.filename)!==null&&w!==void 0?w:""),fileType:Number((E=S.filetype)!==null&&E!==void 0?E:Oo),content:cie(S.content)}}),o=Array.isArray(r?.conversation)?r.conversation.map(g=>{var b,w;let E=Vi(g);return{sender:Number(E.messagesender)===200000001?"agent":"user",message:String((b=E.message)!==null&&b!==void 0?b:""),createdOn:String((w=E.createdon)!==null&&w!==void 0?w:"")}}):void 0,a=g=>o?{...g,conversation:o}:g,s=new Map,l=[],u=!0;for(let g of i){let b=vx(g.name,g.fileType);b?((s.has(b)||g.name!==Gi[b].name)&&(u=!1),s.set(b,g)):(wx(g.name)&&(u=!1),l.push(g))}if(!u||s.size===0)return a(lc(n,i));let c=lc(n,l),d={rows:{}};for(let[g,b]of s)d.rows[g]=b.id;let f=s.get("source");if(f){let g=uc(f.content);if(g===void 0)return a(lc(n,i));c.source=g}let m=s.get("output");m&&(d.output=m.content);let p=s.get("config");if(p){let g=Pp(uc(p.content));if(!g||!Ax(c,d,g))return a(lc(n,i))}let h=s.get("prompt");if(h){let g=Pp(uc(h.content));if(!g||!Sx(c,d,g))return a(lc(n,i))}return c.bag=d,a(c)}async toApiPayload(t,r,n){var i,o,a,s,l,u,c,d,f,m,p,h,g;if(r&&!ol((i=t.conversation)!==null&&i!==void 0?i:[],(o=r.conversation)!==null&&o!==void 0?o:[]))throw new Ta.ValidationError("genPage",t.id,[(0,Ie.issue)("/conversation","genpage-conversation-read-only","conversation is the page's recorded history and cannot be edited. Record a new turn with newTurn; revert the edit to conversation before pushing.")]);let b=Nx(t);if(b.length>0)throw new Ta.ValidationError("genPage",t.id,b);let w=[],E=r===void 0,S=E&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(cc(S)){let I=(s=(a=S.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},D=ge=>{var je;return(je=I[ge])!==null&&je!==void 0?je:Ip(S.id,ge)},O=(ge,je,de)=>{w.push({id:D(ge),name:Gi[ge].name,fileType:Gi[ge].fileType,content:je,unchanged:de})};if(S.source!==void 0){O("source",Rp(S.source),!E&&r?.source===S.source&&I.source!==void 0);let ge=uc((l=S.bag)===null||l===void 0?void 0:l.output);Px(S,r,ge)?O("output",{status:"retain"},!0):O("output",Rp(await this.compile(S,S.source,n)),!1)}else{if(I.source!==void 0)throw new Ta.ValidationError("genPage",S.id,[_x()]);if(I.output!==void 0){if(!E&&!ol((u=r?.dataSources)!==null&&u!==void 0?u:[],(c=S.dataSources)!==null&&c!==void 0?c:[]))throw new Ta.ValidationError("genPage",S.id,[(0,Ie.issue)("/dataSources","genpage-source-required","the page has no source row, so its output cannot be recompiled for new data sources; set a source to change them.")]);O("output",{status:"retain"},!0)}}let x=Cx(S),K=!E&&r!==void 0&&ol(Cx(r),x);(E||I.config!==void 0||!K)&&O("config",Rp(JSON.stringify(x)),K&&I.config!==void 0);let Re=Ex(S),qt=!E&&r!==void 0&&ol(Ex(r),Re);(I.prompt!==void 0||Object.keys(Re).length>0&&!qt)&&O("prompt",Rp(JSON.stringify(Re)),qt&&I.prompt!==void 0)}for(let I of(d=S.files)!==null&&d!==void 0?d:[]){let D=(f=r?.files)===null||f===void 0?void 0:f.find(O=>O.id===I.id);w.push({id:I.id,name:I.name,fileType:I.fileType,content:I.content,unchanged:D!==void 0&&ol(D,I)})}let P=[];if(S.newTurn){let I=S.newTurn.id,D=O=>I?{id:uie(I,O)}:{};P.push({...D("user"),sender:"user",message:S.newTurn.prompt}),S.newTurn.agentMessage&&P.push({...D("agent"),sender:"agent",message:S.newTurn.agentMessage})}let L=(p=(m=S.bag)===null||m===void 0?void 0:m.config)!==null&&p!==void 0?p:{};return{name:S.name,files:w,...P.length>0?{messages:P,messageContext:{dataSources:(h=S.dataSources)!==null&&h!==void 0?h:[],model:(g=S.model)!==null&&g!==void 0?g:"",enabledTools:Array.isArray(L.enabledTools)?L.enabledTools:[],configurableTools:Array.isArray(L.configurableTools)?L.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:Op(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,o,a,s,l;if(!cc(t)&&!t.newTurn)return t;let u=Op(t);if(delete u.newTurn,!cc(t))return u;let c={...(n=u.bag)!==null&&n!==void 0?n:{},rows:{...(o=(i=u.bag)===null||i===void 0?void 0:i.rows)!==null&&o!==void 0?o:{}}};for(let d of(a=r.files)!==null&&a!==void 0?a:[]){let f=Ix.find(p=>Gi[p].name===d.name&&Gi[p].fileType===d.fileType);if(!f||u.files.some(p=>p.id===d.id)||(c.rows[f]=d.id,d.content.status!=="available"))continue;let m=(0,kp.base64ToUtf8)(d.content.data);f==="output"?c.output={status:"available",data:d.content.data}:f==="config"?(delete c.config,delete u.dataSources,delete u.model,delete u.connectorBindings,delete u.actionBindings,Ax(u,c,(s=Pp(m))!==null&&s!==void 0?s:{})):f==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,Sx(u,c,(l=Pp(m))!==null&&l!==void 0?l:{}))}return u.bag=c,u}baselineContent(t){var r;let n={...t};return delete n.conversation,delete n.newTurn,n.files=[...(r=t.files)!==null&&r!==void 0?r:[]].sort((i,o)=>i.id<o.id?-1:i.id>o.id?1:0),n}normalize(t){let r=t.newTurn;return!(0,Ie.isJsonObject)(r)||typeof r.id=="string"&&yx.test(r.id)?t:{...t,newTurn:{...r,id:(0,Lp.newId)()}}}async compile(t,r,n){var i;let o=(i=t.dataSources)!==null&&i!==void 0?i:[],a=[],s=[];if(o.forEach((f,m)=>{var p;let h=(p=n?.resolveEntity)===null||p===void 0?void 0:p.call(n,f);h&&h.columnDetailComplete===!0?a.push(h):s.push((0,Ie.issue)(`/dataSources/${m}`,h?"genpage-data-source-incomplete":"genpage-data-source-unresolved",h?`the column metadata of data source '${f}' could not be read completely (a choice or lookup read failed, or returned options with no label), so the page cannot be compiled with its enums. Retry the push.`:`the metadata of data source '${f}' could not be read, so the page cannot be compiled with its enums. Check the table's logical name and that it exists in this environment.`))}),s.length>0)throw new Ta.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new Ta.ValidationError("genPage",t.id,[(0,Ie.issue)("/source","genpage-compiler-unavailable","no TypeScript compiler is available to compile the page")]);let l=await n.loadTypeScript(),u=a.length>0?(0,Ev.buildGenPageRuntimeTypes)(a):void 0,c=a.length>0?(0,Ev.buildGenPageLegacyEnums)(a):void 0,d=(0,Tx.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new Ta.ValidationError("genPage",t.id,d.diagnostics.map(pie));return d.code}metadataNeeds(t,r){if(t.source===void 0||!Array.isArray(t.dataSources))return[];let n=die(t,r)?{fetchRequired:!1}:{};return t.dataSources.filter(i=>typeof i=="string"&&i!=="").map(i=>({entityLogicalName:i,fieldName:"",needsColumnDetail:!0,...n}))}createDefault(t){var r,n;let i=bx(t.id),o={id:i,name:(r=t.name)!==null&&r!==void 0?r:"New page",files:((n=t.files)!==null&&n!==void 0?n:[]).map(a=>{var s,l,u;return{id:bx(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=a.fileType)!==null&&l!==void 0?l:Oo,content:(u=a.content)!==null&&u!==void 0?u:{status:"available",data:""}}})};t.source!==void 0&&(o.source=t.source),t.dataSources!==void 0&&(o.dataSources=[...t.dataSources]);for(let a of["model","firstPrompt","firstAgentMessage"])t[a]!==void 0&&(o[a]=t[a]);return t.newTurn!==void 0&&(o.newTurn={...t.newTurn}),t.connectorBindings!==void 0&&(o.connectorBindings=Op(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=Op(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:Ip(i,"source"),output:Ip(i,"output"),config:Ip(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,Lp.newId)()};if(!(0,Ie.isJsonObject)(t))return t;let r=t;return(Object.keys(r).length===0||"id"in r||"content"in r||"fileType"in r||Array.isArray(r.files))&&(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Lp.newId)()),r}validate(t){let r=[],n=t;for(let s of["source","model","firstPrompt","firstAgentMessage"])n[s]!==void 0&&typeof n[s]!="string"&&r.push((0,Ie.issue)(`/${s}`,"genpage-field-type",`${s} must be a string, got ${typeof n[s]}`));if(n.source===void 0&&Vi(Vi(n.bag).rows).source!==void 0&&r.push(_x()),r.push(...Nx(t)),n.newTurn!==void 0){let s=Vi(n.newTurn);(!(0,Ie.isJsonObject)(n.newTurn)||typeof s.prompt!="string"||s.prompt.trim()==="")&&r.push((0,Ie.issue)("/newTurn/prompt","genpage-turn-prompt","newTurn needs a non-empty prompt")),s.agentMessage!==void 0&&typeof s.agentMessage!="string"&&r.push((0,Ie.issue)("/newTurn/agentMessage","genpage-field-type","newTurn.agentMessage must be a string")),s.id!==void 0&&(typeof s.id!="string"||!yx.test(s.id))&&r.push((0,Ie.issue)("/newTurn/id","genpage-turn-id","newTurn.id is the turn's identity, which the SDK mints \u2014 remove it, or keep the GUID it minted"))}if(n.dataSources!==void 0)if(!Array.isArray(n.dataSources))r.push((0,Ie.issue)("/dataSources","genpage-data-sources-array","dataSources must be an array of table logical names"));else{let s=new Set;n.dataSources.forEach((l,u)=>{typeof l!="string"||!Ev.TABLE_LOGICAL_NAME.test(l)?r.push((0,Ie.issue)(`/dataSources/${u}`,"genpage-data-source-name",`a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(l)}'`)):s.has(l)?r.push((0,Ie.issue)(`/dataSources/${u}`,"genpage-data-source-duplicate",`data source '${l}' is listed twice`)):s.add(l)})}n.conversation!==void 0&&!Array.isArray(n.conversation)&&r.push((0,Ie.issue)("/conversation","genpage-conversation-array","conversation must be an array"));let i=n.files;if(i!==void 0&&!Array.isArray(i))return r.push((0,Ie.issue)("/files","files-must-be-array",`files must be an array, got ${typeof i}`)),r;let o=cc(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=Vi(s),d=typeof c.id=="string"?c.id.trim().toLowerCase():"";if(d==="")r.push((0,Ie.issue)(u,"file-id-required","a generative-page file needs an id"));else{let g=a.get(d);g!==void 0?r.push((0,Ie.issue)(u,"file-id-duplicate",`two files share the id '${c.id}' (also at /files/${g}); a file's id is its identity, so a duplicate makes an edit ambiguous`)):a.set(d,l)}let f=typeof c.name=="string"?c.name:"",m=f.split("/");f===""||/[\u0000-\u001F\u007F]/.test(f)||f.includes("\\")||m.some(g=>g===""||g==="."||g==="..")?r.push((0,Ie.issue)(u+"/name","file-name-invalid",`a file name must be a relative path of non-empty '/'-separated segments (no '.', '..', backslash or control character \u2014 its last segment is sent as an HTTP header); got '${f}'`)):o&&(wx(f)||vx(f,Number(c.fileType))!==void 0)&&r.push((0,Ie.issue)(u+"/name","file-name-reserved",`'${f}' would be read by the maker portal as one of the page's managed rows (its source, output, config or first prompt), which the SDK writes from source and the configuration fields; it cannot also be a file in files[]`));let p=c.content;if(p===void 0){r.push((0,Ie.issue)(u+"/content","file-content-required","content is required: omitting it is indistinguishable from an empty file, and the two have opposite effects on the next push"));return}let h=Vi(p);h.status==="available"?typeof h.data!="string"&&r.push((0,Ie.issue)(u+"/content/data","file-content-data-invalid","available content needs base64 `data`")):h.status!=="unavailable"&&r.push((0,Ie.issue)(u+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(h.status)}`))}),r}};al.GenPageAdapter=$p;function pie(e){let t=`line ${e.line}, column ${e.column}`;return e.rule==="genpage-source-syntax"?(0,Ie.issue)("/source",e.rule,`${t}: ${e.message} (TS${e.code}) \u2014 the page cannot run, so it was not pushed`):(0,Ie.issue)("/source",e.rule,`${t}: ${e.message}`)}function mie(){return{adapter:new $p,api:rie.genPageApi,publish:(e,t)=>(0,nie.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}al.genPageRegistration=mie});var $x=v(Fp=>{"use strict";Object.defineProperty(Fp,"__esModule",{value:!0});Fp.reconcileBpfSecurityRoles=void 0;var kx=Lt(),Nv=Q(),xp=ye(),dc=se(),hie="Global",Sv={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function gie(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,dc.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,i=(0,xp.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.Privileges;if(!Array.isArray(o))throw new Nv.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of business process flow table '${t}' returned no 'Privileges' array (got ${(0,kx.describeMalformedValue)(o)}), so which access it can grant is unknown.`);let a=o,s={},l=new Set;return Object.keys(Sv).forEach(u=>{let c=a.find(d=>d.PrivilegeType===Sv[u]);if(c){let d=(0,dc.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function yie(e,t){var r;let n=`/RetrieveRolePrivilegesRole(RoleId=${t})`,i=(0,xp.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.RolePrivileges;if(!Array.isArray(o))throw new Nv.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of role '${t}' returned no 'RolePrivileges' array (got ${(0,kx.describeMalformedValue)(o)}), so what it holds is unknown.`);return new Set(o.map(a=>(0,dc.normalizeGuid)(a.PrivilegeId,"PrivilegeId")))}async function bie(e,t,r){if(r.length===0)return;let n={Privileges:r.map(o=>({Depth:hie,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,xp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function vie(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,xp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function wie(e,t,r){var n,i,o;if(!r||r.length===0)return;let a=await gie(e,t.toLowerCase());for(let s of r){let l=(0,dc.normalizeGuid)(s.roleId,"roleId"),u=((n=s.access)!==null&&n!==void 0?n:[]).find(c=>!a.byAccess[c]);if(u!==void 0)throw new Nv.InvalidArgumentError(`Cannot grant '${u}' access to role '${l}' on business process flow table '${t.toLowerCase()}': its metadata lists no '${(i=Sv[u])!==null&&i!==void 0?i:u}' privilege. No security role was changed.`)}for(let s of r){let l=(0,dc.normalizeGuid)(s.roleId,"roleId"),u=new Set(((o=s.access)!==null&&o!==void 0?o:[]).map(p=>a.byAccess[p]).filter(p=>!!p)),c=await yie(e,l),d=new Set([...c].filter(p=>a.all.has(p))),f=[...u].filter(p=>!d.has(p)),m=[...d].filter(p=>!u.has(p));await bie(e,l,f);for(let p of m)await vie(e,l,p)}}Fp.reconcileBpfSecurityRoles=wie});var Kx=v(Up=>{"use strict";Object.defineProperty(Up,"__esModule",{value:!0});Up.bpfApi=void 0;var dr=Yi(),xx=Wl(),Cie=Lt(),Qe=Q(),ut=ye(),mn=se(),Eie=$x(),Aie=_m(),fc=Dm(),Sie={"Content-Type":"application/json",Accept:"application/json"},Tv={...Sie,Prefer:"return=representation"},Nie=`category eq ${dr.WorkflowCategory.BusinessProcessFlow} and type eq ${dr.WorkflowTypeCode.Definition} and businessprocesstype eq ${dr.BusinessProcessType.BusinessFlow}`,_ie="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",Tie="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",Die=["xaml","name","description","processorder"];async function _v(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,Eie.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Iv(e,t,r){let n={statecode:dr.StateCode.Activated,statuscode:dr.StatusCode.Activated},i=`/workflows(${t})`,{response:o,resent:a}=await Hx(e,i,n,r,null);try{return(0,ut.ensureSuccess)(o,e.apiUrl(i))}catch(s){throw a?zx(s):s}}var Wx=new WeakSet;function zx(e){return typeof e=="object"&&e!==null&&Wx.add(e),e}function jx(e){return typeof e=="object"&&e!==null&&Wx.has(e)}function Fx(e){return e instanceof Qe.ConnectionError&&(e.statusCode===0||ut.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}async function Hx(e,t,r,n,i){let o=n??i,a=0;try{return{response:await(0,ut.resendWhile)(ut.isConcurrencyLockRefusal,()=>{a+=1;let l=a===1?n:o,u={...Tv};return l&&(u["If-Match"]=l),e.patch(t,r,{headers:u})},o?ut.LOCK_BACKOFF_MS:[]),resent:a>1}}catch(s){throw a>1?zx(s):s}}async function Mx(e,t,r){return(0,ut.readEtag)(await Iv(e,t,r))}function Ux(e,t){return new Qe.SdkError("BPF_WRITE_NOT_ECHOED",`The ${t} of business process flow '${e}' was applied, but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next step could not be conditioned on a token this push produced and was NOT sent. `+Mp(e))}async function pc(e,t){var r;let n=`/workflows(${t})${(0,mn.odataQuery)([["$select","statecode"]])}`,i=(0,ut.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.statecode,a=Number(o);if(o==null||o===""||!Number.isFinite(a))throw new Qe.SdkError("BPF_STATE_UNREADABLE",`Reading the state of business process flow '${t}' answered HTTP ${i.status} without a usable statecode, so whether it is Active cannot be decided.`);return a}async function Dv(e,t,r,n,i=null){if((n??await pc(e,t))!==dr.StateCode.Activated)return{deactivated:!1,etag:null};let o={statecode:dr.StateCode.Draft,statuscode:dr.StatusCode.Draft},a=`/workflows(${t})`,s,l;try{({response:s,resent:l}=await Hx(e,a,o,r,i))}catch(c){return await Bx(e,t,c,jx(c))}if(ut.AMBIGUOUS_WRITE_STATUSES.has(s.status))return await Bx(e,t,new Qe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' answered HTTP ${s.status} from an intermediary, so whether it committed is unknown.`),l);let u=(0,ut.ensureSuccess)(s,e.apiUrl(a));return{deactivated:!0,etag:(0,ut.readEtag)(u)}}async function Bx(e,t,r,n){let i;try{i=await pc(e,t)}catch{i=void 0}if(i===dr.StateCode.Draft&&!n)return{deactivated:!0,etag:null,uncertainCause:r};if(i===dr.StateCode.Activated)throw r;let o=new Qe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",i===dr.StateCode.Draft?`Deactivating business process flow '${t}' waited for the platform's concurrency lock, and its last attempt ended without a definitive answer. The process now reads Draft, but whether this deactivate or another writer's change put it there is unknown \u2014 the row may even have been replaced at the same id \u2014 so nothing more was sent: no edit, no re-activation, no delete. It MAY be left DISABLED: read it before retrying. Original failure: ${r instanceof Error?r.message:String(r)}`:`Deactivating business process flow '${t}' did not complete, and its state could not be re-read \u2014 it MAY be left DISABLED and needs reconciling. Original failure: ${r instanceof Error?r.message:String(r)}`);throw(0,Qe.attachCause)(o,r),o}async function Iie(e,t){let r=(0,mn.normalizeGuid)(t,"workflowid");try{return await Iv(e,r,null),"restored"}catch{return Ov(e,r)}}async function Oie(e,t,r){let n=(0,mn.normalizeGuid)(t,"workflowid");try{return await Iv(e,n,r),"restored"}catch(i){return i instanceof Qe.SdkError&&i.code===ut.VERSION_CONFLICT_CODE?"changed":Ov(e,n)}}async function Ov(e,t){try{let r=await pc(e,t);return r===dr.StateCode.Activated?"restored":r===dr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}async function qx(e,t,r,n){return r?{outcome:await Oie(e,t,r),attempted:!0}:n?{outcome:await Ov(e,(0,mn.normalizeGuid)(t,"workflowid")),attempted:!1}:{outcome:await Iie(e,t),attempted:!0}}function Pie(e,t){let r=new Qe.SdkError(fc.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting business process flow '${e}' failed${(0,fc.failedAfterResend)(t)?" after it was re-sent":""}, and re-activating the process this delete had deactivated was refused (HTTP 412): the row at that id is no longer the version this delete deactivated \u2014 it was edited, or deleted and re-created at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read the row before deleting it again. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function Vx(e,t,r,n,i=!0){let o=`Original failure: ${n instanceof Error?n.message:String(n)}`,a="it was NOT re-activated: it waited for the platform's concurrency lock, and no write of this operation proves the row is still its own, so a re-activation could have enabled another writer's edit",s;return r==="changed"?s=new Qe.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",`Business process flow '${e}' was deactivated ${t}, and re-activating it was refused (HTTP 412): the row is no longer the version this operation last wrote \u2014 another writer changed it, or replaced it at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read it before retrying. ${o}`):r==="disabled"?s=new Qe.SdkError("BPF_LEFT_DEACTIVATED",i?`Business process flow '${e}' was deactivated ${t}, and it could NOT be reactivated \u2014 it is left DISABLED. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a} \u2014 it is left DISABLED. ${o}`):s=new Qe.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",i?`Business process flow '${e}' was deactivated ${t}, and whether it was reactivated could not be confirmed \u2014 it MAY be left DISABLED and needs checking. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a}; its state could not be read \u2014 it MAY be left DISABLED and needs checking. ${o}`),(0,Qe.attachCause)(s,n),s}async function Rie(e,t){try{return await pc(e,t),"survived"}catch(r){return r instanceof Qe.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function Lie(e,t,r){if(r)try{let{deactivated:n,etag:i}=await Dv(e,t,r),o=n?i:r;if(o)return await(0,fc.deleteWorkflowResending)(e,t,{bindingToken:o,kindName:"business process flow",resendDeadlockVictim:!0,ifMatchOnFirst:!0}),"removed"}catch{}return Rie(e,t)}function Mp(e){return`Adopt the server's copy with fetchArtifact('bpf', '${e}', { overwrite: true }) \u2014 it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push.`}function Gx(e,t){return new Qe.SdkError("BPF_CREATE_NO_TOKEN",`Created business process flow '${e}' but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next push would have nothing to condition on. ${t} It was NOT rolled back: deleting it without a token could remove an edit made since. ${Mp(e)}`)}function kie(e,t){let r=new Qe.SdkError("BPF_CREATE_NOT_ROLLED_BACK",`Creating business process flow '${e}' failed part-way, and the rollback could NOT remove it \u2014 it still EXISTS, possibly Active and half-configured. (The rollback deletes only on a token this create produced, so a row somebody has since edited is left in place on purpose; a delete the platform refused or failed leaves it too.) ${Mp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function $ie(e,t){let r=new Qe.SdkError("BPF_CREATE_ROLLBACK_OUTCOME_UNKNOWN",`Creating business process flow '${e}' failed part-way, and whether its rollback removed the process could not be confirmed \u2014 it MAY still exist, possibly Active and half-configured. ${Mp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function xie(e,t){let r=new Qe.SdkError("BPF_CREATE_REMOVED_AFTER_CONFLICT",`Creating business process flow '${e}' was interrupted: another writer changed it right after it was created, so this push's next step was refused rather than overwrite or activate their edit \u2014 and the process has since been removed. Nothing is left behind and there is nothing to fetch. If the removal was deliberate, stop here; otherwise push again to re-create it at the same id. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function Pv(e){let t={};for(let r of Die)e[r]!==void 0&&(t[r]=e[r]);return t}var Fie=["name,processorder","description,name,processorder"];function Mie(e){let{xaml:t,...r}=Pv(e);return typeof t=="string"&&Fie.includes(Object.keys(r).sort().join(","))}async function Uie(e,t,r,n){let{xaml:i,...o}=Pv(r),[,a]=await(0,xx.sendChangeSet)(e,[{method:"PATCH",path:`/workflows(${t})`,body:o,etag:n},{method:"PATCH",path:`/workflows(${t})${(0,mn.odataQuery)([["$select","workflowid"]])}`,body:{xaml:i},headers:{Prefer:"return=representation"}}],`business process flow '${t}'`);return(0,ut.readEtag)((0,xx.partResponse)(a))}Up.bpfApi={async get(e,t){let n=`/workflows(${(0,mn.normalizeGuid)(t,"id")})${(0,mn.odataQuery)([["$select",Tie]])}`,i=(0,ut.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,ut.readEtag)(i)}},async list(e,t){let r=[Nie];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,mn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,mn.odataQuery)([["$select",_ie],["$filter",r.join(" and ")]])}`;return(await(0,Cie.collectPages)(e,n,"listArtifacts('bpf')")).map(o=>{var a,s;return{type:"bpf",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){let r=t,n=(0,mn.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",o=(0,ut.ensureSuccess)(await e.post(i,r.record,{headers:Tv}),e.apiUrl(i)),a=(0,ut.readEtag)(o);if(!a)throw Gx(n,r.status==="Active"?"The process EXISTS as Draft and was NOT activated \u2014 an activation that cannot be conditioned on our own write could activate somebody else's edit.":"The process EXISTS as Draft.");let s=a;try{r.status==="Active"&&(s=await Mx(e,n,a)),await _v(e,r)}catch(l){let u=await Lie(e,n,s);throw u==="survived"?kie(n,l):u==="unknown"?$ie(n,l):l instanceof Qe.SdkError&&l.code===ut.VERSION_CONFLICT_CODE?xie(n,l):l}if(!s)throw Gx(n,"The process EXISTS and IS Active, but its activation returned no token.");return{id:n,etag:s}},async update(e,t,r,n){let i=r,o=(0,mn.normalizeGuid)(t,"id"),a=(0,ut.requireEtag)(n,"bpf",o),s=await pc(e,o);if(s===dr.StateCode.Activated&&i.status==="Active"&&e.supportsAtomicBatch&&Mie(i.record)){let m=await Uie(e,o,i.record,a);return await _v(e,i),{id:o,etag:m}}let{deactivated:l,etag:u,uncertainCause:c}=await Dv(e,o,a,s),d=u,f=!1;try{if(c!==void 0)throw c;let m=a;if(l){if(!u)throw Ux(o,"deactivation");m=u}let p=`/workflows(${o})`,h;try{h=(0,ut.ensureSuccess)(await e.patch(p,Pv(i.record),{headers:{...Tv,"If-Match":m}}),e.apiUrl(p))}catch(b){throw Fx(b)&&(d=null),b}let g=(0,ut.readEtag)(h);if(d=g,i.status==="Active"){if(!g)throw Ux(o,"definition write");try{g=await Mx(e,o,g)}catch(b){throw Fx(b)&&(d=null),b}f=!0}return await _v(e,i),{id:o,etag:g}}catch(m){if(l&&!f){let{outcome:p,attempted:h}=await qx(e,o,d,jx(m));if(p!=="restored")throw Vx(o,"to apply an edit, the edit failed",p,m,h)}throw m}},async delete(e,t){let r=(0,mn.normalizeGuid)(t,"id"),n=await(0,Aie.assertWorkflowKind)(e,r,dr.WorkflowCategory.BusinessProcessFlow),{deactivated:i,etag:o}=await Dv(e,r,null,void 0,n);try{await(0,fc.deleteWorkflowResending)(e,r,{bindingToken:i?o:n,kindName:"business process flow",deactivated:i,resendDeadlockVictim:!0})}catch(a){if(i&&!(0,fc.isWorkflowDeleteUnsettled)(a)){let{outcome:s,attempted:l}=await qx(e,r,o,!1);if(s==="changed")throw Pie(r,a);if(s!=="restored")throw Vx(r,"so it could be deleted, the delete failed",s,a,l)}throw a}}}});var PF=v(ll=>{"use strict";Object.defineProperty(ll,"__esModule",{value:!0});ll.bpfRegistration=ll.BpfAdapter=void 0;var Bp=Yi(),Bie=Kx(),Rv=so(),Da=uo(),sF=lo(),zr=en(),$r=dt(),xn=Q(),qie=100,Lv='<?xml version="1.0" encoding="utf-16"?>',Jx=1033,lF="mxswa:Workflow",Vie="mxswa:ActivityReference.Properties",Gie="mcwo:StepLabel",Wie="mcwb:Control",Yx="mcwb:Control.ControlDisplayName",uF="mcwb:Control.DataFieldName",cF="DataFieldName",Qx="ControlDisplayName",dF="Literal",Vp="x:Null",Xx="x:String",kv="x:Key",$v="DisplayName",Wp="Activities",zie="StepLabels",fF="StageId",pF="StageCategory",mF="NextStageId",hF="ProcessStepId",qp="IsProcessRequired",gF="EntityComposite",yF="StageComposite",bF="StepComposite";function mc(e){return(0,zr.isJsonObject)(e)?e:{}}function ui(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 Ia(e,t){var r;return(r=ui(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function di(e){return Ia(e,Vie)}function fr(e,t){var r;return(r=ui(e).find(n=>n.getAttribute(kv)===t))!==null&&r!==void 0?r:null}function sl(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function ci(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function vF(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function hc(e){var t;let r=(t=e.getAttribute($v))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function wF(e,t){var r;let n=(r=e.getAttribute($v))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute($v,i>=0?n.slice(0,i+2)+t:t)}function CF(e,t){let r=fr(e,zie),n=Ia(r,Gie);n&&n.setAttribute("Description",t)}function jie(e){let t=fr(e,pF);if(!t||t.tagName===Vp)return;let r=ci(t).trim();return r===""?void 0:Number(r)}function Hie(e){let t=fr(e,mF);if(!t||t.tagName===Vp)return;let r=ci(t).trim();return r===""?void 0:r}function EF(e){let t=AF(e);if(!t)return;let r=NF(t,cF,uF);return r===""?void 0:r}function xv(e,t){let r=ui(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of ui(n))r.push(i)}return null}function AF(e){let t=fr(di(e),Wp);return t?xv(t,Wie):null}function SF(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 NF(e,t,r){var n;return SF(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":Xie(e,r)}function Zx(e,t,r,n){if(SF(e,t)){e.setAttribute(t,n);return}if(Ia(e,r)){Kie(e,r,n);return}throw new xn.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function Kie(e,t,r){let n=Ia(e,t),i=n?xv(n,dF):null;if(!i)throw new xn.InvalidArgumentError(`BPF step control's <${t}> wrapper holds no <Literal> to bind a column`);i.setAttribute("Value",r)}function _F(e){return hc(e)}function zp(e){let t=Ia(e,lF),r=[];for(let n of ui(t).filter(i=>sl(i,gF))){let i=fr(di(n),Wp);for(let o of ui(i).filter(a=>sl(a,yF)))r.push({el:o,entity:_F(n)})}return r}function Fv(e){let t=fr(di(e),Wp);return ui(t).filter(r=>sl(r,bF))}function Jie(e){let t=di(e),r=ci(fr(t,qp)).trim().toLowerCase(),n=EF(e),i={id:ci(fr(t,hF)),name:hc(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function Yie(e,t){let r=di(e),n=jie(r),i=Hie(r),o={id:ci(fr(r,fF)),name:hc(e),entityLogicalName:t,steps:Fv(e).map(Jie)};return n!==void 0&&(o.category=n),i!==void 0&&(o.nextStageId=i),o}function Qie(e){return zp(e).map(({el:t,entity:r})=>Yie(t,r))}function li(e){return new xn.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 Xie(e,t){var r;let n=Ia(e,t),i=n?xv(n,dF):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function Mv(e,t){var r;let n=e.createElement(t.tagName),i=t.attributes;for(let a=0;a<i.length;a+=1)n.setAttribute(i[a].name,i[a].value);let o=t.childNodes;for(let a=0;a<o.length;a+=1){let s=o[a];s.nodeType===1?n.appendChild(Mv(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function TF(e){return fr(di(e),Wp)}function Zie(e,t,r){var n;let i=t.entityLogicalName&&t.entityLogicalName.trim()!==""?t.entityLogicalName:r,o=!((n=t.steps[0])===null||n===void 0)&&n.id&&t.steps[0].id.trim()!==""?t.steps[0].id:(0,$r.newId)(),{body:a}=jp(Uv(i,(0,$r.newId)(),t.id,o));return Mv(e,zp((0,Da.parseXmlRoot)(a,"<Activity/>"))[0].el)}function eoe(e,t){let{body:r}=jp(Uv("account",(0,$r.newId)(),(0,$r.newId)(),t.id));return Mv(e,Fv(zp((0,Da.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function DF(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function IF(e,t,r,n){let i=fr(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw li(`setting '${r}' on a stage whose xaml does not expose that slot`);return}let o=i.parentNode;if(n===void 0||n===""){if(i.tagName!==Vp&&ci(i).trim()!==""){let s=t.createElement(Vp);s.setAttribute(kv,r),o.replaceChild(s,i)}return}if(i.tagName===Xx){ci(i).trim()!==n&&vF(i,t,n);return}let a=t.createElement(Xx);a.setAttribute(kv,r),a.appendChild(t.createTextNode(n)),o.replaceChild(a,i)}function toe(e,t,r){IF(e,t,pF,r===void 0?void 0:String(r))}function roe(e,t,r){IF(e,t,mF,r)}function OF(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 eF(e){return ci(fr(di(e),fF))}function tF(e){return ci(fr(di(e),hF))}function rF(e,t,r){var n,i,o,a;let s=di(e);r.name!==hc(e)&&(wF(e,r.name),CF(s,r.name));let l=ci(fr(s,qp)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=fr(s,qp);if(!u)throw li(`setting '${qp}' on a step whose xaml does not expose that slot`);vF(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((o=EF(e))!==null&&o!==void 0?o:"")){let u=AF(e);if(!u)throw new xn.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=r.fieldName)!==null&&a!==void 0?a:"";Zx(u,cF,uF,c),c!==""&&NF(u,Qx,Yx)===""&&Zx(u,Qx,Yx,c)}}function nF(e,t,r,n){var i;let o=di(e);if(!o)throw new xn.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==hc(e)&&(wF(e,r.name),CF(o,r.name)),toe(o,t,r.category),roe(o,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw li("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw li("stage actions or conditional branching");let a=TF(e);if(!a)throw new xn.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new xn.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=Fv(e);if(OF(l,s.map(d=>d.id),tF)){l.forEach((d,f)=>rF(d,t,s[f]));return}let u=new Map(l.map(d=>[tF(d),d]));if(ui(a).some(d=>!sl(d,bF)))throw li("adding, removing or reordering steps on a stage that also contains branching or actions");let c=s.map(d=>{var f;return(f=u.get(d.id))!==null&&f!==void 0?f:eoe(t,d)});DF(a,c),c.forEach((d,f)=>rF(d,t,s[f]))}function noe(e,t,r){let n=Ia(e,lF);if(!n)throw new xn.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw li("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new xn.InvalidArgumentError("a BPF must have at least one stage");let i=zp(e),o=i.map(f=>f.el);if(OF(o,r.stages.map(f=>f.id),eF)){i.forEach(({el:f,entity:m},p)=>{let h=r.stages[p];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==m)throw li(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${m}')`);nF(f,t,h,h.nextStageId)});return}let a=ui(n).filter(f=>sl(f,gF));if(a.length!==1)throw li("adding, removing or reordering stages on a multi-table process");let s=a[0],l=_F(s),u=TF(s);if(!u)throw new xn.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(ui(u).some(f=>!sl(f,yF)))throw li("adding, removing or reordering stages on a process whose primary composite holds non-stage activities (multi-table nesting or advanced constructs)");for(let f of r.stages)if(f.entityLogicalName&&f.entityLogicalName.trim()!==""&&f.entityLogicalName!==l)throw li(`a stage on a different table ('${f.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(o.map(f=>[eF(f),f])),d=r.stages.map(f=>{var m;return(m=c.get(f.id))!==null&&m!==void 0?m:Zie(t,f,l)});DF(u,d),d.forEach((f,m)=>{let p=m<d.length-1?r.stages[m+1].id:void 0;nF(f,t,r.stages[m],p)})}function jp(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function ioe(e){var t,r,n,i,o,a;(0,sF.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let f=new DOMParser().parseFromString("<root/>","text/xml"),m={n:"Activity",a:(0,Rv.mergeAttrs)(s.a,[]),c:(0,Rv.spliceChildren)(s.c,[])};return{root:(0,Rv.rebuildRaw)(m,(0,Da.domEngine)(f),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Lv,eol:(o=(i=e.bag)===null||i===void 0?void 0:i.xamlEol)!==null&&o!==void 0?o:"lf"}}let l=e.stages[0],u=(a=l?.steps)===null||a===void 0?void 0:a[0],c=Uv(e.entityLogicalName,(0,$r.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,$r.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,$r.newId)()),{body:d}=jp(c);return{root:(0,Da.parseXmlRoot)(d,"<Activity/>"),prolog:Lv,eol:"lf"}}function ooe(e){let{root:t,prolog:r,eol:n}=ioe(e);noe(t,t.ownerDocument,e);let i=(0,Da.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r
-`)),r+i}function aoe(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Gp=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,sF.installDomShim)();let i=t,o=typeof i.xaml=="string"?i.xaml:"",a={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&&(a.uniqueName=String(i.uniquename)),i.description!=null&&i.description!==""&&(a.description=String(i.description)),i.processorder!=null&&i.processorder!==""&&(a.order=Number(i.processorder)),o.trim()!==""){let{prolog:s,body:l}=jp(o),u=(0,Da.parseXmlRoot)(l,"<Activity/>");a.stages=Qie(u),a.bag={xaml:(0,Da.projectElementBag)(u),xamlProlog:s,xamlEol:/\r\n/.test(o)?"crlf":"lf"}}return a}toApiPayload(t){var r;let n={workflowid:t.id&&t.id.trim()!==""?t.id:(0,$r.newId)(),name:t.name,uniquename:aoe(t),primaryentity:t.entityLogicalName,xaml:ooe(t),category:Bp.WorkflowCategory.BusinessProcessFlow,type:Bp.WorkflowTypeCode.Definition,businessprocesstype:Bp.BusinessProcessType.BusinessFlow,scope:Bp.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:qie};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 xn.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 o=t.stages&&t.stages.length>0?t.stages.map(oF):[oF({id:(0,$r.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,$r.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:o};return t.uniqueName&&(a.uniqueName=t.uniqueName),t.description!==void 0&&(a.description=t.description),t.order!==void 0&&(a.order=t.order),t.globalActions!==void 0&&(a.globalActions=t.globalActions),t.securityRoles!==void 0&&(a.securityRoles=t.securityRoles),a}assignMissingIds(t){let r=mc(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,$r.newId)());for(let n of["stages","steps","actions","globalActions"]){let i=r[n];Array.isArray(i)&&i.forEach(o=>this.assignMissingIds(o))}return r}validate(t){let r=[],n=t.stages;if(n!==void 0&&!Array.isArray(n))return r.push((0,zr.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,zr.issue)("/stages","too-many-stages",`a BPF allows at most 30 stages, got ${i.length}`));let o=new Set,a=new Map;i.forEach((l,u)=>{let c=`/stages/${u}`,d=mc(l),f=typeof d.id=="string"?d.id.trim():"";f===""?r.push((0,zr.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(f.toLowerCase())?r.push((0,zr.issue)(`${c}/id`,"stage-id-duplicate",`two stages share the id '${d.id}' (also at /stages/${a.get(f.toLowerCase())})`)):a.set(f.toLowerCase(),u),typeof d.entityLogicalName=="string"&&d.entityLogicalName!==""&&o.add(d.entityLogicalName);let m=Array.isArray(d.steps)?d.steps:[];m.length===0&&r.push((0,zr.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),m.length>30&&r.push((0,zr.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${m.length}`));let p=new Map;m.forEach((h,g)=>{let b=`${c}/steps/${g}`,w=typeof mc(h).id=="string"?h.id.trim():"";w===""?r.push((0,zr.issue)(`${b}/id`,"step-id-required","a step needs an id")):p.has(w.toLowerCase())?r.push((0,zr.issue)(`${b}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):p.set(w.toLowerCase(),g)}),d.branch&&!iF(i,d.branch.nextStageId)&&r.push((0,zr.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${d.branch.nextStageId}' does not match any stage id`)),typeof d.nextStageId=="string"&&d.nextStageId!==""&&!iF(i,d.nextStageId)&&r.push((0,zr.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${d.nextStageId}' does not match any stage id`))}),o.size>5&&r.push((0,zr.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=soe(i);return s>=0&&r.push((0,zr.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};ll.BpfAdapter=Gp;function soe(e){let t=new Map(e.map(r=>[mc(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 iF(e,t){return e.some(r=>mc(r).id===t)}function oF(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(aF):[aF({id:(0,$r.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,$r.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 aF(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,$r.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 Uv(e,t,r,n){return`${Lv}<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="${Jx}" /></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="${Jx}" /></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 loe(){return{adapter:new Gp,api:Bie.bpfApi,languageSensitive:!0}}ll.bpfRegistration=loe});var RF=v(Hp=>{"use strict";Object.defineProperty(Hp,"__esModule",{value:!0});Hp.buildRegistrations=void 0;var uoe=SL(),coe=WL(),doe=_1(),foe=W1(),poe=h$(),moe=k$(),hoe=Q$(),goe=Lx(),yoe=PF();function boe(e){let t=new Map;return t.set("form",(0,uoe.formRegistration)(e)),t.set("view",(0,coe.viewRegistration)()),t.set("businessRule",(0,doe.businessRuleRegistration)()),t.set("app",(0,foe.appRegistration)(e)),t.set("command",(0,poe.commandRegistration)()),t.set("chart",(0,moe.chartRegistration)()),t.set("dashboard",(0,hoe.dashboardRegistration)(e)),t.set("genPage",(0,goe.genPageRegistration)()),t.set("bpf",(0,yoe.bpfRegistration)()),t}Hp.buildRegistrations=boe});var jF=v(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE=Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE=Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE=Te.removeRowSummary=Te.configureRowSummary=Te.buildGptDynamicPrompt=Te.setAppAiFeatures=Te.getAiReadiness=Te.saveSettingValue=Te.retrieveSetting=Te.AI_GATE=void 0;var Wi=Lt(),hn=ye(),qe=se(),LF=dt(),Ve=Q();Te.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var UF={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},voe=new Set(Object.entries(Te.AI_GATE).filter(([e,t])=>UF[e]===t).map(([e])=>e)),woe={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function Bv(e){return woe[e]}var Kp=1e6;function Coe(e,t){let r=Bv(t),n=()=>{throw new Ve.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Kp} (e.g. 0, 1, 2); got '${String(e)}'.`)},i=o=>r?o?r.enabled:r.disabled:o?"1":"0";if(typeof e=="boolean")return i(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>Kp?n():String(e);if(typeof e=="string"){let o=e.trim(),a=o.toLowerCase();if(a==="true")return i(!0);if(a==="false")return i(!1);if(/^[0-9]+$/.test(o)){let s=o.replace(/^0+(?=[0-9])/,"");return s.length>String(Kp).length||Number(s)>Kp?n():s}}return n()}function Eoe(e,t){let r=Bv(t);return r?e===r.enabled:e!=="0"}async function Aoe(e,t){var r,n;let i=`/appmodules${(0,qe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,o=await e.get(i);if(o.status<200||o.status>=300)return;let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ve.ConnectionError(e.apiUrl(i),o.status,`the app lookup for '${t}' returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,Wi.describeMalformedValue)(a)}`);return(n=a[0])===null||n===void 0?void 0:n.appmoduleid}async function Soe(e,t){var r,n;let i=`/appmodules${(0,qe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,o;try{o=await e.get(i)}catch(l){throw new Ve.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(o.status<200||o.status>=300)throw new Ve.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned HTTP ${o.status}. Retry, or omit appModuleId to verify by name.`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ve.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a malformed body.`);if(a.length===0)return;let s=(n=a[0])===null||n===void 0?void 0:n.appmoduleid;if(!s)throw new Ve.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var kF=new WeakMap;async function Noe(e,t){var r,n;let i=kF.get(e);if(i||(i=new Map,kF.set(e,i)),i.has(t))return i.get(t);let o=`/settingdefinitions${(0,qe.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,a=await e.get(o);if(a.status<200||a.status>=300)return;let s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))throw new Ve.ConnectionError(e.apiUrl(o),a.status,`the setting definition lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,Wi.describeMalformedValue)(s)}`);let l=(n=s[0])===null||n===void 0?void 0:n.settingdefinitionid;return l&&i.set(t,l),l}async function _oe(e,t,r){var n,i;let o=await Noe(e,r);if(!t||!o)return;let a=`/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()${(0,qe.odataQuery)([["$select","value,componentstate"],["$filter",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${o}`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)return;let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new Ve.ConnectionError(e.apiUrl(a),s.status,`the app-scope override read returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,Wi.describeMalformedValue)(l)}`);let u=l;if(u.length===0)return{exists:!1};let c=(i=u.find(d=>d?.componentstate===1))!==null&&i!==void 0?i:u[0];return{exists:!0,value:c.value,pendingPublish:c.componentstate===1}}var Toe=4,Doe=500,$F=20,xF=3e4;function Ioe(e){if(e===void 0)return Toe;if(!Number.isFinite(e))throw new Ve.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${$F}; got ${e}.`);return Math.min($F,Math.max(1,Math.floor(e)))}function Ooe(e){if(e===void 0)return Doe;if(!Number.isFinite(e))throw new Ve.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${xF}; got ${e}.`);return Math.min(xF,Math.max(0,Math.floor(e)))}async function Poe(e,t,r,n,i,o,a){let s,l,u,c=!1;for(let d=0;d<o;d+=1){d>0&&await new Promise(m=>setTimeout(m,a*d));let f;try{let m=await t();m?(f=await _oe(e,m,n),f===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){f=void 0,u=m.message}c=f!==void 0,l=f?.exists;try{s=(await Jp(e,n,{appUniqueName:r})).value}catch{}if(f?.exists&&f.value===i)return{result:"proven",effectiveValue:f.value,appOverrideExists:!0,...f.pendingPublish?{pendingPublish:!0}:{}}}return c?{result:"absent",effectiveValue:s,appOverrideExists:l}:{result:"unverifiable",effectiveValue:s,appOverrideExists:void 0,reason:u}}function BF(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?Bv(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function Jp(e,t,r={}){var n;let i=[`SettingName='${(0,qe.odataPathLiteral)(t)}'`];r.appUniqueName&&i.push(`AppUniqueName='${(0,qe.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${i.join(",")})`,a=(0,hn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.SettingDetail;if(s===null||typeof s!="object"||Array.isArray(s)||!("Value"in s))throw new Ve.ConnectionError(e.apiUrl(o),a.status,`RetrieveSetting for '${t}' returned a malformed answer \u2014 expected a SettingDetail with a Value`);let{Value:l,DataType:u}=s;return{value:l,dataType:u}}Te.retrieveSetting=Jp;async function qF(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,hn.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Te.saveSettingValue=qF;async function Roe(e,t={}){let r={};for(let[n,i]of Object.entries(Te.AI_GATE)){let{value:o,dataType:a}=await Jp(e,i,t);r[n]={enabled:BF(o,a,n),setting:i,value:o}}return r}Te.getAiReadiness=Roe;async function Loe(e,t,r,n={}){var i;if(!t||!t.trim())throw new Ve.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let o=Ioe(n.verifyAttempts),a=Ooe(n.verifyDelayMs),s=[];for(let[p,h]of Object.entries(r)){if(h===void 0)continue;let g=UF[p];g&&s.push({feature:p,setting:g,requestedValue:Coe(h,p)})}let l=[],u=n.appModuleId?(0,qe.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(u){let p=await Soe(e,t);if(p&&(0,qe.normalizeGuid)(p,"appModuleId")!==u)throw new Ve.InvalidArgumentError(`setAppAiFeatures: appModuleId '${u}' does not belong to app '${t}' (which resolves to '${p}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let c,d=async()=>u||(c||(c=await Aoe(e,t)),c),f=new Map,m=async p=>{if(voe.has(p))return;let h=Te.AI_GATE[p];if(h){if(!f.has(h))try{let{value:g,dataType:b}=await Jp(e,h);f.set(h,{enabled:BF(g,b,p),setting:h,value:g})}catch{f.set(h,void 0)}return f.get(h)}};for(let{feature:p,setting:h,requestedValue:g}of s)try{await qF(e,h,g,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let b=await Poe(e,d,t,h,g,o,a),w={feature:p,setting:h,requestedValue:g,effectiveValue:b.effectiveValue,appOverrideExists:b.appOverrideExists};if(b.result==="proven")l.push({...w,status:"applied",...b.pendingPublish?{pendingPublish:!0}:{}});else if(b.result==="absent"){let E=Eoe(g,p)?await m(p):void 0;E&&!E.enabled?l.push({...w,status:"skipped",reason:`the write was issued and no app-scope override holding '${g}' was observed for '${h}' after ${o} attempt(s); the org readiness gate '${E.setting}' reads '${E.value}', so an environment admin must enable it before this app can turn the feature on`}):l.push({...w,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${g}' was observed for '${h}' after ${o} attempt(s) \u2014 ${b.effectiveValue===void 0?"the value in effect for this app could not be read":`it reads '${b.effectiveValue}' for this app`} (Dataverse can accept an app-scope write without storing it)`})}else l.push({...w,status:"unverified",reason:`the write was issued but could not be confirmed: ${(i=b.reason)!==null&&i!==void 0?i:"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(b){l.push({feature:p,setting:h,requestedValue:g,status:"failed",reason:b.message})}return{applied:l.filter(p=>p.status==="applied").map(p=>p.feature),skipped:l.filter(p=>p.status==="skipped").map(p=>p.feature),notPersisted:l.filter(p=>p.status==="notPersisted").map(p=>p.feature),unverified:l.filter(p=>p.status==="unverified").map(p=>p.feature),failed:l.filter(p=>p.status==="failed").map(p=>p.feature),outcomes:l}}Te.setAppAiFeatures=Loe;var VF="GptPowerPrompt",koe='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function GF(e){var t,r,n,i;let o=e.entityLogicalName,a=[{type:"literal",text:e.instruction.replace(/\s*$/,"")+" "}];return e.columns.forEach((s,l)=>{a.push({type:"data",id:`${o}.${s.logical}`,text:s.display}),l<e.columns.length-1&&a.push({type:"literal",text:", "})}),{version:"GptDynamicPrompt-2",prompt:a,definitions:{inputs:[{id:"RecordId",text:"RecordId",type:"text"},{id:"LanguageCode",text:"LanguageCode",type:"text"}],formulas:[],data:[{id:o,displayName:o,type:"dataverseTable",filters:[{filterType:"equal",attribute:e.primaryKey,valueType:"inputVariable",value:"RecordId"}]}],output:{formats:[(t=e.outputFormat)!==null&&t!==void 0?t:"text"]}},modelParameters:{modelType:"default",gptParameters:{temperature:(r=e.temperature)!==null&&r!==void 0?r:0}},settings:{recordRetrievalLimit:(n=e.recordRetrievalLimit)!==null&&n!==void 0?n:30,shouldPreserveRecordLinks:null,runtime:null,enableReasoning:(i=e.enableReasoning)!==null&&i!==void 0?i:!0},code:"",signature:""}}Te.buildGptDynamicPrompt=GF;async function $oe(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,qe.odataPathLiteral)(t)}')${(0,qe.odataQuery)([["$select","MetadataId"]])}`,i=(0,hn.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.MetadataId;if(typeof o!="string"||o==="")throw new Ve.ConnectionError(e.apiUrl(n),i.status,`the table metadata read for '${t}' returned a malformed answer \u2014 expected a MetadataId but got ${o===""?"an empty string":(0,Wi.describeMalformedValue)(o)}`);return o}function qv(e,t,r,n){if(e.length===0)return;let i=e[0];if(typeof i!="object"||i===null||Array.isArray(i))throw new Ve.ConnectionError(t,r,`${n} returned a malformed row \u2014 expected an object but got ${Array.isArray(i)?"an array":(0,Wi.describeMalformedValue)(i)}`);return i}async function WF(e){var t;let r=`/msdyn_aitemplates${(0,qe.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${VF}'`],["$top",1]])}`,n=(0,hn.ensureSuccess)(await e.get(r),e.apiUrl(r)),i=(t=n.body)===null||t===void 0?void 0:t.value;if(!Array.isArray(i))throw new Ve.ConnectionError(e.apiUrl(r),n.status,`the row-summary template lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,Wi.describeMalformedValue)(i)}`);let o=qv(i,e.apiUrl(r),n.status,"the row-summary template lookup");if(!o)return;let a=o.msdyn_aitemplateid;if(typeof a=="string"&&a!=="")try{return(0,qe.normalizeGuid)(a,"msdyn_aitemplateid")}catch{}throw new Ve.ConnectionError(e.apiUrl(r),n.status,`the row-summary template lookup returned a malformed row \u2014 expected a GUID 'msdyn_aitemplateid' but got ${a===""?"an empty string":typeof a=="string"?"a string that is not a GUID":(0,Wi.describeMalformedValue)(a)}`)}function zF(e){return`${e} row summary`}async function xoe(e,t,r){var n;let i=`/msdyn_aimodels(${t})${(0,qe.odataQuery)([["$select","msdyn_name,_msdyn_templateid_value"]])}`,o=await e.get(i);if(o.status===404)return!1;let a=(n=(0,hn.ensureSuccess)(o,e.apiUrl(i)).body)!==null&&n!==void 0?n:{},s=await WF(e);return typeof a.msdyn_name=="string"&&a.msdyn_name.toLowerCase()===zF(r).toLowerCase()&&typeof a._msdyn_templateid_value=="string"&&s!==void 0&&a._msdyn_templateid_value.toLowerCase()===s.toLowerCase()}async function Foe(e,t,r={}){var n;let i=`ais_RowSummary_${t.entityLogicalName}`,o=`/aiskillconfigs${(0,qe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(i)}'`],["$top",1]])}`,a=(0,hn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new Ve.ConnectionError(e.apiUrl(o),a.status,`the existing row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,Wi.describeMalformedValue)(s)}`);let l=qv(s,e.apiUrl(o),a.status,"the existing row-summary skill lookup");if(l)return{modelId:l._aimodel_value,aiSkillConfigId:l.aiskillconfigid};let u=await $oe(e,t.entityLogicalName),c=await WF(e);if(c===void 0)throw new Ve.SdkError(Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE,`Cannot configure the row summary of '${t.entityLogicalName}': this org has no AI template '${VF}' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written.`);let d=(0,LF.newId)(),f=(0,LF.newId)(),m=JSON.stringify(GF(t)),p={ModelId:d,RunConfigurationId:f,ModelName:zF(t.entityLogicalName),TemplateId:c,CustomConfiguration:m,Source:koe,RunConfiguration:""};(0,hn.ensureSuccess)(await e.post("/AIModelPublish",p),e.apiUrl("/AIModelPublish"));try{let h={uniquename:i,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${u})`,"[email protected]":`/msdyn_aimodels(${d})`,aiskill:"RowSummary"},g=(0,hn.ensureSuccess)(await e.post("/aiskillconfigs",h),e.apiUrl("/aiskillconfigs")),b=(0,hn.requireCreatedId)(g,"aiskillconfigid","row-summary skill");return{modelId:d,aiSkillConfigId:b}}catch(h){try{await e.delete(`/msdyn_aimodels(${d})`)}catch{}throw h}}Te.configureRowSummary=Foe;async function Moe(e,t){var r;let n=`ais_RowSummary_${t.entityLogicalName}`,i=`/aiskillconfigs${(0,qe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(n)}'`],["$top",1]])}`,o=(0,hn.ensureSuccess)(await e.get(i),e.apiUrl(i)),a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ve.ConnectionError(e.apiUrl(i),o.status,`the row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,Wi.describeMalformedValue)(a)}`);let s=qv(a,e.apiUrl(i),o.status,"the row-summary skill lookup");if(!s)return{removed:!1};let l=(0,qe.normalizeGuid)(s.aiskillconfigid,"aiskillconfigid"),u=s._aimodel_value?(0,qe.normalizeGuid)(s._aimodel_value,"_aimodel_value"):void 0,c=u?await xoe(e,u,t.entityLogicalName):!1,d=t.entityLogicalName,f=`/aiskillconfigs(${l})`,m=await FF(e,f,`${f}${(0,qe.odataQuery)([["$select","aiskillconfigid"]])}`);if(m.kind==="failed")throw m.stillThere===void 0&&u&&c?(0,Ve.attachCause)(new Ve.SdkError(Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE,`Removing the row summary of '${d}' could not be confirmed: deleting its skill row failed (${MF(m.failure)}) and the row could not be read back. If it is gone, its AI model '${u}' is left behind, unreferenced. Retry removeRowSummary: while the skill row exists it removes both; once it is gone, delete that model.`),m.failure):m.failure;if(u&&c){let p=`/msdyn_aimodels(${u})`,h=await FF(e,p,`${p}${(0,qe.odataQuery)([["$select","msdyn_aimodelid"]])}`,Boe);if(h.kind==="failed")throw(0,Ve.attachCause)(new Ve.SdkError(Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE,`The row summary of '${d}' was removed, but its AI model '${u}' ${h.stillThere?"was not deleted":"could not be confirmed deleted"} (${MF(h.failure)}). The model is no longer used by the row summary; delete it before configuring a row summary for '${d}' again, which needs its name.`),h.failure)}return{removed:!0}}Te.removeRowSummary=Moe;Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE="ROW_SUMMARY_MODEL_NOT_DELETED";Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE="ROW_SUMMARY_REMOVAL_UNCONFIRMED";Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE="ROW_SUMMARY_TEMPLATE_NOT_FOUND";var Uoe="0x8004f01f";function Boe(e){var t,r;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return e.status===400&&typeof n=="string"&&n.toLowerCase()===Uoe}function qoe(e){if(e.status!==400&&e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/chosen as the deadlock victim|\bSql Number:\s*1205\b/i.test(t)}async function FF(e,t,r,n=()=>!1){let i;try{let o=await(0,hn.resendWhile)(qoe,()=>e.delete(t));if(o.status>=200&&o.status<300||o.status===404)return{kind:"gone"};if(n(o))return{kind:"kept"};try{(0,hn.ensureSuccess)(o,e.apiUrl(t))}catch(a){i=a}}catch(o){i=o}try{let o=await e.get(r);return o.status===404?{kind:"gone"}:{kind:"failed",failure:i,stillThere:o.status>=200&&o.status<300?!0:void 0}}catch{return{kind:"failed",failure:i,stillThere:void 0}}}function MF(e){return e instanceof Error?e.message:String(e)}});var JF=v(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});ul.findArtifact=ul.resolveArtifact=void 0;var Bt=se(),zi=Td(),Voe=Ud(),Goe=Lt(),Woe=ye(),HF=Q();async function KF(e,t,r){let n="/uxagentprojects"+(0,Bt.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,Bt.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,Goe.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function zoe(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p;switch(t){case"app":{let h=(0,Voe.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,Bt.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),b=(i=(0,Woe.ensureSuccess)(await e.get(h),e.apiUrl(h)).body)===null||i===void 0?void 0:i.value,w=b&&b[0];return w?[{id:String(w.appmoduleid),name:String(w.name),appModuleIdUnique:String(w.appmoduleidunique)}]:[]}case"dashboard":return(await(0,zi.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,Bt.odataLiteral)((o=r.name)!==null&&o!==void 0?o:"")}' and type eq 0`,top:10})||[]).map(g=>({id:String(g.formid),name:String(g.name)}));case"command":{if(!r.entity)return[];let h=await(0,zi.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,Bt.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?[{id:r.entity,entity:r.entity}]:[]}case"form":return(await(0,zi.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,Bt.odataLiteral)((a=r.name)!==null&&a!==void 0?a:"")}' and objecttypecode eq '${(0,Bt.odataLiteral)((s=r.entity)!==null&&s!==void 0?s:"")}'`,top:10})||[]).map(g=>({id:String(g.formid),name:String(g.name)}));case"chart":return(await(0,zi.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,Bt.odataLiteral)((l=r.name)!==null&&l!==void 0?l:"")}' and primaryentitytypecode eq '${(0,Bt.odataLiteral)((u=r.entity)!==null&&u!==void 0?u:"")}'`,top:10})||[]).map(g=>({id:String(g.savedqueryvisualizationid),name:String(g.name)}));case"view":return(await(0,zi.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,Bt.odataLiteral)((c=r.name)!==null&&c!==void 0?c:"")}' and returnedtypecode eq '${(0,Bt.odataLiteral)((d=r.entity)!==null&&d!==void 0?d:"")}'`,top:10})||[]).map(g=>({id:String(g.savedqueryid),name:String(g.name)}));case"webResource":return(await(0,zi.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,Bt.odataLiteral)((f=r.name)!==null&&f!==void 0?f:"")}'`,top:1})||[]).map(g=>({id:String(g.webresourceid),name:String(g.name)}));case"solution":return(await(0,zi.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,Bt.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(g=>({id:String(g.solutionid),name:String(g.uniquename)}));case"genPage":return KF(e,(p=r.name)!==null&&p!==void 0?p:"");default:return[]}}ul.resolveArtifact=zoe;async function joe(e,t,r){var n,i,o,a,s,l;let u=(0,Bt.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),c=(0,Bt.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){if(!r.entity)return null;let h=await(0,zi.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,Bt.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?r.entity:null}if(t==="genPage"){let h=await KF(e,(o=r.name)!==null&&o!==void 0?o:"",2);if(h.length>1)throw new HF.AmbiguousArtifactError(t,(a=r.name)!==null&&a!==void 0?a:"",h.length);return h.length===1?h[0].id:null}let d=Hoe(t,u,c,r),f=t!=="app",m=await(0,zi.queryRecords)(e,d.set,{select:[d.idField],filter:d.filter,top:f?2:1});if(f&&m&&m.length>1)throw new HF.AmbiguousArtifactError(t,(l=(s=r.name)!==null&&s!==void 0?s:r.uniqueName)!==null&&l!==void 0?l:"",m.length);let p=m&&m[0]&&m[0][d.idField];return p!=null?String(p):null}ul.findArtifact=joe;function Hoe(e,t,r,n){var i;switch(e){case"view":return{set:"savedquery",idField:"savedqueryid",filter:`returnedtypecode eq '${r}' and name eq '${t}'`};case"chart":return{set:"savedqueryvisualization",idField:"savedqueryvisualizationid",filter:`primaryentitytypecode eq '${r}' and name eq '${t}'`};case"form":return{set:"systemform",idField:"formid",filter:`objecttypecode eq '${r}' and name eq '${t}'`};case"app":return{set:"appmodule",idField:"appmoduleid",filter:`uniquename eq '${(0,Bt.odataLiteral)((i=n.uniqueName)!==null&&i!==void 0?i:"")}'`};case"dashboard":return{set:"systemform",idField:"formid",filter:`name eq '${t}' and type eq 0`};default:throw new Error(`Unsupported findable kind: ${e}`)}}});var QF=v(Qp=>{"use strict";Object.defineProperty(Qp,"__esModule",{value:!0});Qp.seedRecordGraph=void 0;var YF=Td(),Koe=cd(),Yp=se(),Joe=Q();async function Yoe(e,t,r={}){var n,i,o,a,s;let l=(n=r.createdIds)!==null&&n!==void 0?n:{},u=(i=r.entitySetFor)!==null&&i!==void 0?i:(f=>(0,Koe.resolveEntitySetName)(e,f)),c={},d=f=>{var m;return(m=c[f])!==null&&m!==void 0?m:l[f]};for(let f of t){let m=f.entityLogical.toLowerCase(),p=(o=f.matchOn)===null||o===void 0?void 0:o.toLowerCase(),h=[];for(let L of f.records){let I={...L.body};for(let D of(a=L.binds)!==null&&a!==void 0?a:[]){let O=D.parentEntity.toLowerCase(),x=(s=d(O))===null||s===void 0?void 0:s[D.parentIndex];if(!x)throw new Joe.InvalidArgumentError(`Cannot resolve bind '${D.navProperty}' on a '${m}' record: parent '${D.parentEntity}'[${D.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let K=(0,Yp.assertODataName)(await u(O),`entity set for parent '${D.parentEntity}'`),Re=(0,Yp.normalizeGuid)(x,`parent id for bind '${D.navProperty}'`);I[`${D.navProperty}@odata.bind`]=`/${K}(${Re})`}h.push(I)}let g=p?h.map(L=>{let I=L[p];return I!=null&&I!==""?String(I):null}):h.map(()=>null),b=new Map;if(p){let L=(0,Yp.assertODataName)(p,"RecordGraph matchOn key"),I=[...new Set(g.filter(D=>D!==null))];if(I.length){let D=I.map(x=>`${L} eq '${(0,Yp.odataLiteral)(x)}'`).join(" or "),O=await(0,YF.queryRecords)(e,m,{select:[L,`${m}id`],filter:D,top:5e3});for(let x of O??[]){let K=x[L];K!=null&&b.set(String(K).toLowerCase(),String(x[`${m}id`]))}}}let w=[],E=new Map,S=h.map((L,I)=>{let D=g[I];if(D&&b.has(D.toLowerCase()))return null;if(D){let O=D.toLowerCase(),x=E.get(O);if(x!==void 0)return x;let K=w.push(L)-1;return E.set(O,K),K}return w.push(L)-1}),P=w.length?await(0,YF.createRecordsBulk)(e,m,w):[];c[m]=h.map((L,I)=>{let D=g[I];return D&&b.has(D.toLowerCase())?b.get(D.toLowerCase()):P[S[I]]})}return{createdIds:c}}Qp.seedRecordGraph=Yoe});var sM=v(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.getEntityPrivileges=Zt.addEntityPrivilegesToRole=Zt.deleteSecurityRole=Zt.createPersonaRole=Zt.createSecurityRole=Zt.SDK_ROLE_MARKER=void 0;var Fn=ye(),Pt=se(),jr=Q(),Xp={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},Gv={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},XF={user:1,businessUnit:2,parentChild:3,organization:4},Vv={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};Zt.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function Qoe(e){return Object.prototype.hasOwnProperty.call(Xp,e)?Xp[e]:void 0}function Xoe(e){return Object.prototype.hasOwnProperty.call(Gv,e)}var ZF=new WeakMap,eM=new WeakMap;async function nM(e,t){var r,n;(0,Pt.assertODataName)(t,"entity logical name");let i=ZF.get(e);i||(i=new Map,ZF.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,Pt.odataPathLiteral)(t)}')${(0,Pt.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,Fn.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[];if(l.length===0)throw new jr.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function Zoe(e){var t,r,n;let i=eM.get(e);if(i)return i;let o=`/businessunits${(0,Pt.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,Fn.ensureSuccess)(await e.get(o),e.apiUrl(o)).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 jr.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,Pt.normalizeGuid)(l,"businessUnitId");return eM.set(e,u),u}async function iM(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new jr.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let o=(r=i.scope)!==null&&r!==void 0?r:"user";if(!Xoe(o))throw new jr.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await nM(e,i.entity);for(let s of i.access){let l=Qoe(s);if(!l)throw new jr.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=a.find(p=>p.PrivilegeType===l);if(!u)throw new jr.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=Vv[o];if(u[c]===!1)throw new jr.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,Pt.normalizeGuid)(u.PrivilegeId,"PrivilegeId"),f=n.get(d);if(!f){n.set(d,{privilegeName:u.Name,privilegeType:l,scope:o,entities:new Set([i.entity])});continue}if(f.scope===o){f.entities.add(i.entity);continue}if(!(f.entities.size===1&&f.entities.has(i.entity))){let p=[...f.entities].sort().join(", ");throw new jr.InvalidArgumentError(`Entities '${p}' 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.`)}f.scope=XF[o]>XF[f.scope]?o:f.scope}}return[...n.entries()].map(([i,o])=>({entity:[...o.entities].sort().join(", "),privilegeId:i,privilegeName:o.privilegeName,privilegeType:o.privilegeType,scope:o.scope}))}async function eae(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(a=>({Depth:Gv[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,Fn.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function tM(e,t,r,n,i){var o,a;let s=`/${t}(${r})/${n}${(0,Pt.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((a=(o=(0,Fn.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||o===void 0?void 0:o.value)!==null&&a!==void 0?a:[]).length>0}async function tae(e,t,r){var n,i;let o=[],a=[],s={"@odata.id":e.apiUrl(`/roles(${t})`)};for(let l of(n=r?.teams)!==null&&n!==void 0?n:[]){let u=(0,Pt.normalizeGuid)(l,"teamId");if(!await tM(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,Fn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}for(let l of(i=r?.users)!==null&&i!==void 0?i:[]){let u=(0,Pt.normalizeGuid)(l,"userId");if(!await tM(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,Fn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}return{teams:o,users:a}}async function rM(e,t,r){var n,i;let o=`/roles${(0,Pt.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Pt.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,Fn.ensureSuccess)(await e.get(o),e.apiUrl(o)).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 f;return d.ismanaged!==!0&&((f=d.description)!==null&&f!==void 0?f:"")===Zt.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new jr.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 jr.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,Pt.normalizeGuid)(c,"roleId"):void 0}function rae(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,Pt.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,Pt.normalizeGuid)(n,"userId"))}}function oM(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function aM(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new jr.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,Pt.normalizeGuid)(t.businessUnitId,"businessUnitId"):await Zoe(e),a=await iM(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=rae(t.assignTo),l=await rM(e,i,o),u=l!==void 0;if(!l){let d="/roles",f={name:i,description:Zt.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let m=(0,Fn.ensureSuccess)(await e.post(d,f),e.apiUrl(d));l=(0,Pt.normalizeGuid)((0,Fn.requireCreatedId)(m,"roleid","role"),"roleId")}catch(m){let p;try{p=await rM(e,i,o)}catch{p=void 0}if(!p)throw m;l=p}}await eae(e,l,a,u);let c=await tae(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:oM(a),assignedTeams:c.teams,assignedUsers:c.users}}Zt.createSecurityRole=aM;async function nae(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new jr.InvalidArgumentError("createPersonaRole: a non-empty persona name is required.");let o=[...t.jobs.flatMap(a=>{var s;return(s=a.privileges)!==null&&s!==void 0?s:[]}),...(n=t.additionalPrivileges)!==null&&n!==void 0?n:[]];return aM(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}Zt.createPersonaRole=nae;async function iae(e,t){let n=`/roles(${(0,Pt.normalizeGuid)(t,"roleId")})`;(0,Fn.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Zt.deleteSecurityRole=iae;async function oae(e,t,r){let n=(0,Pt.normalizeGuid)(t,"roleId");if(r.length===0)throw new jr.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await iM(e,r),o={Privileges:i.map(s=>({Depth:Gv[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,Fn.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),oM(i)}Zt.addEntityPrivilegesToRole=oae;var aae=new Map(Object.keys(Xp).map(e=>[Xp[e],e]));async function sae(e,t){return(await nM(e,t)).map(n=>{let i=Object.keys(Vv).filter(a=>n[Vv[a]]!==!1),o=aae.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...o?{access:o}:{},scopes:i}})}Zt.getEntityPrivileges=sae});var SM=v(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.createMakerSdk=mr.MakerSdk=mr.PUSH_NOT_ATTEMPTED_CODE=mr.ALREADY_EXISTS_CODE=void 0;var lM=Im(),uM=Jr(),Z=Q(),gn=$a(),lae=DC(),wM=$C(),cl=qC(),uae=Pm(),cae=lE(),dl=dE(),dae=NE(),fae=PE(),pae=lA(),cM=iS(),Rt=cd(),Wv=vg(),dM=hN(),Zp=Xl(),ji=Td(),em=AN(),fl=Od(),mae=Rd(),er=wg(),hae=Tg(),gae=$g(),fM=Dg(),yae=RF(),tm=dt(),bae=Ho(),fi=Pb(),yn=xm(),zv=gv(),vae=3e5,pr=ye(),Oa=se(),pl=jF(),pM=JF(),wae=QF(),Cae=Hy(),gc=sM(),CM=Symbol("cds-maker-sdk.committedWrite");function Eae(e){return typeof e=="object"&&e!==null&&(e[CM]=!0),e}function Aae(e){return typeof e=="object"&&e!==null&&e[CM]===!0}var Sae={fileConcurrency:1},jv="SOLUTION_COMPONENT_UNCLASSIFIED",Nae=2,_ae=4,Tae="This table is in the solution with ALL its subcomponents. Those are members the solution does not list one by one, so fetchSolution did not enumerate or fetch them: none of its forms, views, charts or dashboards were fetched here. To fetch them, read the table's logical name from its metadata (EntityDefinitions(<componentId>), $select=LogicalName), list each kind with fetchArtifactList \u2014 'form' with formTypes Main, QuickView, QuickCreate and Card; 'view'; 'chart'; 'dashboard' \u2014 passing { entityLogicalName }, and fetch each listed id with fetchArtifact: listing returns ids and names only.";function mM(e){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"unsupported",...e.includesAllSubcomponents?{detail:Tae}:{}}}function hM(e,t){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"failed",error:Po(t)}}function gM(e,t,r){let n=r;return{type:e,id:t.objectId,name:typeof n.name=="string"?n.name:t.objectId,entityLogicalName:typeof n.entityLogicalName=="string"?n.entityLogicalName:void 0,lastFetched:(0,pr.nowIso)(),isDirty:!1}}var Dae=new Set(["entity","appmodule","dashboard","uxagentproject"]);function Iae(e){var t;let r={entity:[],appmodule:[],dashboard:[],uxagentproject:[]},n=new Set,i=(s,l)=>{let u=`${s}\0${l.toLowerCase()}`;n.has(u)||(n.add(u),r[s].push(l))};for(let{scope:s}of e)if(s?.envelope==="entity")s.entityLogicalName&&i("entity",s.entityLogicalName);else if(s&&s.envelope!=="webresource")for(let l of(t=s.targetIds)!==null&&t!==void 0?t:[])i(s.envelope,l);let o=(s,l,u)=>u.length>0?`<${s}>${u.map(c=>`<${l}>${(0,Oa.xmlText)(c)}</${l}>`).join("")}</${s}>`:"",a=o("entities","entity",r.entity)+o("appmodules","appmodule",r.appmodule)+o("dashboards","dashboard",r.dashboard)+o("uxagentprojects","uxagentproject",r.uxagentproject);return a?`<importexportxml>${a}</importexportxml>`:void 0}function Oae(e){let t=e.workspaceStorage;if(t==null)throw new Error("createMakerSdk requires a workspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'; a host with no filesystem implements WorkspaceStorage directly.");return new wM.WorkspaceManager(Rae,e.instanceUrl,(0,uae.assertStorageContract)(t))}mr.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var Pae="this build answers a replayed create with HTTP 404, and the unpublished read of an existing row is not authoritative after another writer's save on it, so the row cannot be proven to be what this create wrote";mr.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var Rae="<injected workspaceStorage>",rm=class{constructor(t){var r,n;if(this.artifactLocks=new Map,this.observedGenerations=new Map,this.baselineObserved=new Map,this.generationHighWater=new Map,this.entityMetadataLoads=new Map,this.entityMetadataLoadEpochs=new WeakMap,this.schemaWrites=new Map,this.undroppedMetadata=new Set,this.metadataPublications=new Set,t.createRecovery!==void 0&&t.createRecovery!=="adoptExact")throw new Z.InvalidArgumentError(`createRecovery must be 'adoptExact' or omitted (got '${String(t.createRecovery)}').`);this.createRecovery=t.createRecovery,this.readConcurrency=(0,zv.resolveReadConcurrency)(t.readConcurrency),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:bae.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:vae,this.compiler={load:(0,hae.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=Oae(t),this.versions=new cl.VersionManager(this.workspace),this.dataverse=new cae.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName,this.readConcurrency),this.connectivity=new pae.ConnectivityRouter(this.dataverse,t.instanceUrl,{powerAppsServiceClient:t.powerAppsServiceClient,powerPlatformApiClient:t.powerPlatformApiClient,connectorRuntimeClient:t.connectorRuntimeClient}),this.registrations=(0,yae.buildRegistrations)(this.languageCode)}async initWorkspace(){await this.workspace.init()}async getManifest(){return this.workspace.getManifest()}async cleanWorkspace(){await this.workspace.clean()}withArtifactLock(t,r,n){var i;let o=this.artifactKey(t,r),s=((i=this.artifactLocks.get(o))!==null&&i!==void 0?i:Promise.resolve()).then(n,n),l=s.then(()=>{},()=>{});return this.artifactLocks.set(o,l),l.then(()=>{this.artifactLocks.get(o)===l&&this.artifactLocks.delete(o)}),s}async fetchArtifact(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.fetchArtifactUnlocked(t,r,n);return await this.acknowledgeRefresh(t,r),i})}async fetchArtifactUnlocked(t,r,n){let i=this.requireRegistration(t,"fetchArtifact"),o=await i.api.get(this.dataverse,r);return this.applyFetchedArtifactUnlocked(t,r,i,o,n)}async applyFetchedArtifactUnlocked(t,r,n,i,o){var a,s,l;let{raw:u,etag:c,memberEtags:d,siblingEtags:f}=i,m=n.adapter.fromApiResponse(u);if(!o?.overwrite&&await this.versions.isDirty(t,r)){let h=(s=(a=await this.versions.getMeta(t,r))===null||a===void 0?void 0:a.etag)!==null&&s!==void 0?s:null;if(h&&c&&h!==c)throw new Z.LocalEditsWouldBeLostError(t,r,h,c);let g=await this.workspace.readArtifact(t,r);if(g){let b=await this.versions.getMeta(t,r);if(b&&!b.etag&&c){if(!(0,yn.deepEqual)(b.snapshot,m))throw new Z.LocalEditsWouldBeLostError(t,r,h,c);await this.versions.storeMeta(t,r,{...b,etag:c,fetchedAt:(0,pr.nowIso)()},b)}return(0,fi.cloneJson)(g)}}await this.workspace.writeArtifact(t,r,m);let p=await this.versions.getMeta(t,r);return await this.versions.storeMeta(t,r,{etag:c,languageCode:this.languageCode,projectionVersion:cl.PROJECTION_VERSION,fetchedAt:(0,pr.nowIso)(),snapshot:(0,fi.cloneJson)(m),...d?{memberEtags:d}:{},...f?{siblingEtags:f}:{},...p?.refreshGeneration?{refreshGeneration:p.refreshGeneration,observedGeneration:(l=p.observedGeneration)!==null&&l!==void 0?l:0}:{}},p),(0,fi.cloneJson)(m)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){await this.workspace.ensureReady();let r=await(0,er.fetchSolutionComponents)(this.dataverse,t),n=[],i=[];if(this.readConcurrency>1)await this.fetchComponentsOverlapped(r,n,i);else for(let o of r)try{let a=await this.resolveComponentType(o);if(!a){i.push(mM(o));continue}let s=await this.fetchArtifact(a,o.objectId);n.push(gM(a,o,s))}catch(a){i.push(hM(o,a))}return await this.workspace.updateManifest({lastSyncAt:(0,pr.nowIso)()}),{summaries:n,skipped:i}}async fetchComponentsOverlapped(t,r,n){await(0,zv.readEveryInOrder)(t,this.readConcurrency,i=>this.beginComponentRead(i),async(i,o)=>{try{if(!i.ok)throw i.error;let a=i.value;if(a.kind==="unsupported"){n.push(mM(o));return}let s=await this.applyFetchedArtifactUnlocked(a.type,o.objectId,a.reg,a.fetched);await this.acknowledgeRefresh(a.type,o.objectId),r.push(gM(a.type,o,s))}catch(a){n.push(hM(o,a))}})}async beginComponentRead(t){let r=await this.resolveComponentType(t);return r?this.lockedRead(r,t.objectId,async()=>{let n=this.requireRegistration(r,"fetchArtifact"),i=await n.api.get(this.dataverse,t.objectId,Sae);return{kind:"artifact",type:r,reg:n,fetched:i}}):(0,zv.plainRead)(async()=>({kind:"unsupported"}))}lockedRead(t,r,n){let i,o=new Promise(u=>{i=u}),a,s=new Promise(u=>{a=u}),l=this.withArtifactLock(t,r,async()=>{try{i({ok:!0,value:await n()})}catch(c){i({ok:!1,error:c})}let u=await s;await u?.()});return{outcome:o,finish:u=>(a(u),l),discard:async()=>{a(void 0),await l}}}async fetchEntityMetadata(t){let r=t.toLowerCase(),n=this.schemaEpoch(r),i=await(0,dl.fetchEntityMetadataFromApi)(this.dataverse,t);if(this.schemaEpoch(r)!==n)return i;let o=this.workspace.writeEntityMetadata(t,i),a={key:r,settled:o.then(()=>{},()=>{})};this.metadataPublications.add(a);try{await o}finally{this.metadataPublications.delete(a)}return this.schemaEpoch(r)===n&&this.undroppedMetadata.delete(r),i}schemaEpoch(t){var r,n;return`${(r=this.schemaWrites.get("*"))!==null&&r!==void 0?r:0}:${(n=this.schemaWrites.get(t.toLowerCase()))!==null&&n!==void 0?n:0}`}async schemaWrite(t,r){try{return await r()}finally{await this.forgetEntityMetadata(t)}}async forgetEntityMetadata(t){let r=i=>{var o;this.schemaWrites.set(i,((o=this.schemaWrites.get(i))!==null&&o!==void 0?o:0)+1)};if(t===void 0){r("*"),await this.publicationsSettled(void 0),await this.dropCachedMetadata(void 0);return}let n=[...new Set(t.filter(i=>typeof i=="string"&&i!=="").map(i=>i.toLowerCase()))];n.forEach(r),await this.publicationsSettled(n);for(let i of n)await this.dropCachedMetadata(i)}async publicationsSettled(t){let r=t===void 0?void 0:new Set(t);await Promise.all([...this.metadataPublications].filter(n=>r===void 0||r.has(n.key)).map(n=>n.settled))}async dropCachedMetadata(t){try{await this.workspace.dropEntityMetadata(t)}catch(r){r instanceof Z.WorkspaceNotInitializedError||r instanceof Z.WorkspaceOrgMismatchError||this.undroppedMetadata.add(t??"*");return}t===void 0?this.undroppedMetadata.clear():this.undroppedMetadata.delete(t)}async readCachedEntityMetadata(t){let r=t.toLowerCase();return this.undroppedMetadata.has("*")&&await this.dropCachedMetadata(void 0),this.undroppedMetadata.has(r)&&await this.dropCachedMetadata(r),this.undroppedMetadata.has("*")||this.undroppedMetadata.has(r)?null:this.workspace.readEntityMetadata(t)}loadMissedEntityMetadata(t){let r=this.schemaEpoch(t),n=this.entityMetadataLoads.get(t);if(n&&this.entityMetadataLoadEpochs.get(n)===r)return n;let i=this.fetchEntityMetadata(t).then(()=>{});this.entityMetadataLoads.set(t,i),this.entityMetadataLoadEpochs.set(i,r);let o=()=>{this.entityMetadataLoads.get(t)===i&&this.entityMetadataLoads.delete(t)};return i.then(o,o),i}generateGenPageRuntimeTypes(t,r){return(0,dae.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,dl.findTables)(this.dataverse,t,r)}getEnvironmentLanguages(){return(0,fae.getEnvironmentLanguages)(this.dataverse)}listConnections(){return this.connectivity.listConnections()}listConnectorOperations(t){return this.connectivity.listConnectorOperations(t)}getConnectorOperationSchema(t,r){return this.connectivity.getConnectorOperationSchema(t,r)}listConnectorTables(t,r,n){return this.connectivity.listConnectorTables(t,r,n)}getConnectorTableSchema(t,r,n,i){return this.connectivity.getConnectorTableSchema(t,r,n,i)}findColumns(t,r,n){return(0,dl.findColumns)(this.dataverse,t,r,n)}createTable(t){return this.schemaWrite([t.schemaName],()=>(0,Rt.createTable)(this.dataverse,t))}createColumn(t,r){return this.schemaWrite([t],()=>(0,Rt.createColumn)(this.dataverse,t,r))}createColumns(t,r){return this.schemaWrite([t],()=>(0,Rt.createColumns)(this.dataverse,t,r))}updateColumn(t,r,n){return this.schemaWrite([t],()=>(0,Rt.updateColumn)(this.dataverse,t,r,n))}deleteColumn(t,r){return this.schemaWrite([t],()=>(0,Rt.deleteColumn)(this.dataverse,t,r))}setFormSecurityRoles(t,r){return(0,Wv.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,Wv.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,Rt.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,Rt.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return this.schemaWrite([t,"account","contact"],()=>(0,Rt.createCustomerColumn)(this.dataverse,t,r))}insertStatusValue(t,r){return this.schemaWrite([t],()=>(0,Rt.insertStatusValue)(this.dataverse,t,r))}updateTable(t,r){return this.schemaWrite([t],()=>(0,Rt.updateTable)(this.dataverse,t,r))}async setEntityIcon(t,r){if(await this.schemaWrite([t],()=>(0,Rt.updateTable)(this.dataverse,t,{iconVectorName:r.vector,iconSmallName:r.small,iconMediumName:r.medium,iconLargeName:r.large})),r.publish!==!1){let n=`<importexportxml><entities><entity>${(0,Oa.xmlText)(t)}</entity></entities></importexportxml>`;(0,pr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,Rt.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,Rt.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){let r=t.type==="ManyToMany"?[t.entity1,t.entity2]:[t.referencedEntity,t.referencingEntity];return this.schemaWrite(r,()=>(0,Rt.createRelationship)(this.dataverse,t))}deleteRelationship(t){return this.schemaWrite(void 0,()=>(0,Rt.deleteRelationship)(this.dataverse,t))}createGlobalOptionSet(t){return(0,Rt.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,Rt.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return this.schemaWrite(void 0,()=>(0,Rt.deleteTable)(this.dataverse,t))}createSecurityRole(t){return(0,gc.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,gc.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,gc.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,gc.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,gc.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,ji.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,ji.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,ji.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,ji.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,ji.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,ji.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,ji.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,wae.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,pM.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,pM.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){await this.workspace.ensureReady();let n=await(0,gae.deleteAppCascade)(this.dataverse,t,r),i=(0,Oa.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,ji.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,ji.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,em.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,em.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,em.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,em.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,fl.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,fl.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new Z.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:mae.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,fl.setAppSetting)(this.dataverse,t,fl.HEADER_AND_NAVIGATION_REFRESH,r?fl.APP_SETTING_ON:fl.APP_SETTING_OFF)}getSolution(t){return(0,er.getSolution)(this.dataverse,t)}createPublisher(t){return(0,er.createPublisher)(this.dataverse,t)}createSolution(t){return(0,er.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,er.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,er.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,er.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,er.exportSolution)(this.dataverse,t)}importSolution(t){return this.schemaWrite(void 0,()=>(0,er.importSolution)(this.dataverse,t))}getDeploymentSettingsTemplate(t){return(0,er.getDeploymentSettingsTemplate)(this.dataverse,t)}deleteSolution(t){return this.schemaWrite(void 0,()=>(0,er.deleteSolution)(this.dataverse,t))}async getArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let{artifact:n,meta:i}=await this.readWhole(t,r);return await this.acknowledgeRefresh(t,r,i),n})}async getArtifactUnlocked(t,r){return this.readRaw(t,r)}async readWhole(t,r){let{meta:n}=await this.revalidate(t,r);return{artifact:await this.readLocal(t,r),meta:n}}async acknowledgeRefresh(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=n===void 0?await this.versions.getMeta(t,r):n;this.baselineObserved.has(s)||this.baselineObserved.set(s,(i=l?.observedGeneration)!==null&&i!==void 0?i:0);let u=(o=l?.refreshGeneration)!==null&&o!==void 0?o:0;this.raiseGenerationHighWater(s,u),l&&u!==((a=l.observedGeneration)!==null&&a!==void 0?a:0)&&await this.versions.storeMeta(t,r,{...l,observedGeneration:u},l),this.observedGenerations.set(s,u)}raiseGenerationHighWater(t,r){var n;r>((n=this.generationHighWater.get(t))!==null&&n!==void 0?n:0)&&this.generationHighWater.set(t,r)}async observedAtInvocation(t,r,n){var i,o;if(n!==void 0)return n;let a=this.baselineObserved.get(this.artifactKey(t,r));return a!==void 0?a:(o=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.observedGeneration)!==null&&o!==void 0?o:0}artifactKey(t,r){return`${t}\0${(0,wM.canonicalArtifactId)(r)}`}nextRefreshGeneration(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=Math.max((i=n?.refreshGeneration)!==null&&i!==void 0?i:0,(o=n?.observedGeneration)!==null&&o!==void 0?o:0,(a=this.generationHighWater.get(s))!==null&&a!==void 0?a:0)+1;return this.raiseGenerationHighWater(s,l),l}async readRaw(t,r){return await this.revalidateIfStale(t,r),this.readLocal(t,r)}async readForMutation(t,r,n,i){var o,a;let s=await this.observedAtInvocation(t,r,i);if(((a=(o=await this.versions.getMeta(t,r))===null||o===void 0?void 0:o.refreshGeneration)!==null&&a!==void 0?a:0)>s)throw new Z.StaleArtifactError(t,r,n,"pushed");if(await this.revalidateIfStale(t,r)==="refreshed-changed")throw new Z.StaleArtifactError(t,r,n);return this.readLocal(t,r)}async readLocal(t,r){let n=await this.workspace.readArtifact(t,r);if(!n)throw new Z.ArtifactNotFoundError(t,r);return n}async revalidateIfStale(t,r){return(await this.revalidate(t,r)).outcome}async revalidate(t,r){let n=await this.versions.getMeta(t,r);if(!n)return{outcome:"skipped",meta:null};let i=n.fetchedAt?Date.parse(n.fetchedAt):NaN,o=Date.now()-i;if(!Number.isNaN(i)&&this.cacheStalenessMs>0&&o<=this.cacheStalenessMs)return{outcome:"fresh",meta:n};if(await this.versions.isDirty(t,r,n))return{outcome:"skipped",meta:n};let a=await this.workspace.readArtifact(t,r);await this.fetchArtifactUnlocked(t,r);let s=await this.workspace.readArtifact(t,r);return{outcome:(0,yn.deepEqual)(a,s)?"refreshed-unchanged":"refreshed-changed"}}async queryTree(t,r,n){return this.withArtifactLock(t,r,async()=>{let{artifact:i,meta:o}=await this.readWhole(t,r),a=gn.JsonPointer.resolve(i,n);if(a===void 0)throw new Z.PathNotFoundError(t,r,n);return n===""&&await this.acknowledgeRefresh(t,r,o),a})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,lae.findElements)(await this.getArtifactUnlocked(t,r),n))}async withDirtyFlags(t){let r=[];for(let n of t)r.push({...n,isDirty:await this.versions.isDirty(n.type,n.id)});return r}async listArtifacts(t,r){return this.withDirtyFlags(await this.workspace.listArtifacts(t,r))}async getEntityMetadata(t){let r=await this.readCachedEntityMetadata(t);if(!r)throw new Z.ArtifactNotFoundError("entityMetadata",t);return r}async getFieldMetadata(t,r){let i=(await this.getEntityMetadata(t)).attributes.find(o=>o.logicalName===r);if(!i)throw new Z.PathNotFoundError("entityMetadata",t,r);return i}async updateElement(t,r,n,i){let o=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let a=await this.readForMutation(t,r,n,o),s=gn.JsonPointer.resolve(a,n);if(s===void 0)throw new Z.PathNotFoundError(t,r,n);let l=Hi(s)&&Hi(i)?{...s,...i}:i;return gn.JsonPointer.set(a,n,(0,fi.cloneJson)(l)),this.assertStructurallyValid(t,r,a,n),await this.workspace.writeArtifact(t,r,a),this.getArtifactUnlocked(t,r)})}async addElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let s=await this.readForMutation(t,r,n,a),l=gn.JsonPointer.resolve(s,n);if(l===void 0)throw new Z.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!Hi(l)||!Hi(i))throw new Z.ValidationError(t,r,n,"parent must be an array, or an object with an object of properties to add");if(o?.position!==void 0)throw new Z.ValidationError(t,r,n,"position is not supported for an object parent");let d={};for(let f of Object.keys(i)){if(f==="id")throw new Z.ValidationError(t,r,n,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let m=(0,fi.cloneJson)(i[f]),p=(0,tm.isValueMapKey)(f)||(0,tm.pointerTouchesValueMap)(n);d[f]=p?m:Array.isArray(m)?m.map(h=>Hi(h)?this.assignMissingIds(t,h):h):Hi(m)?this.assignMissingIds(t,m):m}for(let f of Object.keys(d))gn.JsonPointer.set(s,gn.JsonPointer.append(n,f),d[f]);return this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)}let u=(0,tm.pointerTouchesValueMap)(n)?(0,fi.cloneJson)(i):this.assignMissingIds(t,(0,fi.cloneJson)(i)),c=xae(l,o?.position);return l.splice(c,0,u),this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)})}async moveElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{var s;let l=await this.readForMutation(t,r,n,a),u=gn.JsonPointer.resolve(l,n);if(u===void 0)throw new Z.PathNotFoundError(t,r,n);let c=gn.JsonPointer.resolve(l,i);if(c===void 0)throw new Z.PathNotFoundError(t,r,i);if(!Array.isArray(c))throw new Z.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new Z.ValidationError(t,r,i,"cannot move an element into its own subtree");gn.JsonPointer.remove(l,n);let d=(s=o?.index)!==null&&s!==void 0?s:c.length;c.splice(Math.max(0,Math.min(d,c.length)),0,u),vM(c);let f=gn.JsonPointer.resolve(l,bM(n));return Array.isArray(f)&&f!==c&&vM(f),this.assertStructurallyValid(t,r,l,i),await this.workspace.writeArtifact(t,r,l),this.getArtifactUnlocked(t,r)})}async removeElement(t,r,n){let i=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let o=await this.readForMutation(t,r,n,i);if(gn.JsonPointer.resolve(o,n)===void 0)throw new Z.PathNotFoundError(t,r,n);return gn.JsonPointer.remove(o,n),this.assertStructurallyValid(t,r,o,bM(n)),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)})}assertStructurallyValid(t,r,n,i){var o,a,s;let l=this.registrations.get(t),u=(s=(a=l==null?void 0:(o=l.adapter).validate)===null||a===void 0?void 0:a.call(o,n,i))!==null&&s!==void 0?s:[];if(u.length>0)throw new Z.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,pl.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,pl.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,pl.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,pl.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,pl.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,pl.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,Cae.findDefaultViews)(this.dataverse,t,{excludeViewIds:n.excludeViewIds}),o=n.publish===!1,a=[],s=[],l=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,uM.boundEntityPublishScope)({entityLogicalName:t}),artifacts:a.map(c=>({type:"view",id:c}))}]:[]}),u;try{for(let c of i){await this.fetchArtifact("view",c.id),await this.updateElement("view",c.id,"/columns",r),u=c.id;let d=await this.pushArtifact("view",c.id);u=void 0,s.push(d),d.saved&&a.push(c.id)}}catch(c){throw u&&Aae(c)&&a.push(u),o?(0,Z.withPartialEnrichment)(c,l()):c}if(o)return l();if(a.length){let c=await this.publishArtifact("view",a[0]);if(c.publish.kind==="failed")throw new Z.SdkError("ENRICH_DEFAULT_VIEWS_PUBLISH_FAILED",`enrichDefaultViews: ${a.length} view(s) on '${t}' were saved but the publish FAILED, so none of them is live (${c.publish.error.message}). Re-publish the entity to make them visible; the saves themselves are unaffected.`)}return{updated:a}}async createArtifact(t,r){let n=this.requireRegistration(t,"createArtifact"),i=n.adapter.assignMissingIds(n.adapter.createDefault(r)),o=i.id;if(!o)throw new Z.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,o,async()=>(await this.workspace.writeArtifact(t,o,i),(0,fi.cloneJson)(i)))}async deleteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.workspace.deleteArtifact(t,r)})}async deleteRemoteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let n=this.requireRegistration(t,"deleteRemoteArtifact");await this.workspace.ensureReady(),await n.api.delete(this.dataverse,r),await this.workspace.readArtifact(t,r)&&await this.workspace.deleteArtifact(t,r)})}async publishArtifact(t,r,n){let{result:i,siblings:o}=await this.withArtifactLock(t,r,()=>this.publishArtifactUnlocked(t,r,n));for(let a of o)await this.withArtifactLock(a.type,a.id,()=>this.adoptBracket(a));return i}async publishArtifacts(t,r){var n,i;let o=new Map;for(let p of t){let h=this.artifactKey(p.type,p.id);o.has(h)||o.set(h,{type:p.type,id:p.id})}let a=[];for(let[p,h]of o)a.push(await this.withArtifactLock(h.type,h.id,()=>this.preparePublish(p,h.type,h.id)));let s=new Set(o.keys()),l=[],u=new Set;for(let p of a){let h=((n=p.scope)===null||n===void 0?void 0:n.envelope)==="entity"?(i=p.scope.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;p.scope&&h&&!u.has(h)&&(u.add(h),l.push(p.scope))}let c=await this.captureSiblings(l,s),d=Iae(a),f;if(d)try{await(0,uM.publishXml)(this.dataverse,d)}catch(p){f=Po(p)}let m=new Map;for(let p of a)m.set(p.key,await this.withArtifactLock(p.type,p.id,()=>this.settlePublish(p,f,r)));for(let p of c)await this.withArtifactLock(p.type,p.id,()=>this.adoptBracket(p));return t.map(p=>({...m.get(this.artifactKey(p.type,p.id))}))}async preparePublish(t,r,n){var i;let o=await this.readRaw(r,n),a=this.registrations.get(r);if(!a?.publish)return{key:t,type:r,id:n,artifact:o,notApplicable:!0};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,n,o);if(!s||!Dae.has(s.envelope))throw new Z.InvalidArgumentError(`publishArtifacts: ${r} '${n}' publishes through ${s?`a '${s.envelope}'`:"no declared"} scope, which one PublishXml envelope cannot carry. Publish it with publishArtifact.`);let l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,r,n):void 0;return{key:t,type:r,id:n,artifact:o,reg:a,scope:s,...l?{own:l}:{}}}async settlePublish(t,r,n){let{type:i,id:o}=t;if(t.notApplicable||!t.reg)return{type:i,id:o,shipped:!1,publish:{kind:"notApplicable"}};let a=t.scope?{publishScope:t.scope}:{};if(t.reg.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(t.reg,i,o),t.own&&await this.adoptBracket(t.own),r)return{type:i,id:o,shipped:!1,publish:{kind:"failed",error:r},...a};if(!n?.verify)return{type:i,id:o,shipped:!1,publish:{kind:"submitted"},...a};let s=await this.workspace.readArtifact(i,o).catch(()=>null);if(!s||!(0,yn.deepEqual)(s,t.artifact))return{type:i,id:o,shipped:!1,publish:{kind:"unverifiable",reason:`the local ${i} was ${s?"edited":"deleted"} while the publish was in flight, so what shipped cannot be told from what is local now; verify it with publishArtifact`},...a};let l=await this.verifyPublished(i,o,t.artifact);return{type:i,id:o,shipped:l.kind==="verified",publish:l,...a}}async publishArtifactUnlocked(t,r,n){var i;let o=await this.readRaw(t,r),a=this.registrations.get(t);if(!a?.publish)return{result:{type:t,id:r,shipped:!1,publish:{kind:"notApplicable"}},siblings:[]};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,r,o),l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,t,r):void 0,u=s?await this.captureSiblings([s],new Set([this.artifactKey(t,r)])):[];try{await a.publish(this.dataverse,r,o)}catch(d){return{result:{type:t,id:r,shipped:!1,publish:{kind:"failed",error:Po(d)},...s?{publishScope:s}:{}},siblings:[]}}if(a.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(a,t,r),l&&await this.adoptBracket(l),!n?.verify)return{result:{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}},siblings:u};let c=await this.verifyPublished(t,r,o);return{result:{type:t,id:r,shipped:c.kind==="verified",publish:c,...s?{publishScope:s}:{}},siblings:u}}async captureBracket(t,r,n){try{let i=await this.versions.getMeta(r,n),o=i?.etag;if(!(0,pr.isVersionToken)(o)||!t.api.readContentThenToken)return;let{raw:a,etag:s,siblingEtags:l}=await t.api.readContentThenToken(this.dataverse,n),u=i?.siblingEtags;return s!==o||!kae(u,l)?void 0:{type:r,id:n,reg:t,heldEtag:o,...u?{heldSiblings:u}:{},content:this.bracketContent(t,a)}}catch{return}}async captureSiblings(t,r){var n,i,o;let a=new Map;for(let u of t){let c=u.envelope==="entity"?(n=u.entityLogicalName)===null||n===void 0?void 0:n.toLowerCase():void 0;c&&!a.has(c)&&a.set(c,[])}if(a.size===0)return[];let s;try{s=await this.workspace.listArtifacts()}catch{return[]}for(let u of s){let c=this.registrations.get(u.type);if(!(r.has(this.artifactKey(u.type,u.id))||c?.rebaselineAfterPublish!=="bracket"||!c.publishScope))try{let d=await this.workspace.readArtifact(u.type,u.id),f=d?c.publishScope(u.id,d):void 0,m=f?.envelope==="entity"?(i=f.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;m!==void 0&&((o=a.get(m))===null||o===void 0||o.push(u))}catch{continue}}let l=[];for(let u of a.values())for(let c of u){let d=this.registrations.get(c.type),f=d?await this.captureBracket(d,c.type,c.id):void 0;f&&l.push(f)}return l}async adoptBracket(t){var r;try{let n=await this.versions.getMeta(t.type,t.id);if(!n||n.etag!==t.heldEtag||!(0,yn.deepEqual)((r=n.siblingEtags)!==null&&r!==void 0?r:void 0,t.heldSiblings))return;let{raw:i,etag:o,siblingEtags:a}=await t.reg.api.get(this.dataverse,t.id);if(!(0,pr.isVersionToken)(o)||!EM(a,t.heldSiblings)||!AM(a)||!(o!==t.heldEtag||!(0,yn.deepEqual)(a??void 0,t.heldSiblings))||!(0,yn.deepEqual)(this.bracketContent(t.reg,i),t.content))return;await this.versions.storeMeta(t.type,t.id,{...n,etag:o,...t.heldSiblings?{siblingEtags:{...a}}:{},fetchedAt:(0,pr.nowIso)()},n)}catch{}}bracketContent(t,r){var n,i,o;let a=t.adapter.fromApiResponse(r);return(o=(i=(n=t.adapter).baselineContent)===null||i===void 0?void 0:i.call(n,a))!==null&&o!==void 0?o:a}adoptReadBack(t,r){try{return{artifact:t.adapter.fromApiResponse(r)}}catch(n){return{warning:`The write was saved, but the record read back after it could not be read into the local copy (${Po(n).message}). The SDK holds no version for it now, so the next push is refused: re-fetch before editing again.`}}}adoptedAsSent(t,r,n,i){try{let o={...n,...i},a=t.adapter.fromApiResponse(t.adapter.completeAsStored?t.adapter.completeAsStored(o,n):o);return(0,yn.deepEqual)(r,a)}catch{return!1}}async rebaselineAfterPublish(t,r,n){try{let i=await this.versions.getMeta(r,n);if(!i)return;let{raw:o,etag:a,memberEtags:s,siblingEtags:l}=t.api.getForRebaseline?await t.api.getForRebaseline(this.dataverse,n):await t.api.get(this.dataverse,n),u=t.adapter.fromApiResponse(o),c=d=>{var f,m,p;return(p=(m=(f=t.adapter).baselineContent)===null||m===void 0?void 0:m.call(f,d))!==null&&p!==void 0?p:d};if(!a||!(0,yn.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:a,fetchedAt:(0,pr.nowIso)(),...s?{memberEtags:s}:{},...l?{siblingEtags:l}:{}},i)}catch{}}async verifyPublished(t,r,n){var i;if(t!=="app"){let o=this.registrations.get(t);return o?.api.getPublished?this.verifyPublishedContent(o,t,r,n):{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`}}try{let o=`/appmodules(${(0,Oa.normalizeGuid)(r,"id")})${(0,Oa.odataQuery)([["$select","appmoduleid,name,description"]])}`,a=await this.dataverse.get(o);if(a.status>=200&&a.status<300){let s=(i=a.body)!==null&&i!==void 0?i:{},l=n;if(!l)return{kind:"unverifiable",reason:"there is no local copy of the app to compare the published projection with"};let u=["name","description"].filter(d=>l[d]!==void 0);if(u.length===0)return{kind:"unverifiable",reason:"the local copy of the app holds neither a name nor a description to compare the published projection with, and its presence alone proves nothing for a re-publish"};let c=u.filter(d=>{var f,m;return((f=l[d])!==null&&f!==void 0?f:"")!==((m=s[d])!==null&&m!==void 0?m:"")});return c.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${c.join(", ")} still differ). PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}:{kind:"verified"}}return{kind:"unverifiable",reason:`the published projection answered HTTP ${a.status}`}}catch(o){return{kind:"unverifiable",reason:Po(o).message}}}async verifyPublishedContent(t,r,n,i){var o,a,s;try{let l=f=>{var m,p,h;return(h=(p=(m=t.adapter).baselineContent)===null||p===void 0?void 0:p.call(m,f))!==null&&h!==void 0?h:f},u=l(i),c=(o=await this.versions.getMeta(r,n))===null||o===void 0?void 0:o.snapshot;if(c===void 0||!(0,yn.deepEqual)(u,l(c)))return{kind:"unverifiable",reason:`the local ${r} holds edits that were never pushed, so no publish could have shipped them \u2014 push, then publish again`};let d=await((s=(a=t.api).getPublished)===null||s===void 0?void 0:s.call(a,this.dataverse,n));return d?(0,yn.deepEqual)(u,l(t.adapter.fromApiResponse(d.raw)))?{kind:"verified"}:{kind:"unverifiable",reason:"the published projection does not show what was pushed. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists"}:{kind:"unverifiable",reason:`the ${r} is not in the published projection yet. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}}catch(l){return{kind:"unverifiable",reason:Po(l).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async prepareArtifactUnlocked(t,r,n){var i,o;let a=this.requireRegistration(t,"pushArtifact"),s=await this.workspace.readArtifactWithText(t,r);if(!s)throw new Z.ArtifactNotFoundError(t,r);let l=s.artifact,u=s.text,c=(o=(i=a.adapter).normalize)===null||o===void 0?void 0:o.call(i,l);c&&c!==l&&(await this.workspace.writeArtifact(t,r,c),l=c,u=void 0);let d=await this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,d,a),this.assertProjectionMatches(t,r,d);let f=await this.buildMetadataContext(a.adapter,l,d?.snapshot),m=await a.adapter.toApiPayload(l,d?.snapshot,f);return await this.assertSemanticallyComplete(a,t,r,l,d===null,d?.everActivated,n),{type:t,id:r,reg:a,json:l,...u!==void 0?{storedText:u}:{},meta:d,payload:m}}async assertSemanticallyComplete(t,r,n,i,o,a,s){let l=t.adapter.issuesBlockingPush;if(!l)return;let u=i.entityLogicalName,d=(u?await this.columnsForCheck(t,u,i,s):[]).map(m=>({logicalName:m.logicalName,displayName:m.displayName,attributeType:m.attributeType,isCustomAttribute:m.isCustomAttribute,...m.maxLength!==void 0?{maxLength:m.maxLength}:{},...m.options?{options:m.options.map(p=>({value:p.value,label:p.label}))}:{},...m.targets?{targets:m.targets}:{}})),f=l.call(t.adapter,i,d,{isCreate:o,everActivated:a});if(f.length>0)throw new Z.ValidationError(r,n,f)}columnsForCheck(t,r,n,i){var o,a,s;let l=(s=(a=(o=t.adapter).columnsCheckedAtPush)===null||a===void 0?void 0:a.call(o,n))!==null&&s!==void 0?s:[],u=async()=>{let f=await this.readCachedEntityMetadata(r);if(f)return f.attributes;try{return await(0,dl.readCheckColumns)(this.dataverse,r,l)}catch{return[]}};if(!i)return u();let c=[r,...[...new Set(l)].sort()].join("\0"),d=i.get(c);return d||(d=u(),i.set(c,d)),d}async pushArtifactUnlocked(t,r,n){return this.executePrepared(await this.prepareArtifactUnlocked(t,r,n))}async executePrepared(t){var r,n,i,o,a,s,l,u,c;let{type:d,id:f,reg:m,json:p,meta:h,payload:g}=t,b=!1;try{let w;if(h)w=await m.api.update(this.dataverse,f,g,h.etag,h.memberEtags,h.siblingEtags);else{let O=await this.createWithMintedId(m,d,f,g,p);if("adopted"in O)return await this.persistAdoption(d,f,p,O.adopted);w=O.written}b=!0;let E=f;h||(w.serverIdentity&&m.adapter.applyServerIdentity&&m.adapter.applyServerIdentity(p,w.serverIdentity),w.id&&w.id!==f&&(p.id=w.id,await this.workspace.deleteArtifact(d,f),E=w.id));let S=h&&w.readBack!==void 0?this.adoptReadBack(m,w.readBack):void 0,P=S?.artifact?{artifact:S.artifact,baseline:S.artifact}:m.adapter.committed?m.adapter.committed(p,g,{intentPending:w.intentPending===!0}):{artifact:p,baseline:p};await this.workspace.writeArtifact(d,E,P.artifact,h&&E===f?t.storedText:void 0);let L=S?.artifact!==void 0&&!(0,yn.deepEqual)(S.artifact,p),I=L?this.nextRefreshGeneration(d,E,h):(r=h?.refreshGeneration)!==null&&r!==void 0?r:0,D=[...(n=w.warnings)!==null&&n!==void 0?n:[],...S?.warning?[S.warning]:[],...S?.artifact!==void 0&&!this.adoptedAsSent(m,S.artifact,w.readBack,g)?[`Saved, but the server holds something other than what was pushed (another writer saved in between, or the platform rewrote something the SDK does not model \u2014 a label in a language the org does not provision, a hand-written fragment); the local ${d} now holds the server's version. Read it (getArtifact) before the next edit: a mutation whose pointer was derived from the earlier copy is refused (StaleArtifactError).`]:[]];return await this.versions.storeMeta(d,E,{etag:S&&!S.artifact?null:w.etag,...I>0?{refreshGeneration:I,observedGeneration:(i=h?.observedGeneration)!==null&&i!==void 0?i:0}:{},languageCode:this.languageCode,projectionVersion:cl.PROJECTION_VERSION,fetchedAt:(0,pr.nowIso)(),snapshot:(0,fi.cloneJson)(P.baseline),...w.memberEtags?{memberEtags:w.memberEtags}:{},...w.siblingEtags?{siblingEtags:w.siblingEtags}:{}},E===f?h:void 0),{type:d,id:E,saved:!0,shipped:!1,publish:(o=w.publish)!==null&&o!==void 0?o:{kind:"notRequested"},...w.publish&&w.publish.kind!=="notRequested"?(()=>{var O;let x=(O=m.publishScope)===null||O===void 0?void 0:O.call(m,E,p);return x?{publishScope:x}:{}})():{},...L?{refreshed:!0}:{},...D.length>0?{warnings:D}:{}}}catch(w){let E=(0,Z.readPartialTokens)(w);if(E&&h){let S={...(a=h.memberEtags)!==null&&a!==void 0?a:{},...(s=E.memberEtags)!==null&&s!==void 0?s:{}},P={...(l=h.siblingEtags)!==null&&l!==void 0?l:{},...(u=E.siblingEtags)!==null&&u!==void 0?u:{}};await this.versions.storeMeta(d,f,{...h,...Object.keys(S).length>0?{memberEtags:S}:{},...Object.keys(P).length>0?{siblingEtags:P}:{}},h)}if(w instanceof Z.SdkError&&w.code===mr.ALREADY_EXISTS_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===lM.WFOM_API_UNAVAILABLE_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===lM.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===pr.VERSION_CONFLICT_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,fM.isFailureAfterPrimaryWrite)(w)?w:new Z.VersionConflictError(d,f,(c=h?.etag)!==null&&c!==void 0?c:null,null,w.message)};throw b?Eae(w):w}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new Z.SdkError("ARTIFACT_LANGUAGE_MISMATCH",`Refusing to push ${t} '${r}': it was fetched with languageCode ${n.languageCode} but this SDK is configured with ${this.languageCode}. Pushing would rewrite labels read in one language as labels in another. Re-fetch with languageCode ${this.languageCode}, or create the SDK with languageCode ${n.languageCode}.`)}assertProjectionMatches(t,r,n){var i;if(n&&n.projectionVersion!==cl.PROJECTION_VERSION)throw new Z.SdkError("ARTIFACT_PROJECTION_STALE",`Refusing to push ${t} '${r}': its workspace copy was produced by projection version ${(i=n.projectionVersion)!==null&&i!==void 0?i:"unknown (pre-versioning)"}, but this SDK produces version ${cl.PROJECTION_VERSION}. The parsers changed in between, so an unedited part of this artifact can no longer be told apart from an edited one and pushing could overwrite server content the caller never touched. Re-fetch it with fetchArtifact('${t}', '${r}') and re-apply any local edits.`)}async createWithMintedId(t,r,n,i,o){try{return{written:await t.api.create(this.dataverse,i,n)}}catch(a){let s=r==="form"?(0,Wv.readPrimaryCreateRefusal)(a):void 0;if(s?.status===404&&await(0,dM.formExistsAtId)(()=>t.api.get(this.dataverse,n),s.sent.formid)){let u=`the platform answered the create with ${a.message} \u2014 this build refuses a replayed create that way \u2014 but a read of that id finds the record`;throw(0,Z.attachCause)(new Z.SdkError(mr.ALREADY_EXISTS_CODE,Hv(r,n,u)+(this.createRecovery==="adoptExact"?` ${yM(Pae)}`:"")),a)}if(!(a instanceof Z.SdkError)||a.code!==pr.VERSION_CONFLICT_CODE||(0,fM.isFailureAfterPrimaryWrite)(a))throw a;if(this.createRecovery==="adoptExact"&&s?.status===412){let l=await(0,dM.recoverFormCreate)({client:this.dataverse,read:()=>t.api.get(this.dataverse,n),sent:s.sent,authoredFormType:o.formType,project:u=>t.adapter.fromApiResponse(u)});if("adopted"in l)return{adopted:l.adopted};throw new Z.SdkError(mr.ALREADY_EXISTS_CODE,`${Hv(r,n)} ${yM(l.refused)}`)}throw new Z.SdkError(mr.ALREADY_EXISTS_CODE,Hv(r,n))}}async persistAdoption(t,r,n,i){let{artifact:o,etag:a}=i,s=!(0,yn.deepEqual)(o,n);return await this.versions.storeMeta(t,r,{etag:a,...s?{refreshGeneration:this.nextRefreshGeneration(t,r,null),observedGeneration:0}:{},languageCode:this.languageCode,projectionVersion:cl.PROJECTION_VERSION,fetchedAt:(0,pr.nowIso)(),snapshot:(0,fi.cloneJson)(o)},null),s&&await this.workspace.writeArtifact(t,r,o),{type:t,id:r,saved:!1,adoptedExisting:!0,shipped:!1,publish:{kind:"notRequested"},...s?{refreshed:!0}:{}}}async buildMetadataContext(t,r,n){var i,o,a,s;let l=(o=(i=t.metadataNeeds)===null||i===void 0?void 0:i.call(t,r,n))!==null&&o!==void 0?o:[],u=new Set(l.map(L=>L.entityLogicalName).filter(L=>!!L)),c=new Set(l.filter(L=>L.needsColumnDetail).map(L=>L.entityLogicalName)),d=new Set(l.filter(L=>L.needsColumnDetail||!L.fieldName).map(L=>L.entityLogicalName)),f=L=>l.filter(I=>I.entityLogicalName===L).every(I=>I.fetchRequired===!1),m=new Map,p=new Map;for(let L of u){let I=await this.readCachedEntityMetadata(L);if(I&&c.has(L)&&(I.columnDetailComplete!==!0||!(typeof I.columnDetailVersion=="number"&&I.columnDetailVersion>=dl.COLUMN_DETAIL_VERSION)||I.attributes.some(D=>typeof D.attributeTypeName!="string"))&&(I=null),!I&&!d.has(L)){if(!f(L)){let D=l.filter(O=>O.entityLogicalName===L).map(O=>O.fieldName);try{let O=await(0,dl.readColumnHints)(this.dataverse,L,D);p.set(L,new Map(O.map(x=>[x.logicalName,x])))}catch{}}continue}if(!I&&!f(L))try{await this.loadMissedEntityMetadata(L),I=await this.readCachedEntityMetadata(L)}catch{}I&&m.set(L,I)}let h=(L,I)=>{var D,O,x;return(O=(D=m.get(L))===null||D===void 0?void 0:D.attributes.find(K=>K.logicalName===I))!==null&&O!==void 0?O:(x=p.get(L))===null||x===void 0?void 0:x.get(I)},g=this.languageCode,w=l.some(L=>{if(!L.needsLabel||!L.fieldName)return!1;let I=h(L.entityLogicalName,L.fieldName);return I?.localizedDisplayName!==void 0&&!I.localizedDisplayName[g]})?await this.readBaseLanguage():void 0,E=!((a=t.needsBaseLanguage)===null||a===void 0)&&a.call(t,r)?await this.readBaseLanguage():void 0,S=(s=t.customControlNeeds)===null||s===void 0?void 0:s.call(t,r,n),P=S&&(S.controls.length>0||S.columns.length>0)?await this.readPcfNeeds(S):void 0;return{resolveField:(L,I)=>{let D=h(L,I);return D?{displayName:$ae(D,g,w),attributeType:D.attributeType}:void 0},resolveEntity:L=>m.get(L),loadTypeScript:()=>this.compiler.load(),...E!==void 0?{baseLanguageCode:E}:{},...P?{pcf:P}:{}}}async readPcfNeeds(t){let r=new Map;for(let i of t.controls)r.set(i,await(0,cM.readControlManifest)(this.dataverse,i));let n=new Map;for(let i of t.columns)n.set(i,await(0,cM.readPcfColumn)(this.dataverse,t.entityLogicalName,i,t.requireCreateEligibility?{requireCreateEligibility:!0}:void 0));return{control:i=>r.get(i),column:(i,o)=>i===t.entityLogicalName?n.get(o):void 0}}readBaseLanguage(){if(!this.baseLanguage){let t=(async()=>{var r,n,i;try{let o=await this.dataverse.get("/organizations?$select=languagecode");if(o.status<200||o.status>=300)return;let a=Number((i=(n=(r=o.body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.languagecode);return Number.isInteger(a)&&a>0?a:void 0}catch{return}})();this.baseLanguage=t,t.then(r=>{r===void 0&&this.baseLanguage===t&&(this.baseLanguage=void 0)})}return this.baseLanguage}async pushAll(){let t=await this.getDirtyArtifacts();await this.warmBatchMetadata(t);let r=new Map,n=new Map;for(let o=0;o<t.length;o+=1){let a=t[o];try{await this.withArtifactLock(a.type,a.id,()=>this.prepareArtifactUnlocked(a.type,a.id,r))}catch(s){n.set(o,{type:a.type,id:a.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Po(s)})}}if(n.size>0)return t.map((o,a)=>{var s;return(s=n.get(a))!==null&&s!==void 0?s:{type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new Z.SdkError(mr.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${n.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let i=[];for(let o of t)try{i.push(await this.withArtifactLock(o.type,o.id,()=>this.pushArtifactUnlocked(o.type,o.id,r)))}catch(a){i.push({type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Po(a)})}return i}async warmBatchMetadata(t){var r,n,i;let o=new Set;for(let a of t){let s=this.registrations.get(a.type);if(!s)continue;let l;try{l=await this.readLocal(a.type,a.id)}catch{continue}let u=l.entityLogicalName;u&&o.add(u);for(let c of(i=(n=(r=s.adapter).metadataNeeds)===null||n===void 0?void 0:n.call(r,l))!==null&&i!==void 0?i:[])c.entityLogicalName&&o.add(c.entityLogicalName)}for(let a of o)if(!await this.readCachedEntityMetadata(a))try{await this.loadMissedEntityMetadata(a)}catch{}}async getDirtyArtifacts(){return(await this.withDirtyFlags(await this.workspace.listArtifacts())).filter(r=>r.isDirty)}async diffArtifact(t,r){return this.versions.diff(t,r)}assignMissingIds(t,r){let n=this.registrations.get(t);return n?n.adapter.assignMissingIds(r):(0,tm.assignMissingIds)(r)}async resolveComponentType(t){if(t.genPage)return"genPage";switch(t.componentType){case er.SolutionComponentType.SavedQuery:return"view";case er.SolutionComponentType.SavedQueryVisualization:return"chart";case er.SolutionComponentType.AppModule:return"app";case er.SolutionComponentType.Workflow:return this.workflowArtifactType(t);case er.SolutionComponentType.SystemForm:return this.systemFormArtifactType(t.objectId);default:return}}async systemFormArtifactType(t){let r=await(0,Zp.readSystemFormType)(this.dataverse,t);if(Number.isNaN(r))throw new Z.SdkError(jv,`System form '${t}' answered without a readable type, so whether it is a form or a dashboard cannot be told.`);return(0,Zp.systemFormKindOf)(r)}async workflowArtifactType(t){let r=(0,Oa.normalizeGuid)(t.objectId,"workflowId"),n=`/workflows(${r})${(0,Oa.odataQuery)([["$select","category,businessprocesstype"]])}`,o=(0,pr.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)).body,a=(0,Zp.decodeCode)(o?.category);if(Number.isNaN(a))throw new Z.SdkError(jv,`Workflow '${r}' answered without a readable category, so its kind cannot be told.`);if(t.workflowCategory=a,a===Nae)return"businessRule";if(a===_ae){let s=(0,Zp.decodeCode)(o?.businessprocesstype);if(Number.isNaN(s))throw new Z.SdkError(jv,`Workflow '${r}' (category 4) answered without a readable businessprocesstype, so whether it is a business process flow or a task flow cannot be told.`);return s===0?"bpf":void 0}}requireRegistration(t,r){let n=this.registrations.get(t);if(!n)throw new Z.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};mr.MakerSdk=rm;function Lae(e){return new rm(e)}mr.createMakerSdk=Lae;function Po(e){return e instanceof Error?e:new Error(String(e))}function EM(e,t){let r=Object.keys(e??{}),n=Object.keys(t??{});return r.length===n.length&&r.every(i=>Object.prototype.hasOwnProperty.call(t??{},i))}function AM(e){return Object.values(e??{}).every(pr.isVersionToken)}function kae(e,t){return EM(e,t)&&AM(e)&&Object.keys(e??{}).every(r=>t?.[r]===e?.[r])}function yM(e){return`createRecovery 'adoptExact' did not adopt it: ${e}.`}function Hv(e,t,r){return`Cannot create ${e} '${t}': a record already exists at that id${r?` (${r})`:""}, so an earlier push of this artifact committed before its local version metadata was saved. No duplicate was created. Run fetchArtifact('${e}', '${t}', { overwrite: true }) to adopt the existing record's identity, etag and snapshot \u2014 the overwrite is required, because this local copy has never been pushed, so a plain fetch keeps it and adopts nothing; it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push again: a conditional update, provided the adopted record is complete. If the earlier push committed only PART of a multi-row artifact (e.g. an app's appmodule without its sitemap), that update refuses, naming what is missing and how to remove the partial record. This is not done automatically because the only recovery available here would be an UNCONDITIONAL overwrite, which would destroy any edit made to the record in the meantime.`}function $ae(e,t,r){let n=e.localizedDisplayName;return n?.[t]||(r===void 0?void 0:n?.[r])||e.displayName}function Hi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function bM(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function vM(e){e.length===0||!e.every(t=>Hi(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function xae(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=>Hi(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>Hi(n)&&n.id===t.after);return r<0?e.length:r+1}});var NM=v(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});nm.ARTIFACT_TYPES=void 0;nm.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var TM=v(_M=>{"use strict";Object.defineProperty(_M,"__esModule",{value:!0})});var IM=v(DM=>{"use strict";Object.defineProperty(DM,"__esModule",{value:!0})});var PM=v(OM=>{"use strict";Object.defineProperty(OM,"__esModule",{value:!0})});var LM=v(RM=>{"use strict";Object.defineProperty(RM,"__esModule",{value:!0})});var $M=v(kM=>{"use strict";Object.defineProperty(kM,"__esModule",{value:!0})});var FM=v(xM=>{"use strict";Object.defineProperty(xM,"__esModule",{value:!0})});var UM=v(MM=>{"use strict";Object.defineProperty(MM,"__esModule",{value:!0})});var qM=v(BM=>{"use strict";Object.defineProperty(BM,"__esModule",{value:!0})});var GM=v(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0})});var zM=v(WM=>{"use strict";Object.defineProperty(WM,"__esModule",{value:!0})});var HM=v(jM=>{"use strict";Object.defineProperty(jM,"__esModule",{value:!0})});var JM=v(KM=>{"use strict";Object.defineProperty(KM,"__esModule",{value:!0})});var QM=v(YM=>{"use strict";Object.defineProperty(YM,"__esModule",{value:!0})});var ZM=v(XM=>{"use strict";Object.defineProperty(XM,"__esModule",{value:!0})});var tU=v(eU=>{"use strict";Object.defineProperty(eU,"__esModule",{value:!0})});var nU=v(rU=>{"use strict";Object.defineProperty(rU,"__esModule",{value:!0})});var oU=v(iU=>{"use strict";Object.defineProperty(iU,"__esModule",{value:!0})});var sU=v(aU=>{"use strict";Object.defineProperty(aU,"__esModule",{value:!0})});var uU=v(lU=>{"use strict";Object.defineProperty(lU,"__esModule",{value:!0})});var dU=v(cU=>{"use strict";Object.defineProperty(cU,"__esModule",{value:!0})});var pU=v(fU=>{"use strict";Object.defineProperty(fU,"__esModule",{value:!0})});var hU=v(ce=>{"use strict";var Fae=ce&&ce.__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]})),Ge=ce&&ce.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Fae(t,e,r)};Object.defineProperty(ce,"__esModule",{value:!0});ce.projectConnectorOperationSchema=ce.projectConnectorOperations=ce.createMakerSdk=void 0;var Mae=SM();Object.defineProperty(ce,"createMakerSdk",{enumerable:!0,get:function(){return Mae.createMakerSdk}});Ge(NM(),ce);Ge(TM(),ce);Ge(IM(),ce);Ge(PM(),ce);Ge(LM(),ce);Ge($M(),ce);Ge(FM(),ce);Ge(UM(),ce);Ge(qM(),ce);Ge(GM(),ce);Ge(zM(),ce);Ge(HM(),ce);Ge(JM(),ce);Ge(QM(),ce);Ge(ZM(),ce);Ge(Rd(),ce);Ge(tU(),ce);Ge(nU(),ce);Ge(oU(),ce);Ge(sU(),ce);Ge(uU(),ce);Ge(dU(),ce);Ge(pU(),ce);Ge(Q(),ce);var mU=Al();Object.defineProperty(ce,"projectConnectorOperations",{enumerable:!0,get:function(){return mU.projectConnectorOperations}});Object.defineProperty(ce,"projectConnectorOperationSchema",{enumerable:!0,get:function(){return mU.projectConnectorOperationSchema}})});var Jv=v(pi=>{"use strict";var Uae=pi&&pi.__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]})),Bae=pi&&pi.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),bU=pi&&pi.__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)&&Uae(t,e,r);return Bae(t,e),t};Object.defineProperty(pi,"__esModule",{value:!0});pi.NodeFileSystemStorage=void 0;var vt=bU(require("fs")),tr=bU(require("path")),gU=Q(),yU=Rm();async function vU(e){let t;try{t=await vt.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await vt.promises.unlink(e)}catch{await vt.promises.rmdir(e)}return}if(!t.isDirectory()){await vt.promises.unlink(e);return}for(let r of await vt.promises.readdir(e))await vU(tr.join(e,r));await vt.promises.rmdir(e)}var Kv=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(tr.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!vt.existsSync(r);){n.unshift(tr.basename(r));let i=tr.dirname(r);if(i===r)return tr.resolve(t);r=i}return tr.resolve(vt.realpathSync(r),...n)}assertWithinRoot(t,r){let n=tr.resolve(this.root),i=tr.resolve(t);if(i!==n&&!i.startsWith(n+tr.sep))throw new gU.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(n),a=r?this.realPathThroughNearestAncestor(i):tr.resolve(this.realPathThroughNearestAncestor(tr.dirname(i)),tr.basename(i));if(a!==o&&!a.startsWith(o+tr.sep))throw new gU.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!vt.existsSync(r))return null;try{return await(0,yU.retryTransientIoAsync)(()=>vt.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=tr.dirname(n);await vt.promises.mkdir(i,{recursive:!0});let o=tr.join(i,`.${tr.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await vt.promises.writeFile(o,r,"utf8"),await(0,yU.retryTransientIoAsync)(()=>vt.promises.rename(o,n))}catch(a){try{vt.existsSync(o)&&await vt.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let r=this.pathFor(t);vt.existsSync(r)&&await vt.promises.unlink(r)}async deleteByPrefix(t){await vU(this.pathFor(t,!1))}async ensureContainer(t){await vt.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return vt.existsSync(this.pathFor(t))}};pi.NodeFileSystemStorage=Kv});var wU=v(xr=>{"use strict";var qae=xr&&xr.__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]})),Vae=xr&&xr.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Gae=xr&&xr.__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)&&qae(t,e,r);return Vae(t,e),t};Object.defineProperty(xr,"__esModule",{value:!0});xr.loadNodeTypeScript=xr.createNodeWorkspaceStorage=xr.NodeFileSystemStorage=void 0;var Wae=Jv(),zae=Jv();Object.defineProperty(xr,"NodeFileSystemStorage",{enumerable:!0,get:function(){return zae.NodeFileSystemStorage}});function jae(e){return new Wae.NodeFileSystemStorage(e)}xr.createNodeWorkspaceStorage=jae;async function Hae(){return await Promise.resolve().then(()=>Gae(require("typescript")))}xr.loadNodeTypeScript=Hae});var Ki={};module.exports=Fr(Ki);Ji(Ki,Ee(hU()),module.exports);Ji(Ki,Ee(wU()),module.exports);
+`),diagnostics:c}}ke.compileGenPage=Y5});var xg=v(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});ys.isFailureAfterPrimaryWrite=ys.failedAfterPrimaryWrite=void 0;var QN=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function Q5(e){return typeof e=="object"&&e!==null&&(e[QN]=!0),e}ys.failedAfterPrimaryWrite=Q5;function X5(e){return typeof e=="object"&&e!==null&&e[QN]===!0}ys.isFailureAfterPrimaryWrite=X5});var zd=v(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.appApi=Xn.deleteAppResolvingOnce=Xn.mainFormSetShapeIssues=Xn.unpublishedAppModulesQuery=void 0;var mo=Lt(),Z5=zg(),e8=bg(),XN=Qr(),t8=Fd(),r8=xg(),fe=ye(),Ce=le(),Mg=pt(),Ug=Kl(),de=Q(),n8=(0,Ce.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),Bg="appmoduleid,name,uniquename,description,aiappdescription";function uu(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ce.odataQuery)([["$select",e],["$filter",t],["$top",r]])}Xn.unpublishedAppModulesQuery=uu;function qg(e,t){return uu(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function Gd(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ce.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function su(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function i8(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Wd(e,t){if(typeof e!="string")return!1;try{return(0,Ce.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function na(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function o8(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function a8(e,t){var r,n;let i=u=>{throw new de.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 o=`/sitemaps${(0,Ce.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,Ce.odataLiteral)(t)}'`],["$top",1]])}`,a;try{a=await e.get(o)}catch(u){return i(`failed (${u.message})`)}if(a.status<200||a.status>=300)return i(`returned HTTP ${a.status}`);let s=(r=a.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 s8(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,Ce.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 o=t(await e.get(r(`${n} and ismanaged eq false`)));if(o)return{id:o,managed:!1};let a=t(await e.get(r(n)));return a?{id:a,managed:!0}:void 0}var ZN="627090ff-40a3-4053-8790-584edc5be201";function Dr(e){return e instanceof Error?e.message:String(e)}async function l8(e,t){var r;try{let n=`/roles${(0,Ce.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${ZN}`]])}`,i=await(0,mo.collectPages)(e,n,"the System Administrator role"),o=i.find(l=>typeof l.roleid=="string"&&typeof l._parentrootroleid_value=="string"&&l.roleid.toLowerCase()===l._parentrootroleid_value.toLowerCase()),a=(r=o??i.find(l=>typeof l.roleid=="string"))===null||r===void 0?void 0:r.roleid;if(!a)return`App roles: no 'System Administrator' role (template ${ZN}) was found in this environment, so the SDK did not associate one with the app \u2014 it may not be visible or playable until a role is granted access to it.`;let s=`/appmodules(${t})/appmoduleroles_association/$ref`;return(0,fe.ensureSuccess)(await e.post(s,{"@odata.id":e.apiUrl(`/roles(${a})`)}),e.apiUrl(s)),null}catch(n){return`App roles: could not associate the 'System Administrator' role with the app (${Dr(n)}); it will not be visible or playable until a role is granted access to it.`}}async function u8(e,t,r=!0){let n=[];async function i(l,u,c){try{return(await(0,mo.collectPages)(e,l,`app assets (${c} for '${t}')`)).map(f=>String(f[u])).filter(f=>f&&f!=="undefined")}catch(d){return n.push(`App components: could not enumerate ${c} for table '${t}' (${Dr(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([r?i(`/systemforms${(0,Ce.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,Ce.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,Ce.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,Ce.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,Ce.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,Ce.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:n}}var e_=new WeakMap;async function c8(e,t){let r=e_.get(e);r||(r=new Map,e_.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await d8(e,t);return i&&r.set(t,i),i}async function t_(e,t,r){let n=new Array(e.length),i=0;async function o(){for(let a=i;a<e.length;a=i)i=a+1,n[a]=await r(e[a])}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),n}async function d8(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Ce.odataPathLiteral)(t)}')${(0,Ce.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 r_(e,t,r){let n=[],i=na(t.entities),o=4,a=await t_(i,o,g=>c8(e,g)),s=i.filter((g,b)=>!a[b]);if(s.length>0)throw new de.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${s.map(g=>`'${g}'`).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 l=a.filter(g=>!!g);for(let g of l)n.push({"@odata.id":`${g.entitySetName}(${g.metadataId})`});for(let g of na(t.components.forms))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of na(t.components.views))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of na(t.components.charts))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of na(t.components.dashboards))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});let u=new Set(t.components.forms),c=new Set(t.components.views),d=new Set(t.components.charts),f=new Map((r??[]).map(g=>[g.table,g])),m=await t_(i,o,g=>u8(e,g,!f.has(g.toLowerCase()))),p=m.flatMap(g=>g.warnings),h=new Set([...na(t.components.forms),...na(t.components.dashboards)].map(at));return m.forEach((g,b)=>{let w=f.get(i[b].toLowerCase());if(w)for(let C of w.allowed)h.has(C)||(h.add(C),u.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:C}));else for(let C of g.forms)u.has(C)||(u.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:C}));for(let C of g.views)c.has(C)||(c.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:C}));for(let C of g.charts)d.has(C)||(d.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:C}))}),{components:n,tables:l,warnings:p}}function at(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var bs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Vg="/components/mainFormsByTable",n_=50;function f_(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function p_(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:Vg,rule:"app-main-form-set-shape",message:"must be an object mapping a table logical name to its Main form ids"}];let r=[],n=new Set(t.map(o=>o.toLowerCase())),i=new Set;for(let[o,a]of Object.entries(e)){let s=o.toLowerCase(),l=`${Vg}/${f_(o)}`;if(i.has(s)){r.push({pointer:l,rule:"app-main-form-set-shape",message:`table '${o}' is listed twice (logical names compare case-insensitively)`});continue}if(i.add(s),n.has(s)||r.push({pointer:l,rule:"app-main-form-set-table",message:`'${o}' is not a table this app's sitemap navigates to (Entity subareas: ${[...n].join(", ")||"none"})`}),!Array.isArray(a)){r.push({pointer:l,rule:"app-main-form-set-shape",message:"must be an array of Main form ids"});continue}if(a.length===0){r.push({pointer:l,rule:"app-main-form-set-empty",message:`an empty list is refused: an app with no Main form of '${o}' offers every form of the table`});continue}let u=new Set;a.forEach((c,d)=>{let f=`${l}/${d}`;typeof c!="string"||!bs.test(at(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):u.has(at(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):u.add(at(c))})}return r}Xn.mainFormSetShapeIssues=p_;async function i_(e,t,r){let n=t.components.mainFormsByTable;if(n===void 0)return;let i=p_(n,t.entities);if(i.length>0)throw new de.ValidationError("app",r,i);if(Object.keys(n).length===0)return;let o=[],a=[];for(let[l,u]of Object.entries(n)){let c=l.toLowerCase(),d=await(0,mo.collectPages)(e,`/systemforms${(0,Ce.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,Ce.odataLiteral)(c)}' and type eq 2`]])}`,`app Main-form allow-list ('${c}')`),f=new Set,m=new Set;for(let h of d)typeof h.formid=="string"&&(f.add(at(h.formid)),Number(h.formactivationstate)===1&&m.add(at(h.formid)));let p=u.map(at);p.forEach((h,g)=>{let b=`${Vg}/${f_(l)}/${g}`;f.has(h)?m.has(h)||o.push({pointer:b,rule:"app-main-form-set-inactive",message:`Main form '${u[g]}' of '${c}' is inactive, so no app can offer it`}):o.push({pointer:b,rule:"app-main-form-set-not-main-form",message:`'${u[g]}' is not a Main form of '${c}'`})}),a.push({table:c,allowed:p,catalog:f})}let s=[...t.components.forms.map((l,u)=>({id:l,pointer:`/components/forms/${u}`})),...t.components.dashboards.map((l,u)=>({id:l,pointer:`/components/dashboards/${u}`}))];for(let l of s){let u=at(l.id);for(let c of a)c.catalog.has(u)&&!c.allowed.includes(u)&&o.push({pointer:l.pointer,rule:"app-main-form-set-conflict",message:`'${l.id}' is a Main form of '${c.table}' outside its allow-list, and this pin (an explicit form or dashboard, or a sitemap DashBoard subarea) would add it. Remove the pin, or list the form.`})}if(o.length>0)throw new de.ValidationError("app",r,o);return a}async function Wg(e,t){var r,n;let i=u=>({kind:"inconclusive",reason:u}),o=await e.get(uu("appmoduleid,appmoduleidunique,componentstate",`appmoduleid eq ${t}`));if(o.status<200||o.status>=300)return i(`reading the app returned HTTP ${o.status}`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a)||a.length===0)return i("reading the app returned no row");let s=a.length===1?a:a.filter(u=>Number(u?.componentstate)===1),l=s.length===1?(n=s[0])===null||n===void 0?void 0:n.appmoduleidunique:"";return typeof l!="string"||!bs.test(at(l))?i(`no single current layer among ${a.length} app row(s)`):{kind:"read",unique:at(l)}}function qd(e,t){let r;return()=>r??(r=Wg(e,t))}var m_=62;function f8(e,t,r,n,i){let o=i.map(a=>`'${a}'`).join(", ");return t==="delete"?new de.SdkError("APP_SITEMAP_SHARED",`Refusing to delete app '${e}': its sitemap '${r.sitemapId}' is also the navigation of app ${o}. The delete removes an app's sitemap with it, and the platform does not stop that for a sitemap another app uses, so those apps would be left without navigation. Nothing was deleted. Remove the sitemap from the other app first, then retry.`):new de.SdkError("APP_SITEMAP_SHARED",`Refusing to ${t} app '${e}': it has no SiteMap component, and the sitemap named like it ('${n??""}', '${r.sitemapId}') is the navigation of app ${o}, so it is not this app's. Nothing was ${t==="fetch"?"saved":"modified"}.`)}async function lu(e,t,r,n,i=!1){var o;let a=c=>{throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to ${n} app '${t}': ${c}, so it cannot be determined which sitemap is this app's. Nothing was ${n==="fetch"?"saved":n==="delete"?"deleted":"modified"}. Retry.`)},s;try{s=await Wg(e,t)}catch(c){return a(`reading its current layer failed (${Dr(c)})`)}if(s.kind==="inconclusive")return a(`its current layer could not be read (${s.reason})`);let l;try{l=await(0,mo.collectPages)(e,`/appmodulecomponents${(0,Ce.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${s.unique} and componenttype eq ${m_}`]])}`,`app SiteMap component ('${t}')`)}catch(c){return a(`reading its SiteMap component failed (${Dr(c)})`)}let u;if(l.length>1)return a(`its current layer carries ${l.length} SiteMap components, where an app can hold one`);if(l.length===1){let c=(o=l[0])===null||o===void 0?void 0:o.objectid;if(typeof c!="string"||!bs.test(at(c)))return a(`its SiteMap component carries an object id that is not a GUID ('${String(c)}')`);u={sitemapId:at(c),by:"component"}}else{let c=await a8(e,r);if(!c)return;let d;try{d=(0,Ce.normalizeGuid)(c,"sitemapId")}catch{return a(`the sitemap lookup by unique name returned a sitemapid that is not a GUID ('${String(c)}')`)}u={sitemapId:d,by:"name"}}if(i||u.by==="name"){let c=await p8(e,u.sitemapId,t,a);if(c.length>0)throw f8(t,n,u,r,c)}return u}async function p8(e,t,r,n){var i;let o;try{o=await(0,mo.collectPages)(e,`/appmodulecomponents${(0,Ce.odataQuery)([["$select","_appmoduleidunique_value"],["$filter",`componenttype eq ${m_} and objectid eq ${t}`]])}`,`apps using sitemap '${t}'`)}catch(u){return n(`reading which apps use sitemap '${t}' failed (${Dr(u)})`)}let a=new Set;for(let u of o){let c=u?._appmoduleidunique_value;if(typeof c!="string"||!bs.test(at(c)))return n(`a SiteMap component naming sitemap '${t}' carries no app layer id`);a.add(at(c))}let s=at(r),l=[];for(let u of a){let c;try{c=await e.get(uu("appmoduleid",`appmoduleidunique eq ${u}`))}catch(f){return n(`resolving app layer '${u}' failed (${Dr(f)})`)}if(c.status<200||c.status>=300)return n(`resolving app layer '${u}' returned HTTP ${c.status}`);let d=(i=c.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(d))return n(`resolving app layer '${u}' returned a malformed body`);for(let f of d){let m=f?.appmoduleid;if(typeof m!="string"||!bs.test(at(m)))return n(`app layer '${u}' resolved to a row with no app id`);let p=at(m);if(p===s||l.includes(p))continue;let h;try{h=await Wg(e,p)}catch(g){return n(`reading the current layer of app '${p}' failed (${Dr(g)})`)}if(h.kind==="inconclusive")return n(`the current layer of app '${p}' could not be read (${h.reason})`);h.unique===u&&l.push(p)}}return l}async function h_(e,t,r,n=qd(e,t)){let i=m=>({kind:"inconclusive",reason:m}),o=await n();if(o.kind==="inconclusive")return o;let a=o.unique,s;try{let m=await(0,mo.collectPages)(e,`/appmodulecomponents${(0,Ce.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${at(a)} and componenttype eq 60`]])}`,`app Main-form membership ('${t}')`);if(m.some(p=>typeof p.objectid!="string"))return i("a form component carries no object id");s=m.map(p=>at(String(p.objectid)))}catch(m){return i(`reading its form components failed (${Dr(m)})`)}let l=new Map,u=[];for(let m of new Set(s)){let p=r.find(h=>h.catalog.has(m));p?l.set(m,p.table):u.push(m)}if(u.some(m=>!bs.test(m)))return i("a form component carries an object id that is not a GUID");let c=new Set(r.map(m=>m.table)),d=new Set;for(let m=0;m<u.length;m+=n_){let p=u.slice(m,m+n_);try{let h=await(0,mo.collectPages)(e,`/systemforms${(0,Ce.odataQuery)([["$select","formid,type,objecttypecode"],["$filter",p.map(g=>`formid eq ${g}`).join(" or ")]])}`,`app Main-form membership ('${t}': classifying components)`);for(let g of h){if(typeof g.formid!="string"||typeof g.type!="number"||g.type===2&&(typeof g.objecttypecode!="string"||g.objecttypecode===""))continue;let b=at(g.formid);d.add(b);let w=g.type===2?String(g.objecttypecode).toLowerCase():"";c.has(w)&&l.set(b,w)}}catch(h){return i(`classifying its form components failed (${Dr(h)})`)}}let f=u.filter(m=>!d.has(m));return f.length>0?i(`form component(s) ${f.join(", ")} could not be classified`):{kind:"read",tables:r.map(m=>{let p=[...l].filter(([,h])=>h===m.table).map(([h])=>h);return{table:m.table,members:p,extras:p.filter(h=>!m.allowed.includes(h)),missing:m.allowed.filter(h=>!p.includes(h))}})}}async function m8(e,t,r,n){let i=await h_(e,t,r,n);if(i.kind==="inconclusive")throw new de.SdkError("APP_MAIN_FORM_SET_UNVERIFIED",`App '${t}': its Main-form allow-list was written but could not be verified \u2014 ${i.reason}.`);let o=i.tables.filter(a=>a.extras.length>0||a.missing.length>0);if(o.length>0)throw new de.SdkError("APP_MAIN_FORM_SET_NOT_APPLIED",`App '${t}': its Main forms do not match the allow-list after the write \u2014 ${o.map(a=>`'${a.table}': unexpected [${a.extras.join(", ")}], missing [${a.missing.join(", ")}]`).join("; ")}.`)}async function h8(e,t,r,n){let i;try{i=await h_(e,t,r,n)}catch(a){i={kind:"inconclusive",reason:Dr(a)}}if(i.kind==="inconclusive")return[`Main-form membership of app '${t}' could not be verified (${i.reason}).`];let o=[];for(let a of i.tables)a.extras.length>0&&o.push(`Main-form components outside the allow-list remain for table '${a.table}': [${a.extras.join(", ")}]. This option controls additions only; it does not remove existing components. Runtime form availability has not been verified.`),a.missing.length>0&&o.push(`Allow-listed Main forms are not in app '${t}' after the push for table '${a.table}': [${a.missing.join(", ")}]; re-push to retry.`);return o}async function o_(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,fe.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}async function a_(e,t,r,n=qd(e,t)){var i;if(r.length===0)return;let o=await n();if(o.kind==="inconclusive")throw new de.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 ${o.reason}. Re-push to retry.`);let a=`/appmodulecomponents${(0,Ce.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${o.unique} and componenttype eq 1`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)throw new de.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 reading them back returned HTTP ${s.status}. Re-push to retry.`);let l=(i=s.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(l))throw new de.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 u=new Set(l.map(d=>d.objectid).filter(d=>typeof d=="string").map(d=>d.toLowerCase())),c=r.filter(d=>!u.has(d.metadataId.toLowerCase()));if(c.length>0)throw new de.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${c.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${c.map(d=>`'${d.logicalName}' (expected objectid ${d.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function g8(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`,o;try{o=await b8(e,r.sitemapId,r.sitemapNameUnique)}catch(l){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${Dr(l)})`}}let a=o==="foreign",s=l=>l.kind==="deleted"?{outcome:"removed",foreignSitemap:a}:l.kind==="refused"?{outcome:"kept",foreignSitemap:a,reason:`its delete was refused (${Dr(l.error)})`,...l.lock?{lock:!0}:{}}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${Dr(l.error)})`,...l.lock?{lock:!0}:{}};try{if(o==="absent"||o==="foreign"){if(!r.serverRefusedSitemap)return{outcome:"kept",foreignSitemap:a,reason:"the sitemap write's outcome was never observed, so its row may still appear"};let l=await(0,fe.resendAppSearchIndexRace)(()=>e.delete(n));if(l.status===404)return s({kind:"deleted"});let u=Gg(l,e.apiUrl(n));return s(u.kind!=="deleted"&&(0,fe.isConcurrencyLockRefusal)(l)?{...u,lock:!0}:u)}return e.supportsAtomicBatch?r.sitemapWriteToken?s(await y_(e,[{path:n},{path:i,etag:r.sitemapWriteToken}],{reportLock:!0})):{outcome:"kept",reason:"the sitemap write returned no token of its own, and deleting the row without one could destroy another writer's change"}:{outcome:"kept",reason:"the HttpClient cannot send an atomic change set (no `postRaw`), and deleting the two rows one at a time could strand the sitemap"}}catch(l){return s({kind:"unknown",error:l})}}function y8(e,t,r){if(!(e instanceof Error))return e;let n=t.foreignSitemap?` Sitemap id '${r.sitemapId}' already belongs to ANOTHER app's sitemap, which was left untouched and must not be deleted: supply a sitemapId no other app uses, or omit it so one is minted.`:"";if(t.outcome==="removed")return e.message+=` The partial app this create wrote was removed.${n}`,e;let i=t.foreignSitemap?`appmodule '${r.appId}' (unique name '${r.uniqueName}')`:`appmodule '${r.appId}' (unique name '${r.uniqueName}') and, if it was written, sitemap '${r.sitemapId}'`,a=`a create with that unique name is refused \u2014 remove it in the maker portal, or, once you have confirmed the rows are this create's own, with ${t.foreignSitemap?`deleteRecord('appmodule', '${r.appId}')`:`deleteRecord('appmodule', '${r.appId}') and deleteRecord('sitemap', '${r.sitemapId}')`}.`,s="Once the lock frees \u2014 another customization operation holds it \u2014 check that the rows exist and are this create's own before removing them.";return t.lock&&t.outcome==="kept"?e.message+=` The partial app this create wrote was KEPT \u2014 its rollback deleted nothing, because the environment's customization lock refused it (another customization operation was running): ${i}. ${s} While it exists, ${a}`:t.lock?e.message+=` Whether the partial app this create wrote was removed could not be confirmed, because the environment's customization lock refused or interrupted its rollback, so it may not have run. Check for ${i}. ${s} While any of it exists, ${a}`:e.message+=t.outcome==="kept"?` The partial app this create wrote was KEPT, because ${t.reason}: ${i}. While it exists, ${a}`:` Whether the partial app this create wrote was removed could not be confirmed, because ${t.reason}. Check for ${i}: while any of it exists, ${a}`,e.message+=n,e}async function b8(e,t,r){var n,i,o;let a=Gd(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);return l.length===0?"absent":String((o=(i=l[0])===null||i===void 0?void 0:i.sitemapnameunique)!==null&&o!==void 0?o:"")===r?"ours":"foreign"}async function v8(e,t){var r;let n;try{n=await e.get(uu("appmoduleid,uniquename,componentstate",`appmoduleid eq ${t}`))}catch(s){return{kind:"unsettled",why:`its unpublished read failed (${s.message})`}}if(n.status<200||n.status>=300)return{kind:"unsettled",why:`its unpublished read returned HTTP ${n.status}`};let i=(r=n.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(i)||i.length!==1)return{kind:"unsettled",why:`its unpublished read returned ${Array.isArray(i)?i.length:"no"} row(s), not exactly one`};let o=i[0],a=o?.uniquename;return!Wd(o?.appmoduleid,t)||o?.componentstate!==1||typeof a!="string"||!a?{kind:"unsettled",why:"its unpublished row is not this app as a never-published draft"}:{kind:"draft",uniquename:a}}async function g_(e,t){var r;let n=(0,Ce.normalizeGuid)(t,"id"),i=w=>{throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${w} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`)},o=`/appmodules(${n})${n8}`,a;try{a=await e.get(o)}catch(w){return i(`reading the app failed (${w.message}).`)}let s,l=!1;if(a.status===404){let w=await v8(e,n);if(w.kind!=="draft")return i(`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; ${w.why}.`);s=w.uniquename,l=!0}else{if(a.status<200||a.status>=300)return i(`reading the app returned HTTP ${a.status}.`);s=(r=a.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 u=l?{draft:!0}:{appEtag:(0,fe.readEtag)(a)},c=await lu(e,n,s,"delete");if(!c)return{uniquename:s,...u};let d=c.sitemapId,f=await Vd(e,d),m=Gd(d,"sitemapid,sitemapnameunique,sitemapxml"),p;try{p=await e.get(m)}catch(w){return i(`reading sitemap '${d}' failed (${w.message}).`)}if(p.status<200||p.status>=300)return i(`reading sitemap '${d}' returned HTTP ${p.status}.`);let h=su(p);if(!h)return i(`sitemap '${d}' was not returned by the unpublished-aware read.`);if(c.by==="name"&&h.sitemapnameunique!==s)return i(`sitemap '${d}' now carries sitemapnameunique '${String(h.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);if(!Wd(h.sitemapid,d))return i(`sitemap '${d}' was read back as a row carrying sitemapid '${String(h.sitemapid)}'.`);let g=h.sitemapxml;if(typeof g!="string")return i(`sitemap '${d}' returned no sitemapxml.`);let b=await lu(e,n,s,"delete",!0);return b?.sitemapId!==d||b.by!==c.by?i(`its sitemap link changed while it was read (sitemap '${d}' by ${c.by}, then ${b?`'${b.sitemapId}' by ${b.by}`:"none"}).`):{sitemapId:d,uniquename:s,sitemapXml:g,...u,sitemapEtag:f}}async function w8(e,t,r){let n=(0,Ce.normalizeGuid)(t,"id"),i=await g_(e,n);await r?.(i.sitemapXml),await v_(e,n,i)}Xn.deleteAppResolvingOnce=w8;async function C8(e,t){let r=await y_(e,t);if(r.kind!=="deleted")throw r.error}function Gg(e,t){try{return(0,fe.ensureSuccess)(e,t),{kind:"deleted"}}catch(r){return b_(e.status)?{kind:"refused",error:r}:{kind:"unknown",error:r}}}function E8(e,t){var r;if(e.status!==400&&(e.status<200||e.status>=300))return!1;let n=(r=(0,Ug.parseChangeSetParts)(e.body,t))===null||r===void 0?void 0:r.filter(i=>i.status<200||i.status>=300);return n!==void 0&&n.length>0&&n.every(i=>i.status===400&&(0,fe.namesAppSearchIndexRace)(i.text))}async function y_(e,t,r={}){let n=`batch_${(0,Mg.newId)()}`,i=`changeset_${(0,Mg.newId)()}`,o=t.map((p,h)=>[`--${i}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${h+1}`,"",`DELETE ${e.apiUrl(p.path)} HTTP/1.1`,...p.etag?[`If-Match: ${p.etag}`]:[],""].join(`\r
+`)),a=[`--${n}`,`Content-Type: multipart/mixed;boundary=${i}`,"",...o,`--${i}--`,`--${n}--`,""].join(`\r
+`),s=e.apiUrl("/$batch"),l=o.map((p,h)=>String(h+1)),u;try{u=await(0,fe.resendWhile)(p=>E8(p,l),()=>e.postBatch(a,n),fe.DEADLOCK_BACKOFF_MS)}catch(p){return{kind:"unknown",error:p}}if(r.reportLock){if((0,Ug.isChangeSetLockRefusal)(u,l))return{kind:"refused",lock:!0,error:new de.ConnectionError(s,u.status,`atomic delete of app '${t[0].path}' was refused whole by the customization lock, so it deleted nothing`)};if((0,fe.isConcurrencyLockRefusal)(u)){let p=Gg(u,s);return p.kind==="deleted"?p:{...p,lock:!0}}}let c=Gg(u,s);if(c.kind!=="deleted")return c;let d=`app '${t[0].path}'`;if(typeof u.body!="string"||u.body.length===0)return{kind:"unknown",error:new de.ConnectionError(s,u.status,`atomic delete of ${d} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`)};let f=(0,Ug.parseChangeSetStatuses)(u.body,l);if(f===void 0)return{kind:"unknown",error:new de.ConnectionError(s,u.status,`atomic delete of ${d} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let m=f.find(p=>p<200||p>=300);return m!==void 0?{kind:"refused",error:new de.ConnectionError(s,m,`atomic delete of ${d} was rolled back: the change set reported HTTP ${m}`)}:f.length!==o.length?{kind:"unknown",error:new de.ConnectionError(s,u.status,`atomic delete of ${d} cannot be confirmed: the $batch response reported ${f.length} operation result(s), expected exactly ${o.length}`)}:{kind:"deleted"}}async function Vd(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,fe.readEtag)(r)}catch{return null}}async function s_(e,t){let r=`/appmodules(${t})?$select=appmoduleid`,n=await e.get(r);if(n.status!==404)return(0,fe.ensureSuccess)(n,e.apiUrl(r)),(0,fe.readEtag)(n)}function l_(e){return{sitemapxml:e.sitemapxml,...e.sitemapname!==void 0?{sitemapname:e.sitemapname}:{}}}async function Fg(e,t,r,n){if(!n)return null;let i=await Vd(e,t);if(!i)return null;try{let o=await e.get(Gd(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=su(o);return!a||!Wd(a.sitemapid,t)||a.sitemapnameunique!==n||a.sitemapxml!==r.sitemapxml||r.sitemapname!==void 0&&a.sitemapname!==r.sitemapname?null:i}catch{return null}}function b_(e){return e>=400&&e<500&&e!==408&&e!==429}function u_(e,t,r){if(!e)throw new de.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 v_(e,t,r){let n=`/appmodules(${t})`,i=r.draft?void 0:u_(r.appEtag,t,"app");if(!r.sitemapId){if(r.draft){(0,fe.ensureSuccess)(await(0,fe.resendAppSearchIndexRace)(()=>e.delete(n)),e.apiUrl(n));return}await A8(e,n,i);return}if(!e.supportsAtomicBatch)throw new de.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 C8(e,[{path:n,etag:i},{path:`/sitemaps(${r.sitemapId})`,etag:u_(r.sitemapEtag,t,"sitemap")}])}async function A8(e,t,r){(0,fe.ensureSuccess)(await(0,fe.resendAppSearchIndexRace)(()=>e.delete(t,{headers:{"If-Match":r}})),e.apiUrl(t))}async function c_(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,Z5.collectGenPageIds)(t))]}catch(i){throw new de.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 (${Dr(i)}).`)}if(r.length===0)return;let n=await(0,e8.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new de.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${n.map(i=>`'${i}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function S8(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")}function N8(e,t){var r;let n=[["name",e.appModuleName],["description",e.appModuleDescription],["aiappdescription",e.appModuleAiDescription]],i={};for(let[o,a]of n)a!==void 0&&(t!==void 0&&String((r=t[o])!==null&&r!==void 0?r:"")===String(a??"")||(i[o]=a));return i}async function d_(e,t,r){var n;let i=(0,Ce.normalizeGuid)(t,"id"),o=r==="tokens-first",a=o?await s_(e,i):null,s=qg(Bg,i),l=(0,fe.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=(n=su(l))!==null&&n!==void 0?n:{};if(!u.appmoduleid)throw new de.SdkError("APP_NOT_FOUND",`App '${i}' was not found (checked the unpublished-aware projection, which includes drafts).`);let c=await lu(e,i,u.uniquename,"fetch"),d=c?.sitemapId,f=null;if(c&&d){o&&(f=await Vd(e,d));let p=Gd(d,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),h=(0,fe.ensureSuccess)(await e.get(p),e.apiUrl(p)),g=su(h),b=C=>{throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap '${d}' was located by its ${c.by==="component"?"SiteMap component":"unique name"}, but ${C}, so the sitemap cannot be read. Persisting the app without it would misreport it as having no sitemap, or write an empty one over its navigation. Retry.`)};if(!g)return b("the by-id read returned no row");if(c.by==="name"&&g.sitemapnameunique!==u.uniquename)throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': sitemap '${d}' now carries sitemapnameunique '${String(g.sitemapnameunique)}', not '${String(u.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!Wd(g.sitemapid,d))return b(`the by-id read returned a row carrying sitemapid '${String(g.sitemapid)}'`);if(typeof g.sitemapxml!="string")return b("the by-id read returned no sitemapxml");let w=await lu(e,i,u.uniquename,"fetch");if(w?.sitemapId!==d||w.by!==c.by)throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap link changed while it was read (sitemap '${d}' by ${c.by}, then ${w?`'${w.sitemapId}' by ${w.by}`:"none"}). Nothing was saved. Retry.`);u.$sitemap=g,o||(f=await Vd(e,d))}o||(a=await s_(e,i));let m=a??i8(u);return{raw:u,etag:f,...u.appmoduleid?{siblingEtags:{[(0,Ce.normalizeGuid)(u.appmoduleid,"appmoduleid")]:m}}:{}}}Xn.appApi={get(e,t){return d_(e,t,"tokens-first")},readContentThenToken(e,t){return d_(e,t,"content-first")},async list(e,t){let r=qg(Bg);return(await(0,mo.collectPages)(e,r,"listArtifacts('app')")).map(i=>{var o,a;return{type:"app",id:(o=i.appmoduleid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",isDirty:!1}})},async create(e,t,r){let n=t;if(typeof n.appModuleName!="string"||n.appModuleName.trim()==="")throw new de.ValidationError("app",n.appModuleId,[{pointer:"/name",rule:"app-name-required",message:"an app needs a name to be created, and its 'name' is missing or blank \u2014 set it (updateElement('app', id, '/name', \u2026), or addElement when the key was removed) and push again. Nothing was written."}]);await c_(e,n.sitemapxml);let i=await i_(e,n,n.appModuleId),o=n.iconWebResourceId?void 0:await s8(e),a=n.iconWebResourceId||o?.id;if(!a)throw new de.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 s=null;o?.managed&&(s=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${o.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 l=n.appModuleUniqueName||o8(n.appModuleId),u={name:n.appModuleName,uniquename:l,clienttype:4,formfactor:1,navigationtype:0};n.appModuleDescription&&(u.description=n.appModuleDescription),n.appModuleAiDescription&&(u.aiappdescription=n.appModuleAiDescription),a&&(u.webresourceid=a);let c="/appmodules",d=(0,fe.ensureSuccess)(await(0,fe.resendDeadlockVictim)(()=>e.post(c,(0,fe.withClientMintedId)(u,"appmoduleid",r))),e.apiUrl(c)),f=(0,fe.resolveCreatedId)(d,"appmoduleid","app module",r),m=null,p=null,h=[];s&&h.push(s);let g={kind:"notRequested"},b=n.sitemapId?(0,Ce.normalizeGuid)(n.sitemapId,"sitemapId"):(0,Mg.newId)(),w=!1,C=l_(n);try{let O="/sitemaps",k=(0,fe.echoWrite)("sitemapid"),I=await e.post(`${O}${k.query}`,{sitemapid:b,sitemapnameunique:l,...C},k.options);w=b_(I.status);let D=(0,fe.ensureSuccess)(I,e.apiUrl(O));p=(0,fe.readEtag)(D),m=p??await Fg(e,b,C,l);let P=await r_(e,n,i);h.push(...P.warnings);let x=P.components;x.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:b}),await o_(e,f,x);let K=qd(e,f);await a_(e,f,P.tables,K),i&&await m8(e,f,i,K);let Oe=await l8(e,f);Oe&&h.push(Oe),n.appSettings&&Object.keys(n.appSettings).length>0&&h.push(...await(0,t8.applyAppSettings)(e,f,n.appSettings)),n.published!==!1&&(await(0,XN.publishAppModule)(e,f),g={kind:"submitted"})}catch(O){let k=await g8(e,f,{sitemapId:b,sitemapNameUnique:l,serverRefusedSitemap:w,sitemapWriteToken:p});throw(0,r8.failedAfterPrimaryWrite)(y8(O,k,{appId:f,sitemapId:b,uniqueName:l}))}let S=null;if(g.kind==="submitted")try{let O=await e.get(`/appmodules(${f})?$select=appmoduleid`);O.status>=200&&O.status<300&&(S=(0,fe.readEtag)(O))}catch{}return{id:f,etag:m,serverIdentity:{sitemapId:b},siblingEtags:{[f]:S},publish:g,...h.length>0?{warnings:h}:{}}},async update(e,t,r,n,i,o){var a,s,l;let u=r,c=(0,Ce.normalizeGuid)(t,"id");if(await c_(e,u.sitemapxml),!u.sitemapId)throw new de.ValidationError("app",c,[{pointer:"/sitemapId",rule:"app-sitemap-identity-missing",message:`missing sitemap identity \u2014 re-fetch the app before pushing edits: fetchArtifact('app', '${c}', { overwrite: true }) (it REPLACES the local copy \u2014 keep outstanding changes aside), push that refreshed copy UNTOUCHED, then re-apply your changes and push again. If the untouched push is refused with this same rule, the app has NO sitemap on the server \u2014 an earlier create committed its appmodule but not its sitemap \u2014 and it can be neither updated, published nor removed with deleteRemoteArtifact (an unpublished app reads back 404). Only for an app you have confirmed is your own abandoned partial create, with nothing else provisioning it: remove its appmodule row with deleteRecord('appmodule', '${c}'), clear the local copy with deleteArtifact('app', '${c}'), then author the app again and push.`}]);let d=(0,Ce.normalizeGuid)(u.sitemapId,"sitemapId");if(!(0,fe.isVersionToken)(n))throw new de.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${c}': ${n?`the concurrency token held for its sitemap row ('${n}') is not a version`:"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 f=await i_(e,u,c),m=await r_(e,u,f),p=`/appmodules(${c})`,h=(a=o?.[c])!==null&&a!==void 0?a:null,g,b;try{let Ne=qg(Bg,c),se=await e.get(Ne);if(se.status>=200&&se.status<300){let We=su(se);if(typeof We=="object"&&We!==null&&!Array.isArray(We)){g=We;let ir=g.uniquename;b=typeof ir=="string"&&ir?ir:void 0}}}catch{}let w=N8(u,g),C=await lu(e,c,b||u.appModuleUniqueName,"push");if(C?.sitemapId!==d)throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to push app '${c}': ${C?`its sitemap is now '${C.sitemapId}'`:"it has no sitemap now"}, not '${d}', the one this copy holds \u2014 the app's sitemap is no longer the one this copy was fetched with. Nothing was modified. Re-fetch the app (fetchArtifact('app', '${c}', { overwrite: true })) and re-apply the change.`);let S=h;if(Object.keys(w).length>0){if(!(0,fe.isVersionToken)(h))throw new de.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${c}': ${h?`the concurrency token held for its appmodule header ('${h}') is not a version`:"no concurrency token is held for its appmodule header"}, so its header edit could not be made conditional and would silently overwrite a concurrent edit. Nothing was modified. Re-fetch the app (fetchArtifact('app', '${c}', { overwrite: true })) and re-apply the change.`);let Ne=(0,fe.echoWrite)("appmoduleid",{"If-Match":h}),se=await e.patch(`${p}${Ne.query}`,w,Ne.options);if(S8(se))throw new de.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${c}': its appmodule row is UNPUBLISHED, and Dataverse cannot resolve version numbers for a draft appmodule (HTTP 400). A draft header cannot be PATCHed at all \u2014 a plain retry fails too, as an upsert-create ("webresourceid cannot be NULL"). Publish the app first, then push the header edit. Nothing was modified by this call.`);(0,fe.ensureSuccess)(se,e.apiUrl(p)),S=(0,fe.readEtag)(se)}let O=l_(u),k=u.sitemapNameUnique||b||u.appModuleUniqueName||void 0,I=(0,fe.echoWrite)("sitemapid",{"If-Match":n}),D=`/sitemaps(${d})`,P;try{P=(0,fe.ensureSuccess)(await e.patch(`${D}${I.query}`,{...O},I.options),e.apiUrl(D))}catch(Ne){throw(0,de.withPartialTokens)(Ne,{siblingEtags:{[c]:S}})}let x=[...m.warnings],K=qd(e,c);try{await o_(e,c,m.components),await a_(e,c,m.tables,K)}catch(Ne){x.push(`App '${c}': one or more components were not pinned (${Ne.message}). Navigation may reference content not included in the app; re-push to retry.`)}f&&x.push(...await h8(e,c,f,K));let Oe={kind:"notRequested"},Vt=S,Xe=(s=(0,fe.readEtag)(P))!==null&&s!==void 0?s:await Fg(e,d,O,k);if(u.published===!0){try{await(0,XN.publishAppModule)(e,c),Oe={kind:"submitted"}}catch(Ne){Oe={kind:"failed",error:Ne},x.push(`App '${c}': saved, but publishing failed (${Ne.message}). The app remains unpublished; re-push to retry.`)}if(Oe.kind==="submitted"){Vt=null;try{let Ne=await e.get(`/appmodules(${c})?$select=appmoduleid`);Ne.status>=200&&Ne.status<300&&(Vt=(0,fe.readEtag)(Ne)),Xe=(l=await Fg(e,d,O,k))!==null&&l!==void 0?l:Xe}catch{}}}return{id:c,etag:Xe,siblingEtags:{[c]:Vt},publish:Oe,...x.length>0?{warnings:x}:{}}},async delete(e,t){let r=(0,Ce.normalizeGuid)(t,"id");await v_(e,r,await g_(e,r))}}});var zg=v(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});vs.deleteAppCascade=vs.collectGenPageIds=void 0;var _8=zd(),T8=Q(),jg=le(),D8=ns();function w_(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),n=new D8.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml"),i=n?.documentElement;if(!i||t.length>0)throw new T8.InvalidArgumentError(`The app sitemap xml could not be parsed cleanly, so its generative-page children cannot be determined${t.length>0?` (${t[0]})`:""}`);let o=[],a=s=>{if(s.nodeName==="SubArea"){let u=s.getAttribute("GenPageId");u&&o.push((0,jg.normalizeGuid)(u,"GenPageId"))}let l=s.childNodes;for(let u=0;u<l.length;u+=1){let c=l[u];c.nodeType===1&&a(c)}};return a(i),o}vs.collectGenPageIds=w_;async function I8(e,t,r){let n=(0,jg.normalizeGuid)(t,"appModuleId");(0,jg.normalizeGuid)(r,"appModuleIdUnique");let i=[],o=[],a=[];await(0,_8.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&a.push(...w_(l))}),i.push({type:"app",id:n});let s=[...new Set(a)].map(l=>({type:"genPage",id:l}));return{success:o.length===0,deleted:i,failures:o,retained:s}}vs.deleteAppCascade=I8});var C_={};Jr(C_,{Guid:()=>U});var U,ht=L(()=>{"use strict";U=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 q,Xt=L(()=>{"use strict";st();q=class e{static get EmptyString(){return""}static IsTrue(t){let r=!1;return r=t&&(this.IsStrictTrue(t)||this.IsYes(t)),r}static IsStrictTrue(t){let r=!1;return t&&(r=t.toLowerCase()==="true"),r}static IsYes(t){return t.toLowerCase()==="yes"||t.toLowerCase()==="y"}static get WhiteSpace(){return/ /g}static get EnglishAndNumericCharacters(){return/([a-z0-9A-Z]+)/g}static get ValidIdExpression(){return/([a-z0-9A-Z_]+)/g}static IsNullOrEmpty(t){return t==null||t==null||t==""}static Format(t,r){return e.IsNullOrEmpty(t)?t:t.replace(/\{\{|\}\}|\{(\d+)\}/g,function(n,i){return n=="{{"?"{":n=="}}"?"}":r[i]})}static EndsWithString(t,r){return t.indexOf(r,t.length-r.length)!==-1}static IsBlankString(t){return t.replace(/\s/g,"").length==0}static EscapeXml(t,r){let n=t;return this.IsNullOrEmpty(n)||(n=n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),r&&(n=n.replace(/"/g,"&quot;").replace(/'/g,"&apos;"))),n}static EscapeDomId(t){return t.replace(".","\\.")}static ToSnakeCase(t){let r=e.EmptyString;for(let n=0;n<t.length;n++)n!==0&&t[n]==t[n].toUpperCase()&&(r+="-"),r+=t[n].toLowerCase();return r}static GetSnakeCaseMarkup(t,r){let n="<"+this.ToSnakeCase(t);if(!R.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 R.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 E_={};Jr(E_,{ScriptUtilities:()=>R});var R,st=L(()=>{"use strict";ht();Xt();R=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return q.IsNullOrEmpty(t.ToString())?!0:U.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:q.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 jd,Hd,ia,Kd,Hg,Jd,Kg=L(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(jd||(jd={}));Hd=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},ia=class extends Hd{key;oldValue;newValue;constructor(t,r,n,i){super(jd.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)}},Kd=class extends Hd{property;oldValue;newValue;constructor(t,r,n,i){super(jd.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)}},Hg=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()})}},Jd=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 Hg(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 A_={};Jr(A_,{ChartGridMode:()=>ln,ColumnLayoutWidths:()=>L8,ComponentCategory:()=>Qd,ComponentType:()=>Jg,ControlLayoutTypes:()=>r0,DisplayConditionsInfo:()=>R8,ElementNames:()=>E,ElementProperties:()=>y,ElementType:()=>Qg,EntityAttributeProperty:()=>Xg,EventType:()=>cu,FormActivationState:()=>t0,FormCanvasServiceScope:()=>j8,FormDesignerSideBarTab:()=>Yg,FormPresentation:()=>Zg,FormState:()=>Yd,FormType:()=>gt,HeaderDensityType:()=>ho,LookUpTable:()=>Zn,MORE_TAB_PREFIX:()=>x8,NavBarChildElementType:()=>e0,PREVIEW_ID_HEADER_FLYOUT:()=>B8,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>V8,PREVIEW_ID_NAVIGATION_AREA:()=>M8,PREVIEW_ID_QUICKCREATE_ROOT:()=>W8,PREVIEW_ID_TAB:()=>G8,PREVIEW_ID_TAB_LIST:()=>q8,PREVIEW_ID_TAB_PANEL:()=>U8,PropertyModelKeys:()=>o0,PropertyModelSectionKeys:()=>$8,RELATED_TAB_ID:()=>a0,RELATED_TAB_PREFIX:()=>F8,SectionDefaultProperties:()=>k8,SectionLayoutTypes:()=>je,TabContentType:()=>n0,TabDefaultProperties:()=>go,TabLayoutTypes:()=>ze,TelemetryPropertyNames:()=>z8,UnboundControlPropertyKeys:()=>i0,compositeAddressFields:()=>P8,compositeFieldNames:()=>zr,compositeFields:()=>O8});var gt,Jg,Yg,E,y,Qg,zr,O8,P8,Xg,Zn,Yd,ho,Zg,R8,e0,t0,ze,k8,go,je,r0,n0,L8,i0,o0,$8,cu,ln,a0,x8,F8,M8,U8,B8,q8,V8,G8,W8,z8,Qd,j8,ue=L(()=>{"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"})(gt||(gt={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(Jg||(Jg={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(Yg||(Yg={}));(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"})(E||(E={}));y={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"})(Qg||(Qg={}));zr={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},O8=[zr.fullname,zr.yomifullname,zr.address1_composite,zr.address2_composite,zr.address3_composite,zr.billto,zr.shipto],P8=[zr.address1_composite,zr.address2_composite,zr.address3_composite,zr.billto,zr.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(Xg||(Xg={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(Zn||(Zn={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Yd||(Yd={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(ho||(ho={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Zg||(Zg={}));R8={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(e0||(e0={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(t0||(t0={}));(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"})(ze||(ze={}));k8={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},go={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"})(je||(je={}));(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"})(r0||(r0={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(n0||(n0={}));L8={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"})(i0||(i0={}));(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"})(o0||(o0={}));$8={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"})(cu||(cu={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(ln||(ln={}));a0="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",x8="more_tab_",F8="related_tab_",M8="preview_id_navigation_area",U8="tab-section",B8="headerFieldsFlyout",q8="tablist",V8="header_overflowButton",G8="tab",W8="quickCreateRoot",z8={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"})(Qd||(Qd={}));j8="CellCanvasServiceScope"});var S_={};Jr(S_,{Attribute:()=>Xd,FormElementNode:()=>re});var Xd,re,It=L(()=>{"use strict";st();Xt();Kg();ue();ht();Xd=class{key;value;constructor(t,r){this.key=t,this.value=r}},re=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-${U.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(E.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new Xd(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 ia(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 ia(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 ia(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 Kd(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 ia(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){R.IsNullOrUndefined(t)||(t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,0,t)}))}moveChild(t,r){let n=this.childrenNodes.indexOf(t);if(n<0)return!1;let i=Math.min(Math.max(0,n+r),this.childrenNodes.length-1);return n!==i&&this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(i,0,this.childrenNodes.splice(n,1)[0])}),!0}getChildren(t){let r=[];for(let n of this.childrenNodes)n.nodeName===t&&r.push(n);return r}getFirstChild(t){for(let r of this.childrenNodes)if(r.nodeName===t)return r;return null}getAllGrandChildren(t){let r=this.getChildren(t),n=null;return r.length===0?new Array:(n=r[0],n.childrenNodes)}deleteChild(t){if(R.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:q.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=R.IsNullOrUndefined(r)?this.childrenNodes.length:r,this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(t,r)})}deleteGrandChildren(t,r,n){this.getChildren(t)[0].deleteChildren(r,n)}addGrandChild(t,r){let n=this.getChildren(t),i=null;n.length===0?(i=new e(t,this),this.addChild(i)):i=n[0],i.addChild(r)}addGrandChildAtIndex(t,r,n){let i=this.getChildren(t),o=null;i.length===0?(o=new e(t,this),this.addChild(o)):o=i[0],o.insertChildAtIndex(r,n)}GetPropertyByParameter(t){return this.getProperty(t)}getSemanticParent(){switch(this.getNodeName()){case E.formCell:let t=this.getAncestor(E.formSection);return t||(t=this.getAncestor(E.formHeader),t)||(t=this.getAncestor(E.formFooter),t)?t:null;case E.formSection:return this.getAncestor(E.formTab);case E.formTab:return this.getAncestor(E.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(E.form);return t?t.changeTracker():null}}});var N_={};Jr(N_,{ControlClassId:()=>N,ControlNamePrefixes:()=>Zd,getControlDisplayNames:()=>H8});function H8(e){return{[N.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[N.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[N.ACIControl]:e("controls.controlNames.aci"),[N.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[N.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[N.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[N.ArticleContentControl]:e("controls.controlNames.articleContent"),[N.BooleanControl]:e("controls.controlNames.twoOption"),[N.ButtonControl]:e("controls.controlNames.button"),[N.CheckboxControl]:e("controls.controlNames.checkbox"),[N.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[N.ConnectionControl]:e("controls.controlNames.connection"),[N.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[N.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[N.DashboardControl]:e("controls.controlNames.dashboard"),[N.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[N.EditFilterControl]:e("controls.controlNames.editFilter"),[N.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[N.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[N.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[N.KBViewerControl]:e("controls.controlNames.kbViewer"),[N.LabelControl]:e("controls.controlNames.label"),[N.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[N.MapLinkControl]:e("controls.controlNames.mapLink"),[N.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[N.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[N.PowerBIControl]:e("controls.controlNames.powerBI"),[N.ProcessControl]:e("controls.controlNames.process"),[N.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[N.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[N.ReportControl]:e("controls.controlNames.report"),[N.StreamsControl]:e("controls.controlNames.streams"),[N.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[N.CurrencyControl]:e("controls.controlNames.currency"),[N.DateTimeControl]:e("controls.controlNames.dateAndTime"),[N.DecimalControl]:e("controls.controlNames.decimal"),[N.DurationControl]:e("controls.controlNames.duration"),[N.EmailAddressControl]:e("controls.controlNames.email"),[N.FileControl]:e("controls.controlNames.file"),[N.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[N.IframeControl]:e("controls.controlNames.iframe"),[N.ImageControl]:e("controls.controlNames.image"),[N.LookupControl]:e("controls.controlNames.lookup"),[N.MapsControl]:e("controls.controlNames.maps"),[N.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[N.ChoiceControl]:e("controls.controlNames.choice"),[N.QuickViewControl]:e("controls.controlNames.quickView"),[N.QuickFormControl]:e("controls.controlNames.quickForm"),[N.CustomControl]:e("controls.controlNames.customControl"),[N.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[N.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[N.SubgridControl]:e("controls.controlNames.subgrid"),[N.TextAreaControl]:e("controls.controlNames.textArea"),[N.TextboxControl]:e("controls.controlNames.textBox"),[N.TickerControl]:e("controls.controlNames.ticker"),[N.UrlControl]:e("controls.controlNames.url"),[N.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[N.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[N.IntegerControl]:e("controls.controlNames.integer"),[N.TimerControl]:e("controls.controlNames.timer"),[N.TimelineControl]:e("controls.controlNames.timeline"),[N.EmailBodyControl]:e("controls.controlNames.emailBody"),[N.PartyListControl]:e("controls.controlNames.partyList"),[N.TimezoneControl]:e("controls.controlNames.timezone"),[N.LanguageControl]:e("controls.controlNames.language"),[N.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[N.ChoicesControl]:e("controls.controlNames.choices"),[N.RegardingControl]:e("controls.controlNames.regarding"),[N.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[N.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[N.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[N.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[N.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[N.KBEditorControl]:e("controls.controlNames.KBEditor"),[N.LinkControl]:e("controls.controlNames.link")}}var N,Zd,oa=L(()=>{"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"})(N||(N={}));Zd={[N.WebResourceHTMLControl]:"WebResource",[N.WebResourceImageControl]:"WebResource",[N.IframeControl]:"IFRAME",[N.SearchWidgetControl]:"Search widget",[N.SubgridControl]:"Subgrid",[N.TimelineControl]:"Timeline",[N.QuickViewControl]:"QuickviewControl"}});var aa=v((Ble,T_)=>{var du=new Proxy(function(){return du},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:du},apply:function(){return du},construct:function(){return{}}}),__=function(){return du};Object.setPrototypeOf(__,du);T_.exports=__});var cr,Ri,D_,I_,ws=L(()=>{"use strict";cr="cds-designer-models",Ri="FormCustomControl",D_="FormCell",I_="Form"});var sa,s0=L(()=>{"use strict";Wl();ue();sa=class e{static lockedFieldCount=new ar;static dependencyFieldCount=new ar;static getNecessaryLookUpTable(t){switch(t){case Zn.DependencyFieldTable:return e.dependencyFieldCount;case Zn.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case Zn.DependencyFieldTable:e.dependencyFieldCount=new ar;case Zn.LockedFieldTable:e.lockedFieldCount=new ar}}}});var ef,O_=L(()=>{"use strict";ht();st();ue();It();ef=class extends re{constructor(t){super(E.controlDescription,t)}get forControl(){let t=this.getProperty(y.ForControl);return R.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set forControl(t){this.setProperty(y.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(E.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!R.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!R.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)R.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}}});function ki(){return ei||(ei=window._makerConfig,ei&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(ei={...ei,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),ei?.region==="prod"&&(ei={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/"}}},...ei}),ei||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var ei,tf=L(()=>{"use strict";});function P_(e,t,r){if(!e)return rf.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),rf.add("")),!1;if(e){if(e=e.toLowerCase(),rf.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}}),rf.add(e),!1}return!0}function K8(e){return P_(e,l0,"Location dictionary")?l0[e.toLowerCase()]:"us"}function J8(){let e=ki().location.toLowerCase();return P_(e,l0,"Current location dictionary")?e:"us"}var rf,l0,Zle,R_=L(()=>{"use strict";tf();rf=new Set,l0={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"};Zle=K8(J8())});var Y,tue,k_=L(()=>{"use strict";Y={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"},tue={[Y.USWest]:{geoName:"us",regionShortName:"wus"},[Y.USCentral]:{geoName:"us",regionShortName:"cus"},[Y.USEast]:{geoName:"us",regionShortName:"eus"},[Y.USEast2]:{geoName:"us",regionShortName:"eus2"},[Y.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[Y.USWest2]:{geoName:"us",regionShortName:"wus2"},[Y.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[Y.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[Y.UKSouth]:{geoName:"uk",regionShortName:"suk"},[Y.UKWest]:{geoName:"uk",regionShortName:"wuk"},[Y.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[Y.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[Y.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[Y.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[Y.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[Y.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[Y.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[Y.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[Y.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[Y.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[Y.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[Y.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[Y.AsiaEast]:{geoName:"as",regionShortName:"eas"},[Y.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[Y.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[Y.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[Y.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[Y.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[Y.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[Y.UAENorth]:{geoName:"ae",regionShortName:"nae"},[Y.UAECentral]:{geoName:"ae",regionShortName:"cae"},[Y.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[Y.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[Y.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[Y.NorwayEast]:{geoName:"no",regionShortName:"eno"},[Y.NorwayWest]:{geoName:"no",regionShortName:"wno"},[Y.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[Y.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[Y.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[Y.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[Y.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[Y.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[Y.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[Y.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[Y.GovernmentUSDodCentral]:{regionShortName:"udc"},[Y.GovernmentUSDodEast]:{regionShortName:"ude"},[Y.ChinaEast]:{regionShortName:"cne"},[Y.ChinaEast2]:{regionShortName:"cne2"},[Y.ChinaEast3]:{regionShortName:"cne3"},[Y.ChinaNorth]:{regionShortName:"cnn"},[Y.ChinaNorth2]:{regionShortName:"cnn2"},[Y.ChinaNorth3]:{regionShortName:"cnn3"},[Y.UssecEast]:{geoName:"us",regionShortName:"erx"},[Y.UssecWest]:{geoName:"us",regionShortName:"wrx"},[Y.UsnatEast]:{geoName:"us",regionShortName:"eex"},[Y.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var L_=L(()=>{"use strict";tf();});var fu=L(()=>{"use strict";tf();R_();k_();L_();});function pu(e,t){return $_?$_.isOverridden(e,t):{overridden:!1}}var $_,mu=L(()=>{"use strict";});var u0=L(()=>{"use strict";fu();mu();});function Y8(e,t){let{region:r}=ki();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=pu(e.packageName,t);if(s.overridden)return typeof s.value=="string"?Q8(s.value):s.value}let o=n.values,a=process.env.SETTINGS_FALLBACK_REGION?.[r];return o[r]!==void 0?o[r]:a&&o[a]!==void 0?o[a]:o.default}}function Q8(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function X8(e){let t=e.packageName;if(nf.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=>d0(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=>!af(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function hu(e){X8(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:Y8(e,r)}}),nf.set(e.packageName,e),Object.defineProperties({},t)}function c0(e,t){return nf.has(e)?!!nf.get(e).settings[t]:!1}var nf,of=L(()=>{"use strict";fu();mu();f0();gu();nf=new Map});function x_(e,t){let{region:r}=ki();return()=>{let n=pu(e.packageName,t);if(n.overridden)return n.value.toString()==="true";let i=e.features[t].enabledFor,o=process.env.SETTINGS_FALLBACK_REGION?.[r];return i[r]!==void 0?!!i[r]:o&&i[o]!==void 0?!!i[o]:!1}}function Z8(e){let t=e.packageName;if(sf.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=>c0(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=>!af(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function p0(e){Z8(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:x_(e,i)}});let r={},n=new Set;return t.dangerouslySet={enumerable:!1,value:(i,o)=>{n.add(i),Object.defineProperty(r,i,{enumerable:!0,configurable:!0,value:o})}},t.dangerouslyReset={enumerable:!1,value:()=>{let i={};n.forEach(o=>{i[o.toString()]={enumerable:!0,configurable:!0,get:x_(e,o.toString())}}),Object.defineProperties(r,i),n.clear()}},sf.set(e.packageName,e),Object.defineProperties(r,t)}function d0(e,t){return sf.has(e)?!!sf.get(e).features[t]:!1}var sf,f0=L(()=>{"use strict";fu();gu();mu();of();sf=new Map});var M_=v((_ue,F_)=>{"use strict";F_.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 q_=v(m0=>{"use strict";var e6=Object.prototype.hasOwnProperty,t6;function U_(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function B_(e){try{return encodeURIComponent(e)}catch{return null}}function r6(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=U_(n[1]),o=U_(n[2]);i===null||o===null||i in r||(r[i]=o)}return r}function n6(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(e6.call(e,i)){if(n=e[i],!n&&(n===null||n===t6||isNaN(n))&&(n=""),i=B_(i),n=B_(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}m0.stringify=n6;m0.parse=r6});var y0=v((Due,H_)=>{"use strict";var G_=M_(),lf=q_(),W_=/[\n\r\t]/g,i6=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,o6=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,a6=/^[a-zA-Z]:/,s6=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function g0(e){return(e||"").toString().replace(s6,"")}var h0=[["#","hash"],["?","query"],function(t,r){return ti(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]],V_={hash:1,query:1};function z_(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,o;if(e.protocol==="blob:")n=new ri(unescape(e.pathname),{});else if(i==="string"){n=new ri(e,{});for(o in V_)delete n[o]}else if(i==="object"){for(o in e)o in V_||(n[o]=e[o]);n.slashes===void 0&&(n.slashes=i6.test(e.href))}return n}function ti(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function j_(e,t){e=g0(e),e=e.replace(W_,""),t=t||{};var r=o6.exec(e),n=r[1]?r[1].toLowerCase():"",i=!!r[2],o=!!r[3],a=0,s;return i?o?(s=r[2]+r[3]+r[4],a=r[2].length+r[3].length):(s=r[2]+r[4],a=r[2].length):o?(s=r[3]+r[4],a=r[3].length):s=r[4],n==="file:"?a>=2&&(s=s.slice(2)):ti(n)?s=r[4]:n?i&&(s=s.slice(2)):a>=2&&ti(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||ti(n),slashesCount:a,rest:s}}function l6(e,t){if(e==="")return t;for(var r=(t||"/").split("/").slice(0,-1).concat(e.split("/")),n=r.length,i=r[n-1],o=!1,a=0;n--;)r[n]==="."?r.splice(n,1):r[n]===".."?(r.splice(n,1),a++):a&&(n===0&&(o=!0),r.splice(n,1),a--);return o&&r.unshift(""),(i==="."||i==="..")&&r.push(""),r.join("/")}function ri(e,t,r){if(e=g0(e),e=e.replace(W_,""),!(this instanceof ri))return new ri(e,t,r);var n,i,o,a,s,l,u=h0.slice(),c=typeof t,d=this,f=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=lf.parse),t=z_(t),i=j_(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||a6.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!ti(d.protocol)))&&(u[3]=[/(.*)/,"pathname"]);f<u.length;f++){if(a=u[f],typeof a=="function"){e=a(e,d);continue}o=a[0],l=a[1],o!==o?d[l]=e:typeof o=="string"?(s=o==="@"?e.lastIndexOf(o):e.indexOf(o),~s&&(typeof a[2]=="number"?(d[l]=e.slice(0,s),e=e.slice(s+a[2])):(d[l]=e.slice(s),e=e.slice(0,s)))):(s=o.exec(e))&&(d[l]=s[1],e=e.slice(0,s.index)),d[l]=d[l]||n&&a[3]&&t[l]||"",a[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=l6(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&ti(d.protocol)&&(d.pathname="/"+d.pathname),G_(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:"&&ti(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function u6(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||lf.parse)(t)),n[e]=t;break;case"port":n[e]=t,G_(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 o=t.indexOf(":");~o?(n.username=t.slice(0,o),n.username=encodeURIComponent(decodeURIComponent(n.username)),n.password=t.slice(o+1),n.password=encodeURIComponent(decodeURIComponent(n.password))):n.username=encodeURIComponent(decodeURIComponent(t))}for(var a=0;a<h0.length;a++){var s=h0[a];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:"&&ti(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function c6(e){(!e||typeof e!="function")&&(e=lf.stringify);var t,r=this,n=r.host,i=r.protocol;i&&i.charAt(i.length-1)!==":"&&(i+=":");var o=i+(r.protocol&&r.slashes||ti(r.protocol)?"//":"");return r.username?(o+=r.username,r.password&&(o+=":"+r.password),o+="@"):r.password?(o+=":"+r.password,o+="@"):r.protocol!=="file:"&&ti(r.protocol)&&!n&&r.pathname!=="/"&&(o+="@"),n[n.length-1]===":"&&(n+=":"),o+=n+r.pathname,t=typeof r.query=="object"?e(r.query):r.query,t&&(o+=t.charAt(0)!=="?"?"?"+t:t),r.hash&&(o+=r.hash),o}ri.prototype={set:u6,toString:c6};ri.extractProtocol=j_;ri.location=z_;ri.trimLeft=g0;ri.qs=lf;H_.exports=ri});var d6,K_=L(()=>{"use strict";d6=Ae(y0());});function b0(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 uf=L(()=>{"use strict";});var v0,w0,C0=L(()=>{"use strict";uf();v0=class{features=new Map;register(t,r){let n=b0(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()}},w0=new v0});var E0=L(()=>{"use strict";});function af(e){return f6.has(e)}var f6,gu=L(()=>{"use strict";u0();f0();of();mu();u0();K_();C0();uf();E0();f6=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var p6,J_=L(()=>{"use strict";gu();p6=hu({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 Z_,S0,Cs,la,A0,cf,Es,Li,Ue,Y_,Q_,X_,Tn=L(()=>{"use strict";Z_={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},S0={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"})(Cs||(Cs={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(la||(la={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(A0||(A0={}));cf=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"})(Es||(Es={}));Li=class{static StartTag="<"},Ue={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:la.Left,labelPosition:Es.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"})(Y_||(Y_={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(Q_||(Q_={}));(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"})(X_||(X_={}))});var N0,eT=L(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(N0||(N0={}))});var nT,m6,tT,Ace,Sce,yu,rT,Nce,_ce,iT=L(()=>{"use strict";nT=Ae(aa());st();ws();J_();os();Tn();Ho();ue();m6=Ae(Qi());eT();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(tT||(tT={}));Ace={Read:io.Read,Edit:io.Edit,Both:io.Both,Container:io.Container},Sce={input:jo.Input,bound:jo.Bound,output:jo.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(yu||(yu={}));(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"})(rT||(rT={}));Nce=new Set([F.Currency,F.Decimal,F.FP,F.Multiple,F.SingleLineEmail,F.SingleLinePhone,F.SingleLineText,F.SingleLineTextArea,F.SingleLineURL,F.SingleLineTickerSymbol,F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.Enum,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.TwoOptions,F.Boolean,F.PowerBIReport,F.DateAndTimeDateAndTime,F.DateAndTimeDateOnly,F.OptionSet,F.MultiSelectOptionSet,F.CardForm]),_ce={numbers:[F.WholeNone,F.FP,F.Decimal,F.Currency],text:[F.SingleLineText,F.SingleLineTextArea,F.Multiple],lookup:[F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding],dates:[F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime],allFields:[F.TwoOptions,F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime,F.FP,F.Decimal,F.WholeNone,F.WholeDuration,F.WholeTimeZone,F.WholeLanguage,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.Multiple,F.OptionSet,F.SingleLineText,F.SingleLineTextArea,F.SingleLineEmail,F.SingleLineURL,F.SingleLineTickerSymbol,F.SingleLinePhone]}});var Dn,df,oT=L(()=>{"use strict";Dn=Ae(aa());ht();st();Xt();ws();Ho();iT();os();ue();It();Tn();df=class extends re{constructor(t){super(E.customControl,t)}customControlId;get id(){let t=this.getProperty(y.id);return R.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(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 o=i.getNodeName();t.get(o)?t.get(o).push(i):t.set(o,[i])}}}return t}getFormComponentValueByParameterName(t){let r=this.getParameters()?.get(Ht.value);if(r?.length>0){let n=r[0],i=n?.getAllChildren()?.length>0?n.getAllChildren().find(a=>a.getNodeName()===t):null,o=i?.getAllChildren()?.length>0?i.getAllChildren()[0].getNodeName():"";return this.normalizePropertyValue(o)}}getParameterValue(t){let r=this.getParameterNodeChild(t);return r&&this.normalizePropertyValue(r.getNodeName())}getParameterNodeChild(t){let r=this.getParameters().get(t);return r?.length>0&&r[0].getAllChildren()?.length>0?r[0].getAllChildren()[0]:null}getDatasetName(t){return t.getAllProperties().find(r=>r.key===Ht.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===Ht.name)?.value,o={Name:i,Type:F.Grid,Columns:[]},l=this.getParameters().get(Ht.dataset).find(u=>this.getDatasetName(u)===i).getAllChildren();for(let u of l){let c=u.getNodeName();if(u&&u.getAllChildren().length>0){let d=this.normalizePropertyValue(u.getAllChildren()[0].getNodeName());o[c]=d}}return o}}getParameterIsStatic(t){let r=!1,n=this.getParameters().get(t)[0],i=n&&n.getAllProperties();if(i){for(let o of i)if(o.key===y.static&&o.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(y.Name)}get formFactor(){return this.getProperty(y.formFactor)}set formFactor(t){this.setProperty(y.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(Li.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,o=this.getParameters();for(let[a,s]of o)if(this.isDataSet(a))for(let l of o.get(a)){let u=l.getAllProperties(),c=this.getDatasetName(l),d=i.get(c),f=await this.parameterJSON(a,u,d,t);r.push({Name:c,Value:f})}else if(this.isGroups(s))r.push({Name:a,Value:{Type:qh.GroupDefinition,Value:this.normalizePropertyValue(this.getParameterNodeChild(s[0].NodeName).NodeName)}}),i.get(a).groupSet?.forEach(u=>{u.groupConfigurableProperties.forEach(async c=>{let d=c.name;c.propertyType===yu.dataset?o.get(Ht.dataset)?.some(m=>this.getDatasetName(m)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:F.Grid}}):c.propertyType===yu.property&&(o.has(d)||r.push({Name:d,Value:{Usage:c.usage}}))})});else{let l=s[0].getAllProperties(),u=i.get(a),c=await this.parameterJSON(a,l,u,t);if(c)r.push({Name:a,Value:c});else{(0,Dn.trackInfoTrace)(cr,{eventName:`${Ri}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/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,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/parametersToJSON`,eventData:{message:"parameters to json failed"}},n)}return r}async parameterJSON(t,r,n,i){if(this.isDataSet(t)){let o=n,a=r.find(s=>s.key===Ht.name)?.value;if(o)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${a}`);(0,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let o=n,a=r&&r.find(l=>l.key===y.Type),s=o&&!o.ofTypeGroup.every(l=>!fd.includes(l));if(this.isLookupType(a?.value)||this.isLookupType(o?.ofType)||s)if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=o.isPrimary;if(this.name===Ti.FormComponent){let d=this.getFormComponentValueByParameterName(y.bindAttribute),f=await i.formModelService.loadLookupModel(d),m=f.lookupColumn,p=this.getLookupDataTypeFromAttributeMetadata(m);return{Name:t,Type:p,Usage:l,Static:u,Primary:c,EntityName:f.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(Bh.DefaultViewId),TargetEntityType:m.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(y.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(y.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(y.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(y.DependentAttributeType),AllowFilterOff:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.AllowFilterOff)),DisableQuickFind:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.DisableQuickFind)),EnableViewPicker:!q.IsStrictTrue(this.getFormComponentValueByParameterName(y.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,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/parameterJSON`,eventData:{message:"Missing custom control manifest lookup property info"}},l)}if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=this.getParameterValue(t),d=o.isPrimary;if(a){let m=a.value;return{Type:m,Static:u,Usage:l,Value:this.isNumberTypeProperty(o,m)&&Number(c)?Number(c):c,Primary:d}}if(o.ofType)return{Type:o.ofType,Static:u,Usage:l,Value:c,Primary:!0};if(o.ofTypeGroup)return{Static:u,Usage:l,Value:c,Primary:!0};let f=new Error(`No property type info for ${t}`);(0,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/parameterJSON`,eventData:{message:"Missing property type info"}},f)}else{let l=new Error(`No property manifest info for ${t}`);(0,Dn.trackWarningTrace)(cr,{eventName:`${Ri}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case $.Customer:return F.LookupCustomer;case $.Owner:return F.LookupOwner;case $.PartyList:return F.LookupPartyList;default:return n===W.Regarding?F.LookupRegarding:F.LookupSimple}}isLookupType(t){return fd.includes(t)}isNumberTypeProperty(t,r){return pd.includes(r)||t.ofTypeGroup.some(n=>pd.includes(n))}isDataSet(t){return Ht.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var ee,_0=L(()=>{"use strict";ee=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 aT={};Jr(aT,{CustomControlUniqueId:()=>ua,DeprecatedControlClassIds:()=>G,FieldControlTypes:()=>lt,mapFieldTypeToControl:()=>h6});function h6(e,t){switch(e){case $.TwoOptions:return N.BooleanControl;case $.Customer:case $.CustomerType:return N.LookupControl;case $.DateTime:return t===W.DateAndTime?N.DateTimeControl:N.DateTimeControl;case $.DecimalNumber:return N.DecimalControl;case $.FloatingPointNumber:return N.FloatingNumberControl;case $.WholeNumber:return t===W.Duration?N.DurationControl:t===W.Language?N.LanguageControl:t===W.TimeZone?N.TimezoneControl:N.IntegerControl;case $.CustomerType:case $.Lookup:case $.LookupType:return t===W.Regarding?N.RegardingControl:N.LookupControl;case $.MultipleLineofText:return t===W.Email?N.EmailBodyControl:N.TextAreaControl;case $.Currency:return N.CurrencyControl;case $.Owner:case $.OwnerType:return N.LookupControl;case $.PartyList:case $.PartyListType:return N.PartyListControl;case $.Status:case $.OptionSet:return N.ChoiceControl;case $.SingleLineofText:return t===W.Email?N.EmailAddressControl:t===W.Phone?N.PhoneNumberControl:t===W.Text?N.TextboxControl:t===W.TextArea?N.TextAreaControl:t===W.TickerSymbol?N.TickerControl:t===W.Url?N.UrlControl:t===W.PhoneticGuide?N.TextboxControl:N.TextboxControl;case $.MultiSelectOptionSet:return N.ChoicesControl;case $.Image:return N.ImageControl;case $.File:return N.FileControl;case $.State:return N.ChoiceControl;case $.Status:return N.ChoiceStatusControl;default:throw new Error(`Cannot get base control for ${e} field type`)}}var G,ua,lt,bu=L(()=>{"use strict";ht();Wl();st();Xt();os();oa();_0();Tn();G=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"}};ua=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},lt=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new ar;static initializeFieldControls(){let t=new ar,r=e.getControlName($.SingleLineofText,W.Phone);t.add(r,new U(G.PhoneNumberControl));let n=e.getControlName($.SingleLineofText,W.TextArea);t.add(n,new U(G.TextAreaControl));let i=e.getControlName($.SingleLineofText,W.Text);t.add(i,new U(G.TextBoxControl));let o=e.getControlName($.SingleLineofText,W.Email);t.add(o,new U(G.EmailAddressControl));let a=e.getControlName($.SingleLineofText,W.Url);t.add(a,new U(G.UrlControl));let s=e.getControlName($.SingleLineofText,W.TickerSymbol);t.add(s,new U(G.TickerControl));let l=e.getControlName($.SingleLineofText,W.PhoneticGuide);t.add(l,new U(G.TextBoxControl));let u=e.getControlName($.WholeNumber,W.Duration);t.add(u,new U(G.DurationControl));let c=e.getControlName($.WholeNumber,W.Language);t.add(c,new U(G.LanguagePickerControl));let d=e.getControlName($.WholeNumber,W.TimeZone);t.add(d,new U(G.TimeZonePicklistControl));let f=e.getControlName($.WholeNumber,W.None);t.add(f,new U(G.IntegerControl));let m=e.getControlName($.DateTime,W.DateOnly);t.add(m,new U(G.DateTimeControl));let p=e.getControlName($.DateTime,W.DateAndTime);t.add(p,new U(G.DateTimeControl));let h=e.getControlName($.LookupType,W.None);t.add(h,new U(G.LookupControl));let g=e.getControlName($.CustomerType,W.None);t.add(g,new U(G.LookupControl));let b=e.getControlName($.FloatingPointNumber,W.None);t.add(b,new U(G.FloatControl));let w=e.getControlName($.DecimalNumber,W.None);t.add(w,new U(G.DecimalControl));let C=e.getControlName($.Currency,W.None);t.add(C,new U(G.MoneyControl));let S=e.getControlName($.MultipleLineofText,W.None);t.add(S,new U(G.TextAreaControl));let O=e.getControlName($.MultipleLineofText,W.Text);t.add(O,new U(G.TextAreaControl));let k=e.getControlName($.MultipleLineofText,W.TextArea);t.add(k,new U(G.TextAreaControl));let I=e.getControlName($.MultipleLineofText,W.Email);t.add(I,new U(G.EmailBodyControl));let D=e.getControlName($.OptionSet,W.None);t.add(D,new U(G.PicklistControl));let P=e.getControlName($.TwoOptions,W.None);t.add(P,new U(G.RadioControl));let x=e.getControlName($.Image,W.None);t.add(x,new U(G.WebResourceImageControl));let K=e.getControlName($.Image,W.None);t.add(K,new U(G.WebResourceHtmlControl));let Oe=e.getControlName($.TwoOptions,"Radio");t.add(Oe,new U(G.RadioControl));let Vt=e.getControlName($.TwoOptions,"CheckBox");t.add(Vt,new U(G.CheckBoxControl));let Xe=e.getControlName($.TwoOptions,"List");t.add(Xe,new U(G.PicklistControl));let Ne=e.getControlName($.State,W.None);t.add(Ne,new U(G.PicklistControl));let se=e.getControlName($.Status,W.None);t.add(se,new U(G.PicklistStatusControl));let We=e.getControlName($.OwnerType,W.None);t.add(We,new U(G.LookupControl));let ir=e.getControlName($.PartyListType,W.None);t.add(ir,new U(G.PartyListControl));let PU=e.getControlName($.LookupType,W.Regarding);t.add(PU,new U(G.RegardingControl));let RU=e.getControlName($.MultiSelectOptionSet,W.None);return t.add(RU,new U(G.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(!R.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=R.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===G.CustomControl}static initializeUnboundControls(){let t=new ar;return t.add(G.ACIControl,ee.ACIControl),t.add(G.IframeControl,ee.IframeControl),t.add(G.SearchWidgetControl,ee.SearchWidgetControl),t.add(G.MapsControl,ee.MapsControl),t.add(G.QuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.GridControl,ee.SubGridControl),t.add(G.WebResourceImageControl,ee.WebResourceImageControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.TimerControl,ee.TimerControl),t.add(G.TimeLineControl,ee.NotesControl),t.add(G.TimeLineControlUC,ee.NotesControl),t.add(G.SocialInsightControl,ee.SocialInsightControl),t.add(ua.RelationshipAssistant,ee.CustomControl),t}static initializeReferencePanelControls(){let t=new ar;return t.add(G.IframeControl,ee.IframeControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.WebResourceImageControl,ee.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new is;return t.add(Cs.IFRAME,!0),t.add(Cs.SPACER,!0),t.add(Cs.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!R.IsNullOrUndefined(t)&&!R.IsNullOrUndefined(t.Name)&&t.Name.indexOf(Ue.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=q.EmptyString;if(R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.guidString)?q.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===G.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!R.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case ee.IframeControl:case ee.ACIControl:case ee.SocialInsightControl:return 6;case ee.SubGridControl:case ee.CustomControl:return 4;case ee.WebResourceImageControl:return 15;case ee.WebResourceHtmlControl:return 15;case ee.MapsControl:return 8;case ee.SearchWidgetControl:return 10;case ee.NotesControl:case ee.TimeLineControl:return 15;case ee.TimerControl:return 2;default:}}static isLookUpControl(t){return!R.IsNullOrUndefined(t)&&t.ClassId.guidString===G.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!R.IsNullOrUndefined(t)&&(t.guidString===ua.RelationshipAssistant||t.guidString===ua.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!R.IsNullOrUndefined(t)&&t.guidString===ua.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(R.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!R.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var ff,sT=L(()=>{"use strict";ff=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 ca,As,lT,uT,yo,cT,dT,T0=L(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(ca||(ca={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(As||(As={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(lT||(lT={}));(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"})(uT||(uT={}));(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"})(yo||(yo={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(cT||(cT={}));(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"})(dT||(dT={}))});var Ss,fT=L(()=>{"use strict";gu();Ss=p0({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 pT(e){return{...e,extractConfig:t=>g6(t,Object.keys(e.fallback))}}function g6(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var D0=L(()=>{"use strict";});var I0=v((Zce,hT)=>{var vu=new Proxy(function(){return vu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:vu},apply:function(){return vu},construct:function(){return{}}}),mT=function(){return vu};Object.setPrototypeOf(mT,vu);hT.exports=mT});var bT=v((ede,yT)=>{var wu=new Proxy(function(){return wu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:wu},apply:function(){return wu},construct:function(){return{}}}),gT=function(){return wu};Object.setPrototypeOf(gT,wu);yT.exports=gT});var O0=v((tde,wT)=>{var Cu=new Proxy(function(){return Cu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Cu},apply:function(){return Cu},construct:function(){return{}}}),vT=function(){return Cu};Object.setPrototypeOf(vT,Cu);wT.exports=vT});var ET=v((rde,CT)=>{function y6(){this.__data__=[],this.size=0}CT.exports=y6});var Ns=v((nde,AT)=>{function b6(e,t){return e===t||e!==e&&t!==t}AT.exports=b6});var Eu=v((ide,ST)=>{var v6=Ns();function w6(e,t){for(var r=e.length;r--;)if(v6(e[r][0],t))return r;return-1}ST.exports=w6});var _T=v((ode,NT)=>{var C6=Eu(),E6=Array.prototype,A6=E6.splice;function S6(e){var t=this.__data__,r=C6(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():A6.call(t,r,1),--this.size,!0}NT.exports=S6});var DT=v((ade,TT)=>{var N6=Eu();function _6(e){var t=this.__data__,r=N6(t,e);return r<0?void 0:t[r][1]}TT.exports=_6});var OT=v((sde,IT)=>{var T6=Eu();function D6(e){return T6(this.__data__,e)>-1}IT.exports=D6});var RT=v((lde,PT)=>{var I6=Eu();function O6(e,t){var r=this.__data__,n=I6(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}PT.exports=O6});var Au=v((ude,kT)=>{var P6=ET(),R6=_T(),k6=DT(),L6=OT(),$6=RT();function _s(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])}}_s.prototype.clear=P6;_s.prototype.delete=R6;_s.prototype.get=k6;_s.prototype.has=L6;_s.prototype.set=$6;kT.exports=_s});var $T=v((cde,LT)=>{var x6=Au();function F6(){this.__data__=new x6,this.size=0}LT.exports=F6});var FT=v((dde,xT)=>{function M6(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}xT.exports=M6});var UT=v((fde,MT)=>{function U6(e){return this.__data__.get(e)}MT.exports=U6});var qT=v((pde,BT)=>{function B6(e){return this.__data__.has(e)}BT.exports=B6});var P0=v((mde,VT)=>{var q6=typeof global=="object"&&global&&global.Object===Object&&global;VT.exports=q6});var In=v((hde,GT)=>{var V6=P0(),G6=typeof self=="object"&&self&&self.Object===Object&&self,W6=V6||G6||Function("return this")();GT.exports=W6});var Su=v((gde,WT)=>{var z6=In(),j6=z6.Symbol;WT.exports=j6});var KT=v((yde,HT)=>{var zT=Su(),jT=Object.prototype,H6=jT.hasOwnProperty,K6=jT.toString,Nu=zT?zT.toStringTag:void 0;function J6(e){var t=H6.call(e,Nu),r=e[Nu];try{e[Nu]=void 0;var n=!0}catch{}var i=K6.call(e);return n&&(t?e[Nu]=r:delete e[Nu]),i}HT.exports=J6});var YT=v((bde,JT)=>{var Y6=Object.prototype,Q6=Y6.toString;function X6(e){return Q6.call(e)}JT.exports=X6});var da=v((vde,ZT)=>{var QT=Su(),Z6=KT(),ez=YT(),tz="[object Null]",rz="[object Undefined]",XT=QT?QT.toStringTag:void 0;function nz(e){return e==null?e===void 0?rz:tz:XT&&XT in Object(e)?Z6(e):ez(e)}ZT.exports=nz});var $i=v((wde,eD)=>{function iz(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}eD.exports=iz});var pf=v((Cde,tD)=>{var oz=da(),az=$i(),sz="[object AsyncFunction]",lz="[object Function]",uz="[object GeneratorFunction]",cz="[object Proxy]";function dz(e){if(!az(e))return!1;var t=oz(e);return t==lz||t==uz||t==sz||t==cz}tD.exports=dz});var nD=v((Ede,rD)=>{var fz=In(),pz=fz["__core-js_shared__"];rD.exports=pz});var aD=v((Ade,oD)=>{var R0=nD(),iD=(function(){var e=/[^.]+$/.exec(R0&&R0.keys&&R0.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function mz(e){return!!iD&&iD in e}oD.exports=mz});var k0=v((Sde,sD)=>{var hz=Function.prototype,gz=hz.toString;function yz(e){if(e!=null){try{return gz.call(e)}catch{}try{return e+""}catch{}}return""}sD.exports=yz});var uD=v((Nde,lD)=>{var bz=pf(),vz=aD(),wz=$i(),Cz=k0(),Ez=/[\\^$.*+?()[\]{}|]/g,Az=/^\[object .+?Constructor\]$/,Sz=Function.prototype,Nz=Object.prototype,_z=Sz.toString,Tz=Nz.hasOwnProperty,Dz=RegExp("^"+_z.call(Tz).replace(Ez,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Iz(e){if(!wz(e)||vz(e))return!1;var t=bz(e)?Dz:Az;return t.test(Cz(e))}lD.exports=Iz});var dD=v((_de,cD)=>{function Oz(e,t){return e?.[t]}cD.exports=Oz});var bo=v((Tde,fD)=>{var Pz=uD(),Rz=dD();function kz(e,t){var r=Rz(e,t);return Pz(r)?r:void 0}fD.exports=kz});var mf=v((Dde,pD)=>{var Lz=bo(),$z=In(),xz=Lz($z,"Map");pD.exports=xz});var _u=v((Ide,mD)=>{var Fz=bo(),Mz=Fz(Object,"create");mD.exports=Mz});var yD=v((Ode,gD)=>{var hD=_u();function Uz(){this.__data__=hD?hD(null):{},this.size=0}gD.exports=Uz});var vD=v((Pde,bD)=>{function Bz(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}bD.exports=Bz});var CD=v((Rde,wD)=>{var qz=_u(),Vz="__lodash_hash_undefined__",Gz=Object.prototype,Wz=Gz.hasOwnProperty;function zz(e){var t=this.__data__;if(qz){var r=t[e];return r===Vz?void 0:r}return Wz.call(t,e)?t[e]:void 0}wD.exports=zz});var AD=v((kde,ED)=>{var jz=_u(),Hz=Object.prototype,Kz=Hz.hasOwnProperty;function Jz(e){var t=this.__data__;return jz?t[e]!==void 0:Kz.call(t,e)}ED.exports=Jz});var ND=v((Lde,SD)=>{var Yz=_u(),Qz="__lodash_hash_undefined__";function Xz(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Yz&&t===void 0?Qz:t,this}SD.exports=Xz});var TD=v(($de,_D)=>{var Zz=yD(),ej=vD(),tj=CD(),rj=AD(),nj=ND();function Ts(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])}}Ts.prototype.clear=Zz;Ts.prototype.delete=ej;Ts.prototype.get=tj;Ts.prototype.has=rj;Ts.prototype.set=nj;_D.exports=Ts});var OD=v((xde,ID)=>{var DD=TD(),ij=Au(),oj=mf();function aj(){this.size=0,this.__data__={hash:new DD,map:new(oj||ij),string:new DD}}ID.exports=aj});var RD=v((Fde,PD)=>{function sj(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}PD.exports=sj});var Tu=v((Mde,kD)=>{var lj=RD();function uj(e,t){var r=e.__data__;return lj(t)?r[typeof t=="string"?"string":"hash"]:r.map}kD.exports=uj});var $D=v((Ude,LD)=>{var cj=Tu();function dj(e){var t=cj(this,e).delete(e);return this.size-=t?1:0,t}LD.exports=dj});var FD=v((Bde,xD)=>{var fj=Tu();function pj(e){return fj(this,e).get(e)}xD.exports=pj});var UD=v((qde,MD)=>{var mj=Tu();function hj(e){return mj(this,e).has(e)}MD.exports=hj});var qD=v((Vde,BD)=>{var gj=Tu();function yj(e,t){var r=gj(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}BD.exports=yj});var hf=v((Gde,VD)=>{var bj=OD(),vj=$D(),wj=FD(),Cj=UD(),Ej=qD();function Ds(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])}}Ds.prototype.clear=bj;Ds.prototype.delete=vj;Ds.prototype.get=wj;Ds.prototype.has=Cj;Ds.prototype.set=Ej;VD.exports=Ds});var WD=v((Wde,GD)=>{var Aj=Au(),Sj=mf(),Nj=hf(),_j=200;function Tj(e,t){var r=this.__data__;if(r instanceof Aj){var n=r.__data__;if(!Sj||n.length<_j-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new Nj(n)}return r.set(e,t),this.size=r.size,this}GD.exports=Tj});var L0=v((zde,zD)=>{var Dj=Au(),Ij=$T(),Oj=FT(),Pj=UT(),Rj=qT(),kj=WD();function Is(e){var t=this.__data__=new Dj(e);this.size=t.size}Is.prototype.clear=Ij;Is.prototype.delete=Oj;Is.prototype.get=Pj;Is.prototype.has=Rj;Is.prototype.set=kj;zD.exports=Is});var HD=v((jde,jD)=>{var Lj="__lodash_hash_undefined__";function $j(e){return this.__data__.set(e,Lj),this}jD.exports=$j});var JD=v((Hde,KD)=>{function xj(e){return this.__data__.has(e)}KD.exports=xj});var QD=v((Kde,YD)=>{var Fj=hf(),Mj=HD(),Uj=JD();function gf(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Fj;++t<r;)this.add(e[t])}gf.prototype.add=gf.prototype.push=Mj;gf.prototype.has=Uj;YD.exports=gf});var ZD=v((Jde,XD)=>{function Bj(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}XD.exports=Bj});var tI=v((Yde,eI)=>{function qj(e,t){return e.has(t)}eI.exports=qj});var $0=v((Qde,rI)=>{var Vj=QD(),Gj=ZD(),Wj=tI(),zj=1,jj=2;function Hj(e,t,r,n,i,o){var a=r&zj,s=e.length,l=t.length;if(s!=l&&!(a&&l>s))return!1;var u=o.get(e),c=o.get(t);if(u&&c)return u==t&&c==e;var d=-1,f=!0,m=r&jj?new Vj:void 0;for(o.set(e,t),o.set(t,e);++d<s;){var p=e[d],h=t[d];if(n)var g=a?n(h,p,d,t,e,o):n(p,h,d,e,t,o);if(g!==void 0){if(g)continue;f=!1;break}if(m){if(!Gj(t,function(b,w){if(!Wj(m,w)&&(p===b||i(p,b,r,n,o)))return m.push(w)})){f=!1;break}}else if(!(p===h||i(p,h,r,n,o))){f=!1;break}}return o.delete(e),o.delete(t),f}rI.exports=Hj});var x0=v((Xde,nI)=>{var Kj=In(),Jj=Kj.Uint8Array;nI.exports=Jj});var oI=v((Zde,iI)=>{function Yj(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}iI.exports=Yj});var sI=v((efe,aI)=>{function Qj(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}aI.exports=Qj});var fI=v((tfe,dI)=>{var lI=Su(),uI=x0(),Xj=Ns(),Zj=$0(),e7=oI(),t7=sI(),r7=1,n7=2,i7="[object Boolean]",o7="[object Date]",a7="[object Error]",s7="[object Map]",l7="[object Number]",u7="[object RegExp]",c7="[object Set]",d7="[object String]",f7="[object Symbol]",p7="[object ArrayBuffer]",m7="[object DataView]",cI=lI?lI.prototype:void 0,F0=cI?cI.valueOf:void 0;function h7(e,t,r,n,i,o,a){switch(r){case m7:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case p7:return!(e.byteLength!=t.byteLength||!o(new uI(e),new uI(t)));case i7:case o7:case l7:return Xj(+e,+t);case a7:return e.name==t.name&&e.message==t.message;case u7:case d7:return e==t+"";case s7:var s=e7;case c7:var l=n&r7;if(s||(s=t7),e.size!=t.size&&!l)return!1;var u=a.get(e);if(u)return u==t;n|=n7,a.set(e,t);var c=Zj(s(e),s(t),n,i,o,a);return a.delete(e),c;case f7:if(F0)return F0.call(e)==F0.call(t)}return!1}dI.exports=h7});var mI=v((rfe,pI)=>{function g7(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}pI.exports=g7});var vo=v((nfe,hI)=>{var y7=Array.isArray;hI.exports=y7});var yI=v((ife,gI)=>{var b7=mI(),v7=vo();function w7(e,t,r){var n=t(e);return v7(e)?n:b7(n,r(e))}gI.exports=w7});var vI=v((ofe,bI)=>{function C7(e,t){for(var r=-1,n=e==null?0:e.length,i=0,o=[];++r<n;){var a=e[r];t(a,r,e)&&(o[i++]=a)}return o}bI.exports=C7});var CI=v((afe,wI)=>{function E7(){return[]}wI.exports=E7});var SI=v((sfe,AI)=>{var A7=vI(),S7=CI(),N7=Object.prototype,_7=N7.propertyIsEnumerable,EI=Object.getOwnPropertySymbols,T7=EI?function(e){return e==null?[]:(e=Object(e),A7(EI(e),function(t){return _7.call(e,t)}))}:S7;AI.exports=T7});var _I=v((lfe,NI)=>{function D7(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}NI.exports=D7});var wo=v((ufe,TI)=>{function I7(e){return e!=null&&typeof e=="object"}TI.exports=I7});var II=v((cfe,DI)=>{var O7=da(),P7=wo(),R7="[object Arguments]";function k7(e){return P7(e)&&O7(e)==R7}DI.exports=k7});var M0=v((dfe,RI)=>{var OI=II(),L7=wo(),PI=Object.prototype,$7=PI.hasOwnProperty,x7=PI.propertyIsEnumerable,F7=OI((function(){return arguments})())?OI:function(e){return L7(e)&&$7.call(e,"callee")&&!x7.call(e,"callee")};RI.exports=F7});var LI=v((ffe,kI)=>{function M7(){return!1}kI.exports=M7});var yf=v((Du,Os)=>{var U7=In(),B7=LI(),FI=typeof Du=="object"&&Du&&!Du.nodeType&&Du,$I=FI&&typeof Os=="object"&&Os&&!Os.nodeType&&Os,q7=$I&&$I.exports===FI,xI=q7?U7.Buffer:void 0,V7=xI?xI.isBuffer:void 0,G7=V7||B7;Os.exports=G7});var bf=v((pfe,MI)=>{var W7=9007199254740991,z7=/^(?:0|[1-9]\d*)$/;function j7(e,t){var r=typeof e;return t=t??W7,!!t&&(r=="number"||r!="symbol"&&z7.test(e))&&e>-1&&e%1==0&&e<t}MI.exports=j7});var U0=v((mfe,UI)=>{var H7=9007199254740991;function K7(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=H7}UI.exports=K7});var qI=v((hfe,BI)=>{var J7=da(),Y7=U0(),Q7=wo(),X7="[object Arguments]",Z7="[object Array]",eH="[object Boolean]",tH="[object Date]",rH="[object Error]",nH="[object Function]",iH="[object Map]",oH="[object Number]",aH="[object Object]",sH="[object RegExp]",lH="[object Set]",uH="[object String]",cH="[object WeakMap]",dH="[object ArrayBuffer]",fH="[object DataView]",pH="[object Float32Array]",mH="[object Float64Array]",hH="[object Int8Array]",gH="[object Int16Array]",yH="[object Int32Array]",bH="[object Uint8Array]",vH="[object Uint8ClampedArray]",wH="[object Uint16Array]",CH="[object Uint32Array]",$e={};$e[pH]=$e[mH]=$e[hH]=$e[gH]=$e[yH]=$e[bH]=$e[vH]=$e[wH]=$e[CH]=!0;$e[X7]=$e[Z7]=$e[dH]=$e[eH]=$e[fH]=$e[tH]=$e[rH]=$e[nH]=$e[iH]=$e[oH]=$e[aH]=$e[sH]=$e[lH]=$e[uH]=$e[cH]=!1;function EH(e){return Q7(e)&&Y7(e.length)&&!!$e[J7(e)]}BI.exports=EH});var GI=v((gfe,VI)=>{function AH(e){return function(t){return e(t)}}VI.exports=AH});var zI=v((Iu,Ps)=>{var SH=P0(),WI=typeof Iu=="object"&&Iu&&!Iu.nodeType&&Iu,Ou=WI&&typeof Ps=="object"&&Ps&&!Ps.nodeType&&Ps,NH=Ou&&Ou.exports===WI,B0=NH&&SH.process,_H=(function(){try{var e=Ou&&Ou.require&&Ou.require("util").types;return e||B0&&B0.binding&&B0.binding("util")}catch{}})();Ps.exports=_H});var vf=v((yfe,KI)=>{var TH=qI(),DH=GI(),jI=zI(),HI=jI&&jI.isTypedArray,IH=HI?DH(HI):TH;KI.exports=IH});var q0=v((bfe,JI)=>{var OH=_I(),PH=M0(),RH=vo(),kH=yf(),LH=bf(),$H=vf(),xH=Object.prototype,FH=xH.hasOwnProperty;function MH(e,t){var r=RH(e),n=!r&&PH(e),i=!r&&!n&&kH(e),o=!r&&!n&&!i&&$H(e),a=r||n||i||o,s=a?OH(e.length,String):[],l=s.length;for(var u in e)(t||FH.call(e,u))&&!(a&&(u=="length"||i&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||LH(u,l)))&&s.push(u);return s}JI.exports=MH});var wf=v((vfe,YI)=>{var UH=Object.prototype;function BH(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||UH;return e===r}YI.exports=BH});var V0=v((wfe,QI)=>{function qH(e,t){return function(r){return e(t(r))}}QI.exports=qH});var ZI=v((Cfe,XI)=>{var VH=V0(),GH=VH(Object.keys,Object);XI.exports=GH});var tO=v((Efe,eO)=>{var WH=wf(),zH=ZI(),jH=Object.prototype,HH=jH.hasOwnProperty;function KH(e){if(!WH(e))return zH(e);var t=[];for(var r in Object(e))HH.call(e,r)&&r!="constructor"&&t.push(r);return t}eO.exports=KH});var Pu=v((Afe,rO)=>{var JH=pf(),YH=U0();function QH(e){return e!=null&&YH(e.length)&&!JH(e)}rO.exports=QH});var iO=v((Sfe,nO)=>{var XH=q0(),ZH=tO(),eK=Pu();function tK(e){return eK(e)?XH(e):ZH(e)}nO.exports=tK});var aO=v((Nfe,oO)=>{var rK=yI(),nK=SI(),iK=iO();function oK(e){return rK(e,iK,nK)}oO.exports=oK});var uO=v((_fe,lO)=>{var sO=aO(),aK=1,sK=Object.prototype,lK=sK.hasOwnProperty;function uK(e,t,r,n,i,o){var a=r&aK,s=sO(e),l=s.length,u=sO(t),c=u.length;if(l!=c&&!a)return!1;for(var d=l;d--;){var f=s[d];if(!(a?f in t:lK.call(t,f)))return!1}var m=o.get(e),p=o.get(t);if(m&&p)return m==t&&p==e;var h=!0;o.set(e,t),o.set(t,e);for(var g=a;++d<l;){f=s[d];var b=e[f],w=t[f];if(n)var C=a?n(w,b,f,t,e,o):n(b,w,f,e,t,o);if(!(C===void 0?b===w||i(b,w,r,n,o):C)){h=!1;break}g||(g=f=="constructor")}if(h&&!g){var S=e.constructor,O=t.constructor;S!=O&&"constructor"in e&&"constructor"in t&&!(typeof S=="function"&&S instanceof S&&typeof O=="function"&&O instanceof O)&&(h=!1)}return o.delete(e),o.delete(t),h}lO.exports=uK});var dO=v((Tfe,cO)=>{var cK=bo(),dK=In(),fK=cK(dK,"DataView");cO.exports=fK});var pO=v((Dfe,fO)=>{var pK=bo(),mK=In(),hK=pK(mK,"Promise");fO.exports=hK});var hO=v((Ife,mO)=>{var gK=bo(),yK=In(),bK=gK(yK,"Set");mO.exports=bK});var yO=v((Ofe,gO)=>{var vK=bo(),wK=In(),CK=vK(wK,"WeakMap");gO.exports=CK});var NO=v((Pfe,SO)=>{var G0=dO(),W0=mf(),z0=pO(),j0=hO(),H0=yO(),AO=da(),Rs=k0(),bO="[object Map]",EK="[object Object]",vO="[object Promise]",wO="[object Set]",CO="[object WeakMap]",EO="[object DataView]",AK=Rs(G0),SK=Rs(W0),NK=Rs(z0),_K=Rs(j0),TK=Rs(H0),fa=AO;(G0&&fa(new G0(new ArrayBuffer(1)))!=EO||W0&&fa(new W0)!=bO||z0&&fa(z0.resolve())!=vO||j0&&fa(new j0)!=wO||H0&&fa(new H0)!=CO)&&(fa=function(e){var t=AO(e),r=t==EK?e.constructor:void 0,n=r?Rs(r):"";if(n)switch(n){case AK:return EO;case SK:return bO;case NK:return vO;case _K:return wO;case TK:return CO}return t});SO.exports=fa});var kO=v((Rfe,RO)=>{var K0=L0(),DK=$0(),IK=fI(),OK=uO(),_O=NO(),TO=vo(),DO=yf(),PK=vf(),RK=1,IO="[object Arguments]",OO="[object Array]",Cf="[object Object]",kK=Object.prototype,PO=kK.hasOwnProperty;function LK(e,t,r,n,i,o){var a=TO(e),s=TO(t),l=a?OO:_O(e),u=s?OO:_O(t);l=l==IO?Cf:l,u=u==IO?Cf:u;var c=l==Cf,d=u==Cf,f=l==u;if(f&&DO(e)){if(!DO(t))return!1;a=!0,c=!1}if(f&&!c)return o||(o=new K0),a||PK(e)?DK(e,t,r,n,i,o):IK(e,t,l,r,n,i,o);if(!(r&RK)){var m=c&&PO.call(e,"__wrapped__"),p=d&&PO.call(t,"__wrapped__");if(m||p){var h=m?e.value():e,g=p?t.value():t;return o||(o=new K0),i(h,g,r,n,o)}}return f?(o||(o=new K0),OK(e,t,r,n,i,o)):!1}RO.exports=LK});var FO=v((kfe,xO)=>{var $K=kO(),LO=wo();function $O(e,t,r,n,i){return e===t?!0:e==null||t==null||!LO(e)&&!LO(t)?e!==e&&t!==t:$K(e,t,r,n,$O,i)}xO.exports=$O});var UO=v((Lfe,MO)=>{var xK=FO();function FK(e,t){return xK(e,t)}MO.exports=FK});var J0=v(($fe,BO)=>{var MK=bo(),UK=(function(){try{var e=MK(Object,"defineProperty");return e({},"",{}),e}catch{}})();BO.exports=UK});var Ef=v((xfe,VO)=>{var qO=J0();function BK(e,t,r){t=="__proto__"&&qO?qO(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}VO.exports=BK});var Y0=v((Ffe,GO)=>{var qK=Ef(),VK=Ns();function GK(e,t,r){(r!==void 0&&!VK(e[t],r)||r===void 0&&!(t in e))&&qK(e,t,r)}GO.exports=GK});var zO=v((Mfe,WO)=>{function WK(e){return function(t,r,n){for(var i=-1,o=Object(t),a=n(t),s=a.length;s--;){var l=a[e?s:++i];if(r(o[l],l,o)===!1)break}return t}}WO.exports=WK});var HO=v((Ufe,jO)=>{var zK=zO(),jK=zK();jO.exports=jK});var XO=v((Ru,ks)=>{var HK=In(),QO=typeof Ru=="object"&&Ru&&!Ru.nodeType&&Ru,KO=QO&&typeof ks=="object"&&ks&&!ks.nodeType&&ks,KK=KO&&KO.exports===QO,JO=KK?HK.Buffer:void 0,YO=JO?JO.allocUnsafe:void 0;function JK(e,t){if(t)return e.slice();var r=e.length,n=YO?YO(r):new e.constructor(r);return e.copy(n),n}ks.exports=JK});var tP=v((Bfe,eP)=>{var ZO=x0();function YK(e){var t=new e.constructor(e.byteLength);return new ZO(t).set(new ZO(e)),t}eP.exports=YK});var nP=v((qfe,rP)=>{var QK=tP();function XK(e,t){var r=t?QK(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}rP.exports=XK});var oP=v((Vfe,iP)=>{function ZK(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}iP.exports=ZK});var lP=v((Gfe,sP)=>{var eJ=$i(),aP=Object.create,tJ=(function(){function e(){}return function(t){if(!eJ(t))return{};if(aP)return aP(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();sP.exports=tJ});var Q0=v((Wfe,uP)=>{var rJ=V0(),nJ=rJ(Object.getPrototypeOf,Object);uP.exports=nJ});var dP=v((zfe,cP)=>{var iJ=lP(),oJ=Q0(),aJ=wf();function sJ(e){return typeof e.constructor=="function"&&!aJ(e)?iJ(oJ(e)):{}}cP.exports=sJ});var pP=v((jfe,fP)=>{var lJ=Pu(),uJ=wo();function cJ(e){return uJ(e)&&lJ(e)}fP.exports=cJ});var gP=v((Hfe,hP)=>{var dJ=da(),fJ=Q0(),pJ=wo(),mJ="[object Object]",hJ=Function.prototype,gJ=Object.prototype,mP=hJ.toString,yJ=gJ.hasOwnProperty,bJ=mP.call(Object);function vJ(e){if(!pJ(e)||dJ(e)!=mJ)return!1;var t=fJ(e);if(t===null)return!0;var r=yJ.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&mP.call(r)==bJ}hP.exports=vJ});var X0=v((Kfe,yP)=>{function wJ(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}yP.exports=wJ});var Z0=v((Jfe,bP)=>{var CJ=Ef(),EJ=Ns(),AJ=Object.prototype,SJ=AJ.hasOwnProperty;function NJ(e,t,r){var n=e[t];(!(SJ.call(e,t)&&EJ(n,r))||r===void 0&&!(t in e))&&CJ(e,t,r)}bP.exports=NJ});var wP=v((Yfe,vP)=>{var _J=Z0(),TJ=Ef();function DJ(e,t,r,n){var i=!r;r||(r={});for(var o=-1,a=t.length;++o<a;){var s=t[o],l=n?n(r[s],e[s],s,r,e):void 0;l===void 0&&(l=e[s]),i?TJ(r,s,l):_J(r,s,l)}return r}vP.exports=DJ});var EP=v((Qfe,CP)=>{function IJ(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}CP.exports=IJ});var SP=v((Xfe,AP)=>{var OJ=$i(),PJ=wf(),RJ=EP(),kJ=Object.prototype,LJ=kJ.hasOwnProperty;function $J(e){if(!OJ(e))return RJ(e);var t=PJ(e),r=[];for(var n in e)n=="constructor"&&(t||!LJ.call(e,n))||r.push(n);return r}AP.exports=$J});var ey=v((Zfe,NP)=>{var xJ=q0(),FJ=SP(),MJ=Pu();function UJ(e){return MJ(e)?xJ(e,!0):FJ(e)}NP.exports=UJ});var TP=v((epe,_P)=>{var BJ=wP(),qJ=ey();function VJ(e){return BJ(e,qJ(e))}_P.exports=VJ});var kP=v((tpe,RP)=>{var DP=Y0(),GJ=XO(),WJ=nP(),zJ=oP(),jJ=dP(),IP=M0(),OP=vo(),HJ=pP(),KJ=yf(),JJ=pf(),YJ=$i(),QJ=gP(),XJ=vf(),PP=X0(),ZJ=TP();function eY(e,t,r,n,i,o,a){var s=PP(e,r),l=PP(t,r),u=a.get(l);if(u){DP(e,r,u);return}var c=o?o(s,l,r+"",e,t,a):void 0,d=c===void 0;if(d){var f=OP(l),m=!f&&KJ(l),p=!f&&!m&&XJ(l);c=l,f||m||p?OP(s)?c=s:HJ(s)?c=zJ(s):m?(d=!1,c=GJ(l,!0)):p?(d=!1,c=WJ(l,!0)):c=[]:QJ(l)||IP(l)?(c=s,IP(s)?c=ZJ(s):(!YJ(s)||JJ(s))&&(c=jJ(l))):d=!1}d&&(a.set(l,c),i(c,l,n,o,a),a.delete(l)),DP(e,r,c)}RP.exports=eY});var ty=v((rpe,$P)=>{var tY=L0(),rY=Y0(),nY=HO(),iY=kP(),oY=$i(),aY=ey(),sY=X0();function LP(e,t,r,n,i){e!==t&&nY(t,function(o,a){if(i||(i=new tY),oY(o))iY(e,t,a,r,LP,n,i);else{var s=n?n(sY(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),rY(e,a,s)}},aY)}$P.exports=LP});var ry=v((npe,xP)=>{function lY(e){return e}xP.exports=lY});var MP=v((ipe,FP)=>{function uY(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)}FP.exports=uY});var qP=v((ope,BP)=>{var cY=MP(),UP=Math.max;function dY(e,t,r){return t=UP(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,o=UP(n.length-t,0),a=Array(o);++i<o;)a[i]=n[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=n[i];return s[t]=r(a),cY(e,this,s)}}BP.exports=dY});var GP=v((ape,VP)=>{function fY(e){return function(){return e}}VP.exports=fY});var jP=v((spe,zP)=>{var pY=GP(),WP=J0(),mY=ry(),hY=WP?function(e,t){return WP(e,"toString",{configurable:!0,enumerable:!1,value:pY(t),writable:!0})}:mY;zP.exports=hY});var KP=v((lpe,HP)=>{var gY=800,yY=16,bY=Date.now;function vY(e){var t=0,r=0;return function(){var n=bY(),i=yY-(n-r);if(r=n,i>0){if(++t>=gY)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}HP.exports=vY});var YP=v((upe,JP)=>{var wY=jP(),CY=KP(),EY=CY(wY);JP.exports=EY});var XP=v((cpe,QP)=>{var AY=ry(),SY=qP(),NY=YP();function _Y(e,t){return NY(SY(e,t,AY),e+"")}QP.exports=_Y});var eR=v((dpe,ZP)=>{var TY=Ns(),DY=Pu(),IY=bf(),OY=$i();function PY(e,t,r){if(!OY(r))return!1;var n=typeof t;return(n=="number"?DY(r)&&IY(t,r.length):n=="string"&&t in r)?TY(r[t],e):!1}ZP.exports=PY});var ny=v((fpe,tR)=>{var RY=XP(),kY=eR();function LY(e){return RY(function(t,r){var n=-1,i=r.length,o=i>1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(o=e.length>3&&typeof o=="function"?(i--,o):void 0,a&&kY(r[0],r[1],a)&&(o=i<3?void 0:o,i=1),t=Object(t);++n<i;){var s=r[n];s&&e(t,s,n,o)}return t})}tR.exports=LY});var nR=v((ppe,rR)=>{var $Y=ty(),xY=ny(),FY=xY(function(e,t,r,n){$Y(e,t,r,n)});rR.exports=FY});var un,ku=L(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(un||(un={}))});function oR(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${iR.EcsConfigType[i]}_${r}`;return{getData:i=>{let o=t.getItem(n(i));return Promise.resolve(o?JSON.parse(o):void 0)},putData:(i,o)=>(t.setItem(n(i),JSON.stringify(o)),Promise.resolve())}}var iR,MY,aR=L(()=>{"use strict";iR=Ae(O0()),MY=Ae(I0());});var iy,sR=L(()=>{"use strict";of();iy=hu({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 uR,cR,dR,fR,oy,UY,Af,lR,ay=L(()=>{"use strict";uR=Ae(I0()),cR=Ae(bT()),dR=Ae(O0()),fR=Ae(UO()),oy=Ae(nR());ku();aR();sR();UY=60*1e3,Af=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=un.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"?iy.prodEcsEndpoint:iy.integrationEcsEndpoint}client=new cR.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=uR.StorageHelper.transientWithGlobalFallback,updateIntervalInMinutes:i,overrideEcsInitParams:o})=>{this.client.telemetryEventAdded.subscribe(this.logger.logEvent),this.client.configUpdated.subscribe(this.handleConfigUpdated);let a=(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:[dR.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:oR(this.clientName,n,this.endpointType),...o}),this.client.requestUpdate(),this._status===un.NotLoaded&&(this._status=un.Initialized)}catch(s){this._status=un.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*UY)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,oy.default)({},t.fallback,n,t.override,lR)};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 o=this.getConfig(t);(0,fR.default)(o,n)||(n={...o},r(o))});return{unsubscribe:()=>i.unsubscribe()}};waitUntilLoaded=async t=>{if(t!==void 0){let r,n=new Promise((i,o)=>{r=window.setTimeout(()=>{o(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,oy.default)({},this.client.getConfig()?.config,this.clientConfigOverride,lR);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=un.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})}},lR=(e,t)=>{if(Array.isArray(t))return t}});var mR=v((Epe,pR)=>{"use strict";var BY=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};pR.exports=BY});var sy=v((Ape,gR)=>{var Lu=new Proxy(function(){return Lu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Lu},apply:function(){return Lu},construct:function(){return{}}}),hR=function(){return Lu};Object.setPrototypeOf(hR,Lu);gR.exports=hR});var vR=v((Spe,bR)=>{var $u=new Proxy(function(){return $u},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:$u},apply:function(){return $u},construct:function(){return{}}}),yR=function(){return $u};Object.setPrototypeOf(yR,$u);bR.exports=yR});var _R=v((Npe,NR)=>{"use strict";var ly=vR(),qY={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},VY={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},GY={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},AR={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},uy={};uy[ly.ForwardRef]=GY;uy[ly.Memo]=AR;function wR(e){return ly.isMemo(e)?AR:uy[e.$$typeof]||qY}var WY=Object.defineProperty,zY=Object.getOwnPropertyNames,CR=Object.getOwnPropertySymbols,jY=Object.getOwnPropertyDescriptor,HY=Object.getPrototypeOf,ER=Object.prototype;function SR(e,t,r){if(typeof t!="string"){if(ER){var n=HY(t);n&&n!==ER&&SR(e,n,r)}var i=zY(t);CR&&(i=i.concat(CR(t)));for(var o=wR(e),a=wR(t),s=0;s<i.length;++s){var l=i[s];if(!VY[l]&&!(r&&r[l])&&!(a&&a[l])&&!(o&&o[l])){var u=jY(t,l);try{WY(e,l,u)}catch{}}}}return e}NR.exports=SR});function DR(e,t,r){let[n,i]=(0,Ls.useState)(e.getConfig(t));return(0,Ls.useEffect)(()=>{if(!r?.subscribe&&e.status===un.ConfigsLoaded)return;let o=e.subscribe(t,a=>{i(a),r?.subscribe||o.unsubscribe()});return o?.unsubscribe},[]),n}function IR(e){return function(t,r){return DR(e,t,r)}}function OR(e,t,r,n){let i=o=>{let a=DR(e,t,n),s={...o,...a};return Ls.default.createElement(r,{...s})};return(0,TR.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function PR(e,t,r,n){return t.reduce((i,o)=>OR(e,o,i,n),r)}function RR(e){return function(t,r,n){return OR(e,t,r,n)}}var TR,Ls,cy=L(()=>{"use strict";TR=Ae(_R()),Ls=Ae(sy());ku();});var LR=v((Dpe,kR)=>{var KY=ty(),JY=ny(),YY=JY(function(e,t,r){KY(e,t,r)});kR.exports=YY});var Sf=v((Ipe,$R)=>{var QY=da(),XY=wo(),ZY="[object Symbol]";function eQ(e){return typeof e=="symbol"||XY(e)&&QY(e)==ZY}$R.exports=eQ});var FR=v((Ope,xR)=>{var tQ=vo(),rQ=Sf(),nQ=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,iQ=/^\w*$/;function oQ(e,t){if(tQ(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||rQ(e)?!0:iQ.test(e)||!nQ.test(e)||t!=null&&e in Object(t)}xR.exports=oQ});var BR=v((Ppe,UR)=>{var MR=hf(),aQ="Expected a function";function dy(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(aQ);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],o=r.cache;if(o.has(i))return o.get(i);var a=e.apply(this,n);return r.cache=o.set(i,a)||o,a};return r.cache=new(dy.Cache||MR),r}dy.Cache=MR;UR.exports=dy});var VR=v((Rpe,qR)=>{var sQ=BR(),lQ=500;function uQ(e){var t=sQ(e,function(n){return r.size===lQ&&r.clear(),n}),r=t.cache;return t}qR.exports=uQ});var WR=v((kpe,GR)=>{var cQ=VR(),dQ=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,fQ=/\\(\\)?/g,pQ=cQ(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(dQ,function(r,n,i,o){t.push(i?o.replace(fQ,"$1"):n||r)}),t});GR.exports=pQ});var jR=v((Lpe,zR)=>{function mQ(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}zR.exports=mQ});var XR=v(($pe,QR)=>{var HR=Su(),hQ=jR(),gQ=vo(),yQ=Sf(),bQ=1/0,KR=HR?HR.prototype:void 0,JR=KR?KR.toString:void 0;function YR(e){if(typeof e=="string")return e;if(gQ(e))return hQ(e,YR)+"";if(yQ(e))return JR?JR.call(e):"";var t=e+"";return t=="0"&&1/e==-bQ?"-0":t}QR.exports=YR});var e2=v((xpe,ZR)=>{var vQ=XR();function wQ(e){return e==null?"":vQ(e)}ZR.exports=wQ});var r2=v((Fpe,t2)=>{var CQ=vo(),EQ=FR(),AQ=WR(),SQ=e2();function NQ(e,t){return CQ(e)?e:EQ(e,t)?[e]:AQ(SQ(e))}t2.exports=NQ});var i2=v((Mpe,n2)=>{var _Q=Sf(),TQ=1/0;function DQ(e){if(typeof e=="string"||_Q(e))return e;var t=e+"";return t=="0"&&1/e==-TQ?"-0":t}n2.exports=DQ});var s2=v((Upe,a2)=>{var IQ=Z0(),OQ=r2(),PQ=bf(),o2=$i(),RQ=i2();function kQ(e,t,r,n){if(!o2(e))return e;t=OQ(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var l=RQ(t[i]),u=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(i!=a){var c=s[l];u=n?n(c,l,s):void 0,u===void 0&&(u=o2(c)?c:PQ(t[i+1])?[]:{})}IQ(s,l,u),s=s[l]}return e}a2.exports=kQ});var u2=v((Bpe,l2)=>{var LQ=s2();function $Q(e,t,r){return e==null?e:LQ(e,t,r)}l2.exports=$Q});function p2(e){let{query:t}=(0,f2.default)(window.location.href,!0);return FQ(e,t),e}function FQ(e,t){let r=xQ+e.clientName,n=Object.keys(t).filter(o=>o.startsWith(r));if(!n)return;let i={};n.forEach(o=>{let a=t[o];if(a)try{let s=JSON.parse(a),l=r+m2,u={};if(o===r)u=s;else if(o.startsWith(l)){let c=o.substring(l.length);(0,d2.default)(u,c,s)}(0,c2.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var c2,d2,f2,m2,xQ,h2=L(()=>{"use strict";c2=Ae(LR()),d2=Ae(u2()),f2=Ae(y0());m2=".",xQ="ecs"+m2});function _f(e,t,r){let n=p2(new Af(e,t,r));function i(o){(0,Nf.useEffect)(()=>{n.init(o)},[])}return{featuresClient:n,createFeature:UQ(n),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>PR(n,o,a,s)}}function UQ(e){let t=IR(e),r=RR(e);return function(i){let o=pT(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===un.ConfigsLoaded,w0.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>r(o,a,s),feature:o}}}var MQ,Nf,fy=L(()=>{"use strict";MQ=Ae(mR()),Nf=Ae(sy());D0();ay();ku();cy();h2();C0();});var g2=L(()=>{"use strict";D0();ay();fy();ku();cy();uf();E0();});function Tf(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,$s.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,$s.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,$s.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var $s,py=L(()=>{"use strict";$s=Ae(aa());});var ame,sme,lme,y2=L(()=>{"use strict";g2();py();({featuresClient:ame,createFeature:sme,useFeaturesClientInitParams:lme}=_f("PowerApps-Shell-Test",Tf("shell-features")))});var w2=v((cme,v2)=>{var xu=new Proxy(function(){return xu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:xu},apply:function(){return xu},construct:function(){return{}}}),b2=function(){return xu};Object.setPrototypeOf(b2,xu);v2.exports=b2});var BQ,qQ,C2=L(()=>{"use strict";fu();BQ=Ae(w2()),qQ=Ae(aa());});var E2=L(()=>{"use strict";y2();py();C2();});var vme,xs,wme,A2=L(()=>{"use strict";E2();fy();({featuresClient:vme,createFeature:xs,useFeaturesClientInitParams:wme}=_f("PowerApps-MakerPortal",Tf("powerapps-features")))});var S2,N2,Sme,Nme,_me,Tme,my=L(()=>{"use strict";fT();A2();({feature:S2}=xs({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:Ss.enableAutoInsertionOfCellInRow}})),{feature:N2}=xs({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:Ss.enableOneGridEvents}}),{feature:Sme}=xs({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:Ss.disablePBIComponents}}),{feature:Nme}=xs({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:Ss.enableAgentResponse}}),{feature:_me,useFeature:Tme}=xs({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:Ss.enableDelayedLocalizationForCustomControls}})});var D2=v((Ime,T2)=>{var Fu=new Proxy(function(){return Fu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Fu},apply:function(){return Fu},construct:function(){return{}}}),_2=function(){return Fu};Object.setPrototypeOf(_2,Fu);T2.exports=_2});var Zt,Co=L(()=>{"use strict";ht();st();Xt();bu();ue();It();Zt=class extends re{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(y.colspan);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){R.IsNullOrUndefined(t)||this.setProperty(y.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(y.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}set id(t){this.setProperty(y.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(y.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(y.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}get Name(){return this.getProperty(y.Name)}set Name(t){this.setProperty(y.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(y.languagecode)===r){i.setProperty(y.description,t);return}let n=new re(E.formLabel,null);n.setProperty(y.description,t),n.setProperty(y.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(y.languagecode)===t)return r.getProperty(y.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(y.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(y.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(y.availableforphone)}set availableforphone(t){R.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(y.availableforphone,String(t))}get visible(){return this.getProcessedValue(y.visible)}set visible(t){R.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(y.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(y.showlabel)}set showlabel(t){R.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return R.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(E.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(E.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.DefaultViewId):q.EmptyString}set defaultviewid(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.DependentAttributeName):q.EmptyString}set dependentattributename(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.DependentAttributeType):q.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.FilterRelationshipName):q.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.AvailableViewIds):q.EmptyString}set availableviewids(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(E.formControl);if(t&&t.ClassId){let r=lt.getUniqueIdentifierForControl(t);return!R.IsNullOrUndefined(r)&&lt.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(E.formControl);if(t){let n=lt.getUniqueIdentifierForControl(t).guidString,i=n===G.GridControl||n===G.TimeLineControl||n===G.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===E.formSection||this.NodeName===E.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(E.formControl);if(t){let n=lt.getUniqueIdentifierForControl(t).guidString,i=n===G.MapsControl||n===G.WebResourceHtmlControl||n===G.WebResourceImageControl||n===G.IframeControl||n===G.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(E.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(E.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var Fs,hy=L(()=>{"use strict";Xt();ue();It();Fs=class extends re{constructor(t,r){super(E.dependency,t),q.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}setDefaultProperties(t){this.id=t}}});var I2,Ms,gy=L(()=>{"use strict";st();hy();ue();It();Co();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(I2||(I2={}));Ms=class extends Zt{constructor(t,r){super(E.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(y.Name,t)}get eventName(){return this.getProperty(y.Name)}set application(t){this.setProperty(y.application,t)}get application(){return this.getProperty(y.application)}set attribute(t){this.setProperty(y.EventAttribute,t)}get attribute(){return this.getProperty(y.EventAttribute)}set relationship(t){this.setProperty(y.Relationship,t)}get relationship(){return this.getProperty(y.Relationship)}set control(t){this.setProperty(y.Control,t)}get control(){return this.getProperty(y.Control)}set active(t){this.setProperty(y.EventActive,t)}get active(){return this.getProperty(y.EventActive)}getAllHandlers(){let t=this.getChildren(E.EventHandlers);return t&&t.length?t[0].getChildren(E.handler):[]}getAllDependencies(){let t=this.getChildren(E.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(E.formDependencies);if(R.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new re(E.formDependencies,this)),r=this.getFirstChild(E.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new Fs(r,n.toString()))}}}});var On,Mu=L(()=>{"use strict";ht();Wl();st();oa();ue();It();Tn();On=class extends re{previewVersion;constructor(t){super(E.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(y.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t)}set ClassId(t){this.setProperty(y.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(y.datafieldname)}set dataFieldName(t){this.setProperty(y.datafieldname,t)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}get UniqueId(){let t=this.getProperty(y.uniqueid);return R.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set UniqueId(t){this.setProperty(y.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(y.isRequired)==="true"}set isRequired(t){R.IsNullOrUndefined(t)||this.setProperty(y.isRequired,String(t))}get disableMru(){return this.getParam(y.DisableMru)==="true"}set disableMru(t){R.IsNullOrUndefined(t)||this.setParameter(y.DisableMru,t)}get useMFDForCreate(){return this.getParam(y.UseMFDForCreate)==="true"}set useMFDForCreate(t){R.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(y.UseMFDForEdit)==="true"}set useMFDForEdit(t){R.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForEdit,t)}get disabled(){return this.getProperty(y.disabled)==="true"}set disabled(t){R.IsNullOrUndefined(t)||this.setProperty(y.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(y.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(y.indicationOfSubgrid,String(t))}getAllParameters(){let t=new ar,r=this.getFirstChild(y.parameters);return r&&r.getAllChildren().forEach(n=>{if(n){let i=n.getAllChildren(),o=i&&i.length>0&&i[0];o&&t.add(n.getNodeName(),o.getNodeName())}}),t}setParameter(t,r){let n=!1;r===null&&(n=!0);let i=(Li.StartTag+r).toString(),o=this.parametersNode;if(o){let a=o.findFirst(s=>s&&s.getNodeName()===t);if(a)if(n){this.deleteFirstGrandChildOfName(E.controlParameters,a);return}else{let s=a.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):a.addChild(new re(i,a))}else n||(a=new re(t,o),a.addChild(new re(i,a)),o.addChild(a))}else if(!n){o=new re("parameters",this);let a=new re(t,o);a.addChild(new re(i,a)),o.addChild(a),this.addChild(o)}}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 o=i.getNodeName();return o.charAt(0)===Li.StartTag?o.substring(1):o}}}return null}get parametersNode(){let t=this.getChildren(y.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new ar;switch(this.ClassId.guidString.toUpperCase()){case N.LookupControl:if(t&&t.getKeys())if(t.getKeys().forEach(a=>{n.add(a,this.getParam(a))}),t&&t.containsKey("DefaultViewId")){let a=this.getParam("DefaultViewId").replace("{","").replace("}","");n.upsert("DefaultViewId",a)}else{let a=this.getParent(),s=await r.formModelService.lookupControlService.populateDefaultView(this,a.getParentForm().entityName);s&&s.id&&n.upsert("DefaultViewId",s.id.replace("{","").replace("}",""))}break;default:t&&t.getKeys()&&t.getKeys().forEach(a=>{n.add(a,this.getParam(a))});break}let i=n.getInternalObject(),o=[];for(let a in i)i.hasOwnProperty(a)&&o.push({Name:a,Value:i[a]});return o}getIsUnbound(){return this.getProperty(y.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case N.BooleanControl:case N.CheckboxControl:return 0;case N.DateTimeControl:return 2;case N.DecimalControl:return 3;case N.FloatingNumberControl:return 4;case N.IntegerControl:case N.DurationControl:case N.LanguageControl:case N.TimezoneControl:return 5;case N.LookupControl:return 6;case N.CurrencyControl:return 8;case N.PartyListControl:return 10;case N.ChoiceControl:case N.RelationshipRoleChoiceControl:return 11;case N.ChoiceStatusControl:return 13;case N.TextAreaControl:case N.TextboxControl:case N.LabelControl:case N.EmailAddressControl:case N.UrlControl:case N.TickerControl:case N.ButtonControl:case N.PhoneNumberControl:return 14;case N.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===gt.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 Us,yy=L(()=>{"use strict";Xt();Ho();Mu();ue();It();Us=class extends On{constructor(t){super(t)}get targetEntityType(){return this.getParam(y.targetEntityType)||q.EmptyString}set targetEntityType(t){this.setParameter(y.targetEntityType,t)}get viewId(){return q.StripBraces(this.getParam(y.viewId))||q.EmptyString}set viewId(t){this.setParameter(y.viewId,q.AddBraces(t))}get viewIds(){return this.getParam(y.viewIds)||q.EmptyString}set viewIds(t){this.setParameter(y.viewIds,t)}get relationshipName(){return this.getParam(y.RelationshipName)||q.EmptyString}set relationshipName(t){this.setParameter(y.RelationshipName,t)}get isUserView(){return q.IsStrictTrue(this.getParam(y.isUserView))}set isUserView(t){this.setParameter(y.isUserView,t.toString())}get enableViewPicker(){return q.IsStrictTrue(this.getParam(y.enableViewPicker))}set enableViewPicker(t){this.setParameter(y.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(y.autoExpand)===y.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(y.autoExpand,t?y.Auto:y.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(y.recordsPerPage)?Number(this.getParam(y.recordsPerPage)):Number(y.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(y.recordsPerPage,String(t))}get enableQuickFind(){return q.IsStrictTrue(this.getParam(y.enableQuickFind))}set enableQuickFind(t){this.setParameter(y.enableQuickFind,t)}get teamTemplateId(){return q.StripBraces(this.getParam(y.teamTemplateId))||q.EmptyString}set teamTemplateId(t){this.setParameter(y.teamTemplateId,q.AddBraces(t))}get chartId(){return this.getParam(y.visualizationId)||q.EmptyString}set chartId(t){this.setParameter(y.visualizationId,t)}get enableChartPicker(){return q.IsStrictTrue(this.getParam(y.enableChartPicker))}set enableChartPicker(t){this.setParameter(y.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(y.chartGridMode)){case ln.Chart:return ln.Chart;case ln.Grid:return ln.Grid;default:return ln.All}}set chartGridMode(t){this.setParameter(y.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=ln.Chart:this.chartGridMode=this.enableChartPicker?ln.All:ln.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case y.viewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.viewId));break;case y.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case y.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case y.RelationshipName:let i=n.getAllChildren(),o="<"+r.relationshipName;i.length?n.getAllChildren()[0].setNodeName(o):n.addChild(new re(o,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 o=n[i].getParameters().get(Ht.dataset)?n[i].getParameters().get(Ht.dataset)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var Bs,by=L(()=>{"use strict";Xt();Ho();Mu();ue();Bs=class extends On{constructor(t){super(t)}get defaultViewId(){return q.StripBraces(this.getParam(y.DefaultViewId))||q.EmptyString}set defaultViewId(t){this.setParameter(y.DefaultViewId,q.AddBraces(t))}get autoResolve(){return q.IsStrictTrue(this.getParam(y.AutoResolve))}set autoResolve(t){this.setParameter(y.AutoResolve,t)}get disableQuickFind(){return q.IsStrictTrue(this.getParam(y.DisableQuickFind))}set disableQuickFind(t){this.setParameter(y.DisableQuickFind,t)}get disableViewPicker(){return q.IsStrictTrue(this.getParam(y.DisableViewPicker))}set disableViewPicker(t){this.setParameter(y.DisableViewPicker,t)}get allowFilterOff(){return q.IsStrictTrue(this.getParam(y.AllowFilterOff))}set allowFilterOff(t){this.setParameter(y.AllowFilterOff,t)}get disableMru(){return q.IsStrictTrue(this.getParam(y.DisableMru))}set disableMru(t){this.setParameter(y.DisableMru,t)}get dependentAttributeName(){return this.getParam(y.DependentAttributeName)||q.EmptyString}set dependentAttributeName(t){this.setParameter(y.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(y.DependentAttributeType)||q.EmptyString}set dependentAttributeType(t){this.setParameter(y.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(y.FilterRelationshipName)||q.EmptyString}set filterRelationshipName(t){this.setParameter(y.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(y.AvailableViewIds)||q.EmptyString}set availableViewIds(t){this.setParameter(y.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.datafieldname:case y.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case y.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.defaultViewId));break;case y.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case y.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case y.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case y.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case y.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case y.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case y.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case y.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case y.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 o=n[i].getParameters().get(Ht.value)?n[i].getParameters().get(Ht.value)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var O2,vy,Ir,Uu=L(()=>{"use strict";O2=Ae(D2());Co();ue();st();ht();gy();Mu();bu();_0();s0();Tn();oa();ws();yy();by();wy();os();vy="_",Ir=class e extends Zt{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(E.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,R.IsNullOrUndefined(this.getProperty(y.id))&&(this.id=new U(U.NewGuid()))}addControl(t,r,n,i,o,a,s){n instanceof On?this.addChild(n):n instanceof U&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,o,a,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!R.IsNullOrUndefined(this.control))return R.IsNullOrUndefined(this.control.dataFieldName)?R.IsNullOrUndefined(this.control.id)?!0:!sa.dependencyFieldCount.containsKey(this.control.id):!sa.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new Ms(this,cu.onLoad))}get dependencies(){let t=this.getChildren(E.formEvents);for(let r of t){let n=r.getChildren(E.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let o;if(i&&Zd[i])o=Zd[i].replace(/ /g,vy)+vy;else{o="Control_";let u=new Error("Control class id does not exist or is undefined");(0,O2.trackErrorTrace)(cr,{eventName:`${D_}/getNextAvailableControlName`},u)}let a="new_",s=this.getHighestIndexById(t,i)+1,l=`${o}${a}${s}`;for(;n.has(l);)s++,l=`${o}${a}${s}`;return l}getUnboundControlProperties(t){e.prototype.setProperty.call(t,y.isUnbound,"true"),e.prototype.setProperty.call(t,y.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,o,a,s){let l;o===cn.Grid?(l=new Us(this),l.indicationOfSubgrid=!0):o===cn.Lookup?l=new Bs(this):l=new On(this);let u=n.guidString,c=a||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,y.id,c),l.ClassId=n,!R.IsNullOrUndefined(s)&&(l.UniqueId=s),!a&&r)this.getUnboundControlProperties(l);else{let d=lt.getUniqueIdentifierForControl(l);R.IsNullOrUndefined(d)||(lt.getControlDataTypeByControlOrUniqueId(d)===ee.QuickFormCollectionControl||!lt.isUnboundFormControlByIdentifier(d)?o!==cn.Grid&&a&&u!==N.IframeControl&&u!==N.SubgridControl&&u!==N.ReferencePanelSubgridControl&&(l.dataFieldName=a,e.prototype.setProperty.call(l,y.disabled,"false")):(this.rowspan=lt.GetRowSpan(l),(lt.getControlDataTypeByControlOrUniqueId(d)===ee.NotesControl||lt.getControlDataTypeByControlOrUniqueId(d)===ee.TimeLineControl)&&(e.prototype.setProperty.call(l,y.disabled,"false"),l.id=ee.NotesControl)),(lt.getUnboundControlNameFromIdentifier(n)===ee.SubGridControl||lt.getUnboundControlNameFromIdentifier(n)===ee.NotesControl||lt.getUnboundControlNameFromIdentifier(n)===ee.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(R.IsNullOrUndefined(t))return;let n=t.getAllChildren();for(let i of n){let o=i.getAllChildren();for(let a of o){let s=a.GetPropertyByParameter(y.id);a.getNodeName()===E.dependency&&s?r.push(s):this.buildDependencyList(a,r)}}}get control(){return this.getFirstChild(E.formControl)}set rowspan(t){this.setProperty(y.rowspan,String(t))}get rowspan(){let t=this.getProperty(y.rowspan);return R.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(y.auto,String(t))}get autoexpand(){return this.getProperty(y.auto)==="true"}set colspan(t){let r=Number(S0.ONE_COLUMN),n=Number(S0.FOUR_COLUMN);R.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(y.colspan,String(t))}get colspan(){let t=this.getProperty(y.colspan);return R.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(E.formRow)}getParentSection(){return this.getAncestor(E.formSection)}getParentTab(){return this.getAncestor(E.formTab)}getParentForm(){return this.getAncestor(E.form)}isInHeader(){let t=this.getAncestor(E.formHeader);return!R.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(E.formFooter);return!R.IsNullOrUndefined(t)}isEmpty(){return R.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(E.formHeader):this.isInFooter()?this.getAncestor(E.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(y.userspacer);return R.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(y.userspacer,"true")}ClearUserSpacer(){this.setProperty(y.userspacer,"false")}get columns(){let t=this.getProperty(y.columnName);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case je.TWO_COLUMN:r="11";break;case je.THREE_COLUMN:r="111";break;case je.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(!R.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();R.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 o=i.isDuplicateCell(this,n),a=this.getRequiredLevel(t);if((a===oo.ApplicationRequired||a===oo.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?oo.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??oo.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()===E.formCell){let i=n;i.control&&i!==this&&r.add(n.control.id)}return!1}),r}getHighestIndexById(t,r){let n=t.findAll(o=>o.getNodeName()===E.formCell&&o.control&&o.control.ClassId.guidString===r),i=0;return n.forEach(o=>{i=Math.max(this.parseControlNameIndex(o.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)===vy&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var qs,Cy=L(()=>{"use strict";Xt();ue();It();qs=class extends re{isInternal;constructor(t,r,n,i){super(E.library,t),this.isInternal=!!i,q.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(y.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(y.libraryUniqueId,t)}get name(){return this.getProperty(y.libraryName)}set name(t){this.setProperty(y.libraryName,t)}get displayName(){return this.getProperty(y.displayName)}set displayName(t){this.setProperty(y.displayName,t)}get description(){return this.getProperty(y.description)}set description(t){this.setProperty(y.description,t)}}});var pa,Ey=L(()=>{"use strict";st();Uu();ue();It();pa=class extends re{isRowAddedOnDragOver;constructor(t){super(E.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 R.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return R.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(E.formSection)}insertPaddingCellAtIndex(t){let r=new Ir(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(E.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 VQ(e){switch(e){case la.Left:return ca.Left;case la.Right:return ca.Right;case la.Center:return ca.Center;default:return ca.Left}}function GQ(e){switch(e){case Es.Left:return As.Left;case Es.Top:return As.Top;default:return As.Left}}function P2(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var WQ,ni,Bu=L(()=>{"use strict";T0();ht();st();Xt();my();Uu();ue();Tn();Co();Ey();WQ=115,ni=class e extends Zt{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=je.ONE_COLUMN;break;case 11:t=je.TWO_COLUMN;break;case 111:t=je.THREE_COLUMN;break;case 1111:t=je.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=Ue.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+Ue.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(y.Name,r)}initializeDefaultProperties(t,r,n){if(n===je.REFERENCE_PANEL){this.addProperty(y.rowheight,"25");let i=`${Ue.referencePanelNamePrefix}${U.NewGuid()}${Ue.namePrefix}`;this.addProperty(y.Name,i)}else this.setUniqueName();if(this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,Ue.IsUserDefined),this.addProperty(y.locklevel,Ue.LockLevel),this.addProperty(y.showlabel,Ue.ShowLabel),this.addProperty(y.showbar,Ue.ShowBar),this.addProperty(y.layout,Ue.Layout),this.addProperty(y.Fieldlabelalignment,Ue.labelAlignment),this.addProperty(y.Fieldlabelposition,Ue.labelPosition),R.IsNullOrUndefined(n))this.addProperty(y.columnName,Ue.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(y.columnName,i)}this.addProperty(y.LabelWidth,Ue.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case je.TWO_COLUMN:r="11";break;case je.THREE_COLUMN:r="111";break;case je.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 R.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(q.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new pa(null);if(this.addGrandChild(E.formRows,r),S2.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new Ir(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===je.REFERENCE_PANEL&&(n=je.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(E.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(E.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(E.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(E.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(E.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(E.formRows);return t.length===0?[]:t[0].getChildren(E.formRow)}get columns(){let t=this.getProperty(y.columnName),r=R.IsNullOrUndefined(t)?NaN:parseInt(t,10);if(isNaN(r)){let n=1;for(let i of this.rows)n=Math.max(n,i.cells.length);return P2(n)}return r}set columns(t){R.IsNullOrUndefined(t)||this.setProperty(y.columnName,String(t))}get rowHeight(){let t=this.getProperty(y.rowheight);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(y.rowheight,String(t))}set autoexpand(t){this.setProperty(y.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(y.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(y.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(y.IsUserDefined,"1"):this.setProperty(y.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(E.formColumn)}getParentTab(){return this.getAncestor(E.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(y.showlabel)==="true"}set showlabel(t){R.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}get fieldLabelAlignment(){let t=Ue.labelAlignment,r=this.getProperty(y.Fieldlabelalignment);return R.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){R.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(y.Fieldlabelposition);return R.IsNullOrUndefined(t)?Ue.labelPosition:t}set fieldLabelPosition(t){R.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(y.showbar)==="true"}set showbar(t){R.IsNullOrUndefined(t)||this.setProperty(y.showbar,String(t))}get labelwidth(){let t=+this.getProperty(y.LabelWidth);return t===0?WQ:t}set labelwidth(t){R.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(y.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:VQ(this.fieldLabelAlignment),Position:GQ(this.fieldLabelPosition)},Columns:P2(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()===E.formSection){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!R.IsNullOrUndefined(this)&&!R.IsNullOrUndefined(this.Name)&&this.Name.indexOf(Ue.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===E.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===E.formFooter||this.NodeName===E.formHeader}}});var Eo,Df=L(()=>{"use strict";ue();It();Bu();Eo=class e extends re{constructor(t){super(E.formColumn,t)}initializeDefaultProperties(t){this.addProperty(y.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(E.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new ni(E.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(E.formSections,t,r)}initialize(t,r,n,i=je.ONE_COLUMN){this.initializeDefaultProperties(t);let o=e.createAndInitNewSection(r,n,i);this.addSectionAtIndex(o,this.sections.length),o.setUniqueName()}get parentTab(){return this.getAncestor(E.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(E.formSection)}get width(){return this.getProperty(y.width)}set width(t){this.setProperty(y.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(E.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(y.Name),Id:this.getProperty(y.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(y.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var If,R2=L(()=>{"use strict";ht();ue();Tn();Bu();If=class extends ni{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(y.Name,n),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.columnName,Ue.columns),this.setDisplayName(r,t)}}});var Of,k2=L(()=>{"use strict";Df();ue();R2();Of=class extends Eo{addAndIntializeNavBarSection(t,r,n,i){let o=new If(E.formSection,null);return o.initializeNavArea(t,r,i),this.addGrandChildAtIndex(E.formSections,o,n),o}}});var xi,Pf=L(()=>{"use strict";ht();st();Xt();Df();ue();It();Co();xi=class extends Zt{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(E.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(E.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=ze.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=ze.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=ze.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=ze.TWO_COLUMN_WIDER_RIGHT;break}t=ze.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=ze.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=ze.THREE_COLUMN_WIDER_MID;break}t=ze.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(y.Name,go.namePrefix+t.toString()),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,go.IsUserDefined),this.addProperty(y.locklevel,go.LockLevel),this.addProperty(y.showlabel,go.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=je.ONE_COLUMN,o=!0,a){let s=this.getChildren(E.formColumns)[0],l=[];switch(t){case ze.ONE_COLUMN:l.push(100);break;case ze.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case ze.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case ze.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case ze.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case ze.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new Eo(s);c.initialize(u,r,n,i),this.addGrandChild(E.formColumns,c)}}initialize(t,r,n,i,o,a=je.ONE_COLUMN,s=!0,l){this.addChild(new re(E.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,o,a,s,l)}get columns(){let t=this.getChildren(E.formColumns);return t.length!==1?[]:t[0].getChildren(E.formColumn)}get expanded(){return this.getProcessedValue(y.expanded)}set expanded(t){R.IsNullOrUndefined(t)||this.setProperty(y.expanded,String(t))}get groupName(){return this.getProperty(y.groupName)}get contentType(){return this.getProperty(y.contentType)}set contentType(t){this.setProperty(y.contentType,t)}insertNewColumnAtIndex(t,r,n,i,o){t.initialize(n,i,o),this.addGrandChildAtIndex(E.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(E.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(E.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()===E.formTab){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var ma,Ay=L(()=>{"use strict";ht();ue();It();Tn();k2();Pf();ma=class extends xi{constructor(t,r,n){super(t,ze.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new U(U.NewGuid())}initializeDefaultProps(){this.addChild(new re(E.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(E.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 o of i.cells)if(o.NavId===t)return o;return null}initializeFiveColumns(){for(let t=0;t<cf.FIVE_COLUMN;t++){let r=new Of(this.getChildren(E.formColumns)[0]);r.initializeDefaultProperties(Z_.FiveEqColumn),this.addGrandChild(E.formColumns,r)}}}});function jQ(e){switch(e){case gt.Main:return yo.Main;case gt.QuickCreate:return yo.QuickCreate;case gt.QuickViewForm:return yo.Quick;case gt.Dialog:return yo.Dialog;default:return yo.None}}function HQ(e,t){if(t===gt.Main){if(e)switch(e.toLowerCase()){case"low":return ho.Low;case"highreadonlyvalues":return ho.HighReadOnlyValues;default:return ho.HighWithControls}return ho.Low}}var kf,zQ,Rf,L2=L(()=>{"use strict";sT();kf=Ae(aa());T0();st();Xt();ws();my();ue();Ho();Kg();oa();Uu();ue();Co();Cy();Ay();Pf();zQ="1920";Rf=class e extends Zt{_formUniqueName;isHeaderDefaulted;consistencyStrong=!1;_formId;_rawFormXml;_entityName;_entityDisplayName;_status;_formName;_langCode;_description;_formType;_formPresentation;parameters=[];_formactivationstate;_changeTracker;_metadataChangeEvent;_etag;constructor(t,r,n,i,o,a,s,l,u){super(E.form,null),this._formUniqueName=o,this._formId=t,this._entityName=r,this._status=n,this._formName=i,this._description=l,this._formType=a,this._formPresentation=s,this._formactivationstate=u,this._changeTracker=new Jd,this._metadataChangeEvent=new ff}get FormLibraries(){let t=this.getFirstChild(E.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(o=>o instanceof Ir).forEach(o=>{let a=o.events;a&&(t=t.concat(a))})}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 Ir){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()===E.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let o=i.GetPropertyByParameter(n).replace("$webresource:",""),a=new qs(void 0,void 0,"",!0);return a.name=o,a.displayName=o,a})),r}getDependentFields(){let t=this.getAllEvents(),r=new Set;return t.forEach(n=>{try{n.getAllDependencies().forEach(o=>{r.add(o.id)})}catch(i){throw(0,kf.trackErrorTrace)(I_,{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 q.IsNullOrEmpty(this.getProperty(y.ShowImage))?!0:this.getProperty(y.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(y.ShowImage,String(t)):this.setProperty(y.ShowImage,"false")}get ShowNavigation(){return q.IsNullOrEmpty(this.getProperty(y.ShowNavigationbar))?!0:this.getProperty(y.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(y.ShowNavigationbar,String(t)):this.setProperty(y.ShowNavigationbar,"false")}get MaxWidth(){return q.IsNullOrEmpty(this.getProperty(y.MaxWidth))?zQ:this.getProperty(y.MaxWidth)}set MaxWidth(t){this.setProperty(y.MaxWidth,t)}get headerDensityType(){return this.getProperty(y.HeaderDensityType)}set headerDensityType(t){t&&this.formType===gt.Main?this.setProperty(y.HeaderDensityType,t):this.formType!==gt.Main&&this.headerDensityType&&this.removeProperty(y.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===gt.Main||this.formType===gt.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(E.formHeader);return t.length!==1?null:t[0]}set header(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(E.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(E.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return R.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(E.formFooter);return t.length!==1?null:t[0]}set footer(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new xi(null,t),o=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,o,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(E.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,o){let a=new xi(null,ze.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);a.initialize(ze.ONE_COLUMN,s,this.LanguageCode,r,n,o,!1),this.addGrandChildAtIndex(E.formTabs,a,i);let l=a.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===go.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(E.formTabs);return t.length!==1?[]:t[0].getChildren(E.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof ma)return t}return null}get NavigationNode(){let t=this.getChildren(E.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(E.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(E.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(E.formTabs);if(!R.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(E.formFooter).length>0}get displayCondition(){let t=this.getChildren(E.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(E.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(E.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(E.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);R.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(E.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 Ir))return!1;let o=!0;return r==="Tab"?o=i.getParentTab()!==t.getParentTab():r==="Section"?o=i.getParentSection()!==t.getParentSection():o=i!==t,i instanceof Ir&&i.control&&t.control&&o&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==N.CustomControl?!1:this.cellHasCustomControlWithName(t,Ti.EditableGridControl)||N2.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,Ti.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===N.CustomControl&&this.cellHasCustomControlWithName(t,Ti.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()===E.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 o of r)if(!(o instanceof ma)){let a=o.toJSON(t);n.push(a)}for(let o of n)i.push(await o)}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,kf.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===gt.Main?{HeaderDensity:HQ(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:jQ(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 Lf,Sy,$2=L(()=>{"use strict";ht();st();ue();It();Co();Lf=class extends Zt{constructor(t){super(E.formDisplayConditions,t)}get Order(){let t=this.getProperty(y.Order);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(y.Order,t.toString())}get FallbackForm(){return this.getProperty(y.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(y.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(E.formEveryOne)&&this.getChildren(E.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new Sy(this))}},Sy=class extends re{constructor(t){super(E.formEveryOne,t)}}});var $f,x2=L(()=>{"use strict";ue();It();$f=class extends re{constructor(t,r){super(E.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(y.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(y.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(y.functionName)}set FunctionName(t){this.setProperty(y.functionName,t)}get LibraryName(){return this.getProperty(y.libraryNameEventHandler)}set LibraryName(t){this.setProperty(y.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(y.enabledForField)}set Enabled(t){this.setProperty(y.enabledForField,t)}get PassExecutionContext(){return this.getProperty(y.passExecutionContext)}set PassExecutionContext(t){this.setProperty(y.passExecutionContext,t)}get Parameters(){return this.getProperty(y.parameters)}set Parameters(t){this.setProperty(y.parameters,t)}}});var Vs,Ny=L(()=>{"use strict";ue();Bu();Vs=class extends ni{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(E.formCell);for(let o of i)r.push(o)}}return r}get occupiedCells(){return this.cells.filter(t=>!t.isEmpty())}get maxColumns(){return super.getColumnCountValue()}}});var qu,F2=L(()=>{"use strict";ue();Ny();qu=class extends Vs{_customFooter;constructor(t,r){super(E.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 Vu,M2=L(()=>{"use strict";ue();Ny();Vu=class extends Vs{_customHeader;constructor(t,r){super(E.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(y.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(y.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(y.showBody)}set showBody(t){t!=null&&this.setProperty(y.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(y.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(y.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 Or,ha=L(()=>{"use strict";ht();Xt();ue();Co();Or=class e extends Zt{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(y.LCID)===t)return r.getProperty(y.text);return null}getAllTitles(){let t=this.getChildren(E.Titles);return t.length===0?[]:t[0].getChildren(E.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(y.LCID)===r){i.setProperty(y.text,t);return}let n=new e(E.Title,null);n.setProperty(y.text,t),n.setProperty(y.LCID,String(r)),this.addGrandChild(E.Titles,n)}get Sequence(){return+this.getProperty(y.Sequence)}set Sequence(t){this.setProperty(y.Sequence,t.toString())}get Area(){return this.getProperty(y.Area)}set Area(t){this.setProperty(y.Area,t)}set Id(t){this.setProperty(y.Id,t)}get Id(){return this.getProperty(y.Id)}get id(){return new U(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(y.icon)}set Icon(t){t=t||q.EmptyString,this.setProperty(y.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var Gu,U2=L(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(Gu||(Gu={}))});var xf,B2=L(()=>{"use strict";st();ue();ha();U2();xf=class extends Or{constructor(t){super(E.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 R.IsNullOrUndefined(r)?Gu.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):Gu.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 xe,KQ,q2,b0e,Gs,_y=L(()=>{"use strict";ht();ue();ha();(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"})(xe||(xe={}));KQ=new Map([[xe.Info,"Info"],[xe.Sales,"Sales"],[xe.Service,"Service"],[xe.Marketing,"Marketing"],[xe.ProcessCenter,"ProcessCenter"]]),q2=new Map([["Info",xe.Info],["Sales",xe.Sales],["Service",xe.Service],["Marketing",xe.Marketing],["ProcessCenter",xe.ProcessCenter]]),b0e=new Map([[xe.Info,9e3],[xe.Sales,9200],[xe.Service,9400],[xe.Marketing,9600],[xe.ProcessCenter,9800],[xe.InternetMarketing,1e4],[xe.Async,10200]]),Gs=class extends Or{constructor(t,r){super(E.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=KQ.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(E.formNavigation)}get AreaId(){return this.getProperty(y.Id)}set AreaId(t){this.setProperty(y.Id,t)}get id(){return new U(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 Ws,Ty=L(()=>{"use strict";ue();ha();Ws=class extends Or{constructor(t,r){super(E.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(E.formNavBarArea)}get ParentNavigation(){return this.getAncestor(E.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var Ff,V2=L(()=>{"use strict";st();ue();ha();Ff=class extends Or{RelationshipNameUCIRuntime;constructor(t){super(E.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(y.RelationshipName)}set RelationshipName(t){this.setProperty(y.RelationshipName,t)}set Show(t){this.setProperty(y.Show,String(t))}get Show(){let t=this.getProperty(y.Show);return R.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(y.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 Mf,G2=L(()=>{"use strict";ue();ha();Mf=class extends Or{constructor(t){super(E.formNavBarItem,t)}get Url(){return this.getProperty(y.url)}set Url(t){this.setProperty(y.url,t)}}});var Uf,W2=L(()=>{"use strict";ht();ue();_y();Ty();ha();Uf=class extends Or{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(E.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[xe.Info,xe.Sales,xe.Service,xe.Marketing,xe.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let o=new Set(i.map(a=>q2.get(a.AreaId)));n=n.filter(a=>!o.has(a))}}else{let i=new Ws(E.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let o=new Gs(E.formNavBarArea,this.navBarAreas);o.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(o)}),!0):!1}get navBar(){return this.getFirstChild(E.formNavBar)}get id(){return new U(a0,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(E.formNavBarAreas,r),this.addGrandChildAtIndex(E.formNavBarAreas,r,t))}async getNavBarAreasJSON(t){let r=[],n=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let o of this.navBarAreas.AllNavBarAreaItems)n.push(o.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 z2={};Jr(z2,{ControlType:()=>cn,DeserializationService:()=>Oy,DeserializationServiceScope:()=>Iy,DeserializedFormElementNode:()=>Pr});var Dy,Pr,Iy,cn,Oy,wy=L(()=>{"use strict";Dy=Ae(aa());ht();st();Xt();ws();s0();oa();O_();oT();bu();L2();Uu();Df();Mu();hy();ue();ue();$2();It();Tn();gy();x2();F2();yy();by();M2();Cy();Ey();Bu();Pf();B2();_y();Ty();V2();G2();W2();Pr=class extends re{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},Iy="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(cn||(cn={}));Oy=class{lcid;constructor(t){this.lcid=t}deSerializeFormXml(t,r,n,i,o,a,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,Dy.trackErrorTrace)(cr,{eventName:Iy,eventData:{error:m}}),new Error(m)}let f=this.createFormModel(d.item(0),r,n,i,o,a,s,l,u,c);return R.IsNullOrUndefined(f.displayCondition)&&s!==gt.Dialog&&this.appendDefaultDisplayCondition(f),f}upsertFieldCount(t,r){let n=sa.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(!R.IsNullOrUndefined(t)){let n=R.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,o,a,s,l,u,c){let d=new Rf(r,n,i,o,a,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===gt.Main&&(this.insertHeaderFooterElementProperties(E.formHeader,d,d.header),this.insertHeaderFooterElementProperties(E.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(R.IsNullOrUndefined(n)){let i=t===E.formHeader?new Vu(r,!0):new qu(r,!0);Pr.prototype.insertProperty.call(i,y.id,"{"+U.NewGuid()+"}"),Pr.prototype.insertProperty.call(i,y.Fieldlabelposition,"Top"),Pr.prototype.insertProperty.call(i,y.columnName,Ue.MarginalControlColumns),Pr.prototype.insertProperty.call(i,y.LabelWidth,Ue.LabelWidth),Pr.prototype.insertProperty.call(i,y.Fieldlabelalignment,"Left");let o=null,a=new pa(o);for(let s=0;s<i.maxColumns;s++){let l=new Ir(a);Pr.prototype.insertProperty.call(l,y.id,"{"+U.NewGuid()+"}"),l.setDisplayName(q.EmptyString,this.lcid),Pr.prototype.insertProperty.call(l,y.showlabel,"false"),a.addCell(l)}i.appendRow(a),t===E.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 Pr(`<${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,Dy.trackErrorTrace)(cr,{eventName:Iy,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(Pr.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===E.formCell&&i.name===y.auto&&i.value==="true"&&t.setAutoExpandDetailsForTab())}}populateElementChildren(t,r){for(let n=0;n<r.length;n++){let i=r.item(n),o=this.deSerializeFormXmlNode(i,t);o&&Pr.prototype.insertChild.call(t,o)}}createModelNode(t,r){switch(t.nodeName){case E.form:throw new Error("Form node shouldn't be created using this method");case E.formTab:return new xi(r);case E.formColumn:return new Eo(r);case E.formHeader:return new Vu(r,!1);case E.formFooter:return new qu(r,!1);case E.formSection:return new ni(E.formSection,r);case E.formRow:return new pa(r);case E.formCell:return new Ir(r);case E.formControl:let n=t.attributes,i=t.childNodes.length>0?t.childNodes[0].childNodes:null,o;for(let s=0;s<n.length;s++){let l=n.item(s);if(l.name===y.indicationOfSubgrid&&l.value==="true"||l.name===y.classid&&(l.value?.toLocaleUpperCase()===`{${N.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${N.ReferencePanelSubgridControl}}`))o=cn.Grid;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.LookupControl}}`)o=cn.Lookup;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===y.DefaultViewId&&(o=cn.Lookup)}return o===cn.Grid?new Us(r):o===cn.Lookup?new Bs(r):new On(r);case E.formEvent:return new Ms(r,q.EmptyString);case E.dependency:return this.populateDependencyTable(t),new Fs(r,q.EmptyString);case E.Handler:let a=[];return new $f(a,r);case E.formNavigation:return new Uf(t.nodeName,r);case E.formNavBarArea:return new Gs(t.nodeName,r);case E.formNavBarAreas:return new Ws(t.nodeName,r);case E.formNavBar:return new xf(r);case E.formNavBarByRelationshipItem:return new Ff(r);case E.formNavBarItem:return new Mf(r);case E.formDisplayConditions:return new Lf(r);case E.library:return new qs(r,q.EmptyString,q.EmptyString);case E.controlDescription:return new ef(r);case E.customControl:return this.populateCustomControlConfigurationId(t),new df(r);default:return new Pr(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===y.id&&this.upsertFieldCount(i.value,Zn.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===y.id){let o=new U(i.value.substr(1,i.value.length-2));for(let a=0;a<t.parentNode.attributes.length;a++){let s=t.parentNode.attributes.item(a);if(s.name===y.ForControl){let l=s.value.substr(1,i.value.length-2);lt.CustomControlIdMap.upsert(l,o);break}}break}}}}});var j2={};Jr(j2,{SerializationService:()=>Py,SerializationServiceScope:()=>JQ,SerializedFormElementNode:()=>zs});var JQ,zs,Py,H2=L(()=>{"use strict";Xt();It();Tn();Ay();JQ="SerializationService",zs=class extends re{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},Py=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=zs.prototype.fetchNodeName.call(t);if(r.charAt(0)===Li.StartTag)return q.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return q.EmptyString;let n=zs.prototype.enumerateProperties.call(t),i=zs.prototype.enumerateChildren.call(t);if(!(t instanceof ma)){let o=`<${r}`;if(n.length!==0&&(o+=` ${this.getPropertiesString(n)}`),i.length===0)o+=" />";else{let a=q.EmptyString;for(let s of i)a+=this.serializeFormXmlNode(s);o+=`>${a}</${r}>`}return o}return q.EmptyString}getPropertiesString(t){let r=q.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${q.EscapeXml(n.value,!0)}"`}),r}}});var $y=v(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.completeRecordAsStored=js.completeLabelsAsStored=void 0;var Ry=uo(),YQ="E7A81278-8635-4D9E-8D4D-59480B391C5B",QQ=new Set(["tab","section","cell"]);function Pn(e){let t=[];for(let r=e.firstChild;r;r=r.nextSibling)r.nodeType===1&&t.push(r);return t}function Ao(e,t){return Pn(e).find(r=>r.tagName===t)}function J2(e,t){return e.length===t.length&&e.every((r,n)=>r.tagName===t[n].tagName)}function ky(e){let t=Ao(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===YQ:!1}function Ly(e,t){var r,n;let i=((r=Ao(e,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"";return i!==""&&i===(((n=Ao(t,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"")}function XQ(e,t){if(Ao(e,"labels"))return;let r=Pn(e),n=Pn(t),i=n[0];if(!i||i.tagName!=="labels"||n.length!==r.length+1||!J2(r,n.slice(1)))return;let o=Pn(i);if(!(o.length===0||o.some(s=>s.tagName!=="label"||!s.hasAttribute("description")||!s.hasAttribute("languagecode"))||!(e.tagName==="cell"&&ky(e)&&Ly(e,t))&&o.some(s=>s.getAttribute("description")!=="")))return i}function ZQ(e,t){let r=eX(e.ownerDocument,t),n=Pn(e)[0];n?e.insertBefore(r,n):e.appendChild(r)}function eX(e,t){let r=e.createElement("labels");for(let n of Pn(t))r.appendChild(Y2(e,n));return r}function Y2(e,t){let r=e.createElement("label");for(let n=0;n<t.attributes.length;n+=1){let{name:i,value:o}=t.attributes[n];(i==="description"||i==="languagecode")&&r.setAttribute(i,o)}return r}function K2(e,t){let r=Ao(e,"labels");return r?Pn(r).find(n=>n.tagName==="label"&&n.getAttribute("languagecode")===String(t)):void 0}function tX(e,t,r){if(e.tagName!=="cell"||!ky(e)||!Ly(e,t))return!1;let n=K2(e,r),i=K2(t,r),o=i?.getAttribute("description")||"";return!n||!n.hasAttribute("description")||(n.getAttribute("description")||"")!==""||o===""?!1:(n.setAttribute("description",o),!0)}function rX(e,t){if(e.tagName!=="cell"||!ky(e)||!Ly(e,t))return;let r=Ao(e,"labels"),n=Ao(t,"labels");if(!r||!n)return;let i=Pn(r),o=Pn(n),a=f=>f.tagName==="label"&&f.hasAttribute("description")&&f.hasAttribute("languagecode");if(o.length<=i.length||!i.every(a)||!o.every(a))return;let s=new Map(i.map(f=>[f.getAttribute("languagecode")||"",f]));if(s.size!==i.length)return;let l=new Set,u=0,c=[],d=[];for(let f of o){let m=f.getAttribute("languagecode")||"";if(l.has(m))return;l.add(m);let p=s.get(m);if(!p){d.push(f);continue}if((p.getAttribute("description")||"")!==(f.getAttribute("description")||""))return;u+=1,c.push(...d.map(h=>({label:h,before:p}))),d=[]}return c.push(...d.map(f=>({label:f}))),u===i.length?c:void 0}function Q2(e,t,r,n){if(e.tagName!==t.tagName)return;if(QQ.has(e.tagName)){let a=XQ(e,t);a&&(ZQ(e,a),n.changed=!0),tX(e,t,r)&&(n.changed=!0);let s=rX(e,t),l=Ao(e,"labels");if(s&&l){for(let{label:u,before:c}of s){let d=Y2(e.ownerDocument,u);c?l.insertBefore(d,c):l.appendChild(d)}n.changed=!0}}let i=Pn(e),o=Pn(t);J2(i,o)&&i.forEach((a,s)=>Q2(a,o[s],r,n))}function X2(e,t,r){if(e===t)return e;let n,i;try{n=(0,Ry.parseXmlRoot)(e,""),i=(0,Ry.parseXmlRoot)(t,"")}catch{return e}let o={changed:!1};return Q2(n,i,r,o),o.changed?(0,Ry.serializeNode)(n):e}js.completeLabelsAsStored=X2;function nX(e,t,r){let n=e?.formxml,i=t?.formxml;if(typeof n!="string"||typeof i!="string")return e;let o=X2(n,i,r);return o===n?e:{...e,formxml:o}}js.completeRecordAsStored=nX});var bk=v(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.pcfReadIssues=ce.pcfBindingIssues=ce.commitPcfState=ce.mayCommitPcfState=ce.reconcilePcfDescriptions=ce.customControlNeeds=ce.mintPcfIdentity=ce.planPcfBinding=ce.projectPcfBindings=ce.supportsPcfFormType=ce.storedBindingOf=ce.hasCustomControl=ce.sameAsStored=ce.readPcfDescription=ce.newPcfDescription=ce.editorText=ce.nativeClassFor=ce.pcfEntryLayout=void 0;var iX=(bu(),Br(aT)),oX=Q(),Z2=pt(),V=Dd(),aX=Hh(),Ee=rn(),Ui=["web","phone","tablet"],Wu={web:"2",phone:"0",tablet:"1"},ik=new Map([["2","web"],["0","phone"],["1","tablet"]]),sX=["phone","web","tablet"];function qf(e){let t=new Set(e),r=sX.filter(n=>!t.has(n));return{defaults:r.length===0?[null]:r,named:Ui.filter(n=>t.has(n))}}ce.pcfEntryLayout=qf;function dr(e){return Array.isArray(e)?e:[]}function ut(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function zu(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Fy(e){return{n:`<${e}`,a:[],c:[]}}function ok(e){return typeof e?.n=="string"&&e.n.startsWith("<")}function ek(e){let t=dr(e.c);return t.length===1&&ok(t[0])&&(0,V.rawText)(e)!==""?(0,V.rawText)(e):void 0}function fn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ak(e){return`{${e.replace(/^\{|\}$/g,"").toUpperCase()}}`}function My(e){try{let t=(0,iX.mapFieldTypeToControl)(e.attributeTypeName,e.format);return t?ak(String(t)):void 0}catch{return}}ce.nativeClassFor=My;var Uy=new Map([["Whole.None",{digits:0,min:-2147483648,max:2147483647}],["Whole.Duration",{digits:0,min:0,max:2147483647}],["Decimal",{digits:7,min:-922337203685477,max:922337203685477}],["FP",{digits:5,min:-1e11,max:1e11}],["Currency",{digits:4,min:-1e11,max:1e11}]]),sk=new Set(["TwoOptions","Boolean"]),lk=new Set(["SingleLine.Text","SingleLine.TextArea","SingleLine.Email","SingleLine.Phone","SingleLine.URL","SingleLine.Ticker","Multiple"]),lX=new Map([...[...lk].map(e=>[e,100]),["SingleLine.TextArea",2e3],["Multiple",1048576]]),uX=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function uk(e){return uX.test(e)&&e!=="__proto__"}function By(e){return e!==void 0&&(e==="Enum"||Uy.has(e)||sk.has(e)||lk.has(e))}function ck(e){return typeof e=="number"?e:e!==""&&!Number.isNaN(Number(e))?Number(e):void 0}function ju(e,t){let r=e!==void 0?Uy.get(e):void 0;if(r&&typeof t!="boolean"){let n=ck(t);if(n!==void 0)return n.toFixed(r.digits)}return typeof t=="boolean"?t?"true":"false":String(t)}ce.editorText=ju;function cX(e,t,r){var n;let i=[];for(let o of e.properties){let a=o.name,s;if(o.isPrimary?s=t:o.usage==="input"&&zu(r,a)?s=ju(o.defaultType,r[a]):s=(n=o.defaultValue)!==null&&n!==void 0?n:"",s==="")continue;let l=[];o.defaultType&&l.push(["type",o.defaultType]),!o.isPrimary&&(o.defaultType==="Enum"||o.usage==="input")&&l.push(["static","true"]),i.push({n:a,a:l,c:[Fy(s)]})}return i}function dk(e,t,r,n,i){var o,a;let s=(o=n.formFactors)!==null&&o!==void 0?o:Ui.filter(d=>qy(i).has(d)),l=qf(s),u=cX(i,t,(a=n.parameters)!==null&&a!==void 0?a:{}),c=d=>JSON.parse(JSON.stringify(d));return{n:"controlDescription",a:[["forControl",e]],c:[...l.defaults.map(d=>({n:"customControl",a:d===null?[["id",r]]:[["id",r],["formFactor",Wu[d]]],c:[{n:"parameters",a:[],c:[{n:"datafieldname",a:[],c:[Fy(t)]}]}]})),...l.named.map(d=>({n:"customControl",a:[["name",n.name],["formFactor",Wu[d]]],c:[{n:"parameters",a:[],c:c(u)}]}))]}}ce.newPcfDescription=dk;function qy(e){return new Set(Ui.filter(t=>e.availableOn[t]))}function Bf(e){var t;let r=dr(e.c);if(r.length!==1||((t=r[0])===null||t===void 0?void 0:t.n)!=="parameters"||dr(r[0].a).length>0)return;let n=dr(r[0].c);return n.every(i=>ut(i)&&!ok(i))?n:void 0}function ga(e){let t=dr(e?.c);if(t.length===0||!t.every(p=>ut(p)&&p.n==="customControl"))return;let r=t.findIndex(p=>(0,V.rawAttr)(p,"name")!==void 0);if(r<=0)return;let n=t.slice(r),i=(0,V.rawAttr)(n[0],"name"),o=[];for(let p of n){let h=dr(p.a),g=h.length===2?ik.get(h[1][1]):void 0;if(!g||h[0][0]!=="name"||h[0][1]!==i||h[1][0]!=="formFactor"||o.includes(g))return;o.push(g)}let a=qf(o);if(!fn(a.named,o)||i==="")return;let s=Bf(n[0]);if(!s||!n.every(p=>fn(Bf(p),s)))return;let l=t.slice(0,r);if(l.length!==a.defaults.length)return;let u=(0,V.rawAttr)(l[0],"id"),c;for(let p=0;p<l.length;p+=1){let h=a.defaults[p],g=h===null?[["id",u??""]]:[["id",u??""],["formFactor",Wu[h]]],b=Bf(l[p]),w=b?.length===1&&b[0].n==="datafieldname"&&dr(b[0].a).length===0?ek(b[0]):void 0;if(!u||!fn(dr(l[p].a),g)||w===void 0||c!==void 0&&w!==c)return;c=w}let d={},f={},m;for(let p of s){let h=dr(p.a),g=ek(p),b=h.map(w=>w[0]);if(g===void 0||!uk(p.n)||zu(d,p.n)||p.n===m)return;if((0,V.rawAttr)(p,"static")===void 0){if(m!==void 0||g!==c||!(b.length===0||fn(b,["type"])))return;m=p.n;continue}if((0,V.rawAttr)(p,"static")!=="true"||!(fn(b,["static"])||fn(b,["type","static"])))return;d[p.n]=g,f[p.n]=(0,V.rawAttr)(p,"type")}if(!(m===void 0||c===void 0||u===void 0))return{binding:{name:i,...Object.keys(d).length>0?{parameters:d}:{},...o.length===Ui.length?{}:{formFactors:o}},fieldName:c,nativeClass:u,parameterTypes:f,boundProperty:m}}ce.readPcfDescription=ga;function fk(e,t,r){return e===t?!0:typeof e!="string"&&(t===String(e)||t===ju(r,e))}function pk(e){let t=e.formFactors;return t===void 0?[...Ui]:Array.isArray(t)?Ui.filter(r=>t.includes(r)):[]}function xy(e,t){var r,n,i;if(e.name!==t.binding.name||!fn(pk(e),(r=t.binding.formFactors)!==null&&r!==void 0?r:Ui))return!1;let o=(n=e.parameters)!==null&&n!==void 0?n:{},a=(i=t.binding.parameters)!==null&&i!==void 0?i:{},s=Object.keys(o);return s.length!==Object.keys(a).length?!1:s.every(l=>zu(a,l)&&fk(o[l],a[l],t.parameterTypes[l]))}ce.sameAsStored=xy;function yt(e){return ut(e)&&e.customControl!==void 0}ce.hasCustomControl=yt;function Mi(e,t){var r;return t?dr((r=(0,V.descriptionsRegion)(e))===null||r===void 0?void 0:r.node.c).filter(n=>n?.n==="controlDescription"&&(0,V.normGuid)((0,V.rawAttr)(n,"forControl"))===t):[]}function Vy(e,t){let r=Mi(e.bag,(0,V.controlUniqueId)(t));return r.length===1?ga(r[0]):void 0}ce.storedBindingOf=Vy;function Gy(e){let t=(0,V.effectiveFormType)(e);return t==="Main"||t==="QuickCreate"}ce.supportsPcfFormType=Gy;function dX(e){if(!Gy(e))return;let t=(0,V.controlUniqueIds)(e);for(let{cell:r}of(0,V.typedCellSites)(e)){let n=r.control;if(!ut(n)||!n.fieldName||!Fi(n.classId)||t.get((0,V.controlUniqueId)(n))!==1)continue;let i=Vy(e,n);i&&i.fieldName===n.fieldName&&(n.customControl=JSON.parse(JSON.stringify(i.binding)))}}ce.projectPcfBindings=dX;function Fi(e){return typeof e=="string"&&e.replace(/^\{|\}$/g,"").toUpperCase()===V.CUSTOM_CONTROL_CLASS_ID}var dn=(e,t)=>({kind:"refused",rule:e,message:t});function fX(e){let t=e.replace(/^\{|\}$/g,"");return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)&&!Fi(e)}function tk(e,t,r){var n,i;let o=ga(r);if(!o)return dn("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");if(o.fieldName!==e.fieldName)return dn("pcf-binding-rebind",`the binding is filed for "${o.fieldName}": remove it, push, then bind the new column`);if(t.name!==o.binding.name)return dn("pcf-binding-control-swap",`the binding uses "${o.binding.name}": to use another control, remove customControl, push, then add it`);let a=ut(t.parameters)?t.parameters:{},s=(n=o.binding.parameters)!==null&&n!==void 0?n:{},l=Object.keys(a).sort();if(!fn(l,Object.keys(s).sort()))return dn("pcf-binding-edit-parameter-set",`an edit changes parameter values only \u2014 the binding stores exactly ${Object.keys(s).sort().map(g=>`"${g}"`).join(", ")||"none"}: to add or remove one, remove the binding, push, then add it`);let u=l.filter(g=>!fk(a[g],s[g],o.parameterTypes[g])),c=u.find(g=>ju(o.parameterTypes[g],a[g]).trim()==="");if(c!==void 0)return dn("pcf-binding-edit-parameter-set",`"${c}" cannot be cleared in place \u2014 an empty value is not written, which removes the parameter: remove the binding, push, then add it`);let d=pk(t),f=(i=o.binding.formFactors)!==null&&i!==void 0?i:[...Ui],m=d.filter(g=>!f.includes(g)),p=f.filter(g=>!d.includes(g));if(u.length===0&&m.length===0&&p.length===0)return{kind:"unchanged"};let h=u.find(g=>!By(o.parameterTypes[g]));if(h!==void 0){let g=o.parameterTypes[h];return dn("pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which the property editor does not write: remove the binding, push, then add it`)}return(m.length>0||p.length>0)&&!fX(o.nativeClass)?dn("pcf-binding-edit-fallback",`the factors the control leaves fall back to "${o.nativeClass}", which is not a native control class: remove the binding, push, then add it`):{kind:"edit",description:r,stored:o,changed:u,factors:d,added:m,removed:p}}function pX(e,t){return t&&(0,V.typedCellSites)(e).find(({cell:n})=>yt(n.control)&&(0,V.controlUniqueId)(n.control)===t)?{descriptions:Mi(e.bag,t)}:void 0}function mk(e,t){let r=new Map,n=mX(e),i=new Set,o=new Map,a=u=>{let c=o.get(u);return c||(c={before:[],now:[]},o.set(u,c)),c},s=(u,c)=>({cell:yX(u),uid:(0,V.controlUniqueId)(c),bound:yt(c)});for(let{cell:u}of(0,V.typedCellSites)(e)){let c=u.control;ut(c)&&typeof c.id=="string"&&c.id&&a(c.id).now.push({...s(u,c),control:c})}for(let{cell:u}of(0,V.typedCellSites)(t)){let c=u.control;if(!ut(c))continue;let d=s(u,c);d.bound&&d.uid&&i.add(d.uid),typeof c.id=="string"&&c.id&&a(c.id).before.push(d)}let l=(u,c)=>{let d=u.filter(f=>f.cell===c);return d.length===1?d[0]:void 0};for(let[u,{before:c,now:d}]of o){let f=c.filter(D=>D.bound&&D.uid!==""&&!n.has(D.uid));if(f.length===0||d.length===0)continue;let m=[...c],p=D=>{let P=m.findIndex(D);return P<0?void 0:m.splice(P,1)[0]},g=d.filter(D=>!D.bound||D.uid===""?!0:p(P=>P.bound&&P.uid===D.uid)!==void 0?!1:!i.has(D.uid)).filter(D=>{let P=D.cell?l(c,D.cell):void 0;return!P||!l(d,D.cell)||!m.includes(P)?!0:(m.splice(m.indexOf(P),1),f.includes(P)&&D.uid!==P.uid&&rk(D.control)&&r.set(D.control,nk(P.uid)),!1)}),b=[],w=(D,P)=>{let x=D.uid===""?void 0:p(K=>K.uid===D.uid&&(!P||K.bound===D.bound));return x&&f.includes(x)&&b.push(x),x!==void 0},S=g.filter(D=>!w(D,!0)).filter(D=>!w(D,!1)&&rk(D.control)),O=f.filter(D=>m.includes(D));if(S.length===0||O.length===0&&b.length===0)continue;let k=[...O,...b],I=O.length===1&&S.length===1&&m.length===1?nk(O[0].uid):`the controls with id "${u}" cannot all be matched to those last synced \u2014 their cells do not tell them apart \u2014 and ${k.map(D=>`{${D.uid}}`).join(", ")} no longer ${k.length===1?"names":"name"} a control: which control held ${k.length===1?"that binding":"those bindings"} is ambiguous. Re-fetch the form; to drop a bound control, remove its customControl and push before removing the control`;for(let D of S)r.set(D.control,I)}return r}function mX(e){let t=(0,V.controlUniqueIds)(e),r=new Map;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=ut(i.control)?(0,V.controlUniqueId)(i.control):"";o&&!r.has(o)&&r.set(o,i.control)}let n=new Set;for(let[i,o]of t){let a=r.get(i);(a===void 0||yt(a)||o>1)&&n.add(i)}return n}function rk(e){return yt(e)||e.genPage===void 0&&Fi((0,V.effectiveClassId)(e))}function hX(e,t){let r=o=>(0,V.typedCellSites)(o).flatMap(({cell:a,pointer:s})=>{let l=a.control;if(!ut(l)||yt(l)||l.genPage!==void 0||!Fi((0,V.effectiveClassId)(l)))return[];let u=(0,V.controlUniqueId)(l);return u===""||Mi(o.bag,u).length===0?[{control:l,pointer:`${s}/control`}]:[]}),n=o=>`${String(o.id)}\0${(0,V.controlUniqueId)(o)}`,i=r(t).map(({control:o})=>n(o));return r(e).filter(({control:o})=>{let a=i.indexOf(n(o));return a<0?!0:(i.splice(a,1),!1)})}var gX="this control would keep the custom-control class with no binding (its customControl and uniqueid are gone): remove the binding from an unchanged copy \u2014 keep its uniqueid, and the native control comes back \u2014 or set classId to the column's native control";function nk(e){return`this control's uniqueid changed since it was last synced (it was {${e}}), and a binding is linked to its description by it: restore it (re-fetch the form), or remove the binding, push, then add the new one`}function yX(e){let t=typeof e.id=="string"?e.id.trim():"";return(0,V.normGuid)(t)||t.toLowerCase()}function Hu(e,t,r,n){let i=t.customControl,o=(0,V.controlUniqueId)(t),a=Mi(e.bag,o),s=r?mk(e,r).get(t):void 0;if(s!==void 0)return dn("pcf-binding-unique-id",s);let l=r?pX(r,o):void 0;if(l){let c=l.descriptions,d=c.length===1?ga(c[0]):void 0;if(d&&d.fieldName!==t.fieldName)return dn("pcf-binding-rebind",`the binding is filed for "${d.fieldName}": remove it, push, then bind the new column`);if(c.length===1&&a.length===1&&fn(c[0],a[0]))return tk(t,i,a[0]);let f=a.length===1?ga(a[0]):void 0;return d&&f&&f.fieldName===t.fieldName&&xy(i,d)&&xy(i,f)?{kind:"unchanged"}:dn("pcf-binding-edit-changed-description","the binding\u2019s description changed since it was last synced (edited in the bag, re-keyed or deleted): re-fetch the form before changing the binding")}if(a.length===0)return{kind:"new"};if(a.length>1)return dn("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");let u=tk(t,i,a[0]);return n&&(u.kind==="edit"||u.kind==="unchanged")?u.kind==="unchanged"?u:dn("pcf-binding-edit","this binding\u2019s description was never synced from the server (no baseline): changing it in place is not supported \u2014 remove customControl, push, then add the new one"):u}ce.planPcfBinding=Hu;function hk(e){return e.kind==="edit"&&(e.changed.length>0||e.added.length>0)}function bX(e){let t=n=>yt(n.control)&&(!n.control.id||!n.id||(0,V.authoredUniqueId)(n.control)===void 0);if(!(0,V.typedCellSites)(e).some(({cell:n})=>t(n)))return e;let r=JSON.parse(JSON.stringify(e));for(let{cell:n}of(0,V.typedCellSites)(r)){if(!t(n))continue;let i=n.control;i.id||(i.id=(0,Z2.newId)()),n.id||(n.id=(0,Z2.newId)()),(0,V.authoredUniqueId)(i)===void 0&&(0,V.setUniqueId)(i)}return r}ce.mintPcfIdentity=bX;function vX(e,t){let r=new Set,n=new Set;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=i.control;if(!yt(o)||!ut(o.customControl))continue;let a=o.customControl.name;if(typeof a!="string"||a===""||typeof o.fieldName!="string"||!o.fieldName)continue;let s=Hu(e,o,t,!0);s.kind==="new"?(r.add(a),n.add(o.fieldName)):hk(s)&&r.add(a)}return{controls:[...r],columns:[...n],...n.size>0&&(0,V.effectiveFormType)(e)==="QuickCreate"?{requireCreateEligibility:!0}:{}}}ce.customControlNeeds=vX;function wX(e,t,r){var n,i,o,a,s,l;let u=e.bag,c=new Map;for(let{cell:f,pointer:m}of(0,V.typedCellSites)(e)){let p=f.control;if(!yt(p)||!ut(p.customControl))continue;let h=(0,V.controlUniqueId)(p);h&&Mi(u,h).length>0&&c.set(p,{plan:Hu(e,p,t,!0),pointer:`${m}/control/customControl`})}let d=(0,V.descriptionsRegion)(u);if(d&&t){let f=(0,V.controlUniqueIds)(e),m=new Set,p=new Map;for(let{cell:h}of(0,V.typedCellSites)(e)){let g=ut(h.control)?(0,V.controlUniqueId)(h.control):"";g&&!p.has(g)&&p.set(g,h.control)}for(let{cell:h}of(0,V.typedCellSites)(t)){let g=h.control;if(!yt(g))continue;let b=(0,V.controlUniqueId)(g),w=Mi(t.bag,b),C=Mi(u,b);if(w.length!==1||C.length!==1||!fn(w[0],C[0])||!ga(C[0]))continue;let S=p.get(b);if(S&&!yt(S)){if(((n=f.get(b))!==null&&n!==void 0?n:0)>1)continue;let O=(o=(i=ga(C[0]))===null||i===void 0?void 0:i.nativeClass)!==null&&o!==void 0?o:"";S.classId=O.replace(/^\{|\}$/g,"").toUpperCase(),CX(S,"uniqueid"),m.add(b)}else!S&&!f.has(b)&&m.add(b)}m.size>0&&(d.node.c=dr(d.node.c).filter(h=>!(h?.n==="controlDescription"&&m.has((0,V.normGuid)((0,V.rawAttr)(h,"forControl"))))))}for(let{cell:f}of(0,V.typedCellSites)(e)){let m=f.control;if(!yt(m)||!ut(m.customControl))continue;Fi(m.classId)||(m.classId=V.CUSTOM_CONTROL_CLASS_ID);let p=(0,V.controlUniqueId)(m);if(!p){if((0,V.authoredUniqueId)(m)!==void 0)continue;p=(0,V.setUniqueId)(m)}let h=c.get(m);if(h){if(h.plan.kind==="refused")throw new oX.ValidationError("form",e.id,[(0,Ee.issue)(h.pointer,h.plan.rule,h.plan.message)]);h.plan.kind==="edit"&&EX(h.plan,m.customControl);continue}let g=r?.control(m.customControl.name),b=r?.column(e.entityLogicalName,m.fieldName),w=b?.kind==="found"?My(b.value):void 0;if(g?.kind!=="found"||!w)continue;d||(d={i:(0,V.embedAppendIndex)(u),node:{n:"controlDescriptions",a:[],c:[]}},u.c.push(d));let C=((l=(s=dr((a=m.bag)===null||a===void 0?void 0:a.a).find(O=>O[0]==="uniqueid"))===null||s===void 0?void 0:s[1])!==null&&l!==void 0?l:"").trim(),S=C.startsWith("{")?C:`{${p}}`;d.node.c.push(dk(S,m.fieldName,w,m.customControl,g.value))}}ce.reconcilePcfDescriptions=wX;function CX(e,t){ut(e.bag)&&(e.bag.a=dr(e.bag.a).filter(r=>r[0]!==t))}function EX(e,t){var r,n;let i=dr(e.description.c),o=i.findIndex(g=>(0,V.rawAttr)(g,"name")!==void 0),a=i.slice(0,o),s=i.slice(o),l=(r=t.parameters)!==null&&r!==void 0?r:{};for(let g of s)for(let b of(n=Bf(g))!==null&&n!==void 0?n:[])e.changed.includes(b.n)&&(b.c=[Fy(ju(e.stored.parameterTypes[b.n],l[b.n]))]);if(e.added.length===0&&e.removed.length===0)return;let u=g=>JSON.parse(JSON.stringify(g)),c=g=>{var b;let w=(0,V.rawAttr)(g,"formFactor");return w===void 0?null:(b=ik.get(w))!==null&&b!==void 0?b:null},d=(0,V.rawAttr)(a[0],"id"),f=(0,V.rawAttr)(s[0],"name"),m=qf(e.factors),p=m.defaults.map(g=>{let b=a.find(C=>c(C)===g);if(b)return b;let w=u(a[0]);return w.a=g===null?[["id",d]]:[["id",d],["formFactor",Wu[g]]],w}),h=m.named.map(g=>{let b=s.find(C=>c(C)===g);if(b)return b;let w=u(s[0]);return w.a=[["name",f],["formFactor",Wu[g]]],w});e.description.c=[...p,...h]}function AX(e){return(0,V.typedCellSites)(e).some(({cell:t})=>yt(t.control))}ce.mayCommitPcfState=AX;function SX(e,t){var r;let n=JSON.parse(JSON.stringify(e)),i=!1;for(let{cell:o}of(0,V.typedCellSites)(n)){let a=o.control;if(!yt(a))continue;let s=Vy(n,a);if(!s||s.fieldName!==a.fieldName)continue;let l=t(V.CUSTOM_CONTROL_CLASS_ID),u=dr((r=a.bag)===null||r===void 0?void 0:r.a).find(c=>c[0]==="classid");(!Fi(a.classId)||a.type!==l||u!==void 0&&!Fi(u[1])||!fn(a.customControl,s.binding))&&(Fi(a.classId)||(a.classId=V.CUSTOM_CONTROL_CLASS_ID),a.type=l,u&&!Fi(u[1])&&(u[1]=ak(V.CUSTOM_CONTROL_CLASS_ID)),a.customControl=JSON.parse(JSON.stringify(s.binding)),i=!0)}return i?n:e}ce.commitPcfState=SX;var NX=new Set(["name","parameters","formFactors"]);function _X(e,t,r){let n=[],i=(0,V.controlUniqueIds)(e);for(let{cell:o,pointer:a}of(0,V.typedCellSites)(e)){let s=o.control;yt(s)&&DX(e,s,`${a}/control`,i,n,t,r?.atPush===!0)}return t&&IX(e,t,n),n}ce.pcfBindingIssues=_X;function TX(e,t,r){let n=r.length;if(!ut(e))return r.push((0,Ee.issue)(t,"pcf-binding-shape","customControl must be an object")),!1;for(let i of Object.keys(e))NX.has(i)||r.push((0,Ee.issue)(`${t}/${i}`,"pcf-binding-unknown-key",`customControl has no "${i}"`));if((typeof e.name!="string"||e.name.trim()==="")&&r.push((0,Ee.issue)(`${t}/name`,"pcf-binding-shape","name must be the control's non-empty customcontrols name")),e.parameters!==void 0)if(!ut(e.parameters))r.push((0,Ee.issue)(`${t}/parameters`,"pcf-binding-shape","parameters must be an object"));else for(let[i,o]of Object.entries(e.parameters))typeof o=="string"||typeof o=="boolean"||typeof o=="number"&&Number.isFinite(o)||r.push((0,Ee.issue)(`${t}/parameters/${i}`,"pcf-binding-shape","a parameter must be a string, a finite number or a boolean"));if(e.formFactors!==void 0){let i=e.formFactors;Array.isArray(i)&&i.length>0&&i.every(a=>typeof a=="string"&&Ui.includes(a))&&new Set(i).size===i.length||r.push((0,Ee.issue)(`${t}/formFactors`,"pcf-binding-shape","formFactors must be distinct 'web', 'phone' and 'tablet', at least one"))}return r.length===n}function DX(e,t,r,n,i,o,a){var s;let l=`${r}/customControl`,u=TX(t.customControl,l,i);t.fieldName||i.push((0,Ee.issue)(l,"pcf-binding-unbound","a PCF binding needs a control bound to a column (fieldName)")),t.genPage!==void 0&&i.push((0,Ee.issue)(l,"pcf-binding-with-genpage","a control cannot embed a page and bind a PCF control")),Gy(e)||i.push((0,Ee.issue)(l,"pcf-binding-form-type","PCF bindings are supported on Main and Quick Create forms only (not Quick View or Card)")),t.classId!==void 0&&typeof t.classId!="string"&&i.push((0,Ee.issue)(`${r}/classId`,"pcf-binding-class-id","classId must be a string"));let c=(0,V.authoredUniqueId)(t),d=(0,V.controlUniqueId)(t);if(c!==void 0&&!d?i.push((0,Ee.issue)(`${r}/bag`,"pcf-binding-unique-id","the control's uniqueid must be a GUID")):d&&((s=n.get(d))!==null&&s!==void 0?s:0)>1&&i.push((0,Ee.issue)(`${r}/bag`,"pcf-binding-unique-id","another control carries the same uniqueid")),!u)return;let f=Hu(e,t,o,a);f.kind==="refused"&&i.push((0,Ee.issue)(l,f.rule,f.message))}function IX(e,t,r){var n;let i=new Map,o=mk(e,t);for(let{cell:l,pointer:u}of(0,V.typedCellSites)(e)){let c=ut(l.control)?(0,V.controlUniqueId)(l.control):"";if(c&&!i.has(c)&&i.set(c,{control:l.control,pointer:`${u}/control`}),ut(l.control)&&!yt(l.control)){let d=o.get(l.control);d!==void 0&&r.push((0,Ee.issue)(`${u}/control`,"pcf-binding-unique-id",d))}}let a=(0,V.controlUniqueIds)(e);for(let{cell:l}of(0,V.typedCellSites)(t)){if(!yt(l.control))continue;let u=(0,V.controlUniqueId)(l.control),c=i.get(u);!c||yt(c.control)||(((n=a.get(u))!==null&&n!==void 0?n:0)>1?r.push((0,Ee.issue)(c.pointer,"pcf-binding-unique-id","another control carries this binding\u2019s uniqueid; removing the binding would delete its description too")):fn(Mi(t.bag,u),Mi(e.bag,u))?c.control.fieldName!==l.control.fieldName&&r.push((0,Ee.issue)(c.pointer,"pcf-binding-rebind","remove the binding, push, then bind the new column")):r.push((0,Ee.issue)(c.pointer,"pcf-binding-removed-changed","the binding changed since it was last pushed; remove it from an unchanged copy (re-fetch)")))}let s=new Set(r.map(l=>l.pointer));for(let{pointer:l}of hX(e,t))s.has(l)||r.push((0,Ee.issue)(l,"pcf-binding-unique-id",gX))}var OX=new Set(["Form.Card"]),PX="MscrmControls.ModelForm.ModelFormControl";function gk(e,t){var r;if(e.hasDataset||e.hasGroups)return"it has a data-set or groups";if(!e.isBound)return"its first property is not bound to a column";let n=e.properties;if(n.filter(s=>s.usage==="bound").length!==1)return"it has more than one bound property";let i=n.map(s=>s.name);if(i.some(s=>!s)||new Set(i).size!==i.length)return"a property has no name, or two share one";let o=i.find(s=>!uk(s));if(o!==void 0)return`the property name "${o}" cannot be written as an element`;if(t===PX||n.some(s=>s.defaultType!==void 0&&OX.has(s.defaultType)))return"a property needs a special encoding";if(n.some(s=>s.usage==="output"&&s.defaultValue!==null&&s.defaultValue!==""))return"an output property has a default";let a=n.find(s=>s.usage==="input"&&!By(s.defaultType));return a?`input "${a.name}" has a type the property editor does not write as text (${(r=a.defaultType)!==null&&r!==void 0?r:"none"})`:void 0}function RX(e){return e.ofType!==null?[e.ofType]:e.ofTypeGroup}function yk(e,t,r=e.defaultType){if(r==="Enum")return e.enumValues.some(o=>o.value===String(t))?void 0:`must be one of ${e.enumValues.map(o=>`"${o.value}"`).join(", ")}`;let n=r!==void 0?Uy.get(r):void 0;if(n){let o=typeof t=="boolean"?void 0:ck(t);return o===void 0||o<n.min||o>n.max?`must be a number from ${n.min.toFixed(n.digits)} through ${n.max.toFixed(n.digits)}`:void 0}if(r!==void 0&&sk.has(r))return t===!0||t===!1||t==="true"||t==="false"?void 0:"must be true or false";let i=r!==void 0?lX.get(r):void 0;return i!==void 0&&String(t).length>i?`must be at most ${i} characters`:e.required&&String(t)===""?"is required":void 0}function kX(e,t,r){var n,i,o,a;let s={issues:[]},l=s.issues;for(let{cell:u,pointer:c}of(0,V.typedCellSites)(e)){let d=u.control;if(!yt(d)||!d.fieldName)continue;let f=d.customControl;if(!ut(f)||typeof f.name!="string")continue;let m=`${c}/control/customControl`,p=Hu(e,d,r,!0);if(p.kind==="edit"){hk(p)&&xX(p,f,m,t,s);continue}if(p.kind!=="new")continue;let h=t?.control(f.name),g=t?.column((n=e.entityLogicalName)!==null&&n!==void 0?n:"",d.fieldName);if(!h||h.kind==="unavailable"){(i=s.unavailable)!==null&&i!==void 0||(s.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${f.name}" could not be read`,...h?.kind==="unavailable"?{cause:h.error}:{}});continue}if(h.kind!=="found"){l.push((0,Ee.issue)(`${m}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${f.name}" (${h.kind})`));continue}if(!g||g.kind==="unavailable"){(o=s.unavailable)!==null&&o!==void 0||(s.unavailable={code:"PCF_COLUMN_UNAVAILABLE",message:`the column "${d.fieldName}" could not be read`,...g?.kind==="unavailable"?{cause:g.error}:{}});continue}let b=gk(h.value,f.name);if(b){l.push((0,Ee.issue)(`${m}/name`,"pcf-binding-unsupported-control",`"${f.name}" is not supported: ${b}`));continue}let w=h.value.properties.find(x=>x.isPrimary),C=g.kind==="found"?g.value:void 0,S=C?(a=(0,aX.manifestTypesForColumn)(C.attributeTypeName,C.format,C.formatName))!==null&&a!==void 0?a:[]:[];C!==void 0&&!C.isPrimaryId&&C.isValidForForm&&My(C)!==void 0&&RX(w).some(x=>S.includes(x))?(0,V.effectiveFormType)(e)==="QuickCreate"&&C?.isValidForCreate!==!0&&l.push((0,Ee.issue)(m,"pcf-binding-quick-create-column",`"${d.fieldName}" cannot be set when a record is created, so a Quick Create form cannot bind it`)):l.push((0,Ee.issue)(m,"pcf-binding-incompatible-column",`"${f.name}" cannot be bound to "${d.fieldName}"`));let k=new Map(h.value.properties.filter(x=>x.usage==="input").map(x=>[x.name,x])),I=ut(f.parameters)?f.parameters:{};for(let[x,K]of Object.entries(I)){let Oe=k.get(x);if(!Oe){l.push((0,Ee.issue)(`${m}/parameters/${x}`,"pcf-binding-unknown-parameter",`"${f.name}" has no input "${x}"`));continue}let Vt=yk(Oe,K);Vt&&l.push((0,Ee.issue)(`${m}/parameters/${x}`,"pcf-binding-parameter-value",`"${x}" ${Vt}`))}for(let x of k.values())x.required&&!zu(I,x.name)&&!x.defaultValue&&l.push((0,Ee.issue)(`${m}/parameters`,"pcf-binding-missing-parameter",`"${x.name}" is required`));let D=qy(h.value),P=Array.isArray(f.formFactors)?f.formFactors:void 0;(P?P.some(x=>!D.has(x)):D.size===0)&&l.push((0,Ee.issue)(`${m}/formFactors`,"pcf-binding-form-factor",`"${f.name}" is available on ${D.size===0?"no form factor":[...D].join(", ")}`))}return s}ce.pcfReadIssues=kX;function LX(e,t){return t===void 0||!By(t)?!1:e.ofType!==null?e.ofType===t:e.ofTypeGroup.includes(t)}function $X(e,t,r){var n,i;let o=gk(e,t);if(o)return`it is no longer supported (${o})`;let a=e.properties.find(d=>d.isPrimary);if(a?.name!==r.boundProperty)return`its bound property is now "${(n=a?.name)!==null&&n!==void 0?n:"none"}", not "${r.boundProperty}"`;let s=(i=r.binding.parameters)!==null&&i!==void 0?i:{},l=new Set(e.properties.filter(d=>d.usage==="input").map(d=>d.name)),u=Object.keys(s).find(d=>!l.has(d));if(u!==void 0)return`"${u}" is no longer one of its inputs`;let c=e.properties.find(d=>d.usage==="input"&&d.required&&!d.defaultValue&&!zu(s,d.name));return c?`it now requires "${c.name}", which the binding does not store`:void 0}function xX(e,t,r,n,i){var o,a,s;let l=i.issues,u=n?.control(t.name);if(!u||u.kind==="unavailable"){(o=i.unavailable)!==null&&o!==void 0||(i.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${t.name}" could not be read`,...u?.kind==="unavailable"?{cause:u.error}:{}});return}if(u.kind!=="found"){l.push((0,Ee.issue)(`${r}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${t.name}" (${u.kind})`));return}let c=$X(u.value,t.name,e.stored);if(c){l.push((0,Ee.issue)(r,"pcf-binding-edit-manifest-changed",`"${t.name}" changed since this binding was written: ${c} \u2014 remove the binding, push, then add it`));return}let d=new Map(u.value.properties.filter(h=>h.usage==="input").map(h=>[h.name,h])),f=l.length;for(let h of Object.keys((a=e.stored.binding.parameters)!==null&&a!==void 0?a:{})){let g=e.stored.parameterTypes[h];LX(d.get(h),g)||l.push((0,Ee.issue)(`${r}/parameters/${h}`,"pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which "${t.name}" does not take for it now: remove the binding, push, then add it`))}if(l.length>f)return;let m=(s=t.parameters)!==null&&s!==void 0?s:{};for(let h of e.changed){let g=yk(d.get(h),m[h],e.stored.parameterTypes[h]);g&&l.push((0,Ee.issue)(`${r}/parameters/${h}`,"pcf-binding-parameter-value",`"${h}" ${g}`))}let p=qy(u.value);e.added.some(h=>!p.has(h))&&l.push((0,Ee.issue)(`${r}/formFactors`,"pcf-binding-form-factor",`"${t.name}" is available on ${p.size===0?"no form factor":[...p].join(", ")}`))}});var Lk=v(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.classIdForAttributeType=kr.QUICK_VIEW_CLASS_ID=kr.NOTES_CLASS_ID=kr.SUBGRID_CLASS_ID=kr.formRegistration=kr.FormAdapter=void 0;var Bi=(ht(),Br(C_)),vk=(st(),Br(E_)),FX=(It(),Br(S_)),bt=(ue(),Br(A_)),rt=(oa(),Br(N_)),MX=(wy(),Br(z2)),UX=(H2(),Br(j2)),vt=so(),wk=Qr(),Rr=rn(),BX=_g(),Ks=pt(),qX=$y(),er=Dd(),ii=bk(),Hs=Q(),Jy=le(),Wy=lo(),_k=Jo(),VX={[bt.FormType.Main]:"Main",[bt.FormType.QuickCreate]:"QuickCreate",[bt.FormType.QuickViewForm]:"QuickView",[bt.FormType.Card]:"Card"},Vf={Main:bt.FormType.Main,QuickCreate:bt.FormType.QuickCreate,QuickView:bt.FormType.QuickViewForm,Card:bt.FormType.Card},GX=new Map(Object.entries(rt.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function Yy(e){var t;return e&&(t=GX.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function Ku(e){return e.getAllProperties().map(t=>[t.key,t.value])}function ya(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function Tk(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function Qy(e,t){var r,n;let i=Tk(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(r=o.find(s=>ya(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return a&&(n=ya(a).get("description"))!==null&&n!==void 0?n:""}function WX(e){let t=Tk(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 o=n.getAllChildren()[0],a=o?o.getNodeName():"";a.charAt(0)==="<"&&(a=a.substring(1)),r[i]=a}return r}function Dk(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function zy(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function Ju(e){return String(e??"").replace(/[{}]/g,"")}function jy(e){return`{${Ju(e)}}`}function Hy(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function Wf(e,t,r){let n=e.getAllChildren(),i=n.findIndex(u=>u.getNodeName()===t),o=[];if(n.forEach((u,c)=>{c!==i&&o.push({i:c,node:(0,vt.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:Ku(e),c:o}};let a=n[i],s=[],l=[];return a.getAllChildren().forEach((u,c)=>{u.getNodeName()===r?s.push(u):l.push({i:c,node:(0,vt.rawFromNode)(u)})}),{modeled:s,bag:{a:Ku(e),c:o,w:{n:a.getNodeName(),a:Ku(a),c:l}}}}function Ik(e,t,r){let n=[],i=[];return e.getAllChildren().forEach((o,a)=>{o.getNodeName()===t&&(!r||n.length===0)?n.push(o):i.push({i:a,node:(0,vt.rawFromNode)(o)})}),{modeled:n,bag:{a:Ku(e),c:i}}}function Ck(e,t){let{modeled:r,bag:n}=Wf(e,"tabs","tab");return{tabs:r.map(i=>zX(i,t)),bag:n}}function zX(e,t){var r,n;let i=ya(e),{modeled:o,bag:a}=Wf(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:Qy(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:o.map(s=>jX(s,t)),bag:a}}function jX(e,t){let r=ya(e),{modeled:n,bag:i}=Wf(e,"sections","section");return{width:r.get("width"),sections:n.map(o=>HX(o,t)),bag:i}}function HX(e,t){var r,n,i;let o=ya(e),{modeled:a,bag:s}=Wf(e,"rows","row");return{id:(r=o.get("id"))!==null&&r!==void 0?r:"",name:(n=o.get("name"))!==null&&n!==void 0?n:"",label:Qy(e,t),visible:o.has("visible")?o.get("visible")==="true":!0,showLabel:o.get("showlabel")==="true",columns:Dk((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(l=>KX(l,t)),bag:s}}function KX(e,t){let{modeled:r,bag:n}=Ik(e,"cell",!1);return{cells:r.map(i=>JX(i,t)),bag:n}}function JX(e,t){var r;let n=ya(e),{modeled:i,bag:o}=Ik(e,"control",!0),a=Qy(e,t),s=n.get("showlabel")==="true",l=i[0]?YX(i[0],a,s):null;return{id:(r=n.get("id"))!==null&&r!==void 0?r:"",visible:n.has("visible")?n.get("visible")==="true":!0,colspan:Hy(n.get("colspan"),1),rowspan:Hy(n.get("rowspan"),1),control:l,bag:o}}function YX(e,t,r){var n,i;let o=ya(e),a=Ju((n=o.get("classid"))!==null&&n!==void 0?n:""),s=o.get("datafieldname");return{id:(i=o.get("id"))!==null&&i!==void 0?i:"",classId:a,fieldName:s||null,type:Yy(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:r,parameters:WX(e),bag:{a:Ku(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,vt.rawFromNode)(l)}))}}}function _o(e){return e.a.length===0&&e.c.length===0&&!e.w}function Ok(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function ba(e,t){var r;let n=new Set(e.a.map(a=>a[0])),i=_o(e),o=[];for(let a of t)if(n.has(a.key)){let s=(r=Ok(e,a.key))!==null&&r!==void 0?r:"";a.matches(s)||o.push([a.key,a.render()])}else i?o.push([a.key,a.render()]):a.matches(a.absentDefault)||o.push([a.key,a.render()]);return(0,vt.mergeAttrs)(e.a,o)}var So=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),No=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),Ek=(e,t,r=1)=>({key:e,matches:n=>Hy(n,r)===t,render:()=>String(t),absentDefault:String(r)});function Xy(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function Ky(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>{var r;return{n:(0,Jy.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${(r=e[t])!==null&&r!==void 0?r:""}`,a:[],c:[]}]}})}}function QX(e,t){var r,n;let i=e.c.find(a=>a.n==="label"&&a.a.some(s=>s[0]==="languagecode"&&s[1]===String(t))),o=i??e.c.find(a=>a.n==="label");return(n=(r=o?.a.find(a=>a[0]==="description"))===null||r===void 0?void 0:r[1])!==null&&n!==void 0?n:""}function XX(e,t,r){let n=!1,i=e.c.map(o=>o.n!=="label"||!o.a.some(s=>s[0]==="languagecode"&&s[1]===String(r))?o:(n=!0,{...o,a:o.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 Zy(e,t,r){let n=e.c.findIndex(o=>o.node.n==="labels");if(n<0){if(!t||_o(e))return e;let a=e.c.some(s=>s.i===0)?e.c.map(s=>({...s,i:s.i+1})):e.c;return{...e,c:[{i:0,node:Xy(t,r)},...a]}}if(QX(e.c[n].node,r)===t)return e;let i=XX(e.c[n].node,t,r);return{...e,c:e.c.map((o,a)=>a===n?{...o,node:i}:o)}}function ZX(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],o=i?i.n:"";o.charAt(0)==="<"&&(o=o.substring(1)),t[n]=o}return t}function eZ(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function tZ(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function rZ(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||_o(e))return e;let i=e.c.reduce((o,a)=>a.i>o?a.i:o,-1);return{...e,c:[...e.c,{i:i+1,node:Ky(t)}]}}if(eZ(ZX(e.c[r].node),t))return e;let n=Ky(t);return{...e,c:e.c.map((i,o)=>o===r?{...i,node:n}:i)}}function zf(e,t,r,n){if(e.w){let a={n:e.w.n,a:e.w.a.map(s=>[s[0],s[1]]),c:(0,vt.spliceChildren)(e.w.c,r)};return(0,vt.spliceChildren)(e.c,[a])}let i=n(),o={n:t,a:[],c:r};return e.c.length===0?[...i,o]:(0,vt.spliceChildren)(e.c,[...i,o])}function nZ(e,t){let r=e.tabs.map(n=>iZ(n,t));return{n:"form",a:ba(e.bag,[]),c:e.tabs.length===0&&_o(e.bag)?[]:zf(e.bag,"tabs",r,()=>[])}}function Pk(e,t,r){return t&&!e.c.some(n=>n.node.n==="labels")?[Xy(t,r)]:[]}function iZ(e,t){let r=[So("id",e.id),So("name",e.name),No("expanded",e.expanded),No("visible",e.visible,!0)],n=e.columns.map(o=>oZ(o,t)),i=Zy(e.bag,e.label,t);return{n:"tab",a:ba(i,r),c:zf(i,"columns",n,()=>Pk(i,e.label,t))}}function oZ(e,t){let r=e.width!==void 0?[So("width",e.width)]:[],n=e.sections.map(i=>aZ(i,t));return{n:"column",a:ba(e.bag,r),c:zf(e.bag,"sections",n,()=>[])}}function aZ(e,t){let r=[So("id",e.id),So("name",e.name),No("showlabel",e.showLabel),No("visible",e.visible,!0),{key:"columns",matches:o=>Dk(o)===e.columns,render:()=>zy(e.columns),absentDefault:zy(1)}],n=e.rows.map(o=>sZ(o,t)),i=Zy(e.bag,e.label,t);return{n:"section",a:ba(i,r),c:zf(i,"rows",n,()=>Pk(i,e.label,t))}}function sZ(e,t){let r=e.cells.map(n=>lZ(n,t));return{n:"row",a:ba(e.bag,[]),c:_o(e.bag)?r:(0,vt.assembleChildren)(e.bag,r)}}function lZ(e,t){let r=e.control?e.control.showLabel:Ok(e.bag,"showlabel")==="true",n=[So("id",e.id),No("showlabel",r),No("visible",e.visible,!0),Ek("colspan",e.colspan),Ek("rowspan",e.rowspan)],i=e.control?[uZ(e.control)]:[],o;if(_o(e.bag))o=[...e.control&&e.control.label?[Xy(e.control.label,t)]:[],...i];else{let a=e.control?Zy(e.bag,e.control.label,t):e.bag;o=(0,vt.assembleChildren)(a,i)}return{n:"cell",a:ba(e.bag,n),c:o}}function uZ(e){let t=[So("id",e.id),{key:"classid",matches:i=>Ju(i)===e.classId,render:()=>jy(e.classId||String(rt.ControlClassId.TextboxControl)),absentDefault:""}];e.fieldName!==null&&t.push(So("datafieldname",e.fieldName)),t.push(No("disabled",e.isReadOnly)),t.push(No("isrequired",e.isRequired));let r=e.fieldName===null?tZ(e.bag,"datafieldname"):e.bag,n;return _o(r)?n=Object.keys(e.parameters).length>0?[Ky(e.parameters)]:[]:n=(0,vt.assembleChildren)(rZ(r,e.parameters),[]),{n:"control",a:ba(r,t),c:n}}var cZ={make:(e,t)=>new FX.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function Ak(e,t,r,n){(0,Wy.installDomShim)();let i=fZ(e,r);(0,er.reconcileEmbedDescriptions)(i,n),(0,ii.reconcilePcfDescriptions)(i,n,r?.pcf);let o=(0,vt.rebuildRaw)(nZ(i,t),cZ,null);return new UX.SerializationService(t).serializeFormXmlNode(o)}function dZ(e){return JSON.parse(JSON.stringify(e))}function fZ(e,t){let r=dZ(e);r.bag||(r.bag=(0,vt.emptyBag)()),r.tabs||(r.tabs=[]),wZ(r.bag),t&&pZ(r,t);for(let n of r.tabs)mZ(n);return r}function pZ(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";eb(e,i=>{let o=i.fieldName,a=i;if(!o||a.label!==void 0&&a.classId!==void 0)return;let s=t.resolveField(n,o);s&&(a.label===void 0&&s.displayName&&(a.label=s.displayName),a.classId===void 0&&s.attributeType&&(a.classId=kk(s.attributeType)))})}function Sk(e){let t=[];return eb(e,r=>t.push(r)),t}function eb(e,t){var r,n,i,o,a;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(o=u.rows)!==null&&o!==void 0?o:[])for(let d of(a=c.cells)!==null&&a!==void 0?a:[])d.control&&t(d.control)}function mZ(e){e.id||(e.id=Bi.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)hZ(t);e.bag||(e.bag=(0,vt.emptyBag)())}function hZ(e){e.sections||(e.sections=[]);for(let t of e.sections)gZ(t);e.bag||(e.bag=(0,vt.emptyBag)()),e.width===void 0&&_o(e.bag)&&(e.width="100%")}function gZ(e){e.id||(e.id=Bi.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)yZ(t);e.bag||(e.bag=(0,vt.emptyBag)())}function yZ(e){e.cells||(e.cells=[]);for(let t of e.cells)bZ(t);e.bag||(e.bag=(0,vt.emptyBag)())}function bZ(e){(0,er.hasGenPage)(e.control)&&(0,er.applyEmbedCellDefaults)(e),e.id||(e.id=Bi.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&&vZ(e.control),e.bag||(e.bag=(0,vt.emptyBag)())}function vZ(e){var t;(0,er.hasGenPage)(e)&&(0,er.applyEmbedControlDefaults)(e),e.id||(e.id=Bi.Guid.NewGuid()),(e.classId===void 0||e.classId===null)&&(e.classId=String(rt.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":Yy(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,Jy.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,vt.emptyBag)())}function wZ(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 o of i.c)o.n==="Handler"&&!Nk(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",jy(Bi.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!Nk(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",jy(Bi.Guid.NewGuid())])}}var Gf=class{constructor(t=_k.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,o;let{tabs:a,bag:s}=Ck(t,this.lcid),l={id:t.formId?t.formId.guidString:"",name:(n=t.formName)!==null&&n!==void 0?n:"",entityLogicalName:(i=t.entityName)!==null&&i!==void 0?i:"",formType:(o=VX[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:a,bag:s};return(0,er.projectGenPageEmbeds)(l),(0,ii.projectPcfBindings)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:Ak(t,this.lcid),formid:t.id||(0,Ks.newId)(),objecttypecode:t.entityLogicalName,type:Vf[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:bt.FormPresentation.AirForm,formactivationstate:t.status==="Active"?bt.FormActivationState.Active:bt.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,o,a,s,l;let u=t,c=(r=u.formxml)!==null&&r!==void 0?r:"",d={formxml:c,formid:(n=u.formid)!==null&&n!==void 0?n:(0,Ks.newId)(),objecttypecode:(i=u.objecttypecode)!==null&&i!==void 0?i:"",type:u.type,name:(o=u.name)!==null&&o!==void 0?o:"",uniquename:(a=u.uniquename)!==null&&a!==void 0?a:"",description:(s=u.description)!==null&&s!==void 0?s:"",formpresentation:u.formpresentation,formactivationstate:u.formactivationstate};(0,Wy.installDomShim)();let f=vk.ScriptUtilities.ParseXml(c),m=CZ(f),p=this.deserializeDocument(d,f);return EZ(this.toArtifact(p,(l=u.description)!==null&&l!==void 0?l:void 0),m)}toApiPayload(t,r,n){let i=(0,er.genPageEmbedIssues)(t);if(i.length>0)throw new Hs.ValidationError("form",t.id,i);let o=(0,ii.pcfBindingIssues)(t,r,{atPush:!0});if(o.length>0)throw new Hs.ValidationError("form",t.id,o);let a=(0,ii.pcfReadIssues)(t,n?.pcf,r);if(a.unavailable)throw(0,Hs.attachCause)(new Hs.SdkError(a.unavailable.code,a.unavailable.message),a.unavailable.cause);if(a.issues.length>0)throw new Hs.ValidationError("form",t.id,a.issues);return{formxml:Ak(t,this.lcid,n,r),name:t.name,type:Vf[t.formType],objecttypecode:t.entityLogicalName,...t.description!==void 0?{description:t.description}:{}}}metadataNeeds(t){let r=t.entityLogicalName;if(!r)return[];let n=new Map;return eb(t,i=>{var o;let a=i.fieldName,s=i;if(!a||s.label!==void 0&&s.classId!==void 0)return;let l=(o=n.get(a))!==null&&o!==void 0?o:{entityLogicalName:r,fieldName:a};s.label===void 0&&(l.needsLabel=!0),n.set(a,l)}),[...n.values()]}customControlNeeds(t,r){var n;return{entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",...(0,ii.customControlNeeds)(t,r)}}createDefault(t){var r,n,i,o,a,s,l,u,c,d,f,m;let p=[...(0,er.genPageEmbedIssues)(t),...(0,ii.pcfBindingIssues)(t)];if(p.length>0)throw new Hs.ValidationError("form",t.id||"(new)",p);let h=t.tabs&&t.tabs.length>0?void 0:RZ(this.lcid),g=h!==void 0?h:t.tabs.map(C=>AZ(C,this.lcid)).join(""),b=this.deserialize({formxml:`<form><tabs>${g}</tabs></form>`,formid:t.id||(0,Ks.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:Vf[(n=t.formType)!==null&&n!==void 0?n:"Main"],name:(i=t.name)!==null&&i!==void 0?i:"New Form",uniquename:(o=t.name)!==null&&o!==void 0?o:"New Form",description:(a=t.description)!==null&&a!==void 0?a:"",formpresentation:bt.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?bt.FormActivationState.Active:bt.FormActivationState.InActive});(l=b.displayCondition)===null||l===void 0||l.removeProperty(bt.ElementProperties.Order);let w=this.toArtifact(b,t.description);if(t.tabs&&t.tabs.length>0){let C=Sk(t);Sk(w).forEach((S,O)=>{C[O]&&C[O].label===void 0&&delete S.label,C[O]&&C[O].genPage!==void 0&&(S.genPage=JSON.parse(JSON.stringify(C[O].genPage))),C[O]&&C[O].customControl!==void 0&&(S.customControl=JSON.parse(JSON.stringify(C[O].customControl)))})}return{id:(u=t.id)!==null&&u!==void 0?u:w.id,name:(c=t.name)!==null&&c!==void 0?c:"New Form",entityLogicalName:(d=t.entityLogicalName)!==null&&d!==void 0?d:"",formType:(f=t.formType)!==null&&f!==void 0?f:"Main",status:(m=t.status)!==null&&m!==void 0?m:"Active",...t.description!==void 0?{description:t.description}:{},tabs:w.tabs,bag:w.bag}}assignMissingIds(t){return(0,Ks.assignMissingIds)(t)}completeAsStored(t,r){return(0,qX.completeRecordAsStored)(t,r,this.lcid)}normalize(t){return(0,ii.mintPcfIdentity)((0,er.mintEmbedIdentity)(t))}committed(t,r){var n,i,o,a,s,l;let u=r?.formxml;if(typeof u!="string"||!((0,er.mayCommitEmbedState)(t)||(0,ii.mayCommitPcfState)(t)))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,Ks.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:Vf[(i=t.formType)!==null&&i!==void 0?i:"Main"],name:(o=t.name)!==null&&o!==void 0?o:"",uniquename:(a=t.name)!==null&&a!==void 0?a:"",description:(s=t.description)!==null&&s!==void 0?s:"",formpresentation:bt.FormPresentation.AirForm,formactivationstate:bt.FormActivationState.Active}),{bag:d}=Ck(c,this.lcid),f=(0,ii.commitPcfState)((0,er.commitEmbedState)(t,(l=(0,er.descriptionsRegion)(d))===null||l===void 0?void 0:l.node),Yy);return{artifact:f,baseline:f}}validate(t){return qZ(t)}deserialize(t){return(0,Wy.installDomShim)(),this.deserializeDocument(t,vk.ScriptUtilities.ParseXml(t.formxml))}deserializeDocument(t,r){let n=new MX.DeserializationService(this.lcid).deSerializeFormXml(r,new Bi.Guid(t.formid),t.objecttypecode,bt.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===bt.FormActivationState.InActive?"Inactive":"Active"}};kr.FormAdapter=Gf;var Rk=["header","footer","DisplayConditions"];function CZ(e){var t;let r=e?.getElementsByTagName("form")[0],n=new Set;for(let i=(t=r?.firstChild)!==null&&t!==void 0?t:null;i;i=i.nextSibling)i.nodeType===1&&Rk.includes(i.nodeName)&&n.add(i.nodeName);return n}function EZ(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=Rk.filter(o=>!t.has(o)),i=e.bag.c.filter(o=>{var a;return n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>o.i);return i.length>0&&(e.bag.c=e.bag.c.filter(o=>{var a;return!n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>({...o,i:o.i-i.filter(a=>a<o.i).length}))),e}function Rn(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function tb(e,t){return e?`<labels><label description="${Rn(e)}" languagecode="${t}" /></labels>`:""}function rb(e){return e&&e.length>0?Ju(e):(0,Ks.newId)()}function AZ(e,t){var r,n,i,o;let a=(r=e.columns)!==null&&r!==void 0?r:[],s=(a.length>0?a:[PZ()]).map(l=>SZ(l,t)).join("");return`<tab id="{${Rn(rb(e.id))}}" name="${Rn((n=e.name)!==null&&n!==void 0?n:"")}" expanded="${(i=e.expanded)!==null&&i!==void 0?i:!0}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}">${tb(e.label,t)}<columns>${s}</columns></tab>`}function SZ(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(o=>NZ(o,t)).join("");return`<column width="${Rn((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function NZ(e,t){var r,n,i,o,a;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>_Z(l,t)).join("");return`<section id="{${Rn(rb(e.id))}}" name="${Rn((n=e.name)!==null&&n!==void 0?n:"")}" showlabel="${(i=e.showLabel)!==null&&i!==void 0?i:!1}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}" columns="${zy((a=e.columns)!==null&&a!==void 0?a:1)}">${tb(e.label,t)}<rows>${s}</rows></section>`}function _Z(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>TZ(n,t)).join("")}</row>`}function TZ(e,t){var r,n,i,o,a;let s=DZ(e),l=s.control,u=l?tb((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?IZ(l):"";return`<cell id="{${Rn(rb(s.id))}}" showlabel="${l?(n=l.showLabel)!==null&&n!==void 0?n:!0:!1}" visible="${(i=s.visible)!==null&&i!==void 0?i:!0}" colspan="${(o=s.colspan)!==null&&o!==void 0?o:1}" rowspan="${(a=s.rowspan)!==null&&a!==void 0?a:1}">${u}${c}</cell>`}function DZ(e){if(!(0,er.hasGenPage)(e.control))return e;let t={...e.control};(0,er.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,er.applyEmbedCellDefaults)(r),r}function IZ(e){var t,r,n;let i=e.fieldName?` datafieldname="${Rn(e.fieldName)}"`:"",o=OZ(e.parameters),a=e.classId?Ju(e.classId):String(rt.ControlClassId.TextboxControl);return`<control id="${Rn((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Rn(a)}}"${i} disabled="${(r=e.isReadOnly)!==null&&r!==void 0?r:!1}" isrequired="${(n=e.isRequired)!==null&&n!==void 0?n:!1}">${o}</control>`}function OZ(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,Jy.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Rn(e[n])}</${n}>`).join("")}</parameters>`)}function PZ(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function RZ(e){return`<tab id="{${Bi.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${Bi.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 kZ(e=_k.DEFAULT_LCID){return{adapter:new Gf(e),api:BX.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,wk.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,wk.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}kr.formRegistration=kZ;var LZ=new Set(["id","name","label","expanded","visible","columns","bag"]),$Z=new Set(["id","width","sections","bag"]),xZ=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),FZ=new Set(["id","cells","bag"]),MZ=new Set(["id","visible","colspan","rowspan","control","bag"]),UZ=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","customControl","bag"]),BZ={elsewhere:{isReadOnly:"control",isRequired:"control",fieldName:"control",classId:"control",label:"control",showLabel:"control",parameters:"control"},unsupported:{createOnly:"FormXml has no create-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled.",updateOnly:"FormXml has no update-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled."}};function qZ(e){let t=[];return(0,Rr.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let o=`/tabs/${i}`;(0,Rr.rejectUnknownKeys)(n,LZ,o,"tab",t),(0,Rr.childObjects)(n,"columns",o,"column",t).forEach(({node:s,index:l})=>{let u=`${o}/columns/${l}`;(0,Rr.rejectUnknownKeys)(s,$Z,u,"column",t),(0,Rr.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:f})=>{let m=`${u}/sections/${f}`;(0,Rr.rejectUnknownKeys)(d,xZ,m,"section",t),(0,Rr.childObjects)(d,"rows",m,"row",t).forEach(({node:h,index:g})=>{let b=`${m}/rows/${g}`;(0,Rr.rejectUnknownKeys)(h,FZ,b,"row",t),(0,Rr.childObjects)(h,"cells",b,"cell",t).forEach(({node:C,index:S})=>{let O=`${b}/cells/${S}`;(0,Rr.rejectUnknownKeys)(C,MZ,O,"cell",t,BZ);let k=C.control;k!=null&&!(0,Rr.isJsonObject)(k)?t.push((0,Rr.issue)(`${O}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof k}`)):(0,Rr.isJsonObject)(k)&&(0,Rr.rejectUnknownKeys)(k,UZ,`${O}/control`,"control",t)})})})})}),t.push(...(0,er.genPageEmbedIssues)(e)),t.push(...(0,ii.pcfBindingIssues)(e)),t}kr.SUBGRID_CLASS_ID=rt.ControlClassId.SubgridControl;kr.NOTES_CLASS_ID=rt.ControlClassId.TimelineControl;kr.QUICK_VIEW_CLASS_ID=rt.ControlClassId.QuickViewControl;var VZ={Lookup:String(rt.ControlClassId.LookupControl),Customer:String(rt.ControlClassId.LookupControl),Owner:String(rt.ControlClassId.LookupControl),PartyList:String(rt.ControlClassId.PartyListControl),Boolean:String(rt.ControlClassId.BooleanControl),DateTime:String(rt.ControlClassId.DateTimeControl),Decimal:String(rt.ControlClassId.DecimalControl),Double:String(rt.ControlClassId.FloatingNumberControl),Money:String(rt.ControlClassId.CurrencyControl),Integer:String(rt.ControlClassId.IntegerControl),BigInt:String(rt.ControlClassId.IntegerControl),Memo:String(rt.ControlClassId.TextAreaControl),String:String(rt.ControlClassId.TextboxControl)},GZ="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function kk(e){return e==="Picklist"||e==="State"||e==="Status"?GZ:e&&VZ[e]||String(rt.ControlClassId.TextboxControl)}kr.classIdForAttributeType=kk;function Nk(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var nb=v(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.viewApi=Js.findDefaultViews=void 0;var Mk=Lt(),fr=ye(),kn=le(),WZ=ns(),$k="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",zZ="savedqueryid,name,returnedtypecode,querytype,isdefault",jZ=60*1e3;function jf(e){return(e.localName||e.nodeName).toLowerCase()}function Yu(e,t){let r;for(let n=0;n<e.attributes.length;n+=1){let i=e.attributes[n];i.nodeName.toLowerCase()===t&&(r=r===void 0?i.value:null)}return r}function HZ(e){if(!e)return;let t=!0,r=()=>{t=!1},n=new WZ.DOMParser({errorHandler:{warning:r,error:r,fatalError:r}}).parseFromString(e,"text/xml").documentElement;return t&&n&&jf(n)==="fetch"?n:void 0}function KZ(e){for(let t=e.parentNode;t;t=t.parentNode)if(jf(t)==="link-entity")return!0;return!1}function xk(e,t){var r,n,i;if(((r=e.canbedeleted)===null||r===void 0?void 0:r.Value)!==!1)return!1;let o=HZ(e.fetchxml);if(!o)return!1;let a=Array.from(o.getElementsByTagName("*")),s=a.filter(u=>jf(u)==="condition"),l=s.length===1?s[0]:void 0;return l!==void 0&&a.filter(u=>jf(u)==="link-entity").every(u=>{var c;return((c=Yu(u,"link-type"))===null||c===void 0?void 0:c.toLowerCase())==="outer"})&&!KZ(l)&&Yu(l,"entityname")===void 0&&((n=Yu(l,"attribute"))===null||n===void 0?void 0:n.toLowerCase())==="statecode"&&((i=Yu(l,"operator"))===null||i===void 0?void 0:i.toLowerCase())==="eq"&&Yu(l,"value")===String(t)}function JZ(e,t){let r=String(e??"").trim().toLowerCase().split(/\s+/).filter(i=>i!==""),n=String(t??"").trim().toLowerCase().split(/\s+/).filter(i=>i!=="");return r.length===n.length&&r.filter((i,o)=>i!==n[o]).length===1}function YZ(e){var t,r;let n=e.filter(a=>xk(a,0)),i=e.filter(a=>xk(a,1)),o=[];for(let a of n)for(let s of i)Math.abs(Date.parse(String((t=s.createdon)!==null&&t!==void 0?t:""))-Date.parse(String((r=a.createdon)!==null&&r!==void 0?r:"")))<=jZ&&JZ(a.name,s.name)&&o.push({active:a,inactive:s});return o.length===1?o[0]:void 0}async function QZ(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,kn.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,kn.odataQuery)([["$select","savedqueryid,name,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,Mk.collectPages)(e,a,`findDefaultViews('${t}')`),l=YZ(s),u=new Set(l?[l.active,l.inactive]:[]);return s.filter(c=>c.savedqueryid&&!i.has(c.savedqueryid)&&u.has(c)).map(c=>{var d;return{id:String(c.savedqueryid),name:String((d=c.name)!==null&&d!==void 0?d:"")}})}Js.findDefaultViews=QZ;async function XZ(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,kn.odataPathLiteral)(t)}')${(0,kn.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status>=200&&i.status<300){let o=(r=i.body)===null||r===void 0?void 0:r.ObjectTypeCode;return typeof o=="number"?o:void 0}}async function Fk(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await XZ(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}Js.viewApi={async get(e,t){let r=(0,kn.normalizeGuid)(t,"id"),n=await(0,fr.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,kn.odataQuery)([["$select",$k]]);return{raw:(0,fr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,kn.normalizeGuid)(t,"id"),n=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,kn.odataQuery)([["$select",$k]]),i=(0,fr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,fr.readRowEtag)(e,"savedqueries","savedqueryid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueries${(0,kn.odataQuery)([["$select",zZ],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,kn.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,Mk.collectPages)(e,r,"listArtifacts('view')")).map(i=>{var o,a;return{type:"view",id:(o=i.savedqueryid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.returnedtypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,fr.echoWrite)("savedqueryid"),o=`/savedqueries${i.query}`,a=await Fk(e,n.layoutxml,n.returnedtypecode),s=Object.freeze((0,fr.withClientMintedId)({name:n.name,description:n.description,fetchxml:n.fetchxml,layoutxml:a,returnedtypecode:n.returnedtypecode,querytype:n.querytype,isdefault:n.isdefault},"savedqueryid",r)),l=(0,fr.ensureSuccess)(await(0,fr.resendDeadlockVictim)(()=>e.post(o,{...s},i.options)),e.apiUrl(o));return{id:(0,fr.resolveCreatedId)(l,"savedqueryid","view",r),etag:(0,fr.readEtag)(l)}},async update(e,t,r,n){let i=r,o=(0,kn.normalizeGuid)(t,"id"),a=(0,fr.echoWrite)("savedqueryid",{"If-Match":(0,fr.requireEtag)(n,"view",o)}),s=`/savedqueries(${o})${a.query}`,l=await Fk(e,i.layoutxml,i.returnedtypecode),u=(0,fr.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,fetchxml:i.fetchxml,layoutxml:l},a.options),e.apiUrl(s));return{id:o,etag:(0,fr.readEtag)(u)}},delete(e,t){return(0,fr.deleteRecord)(e,"savedqueries",t)}}});var eL=v(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});Ys.viewRegistration=Ys.ViewAdapter=void 0;var zk=Q(),jr=rn(),ib=so(),va=uo(),Uk=Qr(),ZZ=nb(),ob=lo(),eee=pt(),jk=100,Kf=class{toArtifact(t){var r,n,i,o,a,s,l,u;(0,ob.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",f=(0,va.parseXmlRoot)(c,"<fetch/>"),m=(0,va.parseXmlRoot)(d,"<grid/>"),p=Kk(f);return{id:(i=t.savedqueryid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.returnedtypecode)!==null&&s!==void 0?s:ree(f),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:Hk(m,f),filters:Yk(f),sort:Jk(f),...p.length>0?{linkEntities:p}:{},fetchBag:c?(0,va.projectElementBag)(f):void 0,layoutBag:d?(0,va.projectElementBag)(m):void 0}}fromArtifact(t){(0,ob.installDomShim)();let{fetchxml:r,layoutxml:n}=Bk(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,o,a;(0,ob.installDomShim)();let{fetchxml:s,layoutxml:l}=Bk(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:(o=t.queryType)!==null&&o!==void 0?o:0,isdefault:(a=t.isDefault)!==null&&a!==void 0?a:!1}}createDefault(t){var r,n,i,o,a,s,l,u;let c=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,eee.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New View",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:c,queryType:(a=t.queryType)!==null&&a!==void 0?a:0,isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,columns:t.columns&&t.columns.length>0?t.columns:[{name:`${c}id`,width:300,order:0}],filters:(l=t.filters)!==null&&l!==void 0?l:{type:"and",conditions:[],groups:[]},sort:(u=t.sort)!==null&&u!==void 0?u:[],...t.linkEntities&&t.linkEntities.length>0?{linkEntities:t.linkEntities}:{}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;(0,jr.childObjects)(n,"columns","","column",r),(0,jr.childObjects)(n,"sort","","sort",r),(0,jr.childObjects)(n,"linkEntities","","linkEntity",r),tee(n.linkEntities,r);let i=n.filters;return i!=null&&((0,jr.isJsonObject)(i)?ab(i,"/filters",r):r.push((0,jr.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};Ys.ViewAdapter=Kf;function tee(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,jr.isJsonObject)(r))return;for(let o of["name","from","to"]){let a=r[o];(typeof a!="string"||a.trim()==="")&&t.push((0,jr.issue)(`/linkEntities/${n}/${o}`,"linkentity-needs-keys",`a join needs a non-empty '${o}' \u2014 'from'/'to' are what DEFINE the relationship, and a link without them is unresolvable. Got ${JSON.stringify(a)}.`))}let i=r.filters;i!=null&&((0,jr.isJsonObject)(i)?ab(i,`/linkEntities/${n}/filters`,t):t.push((0,jr.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function ab(e,t,r){(0,jr.childObjects)(e,"conditions",t,"condition",r),(0,jr.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:o})=>ab(i,`${t}/groups/${o}`,r))}function ree(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function Hk(e,t){var r;let n=Jf(t),i=e.getElementsByTagName("cell"),o=[],a=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)?jk:c,order:a},f=n.get(u);f&&(d.relatedEntity=f.linkKey,f.attributeName&&f.attributeName!==u&&(d.sourceAttribute=f.attributeName)),a+=1,o.push(d)}return o}function Jf(e){let t=new Map,r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("name")||"",c=l.getAttribute("alias")||u;c&&t.set(c,{linkKey:i.getAttribute("alias")||o,linkName:o,attributeName:u,link:i})}}return t}function Kk(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of Mt(t,"link-entity")){let i=n.getAttribute("name"),o=n.getAttribute("from"),a=n.getAttribute("to");if(!i||!o||!a)continue;let s=n.getAttribute("alias"),l=n.getAttribute("link-type"),u=Mt(n,"filter").find(c=>!Yf(c));r.push({name:i,from:o,to:a,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:sb(u)}:{}})}return r}function Jk(e){var t;let r=e.getElementsByTagName("entity")[0];if(!r)return[];let n=[],i=r.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a.nodeType===1&&a.tagName==="order"){let s=a.getAttribute("attribute");s&&n.push({attribute:s,descending:((t=a.getAttribute("descending"))!==null&&t!==void 0?t:"").toLowerCase()==="true",entityname:a.getAttribute("entityname")||""})}}return n}function Yk(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=Mt(t,"filter").filter(i=>!Yf(i)).map(sb);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function Yf(e){if(e.getAttribute("isquickfindfields")==="1"||Qk(e))return!0;if(Mt(e,"filter").length>0)return!1;let t=Mt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||Mt(r,"value").length>0||iee(r))}function Qk(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&(n.tagName==="filter"?Qk(n):n.tagName!=="condition"))return!0}return!1}var nee=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function iee(e){var t;let r=e.attributes;for(let n=0;n<r.length;n+=1){let i=(t=r[n])===null||t===void 0?void 0:t.name;if(i&&!nee.has(i))return!0}return!1}function sb(e){var t,r;let n=((t=e.getAttribute("type"))!==null&&t!==void 0?t:"and").toLowerCase()==="or"?"or":"and",i=[],o=[],a=e.childNodes;for(let s=0;s<a.length;s+=1){let l=a[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:""};l.hasAttribute("value")&&(c.value=l.getAttribute("value")||"");let d=l.getAttribute("entityname")||"";d&&(c.entityname=d),i.push(c)}else l.tagName==="filter"&&o.push(sb(l))}return{type:n,conditions:i,groups:o}}function Mt(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}var lb=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function oee(e,t){let r=Jf(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=r.get(i.name);if(o){let a=lb(i),s=n.get(a);s?s.push(o.link):n.set(a,[o.link])}}return n}function aee(e,t,r,n){if(!n||n.size===0)return;let i=new Set,o=t.getElementsByTagName("link-entity");for(let s=0;s<o.length;s+=1)i.add(o[s]);let a=r.filter(s=>{if(!s.relatedEntity)return!1;let l=n.get(lb(s));return!!l&&l.some(u=>!i.has(u))});if(a.length!==0)throw new zk.ValidationError("view",e.id,a.map(s=>(0,jr.issue)(`/columns/${r.indexOf(s)}`,"view-column-orphaned-by-join-removal",`column '${s.name}' came from a join this push REMOVED. Another join matching '${s.relatedEntity}' still exists, but nothing can say whether it is the one the column belonged to \u2014 re-attaching it there would silently change the data the column shows. Remove the column too, keep the join it came from, or point the column at the join you want by setting relatedEntity to that join's alias.`)))}function Bk(e){var t,r;let n=see(e.columns),i=(t=e.sort)!==null&&t!==void 0?t:[],o=(r=e.filters)!==null&&r!==void 0?r:{type:"and",conditions:[],groups:[]};if(!qk(e.fetchBag)||!qk(e.layoutBag))return{fetchxml:wee({...e,columns:n,sort:i,filters:o}),layoutxml:Cee({...e,columns:n},`${e.entityLogicalName}id`)};let a=new DOMParser().parseFromString("<root/>","text/xml"),s=Vk(e.fetchBag,"fetch",a),l=Vk(e.layoutBag,"grid",a),u=Hk(l,s),c=!Hf(n,u),d=!Hf(i,Jk(s)),f=!Hf(o,Yk(s)),m=e.linkEntities,p=m!==void 0&&!Hf(m,Kk(s)),h=p?oee(s,u):void 0;return p&&yee(a,s,m),p&&(vee(e,s,n,h),aee(e,s,n,h)),c?(Gk(a,s,n,u),fee(a,l,n)):p&&Gk(a,s,n,u),d&&hee(a,s,i),f&&gee(a,s,o),{fetchxml:(0,va.serializeNode)(s),layoutxml:(0,va.serializeNode)(l)}}function see(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:jk,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function qk(e){return!!e&&(e.c.length>0||e.a.length>0)}function Vk(e,t,r){let n={n:t,a:(0,ib.mergeAttrs)(e.a,[]),c:(0,ib.spliceChildren)(e.c,[])};return(0,ib.rebuildRaw)(n,(0,va.domEngine)(r),null)}function Gk(e,t,r,n){var i,o,a;let s=t.getElementsByTagName("entity")[0];if(!s)return;let l=p=>{var h,g;return`${(h=p.relatedEntity)!==null&&h!==void 0?h:""}:${p.name}:${(g=p.sourceAttribute)!==null&&g!==void 0?g:p.name}`},u=new Set(r.map(l)),c=new Set(r.map(p=>p.name)),d=Jf(t);for(let p of n)u.has(l(p))||(uee(s,p),p.relatedEntity&&c.has(p.name)&&lee((i=d.get(p.name))===null||i===void 0?void 0:i.link,p.name));let f=Jf(t),m=new Set(Mt(s,"attribute").map(p=>p.getAttribute("name")).filter(p=>!!p));for(let p of[...r].sort((h,g)=>h.order-g.order))if(p.relatedEntity){let h=f.get(p.name);if(h&&h.attributeName===((o=p.sourceAttribute)!==null&&o!==void 0?o:p.name)&&(h.linkKey===p.relatedEntity||h.linkName===p.relatedEntity||!Zk(s,p.relatedEntity)))continue;let g=cee(e,s,p.relatedEntity),b=e.createElement("attribute");Xk(b,p),g.appendChild(b),f.set(p.name,{linkKey:p.relatedEntity,linkName:g.getAttribute("name")||p.relatedEntity,attributeName:(a=p.sourceAttribute)!==null&&a!==void 0?a:p.name,link:g})}else{if(m.has(p.name))continue;let h=e.createElement("attribute");h.setAttribute("name",p.name),dee(s,h),m.add(p.name)}}function Xk(e,t){if(t.sourceAttribute&&t.sourceAttribute!==t.name){e.setAttribute("name",t.sourceAttribute),e.setAttribute("alias",t.name);return}e.setAttribute("name",t.name)}function lee(e,t){if(e){for(let r of Mt(e,"attribute"))if((r.getAttribute("alias")||r.getAttribute("name"))===t){e.removeChild(r);return}}}function uee(e,t){if(t.relatedEntity){for(let r of Mt(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of Mt(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of Mt(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function Zk(e,t,r=!1){let n=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of Mt(e,"link-entity"))if(n(o))return o;if(r)return;let i=e.getElementsByTagName("link-entity");for(let o=0;o<i.length;o+=1)if(n(i[o]))return i[o]}function cee(e,t,r){let n=Zk(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function dee(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 fee(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),o=pee(n);if(mee(o,i)){for(let s=0;s<i.length;s+=1){let l=String(i[s].width);o[s].getAttribute("width")!==l&&o[s].setAttribute("width",l)}return}let a=new Map;for(let s of o){let l=s.getAttribute("name");l&&a.set(l,s),n.removeChild(s)}for(let s of i){let l=a.get(s.name);l||(l=e.createElement("cell"),l.setAttribute("name",s.name)),l.setAttribute("width",String(s.width)),n.appendChild(l)}}function pee(e){return Mt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function mee(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 hee(e,t,r){let n=t.getElementsByTagName("entity")[0];if(!n)return;let i=(m,p)=>`${m.toLowerCase()}\0${p.toLowerCase()}`,o=new Map,a=new Map,s=(m,p,h)=>{let g=m.get(p);g?g.push(h):m.set(p,[h])},l=null;for(let m of Mt(n,"order")){let p=m.getAttribute("attribute")||"";p&&(l||(l=e.createTextNode(""),n.insertBefore(l,m)),s(o,i(m.getAttribute("entityname")||"",p),m),s(a,p.toLowerCase(),m),n.removeChild(m))}let u=new Set,c=(m,p)=>{let h=m.get(p);for(;h&&h.length>0;){let g=h.shift();if(!u.has(g))return u.add(g),g}},d=m=>{var p;let h=a.get(m.toLowerCase());if(!h)return;let g=h.filter(w=>!u.has(w)),b=(p=g.find(w=>!w.getAttribute("entityname")))!==null&&p!==void 0?p:g[0];return b&&u.add(b),b},f=r.map(m=>{let p=String(m.attribute);return m.entityname===void 0?{expression:m,element:void 0}:{expression:m,element:c(o,i(m.entityname,p))}});for(let m of f)m.expression.entityname===void 0&&(m.element=d(String(m.expression.attribute)));for(let{expression:m,element:p}of f){let h=p??e.createElement("order");h.setAttribute("attribute",m.attribute),h.setAttribute("descending",String(m.descending)),m.entityname?h.setAttribute("entityname",m.entityname):m.entityname===""&&h.removeAttribute("entityname"),n.insertBefore(h,l)}l&&n.removeChild(l)}function gee(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Mt(n,"filter"))Yf(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(Qu(e,r))}}function Hf(e,t){return JSON.stringify(e)===JSON.stringify(t)}function yee(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=Mt(i,"link-entity").filter(p=>p.getAttribute("name")&&p.getAttribute("from")&&p.getAttribute("to")),a=(p,h)=>p.getAttribute(h)||"",s=new Array(r.length),l=new Set,u=p=>{r.forEach((h,g)=>{if(s[g])return;let b=o.filter(S=>!l.has(S)&&p(S,h));if(b.length!==1)return;let w=b[0];r.some((S,O)=>O!==g&&!s[O]&&p(w,S))||(s[g]=w,l.add(w))})};u((p,h)=>!!h.alias&&a(p,"name")===h.name&&a(p,"alias")===h.alias),u((p,h)=>a(p,"name")===h.name&&a(p,"from")===h.from&&a(p,"to")===h.to),u((p,h)=>a(p,"name")===h.name&&a(p,"from")===h.from),u((p,h)=>a(p,"name")===h.name&&a(p,"to")===h.to),u((p,h)=>a(p,"name")===h.name);let c=r.map((p,h)=>h).filter(p=>!s[p]),d=o.filter(p=>!l.has(p)),f=new Map;for(let p of d){let h=f.get(a(p,"name"));h?h.push(p):f.set(a(p,"name"),[p])}let m=new Map;for(let p of c){let h=m.get(r[p].name);h?h.push(p):m.set(r[p].name,[p])}for(let[p,h]of m){let g=(n=f.get(p))!==null&&n!==void 0?n:[];g.length===h.length&&h.forEach((b,w)=>{s[b]=g[w],l.add(g[w])})}r.forEach((p,h)=>{let g=s[h];if(g){Wk(e,g,p);return}let b=e.createElement("link-entity");Wk(e,b,p),i.appendChild(b)});for(let p of o)l.has(p)||i.removeChild(p)}var bee=new Set(["inner","outer"]);function vee(e,t,r,n){if(!t.getElementsByTagName("entity")[0])return;let o=new Set,a=t.getElementsByTagName("link-entity");for(let c=0;c<a.length;c+=1){let d=a[c],f=d.getAttribute("name"),m=d.getAttribute("alias");f&&o.add(f),m&&o.add(m)}let s=new Set;for(let c=0;c<a.length;c+=1)s.add(a[c]);let l=c=>{let d=n?.get(lb(c));return!!d&&d.every(f=>s.has(f))},u=r.filter(c=>c.relatedEntity&&!o.has(c.relatedEntity)&&!l(c));if(u.length!==0)throw new zk.ValidationError("view",e.id,u.map(c=>{var d;let f=((d=e.linkEntities)!==null&&d!==void 0?d:[]).some(m=>m.name===c.relatedEntity||m.alias===c.relatedEntity);return(0,jr.issue)(`/columns/${r.indexOf(c)}`,"view-column-dangling-link",`column '${c.name}' has relatedEntity '${c.relatedEntity}', but no matching join remains in linkEntities. `+(f?"Remove the column too, or keep the join.":"That join is NESTED (a join off a join), which the typed layer does not model, so it cannot be re-declared in linkEntities \u2014 it only survives while the join above it does. Remove the column, or restore the parent join this push replaced."))}))}function Wk(e,t,r){t.setAttribute("name",r.name),t.setAttribute("from",r.from),t.setAttribute("to",r.to),r.alias?t.setAttribute("alias",r.alias):t.removeAttribute("alias"),r.linkType?t.setAttribute("link-type",r.linkType):bee.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=Mt(t,"filter").find(o=>!Yf(o)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?Qu(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function wee(e){var t;let r=new DOMParser().parseFromString("<fetch/>","text/xml"),n=r.documentElement;n.setAttribute("version","1.0"),n.setAttribute("mapping","logical");let i=r.createElement("entity");i.setAttribute("name",e.entityLogicalName),n.appendChild(i);let o=new Map;for(let a of(t=e.linkEntities)!==null&&t!==void 0?t:[]){let s=r.createElement("link-entity");s.setAttribute("name",a.name),s.setAttribute("from",a.from),s.setAttribute("to",a.to),a.alias&&s.setAttribute("alias",a.alias),a.linkType&&s.setAttribute("link-type",a.linkType),a.filters&&(a.filters.conditions.length>0||a.filters.groups.length>0)&&s.appendChild(Qu(r,a.filters)),i.appendChild(s);for(let l of[a.alias||a.name,a.name])o.has(l)||o.set(l,s)}for(let a of[...e.columns].sort((s,l)=>s.order-l.order)){let s=r.createElement("attribute");if(a.relatedEntity){Xk(s,a);let l=o.get(a.relatedEntity);l||(l=r.createElement("link-entity"),l.setAttribute("name",a.relatedEntity),i.appendChild(l),o.set(a.relatedEntity,l)),l.appendChild(s)}else s.setAttribute("name",a.name),i.appendChild(s)}for(let a of e.sort){let s=r.createElement("order");s.setAttribute("attribute",a.attribute),s.setAttribute("descending",String(a.descending)),a.entityname&&s.setAttribute("entityname",a.entityname),i.appendChild(s)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&i.appendChild(Qu(r,e.filters)),new XMLSerializer().serializeToString(r)}function Qu(e,t){let r=e.createElement("filter");r.setAttribute("type",t.type);for(let n of t.conditions){let i=e.createElement("condition");i.setAttribute("attribute",n.attribute),i.setAttribute("operator",n.operator),n.entityname&&i.setAttribute("entityname",n.entityname),n.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(Qu(e,n));return r}function Cee(e,t){var r;let n=new DOMParser().parseFromString("<grid/>","text/xml"),i=n.documentElement,o=[...e.columns].sort((s,l)=>s.order-l.order);i.setAttribute("name","resultset"),i.setAttribute("jump",((r=o[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 a=n.createElement("row");a.setAttribute("name","result"),a.setAttribute("id",t||`${e.entityLogicalName}id`),i.appendChild(a);for(let s of o){let l=n.createElement("cell");l.setAttribute("name",s.name),l.setAttribute("width",String(s.width)),a.appendChild(l)}return new XMLSerializer().serializeToString(n)}function Eee(){return{adapter:new Kf,api:ZZ.viewApi,publish:(e,t,r)=>(0,Uk.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,Uk.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}Ys.viewRegistration=Eee});function Qf(e,t){return e==="SetFieldValue"&&t!==void 0&&Aee.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var Aee,ub=L(()=>{"use strict";Aee=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function tL(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function cb(e){return e==="AllForms"||tL(e)?1:2}function db(e){return tL(e)?e:null}function rL(e,t){return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:e.name,description:e.description,workflowid:t,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:Qs.WorkflowCategory.BusinessRule,type:Qs.WorkflowTypeCode.Definition,mode:1,scope:Qs.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:cb(e.scope),processtriggerformid:db(e.scope)}}var Qs,nL=L(()=>{"use strict";Qs=Ae(Qi());});function iL(e,t=0){return(Ut[e[t+0]]+Ut[e[t+1]]+Ut[e[t+2]]+Ut[e[t+3]]+"-"+Ut[e[t+4]]+Ut[e[t+5]]+"-"+Ut[e[t+6]]+Ut[e[t+7]]+"-"+Ut[e[t+8]]+Ut[e[t+9]]+"-"+Ut[e[t+10]]+Ut[e[t+11]]+Ut[e[t+12]]+Ut[e[t+13]]+Ut[e[t+14]]+Ut[e[t+15]]).toLowerCase()}var Ut,oL=L(()=>{Ut=[];for(let e=0;e<256;++e)Ut.push((e+256).toString(16).slice(1))});function fb(){return Xf>Zf.length-16&&((0,aL.randomFillSync)(Zf),Xf=0),Zf.slice(Xf,Xf+=16)}var aL,Zf,Xf,sL=L(()=>{aL=require("crypto"),Zf=new Uint8Array(256),Xf=Zf.length});var lL,pb,uL=L(()=>{lL=require("crypto"),pb={randomUUID:lL.randomUUID}});function See(e,t,r){if(pb.randomUUID&&!t&&!e)return pb.randomUUID();e=e||{};let n=e.random??e.rng?.()??fb();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 iL(n)}var pr,cL=L(()=>{uL();sL();oL();pr=See});var mb=L(()=>{cL()});var dL=L(()=>{"use strict";});function fL(e){return e!=null&&Nee.has(e)}function ep(e){if(e==null)return!1;let t=e.trim();if(!/^[+-]?\d+$/.test(t))return!1;let r=Number(t);return Number.isInteger(r)&&r>=-2147483648&&r<=2147483647}var Nee,hb=L(()=>{"use strict";Nee=new Set(["Picklist","State","Status"])});var tp=v(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.WorkflowConditionOperator=pn.WorkflowAttributeType=pn.SystemStep=pn.FieldRequiredLevelTypes=pn.AttributeDateTimeBehavior=void 0;pn.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};pn.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};pn.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};pn.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"};pn.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 rp(e){return e!=null&&mL.includes(e)}function gb(e){return e===oe.WorkflowAttributeType.Integer}function yb(e,t){return t===oe.WorkflowConditionOperator.Equal||t===oe.WorkflowConditionOperator.NotEqual?e:_ee.includes(t)?mL.includes(e)||e===oe.WorkflowAttributeType.DateTime?e:oe.WorkflowAttributeType.String:t===oe.WorkflowConditionOperator.On||t===oe.WorkflowConditionOperator.NotOn?e===oe.WorkflowAttributeType.DateTime?e:oe.WorkflowAttributeType.String:oe.WorkflowAttributeType.String}function hL(e){let t=e.leftWorkflowType??e.valueWorkflowType??oe.WorkflowAttributeType.String,r=Xu[e.operator]??oe.WorkflowConditionOperator.Equal;return yb(t,r)}function gL(e,t){let r=e.trim(),i=(r.startsWith("+")||r.startsWith("-")?r.slice(1):r).split(".");if(i.length>2)return!1;let[o,a=""]=i;return o.length===0&&a.length===0||!pL.test(o)||!pL.test(a)||o.length>1&&o.startsWith("0")||o.length>Tee?!1:t!==oe.WorkflowAttributeType.Integer||i.length===1}var oe,Xu,mL,_ee,pL,Tee,bb=L(()=>{"use strict";oe=Ae(tp());Xu={Equals:oe.WorkflowConditionOperator.Equal,DoesNotEqual:oe.WorkflowConditionOperator.NotEqual,IsGreaterThan:oe.WorkflowConditionOperator.GreaterThan,IsLessThan:oe.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:oe.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:oe.WorkflowConditionOperator.LessThanOrEqual,Contains:oe.WorkflowConditionOperator.Contains,DoesNotContain:oe.WorkflowConditionOperator.DoesNotContain,BeginsWith:oe.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:oe.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:oe.WorkflowConditionOperator.EndsWith,DoesNotEndWith:oe.WorkflowConditionOperator.DoesNotEndWith,On:oe.WorkflowConditionOperator.On,NotOn:oe.WorkflowConditionOperator.NotOn,ContainsData:oe.WorkflowConditionOperator.NotNull,DoesNotContainData:oe.WorkflowConditionOperator.IsNull},mL=[oe.WorkflowAttributeType.Decimal,oe.WorkflowAttributeType.Float,oe.WorkflowAttributeType.Integer,oe.WorkflowAttributeType.Money],_ee=[oe.WorkflowConditionOperator.GreaterThan,oe.WorkflowConditionOperator.GreaterThanOrEqual,oe.WorkflowConditionOperator.LessThan,oe.WorkflowConditionOperator.LessThanOrEqual];pL=/^\d*$/,Tee=28});var yL=L(()=>{"use strict";});function Ln(e){return!Dee.has(e)}function vb(e){return e==="Equals"||e==="DoesNotEqual"}function np(e){return vL.has(e)?Iee:Lee.has(e)?Oee:wL.has(e)?Pee:xee.has(e)?kee:Ree}function CL(e){return np(e)[0]}function EL(e,t){return np(t).includes(e)}function bL(e){return vL.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":wL.has(e)?"date":$ee.has(e)?"boolean":"other"}function ip(e,t){let r=bL(e),n=bL(t);return r==="other"||n==="other"?e===t:r===n}var Dee,Iee,Oee,Pee,Ree,kee,vL,Lee,wL,$ee,xee,op=L(()=>{"use strict";yL();Dee=new Set(["ContainsData","DoesNotContainData"]);Iee=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],Oee=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],Pee=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],Ree=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],kee=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],vL=new Set(["String","Memo","EntityName"]),Lee=new Set(["Integer","BigInt","Money","Decimal","Double"]),wL=new Set(["DateTime"]),$ee=new Set(["Boolean"]),xee=new Set(["Lookup","Owner","Customer"])});function _L(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 kL(e){return e&&e!==Fe.WorkflowAttributeType.String?e:void 0}function Uee(e){return{__class:RL,parameterName:"primaryEntity",entityName:e}}function AL(e){return{__class:Cb,type:wb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:TL,parameters:[e]}}function SL(e,t,r=Fe.WorkflowAttributeType.String){return{__class:IL,type:r,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,entity:Uee(t),attributeName:e}}function Bee(e,t=Fe.WorkflowAttributeType.String){return{__class:OL,type:t,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function qee(e){return{__class:PL,type:wb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function LL(e,t){let r=Fee[e.operator],n=AL(SL(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=qee(e.right.value??"0"):e.right.kind==="field"?i=SL(e.right.field??"",t,e.right.workflowType):i=Bee(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=AL(i);return{__class:Cb,type:wb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:DL,parameters:[r,n,o]}}function $L(e){return typeof e=="object"&&e.__class===Cb}function Vee(e){return typeof e=="object"&&e.__class===PL}function ap(e){return $L(e)&&e.method===TL&&e.parameters.length>0?ap(e.parameters[0]):e}function NL(e){if(typeof e!="object"||e.__class!==IL)return null;let t=e.entity;if(t&&t.__class&&t.__class!==RL)return null;let r=e.attributeName;return r?{field:r,workflowType:kL(e.type)}:null}function xL(e){if(!e)return null;let t=ap(e);if(!$L(t)||t.method!==DL||t.parameters.length!==3)return null;let r=t.parameters[0],n=Mee[String(r)];if(!n)return null;let i=NL(ap(t.parameters[1]));if(!i)return null;let o=ap(t.parameters[2]);if(Vee(o))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=NL(o);if(a)return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"field",field:a.field,workflowType:a.workflowType}};if(typeof o=="object"&&o.__class===OL){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:kL(o.type)}}}return null}function Ab(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=Eb&&r<=Xs}function wa(e){if(!e||!e.leftField)return"incomplete";if(e.right.kind==="field")return e.right.field&&e.right.field.trim()?null:"incomplete";let t=e.right.value;return!t||!t.trim()?"incomplete":e.dateArithmetic&&!Ab(t)?"invalidDayCount":null}function Zs(e){return wa(e)===null}var Fe,TL,DL,wb,IL,OL,Cb,PL,RL,Fee,Mee,Eb,Xs,Zu=L(()=>{"use strict";Fe=Ae(tp());op();TL="0",DL="3",wb="0",IL="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",OL="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",Cb="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",PL="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",RL="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";Fee={"+":0,"-":1,"*":2,"/":3},Mee={0:"+",1:"-",2:"*",3:"/"};Eb=0,Xs=2147483647});function Wee(e){return e.startsWith("__")&&!Gee.has(e)}function zee(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{Wee(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function YL(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Ea(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function sp(e){return YL(e)||Ea(e)}function jee(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function ec(){return{list:[]}}function Sb(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:pr(),languageCode:r,description:t}]}}function _b(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function dp(e,t,r,n=j.AttributeDateTimeBehavior.None){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:n,typeSet:!1,entity:_b(t),attributeName:e}}function Ca(e,t,r=j.AttributeDateTimeBehavior.None){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:r,typeSet:!1,primitiveValue:e}}function Jee(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?ZL:XL:QL}function e1(e){return e.bpfField==="StageCategory"?j.WorkflowAttributeType.BpfStageCategory:j.WorkflowAttributeType.BpfProcess}function Yee(e,t){let r=e1(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${ML}_${FL}`,entityName:FL,relatedAttributeName:ML},attributeName:Kee}:dp(Hee,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,method:Ib,parameters:[Jee(e),n]}}function t1(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==Ib)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===XL?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===ZL?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===QL?{bpfField:"ProcessName"}:null}function lp(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===Ib){let r=(t.parameters??[])[0];if(typeof r=="string"&&Qee.has(r.replace(/^"+|"+$/g,"")))return!0}return Ea(e)?lp(e.operand):YL(e)?lp(e.left)||(e.right??[]).some(lp):!1}function r1(e){if(e?.__class!=="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.entity;return t==null||t.__class==="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions"}function Xee(e){if(e?.__class!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.primitiveValue;return t===!0||typeof t=="string"&&t.toLowerCase()==="true"}function UL(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return r1(e);case"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions":return e.primitiveValue!=null||e.type!==void 0;case"LookupExpression:#Microsoft.Crm.Workflow.Expressions":case"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions":return!0;default:return!1}}function Zee(e){let t=Db[e.conditionOperatoroperator];if(!t)return!1;let r=t==="ContainsData"||t==="DoesNotContainData";if(Ea(e))return r&&BL(e.operand,!0);let n=e.right??[];return n.length!==(r?0:1)?!1:BL(e.left,r,n[0])}function BL(e,t,r){return t1(e)||r1(e)?t||UL(r):!1}function Tb(e){if(!e||!sp(e))return!1;let t=e.conditionOperatoroperator;if(!Ea(e)&&(t===j.WorkflowConditionOperator.LogicalAnd||t===j.WorkflowConditionOperator.LogicalOr)){let r=e.right??[];return r.length>0&&Tb(e.left)&&r.every(Tb)}return Zee(e)}function qL(e){return!e||Xee(e)?!1:lp(e)||!Tb(e)}function n1(e){return{__class:"LookupExpression:#Microsoft.Crm.Workflow.Expressions",type:e.workflowType??j.WorkflowAttributeType.Lookup,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,entityType:e.entityType,label:e.label??"",staticValue:Ca(e.id.replace(/[{}]/g,""),j.WorkflowAttributeType.UniqueIdentifier)}}function tte(e){return e===j.WorkflowAttributeType.DateTime?j.AttributeDateTimeBehavior.DateOnly:j.AttributeDateTimeBehavior.None}function rte(e,t){if(t!==j.WorkflowAttributeType.DateTime)return j.AttributeDateTimeBehavior.None;let r=e.leftDateTimeBehavior;return r!==void 0&&r!==j.AttributeDateTimeBehavior.None?r:tte(t)}function nte(e,t,r){if(t!==j.WorkflowAttributeType.DateTime)return j.AttributeDateTimeBehavior.None;let n=e.valueFieldDateTimeBehavior;return n!==void 0&&n!==j.AttributeDateTimeBehavior.None?n:r}function ote(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return"1";if(t==="false"||t==="0")return"0"}function pte(e){let t=fte.exec(e);if(t)return`${t[1]}T${t[2]}`;let r=dte.exec(e);if(!r)return;let[,n,i,o,a,s,l]=r,u=cte.indexOf(i.toLowerCase());if(u<0)return;let c=String(u+1).padStart(2,"0");return`${o}-${c}-${n}T${a}:${s}:${l}`}function mte(e){let t=pte(e.trim());return t!==void 0&&i1(t)?t:e}function i1(e){let t=e.trim(),r=t.indexOf("T")>=0?"T":" ",n=t.indexOf(r),i=n>=0?t.slice(0,n):t,o=n>=0?t.slice(n+1):"";if(!ate.test(i)||o.length>0&&!ste.test(o)&&!lte.test(o)&&!ute.test(o))return!1;let[a,s,l]=i.split("-"),u=new Date(`${a}-${s}-${l}T00:00:00Z`);return!Number.isNaN(u.getTime())&&u.getUTCFullYear()===Number(a)&&u.getUTCMonth()+1===Number(s)&&u.getUTCDate()===Number(l)}function hte(e,t){let r={value:e,type:j.WorkflowAttributeType.String};if(t===j.WorkflowAttributeType.String||ite.includes(t)||e.trim().length===0)return r;if(t===j.WorkflowAttributeType.Boolean){let n=ote(e);return n==null?r:{value:n,type:t}}return ete.includes(t)?ep(e)?{value:e.trim(),type:t}:r:rp(t)?{value:e.trim(),type:t}:t===j.WorkflowAttributeType.DateTime&&i1(e)?{value:e.trim(),type:t}:r}function VL(e){return e==="ContainsData"||e==="DoesNotContainData"}function GL(e){return gte.has(e)}function WL(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function zL(e,t){let r=e.leftWorkflowType??e.valueWorkflowType??j.WorkflowAttributeType.String,n=Xu[e.operator]??j.WorkflowConditionOperator.Equal,i=rte(e,r),o=yb(r,n);if(e.source==="BusinessProcess"){let l=Yee(e,t);if(VL(e.operator))return WL(l,n);let u=e1(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:l,right:[Ca(e.value??"",u)]}}let a=dp(e.field,t,r,i);if(VL(e.operator))return WL(a,n);let s;if(e.valueType==="Field"&&e.valueField){let l=GL(o)&&GL(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:o;s=[dp(e.valueField,t,l,nte(e,l,i))]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[n1(e.lookupValue)]}else if(e.valueType==="Clear")s=[Ca(null,j.WorkflowAttributeType.String,i)];else if(e.valueType==="Expression")s=[cp(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)];else{let l=hte(e.value??"",o);s=[Ca(l.value,l.type,i)]}return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:a,right:s}}function yte(){return Ca(!0,j.WorkflowAttributeType.Boolean)}function bte(e,t,r){if(e.length===0)return null;let n=zL(e[0],r);for(let i=1;i<e.length;i++){let o=e[i].connector??t;n={__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?j.WorkflowConditionOperator.LogicalAnd:j.WorkflowConditionOperator.LogicalOr,left:n,right:[zL(e[i],r)]}}return n}function up(e){if(!e)return{valueType:"Value",value:""};if(e.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return{valueType:"Field",valueField:e.attributeName,valueFieldWorkflowType:e.type};if(e.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"){if(e.primitiveValue==null)return{valueType:"Clear",valueWorkflowType:e.type};let t=String(e.primitiveValue);if(e.type===j.WorkflowAttributeType.Boolean){let r=t.trim().toLowerCase();if(r==="1"||r==="true")return{valueType:"Value",value:"true",valueWorkflowType:e.type};if(r==="0"||r==="false")return{valueType:"Value",value:"false",valueWorkflowType:e.type}}return e.type===j.WorkflowAttributeType.DateTime?{valueType:"Value",value:mte(t),valueWorkflowType:e.type}:{valueType:"Value",value:t,valueWorkflowType:e.type}}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!==j.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=xL(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function vte(e){let t=Db[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=Ea(e)?e.operand:e.left,i=Ea(e)?[]:e.right??[],o=t1(n);if(o){let g=i[0];return{id:pr(),field:"",fieldDisplayName:"",source:"BusinessProcess",bpfField:o.bpfField,...o.stageType?{stageType:o.stageType}:{},operator:t,valueType:"Value",value:g?.primitiveValue!=null&&!r?String(g.primitiveValue):""}}let a=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",s=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?n.attributeName:"",l=a?n.type:void 0,u=r?{valueType:"Value"}:up(i[0]),c=l,d=a&&n.type===j.WorkflowAttributeType.DateTime&&n.behavior!==j.AttributeDateTimeBehavior.None?n.behavior:void 0,f=u.valueWorkflowType??l,m=r?void 0:i[0],h=m?.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"&&m.type===j.WorkflowAttributeType.DateTime&&m.behavior!==j.AttributeDateTimeBehavior.None?m.behavior:void 0;return{id:pr(),field:s,fieldDisplayName:s,operator:t,...u,...f?{valueWorkflowType:f}:{},...c?{leftWorkflowType:c}:{},...d!==void 0?{leftDateTimeBehavior:d}:{},...h!==void 0?{valueFieldDateTimeBehavior:h}:{}}}function jL(e){if(!e||!sp(e))return{clauses:[],logic:"AND"};let t=[],r=(o,a)=>{let s=o.conditionOperatoroperator;if(Ea(o)||s!==j.WorkflowConditionOperator.LogicalAnd&&s!==j.WorkflowConditionOperator.LogicalOr){t.push({...vte(o),...a?{connector:a}:{}});return}let l=s===j.WorkflowConditionOperator.LogicalAnd?"AND":"OR";sp(o.left)&&r(o.left,a),(o.right??[]).filter(sp).forEach(u=>r(u,l))};r(e,void 0);let i=t.slice(1).map(o=>o.connector??"AND")[0]??"AND";return{clauses:t,logic:i}}function cp(e,t,r,n,i,o,a,s){if(e==="Field"&&r)return dp(r,n,j.WorkflowAttributeType.String);if(e==="Expression"){if(i)return LL(i,n);if(o!=null)return o}return e==="Lookup"&&a?n1(a):e==="Clear"?Ca(null,s??j.WorkflowAttributeType.String):Ca(t??"",j.WorkflowAttributeType.String)}function Nb(e,t){return{propertyName:e,propertyValueExpr:t}}function el(e){return`Step_${e.value++}`}function mn(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 HL(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):mn(t,r)}function wte(e){return e===JL.StateCode.Activated?"Active":"Draft"}function Cte(e){let t={},r=e;typeof r.ismanaged=="boolean"&&(t.isManaged=r.ismanaged);let n=r.iscustomizable;return typeof n=="boolean"?t.isCustomizable=n:n!==null&&typeof n=="object"&&typeof n.Value=="boolean"&&(t.isCustomizable=n.Value),t}function Ete(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function o1(e,t=1033){return new tl({languageCode:t}).serialize(e)}function a1(e){return new tl().deserialize(e)}var JL,j,Gee,Db,Ib,QL,XL,ZL,Hee,Kee,FL,ML,Qee,ete,ite,ate,ste,lte,ute,cte,dte,fte,gte,Ob,tl,Pb=L(()=>{"use strict";mb();JL=Ae(Qi());dL();hb();bb();Zu();j=Ae(tp());Gee=new Set(["__class"]);Db={};for(let e of Object.keys(Xu))Db[Xu[e]]=e;Ib="23",QL="BpfProcess",XL="ActiveStageCategory",ZL="SelectedStageCategory",Hee="processid",Kee="stagecategory",FL="processstage",ML="stageid";Qee=new Set(["ActiveStage","SelectedStage","Stage"]);ete=[j.WorkflowAttributeType.Picklist,j.WorkflowAttributeType.State,j.WorkflowAttributeType.Status];ite=[j.WorkflowAttributeType.Lookup,j.WorkflowAttributeType.Customer,j.WorkflowAttributeType.Owner];ate=/^\d{4}-\d{2}-\d{2}$/,ste=/^\d{2}:\d{2}$/,lte=/^\d{2}:\d{2}:\d{2}$/,ute=/^\d{2}:\d{2}:\d{2}\.\d{1,7}$/,cte=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],dte=/^[A-Za-z]{3}, (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/,fte=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2}\.\d{1,7}|\d{2}:\d{2}:\d{2}|\d{2}:\d{2})Z$/;gte=new Set([j.WorkflowAttributeType.Lookup,j.WorkflowAttributeType.Owner,j.WorkflowAttributeType.Customer]);Ob={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"};tl=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>Ob[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)]:[],o={...r?.reservedProperties??{},__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:r?.id??t.ruleId??pr(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:ec(),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(o)}makeApplyActionStep(t){return{__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",id:mn("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??el(this.stepCounter),stepLabels:{list:[]},specification:Nb(t.field,cp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:_b(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),o=t??"",a=n?.stepLabels,s=Sb(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:HL(n?.id,"ActionStep",this.idCounter),name:n?.name??el(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??pr(),uniqueName:n?.uniqueName??`id_${pr().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=_b(this.entityName),n=t.stepName??el(this.stepCounter),i=t.stepLabels??ec(),o={name:n,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:mn("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:Nb(t.field,cp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:mn("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:Nb(t.field,cp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:mn("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...o,id:mn("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?j.FieldRequiredLevelTypes.Required:j.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...o,id:mn("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=Sb(t.stepLabels,s,this.languageCode);return{...o,id:mn("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=Sb(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:mn("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: ${a}`)}}serializeConditionNode(t){let r=t.stepName??el(this.stepCounter),n=mn("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??bte(o.clauses,o.logic,this.entityName),l=a?o.branchName??el(this.stepCounter):el(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?HL(o.branchId,"ConditionBranchStep",this.idCounter):mn("ConditionBranchStep",this.idCounter),name:l,description:o.displayName,stepLabels:ec(),conditionExpression:s??(a?yte():void 0),steps:{list:o.trueBranch.map(f=>this.serializeBranchItem(f))}};i.push(c);let d=o.falseBranch;if(d.length===1&&d[0].kind==="condition"){o=d[0],a=!1;continue}d.length>0&&i.push(this.makeTerminalElseBranch(d)),o=void 0}return{__class:"ConditionStep:#Microsoft.Crm.Workflow.ObjectModel",id:n,name:r,description:"",stepLabels:ec(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:mn("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:ec(),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 o=JSON.parse(t.wfomJson);i={id:o.id==="WorkflowStep0"||!o.id?t.workflowid??pr():o.id,name:o.name,description:o.description,nextStepIndex:o.nextStepIndex,category:o.category==="0"||o.category===0?"2":o.category,businessProcessType:o.businessProcessType,mode:o.mode,title:o.title||t.name||"",primaryEntityName:o.primaryEntityName==="1"||!o.primaryEntityName?t.primaryentity??"":o.primaryEntityName,workflowEntityId:o.workflowEntityId==="00000000-0000-0000-0000-000000000000"||!o.workflowEntityId?t.workflowid??"":o.workflowEntityId,formId:o.formId,variables:o.variables,inputs:o.inputs,reservedProperties:zee(o)};let s=(o.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:Ete(r,i?.formId),status:wte(t.statecode),rootCondition:n,wfomRoot:i,...Cte(t)}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(jee);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...o]=t,{clauses:a,logic:s}=jL(i?.conditionExpression),l=this.deserializeBranch(i?.steps?.list??[]),u=this.deserializeElseChain(o,r),c=i?.description||i?.name||r.description||r.name||this.label("condition");return{kind:"condition",id:(n?r.id:i?.id)??pr(),displayName:c,clauses:a,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,...qL(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=jL(n.conditionExpression);return i.length===0&&!qL(n.conditionExpression)?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},o=n.stepLabels?.list,a=o&&o.length>0?o[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||pr(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...up(u?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=up(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=up(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!==j.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:o,acceptanceText:a}=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:a,applyActions:i,recommendationActionStepMeta:o}}return{kind:"action",id:t.id,type:"ShowErrorMessage",displayName:t.description||this.label("showErrorMessage"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,errorMessage:n||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:r,meta:n,acceptanceText:i}=this.parseRecommendationApplyActions({list:[t]});return{kind:"action",id:t.id,type:"Recommendation",displayName:t.name||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.actionControl?.controlId??"",recommendationTitle:t.name||"",messageText:t.description||"",acceptanceText:i,applyActions:r,recommendationActionStepMeta:n}}default:return null}}}});var s1=L(()=>{"use strict";});function Tte(e){return typeof e=="object"&&e!==null?e:null}function rl(e){let t=Tte(e);if(!t)return!1;if(t.__class===Nte){let r=t;return String(r.method)===_te?!0:Array.isArray(r.parameters)&&r.parameters.some(rl)}if(t.__class===Ste)return rl(t.operand);if(t.__class===Ate){let r=t;return rl(r.left)||Array.isArray(r.right)&&r.right.some(rl)}return!1}var Ate,Ste,Nte,_te,l1=L(()=>{"use strict";s1();Ate="BinaryExpression:#Microsoft.Crm.Workflow.Expressions",Ste="UnaryExpression:#Microsoft.Crm.Workflow.Expressions",Nte="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",_te="23"});function $b(e){return Dte.has(e.type)}function Rb(e,t,r,n,i,o,a){let s=i.get(r);!s||!d1.has(s.attributeType)||n!=="Value"||a?.operator&&!vb(a.operator)||o.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:a?.target,itemId:a?.itemId,messageKey:"Validation.InvalidValueTypeForField",messageParams:{label:t}})}function Ite(e,t){let r=t.get(e.field);return!!r&&d1.has(r.attributeType)&&vb(e.operator)}function kb(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function Lb(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${Xs}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:Xs}}}function u1(e,t,r,n,i,o,a,s){if(i!=="Clear")return;let l=o.get(n);Qf(r,l)||a.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 pp(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if($b(t))return!0}else if(pp(t))return!0;return!1}function xb(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=xb(r,t);if(n)return n}}return null}function Ote(e){if(!e||typeof e!="object")return!1;let{__class:t,primitiveValue:r}=e;return t!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?!1:r===!0||typeof r=="string"&&r.toLowerCase()==="true"}function Pte(e){return e.clauses.length===0&&(e.rawConditionExpression===void 0||Ote(e.rawConditionExpression))}function kte(e){return!!e.clauses?.some(t=>t.source==="BusinessProcess")||rl(e.rawConditionExpression)}function nl(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=nl(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=nl(n,t);if(i)return i}}return null}function Fb(e,t){return{...e,trueBranch:c1(e.trueBranch,t),falseBranch:c1(e.falseBranch,t)}}function c1(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?Fb(r,t):r)}function To(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?To(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?To(n,t,r):n)}}function fp(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?fp(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?fp(n,t,r):n)}}function f1(e,t,r,n){return To(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function Mb(e){return e.length===1&&e[0].kind==="condition"}function $te(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(Mb(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function xte(e){return!!e&&$te(e)<Lte}function Fte(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let o=[];if(Mb(n.falseBranch)){let a=r(n.falseBranch[0],i);if(a)return a}else o.push(...n.falseBranch.filter(a=>a.kind==="condition"));o.push(...n.trueBranch.filter(a=>a.kind==="condition"));for(let a of o){let s=r(a,a);if(s)return s}};return r(e,e)}function p1(e,t,r){let n=Fte(e,t);return!n||!xte(n)?e:To(e,t,i=>m1(i,r))}function m1(e,t){if(Mb(e.falseBranch))return{...e,falseBranch:[m1(e.falseBranch[0],t)]};let r=Ub(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function h1(e,t){let r=nl(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 To(e,r.node.id,o=>({...o,falseBranch:i}))}function g1(e,t,r){let n=nl(e,t);if(!n)return e;let i=o=>{let a=[...o],s=a[n.index+r];return s?(a[n.index+r]=a[n.index],a[n.index]=s,a):o};return To(e,n.node.id,o=>({...o,trueBranch:n.branch==="true"?i(o.trueBranch):o.trueBranch,falseBranch:n.branch==="false"?i(o.falseBranch):o.falseBranch}))}function Ub(e){return{kind:"condition",id:pr(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function y1(e,t){let r={kind:"action",id:pr(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:pr(),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 b1(e){if(!e)return[];let t=[];return v1(e,t),[...new Set(t)]}function v1(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?v1(r,t):"field"in r&&r.field&&t.push(r.field)})}function w1(e,t=[],r){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition.",target:"node"}];let n=[],i=new Map(t.map(o=>[o.logicalName,o]));return E1(e,n,i,!0),r==="Entity"&&C1(e,n),pp(e)||n.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),n}function C1(e,t){kte(e)&&t.push({nodeId:e.id,kind:"BPF_IN_ENTITY_SCOPE",message:"Process based conditions are not allowed in Entity scope.",target:"node",messageKey:"Validation.ProcessConditionNotAllowedInEntityScope"}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"&&C1(r,t)})}function E1(e,t,r,n=!1){let i=n&&Pte(e),o=!!e.rawConditionExpression;e.clauses.length===0&&!n&&!o&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition.",target:"node",messageKey:"Validation.AddClause"}),i&&e.falseBranch.length>0&&t.push({nodeId:e.id,kind:"UNREACHABLE_ELSE",message:"Add a condition to the IF clause, or delete the ELSE clause it can never reach.",target:"node",messageKey:"Validation.UnreachableElse"}),e.clauses.forEach(a=>{if(o)return;if(a.source==="BusinessProcess"){a.bpfField?a.value||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id}):t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a business process field for this clause.",target:"clauseField",itemId:a.id,messageKey:"Validation.SelectBusinessProcessField"});return}let s=a.valueType==="Expression"&&!a.rawExpression?wa(a.expression):null;if(!a.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause.",target:"clauseField",itemId:a.id});else if(Ln(a.operator)&&a.valueType==="Value"&&!a.value&&!Ite(a,r))t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id});else if(Ln(a.operator)&&a.valueType==="Value"&&a.value){let u=r.get(a.field);u?.maxLength&&a.value.length>u.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${u.maxLength} characters.`,target:"clauseValue",itemId:a.id,messageParams:{maxLength:u.maxLength}})}else Ln(a.operator)&&a.valueType==="Expression"&&!a.rawExpression&&!Zs(a.expression)?t.push(s==="invalidDayCount"?Lb(e.id,"clauseValue",a.id):{nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.CompleteClauseFormula"}):Ln(a.operator)&&a.valueType==="Field"&&!a.valueField&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a field to compare to for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseCompareField"});Ln(a.operator)&&a.valueType==="Value"&&a.value&&fL(r.get(a.field)?.attributeType)&&!ep(a.value)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_OPTION_VALUE",message:"Please enter a whole number option value for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.InvalidClauseOptionValue"});let l=hL(a);Ln(a.operator)&&a.valueType==="Value"&&a.value&&rp(l)&&!gL(a.value,l)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_NUMERIC_VALUE",message:gb(l)?"Please enter a whole number for this clause.":"Please enter a valid number for this clause.",target:"clauseValue",itemId:a.id,messageKey:gb(l)?"Validation.InvalidClauseWholeNumberValue":"Validation.InvalidClauseNumericValue"}),Ln(a.operator)&&a.valueType==="Lookup"&&(kb(a.lookupValue)||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseLookupValue"})),Ln(a.operator)&&Rb(e.id,"Condition",a.field,a.valueType,r,t,{operator:a.operator,target:"clauseValue",itemId:a.id})}),i&&e.trueBranch.forEach(a=>{a.kind==="action"&&Rte.has(a.type)&&t.push({nodeId:a.id,kind:"ACTION_REQUIRES_CONDITION",message:"Set field value, Show error message, and Recommendation actions require a condition. Add a condition to the IF clause, or use a different action.",target:"node",messageKey:"Validation.ActionRequiresCondition",messageParams:{actionType:a.type}})}),[...e.trueBranch,...e.falseBranch].forEach(a=>{if(a.kind==="condition")E1(a,t,r);else{if(!("field"in a)||!a.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:`${a.type}: a target field is required.`,target:"actionField",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&(a.valueType??"Value")==="Value"&&!a.value?.trim())t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please provide a value.`,target:"actionValue",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Value"&&a.value){let s=r.get(a.field);s?.maxLength&&a.value.length>s.maxLength&&t.push({nodeId:a.id,kind:"ACTION_VALUE_TOO_LONG",message:`${a.type}: value exceeds the field's maximum length of ${s.maxLength} characters.`,target:"actionValue",messageParams:{actionType:a.type,maxLength:s.maxLength}})}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Field"){if(!a.valueField)t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please select a field to copy from.`,target:"actionValue",messageKey:"Validation.SelectActionSourceField",messageParams:{actionType:a.type}});else if(r.size>0){let s=r.get(a.field),l=r.get(a.valueField);s&&l&&!ip(s.attributeType,l.attributeType)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: the source field's type is not compatible with the target field.`,target:"actionValue",messageKey:"Validation.IncompatibleActionSourceField",messageParams:{actionType:a.type}})}}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Expression"){let s=a.rawExpression?null:wa(a.expression);!a.rawExpression&&!Zs(a.expression)&&t.push(s==="invalidDayCount"?Lb(a.id,"actionValue"):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the formula.`,target:"actionValue",messageKey:"Validation.CompleteActionFormula",messageParams:{actionType:a.type}})}else(a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Lookup"&&!kb(a.lookupValue)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the lookup record.`,target:"actionValue",messageKey:"Validation.EmptyActionLookupValue",messageParams:{actionType:a.type}});if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.field&&(Rb(a.id,a.type,a.field,a.valueType,r,t,{target:"actionValue"}),u1(a.id,a.type,a.type,a.field,a.valueType,r,t,{target:"actionValue"})),a.type==="ShowErrorMessage"&&!a.errorMessage?.trim()&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_MESSAGE",message:"Show error message: please enter an error message.",target:"actionMessage"}),a.type==="Recommendation"){let s=a.applyActions??[];a.recommendationTitle?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_TITLE",message:"Recommendation: please enter a recommendation title.",target:"recommendationTitle"}),a.messageText?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_MESSAGE",message:"Recommendation: please enter a recommendation message.",target:"recommendationMessage"}),s.length===0&&t.push({nodeId:a.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply.",target:"node"}),s.forEach(l=>{if(!l.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply.",target:"applyActionField",itemId:l.id,messageKey:"Validation.RecommendationApplyField"});else if(l.valueType==="Field")l.valueField||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplySourceField"});else if(l.valueType==="Expression"){let u=l.rawExpression?null:wa(l.expression);!l.rawExpression&&!Zs(l.expression)&&t.push(u==="invalidDayCount"?Lb(a.id,"applyActionValue",l.id):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyFormula"})}else l.valueType==="Lookup"?kb(l.lookupValue)||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyLookupValue"}):l.valueType==="Clear"||l.value?.trim()||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyValue"});l.field&&(Rb(a.id,"Recommendation",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}),u1(a.id,"Recommendation","SetFieldValue",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}))})}}})}var Dte,d1,Rte,Lte,Bb=L(()=>{"use strict";mb();ub();op();Zu();l1();bb();hb();Dte=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);d1=new Set(["Lookup","Customer","Owner"]);Rte=new Set(["SetFieldValue","ShowErrorMessage","Recommendation"]);Lte=10});var A1={};Jr(A1,{DAY_COUNT_MAX:()=>Xs,DAY_COUNT_MIN:()=>Eb,DEFAULT_DESERIALIZE_LABELS:()=>Ob,WorkflowJsonMapper:()=>tl,addElseIfInTree:()=>p1,appendToBranch:()=>f1,areFieldKindsCompatible:()=>ip,attributeTypeToWorkflowType:()=>_L,buildWorkflowEntity:()=>rL,collectUsedFields:()=>b1,createEmptyAction:()=>y1,createEmptyCondition:()=>Ub,deserializeWorkflowJson:()=>a1,findNode:()=>xb,findParent:()=>nl,getDefaultOperatorForFieldType:()=>CL,getExpressionModelIssue:()=>wa,getOperatorsForFieldType:()=>np,hasAnyTriggerGeneratingAction:()=>pp,isDayCountValid:()=>Ab,isExpressionModelComplete:()=>Zs,isOperatorCompatible:()=>EL,isTriggerGeneratingAction:()=>$b,moveBranchItemInTree:()=>g1,operatorNeedsValue:()=>Ln,processTriggerFormIdFromScope:()=>db,processTriggerScopeFromScope:()=>cb,removeElseIfInTree:()=>h1,removeNodeFromTree:()=>Fb,serializeToWorkflowJson:()=>o1,supportsClearForActionType:()=>Qf,updateActionInTree:()=>fp,updateConditionInTree:()=>To,validateBusinessRule:()=>w1});var S1=L(()=>{"use strict";ub();nL();Pb();Pb();Bb();Bb();op();Zu();Zu();});var qb=v(mp=>{"use strict";Object.defineProperty(mp,"__esModule",{value:!0});mp.cloneJson=void 0;function Mte(e){return JSON.parse(JSON.stringify(e))}mp.cloneJson=Mte});var x1=v(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.BUSINESS_RULE_NULL_GUID=Do.businessRuleRegistration=Do.BusinessRuleAdapter=void 0;var N1=pt(),tc=(S1(),Br(A1)),_1=Qr(),T1=Q(),Ute=qb(),oi=rn(),Bte=Fm(),qte=pt(),Vte=Jo(),Gte=new Set(["ShowErrorMessage","Recommendation"]);function P1(e){var t,r;return e?[...(t=e.trueBranch)!==null&&t!==void 0?t:[],...(r=e.falseBranch)!==null&&r!==void 0?r:[]].some(n=>Array.isArray(n.trueBranch)||Array.isArray(n.falseBranch)?P1(n):Gte.has(String(n.type))):!1}function Wte(e){return R1((0,Ute.cloneJson)(e))}function R1(e){var t,r;let n=i=>(i??[]).map(o=>zte(o)?R1(o):o);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 zte(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 jte(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new T1.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 T1.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 Hte="00000000-0000-0000-0000-000000000000";Do.BUSINESS_RULE_NULL_GUID=Hte;var Kte=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),Jte=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],Yte=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],Qte=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function $n(e,t){return e===void 0?t:{...e,...t}}var Aa=["kind","id","type","displayName","field","stepName","stepLabels"],D1=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],Xte={Recommendation:[...Aa,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...Aa,"lock"],ShowErrorMessage:[...Aa,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...Aa,...D1],SetDefaultValue:[...Aa,...D1],SetBusinessRequired:[...Aa,"required"],SetVisibility:[...Aa,"visible"]};function ne(e,t){return t===void 0?{}:{[e]:t}}function k1(e){var t;return e==null?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function Vb(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",k1(e.lookupValue)),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function L1(e,t){let r=new Set(t),n={};for(let[i,o]of Object.entries(e))r.has(i)||o!==void 0&&(n[i]=o);return Object.keys(n).length>0?n:void 0}var Zte=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function ere(e){return $n(e.bag,{id:e.id,field:e.field,...Vb(e),...ne("stepName",e.stepName),...ne("displayName",e.displayName)})}function tre(e){let t=L1(e,Zte);return{id:e.id,field:e.field,valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",e.lookupValue),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression),...ne("stepName",e.stepName),...ne("displayName",e.displayName),...ne("bag",t)}}function I1(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",e.lookupValue),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function O1(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var rre=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),nre=new Set,ire="INVALID_CLEAR_FOR_FIELD";function ore(e){let t=n=>{var i;return(0,oi.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,oi.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 o of["clauses","trueBranch","falseBranch"])Array.isArray(i[o])&&(i[o]=i[o].map(r));return i};return r(e)}var hp=class{toArtifact(t){let r=this.residualBag(t,Jte),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 $n(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},o=(0,tc.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return P1(t.rootCondition)}toApiPayload(t,r,n){var i,o;let a=this.fromArtifact(t);a.wfomRoot&&(a.wfomRoot={...a.wfomRoot,name:t.name,title:t.name,primaryEntityName:t.entityLogicalName||a.wfomRoot.primaryEntityName},a.entityLogicalName=a.wfomRoot.primaryEntityName);let s=(0,tc.serializeToWorkflowJson)(a,(i=n?.baseLanguageCode)!==null&&i!==void 0?i:Vte.DEFAULT_LCID),l=(o=a.ruleId)!==null&&o!==void 0?o:(0,N1.newId)();return{Entity:this.buildWorkflowEntity(a,l),WfomJson:s,status:t.status}}createDefault(t){var r,n,i,o,a,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:(o=t.entityLogicalName)!==null&&o!==void 0?o:"",scope:(a=t.scope)!==null&&a!==void 0?a:"Entity",status:(s=t.status)!==null&&s!==void 0?s:"Draft",rootCondition:t.rootCondition===void 0?(0,tc.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(Wte(jte(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,N1.newId)()),u}assignMissingIds(t){return(0,qte.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,oi.isJsonObject)(n)?($1(n,"/rootCondition",r),r):(r.push((0,oi.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(a){return[(0,oi.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=n.rootCondition===null?null:ore(n.rootCondition),o;return r.length===0?o=rre:r.some(a=>a.requiredLevel!==void 0)?o=nre:o=new Set([ire]),(0,tc.validateBusinessRule)(i,r).filter(a=>!o.has(a.kind)).map(a=>(0,oi.issue)(`/rootCondition (${a.nodeId})`,`business-rule-${a.kind}`,a.message))}issuesBlockingPush(t,r=[],n){return this.semanticIssues(t,r)}columnsCheckedAtPush(t){let r;try{r=this.fromArtifact(t)}catch{return[]}let n=new Set,i=a=>{a&&n.add(a)},o=a=>{var s;for(let l of a.clauses)i(l.field),i(l.valueField);for(let l of[...a.trueBranch,...a.falseBranch]){if(l.kind==="condition"){o(l);continue}if(i(l.field),l.type==="SetFieldValue"||l.type==="SetDefaultValue")i(l.valueField);else if(l.type==="Recommendation")for(let u of(s=l.applyActions)!==null&&s!==void 0?s:[])i(u.field),i(u.valueField)}};return r.rootCondition&&o(r.rootCondition),[...n]}residualBag(t,r){return L1(t,r)}buildWorkflowEntity(t,r){return(0,tc.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,Yte),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,Qte),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,Xte[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...ne("stepName",t.stepName),...ne("stepLabels",t.stepLabels),...ne("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(tre),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",...I1(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...I1(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return O1(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return $n(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 $n(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,...ne("value",t.value),...ne("valueField",t.valueField),...ne("lookupValue",k1(t.lookupValue)),...ne("expression",t.expression),...ne("rawExpression",t.rawExpression),...ne("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!Kte.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);sre(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...ne("stepName",t.stepName),...ne("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return $n(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(ere),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return $n(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return $n(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return $n(t.bag,{...r,type:"SetFieldValue",...Vb(t)});case"SetDefaultValue":return $n(t.bag,{...r,type:"SetDefaultValue",...Vb(t)});case"SetBusinessRequired":return $n(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return $n(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return O1(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};Do.BusinessRuleAdapter=hp;function $1(e,t,r){(0,oi.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,oi.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,oi.childObjects)(e,n,t,"branchItem",r).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?$1(o,`${t}/${n}/${a}`,r):are(o,`${t}/${n}/${a}`,r)})}function are(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,oi.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function sre(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function lre(){return{adapter:new hp,api:Bte.businessRuleApi,publish:(e,t,r)=>(0,_1.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,_1.boundEntityPublishScope)(t)}}Do.businessRuleRegistration=lre});var e$=v(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});Io.appRegistration=Io.AppAdapter=Io.HEADER_NAV_BOOLEAN_RULE=void 0;var qi=rn(),Ot=so(),ic=uo(),ure=Qr(),j1=zd(),Gb=Fd(),Wb=lo(),cre=pt(),dre=le(),H1=Jo(),K1=Q(),J1=Ud();Object.defineProperty(Io,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return J1.HEADER_NAV_BOOLEAN_RULE}});var vp="7.0.0.0",F1=`<SiteMap IntroducedVersion="${vp}"></SiteMap>`,M1="/_imgs/imagestrips/transparent_spacer.gif",U1="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",Y1=["Entity","Url","DefaultDashboard","Page","GenPageId"],rc="sitemapId",B1="sitemapName",zb="sitemapNameUnique",q1="aiDescription",V1="[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}",fre=new RegExp(`^(?:\\{${V1}\\}|${V1})$`);function G1(e,t){if(!fre.test(e.trim()))throw new K1.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function W1(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new K1.ValidationError("app",t,[Q1(e)]);return e}function Q1(e){return(0,qi.issue)("/headerAndNavigationRefresh",J1.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function pre(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,dre.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}}function mre(e){var t,r,n,i;let o=[];for(let a of(r=(t=e.siteMap)===null||t===void 0?void 0:t.areas)!==null&&r!==void 0?r:[])for(let s of(n=a.groups)!==null&&n!==void 0?n:[])for(let l of(i=s.subAreas)!==null&&i!==void 0?i:[])l.type==="Entity"&&l.entity&&o.push(l.entity);return o}var wp=class{constructor(t=H1.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=gp(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,Ot.emptyBag)()}}fromArtifact(t){(0,Wb.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,Ot.rebuildRaw)(i,(0,ic.domEngine)(n),null)}fromApiResponse(t){var r,n,i,o,a,s,l,u,c,d,f;(0,Wb.installDomShim)();let m=t??{},p=(r=m.$sitemap)!==null&&r!==void 0?r:m,h=(0,ic.parseXmlRoot)((n=p.sitemapxml)!==null&&n!==void 0?n:F1,F1),g=this.toArtifact(h);return g.id=(i=m.appmoduleid)!==null&&i!==void 0?i:"",g.name=(o=m.name)!==null&&o!==void 0?o:"",g.uniqueName=(a=m.uniquename)!==null&&a!==void 0?a:"",g.description=(s=m.description)!==null&&s!==void 0?s:"",m.aiappdescription&&(g.aiDescription=m.aiappdescription),g.bag={a:[[rc,(u=(l=p.sitemapid)!==null&&l!==void 0?l:m._sitemapid_value)!==null&&u!==void 0?u:""],[B1,(c=p.sitemapname)!==null&&c!==void 0?c:""],[zb,(d=p.sitemapnameunique)!==null&&d!==void 0?d:""],[q1,(f=m.aiappdescription)!==null&&f!==void 0?f:""]],c:[]},g}toApiPayload(t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b;(0,Wb.installDomShim)();let w=(0,ic.serializeNode)(this.fromArtifact(t)),C=[],S=[];for(let k of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let I of(o=k.groups)!==null&&o!==void 0?o:[])for(let D of(a=I.subAreas)!==null&&a!==void 0?a:[])D.type==="Entity"&&D.entity?C.push(D.entity):D.type==="DashBoard"&&D.dashboardId&&S.push(D.dashboardId);let O=(s=t.bag)!==null&&s!==void 0?s:(0,Ot.emptyBag)();return{sitemapId:nc(O,rc)||(t.sitemapId?G1(t.sitemapId,t.id):""),sitemapxml:w,sitemapname:nc(O,B1)||t.name,...nc(O,zb)?{sitemapNameUnique:nc(O,zb)}:{},appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:nc(O,q1))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[Gb.HEADER_AND_NAVIGATION_REFRESH]:W1(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?Gb.APP_SETTING_ON:Gb.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:C,components:{forms:(c=(u=t.components)===null||u===void 0?void 0:u.forms)!==null&&c!==void 0?c:[],views:(f=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&f!==void 0?f:[],charts:(p=(m=t.components)===null||m===void 0?void 0:m.charts)!==null&&p!==void 0?p:[],dashboards:[...(g=(h=t.components)===null||h===void 0?void 0:h.dashboards)!==null&&g!==void 0?g:[],...S],...((b=t.components)===null||b===void 0?void 0:b.mainFormsByTable)!==void 0?{mainFormsByTable:t.components.mainFormsByTable}:{}}}}createDefault(t){var r,n,i,o,a,s;let l=!((r=t.siteMap)===null||r===void 0)&&r.areas&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}],u=(n=t.id)!==null&&n!==void 0?n:(0,cre.newId)();return{id:u,name:(i=t.name)!==null&&i!==void 0?i:"New App",uniqueName:(o=t.uniqueName)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",...t.aiDescription?{aiDescription:t.aiDescription}:{},siteMap:{areas:l},...t.sitemapId?{sitemapId:G1(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:W1(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(Kb):Array.isArray(r.areas)?r.areas.forEach(Kb):Array.isArray(r.groups)?Kb(r):Array.isArray(r.subAreas)?Z1(r):"type"in r&&Cp(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,qi.issue)("/published","published-must-be-boolean",`published must be a boolean, got ${typeof n}`));let i=t.siteMap,o=t.headerAndNavigationRefresh;if(o!==void 0&&typeof o!="boolean"&&r.push(Q1(o)),i==null)return r;if(!(0,qi.isJsonObject)(i))return r.push((0,qi.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let a=(0,qi.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return a.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,qi.childObjects)(l,"groups",c,"group",r).forEach(({node:f,index:m})=>{let p=`${c}/groups/${m}`;(0,qi.childObjects)(f,"subAreas",p,"subArea",r).forEach(({node:g,index:b})=>{let w=`${p}/subAreas/${b}`;(0,qi.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],w,"subarea-type-invalid",r);let C=pre(g);if(!C)return;let S=s.get(C);if(S===void 0){s.set(C,w);return}r.push((0,qi.issue)(w,"subarea-duplicate-target",`the sitemap already navigates to this target at ${S}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}issuesBlockingPush(t){var r;return(0,j1.mainFormSetShapeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsByTable,mre(t))}applyServerIdentity(t,r){let n=r[rc];if(!n)return;t.bag||(t.bag=(0,Ot.emptyBag)());let i=t.bag.a.find(o=>o[0]===rc);i?i[1]=n:t.bag.a.push([rc,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=gp(t,"Group"),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:jb(t,this.lcid),groups:i.map(l=>this.groupToJson(l)),bag:n},a=t.getAttribute("Icon");a&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}groupToJson(t){var r;let{bag:n,modeledEls:i}=gp(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:jb(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:n}}subAreaToJson(t){var r;let{bag:n}=gp(t,null),i=hre(t),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:jb(t,this.lcid),bag:n};if(i==="Entity"){let l=t.getAttribute("Entity");l&&(o.entity=l)}else if(i==="DashBoard"){let l=t.getAttribute("DefaultDashboard");l&&(o.dashboardId=l);let u=t.getAttribute("Url");u&&(o.dashboardUrl=u)}else if(i==="CustomPage"){let l=t.getAttribute("Page");l&&(o.page=l)}else if(i==="GenPage"){let l=t.getAttribute("GenPageId");l&&(o.genPageId=l)}else{let l=t.getAttribute("Url");l&&(o.url=l)}let a=t.getAttribute("Icon");a&&a!==M1&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}rootToRaw(t){var r,n,i,o;let a=(n=(r=t.siteMap)===null||r===void 0?void 0:r.bag)!==null&&n!==void 0?n:(0,Ot.emptyBag)(),l=yp(a)?[["IntroducedVersion",vp]]:[],u=((o=(i=t.siteMap)===null||i===void 0?void 0:i.areas)!==null&&o!==void 0?o:[]).map(c=>this.areaToRaw(c));return{n:"SiteMap",a:(0,Ot.mergeAttrs)(a.a,l),c:(0,Ot.spliceChildren)(a.c,u)}}areaToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,Ot.emptyBag)(),o=yp(i),a=[],s=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",vp]),t.icon!==void 0?a.push(["Icon",t.icon]):bp(i.a,"Icon")&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):bp(i.a,"VectorIcon")&&s.push("VectorIcon");let l=((n=t.groups)!==null&&n!==void 0?n:[]).map(c=>this.groupToRaw(c)),u=Hb((0,Ot.spliceChildren)(i.c,l),t.title,o,this.lcid);return{n:"Area",a:(0,Ot.mergeAttrs)(i.a,a,s),c:u}}groupToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,Ot.emptyBag)(),o=yp(i),a=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",vp],["IsProfile","false"]);let s=((n=t.subAreas)!==null&&n!==void 0?n:[]).map(u=>this.subAreaToRaw(u)),l=Hb((0,Ot.spliceChildren)(i.c,s),t.title,o,this.lcid);return{n:"Group",a:(0,Ot.mergeAttrs)(i.a,a),c:l}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,Ot.emptyBag)(),i=yp(n),o=yre(n.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]);let l=!i&&!n.a.some(([c])=>Y1.includes(c));vre(a,t,l),i?(a.push(["ResourceId","SitemapDesigner.NewSubArea"],["Client","All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web"],["Sku","All,OnPremise,Live,SPLA"],["AvailableOffline","true"],["PassParams","false"]),t.icon&&a.push(["Icon",t.icon])):t.icon!==void 0?a.push(["Icon",t.icon]):bp(o,"Icon",M1)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):bp(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",U1]):s.push("VectorIcon"):t.type==="GenPage"&&!gre(o,"VectorIcon")&&a.push(["VectorIcon",U1]);let u=Hb((0,Ot.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,Ot.mergeAttrs)(o,a,s),c:u}}};Io.AppAdapter=wp;function gp(e,t){let r=(0,ic.nodeLikeFromDom)(e).getAllProperties().map(s=>[s.key,s.value]),n=[],i=[],o=e.childNodes,a=0;for(let s=0;s<o.length;s+=1){let l=o[s];l.nodeType!==1&&l.nodeType!==3||(l.nodeType===1&&t!==null&&l.tagName===t?i.push(l):n.push({i:a,node:(0,Ot.rawFromNode)((0,ic.nodeLikeFromDom)(l))}),a+=1)}return{bag:{a:r,c:n},modeledEls:i}}function z1(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}function jb(e,t){var r;let n=z1(e,"Titles")[0];if(!n)return"";let o=z1(n,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(r=o.getAttribute("Title"))!==null&&r!==void 0?r:""}function hre(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function yp(e){return e.a.length===0&&e.c.length===0}function gre(e,t){return e.some(([r])=>r===t)}function bp(e,t,r){let n=e.find(([o])=>o===t),i=n?.[1];return!!i&&i!==r}function nc(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function yre(e,t){let r=bre(t);return e.filter(([n])=>!Y1.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function bre(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 vre(e,t,r){var n,i,o,a,s;switch(t.type){case"Entity":e.push(["Entity",(n=t.entity)!==null&&n!==void 0?n:""]);break;case"URL":(t.url!==void 0||!r)&&e.push(["Url",(i=t.url)!==null&&i!==void 0?i:""]);break;case"DashBoard":e.push(["DefaultDashboard",(o=t.dashboardId)!==null&&o!==void 0?o:""]),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",(s=t.genPageId)!==null&&s!==void 0?s:""]);break;default:break}}function Hb(e,t,r,n){if(!t)return e;let i=e.findIndex(o=>o.n==="Titles");if(i>=0){let o=e.slice();return o[i]=wre(e[i],t,n),o}return r?[Cre(t,n),...e]:e}function wre(e,t,r){let n=!1,i=e.c.map(o=>!n&&o.n==="Title"&&Ere(o,"LCID")===String(r)?(n=!0,{n:o.n,a:(0,Ot.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return n||i.unshift(X1(t,r)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function Cre(e,t){return{n:"Titles",a:[],c:[X1(e,t)]}}function X1(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function Ere(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function Are(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function Cp(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${Are(8)}`)}function Kb(e){var t;Cp(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])Z1(r)}function Z1(e){var t;Cp(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])Cp(r,"subarea")}function Sre(e=H1.DEFAULT_LCID){return{adapter:new wp(e),api:j1.appApi,languageSensitive:!0,publish:(t,r)=>(0,ure.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]}),rebaselineAfterPublish:"bracket"}}Io.appRegistration=Sre});var t$={};Jr(t$,{ActionType:()=>Yb,AppActionOrigin:()=>iv,AppActionVisibilityType:()=>nv,ButtonType:()=>Xb,CannotUpdateAppActionColumns:()=>Nre,Context:()=>ev,IconType:()=>Qb,Location:()=>Zb,OnClickEventType:()=>rv,Scope:()=>tv,VisibilityType:()=>Jb});var Jb,Yb,Qb,Xb,Zb,ev,tv,rv,nv,iv,Nre,r$=L(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(Jb||(Jb={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(Yb||(Yb={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(Qb||(Qb={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(Xb||(Xb={}));(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"})(Zb||(Zb={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(ev||(ev={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(tv||(tv={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(rv||(rv={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(nv||(nv={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(iv||(iv={}));Nre=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var u$=v(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.assertOneWritePerRow=Pt.commandApi=Pt.COMMAND_DUPLICATE_ROW_CODE=Pt.COMMAND_ROW_NOT_IN_BAR_CODE=Pt.COMMAND_TABLE_MISMATCH_CODE=void 0;var ov=Lt(),Lr=ye(),Vi=Q(),$r=le();Pt.COMMAND_TABLE_MISMATCH_CODE="COMMAND_TABLE_MISMATCH";Pt.COMMAND_ROW_NOT_IN_BAR_CODE="COMMAND_ROW_NOT_IN_BAR";Pt.COMMAND_DUPLICATE_ROW_CODE="COMMAND_DUPLICATE_ROW";var _re="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function av(e,t){let r=`/EntityDefinitions(LogicalName='${(0,$r.odataPathLiteral)(t)}')${(0,$r.odataQuery)([["$select","MetadataId"]])}`,i=(0,Lr.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,o=i?.MetadataId;return o?(0,$r.normalizeGuid)(o,"entityMetadataId"):""}function sv(e,t){return t?`_contextentity_value eq ${t}`:`contextvalue eq '${(0,$r.odataLiteral)(e)}'`}function oc(e){return`Nothing was written. Re-fetch the command with fetchArtifact('command', '${e}', { overwrite: true }) \u2014 this discards local edits \u2014 and re-apply the change.`}function n$(e,t){let r=e.entityLogicalName;if(t===void 0)return r;if(typeof r!="string"||r.toLowerCase()!==t.toLowerCase())throw new Vi.SdkError(Pt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': its JSON names table '${String(r)}'. A command's id is its table, so the push would write another table's command bar. Nothing was written. Fix its entityLogicalName, or push it under that table's id.`);return t}async function i$(e,t,r){let n=await av(e,t);if(r){let i=(0,$r.normalizeGuid)(r,"entityMetadataId");if(i!==n)throw new Vi.SdkError(Pt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': it was fetched for table id ${i}, but table '${t}' is ${n||"not resolvable"} on the server \u2014 the table was re-created, or the local copy edited. `+oc(t))}return n}Pt.commandApi={async get(e,t){let r=t,n=await av(e,r),i=sv(r,n),o=`/appactions${(0,$r.odataQuery)([["$expand",_re],["$filter",i]])}`,a,s=await(0,ov.collectPages)(e,o,"fetchArtifact('command')",c=>{a=c}),l={entityLogicalName:r,entityMetadataId:n,appActions:s},u={};for(let c of s){let d=typeof c.appactionid=="string"?c.appactionid:void 0;if(d){let f=c["@odata.etag"];u[(0,$r.normalizeGuid)(d,"appactionid")]=typeof f=="string"?f:null}}return{raw:l,etag:a?(0,Lr.readEtag)(a):null,memberEtags:u}},async list(e,t){let r=t?.entityLogicalName;return r?[{type:"command",id:r,name:`${r} commands`,entityLogicalName:r,isDirty:!1}]:[]},async create(e,t,r){let n=t,i=n$(n,r),o=await i$(e,i,n.entityMetadataId);return o$(e,i,{...n,entityMetadataId:o},!1)},async update(e,t,r,n,i){let o=r,a=n$(o,t),s=await i$(e,a,o.entityMetadataId);return o$(e,a,{...o,entityMetadataId:s},!0,i)},async delete(e,t){let r=await av(e,t),n=`/appactions${(0,$r.odataQuery)([["$select","appactionid"],["$filter",sv(t,r)]])}`,i=await(0,ov.collectPages)(e,n,"deleteArtifact('command')");for(let o of i)o.appactionid&&await(0,Lr.deleteRecord)(e,"appactions",o.appactionid)}};async function o$(e,t,r,n,i){let o=r.entityMetadataId?(0,$r.normalizeGuid)(r.entityMetadataId,"entityMetadataId"):"",a=await Dre(e,t,r,o,n,i),s={};try{await Ore(e,a,o,s)}catch(l){throw(0,Vi.withPartialTokens)(l,{memberEtags:s})}return{id:r.entityLogicalName,etag:null,memberEtags:s}}function lv(e){return e.replace(/[{}]/g,"").toLowerCase()}function l$(e,t){var r;let n=new Map,i=[...t.rows.map(o=>[o.appactionid,"written"]),...((r=t.deletedRowIds)!==null&&r!==void 0?r:[]).map(o=>[o,"deleted"])];for(let[o,a]of i){let s=lv(o),l=n.get(s);if(l===void 0){n.set(s,a);continue}throw new Vi.SdkError(Pt.COMMAND_DUPLICATE_ROW_CODE,l===a?`Refusing to push command '${e}': app action '${s}' appears twice in it \u2014 two of its controls or groups carry that id, as one copied together with its id or bag does \u2014 so one would silently replace or remove the other. Nothing was written. Remove the id and the bag from the copy, so it is created as a new one, and push again.`:`Refusing to push command '${e}': app action '${s}' would be both written and deleted \u2014 one of its controls or groups spells that id differently (case or braces) than the copy last fetched or pushed \u2014 so the delete would remove what the write saved. Nothing was written. Spell the id as it was, and push again.`)}}Pt.assertOneWritePerRow=l$;var Tre={entities:/^\/entities\(([^()]+)\)$/,appactions:/^\/appactions\(([^()]+)\)$/};function a$(e,t){let r=Tre[t].exec(e);return r?lv(r[1]):void 0}async function Dre(e,t,r,n,i,o){var a,s;l$(t,r);let l=Pre(r.rows),u=new Set(l.map(f=>lv(f.appactionid))),c={writes:[],deletes:[]};for(let f of l){let m=f.body["[email protected]"];if(m!==void 0&&!(typeof m=="string"&&n!==""&&a$(m,"entities")===n))throw new Vi.SdkError(Pt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' binds to ${typeof m=="string"?`'${m}'`:String(m)}, not to table '${t}' (${n?`/entities(${n})`:"whose id is not resolvable"}). `+oc(t));let p=f.body["[email protected]"];if(typeof p=="string"){let h=a$(p,"appactions");if(h===void 0||!u.has(h))throw new Vi.SdkError(Pt.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' would be placed under '${p}', which is not a row of this command. `+oc(t))}if(i&&f.exists){let h=(0,$r.normalizeGuid)(f.appactionid,"id"),g=(a=o?.[h])!==null&&a!==void 0?a:f.etag;if(!(0,Lr.isVersionToken)(g))throw s$(t,h,"update",g);c.writes.push({kind:"patch",row:f,id:h,token:g})}else{if(m===void 0&&!n)throw new Vi.SdkError("COMMAND_CONTEXT_ENTITY_UNRESOLVED",`Cannot create app action '${f.appactionid}' for entity '${r.entityLogicalName}': the entity MetadataId could not be resolved, so the required ContextEntity bind cannot be set. A row written without it is created but is permanently unreadable \u2014 commandApi.get filters on _contextentity_value. Verify the entity logical name exists and is readable, then retry.`);c.writes.push({kind:"post",row:f})}}for(let f of(s=r.deletedRowIds)!==null&&s!==void 0?s:[]){let m=(0,$r.normalizeGuid)(f,"id"),p=o?.[m];if(!(0,Lr.isVersionToken)(p))throw s$(t,m,"delete",p);c.deletes.push({id:m,token:p})}let d=[...c.writes.flatMap(f=>f.kind==="patch"?[{id:f.id,verb:"update"}]:[]),...c.deletes.map(f=>({id:f.id,verb:"delete"}))];if(d.length>0){let f=await Ire(e,t,n),m=d.find(p=>!f.has(p.id));if(m)throw new Vi.SdkError(Pt.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': it would ${m.verb} app action '${m.id}', which is not in table '${t}''s command bar on the server \u2014 a row of another table, or one deleted since the fetch. `+oc(t))}return c}function s$(e,t,r,n){return new Vi.SdkError(Lr.UPDATE_NO_ETAG_CODE,`Refusing to push command '${e}': ${typeof n=="string"&&n!==""?`the token held for app action '${t}' ('${n}') is not a version`:`no token is held for app action '${t}'`}, so its ${r} could not be made conditional and would overwrite or remove a concurrent edit. `+oc(e))}async function Ire(e,t,r){let n=`/appactions${(0,$r.odataQuery)([["$select","appactionid"],["$filter",sv(t,r)]])}`,i=await(0,ov.collectPages)(e,n,"pushArtifact('command') bar membership"),o=new Set;for(let a of i)typeof a.appactionid=="string"&&o.add((0,$r.normalizeGuid)(a.appactionid,"appactionid"));return o}async function Ore(e,t,r,n){for(let i of t.writes)if(i.kind==="patch"){let o=(0,Lr.echoWrite)("appactionid",{"If-Match":i.token}),a=`/appactions(${i.id})${o.query}`,s=(0,Lr.ensureSuccess)(await e.patch(a,i.row.body,o.options),e.apiUrl(a));n[i.id]=(0,Lr.readEtag)(s)}else{let o=(0,Lr.echoWrite)("appactionid"),a=`/appactions${o.query}`,s={...i.row.body};s["[email protected]"]===void 0&&(s["[email protected]"]=`/entities(${r})`);let l=(0,Lr.ensureSuccess)(await e.post(a,s,o.options),e.apiUrl(a)),u=(0,Lr.readCreatedId)(l,"appactionid");u&&(n[(0,$r.normalizeGuid)(u,"appactionid")]=(0,Lr.readEtag)(l))}for(let{id:i,token:o}of[...t.deletes].reverse())await(0,Lr.deleteRecord)(e,"appactions",i,o),delete n[i]}function Pre(e){let t=new Map(e.map(o=>[o.appactionid,o])),r=new Set,n=[],i=o=>{if(r.has(o.appactionid))return;let a=o.body["[email protected]"];if(typeof a=="string"){let s=/\(([^)]+)\)/.exec(a),l=s?t.get(s[1]):void 0;l&&i(l)}r.add(o.appactionid),n.push(o)};return e.forEach(i),n}});var N$=v(il=>{"use strict";Object.defineProperty(il,"__esModule",{value:!0});il.commandRegistration=il.CommandAdapter=void 0;var ct=(r$(),Br(t$)),c$=Qr(),wt=rn(),p$=u$(),m$=pt(),ol=le(),h$=Q(),dv="$ClientSvg:",fv=".svg",Rre=2,kre=1,Lre=1,g$="entityMetadataId",$re=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"]),Ep=class{toArtifact(t){var r,n,i,o,a,s,l;let u=(r=t.appActions)!==null&&r!==void 0?r:[],c=(n=t.entityLogicalName)!==null&&n!==void 0?n:"",d=u.find(h=>typeof h.appactionid!="string"||h.appactionid==="");if(d)throw new h$.InvalidArgumentError(`Cannot read the command bar of '${c}': app action row '${String((i=d.name)!==null&&i!==void 0?i:"")}' has no appactionid (its primary key), so it cannot be placed in the bar or written back.`);let f=new Map;for(let h of u){let g=typeof h._parentappactionid_value=="string"&&h._parentappactionid_value?h._parentappactionid_value:"",b=(o=f.get(g))!==null&&o!==void 0?o:[];b.push(h),f.set(g,b)}let m=new Map;for(let h of(a=f.get(""))!==null&&a!==void 0?a:[]){let g=Bre(h.location),b=(s=m.get(g))!==null&&s!==void 0?s:[];b.push(h),m.set(g,b)}let p=[];for(let[h,g]of m)p.push({location:h,groups:Fre(g,f,w$(h),c)});return{id:c,entityLogicalName:c,commandBars:Ure(p),bag:{a:[[g$,(l=t.entityMetadataId)!==null&&l!==void 0?l:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:mv(t),appActions:uv(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?uv(r).map(l=>l.appactionid):[]),i=uv(t,new Set([...n].map(l=>l.toLowerCase()))),o=new Set(i.map(l=>l.appactionid)),a=i.map(l=>{let u=l.exists||n.has(l.appactionid);return{appactionid:l.appactionid,exists:u,etag:l.etag,body:u?Zre(l.row):S$(l.row)}}),s=[...n].filter(l=>!o.has(l));return(0,p$.assertOneWritePerRow)(t.entityLogicalName,{rows:a,deletedRowIds:s}),{entityLogicalName:t.entityLogicalName,entityMetadataId:mv(t),rows:a,...s.length>0?{deletedRowIds:s}:{}}}createDefault(t){var r,n,i,o;let a=(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:a,entityLogicalName:a,commandBars:(o=t.commandBars)!==null&&o!==void 0?o:[]}}assignMissingIds(t){return(0,m$.assignMissingIds)(t)}normalize(t){let r=Wre(t),n=!1,i=(Array.isArray(t.commandBars)?t.commandBars:[]).map(o=>{let a=(0,wt.isJsonObject)(o)&&Array.isArray(o.groups)?o.groups:void 0;if(!a)return o;let s=!1,l=a.map(u=>{let c=(0,wt.isJsonObject)(u)&&Array.isArray(u.controls)?u.controls:void 0;if(!c)return u;let d=c.map(f=>E$(f,r));return d.every((f,m)=>f===c[m])?u:(s=!0,{...u,controls:d})});return s?(n=!0,{...o,groups:l}):o});return n?{...t,commandBars:i}:t}validate(t){let r=[];return(0,wt.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,wt.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",r),(0,wt.childObjects)(i,"groups",a,"group",r).forEach(({node:l,index:u})=>{let c=`${a}/groups/${u}`;Np(l.bag)||((0,wt.optionalGuidId)(l,"id",c,"group-id-invalid",r),typeof l.title=="string"&&l.title.length>0&&r.push({pointer:`${c}/title`,rule:"group-toplevel-title-unsupported",message:"a new top-level command group cannot have a title: Dataverse rejects a Group row with no parent (0x80040265). Leave the title empty to hold the commands without creating a group row, or nest them under a FlyoutAnchor control, which supplies the parent a group needs."})),y$((0,wt.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};il.CommandAdapter=Ep;function Np(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function y$(e,t,r){e.forEach(({node:n,index:i})=>{let o=`${t}/${i}`;Np(n.bag)||(0,wt.optionalGuidId)(n,"id",o,"control-id-invalid",r),(0,wt.optionalEnum)(n,"type",["Button","FlyoutAnchor","SplitButton"],o,"control-type-invalid",r);let a=n.location;a!==void 0&&(typeof a!="number"||!Number.isInteger(a)||a<0||a>6)&&r.push((0,wt.issue)(`${o}/location`,"control-location-invalid",`location must be an integer 0-6 when present, got ${JSON.stringify(a)}`)),n.action!==void 0&&n.action!==null&&((0,wt.isJsonObject)(n.action)?(0,wt.optionalEnum)(n.action,"type",["javascript"],`${o}/action`,"action-type-invalid",r):r.push((0,wt.issue)(`${o}/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",o,"control",r);s.length>0&&y$(s,`${o}/children`,r)})}function pv(e){return{a:Object.entries(e)}}function xre(e){return Object.fromEntries(e.a)}function ac(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function mv(e){let t=ac(e.bag,g$);return typeof t=="string"?t:""}function Fre(e,t,r,n){var i,o;let a=[],s=[];for(let l of Sp(e))l.type===ct.ButtonType.Group?a.push({id:v$(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:Sp((o=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(u=>Ap(u,t,r,n)),bag:pv(l)}):s.push(Ap(l,t,r,n));return s.length>0&&a.unshift({id:Xre(n,r),title:"",controls:s}),a}function hv(e){let t=e.bag?ac(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function Ap(e,t,r,n){var i,o,a,s,l;let u=v$(e.name,n),c={id:u,type:qre(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:pv(e)},d=b$(e);d&&(c.icon=d);let f=Mre(e);f&&(c.action=f),typeof e.hidden=="boolean"&&(c.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(c.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(c.location=e.location);let m=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(m&&m.length>0){let p=[],h=[];for(let g of Sp(m))if(g.type===ct.ButtonType.Group){let b=(o=g.appactionid)!==null&&o!==void 0?o:"",w=pv(g);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(a=g.appactionid)!==null&&a!==void 0?a:void 0,c.flyoutGroupBag=w);let C=[];for(let S of Sp((l=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let O=Ap(S,t,r,n);p.push(O),C.push(hv(O))}h.push({id:b,bag:w,childIds:C})}else p.push(Ap(g,t,r,n));c.children=p,h.length>1&&(c.flyoutGroups=h)}return c}function b$(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(dv)?e.fonticon.slice(dv.length)+fv:e.fonticon}function Mre(e){var t;let r=e.onclickeventjavascriptfunctionname;if(typeof r!="string"||!r)return;let n=e.OnClickEventJavaScriptWebResourceId,i=e._onclickeventjavascriptwebresourceid_value,o={type:"javascript",webResourceId:(t=typeof i=="string"?i:n?.webresourceid)!==null&&t!==void 0?t:"",functionName:r};n?.name&&(o.libraryName=n.name);let a=e.onclickeventjavascriptparameters;return typeof a=="string"&&a&&(o.parameters=a),o}function d$(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function Sp(e){return[...e].sort((t,r)=>d$(t)-d$(r))}function Ure(e){let t={MainTab:0,ContextualTab:1,HomeTab:2};return[...e].sort((r,n)=>{var i,o;return((i=t[r.location])!==null&&i!==void 0?i:9)-((o=t[n.location])!==null&&o!==void 0?o:9)})}function v$(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 Bre(e){switch(e){case ct.Location.Form:case ct.Location.QuickForm:return"MainTab";case ct.Location.HomePageGrid:case ct.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function w$(e){switch(e){case"MainTab":return ct.Location.Form;case"HomeTab":return ct.Location.HomePageGrid;default:return ct.Location.SubGridStandard}}function qre(e){switch(e){case ct.ButtonType.Dropdown:return"FlyoutAnchor";case ct.ButtonType.Split:return"SplitButton";default:return"Button"}}function Vre(e){switch(e){case"FlyoutAnchor":return ct.ButtonType.Dropdown;case"SplitButton":return ct.ButtonType.Split;default:return ct.ButtonType.Standard}}function Gre(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function C$(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 uv(e,t=new Set){var r,n,i,o;let a=[],s=mv(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=w$(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(m=>{var p;return(p=m.controls)!==null&&p!==void 0?p:[]}),d=c.length>0&&c.every(m=>!C$(m,t)),f=0;for(let m of(i=l.groups)!==null&&i!==void 0?i:[]){let p;if(Gre(m)){let h=jre(m,u,void 0,e,s);a.push(h),p=h.appactionid}for(let h of(o=m.controls)!==null&&o!==void 0?o:[])A$(h,u,p,e,s,a,d?f:void 0,t),f+=1}}return a}function E$(e,t){if(!(0,wt.isJsonObject)(e))return e;let r=e.children,n=r,i=!1;Array.isArray(r)&&(n=r.map(s=>E$(s,t)),i=n.some((s,l)=>s!==r[l]));let o=!Np(e.bag)&&(typeof e.id!="string"||e.id.trim()==="");if(!o&&!i)return e;let a;if(o){do a=(0,m$.newId)();while(t.has(a));t.add(a)}return{...e,...a!==void 0?{id:a}:{},...i?{children:n}:{}}}function Wre(e){let t=new Set,r=(o,...a)=>{if((0,wt.isJsonObject)(o))for(let s of[...a.map(l=>o[l]),Np(o.bag)?ac(o.bag,"appactionid"):void 0])typeof s=="string"&&s.trim()!==""&&t.add(s.toLowerCase())},n=o=>{(0,wt.isJsonObject)(o)&&(r(o,"id","flyoutGroupId"),r({bag:o.flyoutGroupBag}),(Array.isArray(o.flyoutGroups)?o.flyoutGroups:[]).forEach(a=>r(a,"id")),(Array.isArray(o.children)?o.children:[]).forEach(n))},i=e.commandBars;return(Array.isArray(i)?i:[]).forEach(o=>{let a=(0,wt.isJsonObject)(o)?o.groups:void 0;(Array.isArray(a)?a:[]).forEach(s=>{r(s,"id");let l=(0,wt.isJsonObject)(s)?s.controls:void 0;(Array.isArray(l)?l:[]).forEach(n)})}),t}function A$(e,t,r,n,i,o,a,s=new Set){var l;let u=zre(e,t,r,n,i,a);o.push(u);let c=(l=e.children)!==null&&l!==void 0?l:[];if(c.length===0&&!(e.flyoutGroups&&e.flyoutGroups.length>0))return;let d=c.every(h=>!C$(h,s)),f=(h,g,b)=>{A$(h,t,g,n,i,o,d?b:void 0,s)},m=e.flyoutGroups;if(m&&m.length>0){let h=new Map(c.map(S=>[hv(S),S])),g=new Set,b=0,w;for(let[S,O]of m.entries()){let k=O.id||(S===0?cv(u.appactionid):yv("flyout-group",`${u.appactionid}#${S}`)),I=f$(k,t,u.appactionid,n,i,O.bag);o.push(I);let D=I.appactionid;w===void 0&&(w=D);for(let P of O.childIds){let x=h.get(P);!x||g.has(P)||(g.add(P),f(x,D,b),b+=1)}}let C=w??cv(u.appactionid);for(let S of c){let O=hv(S);g.has(O)||(g.add(O),f(S,C,b),b+=1)}return}let p=e.flyoutGroupId||cv(u.appactionid);o.push(f$(p,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,g]of c.entries())f(g,p,h)}function zre(e,t,r,n,i,o){let a=gv(e,t,r,n,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let l=b$(s);return e.location!==void 0&&(s.location=e.location),s.type=Vre(e.type),s.buttonlabeltext=e.label,Kre(s,e.icon,l),Yre(s,e.action),Jre(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function jre(e,t,r,n,i){let o=gv(e,t,r,n,i);return o.row.type=ct.ButtonType.Group,o.row.grouptitle=e.title,o}function f$(e,t,r,n,i,o){let a=gv({id:e,bag:o},t,r,n,i),s=a.row;return s["[email protected]"]=`/appactions(${(0,ol.normalizeGuid)(r,"Command flyout group id")})`,s.type=ct.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),a}function gv(e,t,r,n,i){let o,a,s,l;if(e.bag&&e.bag.a.length>0){o=xre(e.bag),a=!0;let u=ac(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=ac(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else{if(typeof e.id!="string"||e.id.trim()==="")throw new h$.InvalidArgumentError(`Cannot serialize command '${n.entityLogicalName}': a new control has no id. Its primary key is minted once, before the first push, by normalize() \u2014 serialize the normalized artifact.`);l=e.id,o=Hre(l,t,n,i),a=!1,s=null}return r?o["[email protected]"]=`/appactions(${(0,ol.normalizeGuid)(r,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==ct.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:l,exists:a,etag:s,row:o}}function Hre(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:ct.Context.Entity,contextvalue:r.entityLogicalName,scope:ct.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,ol.normalizeGuid)(n,"Command context entity metadata id")})`),i}function Kre(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,ol.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(fv)?dv+t.slice(0,t.length-fv.length):t,e.IconWebResourceId=null}function Jre(e){let t=(n,i)=>{let o=e[n];if(typeof o!="string"||o.length===0||e[`${i}@odata.bind`]!==void 0)return;let a=(0,ol.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===kre&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===Lre)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function Yre(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=Rre,t.webResourceId){let r=(0,ol.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 Qre(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 yv(e,t){let r="";for(let n=0;n<4;n+=1)r+=Qre(`${n}:${e}:${t}`).toString(16).padStart(8,"0");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function cv(e){return yv("flyout-group",e)}function Xre(e,t){return yv("loose-group",`${e}|${t}`)}function S$(e){let t={...e};for(let r of $re)delete t[r];return t}function Zre(e){let t=S$(e);for(let r of ct.CannotUpdateAppActionColumns)delete t[r];return t}function ene(){return{adapter:new Ep,api:p$.commandApi,publish:(e,t,r)=>(0,c$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,c$.boundEntityPublishScope)(t)}}il.commandRegistration=ene});var T$=v(_p=>{"use strict";Object.defineProperty(_p,"__esModule",{value:!0});_p.chartApi=void 0;var tne=Lt(),xr=ye(),Sa=le(),_$="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",rne="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";_p.chartApi={async get(e,t){let r=(0,Sa.normalizeGuid)(t,"id"),n=await(0,xr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Sa.odataQuery)([["$select",_$]]);return{raw:(0,xr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,Sa.normalizeGuid)(t,"id"),n=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Sa.odataQuery)([["$select",_$]]),i=(0,xr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,xr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueryvisualizations${(0,Sa.odataQuery)([["$select",rne],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,Sa.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,tne.collectPages)(e,r,"listArtifacts('chart')")).map(i=>{var o,a;return{type:"chart",id:(o=i.savedqueryvisualizationid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.primaryentitytypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,xr.echoWrite)("savedqueryvisualizationid"),o=`/savedqueryvisualizations${i.query}`,a=(0,xr.ensureSuccess)(await e.post(o,(0,xr.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(o));return{id:(0,xr.resolveCreatedId)(a,"savedqueryvisualizationid","chart",r),etag:(0,xr.readEtag)(a)}},async update(e,t,r,n){let i=r,o=(0,Sa.normalizeGuid)(t,"id"),a=(0,xr.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,xr.requireEtag)(n,"chart",o)}),s=`/savedqueryvisualizations(${o})${a.query}`,l=(0,xr.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,datadescription:i.datadescription,presentationdescription:i.presentationdescription},a.options),e.apiUrl(s));return{id:o,etag:(0,xr.readEtag)(l)}},delete(e,t){return(0,xr.deleteRecord)(e,"savedqueryvisualizations",t)}}});var W$=v(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});sl.chartRegistration=sl.ChartAdapter=void 0;var bv=so(),D$=rn(),ai=uo(),I$=Qr(),nne=T$(),vv=lo(),ine=pt(),one=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],ane=new Map(one.map(e=>[e.toLowerCase(),e]));function L$(e){var t;return e&&(t=ane.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function sne(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function lne(e){var t,r;let n=e.entityLogicalName,i=e.series.map((h,g)=>({alias:`agg_${g}`,series:h})),o=e.categories.map((h,g)=>({alias:`grp_${g}`,category:h})),a=h=>`<attribute alias="${h.alias}" name="${al(h.series.attribute)}" aggregate="${al(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${al(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${al(h.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(h,g)=>{if(!h){l.push(g);return}let b=u.get(h);b?b.push(g):u.set(h,[g])};i.forEach(h=>c(h.series.relatedEntity,a(h))),o.forEach(h=>c(h.category.relatedEntity,s(h)));let d=[...u.entries()].map(([h,g])=>`<link-entity name="${al(h)}">${g.join("")}</link-entity>`).join(""),f=l.join("")+d,m=i.map(h=>`<measurecollection><measure alias="${h.alias}" /></measurecollection>`).join(""),p=(r=(t=o[0])===null||t===void 0?void 0:t.alias)!==null&&r!==void 0?r:"";return`<datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="${al(n)}">${f}</entity></fetch></fetchcollection><categorycollection><category alias="${p}">${m}</category></categorycollection></datadefinition>`}var Tp=class{toArtifact(t){var r,n,i,o,a,s,l;(0,vv.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,ai.parseXmlRoot)(u,"<datadefinition/>"),f=(0,ai.parseXmlRoot)(c,"<Chart/>");return{id:(i=t.savedqueryvisualizationid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.primaryentitytypecode)!==null&&s!==void 0?s:"",chartType:Dp(f),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:F$(d),categories:M$(d),presentation:$$(f),dataBag:u?(0,ai.projectElementBag)(d):void 0,presentationBag:c?(0,ai.projectElementBag)(f):void 0,rowBag:une(t.charttype,t.type)}}fromArtifact(t){(0,vv.installDomShim)();let{datadescription:r,presentationdescription:n}=cne(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:O$(t.rowBag,"charttype"),type:O$(t.rowBag,"type"),isdefault:t.isDefault}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,o,a,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:(o=u.presentationdescription)!==null&&o!==void 0?o:"",primaryentitytypecode:(a=u.primaryentitytypecode)!==null&&a!==void 0?a:"",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,o,a,s,l;(0,vv.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,ine.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New Chart",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:u,chartType:(a=t.chartType)!==null&&a!==void 0?a:"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,D$.childObjects)(n,"series","","series",r),(0,D$.childObjects)(n,"categories","","category",r),r}};sl.ChartAdapter=Tp;function une(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 O$(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 Dp(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return L$(t[r].getAttribute("ChartType"));return"Column"}function $$(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],o=((t=i?.textContent)!==null&&t!==void 0?t:"").trim();return o&&(r.title=o),r}function Ip(e){return e.getElementsByTagName("fetch")[0]}function x$(e){let t=new Map;if(!e)return t;let r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("alias")||l.getAttribute("name");u&&t.set(u,o)}}return t}function F$(e){let t=Ip(e);if(!t)return[];let r=x$(t),n=t.getElementsByTagName("attribute"),i=[];for(let o=0;o<n.length;o+=1){let a=n[o],s=a.getAttribute("aggregate");if(!s)continue;let l=a.getAttribute("name");if(!l)continue;let u={attribute:l,aggregate:s},c=a.getAttribute("charttype");c&&(u.seriesType=L$(c));let d=a.getAttribute("alias");d&&(u.alias=d);let f=d||l,m=r.get(f);m&&(u.relatedEntity=m),i.push(u)}return i}function M$(e){var t;let r=Ip(e);if(!r)return[];let n=x$(r),i=r.getElementsByTagName("attribute"),o=[];for(let a=0;a<i.length;a+=1){let s=i[a];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 f=d||l,m=n.get(f);m&&(u.relatedEntity=m),o.push(u)}return o}function cne(e){var t,r;let n=(t=e.series)!==null&&t!==void 0?t:[],i=(r=e.categories)!==null&&r!==void 0?r:[];if(!P$(e.dataBag)||!P$(e.presentationBag)){let c=lne({...e,series:n,categories:i});return{datadescription:c,presentationdescription:Ine(e,c)}}let o=new DOMParser().parseFromString("<root/>","text/xml"),a=R$(e.dataBag,"datadefinition",o),s=R$(e.presentationBag,"Chart",o),l=e.chartType||Dp(s),u=F$(a);if(!wv(n,u)){let c=Cv(a);dne(o,a,n);let d=Cv(a),f=d.length>0?d:n.map(()=>"");U$(o,s,f,c,l)}return wv(i,M$(a))||fne(o,a,i),e.chartType&&e.chartType!==Dp(s)&&V$(s,e.chartType),e.presentation&&!wv(e.presentation,$$(s))&&G$(s,e.presentation),{datadescription:(0,ai.serializeNode)(a),presentationdescription:(0,ai.serializeNode)(s)}}function P$(e){return!!e&&(e.c.length>0||e.a.length>0)}function U$(e,t,r,n,i){let o,a=t.childNodes;for(let d=0;d<a.length;d+=1)if(a[d].nodeType===1&&a[d].tagName==="Series"){o=a[d];break}o||(o=e.createElement("Series"),t.insertBefore(o,t.firstChild));let s=[],l=o.childNodes;for(let d=0;d<l.length;d+=1)l[d].nodeType===1&&l[d].tagName==="Series"&&s.push(l[d]);let u=new Map;n.forEach((d,f)=>{let m=s[f];if(!m)return;let p=u.get(d);p?p.push(m):u.set(d,[m])});let c=r.map(d=>{let f=u.get(d),m=f&&f.length>0?f.shift():void 0;if(m)return m;let p=e.createElement("Series");p.setAttribute("ChartType",i);let h=s.length>0?s[0].getAttribute("ChartArea"):null;return h&&p.setAttribute("ChartArea",h),p});for(let d of s)o.removeChild(d);for(let d of c)o.appendChild(d)}function Cv(e){let t=[],r=e.getElementsByTagName("measure");for(let n=0;n<r.length;n+=1)t.push(r[n].getAttribute("alias")||"");return t}function R$(e,t,r){let n={n:t,a:(0,bv.mergeAttrs)(e.a,[]),c:(0,bv.spliceChildren)(e.c,[])};return(0,bv.rebuildRaw)(n,(0,ai.domEngine)(r),null)}function dne(e,t,r){let n=Ip(t),i=n?.getElementsByTagName("entity")[0];!n||!i||B$(e,t,i,vne(n),r,Cne,{aliasPrefix:"aggregate_column",addRef:hne,removeRef:bne})}function fne(e,t,r){let n=Ip(t),i=n?.getElementsByTagName("entity")[0];!n||!i||B$(e,t,i,wne(n),r,Ene,{aliasPrefix:"groupby_column",addRef:gne,removeRef:yne})}function B$(e,t,r,n,i,o,a){let s=new Map;for(let m of n){let p=m.getAttribute("alias");p&&s.set(p,m)}let l=new Set,u=[],c=(m,p)=>{var h;let g=Ane(r,m),b=p.relatedEntity;(g??void 0)!==(b??void 0)&&((h=m.parentNode)===null||h===void 0||h.removeChild(m),k$(e,r,m,b))};for(let m of i){let p=m.alias?s.get(m.alias):void 0;p&&!l.has(p)?(o(p,m),c(p,m),l.add(p)):u.push(m)}let d=n.filter(m=>!l.has(m)),f=0;for(let m of u)if(f<d.length){let p=d[f];o(p,m),c(p,m),l.add(p),f+=1}else{let p=e.createElement("attribute"),h=m.alias||mne(t,a.aliasPrefix);p.setAttribute("alias",h),o(p,m),k$(e,r,p,m.relatedEntity),a.addRef(e,t,h)}for(let m of n)if(!l.has(m)){let p=m.getAttribute("alias");p&&a.removeRef(t,p),Nne(m)}}function pne(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 o=n[i].getAttribute("alias");o&&t.add(o)}}return t}function mne(e,t){let r=pne(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function q$(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function hne(e,t,r){let n=q$(e,t),i=n.getElementsByTagName("category")[0];i||(i=e.createElement("category"),n.appendChild(i));let o=e.createElement("measurecollection"),a=e.createElement("measure");a.setAttribute("alias",r),o.appendChild(a),i.appendChild(o)}function gne(e,t,r){let n=q$(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function yne(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 bne(e,t){var r;let n=e.getElementsByTagName("measure"),i=[];for(let o=0;o<n.length;o+=1)n[o].getAttribute("alias")===t&&i.push(n[o]);for(let o of i){let a=o.parentNode;a?.removeChild(o),a&&a.tagName==="measurecollection"&&!Tne(a)&&((r=a.parentNode)===null||r===void 0||r.removeChild(a))}}function vne(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 wne(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 Cne(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function Ene(e,t){e.setAttribute("name",t.attribute),e.setAttribute("groupby","true"),t.dateGrouping?e.setAttribute("dategrouping",t.dateGrouping):e.hasAttribute("dategrouping")&&e.removeAttribute("dategrouping")}function Ane(e,t){let r=t.parentNode;for(;r&&r!==e;){let n=r;if(n.nodeType===1&&n.tagName==="link-entity")return n.getAttribute("name")||void 0;r=n.parentNode}}function k$(e,t,r,n){n?Sne(e,t,n).appendChild(r):t.appendChild(r)}function Sne(e,t,r){let n=t.getElementsByTagName("link-entity");for(let o=0;o<n.length;o+=1)if(n[o].getAttribute("name")===r)return n[o];let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function Nne(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!_ne(t))){let r=t.parentNode;r&&r.removeChild(t)}}function _ne(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 Tne(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function V$(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(!Dne(r[i])){r[i].setAttribute("ChartType",t);return}}}function Dne(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 G$(e,t){var r;let n=e.ownerDocument;if(t.palette!==void 0&&e.setAttribute("Palette",t.palette),t.showLegend!==void 0){let i=e.getElementsByTagName("Legend").length>0;if(t.showLegend&&!i){let o=e.getElementsByTagName("Legends")[0];o||(o=n.createElement("Legends"),e.appendChild(o));let a=n.createElement("Legend");a.setAttribute("Name","Default"),o.appendChild(a)}else if(!t.showLegend)for(let o of["Legends","Legend"]){let a=[],s=e.getElementsByTagName(o);for(let l=0;l<s.length;l+=1)a.push(s[l]);for(let l of a)(r=l.parentNode)===null||r===void 0||r.removeChild(l)}}if(t.title!==void 0){let i=e.getElementsByTagName("Title")[0];i&&(i.textContent=t.title)}}function Ine(e,t){let r=(0,ai.parseXmlRoot)(sne(),"<Chart/>"),n=e.chartType||Dp(r);V$(r,n),e.presentation&&G$(r,e.presentation);let i=Cv((0,ai.parseXmlRoot)(t,"<datadefinition/>"));return i.length>0&&U$(r.ownerDocument,r,i,i.slice(0,1),n),(0,ai.serializeNode)(r)}function wv(e,t){return JSON.stringify(e)===JSON.stringify(t)}function al(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function One(){return{adapter:new Tp,api:nne.chartApi,publish:(e,t,r)=>(0,I$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,I$.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}sl.chartRegistration=One});var K$=v(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.dashboardApi=Na.dashboardEntity=void 0;var Pne=Lt(),Oo=ye(),ll=le(),Rne=Cg(),z$=ru();function j$(e){return e&&e.toLowerCase()!=="none"?e:void 0}Na.dashboardEntity=j$;var H$="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",kne={select:H$,required:["name","type","objecttypecode","istabletenabled"]},Lne="formid,name,type,objecttypecode",$ne=0,xne=10;Na.dashboardApi={async get(e,t){let r=(0,ll.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,ll.odataQuery)([["$select",H$]]),i=(0,Oo.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,z$.assertSystemFormRecordKind)(i.body,r,"dashboard","fetch"),{raw:i.body,etag:(0,Oo.readEtag)(i)}},async list(e,t){let r=[`(type eq ${$ne} or type eq ${xne})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,ll.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,ll.odataQuery)([["$select",Lne],["$filter",r.join(" and ")]])}`;return(await(0,Pne.collectPages)(e,n,"listArtifacts('dashboard')")).map(o=>{var a,s;let l=j$(o.objecttypecode);return{type:"dashboard",id:(a=o.formid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",...l?{entityLogicalName:l}:{},isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Oo.echoWrite)("formid"),o=`/systemforms${i.query}`,a={name:n.name,description:n.description,formxml:n.formxml,istabletenabled:n.istabletenabled,type:n.type};n.objecttypecode&&(a.objecttypecode=n.objecttypecode);let s=(0,Oo.ensureSuccess)(await e.post(o,(0,Oo.withClientMintedId)(a,"formid",r),i.options),e.apiUrl(o));return{id:(0,Oo.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Oo.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,Rne.patchSystemForm)(e,(0,ll.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,kne)},readContentThenToken(e,t){return Na.dashboardApi.get(e,t)},async delete(e,t){let r=(0,ll.normalizeGuid)(t,"id");return await(0,z$.assertSystemFormKind)(e,r,"dashboard"),(0,Oo.deleteRecord)(e,"systemforms",r)}}});var sx=v(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.dashboardRegistration=si.TILE_CLASS_ID=si.DashboardAdapter=void 0;var lc=so(),hn=uo(),Ev=Qr(),sc=rn(),ex=K$(),Av=lo(),_a=pt(),tx=le(),rx=Jo(),Fne=$y(),J$="0",Sv="10",Mne=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"]]),Une="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",Pp=class{constructor(t=rx.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,o,a;(0,Av.installDomShim)();let s=(r=t.formxml)!==null&&r!==void 0?r:"",l=(0,hn.parseXmlRoot)(s,"<form/>");return{id:(n=t.formid)!==null&&n!==void 0?n:"",name:(i=t.name)!==null&&i!==void 0?i:"",description:(o=t.description)!==null&&o!==void 0?o:"",dashboardType:Bne(t.type),entityLogicalName:(a=(0,ex.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:qne(l),components:Y$(l,this.lcid),bag:(0,hn.projectElementBag)(l)}}fromArtifact(t){var r;return(0,Av.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?Sv:J$,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:Q$(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}completeAsStored(t,r){return(0,Fne.completeRecordAsStored)(t,r,this.lcid)}toApiPayload(t){return{name:t.name,description:t.description,formxml:Q$(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?Sv:J$,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,o,a,s,l,u;(0,Av.installDomShim)();let c=(0,hn.parseXmlRoot)(eie(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,_a.newId)(),name:(n=t.name)!==null&&n!==void 0?n:"New Dashboard",description:(i=t.description)!==null&&i!==void 0?i:"",dashboardType:(o=t.dashboardType)!==null&&o!==void 0?o:"Standard",entityLogicalName:(a=t.entityLogicalName)!==null&&a!==void 0?a: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:Y$(c,this.lcid),bag:(0,hn.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,_a.newId)())}return t}validate(t){let r=[],n=(0,sc.childObjects)(t,"components","","component",r),i=new Set;return n.forEach(({node:o,index:a})=>{let s=`/components/${a}`;for(let l of["position","parameters"]){let u=o[l];u!==void 0&&!(0,sc.isJsonObject)(u)&&r.push((0,sc.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,sc.isJsonObject)(o.position)){let l=uc(o.position);i.has(l)?r.push((0,sc.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};si.DashboardAdapter=Pp;function Bne(e){return String(e??"")===Sv?"Interactive":"Standard"}function qne(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),r=parseInt(t??"",10);return Number.isNaN(r)?0:r}function ae(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName.toLowerCase()===t&&r.push(o)}return r}function Y$(e,t){let r=[];return ae(e,"tabs").flatMap(i=>ae(i,"tab")).forEach((i,o)=>{ae(i,"columns").flatMap(s=>ae(s,"column")).forEach((s,l)=>{ae(s,"sections").flatMap(c=>ae(c,"section")).forEach((c,d)=>{Vne(c,{tabIndex:o,columnIndex:l,sectionIndex:d},r,t)})})}),r}function Vne(e,t,r,n){ae(e,"rows").flatMap(o=>ae(o,"row")).forEach((o,a)=>{ae(o,"cell").forEach((s,l)=>{let u=Gne(s,{...t,rowIndex:a,cellIndex:l},n);u&&r.push(u)})})}function Gne(e,t,r){var n,i;let o=ox((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(o.toLowerCase().startsWith("spacer"))return null;let a=ae(e,"control")[0];if(!a)return null;let s=(i=a.getAttribute("classid"))!==null&&i!==void 0?i:"",l=jne(a),u=Hne(s,l,a),c=Wne(a);return{id:a.getAttribute("id")||o,type:u,name:ix(e,r),classId:s,position:t,colspan:Rp(e,"colspan",1),rowspan:Rp(e,"rowspan",1),parameters:l,bag:(0,hn.projectElementBag)(e),...c?{icProperties:c}:{}}}function nx(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 Wne(e){let t=nx(e);return t?(0,hn.serializeNode)(t):void 0}function zne(e,t,r){let n=nx(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,o=(0,lc.rebuildRaw)((0,lc.rawFromNode)((0,hn.nodeLikeFromDom)(i)),(0,hn.domEngine)(e),null);n&&(0,hn.serializeNode)(n)===(0,hn.serializeNode)(o)||(n?t.replaceChild(o,n):t.appendChild(o))}function ix(e,t){var r,n;let i=ae(e,"labels")[0];if(!i)return"";let o=ae(i,"label"),a=(r=o.find(s=>s.getAttribute("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return(n=a?.getAttribute("description"))!==null&&n!==void 0?n:""}function jne(e){var t;let r={},n=ae(e,"parameters")[0];if(!n)return r;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];a.nodeType===1&&(r[a.tagName]=((t=a.textContent)!==null&&t!==void 0?t:"").trim())}return r}function Hne(e,t,r){var n;let i=Mne.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"?((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===Une?"assistant":t.ChartGridMode!==void 0||r.getAttribute("indicationOfSubgrid")==="true"?t.ChartGridMode==="Chart"?"chart":"list":"unknown":i:"unknown"}function Rp(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 ox(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function Kne(e,t){let r={n:"form",a:(0,lc.mergeAttrs)(e.bag.a,[]),c:(0,lc.spliceChildren)(e.bag.c,[])};return(0,lc.rebuildRaw)(r,(0,hn.domEngine)(t),null)}function Q$(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=Kne(e,r);return Qne(r,n,e.components,t),Jne(r,n,e.components,t),(0,hn.serializeNode)(n)}function Jne(e,t,r,n){let i=ax(t);for(let o of r)i.has(uc(o.position))||Yne(e,t,o,n)}function Yne(e,t,r,n){var i,o,a,s;let l=(o=(i=r.position)===null||i===void 0?void 0:i.sectionIndex)!==null&&o!==void 0?o:0,u=tie(t,e,l);for(let x of ae(u,"row"))ae(x,"cell").some(K=>ae(K,"control").length>0)||u.removeChild(x);let c=r.classId||si.TILE_CLASS_ID[r.type]||si.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,f=r.bag&&X$(r.bag,"id")?String(X$(r.bag,"id")):Op((0,_a.newId)()),m=r.id?Op(r.id):Op((0,_a.newId)()),p=u.parentNode,h=Math.max(1,parseInt(p&&p.getAttribute&&p.getAttribute("columns")||"1",10)||1),g=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),h),b=ae(u,"row"),w=b[b.length-1],C=w?ae(w,"cell").reduce((x,K)=>x+Rp(K,"colspan",1),0):0;(!w||C+g>h)&&(w=e.createElement("row"),u.appendChild(w));let S=e.createElement("cell");S.setAttribute("id",f),S.setAttribute("colspan",String(g)),S.setAttribute("rowspan",String(d)),S.setAttribute("showlabel","true");let O=e.createElement("labels"),k=e.createElement("label");k.setAttribute("description",(a=r.name)!==null&&a!==void 0?a:""),k.setAttribute("languagecode",String(n)),O.appendChild(k),S.appendChild(O);let I=e.createElement("control");I.setAttribute("id",m),I.setAttribute("classid",Op(c));let D=e.createElement("parameters"),P=(s=r.parameters)!==null&&s!==void 0?s:{};for(let x of Object.keys(P)){let K=(0,tx.createSafeXmlElement)(e,x,"dashboard tile parameter");K.textContent=P[x],D.appendChild(K)}I.appendChild(D),S.appendChild(I),w.appendChild(S)}function X$(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Qne(e,t,r,n){var i;let o=ax(t),a=new Set(r.map(s=>uc(s.position)));for(let s of r){let l=o.get(uc(s.position));if(!l)continue;let u=ae(l,"control")[0];u&&(Xne(e,l,s.name,n),Zne(e,u,s.parameters),Z$(l,"colspan",s.colspan),Z$(l,"rowspan",s.rowspan),s.icProperties!==void 0&&zne(e,u,s.icProperties))}for(let[s,l]of o)a.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function ax(e){let t=new Map;return ae(e,"tabs").flatMap(n=>ae(n,"tab")).forEach((n,i)=>{ae(n,"columns").flatMap(a=>ae(a,"column")).forEach((a,s)=>{ae(a,"sections").flatMap(u=>ae(u,"section")).forEach((u,c)=>{ae(u,"rows").flatMap(f=>ae(f,"row")).forEach((f,m)=>{ae(f,"cell").forEach((p,h)=>{var g;ox((g=p.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||ae(p,"control")[0]&&t.set(uc({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:m,cellIndex:h}),p)})})})})}),t}function uc(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function Xne(e,t,r,n){if(r===ix(t,n))return;let i=ae(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let o=ae(i,"label").find(a=>a.getAttribute("languagecode")===String(n));o||(o=e.createElement("label"),o.setAttribute("languagecode",String(n)),i.appendChild(o)),o.setAttribute("description",r)}function Zne(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let o=ae(t,"parameters")[0];o||(o=e.createElement("parameters"),t.appendChild(o));let a=new Map,s=o.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];u.nodeType===1&&a.set(u.tagName,u)}for(let l of i){let u=r[l],c=a.get(l);if(c)((n=c.textContent)!==null&&n!==void 0?n:"")!==u&&(c.textContent=u);else{let d=(0,tx.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,o.appendChild(d)}}}function Z$(e,t,r){Rp(e,t,1)!==r&&e.setAttribute(t,String(r))}function eie(e=2){let t=`{${(0,_a.newId)()}}`,r=`{${(0,_a.newId)()}}`,n=`{${(0,_a.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>`}si.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 Op(e){return`{${e.replace(/[{}]/g,"")}}`}function tie(e,t,r){var n;let i=ae(e,"tabs").flatMap(u=>ae(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let o=ae(i,"columns").flatMap(u=>ae(u,"column"))[0];if(!o)throw new Error("addDashboardTile: dashboard formxml has no <column>");let a=ae(o,"sections").flatMap(u=>ae(u,"section")),s=(n=a[r])!==null&&n!==void 0?n:a[0];if(!s)throw new Error("addDashboardTile: dashboard formxml has no <section>");let l=ae(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function rie(e=rx.DEFAULT_LCID){return{adapter:new Pp(e),api:ex.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,Ev.publishBoundEntity)(t,n):(0,Ev.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,Ev.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}si.dashboardRegistration=rie});var _v=v(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.readEveryInOrder=Fr.readInOrder=Fr.plainRead=Fr.resolveReadConcurrency=Fr.MAX_READ_CONCURRENCY=void 0;var lx=Q();Fr.MAX_READ_CONCURRENCY=8;function nie(e){if(e===void 0)return 1;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>Fr.MAX_READ_CONCURRENCY)throw new lx.InvalidArgumentError(`readConcurrency must be a whole number from 1 to ${Fr.MAX_READ_CONCURRENCY} (got ${typeof e=="string"?`'${e}'`:String(e)})`);return e}Fr.resolveReadConcurrency=nie;var iie=e=>({ok:!0,value:e}),Nv=e=>({ok:!1,error:e});function oie(e){let t=(async()=>e())().then(iie,Nv);return{outcome:t,finish:async r=>{await r()},discard:async()=>{await t}}}Fr.plainRead=oie;async function ux(e,t,r,n,i){if(!Number.isInteger(t)||t<1)throw new lx.InvalidArgumentError(`a read window holds a whole number of reads, at least 1 (got ${String(t)})`);let o=new Map,a=0,s=Promise.resolve(),l=!1,u=0,c,d=async f=>{if(l)return{refusal:new Error("The read was not started: an earlier read had already failed.")};try{let m=await r(e[f],f),p=m.outcome.catch(Nv);return i==="stop"&&p.then(h=>{l=l||!h.ok}),{read:m,outcome:p}}catch(m){return l=l||i==="stop",{refusal:m}}};try{for(let f=0;f<e.length;f+=1){for(;a<e.length&&a<f+t;){let g=a;a+=1;let b=s.then(()=>d(g));o.set(g,b),s=b}let m=await o.get(f),p="read"in m?await m.outcome:Nv(m.refusal);if(!p.ok&&i==="stop"){c={error:p.error};break}u=f+1,o.delete(f);let h=()=>n(p,e[f],f);"read"in m?await m.read.finish(h):await h()}}finally{l=!0;for(let f=u;f<a;f+=1){let m=await o.get(f);"read"in m&&await m.read.discard().catch(()=>{})}}if(c)throw c.error}function aie(e,t,r,n){return ux(e,t,r,(i,o,a)=>n(i.value,o,a),"stop")}Fr.readInOrder=aie;function sie(e,t,r,n){return ux(e,t,r,n,"continue")}Fr.readEveryInOrder=sie});var _x=v(Lp=>{"use strict";Object.defineProperty(Lp,"__esModule",{value:!0});Lp.genPageApi=void 0;var kp=Lt(),Cx=Kl(),Be=ye(),ve=le(),xn=xd(),Je=Q(),Ex=pt(),cx=_v();function lie(e){if(ArrayBuffer.isView(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(Object.prototype.toString.call(e)==="[object ArrayBuffer]")return new Uint8Array(e);let t=globalThis;if(t.Buffer&&t.Buffer.isBuffer(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}}var li="uxagentprojects",Da="uxagentprojectfiles",fc="agentconversationmessages",pc="uxagentprojectid",Bt="uxagentprojectfileid",Ia="agentconversationmessageid",cc=`${pc},name`,uie=`${Bt},filename,filetype`,Ax=2e8,Sx=200000001,Oa={"MSCRM.IncludeUnpublished":"true"},Tv={};function Ta(e,t){return{"MSCRM.VersioningChangeset":e,...Oa,...t}}async function Ov(e,t,r,n){var i;let o=`/${t}(${r})`+(0,ve.odataQuery)([["$select",n]]),a=(0,Be.ensureSuccess)(await e.get(o,{headers:{...Oa}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,Be.readEtag)(a)}}async function mc(e,t,r=Oa){let n=`/${Da}(${t})/filecontent/$value`,i=await e.get(n,{headers:{...r}});if(i.status===404)return{status:"unavailable",reason:"missing"};(0,Be.ensureSuccess)(i,e.apiUrl(n));let o=i.body,a=lie(o);if(a)return{status:"available",data:(0,xn.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,xn.utf8ToBase64)(o)};throw new Je.SdkError("GENPAGE_CONTENT_UNREADABLE",`Read the content of file '${t}' but the injected HttpClient returned a body this SDK cannot encode (${typeof o}). Return the response as a string, Uint8Array, Buffer, or ArrayBuffer; a byte-returning transport is required to round-trip non-UTF8 assets.`)}function Nx(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function cie(e,t,r,n,i,o){if(!e.supportsBinaryPatch)throw new Je.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 a=`/${Da}(${t})/filecontent`,s=(0,xn.base64ToBytes)(n);(0,ve.assertNoControlChars)(r,"generative-page file name"),(0,Be.ensureSuccess)(await e.patchRaw(a,s,{headers:Ta(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":Nx(r),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function dc(e,t,r=Oa){let n=`/${Da}`+(0,ve.odataQuery)([["$select",uie],["$filter",`_${pc}_value eq ${t}`]]);return(await(0,kp.collectPages)(e,n,"fetchArtifact('genPage')",void 0,{headers:{...r}})).map(o=>({row:o,etag:typeof o["@odata.etag"]=="string"?o["@odata.etag"]:null}))}async function Dv(e,t){let r=`/${fc}`+(0,ve.odataQuery)([["$select",`${Ia},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,kp.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{...Oa}})}async function dx(e,t){var r,n,i;let{row:o,etag:a}=await Ov(e,li,t,cc),s=new Map;for(let{row:l,etag:u}of await dc(e,t))s.set((0,ve.normalizeGuid)(String((r=l[Bt])!==null&&r!==void 0?r:""),Bt),{filename:String((n=l.filename)!==null&&n!==void 0?n:""),filetype:Number(l.filetype),etag:u});return{name:String((i=o.name)!==null&&i!==void 0?i:""),etag:a,rows:s}}function fx(e,t,r){var n,i,o,a,s;let l=[];r||l.push({kind:"createProject",name:t.name});let u=new Set;for(let c of(n=t.files)!==null&&n!==void 0?n:[]){let d=(0,ve.normalizeGuid)(c.id,"file id");u.add(d);let f=r?.rows.get(d);if(c.content.status==="retain"){if(!r)throw new Je.SdkError("GENPAGE_RETAIN_ON_CREATE",`Refusing to create generative page '${e}': file '${c.name}' asks to keep content the page does not have yet. This is an SDK defect \u2014 the page's rows were not written.`);if(!f)throw new Je.SdkError("GENPAGE_RETAINED_ROW_MISSING",`Refusing to write generative page '${e}': file '${c.name}' was to be kept unchanged but is not on the server. Re-fetch the page and retry.`);continue}f&&c.unchanged||(f?(f.filename!==c.name||f.filetype!==c.fileType)&&l.push({kind:"renameRow",file:c}):l.push({kind:"createRow",file:c}),c.content.status==="available"&&l.push({kind:"content",file:c,data:c.content.data,existing:f!==void 0}))}for(let c of(i=r?.rows.keys())!==null&&i!==void 0?i:[])u.has(c)||l.push({kind:"deleteRow",fileId:c});(!r||l.length>0||r.name!==t.name||((a=(o=t.messages)===null||o===void 0?void 0:o.length)!==null&&a!==void 0?a:0)>0)&&l.push({kind:"patchProject",name:t.name});for(let c of(s=t.messages)!==null&&s!==void 0?s:[])l.push({kind:"message",turn:c});return l}function Pv(e){let t=(0,xn.base64ToUtf8)(e);return(0,xn.utf8ToBase64)(t)===(0,xn.bytesToBase64)((0,xn.base64ToBytes)(e))?t:void 0}function die(e,t,r,n){var i,o,a,s,l,u,c,d;let f=t.sender==="user"?{changeSet:n,dataSources:(o=(i=r.messageContext)===null||i===void 0?void 0:i.dataSources)!==null&&o!==void 0?o:[],model:(s=(a=r.messageContext)===null||a===void 0?void 0:a.model)!==null&&s!==void 0?s:"",enabledTools:(u=(l=r.messageContext)===null||l===void 0?void 0:l.enabledTools)!==null&&u!==void 0?u:[],configurableTools:(d=(c=r.messageContext)===null||c===void 0?void 0:c.configurableTools)!==null&&d!==void 0?d:[]}:{changeSet:n};return{...t.id?{[Ia]:(0,ve.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${li}(${e})`,message:t.message,messagecontext:JSON.stringify(f),messagesender:t.sender==="user"?Ax:Sx}}async function fie(e,t,r){var n,i,o,a;let s=((n=r.messages)!==null&&n!==void 0?n:[]).map(f=>f.id).filter(f=>typeof f=="string"&&f!=="").map(f=>(0,ve.normalizeGuid)(f,"message id"));if(s.length===0)return r;let l=`/${fc}`+(0,ve.odataQuery)([["$select",`${Ia},message,messagesender,_regardingobjectid_value`],["$filter",s.map(f=>`${Ia} eq ${f}`).join(" or ")]]),u=await(0,kp.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{...Oa}});if(u.length===0)return r;let c=new Map(u.map(f=>{var m;return[String((m=f[Ia])!==null&&m!==void 0?m:"").toLowerCase(),f]})),d=[];for(let f of(i=r.messages)!==null&&i!==void 0?i:[]){let m=f.id?c.get((0,ve.normalizeGuid)(f.id,"message id")):void 0;if(!m){d.push(f);continue}if(!(String((o=m.message)!==null&&o!==void 0?o:"")===f.message&&Number(m.messagesender)===(f.sender==="user"?Ax:Sx)&&String((a=m._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new Je.SdkError("GENPAGE_TURN_CONFLICT",`Refusing to push generative page '${t}': its pending turn's identity is already recorded \u2014 as a DIFFERENT ${f.sender} message. An earlier push of this turn did commit (its response was lost), and the turn was changed since. Nothing was written, and the turn is still pending. To record it as a new turn, remove '/newTurn/id' (a new identity is minted on the next push); to keep only what was recorded, remove '/newTurn'.`)}return{...r,messages:d}}function Iv(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${li}`,body:(0,Be.withClientMintedId)({name:t.name},pc,e),headers:Ta(n)};case"createRow":return{method:"POST",path:`/${Da}`,body:(0,Be.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${pc}@odata.bind`]:`/${li}(${e})`},Bt,(0,ve.normalizeGuid)(t.file.id,"file id")),headers:Ta(n)};case"renameRow":return{method:"PATCH",path:`/${Da}(${(0,ve.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Ta(n,{"If-Match":"*"})};case"content":{let i=Pv(t.data);if(i===void 0)throw new Je.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,ve.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${Da}(${(0,ve.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Ta(n,{"x-ms-file-name":Nx(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${Da}(${t.fileId})`,headers:Ta(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${li}(${e})`,body:{name:t.name},headers:Ta(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${fc}`,body:die(e,t.turn,r,n)};default:{let i=t;throw new Je.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function px(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||Pv(r.data)!==void 0)}async function mx(e,t,r,n,i){await(0,Cx.postChangeSet)(e,r.map(o=>Iv(t,o,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function hx(e,t,r,n,i){var o;let a=[];for(let s of r){if(s.kind==="message"){a.push(s);continue}if(s.kind==="content"){await cie(e,(0,ve.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=Iv(t,s,n,i),u={headers:(o=l.headers)!==null&&o!==void 0?o:{}},c=l.method==="POST"?await e.post(l.path,l.body,u):l.method==="PATCH"?await e.patch(l.path,l.body,u):await e.delete(l.path,u);(0,Be.ensureSuccess)(c,e.apiUrl(l.path))}if(a.length===0)return{warnings:[],turnRecorded:!0};try{let s=a.map(l=>Iv(t,l,n,i));if(e.supportsAtomicBatch)await(0,Cx.postChangeSet)(e,s,`the conversation turn of generative page '${t}'`);else for(let l of s)(0,Be.ensureSuccess)(await e.post(l.path,l.body),e.apiUrl(l.path));return{warnings:[],turnRecorded:!0}}catch(s){return{warnings:[`Generative page '${t}' was saved, but its conversation turn could not be recorded (${s instanceof Error?s.message:String(s)}). The turn is kept: the next push of the page records it.`],turnRecorded:!1}}}async function gx(e,t,r,n,i,o,a){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...a,u]});try{let u=await dx(e,t),c=new Map;for(let C of r)(C.kind==="createRow"||C.kind==="renameRow"||C.kind==="content")&&c.set((0,ve.normalizeGuid)(C.file.id,"file id"),C.file);let d=[];u.name!==n.name&&d.push(`the page is named '${u.name}', not '${n.name}'`);for(let[C,S]of c){let O=u.rows.get(C);O&&(O.filename!==S.name||O.filetype!==S.fileType)&&d.push(`file '${S.name}' is stored as '${O.filename}' (type ${O.filetype})`)}for(let C of r){if(C.kind!=="content")continue;let S=await mc(e,(0,ve.normalizeGuid)(C.file.id,"file id")),O=(0,xn.bytesToBase64)((0,xn.base64ToBytes)(C.data));(S.status!=="available"||S.data!==O)&&d.push(S.status==="available"?`file '${C.file.name}' holds ${(0,xn.base64ToBytes)(S.data).byteLength} byte(s) that differ from the ${(0,xn.base64ToBytes)(O).byteLength} written`:`file '${C.file.name}' holds no content`)}let f=new Set(r.filter(C=>C.kind==="content").map(C=>(0,ve.normalizeGuid)(C.file.id,"file id")));for(let[C,S]of c)!f.has(C)&&(await mc(e,C)).status==="available"&&d.push(`file '${S.name}' holds content this push did not write`);if(d.length>0)return l(`Generative page '${t}' was written, but reading it back does not match what was sent: ${d.join("; ")}. The local baseline is now unusable: re-fetch the page to see what the server holds \u2014 the next push will refuse rather than overwrite blind.`);let m=await dx(e,t),p=[...m.rows.keys()],h=m.etag!==u.etag||m.rows.size!==u.rows.size||p.some(C=>{var S,O;return((S=u.rows.get(C))===null||S===void 0?void 0:S.etag)!==((O=m.rows.get(C))===null||O===void 0?void 0:O.etag)}),g=p.length!==i.size||p.some(C=>!i.has(C)),b={},w=[];for(let[C,S]of m.rows){let O=c.has(C)||!o?S.etag:(s=o.get(C))!==null&&s!==void 0?s:null;b[C]=O,O!==S.etag&&w.push(S.filename)}return h||g||!m.etag||Object.values(b).some(C=>!C)?l(`Generative page '${t}' was written, but its files changed on the server while the write was in progress, so the new concurrency tokens cannot be trusted. The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`):pie({id:t,etag:m.etag,memberEtags:b},[...a,...w.map(C=>`Generative page '${t}' was written, but its file '${C}' changed on the server while this push ran \u2014 another writer edited it. This push did not touch that file, so the next one refuses until you re-fetch the page and see their change.`)])}catch(u){return l(`The generative page was written, but reading it back failed (${u instanceof Error?u.message:String(u)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`)}}async function yx(e,t,r,n=e.readConcurrency){var i;let o=(0,ve.normalizeGuid)(t,"id"),{row:a,etag:s}=await Ov(e,li,o,cc),l=await dc(e,o),u={},c=[];if(n>1)await(0,cx.readInOrder)(l,n,({row:f})=>{var m;let p=(0,ve.normalizeGuid)(String((m=f[Bt])!==null&&m!==void 0?m:""),Bt);return(0,cx.plainRead)(async()=>({fileId:p,content:await mc(e,p)}))},({fileId:f,content:m},{row:p,etag:h})=>{u[f]=h,c.push({...p,content:m})});else for(let{row:f,etag:m}of l){let p=(0,ve.normalizeGuid)(String((i=f[Bt])!==null&&i!==void 0?i:""),Bt);u[p]=m;let h=await mc(e,p);c.push({...f,content:h})}return{raw:r?{project:a,files:c,conversation:await Dv(e,o)}:{project:a,files:c},etag:s,memberEtags:u}}Lp.genPageApi={get(e,t,r){return yx(e,t,!0,r?.fileConcurrency)},getForRebaseline(e,t){return yx(e,t,!1)},async getPublished(e,t){var r,n;let i=(0,ve.normalizeGuid)(t,"id"),o=`/${li}(${i})`+(0,ve.odataQuery)([["$select",cc]]),a=await e.get(o);if(a.status===404)return null;(0,Be.ensureSuccess)(a,e.apiUrl(o));let s=(r=a.body)!==null&&r!==void 0?r:{},l={},u=[],c=await dc(e,i,Tv);for(let{row:g,etag:b}of c){let w=(0,ve.normalizeGuid)(String((n=g[Bt])!==null&&n!==void 0?n:""),Bt);l[w]=b,u.push({...g,content:await mc(e,w,Tv)})}let d=g=>g.map(({row:b,etag:w})=>`${String(b[Bt])}@${String(w)}`).sort().join("|"),f=()=>new Je.SdkError("GENPAGE_PUBLISHED_READ_MOVED",`The published projection of generative page '${i}' changed while it was being read, so what was read is not one published state. PublishXml is asynchronous \u2014 re-read shortly.`),m=await e.get(o);if(m.status===404)throw f();(0,Be.ensureSuccess)(m,e.apiUrl(o));let p=await dc(e,i,Tv);if([(0,Be.readEtag)(a),(0,Be.readEtag)(m),...[...c,...p].map(g=>g.etag)].some(g=>!g))throw new Je.SdkError("GENPAGE_PUBLISHED_READ_UNVERSIONED",`The published projection of generative page '${i}' answered without a version token for the page or one of its rows, so what was read cannot be proven to be one published state.`);if((0,Be.readEtag)(m)!==(0,Be.readEtag)(a)||d(p)!==d(c))throw f();return{raw:{project:s,files:u,conversation:[]},etag:(0,Be.readEtag)(a),memberEtags:l}},async list(e,t){let r=`/${li}`+(0,ve.odataQuery)([["$select",cc]]);return(await(0,kp.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{...Oa}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[pc])!==null&&o!==void 0?o:""),name:String((a=i.name)!==null&&a!==void 0?a:""),isDirty:!1}})},async create(e,t,r){var n;let i=t,o=r?(0,ve.normalizeGuid)(r,"id"):(0,Ex.newId)(),a=fx(o,i,void 0);wx(e,a),vx(e,o,i);let s=bx(),l=[],u=!0;px(e,a)?await mx(e,o,a,i,s):{warnings:l,turnRecorded:u}=await hx(e,o,a,i,s);let c=new Set(((n=i.files)!==null&&n!==void 0?n:[]).map(f=>(0,ve.normalizeGuid)(f.id,"file id"))),d=await gx(e,o,a,i,c,void 0,l);return u?d:{...d,intentPending:!0}},async update(e,t,r,n,i){var o,a;let s=r,l=(0,ve.normalizeGuid)(t,"id");if(!Array.isArray(s.files))throw new Je.SdkError("GENPAGE_FILES_REQUIRED",`Refusing to update generative page '${l}': its payload has no files list. A page's files are its complete set of rows \u2014 a row the list omits is deleted \u2014 so an omitted list would delete every row of the page. Nothing was written.`);let u=await fie(e,l,s);vx(e,l,u);let c=await dc(e,l),{row:d,etag:f}=await Ov(e,li,l,cc);if(n&&f&&n!==f)throw new Je.SdkError(Be.VERSION_CONFLICT_CODE,`Generative page '${l}' changed on the server after it was fetched (baseline ${n}, server ${f}) \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||!f)throw new Je.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify generative page '${l}' before writing: ${n?"the server did not return the page's current token":"no baseline token was recorded"}. This entity accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let m=new Map(c.map(({row:I})=>{var D,P;return[(0,ve.normalizeGuid)(String((D=I[Bt])!==null&&D!==void 0?D:""),Bt),{filename:String((P=I.filename)!==null&&P!==void 0?P:""),filetype:Number(I.filetype)}]})),p=new Set(m.keys()),h=new Set(((o=u.files)!==null&&o!==void 0?o:[]).map(I=>(0,ve.normalizeGuid)(I.id,"file id")));if(!i)throw new Je.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${l}' before writing: no child baseline was recorded. These rows accept no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let g=new Set(Object.keys(i).map(I=>I.toLowerCase()));for(let I of h)if(!p.has(I)&&g.has(I))throw new Je.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${I}' existed when this page was fetched but is gone from the server now \u2014 another writer deleted it. Refusing to recreate it, because a blind re-create would undo that delete. Re-fetch the page and re-apply the edit.`);for(let I of p)if(!g.has(I))throw new Je.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${I}' is on the server but absent from this page's baseline \u2014 another writer added it after the page was fetched, so its contents cannot be verified. Refusing to write over or delete it. Re-fetch the page so the addition is part of your baseline.`);let b=new Map(c.map(({row:I,etag:D})=>{var P;return[(0,ve.normalizeGuid)(String((P=I[Bt])!==null&&P!==void 0?P:""),Bt),D]}));for(let[I,D]of Object.entries(i)){let P=I.toLowerCase();if(!p.has(P))continue;let x=b.get(P);if(!D||!x)throw new Je.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${P}' before writing: ${D?"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(D!==x)throw new Je.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${P}' changed on the server after this page was fetched (baseline ${D}, server ${x}) \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 w=fx(l,u,{rows:m,name:String((a=d.name)!==null&&a!==void 0?a:"")});if(wx(e,w),w.length===0)return{id:l,etag:f,memberEtags:Object.fromEntries(c.map(({row:I,etag:D})=>{var P;return[(0,ve.normalizeGuid)(String((P=I[Bt])!==null&&P!==void 0?P:""),Bt),D]}))};let C=bx(),S=[],O=!0;px(e,w)?await mx(e,l,w,u,C):{warnings:S,turnRecorded:O}=await hx(e,l,w,u,C);let k=await gx(e,l,w,u,h,b,S);return O?k:{...k,intentPending:!0}},async delete(e,t){var r;let n=(0,ve.normalizeGuid)(t,"id"),i=await Dv(e,n);await(0,Be.deleteRecord)(e,li,n);let o=new Set(i.map(l=>{var u;return String((u=l[Ia])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),a=!1;try{for(let l of await Dv(e,n)){let u=String((r=l[Ia])!==null&&r!==void 0?r:"");u!==""&&o.add(u)}}catch{a=!0}let s=[];for(let l of o)try{await(0,Be.deleteRecord)(e,fc,l)}catch(u){u instanceof Je.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||a)throw new Je.SdkError("GENPAGE_HISTORY_NOT_DELETED",`Generative page '${n}' was deleted, but its conversation history was not fully removed`+(s.length>0?` \u2014 ${s.length} of ${o.size} message(s) could not be (${s.join(", ")})`:"")+(a?" \u2014 and re-reading it after the delete failed, so a late turn may remain":"")+`. They no longer belong to any page; delete them as ${fc} rows regarding '${n}'.`)}};function bx(){return`uxagentproject_${(0,Ex.newId)()}`}function pie(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function vx(e,t,r){var n,i;if(((i=(n=r.messages)===null||n===void 0?void 0:n.length)!==null&&i!==void 0?i:0)>1&&!e.supportsAtomicBatch)throw new Je.SdkError("GENPAGE_TURN_NOT_ATOMIC",`Refusing to write generative page '${t}': its new turn has a prompt AND a reply, which must be recorded together, and the injected HttpClient does not implement postRaw() \u2014 one request at a time, a failure between the two would leave half a turn. Implement postRaw(), or record the prompt alone (omit newTurn.agentMessage). Nothing was written.`)}function wx(e,t){let r=t.filter(i=>i.kind==="content");if(r.length>0&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new Je.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient implements neither patchRaw() nor postRaw(). A Dataverse File column is not writable through a JSON body, so proceeding would create the page and its rows and then fail, leaving a page whose source never uploaded.");if(r.some(i=>Pv(i.data)===void 0)&&!e.supportsBinaryPatch)throw new Je.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: a file's content is not UTF-8 text, which only the binary channel can carry, and the injected HttpClient does not implement patchRaw().")}});var Gx=v(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});cl.genPageRegistration=cl.GenPageAdapter=void 0;var mie=_x(),hie=Qr(),Ie=rn(),Up=pt(),Bp=xd(),gie=le(),Pa=Q(),Fx=$g(),Rv=rh(),Po=2e8,Mx=200000001,Wi={source:{name:"src/pages/page.tsx",fileType:Po},output:{name:"src/pages/page.compiled",fileType:Mx},config:{name:"config.json",fileType:Po},prompt:{name:"firstPrompt.json",fileType:Po}},Ux=Object.keys(Wi),yie=["dataSources","model","connectorBindings","actionBindings"],bie=["userMessage","agentMessage"],Tx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,vie={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},wie="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function Bx(e,t,r){let n=(0,gie.normalizeGuid)(e,r).replace(/-/g,""),i=[];for(let a=0;a<32;a+=1)i.push(parseInt(n[a],16)^parseInt(t[a],16));i[12]=4,i[16]=i[16]&3|8;let o=i.map(a=>a.toString(16)).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function $p(e,t){return Bx(e,vie[t],"id")}function Cie(e,t){let r=Bx(e,wie,"newTurn.id"),n=parseInt(r.slice(24),16)%2**47+(t==="agent"?1:0);return`${r.slice(0,24)}${n.toString(16).padStart(12,"0")}`}function Dx(e){return typeof e=="string"&&e.trim()!==""?e:(0,Up.newId)()}function Gi(e){return(0,Ie.isJsonObject)(e)?e:{}}function ul(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function xp(e){return JSON.parse(JSON.stringify(e))}function Eie(e){let t=Gi(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function gc(e){if(!e||e.status!=="available")return;let t=(0,Bp.base64ToUtf8)(e.data);return(0,Bp.utf8ToBase64)(t)===e.data?t:void 0}function qx(e,t,r){var n,i,o,a;return e.source!==void 0&&t!==void 0&&t?.source===e.source&&ul((n=t?.dataSources)!==null&&n!==void 0?n:[],(i=e.dataSources)!==null&&i!==void 0?i:[])&&((a=(o=e.bag)===null||o===void 0?void 0:o.rows)!==null&&a!==void 0?a:{}).output!==void 0&&(0,Fx.isLoadableGenPageOutput)(r)}function Aie(e,t){var r;try{return qx(e,t,gc((r=e.bag)===null||r===void 0?void 0:r.output))}catch{return!1}}function Fp(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,Ie.isJsonObject)(t)?t:void 0}catch{return}}function Ix(e,t){if(t===Po&&e.includes("page.tsx"))return"source";if(t===Mx&&e.includes(".compiled"))return"output";if(t===Po&&e===Wi.config.name)return"config";if(t===Po&&e===Wi.prompt.name)return"prompt"}function Ox(e){let t=e.toLowerCase();return Ux.some(r=>Wi[r].name.toLowerCase()===t)}function kv(e){return Object.fromEntries(e)}function Vx(e,t,r,n){let i=[],o=new Set,a=new Set(t),s=l=>{if(o.has(l))return;let u=a.has(l)?e[l]:r&&Object.prototype.hasOwnProperty.call(r,l)?r[l]:void 0;u!==void 0&&(o.add(l),i.push([l,u]))};return(n??[]).forEach(s),t.forEach(s),Object.keys(r??{}).forEach(s),kv(i)}function Px(e){var t,r,n;return Vx({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},yie,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function Rx(e){var t,r;return Vx({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},bie,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function kx(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="dataSources"){if(!Array.isArray(o)||!o.every(a=>typeof a=="string"))return!1;e.dataSources=o}else if(i==="model"){if(typeof o!="string")return!1;e.model=o}else i==="connectorBindings"?e.connectorBindings=o:i==="actionBindings"?e.actionBindings=o:n.push([i,o]);return t.configKeys=Object.keys(r),n.length>0&&(t.config=kv(n)),!0}function Lx(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="userMessage"||i==="agentMessage"){if(typeof o!="string")return!1;i==="userMessage"?e.firstPrompt=o:e.firstAgentMessage=o}else n.push([i,o]);return t.promptKeys=Object.keys(r),n.length>0&&(t.prompt=kv(n)),!0}function yc(e){var t,r;return e.source!==void 0||Object.keys((r=(t=e.bag)===null||t===void 0?void 0:t.rows)!==null&&r!==void 0?r:{}).length>0}var Sie=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function $x(e){return yc(e)?[]:Sie.filter(t=>e[t]!==void 0).map(t=>(0,Ie.issue)(`/${t}`,"genpage-raw-structured-field",`${t} cannot be applied: this page is in raw-file mode \u2014 it has no source and no managed rows, so a push writes its files[] exactly as they are, and ${t} nowhere. Set source to make the page managed (the SDK then writes config.json and firstPrompt.json from the typed fields; a file in files[] holding one of those names must be removed first), or change the file that stores the value in files[] directly.`))}function xx(){return(0,Ie.issue)("/source","genpage-source-required","the page's source cannot be removed: its source row still exists, and a page without one cannot run. Set a new source, or delete the page with deleteRemoteArtifact.")}function Mp(e){return{status:"available",data:(0,Bp.utf8ToBase64)(e)}}function hc(e,t){var r,n;return{id:String((r=e.uxagentprojectid)!==null&&r!==void 0?r:""),name:String((n=e.name)!==null&&n!==void 0?n:""),files:t}}var qp=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=Gi(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(g=>{var b,w,C;let S=Gi(g);return{id:String((b=S.uxagentprojectfileid)!==null&&b!==void 0?b:""),name:String((w=S.filename)!==null&&w!==void 0?w:""),fileType:Number((C=S.filetype)!==null&&C!==void 0?C:Po),content:Eie(S.content)}}),o=Array.isArray(r?.conversation)?r.conversation.map(g=>{var b,w;let C=Gi(g);return{sender:Number(C.messagesender)===200000001?"agent":"user",message:String((b=C.message)!==null&&b!==void 0?b:""),createdOn:String((w=C.createdon)!==null&&w!==void 0?w:"")}}):void 0,a=g=>o?{...g,conversation:o}:g,s=new Map,l=[],u=!0;for(let g of i){let b=Ix(g.name,g.fileType);b?((s.has(b)||g.name!==Wi[b].name)&&(u=!1),s.set(b,g)):(Ox(g.name)&&(u=!1),l.push(g))}if(!u||s.size===0)return a(hc(n,i));let c=hc(n,l),d={rows:{}};for(let[g,b]of s)d.rows[g]=b.id;let f=s.get("source");if(f){let g=gc(f.content);if(g===void 0)return a(hc(n,i));c.source=g}let m=s.get("output");m&&(d.output=m.content);let p=s.get("config");if(p){let g=Fp(gc(p.content));if(!g||!kx(c,d,g))return a(hc(n,i))}let h=s.get("prompt");if(h){let g=Fp(gc(h.content));if(!g||!Lx(c,d,g))return a(hc(n,i))}return c.bag=d,a(c)}async toApiPayload(t,r,n){var i,o,a,s,l,u,c,d,f,m,p,h,g;if(r&&!ul((i=t.conversation)!==null&&i!==void 0?i:[],(o=r.conversation)!==null&&o!==void 0?o:[]))throw new Pa.ValidationError("genPage",t.id,[(0,Ie.issue)("/conversation","genpage-conversation-read-only","conversation is the page's recorded history and cannot be edited. Record a new turn with newTurn; revert the edit to conversation before pushing.")]);let b=$x(t);if(b.length>0)throw new Pa.ValidationError("genPage",t.id,b);let w=[],C=r===void 0,S=C&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(yc(S)){let I=(s=(a=S.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},D=Xe=>{var Ne;return(Ne=I[Xe])!==null&&Ne!==void 0?Ne:$p(S.id,Xe)},P=(Xe,Ne,se)=>{w.push({id:D(Xe),name:Wi[Xe].name,fileType:Wi[Xe].fileType,content:Ne,unchanged:se})};if(S.source!==void 0){P("source",Mp(S.source),!C&&r?.source===S.source&&I.source!==void 0);let Xe=gc((l=S.bag)===null||l===void 0?void 0:l.output);qx(S,r,Xe)?P("output",{status:"retain"},!0):P("output",Mp(await this.compile(S,S.source,n)),!1)}else{if(I.source!==void 0)throw new Pa.ValidationError("genPage",S.id,[xx()]);if(I.output!==void 0){if(!C&&!ul((u=r?.dataSources)!==null&&u!==void 0?u:[],(c=S.dataSources)!==null&&c!==void 0?c:[]))throw new Pa.ValidationError("genPage",S.id,[(0,Ie.issue)("/dataSources","genpage-source-required","the page has no source row, so its output cannot be recompiled for new data sources; set a source to change them.")]);P("output",{status:"retain"},!0)}}let x=Px(S),K=!C&&r!==void 0&&ul(Px(r),x);(C||I.config!==void 0||!K)&&P("config",Mp(JSON.stringify(x)),K&&I.config!==void 0);let Oe=Rx(S),Vt=!C&&r!==void 0&&ul(Rx(r),Oe);(I.prompt!==void 0||Object.keys(Oe).length>0&&!Vt)&&P("prompt",Mp(JSON.stringify(Oe)),Vt&&I.prompt!==void 0)}for(let I of(d=S.files)!==null&&d!==void 0?d:[]){let D=(f=r?.files)===null||f===void 0?void 0:f.find(P=>P.id===I.id);w.push({id:I.id,name:I.name,fileType:I.fileType,content:I.content,unchanged:D!==void 0&&ul(D,I)})}let O=[];if(S.newTurn){let I=S.newTurn.id,D=P=>I?{id:Cie(I,P)}:{};O.push({...D("user"),sender:"user",message:S.newTurn.prompt}),S.newTurn.agentMessage&&O.push({...D("agent"),sender:"agent",message:S.newTurn.agentMessage})}let k=(p=(m=S.bag)===null||m===void 0?void 0:m.config)!==null&&p!==void 0?p:{};return{name:S.name,files:w,...O.length>0?{messages:O,messageContext:{dataSources:(h=S.dataSources)!==null&&h!==void 0?h:[],model:(g=S.model)!==null&&g!==void 0?g:"",enabledTools:Array.isArray(k.enabledTools)?k.enabledTools:[],configurableTools:Array.isArray(k.configurableTools)?k.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:xp(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,o,a,s,l;if(!yc(t)&&!t.newTurn)return t;let u=xp(t);if(delete u.newTurn,!yc(t))return u;let c={...(n=u.bag)!==null&&n!==void 0?n:{},rows:{...(o=(i=u.bag)===null||i===void 0?void 0:i.rows)!==null&&o!==void 0?o:{}}};for(let d of(a=r.files)!==null&&a!==void 0?a:[]){let f=Ux.find(p=>Wi[p].name===d.name&&Wi[p].fileType===d.fileType);if(!f||u.files.some(p=>p.id===d.id)||(c.rows[f]=d.id,d.content.status!=="available"))continue;let m=(0,Bp.base64ToUtf8)(d.content.data);f==="output"?c.output={status:"available",data:d.content.data}:f==="config"?(delete c.config,delete u.dataSources,delete u.model,delete u.connectorBindings,delete u.actionBindings,kx(u,c,(s=Fp(m))!==null&&s!==void 0?s:{})):f==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,Lx(u,c,(l=Fp(m))!==null&&l!==void 0?l:{}))}return u.bag=c,u}baselineContent(t){var r;let n={...t};return delete n.conversation,delete n.newTurn,n.files=[...(r=t.files)!==null&&r!==void 0?r:[]].sort((i,o)=>i.id<o.id?-1:i.id>o.id?1:0),n}normalize(t){let r=t.newTurn;return!(0,Ie.isJsonObject)(r)||typeof r.id=="string"&&Tx.test(r.id)?t:{...t,newTurn:{...r,id:(0,Up.newId)()}}}async compile(t,r,n){var i;let o=(i=t.dataSources)!==null&&i!==void 0?i:[],a=[],s=[];if(o.forEach((f,m)=>{var p;let h=(p=n?.resolveEntity)===null||p===void 0?void 0:p.call(n,f);h&&h.columnDetailComplete===!0?a.push(h):s.push((0,Ie.issue)(`/dataSources/${m}`,h?"genpage-data-source-incomplete":"genpage-data-source-unresolved",h?`the column metadata of data source '${f}' could not be read completely (a choice or lookup read failed, or returned options with no label), so the page cannot be compiled with its enums. Retry the push.`:`the metadata of data source '${f}' could not be read, so the page cannot be compiled with its enums. Check the table's logical name and that it exists in this environment.`))}),s.length>0)throw new Pa.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new Pa.ValidationError("genPage",t.id,[(0,Ie.issue)("/source","genpage-compiler-unavailable","no TypeScript compiler is available to compile the page")]);let l=await n.loadTypeScript(),u=a.length>0?(0,Rv.buildGenPageRuntimeTypes)(a):void 0,c=a.length>0?(0,Rv.buildGenPageLegacyEnums)(a):void 0,d=(0,Fx.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new Pa.ValidationError("genPage",t.id,d.diagnostics.map(Nie));return d.code}metadataNeeds(t,r){if(t.source===void 0||!Array.isArray(t.dataSources))return[];let n=Aie(t,r)?{fetchRequired:!1}:{};return t.dataSources.filter(i=>typeof i=="string"&&i!=="").map(i=>({entityLogicalName:i,fieldName:"",needsColumnDetail:!0,...n}))}createDefault(t){var r,n;let i=Dx(t.id),o={id:i,name:(r=t.name)!==null&&r!==void 0?r:"New page",files:((n=t.files)!==null&&n!==void 0?n:[]).map(a=>{var s,l,u;return{id:Dx(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=a.fileType)!==null&&l!==void 0?l:Po,content:(u=a.content)!==null&&u!==void 0?u:{status:"available",data:""}}})};t.source!==void 0&&(o.source=t.source),t.dataSources!==void 0&&(o.dataSources=[...t.dataSources]);for(let a of["model","firstPrompt","firstAgentMessage"])t[a]!==void 0&&(o[a]=t[a]);return t.newTurn!==void 0&&(o.newTurn={...t.newTurn}),t.connectorBindings!==void 0&&(o.connectorBindings=xp(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=xp(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:$p(i,"source"),output:$p(i,"output"),config:$p(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,Up.newId)()};if(!(0,Ie.isJsonObject)(t))return t;let r=t;return(Object.keys(r).length===0||"id"in r||"content"in r||"fileType"in r||Array.isArray(r.files))&&(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Up.newId)()),r}validate(t){let r=[],n=t;for(let s of["source","model","firstPrompt","firstAgentMessage"])n[s]!==void 0&&typeof n[s]!="string"&&r.push((0,Ie.issue)(`/${s}`,"genpage-field-type",`${s} must be a string, got ${typeof n[s]}`));if(n.source===void 0&&Gi(Gi(n.bag).rows).source!==void 0&&r.push(xx()),r.push(...$x(t)),n.newTurn!==void 0){let s=Gi(n.newTurn);(!(0,Ie.isJsonObject)(n.newTurn)||typeof s.prompt!="string"||s.prompt.trim()==="")&&r.push((0,Ie.issue)("/newTurn/prompt","genpage-turn-prompt","newTurn needs a non-empty prompt")),s.agentMessage!==void 0&&typeof s.agentMessage!="string"&&r.push((0,Ie.issue)("/newTurn/agentMessage","genpage-field-type","newTurn.agentMessage must be a string")),s.id!==void 0&&(typeof s.id!="string"||!Tx.test(s.id))&&r.push((0,Ie.issue)("/newTurn/id","genpage-turn-id","newTurn.id is the turn's identity, which the SDK mints \u2014 remove it, or keep the GUID it minted"))}if(n.dataSources!==void 0)if(!Array.isArray(n.dataSources))r.push((0,Ie.issue)("/dataSources","genpage-data-sources-array","dataSources must be an array of table logical names"));else{let s=new Set;n.dataSources.forEach((l,u)=>{typeof l!="string"||!Rv.TABLE_LOGICAL_NAME.test(l)?r.push((0,Ie.issue)(`/dataSources/${u}`,"genpage-data-source-name",`a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(l)}'`)):s.has(l)?r.push((0,Ie.issue)(`/dataSources/${u}`,"genpage-data-source-duplicate",`data source '${l}' is listed twice`)):s.add(l)})}n.conversation!==void 0&&!Array.isArray(n.conversation)&&r.push((0,Ie.issue)("/conversation","genpage-conversation-array","conversation must be an array"));let i=n.files;if(i!==void 0&&!Array.isArray(i))return r.push((0,Ie.issue)("/files","files-must-be-array",`files must be an array, got ${typeof i}`)),r;let o=yc(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=Gi(s),d=typeof c.id=="string"?c.id.trim().toLowerCase():"";if(d==="")r.push((0,Ie.issue)(u,"file-id-required","a generative-page file needs an id"));else{let g=a.get(d);g!==void 0?r.push((0,Ie.issue)(u,"file-id-duplicate",`two files share the id '${c.id}' (also at /files/${g}); a file's id is its identity, so a duplicate makes an edit ambiguous`)):a.set(d,l)}let f=typeof c.name=="string"?c.name:"",m=f.split("/");f===""||/[\u0000-\u001F\u007F]/.test(f)||f.includes("\\")||m.some(g=>g===""||g==="."||g==="..")?r.push((0,Ie.issue)(u+"/name","file-name-invalid",`a file name must be a relative path of non-empty '/'-separated segments (no '.', '..', backslash or control character \u2014 its last segment is sent as an HTTP header); got '${f}'`)):o&&(Ox(f)||Ix(f,Number(c.fileType))!==void 0)&&r.push((0,Ie.issue)(u+"/name","file-name-reserved",`'${f}' would be read by the maker portal as one of the page's managed rows (its source, output, config or first prompt), which the SDK writes from source and the configuration fields; it cannot also be a file in files[]`));let p=c.content;if(p===void 0){r.push((0,Ie.issue)(u+"/content","file-content-required","content is required: omitting it is indistinguishable from an empty file, and the two have opposite effects on the next push"));return}let h=Gi(p);h.status==="available"?typeof h.data!="string"&&r.push((0,Ie.issue)(u+"/content/data","file-content-data-invalid","available content needs base64 `data`")):h.status!=="unavailable"&&r.push((0,Ie.issue)(u+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(h.status)}`))}),r}};cl.GenPageAdapter=qp;function Nie(e){let t=`line ${e.line}, column ${e.column}`;return e.rule==="genpage-source-syntax"?(0,Ie.issue)("/source",e.rule,`${t}: ${e.message} (TS${e.code}) \u2014 the page cannot run, so it was not pushed`):(0,Ie.issue)("/source",e.rule,`${t}: ${e.message}`)}function _ie(){return{adapter:new qp,api:mie.genPageApi,publish:(e,t)=>(0,hie.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}cl.genPageRegistration=_ie});var zx=v(Gp=>{"use strict";Object.defineProperty(Gp,"__esModule",{value:!0});Gp.reconcileBpfSecurityRoles=void 0;var Wx=Lt(),$v=Q(),Vp=ye(),bc=le(),Tie="Global",Lv={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function Die(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,bc.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,i=(0,Vp.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.Privileges;if(!Array.isArray(o))throw new $v.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of business process flow table '${t}' returned no 'Privileges' array (got ${(0,Wx.describeMalformedValue)(o)}), so which access it can grant is unknown.`);let a=o,s={},l=new Set;return Object.keys(Lv).forEach(u=>{let c=a.find(d=>d.PrivilegeType===Lv[u]);if(c){let d=(0,bc.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function Iie(e,t){var r;let n=`/RetrieveRolePrivilegesRole(RoleId=${t})`,i=(0,Vp.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.RolePrivileges;if(!Array.isArray(o))throw new $v.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of role '${t}' returned no 'RolePrivileges' array (got ${(0,Wx.describeMalformedValue)(o)}), so what it holds is unknown.`);return new Set(o.map(a=>(0,bc.normalizeGuid)(a.PrivilegeId,"PrivilegeId")))}async function Oie(e,t,r){if(r.length===0)return;let n={Privileges:r.map(o=>({Depth:Tie,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,Vp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function Pie(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,Vp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function Rie(e,t,r){var n,i,o;if(!r||r.length===0)return;let a=await Die(e,t.toLowerCase());for(let s of r){let l=(0,bc.normalizeGuid)(s.roleId,"roleId"),u=((n=s.access)!==null&&n!==void 0?n:[]).find(c=>!a.byAccess[c]);if(u!==void 0)throw new $v.InvalidArgumentError(`Cannot grant '${u}' access to role '${l}' on business process flow table '${t.toLowerCase()}': its metadata lists no '${(i=Lv[u])!==null&&i!==void 0?i:u}' privilege. No security role was changed.`)}for(let s of r){let l=(0,bc.normalizeGuid)(s.roleId,"roleId"),u=new Set(((o=s.access)!==null&&o!==void 0?o:[]).map(p=>a.byAccess[p]).filter(p=>!!p)),c=await Iie(e,l),d=new Set([...c].filter(p=>a.all.has(p))),f=[...u].filter(p=>!d.has(p)),m=[...d].filter(p=>!u.has(p));await Oie(e,l,f);for(let p of m)await Pie(e,l,p)}}Gp.reconcileBpfSecurityRoles=Rie});var iF=v(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});jp.bpfApi=void 0;var mr=Qi(),jx=Kl(),kie=Lt(),Qe=Q(),Ye=ye(),gn=le(),Lie=zx(),$ie=Lm(),vc=xm(),xie={"Content-Type":"application/json",Accept:"application/json"},xv={...xie,Prefer:"return=representation"},Fie=`category eq ${mr.WorkflowCategory.BusinessProcessFlow} and type eq ${mr.WorkflowTypeCode.Definition} and businessprocesstype eq ${mr.BusinessProcessType.BusinessFlow}`,Mie="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",Uie="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",Bie=["xaml","name","description","processorder"];async function Wp(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,Lie.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Mv(e,t,r){let n={statecode:mr.StateCode.Activated,statuscode:mr.StatusCode.Activated},i=`/workflows(${t})`,{response:o,resent:a}=await nF(e,i,n,r,null);try{return(0,Ye.ensureSuccess)(o,e.apiUrl(i))}catch(s){throw a?tF(s):s}}var eF=new WeakSet;function tF(e){return typeof e=="object"&&e!==null&&eF.add(e),e}function rF(e){return typeof e=="object"&&e!==null&&eF.has(e)}function Hx(e){return e instanceof Qe.ConnectionError&&(e.statusCode===0||Ye.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}async function nF(e,t,r,n,i){let o=n??i,a=0;try{return{response:await(0,Ye.resendWhile)(Ye.isConcurrencyLockRefusal,()=>{a+=1;let l=a===1?n:o,u={...xv};return l&&(u["If-Match"]=l),e.patch(t,r,{headers:u})},o?Ye.LOCK_BACKOFF_MS:[]),resent:a>1}}catch(s){throw a>1?tF(s):s}}async function Kx(e,t,r){return(0,Ye.readEtag)(await Mv(e,t,r))}function Jx(e,t){return new Qe.SdkError("BPF_WRITE_NOT_ECHOED",`The ${t} of business process flow '${e}' was applied, but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next step could not be conditioned on a token this push produced and was NOT sent. `+zp(e))}async function wc(e,t){var r;let n=`/workflows(${t})${(0,gn.odataQuery)([["$select","statecode"]])}`,i=(0,Ye.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.statecode,a=Number(o);if(o==null||o===""||!Number.isFinite(a))throw new Qe.SdkError("BPF_STATE_UNREADABLE",`Reading the state of business process flow '${t}' answered HTTP ${i.status} without a usable statecode, so whether it is Active cannot be decided.`);return a}async function Fv(e,t,r,n,i=null){if((n??await wc(e,t))!==mr.StateCode.Activated)return{deactivated:!1,etag:null};let o={statecode:mr.StateCode.Draft,statuscode:mr.StatusCode.Draft},a=`/workflows(${t})`,s,l;try{({response:s,resent:l}=await nF(e,a,o,r,i))}catch(c){return await Yx(e,t,c,rF(c))}if(Ye.AMBIGUOUS_WRITE_STATUSES.has(s.status))return await Yx(e,t,new Qe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' answered HTTP ${s.status} from an intermediary, so whether it committed is unknown.`),l);let u=(0,Ye.ensureSuccess)(s,e.apiUrl(a));return{deactivated:!0,etag:(0,Ye.readEtag)(u)}}async function Yx(e,t,r,n){let i;try{i=await wc(e,t)}catch{i=void 0}if(i===mr.StateCode.Draft&&!n)return{deactivated:!0,etag:null,uncertainCause:r};if(i===mr.StateCode.Activated)throw r;let o=new Qe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",i===mr.StateCode.Draft?`Deactivating business process flow '${t}' waited for the platform's concurrency lock, and its last attempt ended without a definitive answer. The process now reads Draft, but whether this deactivate or another writer's change put it there is unknown \u2014 the row may even have been replaced at the same id \u2014 so nothing more was sent: no edit, no re-activation, no delete. It MAY be left DISABLED: read it before retrying. Original failure: ${r instanceof Error?r.message:String(r)}`:`Deactivating business process flow '${t}' did not complete, and its state could not be re-read \u2014 it MAY be left DISABLED and needs reconciling. Original failure: ${r instanceof Error?r.message:String(r)}`);throw(0,Qe.attachCause)(o,r),o}async function qie(e,t){let r=(0,gn.normalizeGuid)(t,"workflowid");try{return await Mv(e,r,null),"restored"}catch{return Uv(e,r)}}async function Vie(e,t,r){let n=(0,gn.normalizeGuid)(t,"workflowid");try{let i=await Mv(e,n,r);return{outcome:"restored",acknowledged:!0,echo:(0,Ye.readEtag)(i)}}catch(i){return i instanceof Qe.SdkError&&i.code===Ye.VERSION_CONFLICT_CODE?{outcome:"changed",acknowledged:!1,echo:null}:{outcome:await Uv(e,n),acknowledged:!1,echo:null}}}async function Uv(e,t){try{let r=await wc(e,t);return r===mr.StateCode.Activated?"restored":r===mr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}async function Qx(e,t,r,n){return r?{...await Vie(e,t,r),attempted:!0}:n?{outcome:await Uv(e,(0,gn.normalizeGuid)(t,"workflowid")),attempted:!1,acknowledged:!1,echo:null}:{outcome:await qie(e,t),attempted:!0,acknowledged:!1,echo:null}}function Gie(e,t){let r=new Qe.SdkError(vc.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting business process flow '${e}' failed${(0,vc.failedAfterResend)(t)?" after it was re-sent":""}, and re-activating the process this delete had deactivated was refused (HTTP 412): the row at that id is no longer the version this delete deactivated \u2014 it was edited, or deleted and re-created at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read the row before deleting it again. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function Xx(e,t,r,n,i=!0){let o=`Original failure: ${n instanceof Error?n.message:String(n)}`,a="it was NOT re-activated: it waited for the platform's concurrency lock, and no write of this operation proves the row is still its own, so a re-activation could have enabled another writer's edit",s;return r==="changed"?s=new Qe.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",`Business process flow '${e}' was deactivated ${t}, and re-activating it was refused (HTTP 412): the row is no longer the version this operation last wrote \u2014 another writer changed it, or replaced it at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read it before retrying. ${o}`):r==="disabled"?s=new Qe.SdkError("BPF_LEFT_DEACTIVATED",i?`Business process flow '${e}' was deactivated ${t}, and it could NOT be reactivated \u2014 it is left DISABLED. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a} \u2014 it is left DISABLED. ${o}`):s=new Qe.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",i?`Business process flow '${e}' was deactivated ${t}, and whether it was reactivated could not be confirmed \u2014 it MAY be left DISABLED and needs checking. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a}; its state could not be read \u2014 it MAY be left DISABLED and needs checking. ${o}`),(0,Qe.attachCause)(s,n),s}async function Wie(e,t){try{return await wc(e,t),"survived"}catch(r){return r instanceof Qe.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function zie(e,t,r){if(r)try{let{deactivated:n,etag:i}=await Fv(e,t,r),o=n?i:r;if(o)return await(0,vc.deleteWorkflowResending)(e,t,{bindingToken:o,kindName:"business process flow",resendDeadlockVictim:!0,ifMatchOnFirst:!0}),"removed"}catch{}return Wie(e,t)}function zp(e){return`Adopt the server's copy with fetchArtifact('bpf', '${e}', { overwrite: true }) \u2014 it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push.`}function Zx(e,t){return new Qe.SdkError("BPF_CREATE_NO_TOKEN",`Created business process flow '${e}' but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next push would have nothing to condition on. ${t} It was NOT rolled back: deleting it without a token could remove an edit made since. ${zp(e)}`)}function jie(e,t){let r=new Qe.SdkError("BPF_CREATE_NOT_ROLLED_BACK",`Creating business process flow '${e}' failed part-way, and the rollback could NOT remove it \u2014 it still EXISTS, possibly Active and half-configured. (The rollback deletes only on a token this create produced, so a row somebody has since edited is left in place on purpose; a delete the platform refused or failed leaves it too.) ${zp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function Hie(e,t){let r=new Qe.SdkError("BPF_CREATE_ROLLBACK_OUTCOME_UNKNOWN",`Creating business process flow '${e}' failed part-way, and whether its rollback removed the process could not be confirmed \u2014 it MAY still exist, possibly Active and half-configured. ${zp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function Kie(e,t){let r=new Qe.SdkError("BPF_CREATE_REMOVED_AFTER_CONFLICT",`Creating business process flow '${e}' was interrupted: another writer changed it right after it was created, so this push's next step was refused rather than overwrite or activate their edit \u2014 and the process has since been removed. Nothing is left behind and there is nothing to fetch. If the removal was deliberate, stop here; otherwise push again to re-create it at the same id. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function Bv(e){let t={};for(let r of Bie)e[r]!==void 0&&(t[r]=e[r]);return t}var Jie=["name,processorder","description,name,processorder"];function Yie(e){let{xaml:t,...r}=Bv(e);return typeof t=="string"&&Jie.includes(Object.keys(r).sort().join(","))}async function Qie(e,t,r,n){let{xaml:i,...o}=Bv(r),[,a]=await(0,jx.sendChangeSet)(e,[{method:"PATCH",path:`/workflows(${t})`,body:o,etag:n},{method:"PATCH",path:`/workflows(${t})${(0,gn.odataQuery)([["$select","workflowid"]])}`,body:{xaml:i},headers:{Prefer:"return=representation"}}],`business process flow '${t}'`,{resendWhileLockRefused:!0});return(0,Ye.readEtag)((0,jx.partResponse)(a))}jp.bpfApi={async get(e,t){let n=`/workflows(${(0,gn.normalizeGuid)(t,"id")})${(0,gn.odataQuery)([["$select",Uie]])}`,i=(0,Ye.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Ye.readEtag)(i)}},async list(e,t){let r=[Fie];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,gn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,gn.odataQuery)([["$select",Mie],["$filter",r.join(" and ")]])}`;return(await(0,kie.collectPages)(e,n,"listArtifacts('bpf')")).map(o=>{var a,s;return{type:"bpf",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){let r=t,n=(0,gn.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",o=(0,Ye.ensureSuccess)(await e.post(i,r.record,{headers:xv}),e.apiUrl(i)),a=(0,Ye.readEtag)(o);if(!a)throw Zx(n,r.status==="Active"?"The process EXISTS as Draft and was NOT activated \u2014 an activation that cannot be conditioned on our own write could activate somebody else's edit.":"The process EXISTS as Draft.");let s=a;try{r.status==="Active"&&(s=await Kx(e,n,a)),await Wp(e,r)}catch(l){let u=await zie(e,n,s);throw u==="survived"?jie(n,l):u==="unknown"?Hie(n,l):l instanceof Qe.SdkError&&l.code===Ye.VERSION_CONFLICT_CODE?Kie(n,l):l}if(!s)throw Zx(n,"The process EXISTS and IS Active, but its activation returned no token.");return{id:n,etag:s}},async update(e,t,r,n){let i=r,o=(0,gn.normalizeGuid)(t,"id"),a=(0,Ye.requireEtag)(n,"bpf",o),s=await wc(e,o);if(s===mr.StateCode.Activated&&i.status==="Active"&&e.supportsAtomicBatch&&Yie(i.record)){let p=await Qie(e,o,i.record,a);return await Wp(e,i),{id:o,etag:p}}let{deactivated:l,etag:u,uncertainCause:c}=await Fv(e,o,a,s),d=u,f=!1,m=!1;try{if(c!==void 0)throw c;let p=a;if(l){if(!u)throw Jx(o,"deactivation");p=u}let h=`/workflows(${o})`,g;try{g=(0,Ye.ensureSuccess)(await e.patch(h,Bv(i.record),{headers:{...xv,"If-Match":p}}),e.apiUrl(h))}catch(w){throw Hx(w)&&(d=null),w}let b=(0,Ye.readEtag)(g);if(d=b,i.status==="Active"){if(!b)throw Jx(o,"definition write");try{b=await Kx(e,o,b)}catch(w){throw Hx(w)&&(d=null),m=(0,Ye.isConcurrencyLockRefusalError)(w),w}f=!0}return await Wp(e,i),{id:o,etag:b}}catch(p){if(l&&!f){let{outcome:h,attempted:g,acknowledged:b,echo:w}=await Qx(e,o,d,rF(p));if(m&&b)return f=!0,await Wp(e,i),{id:o,etag:w};if(h!=="restored")throw Xx(o,"to apply an edit, the edit failed",h,p,g)}throw p}},async delete(e,t){let r=(0,gn.normalizeGuid)(t,"id"),n=await(0,$ie.assertWorkflowKind)(e,r,mr.WorkflowCategory.BusinessProcessFlow),{deactivated:i,etag:o}=await Fv(e,r,null,void 0,n);try{await(0,vc.deleteWorkflowResending)(e,r,{bindingToken:i?o:n,kindName:"business process flow",deactivated:i,resendDeadlockVictim:!0})}catch(a){if(i&&!(0,vc.isWorkflowDeleteUnsettled)(a)){let{outcome:s,attempted:l}=await Qx(e,r,o,!1);if(s==="changed")throw Gie(r,a);if(s!=="restored")throw Xx(r,"so it could be deleted, the delete failed",s,a,l)}throw a}}}});var qF=v(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});fl.bpfRegistration=fl.BpfAdapter=void 0;var Hp=Qi(),Xie=iF(),qv=so(),Ra=uo(),yF=lo(),Hr=rn(),Mr=pt(),Fn=Q(),Zie=100,Vv='<?xml version="1.0" encoding="utf-16"?>',oF=1033,bF="mxswa:Workflow",eoe="mxswa:ActivityReference.Properties",toe="mcwo:StepLabel",roe="mcwb:Control",aF="mcwb:Control.ControlDisplayName",vF="mcwb:Control.DataFieldName",wF="DataFieldName",sF="ControlDisplayName",CF="Literal",Jp="x:Null",lF="x:String",Gv="x:Key",Wv="DisplayName",Qp="Activities",noe="StepLabels",EF="StageId",AF="StageCategory",SF="NextStageId",NF="ProcessStepId",Kp="IsProcessRequired",_F="EntityComposite",TF="StageComposite",DF="StepComposite";function Cc(e){return(0,Hr.isJsonObject)(e)?e:{}}function ci(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 ka(e,t){var r;return(r=ci(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function fi(e){return ka(e,eoe)}function hr(e,t){var r;return(r=ci(e).find(n=>n.getAttribute(Gv)===t))!==null&&r!==void 0?r:null}function dl(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function di(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function IF(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function Ec(e){var t;let r=(t=e.getAttribute(Wv))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function OF(e,t){var r;let n=(r=e.getAttribute(Wv))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(Wv,i>=0?n.slice(0,i+2)+t:t)}function PF(e,t){let r=hr(e,noe),n=ka(r,toe);n&&n.setAttribute("Description",t)}function ioe(e){let t=hr(e,AF);if(!t||t.tagName===Jp)return;let r=di(t).trim();return r===""?void 0:Number(r)}function ooe(e){let t=hr(e,SF);if(!t||t.tagName===Jp)return;let r=di(t).trim();return r===""?void 0:r}function RF(e){let t=kF(e);if(!t)return;let r=$F(t,wF,vF);return r===""?void 0:r}function zv(e,t){let r=ci(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of ci(n))r.push(i)}return null}function kF(e){let t=hr(fi(e),Qp);return t?zv(t,roe):null}function LF(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 $F(e,t,r){var n;return LF(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":coe(e,r)}function uF(e,t,r,n){if(LF(e,t)){e.setAttribute(t,n);return}if(ka(e,r)){aoe(e,r,n);return}throw new Fn.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function aoe(e,t,r){let n=ka(e,t),i=n?zv(n,CF):null;if(!i)throw new Fn.InvalidArgumentError(`BPF step control's <${t}> wrapper holds no <Literal> to bind a column`);i.setAttribute("Value",r)}function xF(e){return Ec(e)}function Xp(e){let t=ka(e,bF),r=[];for(let n of ci(t).filter(i=>dl(i,_F))){let i=hr(fi(n),Qp);for(let o of ci(i).filter(a=>dl(a,TF)))r.push({el:o,entity:xF(n)})}return r}function jv(e){let t=hr(fi(e),Qp);return ci(t).filter(r=>dl(r,DF))}function soe(e){let t=fi(e),r=di(hr(t,Kp)).trim().toLowerCase(),n=RF(e),i={id:di(hr(t,NF)),name:Ec(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function loe(e,t){let r=fi(e),n=ioe(r),i=ooe(r),o={id:di(hr(r,EF)),name:Ec(e),entityLogicalName:t,steps:jv(e).map(soe)};return n!==void 0&&(o.category=n),i!==void 0&&(o.nextStageId=i),o}function uoe(e){return Xp(e).map(({el:t,entity:r})=>loe(t,r))}function ui(e){return new Fn.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 coe(e,t){var r;let n=ka(e,t),i=n?zv(n,CF):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function Hv(e,t){var r;let n=e.createElement(t.tagName),i=t.attributes;for(let a=0;a<i.length;a+=1)n.setAttribute(i[a].name,i[a].value);let o=t.childNodes;for(let a=0;a<o.length;a+=1){let s=o[a];s.nodeType===1?n.appendChild(Hv(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function FF(e){return hr(fi(e),Qp)}function doe(e,t,r){var n;let i=t.entityLogicalName&&t.entityLogicalName.trim()!==""?t.entityLogicalName:r,o=!((n=t.steps[0])===null||n===void 0)&&n.id&&t.steps[0].id.trim()!==""?t.steps[0].id:(0,Mr.newId)(),{body:a}=Zp(Kv(i,(0,Mr.newId)(),t.id,o));return Hv(e,Xp((0,Ra.parseXmlRoot)(a,"<Activity/>"))[0].el)}function foe(e,t){let{body:r}=Zp(Kv("account",(0,Mr.newId)(),(0,Mr.newId)(),t.id));return Hv(e,jv(Xp((0,Ra.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function MF(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function UF(e,t,r,n){let i=hr(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw ui(`setting '${r}' on a stage whose xaml does not expose that slot`);return}let o=i.parentNode;if(n===void 0||n===""){if(i.tagName!==Jp&&di(i).trim()!==""){let s=t.createElement(Jp);s.setAttribute(Gv,r),o.replaceChild(s,i)}return}if(i.tagName===lF){di(i).trim()!==n&&IF(i,t,n);return}let a=t.createElement(lF);a.setAttribute(Gv,r),a.appendChild(t.createTextNode(n)),o.replaceChild(a,i)}function poe(e,t,r){UF(e,t,AF,r===void 0?void 0:String(r))}function moe(e,t,r){UF(e,t,SF,r)}function BF(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 cF(e){return di(hr(fi(e),EF))}function dF(e){return di(hr(fi(e),NF))}function fF(e,t,r){var n,i,o,a;let s=fi(e);r.name!==Ec(e)&&(OF(e,r.name),PF(s,r.name));let l=di(hr(s,Kp)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=hr(s,Kp);if(!u)throw ui(`setting '${Kp}' on a step whose xaml does not expose that slot`);IF(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((o=RF(e))!==null&&o!==void 0?o:"")){let u=kF(e);if(!u)throw new Fn.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=r.fieldName)!==null&&a!==void 0?a:"";uF(u,wF,vF,c),c!==""&&$F(u,sF,aF)===""&&uF(u,sF,aF,c)}}function pF(e,t,r,n){var i;let o=fi(e);if(!o)throw new Fn.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==Ec(e)&&(OF(e,r.name),PF(o,r.name)),poe(o,t,r.category),moe(o,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw ui("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw ui("stage actions or conditional branching");let a=FF(e);if(!a)throw new Fn.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new Fn.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=jv(e);if(BF(l,s.map(d=>d.id),dF)){l.forEach((d,f)=>fF(d,t,s[f]));return}let u=new Map(l.map(d=>[dF(d),d]));if(ci(a).some(d=>!dl(d,DF)))throw ui("adding, removing or reordering steps on a stage that also contains branching or actions");let c=s.map(d=>{var f;return(f=u.get(d.id))!==null&&f!==void 0?f:foe(t,d)});MF(a,c),c.forEach((d,f)=>fF(d,t,s[f]))}function hoe(e,t,r){let n=ka(e,bF);if(!n)throw new Fn.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw ui("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new Fn.InvalidArgumentError("a BPF must have at least one stage");let i=Xp(e),o=i.map(f=>f.el);if(BF(o,r.stages.map(f=>f.id),cF)){i.forEach(({el:f,entity:m},p)=>{let h=r.stages[p];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==m)throw ui(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${m}')`);pF(f,t,h,h.nextStageId)});return}let a=ci(n).filter(f=>dl(f,_F));if(a.length!==1)throw ui("adding, removing or reordering stages on a multi-table process");let s=a[0],l=xF(s),u=FF(s);if(!u)throw new Fn.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(ci(u).some(f=>!dl(f,TF)))throw ui("adding, removing or reordering stages on a process whose primary composite holds non-stage activities (multi-table nesting or advanced constructs)");for(let f of r.stages)if(f.entityLogicalName&&f.entityLogicalName.trim()!==""&&f.entityLogicalName!==l)throw ui(`a stage on a different table ('${f.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(o.map(f=>[cF(f),f])),d=r.stages.map(f=>{var m;return(m=c.get(f.id))!==null&&m!==void 0?m:doe(t,f,l)});MF(u,d),d.forEach((f,m)=>{let p=m<d.length-1?r.stages[m+1].id:void 0;pF(f,t,r.stages[m],p)})}function Zp(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function goe(e){var t,r,n,i,o,a;(0,yF.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let f=new DOMParser().parseFromString("<root/>","text/xml"),m={n:"Activity",a:(0,qv.mergeAttrs)(s.a,[]),c:(0,qv.spliceChildren)(s.c,[])};return{root:(0,qv.rebuildRaw)(m,(0,Ra.domEngine)(f),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Vv,eol:(o=(i=e.bag)===null||i===void 0?void 0:i.xamlEol)!==null&&o!==void 0?o:"lf"}}let l=e.stages[0],u=(a=l?.steps)===null||a===void 0?void 0:a[0],c=Kv(e.entityLogicalName,(0,Mr.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,Mr.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,Mr.newId)()),{body:d}=Zp(c);return{root:(0,Ra.parseXmlRoot)(d,"<Activity/>"),prolog:Vv,eol:"lf"}}function yoe(e){let{root:t,prolog:r,eol:n}=goe(e);hoe(t,t.ownerDocument,e);let i=(0,Ra.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r
+`)),r+i}function boe(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Yp=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,yF.installDomShim)();let i=t,o=typeof i.xaml=="string"?i.xaml:"",a={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&&(a.uniqueName=String(i.uniquename)),i.description!=null&&i.description!==""&&(a.description=String(i.description)),i.processorder!=null&&i.processorder!==""&&(a.order=Number(i.processorder)),o.trim()!==""){let{prolog:s,body:l}=Zp(o),u=(0,Ra.parseXmlRoot)(l,"<Activity/>");a.stages=uoe(u),a.bag={xaml:(0,Ra.projectElementBag)(u),xamlProlog:s,xamlEol:/\r\n/.test(o)?"crlf":"lf"}}return a}toApiPayload(t){var r;let n={workflowid:t.id&&t.id.trim()!==""?t.id:(0,Mr.newId)(),name:t.name,uniquename:boe(t),primaryentity:t.entityLogicalName,xaml:yoe(t),category:Hp.WorkflowCategory.BusinessProcessFlow,type:Hp.WorkflowTypeCode.Definition,businessprocesstype:Hp.BusinessProcessType.BusinessFlow,scope:Hp.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:Zie};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 Fn.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 o=t.stages&&t.stages.length>0?t.stages.map(hF):[hF({id:(0,Mr.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,Mr.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:o};return t.uniqueName&&(a.uniqueName=t.uniqueName),t.description!==void 0&&(a.description=t.description),t.order!==void 0&&(a.order=t.order),t.globalActions!==void 0&&(a.globalActions=t.globalActions),t.securityRoles!==void 0&&(a.securityRoles=t.securityRoles),a}assignMissingIds(t){let r=Cc(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Mr.newId)());for(let n of["stages","steps","actions","globalActions"]){let i=r[n];Array.isArray(i)&&i.forEach(o=>this.assignMissingIds(o))}return r}validate(t){let r=[],n=t.stages;if(n!==void 0&&!Array.isArray(n))return r.push((0,Hr.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,Hr.issue)("/stages","too-many-stages",`a BPF allows at most 30 stages, got ${i.length}`));let o=new Set,a=new Map;i.forEach((l,u)=>{let c=`/stages/${u}`,d=Cc(l),f=typeof d.id=="string"?d.id.trim():"";f===""?r.push((0,Hr.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(f.toLowerCase())?r.push((0,Hr.issue)(`${c}/id`,"stage-id-duplicate",`two stages share the id '${d.id}' (also at /stages/${a.get(f.toLowerCase())})`)):a.set(f.toLowerCase(),u),typeof d.entityLogicalName=="string"&&d.entityLogicalName!==""&&o.add(d.entityLogicalName);let m=Array.isArray(d.steps)?d.steps:[];m.length===0&&r.push((0,Hr.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),m.length>30&&r.push((0,Hr.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${m.length}`));let p=new Map;m.forEach((h,g)=>{let b=`${c}/steps/${g}`,w=typeof Cc(h).id=="string"?h.id.trim():"";w===""?r.push((0,Hr.issue)(`${b}/id`,"step-id-required","a step needs an id")):p.has(w.toLowerCase())?r.push((0,Hr.issue)(`${b}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):p.set(w.toLowerCase(),g)}),d.branch&&!mF(i,d.branch.nextStageId)&&r.push((0,Hr.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${d.branch.nextStageId}' does not match any stage id`)),typeof d.nextStageId=="string"&&d.nextStageId!==""&&!mF(i,d.nextStageId)&&r.push((0,Hr.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${d.nextStageId}' does not match any stage id`))}),o.size>5&&r.push((0,Hr.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=voe(i);return s>=0&&r.push((0,Hr.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};fl.BpfAdapter=Yp;function voe(e){let t=new Map(e.map(r=>[Cc(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 mF(e,t){return e.some(r=>Cc(r).id===t)}function hF(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(gF):[gF({id:(0,Mr.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,Mr.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 gF(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,Mr.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 Kv(e,t,r,n){return`${Vv}<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="${oF}" /></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="${oF}" /></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 woe(){return{adapter:new Yp,api:Xie.bpfApi,languageSensitive:!0}}fl.bpfRegistration=woe});var VF=v(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});em.buildRegistrations=void 0;var Coe=Lk(),Eoe=eL(),Aoe=x1(),Soe=e$(),Noe=N$(),_oe=W$(),Toe=sx(),Doe=Gx(),Ioe=qF();function Ooe(e){let t=new Map;return t.set("form",(0,Coe.formRegistration)(e)),t.set("view",(0,Eoe.viewRegistration)()),t.set("businessRule",(0,Aoe.businessRuleRegistration)()),t.set("app",(0,Soe.appRegistration)(e)),t.set("command",(0,Noe.commandRegistration)()),t.set("chart",(0,_oe.chartRegistration)()),t.set("dashboard",(0,Toe.dashboardRegistration)(e)),t.set("genPage",(0,Doe.genPageRegistration)()),t.set("bpf",(0,Ioe.bpfRegistration)()),t}em.buildRegistrations=Ooe});var rM=v(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE=Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE=Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE=Te.removeRowSummary=Te.configureRowSummary=Te.buildGptDynamicPrompt=Te.setAppAiFeatures=Te.getAiReadiness=Te.saveSettingValue=Te.retrieveSetting=Te.AI_GATE=void 0;var zi=Lt(),yn=ye(),qe=le(),GF=pt(),Ve=Q();Te.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var JF={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},Poe=new Set(Object.entries(Te.AI_GATE).filter(([e,t])=>JF[e]===t).map(([e])=>e)),Roe={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function Jv(e){return Roe[e]}var tm=1e6;function koe(e,t){let r=Jv(t),n=()=>{throw new Ve.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${tm} (e.g. 0, 1, 2); got '${String(e)}'.`)},i=o=>r?o?r.enabled:r.disabled:o?"1":"0";if(typeof e=="boolean")return i(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>tm?n():String(e);if(typeof e=="string"){let o=e.trim(),a=o.toLowerCase();if(a==="true")return i(!0);if(a==="false")return i(!1);if(/^[0-9]+$/.test(o)){let s=o.replace(/^0+(?=[0-9])/,"");return s.length>String(tm).length||Number(s)>tm?n():s}}return n()}function Loe(e,t){let r=Jv(t);return r?e===r.enabled:e!=="0"}async function $oe(e,t){var r,n;let i=`/appmodules${(0,qe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,o=await e.get(i);if(o.status<200||o.status>=300)return;let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ve.ConnectionError(e.apiUrl(i),o.status,`the app lookup for '${t}' returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(a)}`);return(n=a[0])===null||n===void 0?void 0:n.appmoduleid}async function xoe(e,t){var r,n;let i=`/appmodules${(0,qe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,o;try{o=await e.get(i)}catch(l){throw new Ve.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(o.status<200||o.status>=300)throw new Ve.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned HTTP ${o.status}. Retry, or omit appModuleId to verify by name.`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ve.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a malformed body.`);if(a.length===0)return;let s=(n=a[0])===null||n===void 0?void 0:n.appmoduleid;if(!s)throw new Ve.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var WF=new WeakMap;async function Foe(e,t){var r,n;let i=WF.get(e);if(i||(i=new Map,WF.set(e,i)),i.has(t))return i.get(t);let o=`/settingdefinitions${(0,qe.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,a=await e.get(o);if(a.status<200||a.status>=300)return;let s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))throw new Ve.ConnectionError(e.apiUrl(o),a.status,`the setting definition lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(s)}`);let l=(n=s[0])===null||n===void 0?void 0:n.settingdefinitionid;return l&&i.set(t,l),l}async function Moe(e,t,r){var n,i;let o=await Foe(e,r);if(!t||!o)return;let a=`/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()${(0,qe.odataQuery)([["$select","value,componentstate"],["$filter",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${o}`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)return;let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new Ve.ConnectionError(e.apiUrl(a),s.status,`the app-scope override read returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(l)}`);let u=l;if(u.length===0)return{exists:!1};let c=(i=u.find(d=>d?.componentstate===1))!==null&&i!==void 0?i:u[0];return{exists:!0,value:c.value,pendingPublish:c.componentstate===1}}var Uoe=4,Boe=500,zF=20,jF=3e4;function qoe(e){if(e===void 0)return Uoe;if(!Number.isFinite(e))throw new Ve.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${zF}; got ${e}.`);return Math.min(zF,Math.max(1,Math.floor(e)))}function Voe(e){if(e===void 0)return Boe;if(!Number.isFinite(e))throw new Ve.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${jF}; got ${e}.`);return Math.min(jF,Math.max(0,Math.floor(e)))}async function Goe(e,t,r,n,i,o,a){let s,l,u,c=!1;for(let d=0;d<o;d+=1){d>0&&await new Promise(m=>setTimeout(m,a*d));let f;try{let m=await t();m?(f=await Moe(e,m,n),f===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){f=void 0,u=m.message}c=f!==void 0,l=f?.exists;try{s=(await rm(e,n,{appUniqueName:r})).value}catch{}if(f?.exists&&f.value===i)return{result:"proven",effectiveValue:f.value,appOverrideExists:!0,...f.pendingPublish?{pendingPublish:!0}:{}}}return c?{result:"absent",effectiveValue:s,appOverrideExists:l}:{result:"unverifiable",effectiveValue:s,appOverrideExists:void 0,reason:u}}function YF(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?Jv(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function rm(e,t,r={}){var n;let i=[`SettingName='${(0,qe.odataPathLiteral)(t)}'`];r.appUniqueName&&i.push(`AppUniqueName='${(0,qe.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${i.join(",")})`,a=(0,yn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.SettingDetail;if(s===null||typeof s!="object"||Array.isArray(s)||!("Value"in s))throw new Ve.ConnectionError(e.apiUrl(o),a.status,`RetrieveSetting for '${t}' returned a malformed answer \u2014 expected a SettingDetail with a Value`);let{Value:l,DataType:u}=s;return{value:l,dataType:u}}Te.retrieveSetting=rm;async function QF(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,yn.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Te.saveSettingValue=QF;async function Woe(e,t={}){let r={};for(let[n,i]of Object.entries(Te.AI_GATE)){let{value:o,dataType:a}=await rm(e,i,t);r[n]={enabled:YF(o,a,n),setting:i,value:o}}return r}Te.getAiReadiness=Woe;async function zoe(e,t,r,n={}){var i;if(!t||!t.trim())throw new Ve.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let o=qoe(n.verifyAttempts),a=Voe(n.verifyDelayMs),s=[];for(let[p,h]of Object.entries(r)){if(h===void 0)continue;let g=JF[p];g&&s.push({feature:p,setting:g,requestedValue:koe(h,p)})}let l=[],u=n.appModuleId?(0,qe.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(u){let p=await xoe(e,t);if(p&&(0,qe.normalizeGuid)(p,"appModuleId")!==u)throw new Ve.InvalidArgumentError(`setAppAiFeatures: appModuleId '${u}' does not belong to app '${t}' (which resolves to '${p}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let c,d=async()=>u||(c||(c=await $oe(e,t)),c),f=new Map,m=async p=>{if(Poe.has(p))return;let h=Te.AI_GATE[p];if(h){if(!f.has(h))try{let{value:g,dataType:b}=await rm(e,h);f.set(h,{enabled:YF(g,b,p),setting:h,value:g})}catch{f.set(h,void 0)}return f.get(h)}};for(let{feature:p,setting:h,requestedValue:g}of s)try{await QF(e,h,g,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let b=await Goe(e,d,t,h,g,o,a),w={feature:p,setting:h,requestedValue:g,effectiveValue:b.effectiveValue,appOverrideExists:b.appOverrideExists};if(b.result==="proven")l.push({...w,status:"applied",...b.pendingPublish?{pendingPublish:!0}:{}});else if(b.result==="absent"){let C=Loe(g,p)?await m(p):void 0;C&&!C.enabled?l.push({...w,status:"skipped",reason:`the write was issued and no app-scope override holding '${g}' was observed for '${h}' after ${o} attempt(s); the org readiness gate '${C.setting}' reads '${C.value}', so an environment admin must enable it before this app can turn the feature on`}):l.push({...w,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${g}' was observed for '${h}' after ${o} attempt(s) \u2014 ${b.effectiveValue===void 0?"the value in effect for this app could not be read":`it reads '${b.effectiveValue}' for this app`} (Dataverse can accept an app-scope write without storing it)`})}else l.push({...w,status:"unverified",reason:`the write was issued but could not be confirmed: ${(i=b.reason)!==null&&i!==void 0?i:"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(b){l.push({feature:p,setting:h,requestedValue:g,status:"failed",reason:b.message})}return{applied:l.filter(p=>p.status==="applied").map(p=>p.feature),skipped:l.filter(p=>p.status==="skipped").map(p=>p.feature),notPersisted:l.filter(p=>p.status==="notPersisted").map(p=>p.feature),unverified:l.filter(p=>p.status==="unverified").map(p=>p.feature),failed:l.filter(p=>p.status==="failed").map(p=>p.feature),outcomes:l}}Te.setAppAiFeatures=zoe;var XF="GptPowerPrompt",joe='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function ZF(e){var t,r,n,i;let o=e.entityLogicalName,a=[{type:"literal",text:e.instruction.replace(/\s*$/,"")+" "}];return e.columns.forEach((s,l)=>{a.push({type:"data",id:`${o}.${s.logical}`,text:s.display}),l<e.columns.length-1&&a.push({type:"literal",text:", "})}),{version:"GptDynamicPrompt-2",prompt:a,definitions:{inputs:[{id:"RecordId",text:"RecordId",type:"text"},{id:"LanguageCode",text:"LanguageCode",type:"text"}],formulas:[],data:[{id:o,displayName:o,type:"dataverseTable",filters:[{filterType:"equal",attribute:e.primaryKey,valueType:"inputVariable",value:"RecordId"}]}],output:{formats:[(t=e.outputFormat)!==null&&t!==void 0?t:"text"]}},modelParameters:{modelType:"default",gptParameters:{temperature:(r=e.temperature)!==null&&r!==void 0?r:0}},settings:{recordRetrievalLimit:(n=e.recordRetrievalLimit)!==null&&n!==void 0?n:30,shouldPreserveRecordLinks:null,runtime:null,enableReasoning:(i=e.enableReasoning)!==null&&i!==void 0?i:!0},code:"",signature:""}}Te.buildGptDynamicPrompt=ZF;async function Hoe(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,qe.odataPathLiteral)(t)}')${(0,qe.odataQuery)([["$select","MetadataId"]])}`,i=(0,yn.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.MetadataId;if(typeof o!="string"||o==="")throw new Ve.ConnectionError(e.apiUrl(n),i.status,`the table metadata read for '${t}' returned a malformed answer \u2014 expected a MetadataId but got ${o===""?"an empty string":(0,zi.describeMalformedValue)(o)}`);return o}function Yv(e,t,r,n){if(e.length===0)return;let i=e[0];if(typeof i!="object"||i===null||Array.isArray(i))throw new Ve.ConnectionError(t,r,`${n} returned a malformed row \u2014 expected an object but got ${Array.isArray(i)?"an array":(0,zi.describeMalformedValue)(i)}`);return i}async function eM(e){var t;let r=`/msdyn_aitemplates${(0,qe.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${XF}'`],["$top",1]])}`,n=(0,yn.ensureSuccess)(await e.get(r),e.apiUrl(r)),i=(t=n.body)===null||t===void 0?void 0:t.value;if(!Array.isArray(i))throw new Ve.ConnectionError(e.apiUrl(r),n.status,`the row-summary template lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(i)}`);let o=Yv(i,e.apiUrl(r),n.status,"the row-summary template lookup");if(!o)return;let a=o.msdyn_aitemplateid;if(typeof a=="string"&&a!=="")try{return(0,qe.normalizeGuid)(a,"msdyn_aitemplateid")}catch{}throw new Ve.ConnectionError(e.apiUrl(r),n.status,`the row-summary template lookup returned a malformed row \u2014 expected a GUID 'msdyn_aitemplateid' but got ${a===""?"an empty string":typeof a=="string"?"a string that is not a GUID":(0,zi.describeMalformedValue)(a)}`)}function tM(e){return`${e} row summary`}async function Koe(e,t,r){var n;let i=`/msdyn_aimodels(${t})${(0,qe.odataQuery)([["$select","msdyn_name,_msdyn_templateid_value"]])}`,o=await e.get(i);if(o.status===404)return!1;let a=(n=(0,yn.ensureSuccess)(o,e.apiUrl(i)).body)!==null&&n!==void 0?n:{},s=await eM(e);return typeof a.msdyn_name=="string"&&a.msdyn_name.toLowerCase()===tM(r).toLowerCase()&&typeof a._msdyn_templateid_value=="string"&&s!==void 0&&a._msdyn_templateid_value.toLowerCase()===s.toLowerCase()}async function Joe(e,t,r={}){var n;let i=`ais_RowSummary_${t.entityLogicalName}`,o=`/aiskillconfigs${(0,qe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(i)}'`],["$top",1]])}`,a=(0,yn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new Ve.ConnectionError(e.apiUrl(o),a.status,`the existing row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(s)}`);let l=Yv(s,e.apiUrl(o),a.status,"the existing row-summary skill lookup");if(l)return{modelId:l._aimodel_value,aiSkillConfigId:l.aiskillconfigid};let u=await Hoe(e,t.entityLogicalName),c=await eM(e);if(c===void 0)throw new Ve.SdkError(Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE,`Cannot configure the row summary of '${t.entityLogicalName}': this org has no AI template '${XF}' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written.`);let d=(0,GF.newId)(),f=(0,GF.newId)(),m=JSON.stringify(ZF(t)),p={ModelId:d,RunConfigurationId:f,ModelName:tM(t.entityLogicalName),TemplateId:c,CustomConfiguration:m,Source:joe,RunConfiguration:""};(0,yn.ensureSuccess)(await e.post("/AIModelPublish",p),e.apiUrl("/AIModelPublish"));try{let h={uniquename:i,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${u})`,"[email protected]":`/msdyn_aimodels(${d})`,aiskill:"RowSummary"},g=(0,yn.ensureSuccess)(await e.post("/aiskillconfigs",h),e.apiUrl("/aiskillconfigs")),b=(0,yn.requireCreatedId)(g,"aiskillconfigid","row-summary skill");return{modelId:d,aiSkillConfigId:b}}catch(h){try{await e.delete(`/msdyn_aimodels(${d})`)}catch{}throw h}}Te.configureRowSummary=Joe;async function Yoe(e,t){var r;let n=`ais_RowSummary_${t.entityLogicalName}`,i=`/aiskillconfigs${(0,qe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(n)}'`],["$top",1]])}`,o=(0,yn.ensureSuccess)(await e.get(i),e.apiUrl(i)),a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ve.ConnectionError(e.apiUrl(i),o.status,`the row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(a)}`);let s=Yv(a,e.apiUrl(i),o.status,"the row-summary skill lookup");if(!s)return{removed:!1};let l=(0,qe.normalizeGuid)(s.aiskillconfigid,"aiskillconfigid"),u=s._aimodel_value?(0,qe.normalizeGuid)(s._aimodel_value,"_aimodel_value"):void 0,c=u?await Koe(e,u,t.entityLogicalName):!1,d=t.entityLogicalName,f=`/aiskillconfigs(${l})`,m=await HF(e,f,`${f}${(0,qe.odataQuery)([["$select","aiskillconfigid"]])}`);if(m.kind==="failed")throw m.stillThere===void 0&&u&&c?(0,Ve.attachCause)(new Ve.SdkError(Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE,`Removing the row summary of '${d}' could not be confirmed: deleting its skill row failed (${KF(m.failure)}) and the row could not be read back. If it is gone, its AI model '${u}' is left behind, unreferenced. Retry removeRowSummary: while the skill row exists it removes both; once it is gone, delete that model.`),m.failure):m.failure;if(u&&c){let p=`/msdyn_aimodels(${u})`,h=await HF(e,p,`${p}${(0,qe.odataQuery)([["$select","msdyn_aimodelid"]])}`,Xoe);if(h.kind==="failed")throw(0,Ve.attachCause)(new Ve.SdkError(Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE,`The row summary of '${d}' was removed, but its AI model '${u}' ${h.stillThere?"was not deleted":"could not be confirmed deleted"} (${KF(h.failure)}). The model is no longer used by the row summary; delete it before configuring a row summary for '${d}' again, which needs its name.`),h.failure)}return{removed:!0}}Te.removeRowSummary=Yoe;Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE="ROW_SUMMARY_MODEL_NOT_DELETED";Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE="ROW_SUMMARY_REMOVAL_UNCONFIRMED";Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE="ROW_SUMMARY_TEMPLATE_NOT_FOUND";var Qoe="0x8004f01f";function Xoe(e){var t,r;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return e.status===400&&typeof n=="string"&&n.toLowerCase()===Qoe}function Zoe(e){if(e.status!==400&&e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/chosen as the deadlock victim|\bSql Number:\s*1205\b/i.test(t)}async function HF(e,t,r,n=()=>!1){let i;try{let o=await(0,yn.resendWhile)(Zoe,()=>e.delete(t));if(o.status>=200&&o.status<300||o.status===404)return{kind:"gone"};if(n(o))return{kind:"kept"};try{(0,yn.ensureSuccess)(o,e.apiUrl(t))}catch(a){i=a}}catch(o){i=o}try{let o=await e.get(r);return o.status===404?{kind:"gone"}:{kind:"failed",failure:i,stillThere:o.status>=200&&o.status<300?!0:void 0}}catch{return{kind:"failed",failure:i,stillThere:void 0}}}function KF(e){return e instanceof Error?e.message:String(e)}});var oM=v(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});pl.findArtifact=pl.resolveArtifact=void 0;var qt=le(),ji=$d(),eae=zd(),tae=Lt(),rae=ye(),nM=Q();async function iM(e,t,r){let n="/uxagentprojects"+(0,qt.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,qt.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,tae.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function nae(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p;switch(t){case"app":{let h=(0,eae.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,qt.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),b=(i=(0,rae.ensureSuccess)(await e.get(h),e.apiUrl(h)).body)===null||i===void 0?void 0:i.value,w=b&&b[0];return w?[{id:String(w.appmoduleid),name:String(w.name),appModuleIdUnique:String(w.appmoduleidunique)}]:[]}case"dashboard":return(await(0,ji.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,qt.odataLiteral)((o=r.name)!==null&&o!==void 0?o:"")}' and type eq 0`,top:10})||[]).map(g=>({id:String(g.formid),name:String(g.name)}));case"command":{if(!r.entity)return[];let h=await(0,ji.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,qt.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?[{id:r.entity,entity:r.entity}]:[]}case"form":return(await(0,ji.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,qt.odataLiteral)((a=r.name)!==null&&a!==void 0?a:"")}' and objecttypecode eq '${(0,qt.odataLiteral)((s=r.entity)!==null&&s!==void 0?s:"")}'`,top:10})||[]).map(g=>({id:String(g.formid),name:String(g.name)}));case"chart":return(await(0,ji.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,qt.odataLiteral)((l=r.name)!==null&&l!==void 0?l:"")}' and primaryentitytypecode eq '${(0,qt.odataLiteral)((u=r.entity)!==null&&u!==void 0?u:"")}'`,top:10})||[]).map(g=>({id:String(g.savedqueryvisualizationid),name:String(g.name)}));case"view":return(await(0,ji.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,qt.odataLiteral)((c=r.name)!==null&&c!==void 0?c:"")}' and returnedtypecode eq '${(0,qt.odataLiteral)((d=r.entity)!==null&&d!==void 0?d:"")}'`,top:10})||[]).map(g=>({id:String(g.savedqueryid),name:String(g.name)}));case"webResource":return(await(0,ji.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,qt.odataLiteral)((f=r.name)!==null&&f!==void 0?f:"")}'`,top:1})||[]).map(g=>({id:String(g.webresourceid),name:String(g.name)}));case"solution":return(await(0,ji.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,qt.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(g=>({id:String(g.solutionid),name:String(g.uniquename)}));case"genPage":return iM(e,(p=r.name)!==null&&p!==void 0?p:"");default:return[]}}pl.resolveArtifact=nae;async function iae(e,t,r){var n,i,o,a,s,l;let u=(0,qt.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),c=(0,qt.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){if(!r.entity)return null;let h=await(0,ji.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,qt.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?r.entity:null}if(t==="genPage"){let h=await iM(e,(o=r.name)!==null&&o!==void 0?o:"",2);if(h.length>1)throw new nM.AmbiguousArtifactError(t,(a=r.name)!==null&&a!==void 0?a:"",h.length);return h.length===1?h[0].id:null}let d=oae(t,u,c,r),f=t!=="app",m=await(0,ji.queryRecords)(e,d.set,{select:[d.idField],filter:d.filter,top:f?2:1});if(f&&m&&m.length>1)throw new nM.AmbiguousArtifactError(t,(l=(s=r.name)!==null&&s!==void 0?s:r.uniqueName)!==null&&l!==void 0?l:"",m.length);let p=m&&m[0]&&m[0][d.idField];return p!=null?String(p):null}pl.findArtifact=iae;function oae(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,qt.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 sM=v(im=>{"use strict";Object.defineProperty(im,"__esModule",{value:!0});im.seedRecordGraph=void 0;var aM=$d(),aae=bd(),nm=le(),sae=Q();async function lae(e,t,r={}){var n,i,o,a,s;let l=(n=r.createdIds)!==null&&n!==void 0?n:{},u=(i=r.entitySetFor)!==null&&i!==void 0?i:(f=>(0,aae.resolveEntitySetName)(e,f)),c={},d=f=>{var m;return(m=c[f])!==null&&m!==void 0?m:l[f]};for(let f of t){let m=f.entityLogical.toLowerCase(),p=(o=f.matchOn)===null||o===void 0?void 0:o.toLowerCase(),h=[];for(let k of f.records){let I={...k.body};for(let D of(a=k.binds)!==null&&a!==void 0?a:[]){let P=D.parentEntity.toLowerCase(),x=(s=d(P))===null||s===void 0?void 0:s[D.parentIndex];if(!x)throw new sae.InvalidArgumentError(`Cannot resolve bind '${D.navProperty}' on a '${m}' record: parent '${D.parentEntity}'[${D.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let K=(0,nm.assertODataName)(await u(P),`entity set for parent '${D.parentEntity}'`),Oe=(0,nm.normalizeGuid)(x,`parent id for bind '${D.navProperty}'`);I[`${D.navProperty}@odata.bind`]=`/${K}(${Oe})`}h.push(I)}let g=p?h.map(k=>{let I=k[p];return I!=null&&I!==""?String(I):null}):h.map(()=>null),b=new Map;if(p){let k=(0,nm.assertODataName)(p,"RecordGraph matchOn key"),I=[...new Set(g.filter(D=>D!==null))];if(I.length){let D=I.map(x=>`${k} eq '${(0,nm.odataLiteral)(x)}'`).join(" or "),P=await(0,aM.queryRecords)(e,m,{select:[k,`${m}id`],filter:D,top:5e3});for(let x of P??[]){let K=x[k];K!=null&&b.set(String(K).toLowerCase(),String(x[`${m}id`]))}}}let w=[],C=new Map,S=h.map((k,I)=>{let D=g[I];if(D&&b.has(D.toLowerCase()))return null;if(D){let P=D.toLowerCase(),x=C.get(P);if(x!==void 0)return x;let K=w.push(k)-1;return C.set(P,K),K}return w.push(k)-1}),O=w.length?await(0,aM.createRecordsBulk)(e,m,w):[];c[m]=h.map((k,I)=>{let D=g[I];return D&&b.has(D.toLowerCase())?b.get(D.toLowerCase()):O[S[I]]})}return{createdIds:c}}im.seedRecordGraph=lae});var yM=v(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.getEntityPrivileges=tr.addEntityPrivilegesToRole=tr.deleteSecurityRole=tr.createPersonaRole=tr.createSecurityRole=tr.SDK_ROLE_MARKER=void 0;var Mn=ye(),Rt=le(),Kr=Q(),om={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},Xv={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},lM={user:1,businessUnit:2,parentChild:3,organization:4},Qv={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};tr.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function uae(e){return Object.prototype.hasOwnProperty.call(om,e)?om[e]:void 0}function cae(e){return Object.prototype.hasOwnProperty.call(Xv,e)}var uM=new WeakMap,cM=new WeakMap;async function pM(e,t){var r,n;(0,Rt.assertODataName)(t,"entity logical name");let i=uM.get(e);i||(i=new Map,uM.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,Rt.odataPathLiteral)(t)}')${(0,Rt.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,Mn.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[];if(l.length===0)throw new Kr.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function dae(e){var t,r,n;let i=cM.get(e);if(i)return i;let o=`/businessunits${(0,Rt.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,Mn.ensureSuccess)(await e.get(o),e.apiUrl(o)).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 Kr.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,Rt.normalizeGuid)(l,"businessUnitId");return cM.set(e,u),u}async function mM(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new Kr.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let o=(r=i.scope)!==null&&r!==void 0?r:"user";if(!cae(o))throw new Kr.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await pM(e,i.entity);for(let s of i.access){let l=uae(s);if(!l)throw new Kr.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=a.find(p=>p.PrivilegeType===l);if(!u)throw new Kr.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=Qv[o];if(u[c]===!1)throw new Kr.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,Rt.normalizeGuid)(u.PrivilegeId,"PrivilegeId"),f=n.get(d);if(!f){n.set(d,{privilegeName:u.Name,privilegeType:l,scope:o,entities:new Set([i.entity])});continue}if(f.scope===o){f.entities.add(i.entity);continue}if(!(f.entities.size===1&&f.entities.has(i.entity))){let p=[...f.entities].sort().join(", ");throw new Kr.InvalidArgumentError(`Entities '${p}' 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.`)}f.scope=lM[o]>lM[f.scope]?o:f.scope}}return[...n.entries()].map(([i,o])=>({entity:[...o.entities].sort().join(", "),privilegeId:i,privilegeName:o.privilegeName,privilegeType:o.privilegeType,scope:o.scope}))}async function fae(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(a=>({Depth:Xv[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,Mn.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function dM(e,t,r,n,i){var o,a;let s=`/${t}(${r})/${n}${(0,Rt.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((a=(o=(0,Mn.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||o===void 0?void 0:o.value)!==null&&a!==void 0?a:[]).length>0}async function pae(e,t,r){var n,i;let o=[],a=[],s={"@odata.id":e.apiUrl(`/roles(${t})`)};for(let l of(n=r?.teams)!==null&&n!==void 0?n:[]){let u=(0,Rt.normalizeGuid)(l,"teamId");if(!await dM(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,Mn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}for(let l of(i=r?.users)!==null&&i!==void 0?i:[]){let u=(0,Rt.normalizeGuid)(l,"userId");if(!await dM(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,Mn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}return{teams:o,users:a}}async function fM(e,t,r){var n,i;let o=`/roles${(0,Rt.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Rt.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,Mn.ensureSuccess)(await e.get(o),e.apiUrl(o)).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 f;return d.ismanaged!==!0&&((f=d.description)!==null&&f!==void 0?f:"")===tr.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new Kr.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 Kr.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,Rt.normalizeGuid)(c,"roleId"):void 0}function mae(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,Rt.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,Rt.normalizeGuid)(n,"userId"))}}function hM(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function gM(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new Kr.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,Rt.normalizeGuid)(t.businessUnitId,"businessUnitId"):await dae(e),a=await mM(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=mae(t.assignTo),l=await fM(e,i,o),u=l!==void 0;if(!l){let d="/roles",f={name:i,description:tr.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let m=(0,Mn.ensureSuccess)(await e.post(d,f),e.apiUrl(d));l=(0,Rt.normalizeGuid)((0,Mn.requireCreatedId)(m,"roleid","role"),"roleId")}catch(m){let p;try{p=await fM(e,i,o)}catch{p=void 0}if(!p)throw m;l=p}}await fae(e,l,a,u);let c=await pae(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:hM(a),assignedTeams:c.teams,assignedUsers:c.users}}tr.createSecurityRole=gM;async function hae(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new Kr.InvalidArgumentError("createPersonaRole: a non-empty persona name is required.");let o=[...t.jobs.flatMap(a=>{var s;return(s=a.privileges)!==null&&s!==void 0?s:[]}),...(n=t.additionalPrivileges)!==null&&n!==void 0?n:[]];return gM(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}tr.createPersonaRole=hae;async function gae(e,t){let n=`/roles(${(0,Rt.normalizeGuid)(t,"roleId")})`;(0,Mn.ensureSuccess)(await e.delete(n),e.apiUrl(n))}tr.deleteSecurityRole=gae;async function yae(e,t,r){let n=(0,Rt.normalizeGuid)(t,"roleId");if(r.length===0)throw new Kr.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await mM(e,r),o={Privileges:i.map(s=>({Depth:Xv[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,Mn.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),hM(i)}tr.addEntityPrivilegesToRole=yae;var bae=new Map(Object.keys(om).map(e=>[om[e],e]));async function vae(e,t){return(await pM(e,t)).map(n=>{let i=Object.keys(Qv).filter(a=>n[Qv[a]]!==!1),o=bae.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...o?{access:o}:{},scopes:i}})}tr.getEntityPrivileges=vae});var LM=v(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.createMakerSdk=yr.MakerSdk=yr.PUSH_NOT_ATTEMPTED_CODE=yr.ALREADY_EXISTS_CODE=void 0;var bM=Fm(),vM=Qr(),Z=Q(),bn=Ma(),wae=MC(),OM=zC(),ml=QC(),Cae=Um(),Eae=bE(),hl=CE(),Aae=$E(),Sae=qE(),Nae=bA(),wM=mS(),kt=bd(),Zv=_g(),CM=_N(),am=ru(),Hi=$d(),sm=$N(),gl=Fd(),_ae=Ud(),rr=Tg(),Tae=$g(),Dae=zg(),EM=xg(),Iae=VF(),lm=pt(),Oae=Jo(),pi=qb(),vn=Wm(),ew=_v(),Pae=3e5,gr=ye(),La=le(),yl=rM(),AM=oM(),Rae=sM(),kae=nb(),Ac=yM(),PM=Symbol("cds-maker-sdk.committedWrite");function Lae(e){return typeof e=="object"&&e!==null&&(e[PM]=!0),e}function $ae(e){return typeof e=="object"&&e!==null&&e[PM]===!0}var xae={fileConcurrency:1},tw="SOLUTION_COMPONENT_UNCLASSIFIED",Fae=2,Mae=4,Uae="This table is in the solution with ALL its subcomponents. Those are members the solution does not list one by one, so fetchSolution did not enumerate or fetch them: none of its forms, views, charts or dashboards were fetched here. To fetch them, read the table's logical name from its metadata (EntityDefinitions(<componentId>), $select=LogicalName), list each kind with fetchArtifactList \u2014 'form' with formTypes Main, QuickView, QuickCreate and Card; 'view'; 'chart'; 'dashboard' \u2014 passing { entityLogicalName }, and fetch each listed id with fetchArtifact: listing returns ids and names only.";function SM(e){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"unsupported",...e.includesAllSubcomponents?{detail:Uae}:{}}}function NM(e,t){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"failed",error:Ro(t)}}function _M(e,t,r){let n=r;return{type:e,id:t.objectId,name:typeof n.name=="string"?n.name:t.objectId,entityLogicalName:typeof n.entityLogicalName=="string"?n.entityLogicalName:void 0,lastFetched:(0,gr.nowIso)(),isDirty:!1}}var Bae=new Set(["entity","appmodule","dashboard","uxagentproject"]);function qae(e){var t;let r={entity:[],appmodule:[],dashboard:[],uxagentproject:[]},n=new Set,i=(s,l)=>{let u=`${s}\0${l.toLowerCase()}`;n.has(u)||(n.add(u),r[s].push(l))};for(let{scope:s}of e)if(s?.envelope==="entity")s.entityLogicalName&&i("entity",s.entityLogicalName);else if(s&&s.envelope!=="webresource")for(let l of(t=s.targetIds)!==null&&t!==void 0?t:[])i(s.envelope,l);let o=(s,l,u)=>u.length>0?`<${s}>${u.map(c=>`<${l}>${(0,La.xmlText)(c)}</${l}>`).join("")}</${s}>`:"",a=o("entities","entity",r.entity)+o("appmodules","appmodule",r.appmodule)+o("dashboards","dashboard",r.dashboard)+o("uxagentprojects","uxagentproject",r.uxagentproject);return a?`<importexportxml>${a}</importexportxml>`:void 0}function Vae(e){let t=e.workspaceStorage;if(t==null)throw new Error("createMakerSdk requires a workspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'; a host with no filesystem implements WorkspaceStorage directly.");return new OM.WorkspaceManager(Wae,e.instanceUrl,(0,Cae.assertStorageContract)(t))}yr.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var Gae="this build answers a replayed create with HTTP 404, and the unpublished read of an existing row is not authoritative after another writer's save on it, so the row cannot be proven to be what this create wrote";yr.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var Wae="<injected workspaceStorage>",um=class{constructor(t){var r,n;if(this.artifactLocks=new Map,this.observedGenerations=new Map,this.baselineObserved=new Map,this.generationHighWater=new Map,this.entityMetadataLoads=new Map,this.entityMetadataLoadEpochs=new WeakMap,this.schemaWrites=new Map,this.undroppedMetadata=new Set,this.metadataPublications=new Set,t.createRecovery!==void 0&&t.createRecovery!=="adoptExact")throw new Z.InvalidArgumentError(`createRecovery must be 'adoptExact' or omitted (got '${String(t.createRecovery)}').`);this.createRecovery=t.createRecovery,this.readConcurrency=(0,ew.resolveReadConcurrency)(t.readConcurrency),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:Oae.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:Pae,this.compiler={load:(0,Tae.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=Vae(t),this.versions=new ml.VersionManager(this.workspace),this.dataverse=new Eae.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName,this.readConcurrency),this.connectivity=new Nae.ConnectivityRouter(this.dataverse,t.instanceUrl,{powerAppsServiceClient:t.powerAppsServiceClient,powerPlatformApiClient:t.powerPlatformApiClient,connectorRuntimeClient:t.connectorRuntimeClient}),this.registrations=(0,Iae.buildRegistrations)(this.languageCode)}async initWorkspace(){await this.workspace.init()}async getManifest(){return this.workspace.getManifest()}async cleanWorkspace(){await this.workspace.clean()}withArtifactLock(t,r,n){var i;let o=this.artifactKey(t,r),s=((i=this.artifactLocks.get(o))!==null&&i!==void 0?i:Promise.resolve()).then(n,n),l=s.then(()=>{},()=>{});return this.artifactLocks.set(o,l),l.then(()=>{this.artifactLocks.get(o)===l&&this.artifactLocks.delete(o)}),s}async fetchArtifact(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.fetchArtifactUnlocked(t,r,n);return await this.acknowledgeRefresh(t,r),i})}async fetchArtifactUnlocked(t,r,n){let i=this.requireRegistration(t,"fetchArtifact"),o=await i.api.get(this.dataverse,r);return this.applyFetchedArtifactUnlocked(t,r,i,o,n)}async applyFetchedArtifactUnlocked(t,r,n,i,o){var a,s,l;let{raw:u,etag:c,memberEtags:d,siblingEtags:f}=i,m=n.adapter.fromApiResponse(u);if(!o?.overwrite&&await this.versions.isDirty(t,r)){let h=(s=(a=await this.versions.getMeta(t,r))===null||a===void 0?void 0:a.etag)!==null&&s!==void 0?s:null;if(h&&c&&h!==c)throw new Z.LocalEditsWouldBeLostError(t,r,h,c);let g=await this.workspace.readArtifact(t,r);if(g){let b=await this.versions.getMeta(t,r);if(b&&!b.etag&&c){if(!(0,vn.deepEqual)(b.snapshot,m))throw new Z.LocalEditsWouldBeLostError(t,r,h,c);await this.versions.storeMeta(t,r,{...b,etag:c,fetchedAt:(0,gr.nowIso)()},b)}return(0,pi.cloneJson)(g)}}await this.workspace.writeArtifact(t,r,m);let p=await this.versions.getMeta(t,r);return await this.versions.storeMeta(t,r,{etag:c,languageCode:this.languageCode,projectionVersion:ml.PROJECTION_VERSION,fetchedAt:(0,gr.nowIso)(),snapshot:(0,pi.cloneJson)(m),...d?{memberEtags:d}:{},...f?{siblingEtags:f}:{},...p?.refreshGeneration?{refreshGeneration:p.refreshGeneration,observedGeneration:(l=p.observedGeneration)!==null&&l!==void 0?l:0}:{}},p),(0,pi.cloneJson)(m)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){await this.workspace.ensureReady();let r=await(0,rr.fetchSolutionComponents)(this.dataverse,t),n=[],i=[];if(this.readConcurrency>1)await this.fetchComponentsOverlapped(r,n,i);else for(let o of r)try{let a=await this.resolveComponentType(o);if(!a){i.push(SM(o));continue}let s=await this.fetchArtifact(a,o.objectId);n.push(_M(a,o,s))}catch(a){i.push(NM(o,a))}return await this.workspace.updateManifest({lastSyncAt:(0,gr.nowIso)()}),{summaries:n,skipped:i}}async fetchComponentsOverlapped(t,r,n){await(0,ew.readEveryInOrder)(t,this.readConcurrency,i=>this.beginComponentRead(i),async(i,o)=>{try{if(!i.ok)throw i.error;let a=i.value;if(a.kind==="unsupported"){n.push(SM(o));return}let s=await this.applyFetchedArtifactUnlocked(a.type,o.objectId,a.reg,a.fetched);await this.acknowledgeRefresh(a.type,o.objectId),r.push(_M(a.type,o,s))}catch(a){n.push(NM(o,a))}})}async beginComponentRead(t){let r=await this.resolveComponentType(t);return r?this.lockedRead(r,t.objectId,async()=>{let n=this.requireRegistration(r,"fetchArtifact"),i=await n.api.get(this.dataverse,t.objectId,xae);return{kind:"artifact",type:r,reg:n,fetched:i}}):(0,ew.plainRead)(async()=>({kind:"unsupported"}))}lockedRead(t,r,n){let i,o=new Promise(u=>{i=u}),a,s=new Promise(u=>{a=u}),l=this.withArtifactLock(t,r,async()=>{try{i({ok:!0,value:await n()})}catch(c){i({ok:!1,error:c})}let u=await s;await u?.()});return{outcome:o,finish:u=>(a(u),l),discard:async()=>{a(void 0),await l}}}async fetchEntityMetadata(t){let r=t.toLowerCase(),n=this.schemaEpoch(r),i=await(0,hl.fetchEntityMetadataFromApi)(this.dataverse,t);if(this.schemaEpoch(r)!==n)return i;let o=this.workspace.writeEntityMetadata(t,i),a={key:r,settled:o.then(()=>{},()=>{})};this.metadataPublications.add(a);try{await o}finally{this.metadataPublications.delete(a)}return this.schemaEpoch(r)===n&&this.undroppedMetadata.delete(r),i}schemaEpoch(t){var r,n;return`${(r=this.schemaWrites.get("*"))!==null&&r!==void 0?r:0}:${(n=this.schemaWrites.get(t.toLowerCase()))!==null&&n!==void 0?n:0}`}async schemaWrite(t,r){try{return await r()}finally{await this.forgetEntityMetadata(t)}}async forgetEntityMetadata(t){let r=i=>{var o;this.schemaWrites.set(i,((o=this.schemaWrites.get(i))!==null&&o!==void 0?o:0)+1)};if(t===void 0){r("*"),await this.publicationsSettled(void 0),await this.dropCachedMetadata(void 0);return}let n=[...new Set(t.filter(i=>typeof i=="string"&&i!=="").map(i=>i.toLowerCase()))];n.forEach(r),await this.publicationsSettled(n);for(let i of n)await this.dropCachedMetadata(i)}async publicationsSettled(t){let r=t===void 0?void 0:new Set(t);await Promise.all([...this.metadataPublications].filter(n=>r===void 0||r.has(n.key)).map(n=>n.settled))}async dropCachedMetadata(t){try{await this.workspace.dropEntityMetadata(t)}catch(r){r instanceof Z.WorkspaceNotInitializedError||r instanceof Z.WorkspaceOrgMismatchError||this.undroppedMetadata.add(t??"*");return}t===void 0?this.undroppedMetadata.clear():this.undroppedMetadata.delete(t)}async readCachedEntityMetadata(t){let r=t.toLowerCase();return this.undroppedMetadata.has("*")&&await this.dropCachedMetadata(void 0),this.undroppedMetadata.has(r)&&await this.dropCachedMetadata(r),this.undroppedMetadata.has("*")||this.undroppedMetadata.has(r)?null:this.workspace.readEntityMetadata(t)}loadMissedEntityMetadata(t){let r=this.schemaEpoch(t),n=this.entityMetadataLoads.get(t);if(n&&this.entityMetadataLoadEpochs.get(n)===r)return n;let i=this.fetchEntityMetadata(t).then(()=>{});this.entityMetadataLoads.set(t,i),this.entityMetadataLoadEpochs.set(i,r);let o=()=>{this.entityMetadataLoads.get(t)===i&&this.entityMetadataLoads.delete(t)};return i.then(o,o),i}generateGenPageRuntimeTypes(t,r){return(0,Aae.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,hl.findTables)(this.dataverse,t,r)}getEnvironmentLanguages(){return(0,Sae.getEnvironmentLanguages)(this.dataverse)}listConnections(){return this.connectivity.listConnections()}listConnectorOperations(t){return this.connectivity.listConnectorOperations(t)}getConnectorOperationSchema(t,r){return this.connectivity.getConnectorOperationSchema(t,r)}listConnectorTables(t,r,n){return this.connectivity.listConnectorTables(t,r,n)}getConnectorTableSchema(t,r,n,i){return this.connectivity.getConnectorTableSchema(t,r,n,i)}findColumns(t,r,n){return(0,hl.findColumns)(this.dataverse,t,r,n)}createTable(t){return this.schemaWrite([t.schemaName],()=>(0,kt.createTable)(this.dataverse,t))}createColumn(t,r){return this.schemaWrite([t],()=>(0,kt.createColumn)(this.dataverse,t,r))}createColumns(t,r){return this.schemaWrite([t],()=>(0,kt.createColumns)(this.dataverse,t,r))}updateColumn(t,r,n){return this.schemaWrite([t],()=>(0,kt.updateColumn)(this.dataverse,t,r,n))}deleteColumn(t,r){return this.schemaWrite([t],()=>(0,kt.deleteColumn)(this.dataverse,t,r))}setFormSecurityRoles(t,r){return(0,Zv.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,Zv.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,kt.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,kt.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return this.schemaWrite([t,"account","contact"],()=>(0,kt.createCustomerColumn)(this.dataverse,t,r))}insertStatusValue(t,r){return this.schemaWrite([t],()=>(0,kt.insertStatusValue)(this.dataverse,t,r))}updateTable(t,r){return this.schemaWrite([t],()=>(0,kt.updateTable)(this.dataverse,t,r))}async setEntityIcon(t,r){if(await this.schemaWrite([t],()=>(0,kt.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,La.xmlText)(t)}</entity></entities></importexportxml>`;(0,gr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,kt.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,kt.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){let r=t.type==="ManyToMany"?[t.entity1,t.entity2]:[t.referencedEntity,t.referencingEntity];return this.schemaWrite(r,()=>(0,kt.createRelationship)(this.dataverse,t))}deleteRelationship(t){return this.schemaWrite(void 0,()=>(0,kt.deleteRelationship)(this.dataverse,t))}createGlobalOptionSet(t){return(0,kt.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,kt.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return this.schemaWrite(void 0,()=>(0,kt.deleteTable)(this.dataverse,t))}createSecurityRole(t){return(0,Ac.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,Ac.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,Ac.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,Ac.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,Ac.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,Hi.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,Hi.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,Hi.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,Hi.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,Hi.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,Hi.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,Hi.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,Rae.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,AM.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,AM.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){await this.workspace.ensureReady();let n=await(0,Dae.deleteAppCascade)(this.dataverse,t,r),i=(0,La.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,Hi.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,Hi.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,sm.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,sm.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,sm.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,sm.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,gl.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,gl.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new Z.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:_ae.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,gl.setAppSetting)(this.dataverse,t,gl.HEADER_AND_NAVIGATION_REFRESH,r?gl.APP_SETTING_ON:gl.APP_SETTING_OFF)}getSolution(t){return(0,rr.getSolution)(this.dataverse,t)}createPublisher(t){return(0,rr.createPublisher)(this.dataverse,t)}createSolution(t){return(0,rr.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,rr.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,rr.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,rr.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,rr.exportSolution)(this.dataverse,t)}importSolution(t){return this.schemaWrite(void 0,()=>(0,rr.importSolution)(this.dataverse,t))}getDeploymentSettingsTemplate(t){return(0,rr.getDeploymentSettingsTemplate)(this.dataverse,t)}deleteSolution(t){return this.schemaWrite(void 0,()=>(0,rr.deleteSolution)(this.dataverse,t))}async getArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let{artifact:n,meta:i}=await this.readWhole(t,r);return await this.acknowledgeRefresh(t,r,i),n})}async getArtifactUnlocked(t,r){return this.readRaw(t,r)}async readWhole(t,r){let{meta:n}=await this.revalidate(t,r);return{artifact:await this.readLocal(t,r),meta:n}}async acknowledgeRefresh(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=n===void 0?await this.versions.getMeta(t,r):n;this.baselineObserved.has(s)||this.baselineObserved.set(s,(i=l?.observedGeneration)!==null&&i!==void 0?i:0);let u=(o=l?.refreshGeneration)!==null&&o!==void 0?o:0;this.raiseGenerationHighWater(s,u),l&&u!==((a=l.observedGeneration)!==null&&a!==void 0?a:0)&&await this.versions.storeMeta(t,r,{...l,observedGeneration:u},l),this.observedGenerations.set(s,u)}raiseGenerationHighWater(t,r){var n;r>((n=this.generationHighWater.get(t))!==null&&n!==void 0?n:0)&&this.generationHighWater.set(t,r)}async observedAtInvocation(t,r,n){var i,o;if(n!==void 0)return n;let a=this.baselineObserved.get(this.artifactKey(t,r));return a!==void 0?a:(o=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.observedGeneration)!==null&&o!==void 0?o:0}artifactKey(t,r){return`${t}\0${(0,OM.canonicalArtifactId)(r)}`}nextRefreshGeneration(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=Math.max((i=n?.refreshGeneration)!==null&&i!==void 0?i:0,(o=n?.observedGeneration)!==null&&o!==void 0?o:0,(a=this.generationHighWater.get(s))!==null&&a!==void 0?a:0)+1;return this.raiseGenerationHighWater(s,l),l}async readRaw(t,r){return await this.revalidateIfStale(t,r),this.readLocal(t,r)}async readForMutation(t,r,n,i){var o,a;let s=await this.observedAtInvocation(t,r,i);if(((a=(o=await this.versions.getMeta(t,r))===null||o===void 0?void 0:o.refreshGeneration)!==null&&a!==void 0?a:0)>s)throw new Z.StaleArtifactError(t,r,n,"pushed");if(await this.revalidateIfStale(t,r)==="refreshed-changed")throw new Z.StaleArtifactError(t,r,n);return this.readLocal(t,r)}async readLocal(t,r){let n=await this.workspace.readArtifact(t,r);if(!n)throw new Z.ArtifactNotFoundError(t,r);return n}async revalidateIfStale(t,r){return(await this.revalidate(t,r)).outcome}async revalidate(t,r){let n=await this.versions.getMeta(t,r);if(!n)return{outcome:"skipped",meta:null};let i=n.fetchedAt?Date.parse(n.fetchedAt):NaN,o=Date.now()-i;if(!Number.isNaN(i)&&this.cacheStalenessMs>0&&o<=this.cacheStalenessMs)return{outcome:"fresh",meta:n};if(await this.versions.isDirty(t,r,n))return{outcome:"skipped",meta:n};let a=await this.workspace.readArtifact(t,r);await this.fetchArtifactUnlocked(t,r);let s=await this.workspace.readArtifact(t,r);return{outcome:(0,vn.deepEqual)(a,s)?"refreshed-unchanged":"refreshed-changed"}}async queryTree(t,r,n){return this.withArtifactLock(t,r,async()=>{let{artifact:i,meta:o}=await this.readWhole(t,r),a=bn.JsonPointer.resolve(i,n);if(a===void 0)throw new Z.PathNotFoundError(t,r,n);return n===""&&await this.acknowledgeRefresh(t,r,o),a})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,wae.findElements)(await this.getArtifactUnlocked(t,r),n))}async withDirtyFlags(t){let r=[];for(let n of t)r.push({...n,isDirty:await this.versions.isDirty(n.type,n.id)});return r}async listArtifacts(t,r){return this.withDirtyFlags(await this.workspace.listArtifacts(t,r))}async getEntityMetadata(t){let r=await this.readCachedEntityMetadata(t);if(!r)throw new Z.ArtifactNotFoundError("entityMetadata",t);return r}async getFieldMetadata(t,r){let i=(await this.getEntityMetadata(t)).attributes.find(o=>o.logicalName===r);if(!i)throw new Z.PathNotFoundError("entityMetadata",t,r);return i}async updateElement(t,r,n,i){let o=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let a=await this.readForMutation(t,r,n,o),s=bn.JsonPointer.resolve(a,n);if(s===void 0)throw new Z.PathNotFoundError(t,r,n);let l=Ki(s)&&Ki(i)?{...s,...i}:i;return bn.JsonPointer.set(a,n,(0,pi.cloneJson)(l)),this.assertStructurallyValid(t,r,a,n),await this.workspace.writeArtifact(t,r,a),this.getArtifactUnlocked(t,r)})}async addElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let s=await this.readForMutation(t,r,n,a),l=bn.JsonPointer.resolve(s,n);if(l===void 0)throw new Z.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!Ki(l)||!Ki(i))throw new Z.ValidationError(t,r,n,"parent must be an array, or an object with an object of properties to add");if(o?.position!==void 0)throw new Z.ValidationError(t,r,n,"position is not supported for an object parent");let d={};for(let f of Object.keys(i)){if(f==="id")throw new Z.ValidationError(t,r,n,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let m=(0,pi.cloneJson)(i[f]),p=(0,lm.isValueMapKey)(f)||(0,lm.pointerTouchesValueMap)(n);d[f]=p?m:Array.isArray(m)?m.map(h=>Ki(h)?this.assignMissingIds(t,h):h):Ki(m)?this.assignMissingIds(t,m):m}for(let f of Object.keys(d))bn.JsonPointer.set(s,bn.JsonPointer.append(n,f),d[f]);return this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)}let u=(0,lm.pointerTouchesValueMap)(n)?(0,pi.cloneJson)(i):this.assignMissingIds(t,(0,pi.cloneJson)(i)),c=Kae(l,o?.position);return l.splice(c,0,u),this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)})}async moveElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{var s;let l=await this.readForMutation(t,r,n,a),u=bn.JsonPointer.resolve(l,n);if(u===void 0)throw new Z.PathNotFoundError(t,r,n);let c=bn.JsonPointer.resolve(l,i);if(c===void 0)throw new Z.PathNotFoundError(t,r,i);if(!Array.isArray(c))throw new Z.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new Z.ValidationError(t,r,i,"cannot move an element into its own subtree");bn.JsonPointer.remove(l,n);let d=(s=o?.index)!==null&&s!==void 0?s:c.length;c.splice(Math.max(0,Math.min(d,c.length)),0,u),IM(c);let f=bn.JsonPointer.resolve(l,DM(n));return Array.isArray(f)&&f!==c&&IM(f),this.assertStructurallyValid(t,r,l,i),await this.workspace.writeArtifact(t,r,l),this.getArtifactUnlocked(t,r)})}async removeElement(t,r,n){let i=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let o=await this.readForMutation(t,r,n,i);if(bn.JsonPointer.resolve(o,n)===void 0)throw new Z.PathNotFoundError(t,r,n);return bn.JsonPointer.remove(o,n),this.assertStructurallyValid(t,r,o,DM(n)),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)})}assertStructurallyValid(t,r,n,i){var o,a,s;let l=this.registrations.get(t),u=(s=(a=l==null?void 0:(o=l.adapter).validate)===null||a===void 0?void 0:a.call(o,n,i))!==null&&s!==void 0?s:[];if(u.length>0)throw new Z.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,yl.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,yl.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,yl.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,yl.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,yl.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,yl.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,kae.findDefaultViews)(this.dataverse,t,{excludeViewIds:n.excludeViewIds}),o=n.publish===!1,a=[],s=[],l=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,vM.boundEntityPublishScope)({entityLogicalName:t}),artifacts:a.map(c=>({type:"view",id:c}))}]:[]}),u;try{for(let c of i){await this.fetchArtifact("view",c.id),await this.updateElement("view",c.id,"/columns",r),u=c.id;let d=await this.pushArtifact("view",c.id);u=void 0,s.push(d),d.saved&&a.push(c.id)}}catch(c){throw u&&$ae(c)&&a.push(u),o?(0,Z.withPartialEnrichment)(c,l()):c}if(o)return l();if(a.length){let c=await this.publishArtifact("view",a[0]);if(c.publish.kind==="failed")throw new Z.SdkError("ENRICH_DEFAULT_VIEWS_PUBLISH_FAILED",`enrichDefaultViews: ${a.length} view(s) on '${t}' were saved but the publish FAILED, so none of them is live (${c.publish.error.message}). Re-publish the entity to make them visible; the saves themselves are unaffected.`)}return{updated:a}}async createArtifact(t,r){let n=this.requireRegistration(t,"createArtifact"),i=n.adapter.assignMissingIds(n.adapter.createDefault(r)),o=i.id;if(!o)throw new Z.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,o,async()=>(await this.workspace.writeArtifact(t,o,i),(0,pi.cloneJson)(i)))}async deleteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.workspace.deleteArtifact(t,r)})}async deleteRemoteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let n=this.requireRegistration(t,"deleteRemoteArtifact");await this.workspace.ensureReady(),await n.api.delete(this.dataverse,r),await this.workspace.readArtifact(t,r)&&await this.workspace.deleteArtifact(t,r)})}async publishArtifact(t,r,n){let{result:i,siblings:o}=await this.withArtifactLock(t,r,()=>this.publishArtifactUnlocked(t,r,n));for(let a of o)await this.withArtifactLock(a.type,a.id,()=>this.adoptBracket(a));return i}async publishArtifacts(t,r){var n,i;let o=new Map;for(let p of t){let h=this.artifactKey(p.type,p.id);o.has(h)||o.set(h,{type:p.type,id:p.id})}let a=[];for(let[p,h]of o)a.push(await this.withArtifactLock(h.type,h.id,()=>this.preparePublish(p,h.type,h.id)));let s=new Set(o.keys()),l=[],u=new Set;for(let p of a){let h=((n=p.scope)===null||n===void 0?void 0:n.envelope)==="entity"?(i=p.scope.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;p.scope&&h&&!u.has(h)&&(u.add(h),l.push(p.scope))}let c=await this.captureSiblings(l,s),d=qae(a),f;if(d)try{await(0,vM.publishXml)(this.dataverse,d)}catch(p){f=Ro(p)}let m=new Map;for(let p of a)m.set(p.key,await this.withArtifactLock(p.type,p.id,()=>this.settlePublish(p,f,r)));for(let p of c)await this.withArtifactLock(p.type,p.id,()=>this.adoptBracket(p));return t.map(p=>({...m.get(this.artifactKey(p.type,p.id))}))}async preparePublish(t,r,n){var i;let o=await this.readRaw(r,n),a=this.registrations.get(r);if(!a?.publish)return{key:t,type:r,id:n,artifact:o,notApplicable:!0};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,n,o);if(!s||!Bae.has(s.envelope))throw new Z.InvalidArgumentError(`publishArtifacts: ${r} '${n}' publishes through ${s?`a '${s.envelope}'`:"no declared"} scope, which one PublishXml envelope cannot carry. Publish it with publishArtifact.`);let l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,r,n):void 0;return{key:t,type:r,id:n,artifact:o,reg:a,scope:s,...l?{own:l}:{}}}async settlePublish(t,r,n){let{type:i,id:o}=t;if(t.notApplicable||!t.reg)return{type:i,id:o,shipped:!1,publish:{kind:"notApplicable"}};let a=t.scope?{publishScope:t.scope}:{};if(t.reg.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(t.reg,i,o),t.own&&await this.adoptBracket(t.own),r)return{type:i,id:o,shipped:!1,publish:{kind:"failed",error:r},...a};if(!n?.verify)return{type:i,id:o,shipped:!1,publish:{kind:"submitted"},...a};let s=await this.workspace.readArtifact(i,o).catch(()=>null);if(!s||!(0,vn.deepEqual)(s,t.artifact))return{type:i,id:o,shipped:!1,publish:{kind:"unverifiable",reason:`the local ${i} was ${s?"edited":"deleted"} while the publish was in flight, so what shipped cannot be told from what is local now; verify it with publishArtifact`},...a};let l=await this.verifyPublished(i,o,t.artifact);return{type:i,id:o,shipped:l.kind==="verified",publish:l,...a}}async publishArtifactUnlocked(t,r,n){var i;let o=await this.readRaw(t,r),a=this.registrations.get(t);if(!a?.publish)return{result:{type:t,id:r,shipped:!1,publish:{kind:"notApplicable"}},siblings:[]};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,r,o),l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,t,r):void 0,u=s?await this.captureSiblings([s],new Set([this.artifactKey(t,r)])):[];try{await a.publish(this.dataverse,r,o)}catch(d){return{result:{type:t,id:r,shipped:!1,publish:{kind:"failed",error:Ro(d)},...s?{publishScope:s}:{}},siblings:[]}}if(a.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(a,t,r),l&&await this.adoptBracket(l),!n?.verify)return{result:{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}},siblings:u};let c=await this.verifyPublished(t,r,o);return{result:{type:t,id:r,shipped:c.kind==="verified",publish:c,...s?{publishScope:s}:{}},siblings:u}}async captureBracket(t,r,n){try{let i=await this.versions.getMeta(r,n),o=i?.etag;if(!(0,gr.isVersionToken)(o)||!t.api.readContentThenToken)return;let{raw:a,etag:s,siblingEtags:l}=await t.api.readContentThenToken(this.dataverse,n),u=i?.siblingEtags;return s!==o||!jae(u,l)?void 0:{type:r,id:n,reg:t,heldEtag:o,...u?{heldSiblings:u}:{},content:this.bracketContent(t,a)}}catch{return}}async captureSiblings(t,r){var n,i,o;let a=new Map;for(let u of t){let c=u.envelope==="entity"?(n=u.entityLogicalName)===null||n===void 0?void 0:n.toLowerCase():void 0;c&&!a.has(c)&&a.set(c,[])}if(a.size===0)return[];let s;try{s=await this.workspace.listArtifacts()}catch{return[]}for(let u of s){let c=this.registrations.get(u.type);if(!(r.has(this.artifactKey(u.type,u.id))||c?.rebaselineAfterPublish!=="bracket"||!c.publishScope))try{let d=await this.workspace.readArtifact(u.type,u.id),f=d?c.publishScope(u.id,d):void 0,m=f?.envelope==="entity"?(i=f.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;m!==void 0&&((o=a.get(m))===null||o===void 0||o.push(u))}catch{continue}}let l=[];for(let u of a.values())for(let c of u){let d=this.registrations.get(c.type),f=d?await this.captureBracket(d,c.type,c.id):void 0;f&&l.push(f)}return l}async adoptBracket(t){var r;try{let n=await this.versions.getMeta(t.type,t.id);if(!n||n.etag!==t.heldEtag||!(0,vn.deepEqual)((r=n.siblingEtags)!==null&&r!==void 0?r:void 0,t.heldSiblings))return;let{raw:i,etag:o,siblingEtags:a}=await t.reg.api.get(this.dataverse,t.id);if(!(0,gr.isVersionToken)(o)||!RM(a,t.heldSiblings)||!kM(a)||!(o!==t.heldEtag||!(0,vn.deepEqual)(a??void 0,t.heldSiblings))||!(0,vn.deepEqual)(this.bracketContent(t.reg,i),t.content))return;await this.versions.storeMeta(t.type,t.id,{...n,etag:o,...t.heldSiblings?{siblingEtags:{...a}}:{},fetchedAt:(0,gr.nowIso)()},n)}catch{}}bracketContent(t,r){var n,i,o;let a=t.adapter.fromApiResponse(r);return(o=(i=(n=t.adapter).baselineContent)===null||i===void 0?void 0:i.call(n,a))!==null&&o!==void 0?o:a}adoptReadBack(t,r){try{return{artifact:t.adapter.fromApiResponse(r)}}catch(n){return{warning:`The write was saved, but the record read back after it could not be read into the local copy (${Ro(n).message}). The SDK holds no version for it now, so the next push is refused: re-fetch before editing again.`}}}adoptedAsSent(t,r,n,i){try{let o={...n,...i},a=t.adapter.fromApiResponse(t.adapter.completeAsStored?t.adapter.completeAsStored(o,n):o);return(0,vn.deepEqual)(r,a)}catch{return!1}}async rebaselineAfterPublish(t,r,n){try{let i=await this.versions.getMeta(r,n);if(!i)return;let{raw:o,etag:a,memberEtags:s,siblingEtags:l}=t.api.getForRebaseline?await t.api.getForRebaseline(this.dataverse,n):await t.api.get(this.dataverse,n),u=t.adapter.fromApiResponse(o),c=d=>{var f,m,p;return(p=(m=(f=t.adapter).baselineContent)===null||m===void 0?void 0:m.call(f,d))!==null&&p!==void 0?p:d};if(!a||!(0,vn.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:a,fetchedAt:(0,gr.nowIso)(),...s?{memberEtags:s}:{},...l?{siblingEtags:l}:{}},i)}catch{}}async verifyPublished(t,r,n){var i;if(t!=="app"){let o=this.registrations.get(t);return o?.api.getPublished?this.verifyPublishedContent(o,t,r,n):{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`}}try{let o=`/appmodules(${(0,La.normalizeGuid)(r,"id")})${(0,La.odataQuery)([["$select","appmoduleid,name,description"]])}`,a=await this.dataverse.get(o);if(a.status>=200&&a.status<300){let s=(i=a.body)!==null&&i!==void 0?i:{},l=n;if(!l)return{kind:"unverifiable",reason:"there is no local copy of the app to compare the published projection with"};let u=["name","description"].filter(d=>l[d]!==void 0);if(u.length===0)return{kind:"unverifiable",reason:"the local copy of the app holds neither a name nor a description to compare the published projection with, and its presence alone proves nothing for a re-publish"};let c=u.filter(d=>{var f,m;return((f=l[d])!==null&&f!==void 0?f:"")!==((m=s[d])!==null&&m!==void 0?m:"")});return c.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${c.join(", ")} still differ). PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}:{kind:"verified"}}return{kind:"unverifiable",reason:`the published projection answered HTTP ${a.status}`}}catch(o){return{kind:"unverifiable",reason:Ro(o).message}}}async verifyPublishedContent(t,r,n,i){var o,a,s;try{let l=f=>{var m,p,h;return(h=(p=(m=t.adapter).baselineContent)===null||p===void 0?void 0:p.call(m,f))!==null&&h!==void 0?h:f},u=l(i),c=(o=await this.versions.getMeta(r,n))===null||o===void 0?void 0:o.snapshot;if(c===void 0||!(0,vn.deepEqual)(u,l(c)))return{kind:"unverifiable",reason:`the local ${r} holds edits that were never pushed, so no publish could have shipped them \u2014 push, then publish again`};let d=await((s=(a=t.api).getPublished)===null||s===void 0?void 0:s.call(a,this.dataverse,n));return d?(0,vn.deepEqual)(u,l(t.adapter.fromApiResponse(d.raw)))?{kind:"verified"}:{kind:"unverifiable",reason:"the published projection does not show what was pushed. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists"}:{kind:"unverifiable",reason:`the ${r} is not in the published projection yet. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}}catch(l){return{kind:"unverifiable",reason:Ro(l).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async prepareArtifactUnlocked(t,r,n){var i,o;let a=this.requireRegistration(t,"pushArtifact"),s=await this.workspace.readArtifactWithText(t,r);if(!s)throw new Z.ArtifactNotFoundError(t,r);let l=s.artifact,u=s.text,c=(o=(i=a.adapter).normalize)===null||o===void 0?void 0:o.call(i,l);c&&c!==l&&(await this.workspace.writeArtifact(t,r,c),l=c,u=void 0);let d=await this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,d,a),this.assertProjectionMatches(t,r,d);let f=await this.buildMetadataContext(a.adapter,l,d?.snapshot),m=await a.adapter.toApiPayload(l,d?.snapshot,f);return await this.assertSemanticallyComplete(a,t,r,l,d===null,d?.everActivated,n),{type:t,id:r,reg:a,json:l,...u!==void 0?{storedText:u}:{},meta:d,payload:m}}async assertSemanticallyComplete(t,r,n,i,o,a,s){let l=t.adapter.issuesBlockingPush;if(!l)return;let u=i.entityLogicalName,d=(u?await this.columnsForCheck(t,u,i,s):[]).map(m=>({logicalName:m.logicalName,displayName:m.displayName,attributeType:m.attributeType,isCustomAttribute:m.isCustomAttribute,...m.maxLength!==void 0?{maxLength:m.maxLength}:{},...m.options?{options:m.options.map(p=>({value:p.value,label:p.label}))}:{},...m.targets?{targets:m.targets}:{}})),f=l.call(t.adapter,i,d,{isCreate:o,everActivated:a});if(f.length>0)throw new Z.ValidationError(r,n,f)}columnsForCheck(t,r,n,i){var o,a,s;let l=(s=(a=(o=t.adapter).columnsCheckedAtPush)===null||a===void 0?void 0:a.call(o,n))!==null&&s!==void 0?s:[],u=async()=>{let f=await this.readCachedEntityMetadata(r);if(f)return f.attributes;try{return await(0,hl.readCheckColumns)(this.dataverse,r,l)}catch{return[]}};if(!i)return u();let c=[r,...[...new Set(l)].sort()].join("\0"),d=i.get(c);return d||(d=u(),i.set(c,d)),d}async pushArtifactUnlocked(t,r,n){return this.executePrepared(await this.prepareArtifactUnlocked(t,r,n))}async executePrepared(t){var r,n,i,o,a,s,l,u,c;let{type:d,id:f,reg:m,json:p,meta:h,payload:g}=t,b=!1;try{let w;if(h)w=await m.api.update(this.dataverse,f,g,h.etag,h.memberEtags,h.siblingEtags);else{let P=await this.createWithMintedId(m,d,f,g,p);if("adopted"in P)return await this.persistAdoption(d,f,p,P.adopted);w=P.written}b=!0;let C=f;h||(w.serverIdentity&&m.adapter.applyServerIdentity&&m.adapter.applyServerIdentity(p,w.serverIdentity),w.id&&w.id!==f&&(p.id=w.id,await this.workspace.deleteArtifact(d,f),C=w.id));let S=h&&w.readBack!==void 0?this.adoptReadBack(m,w.readBack):void 0,O=S?.artifact?{artifact:S.artifact,baseline:S.artifact}:m.adapter.committed?m.adapter.committed(p,g,{intentPending:w.intentPending===!0}):{artifact:p,baseline:p};await this.workspace.writeArtifact(d,C,O.artifact,h&&C===f?t.storedText:void 0);let k=S?.artifact!==void 0&&!(0,vn.deepEqual)(S.artifact,p),I=k?this.nextRefreshGeneration(d,C,h):(r=h?.refreshGeneration)!==null&&r!==void 0?r:0,D=[...(n=w.warnings)!==null&&n!==void 0?n:[],...S?.warning?[S.warning]:[],...S?.artifact!==void 0&&!this.adoptedAsSent(m,S.artifact,w.readBack,g)?[`Saved, but the server holds something other than what was pushed (another writer saved in between, or the platform rewrote something the SDK does not model \u2014 a label in a language the org does not provision, a hand-written fragment); the local ${d} now holds the server's version. Read it (getArtifact) before the next edit: a mutation whose pointer was derived from the earlier copy is refused (StaleArtifactError).`]:[]];return await this.versions.storeMeta(d,C,{etag:S&&!S.artifact?null:w.etag,...I>0?{refreshGeneration:I,observedGeneration:(i=h?.observedGeneration)!==null&&i!==void 0?i:0}:{},languageCode:this.languageCode,projectionVersion:ml.PROJECTION_VERSION,fetchedAt:(0,gr.nowIso)(),snapshot:(0,pi.cloneJson)(O.baseline),...w.memberEtags?{memberEtags:w.memberEtags}:{},...w.siblingEtags?{siblingEtags:w.siblingEtags}:{}},C===f?h:void 0),{type:d,id:C,saved:!0,shipped:!1,publish:(o=w.publish)!==null&&o!==void 0?o:{kind:"notRequested"},...w.publish&&w.publish.kind!=="notRequested"?(()=>{var P;let x=(P=m.publishScope)===null||P===void 0?void 0:P.call(m,C,p);return x?{publishScope:x}:{}})():{},...k?{refreshed:!0}:{},...D.length>0?{warnings:D}:{}}}catch(w){let C=(0,Z.readPartialTokens)(w);if(C&&h){let S={...(a=h.memberEtags)!==null&&a!==void 0?a:{},...(s=C.memberEtags)!==null&&s!==void 0?s:{}},O={...(l=h.siblingEtags)!==null&&l!==void 0?l:{},...(u=C.siblingEtags)!==null&&u!==void 0?u:{}};await this.versions.storeMeta(d,f,{...h,...Object.keys(S).length>0?{memberEtags:S}:{},...Object.keys(O).length>0?{siblingEtags:O}:{}},h)}if(w instanceof Z.SdkError&&w.code===yr.ALREADY_EXISTS_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===bM.WFOM_API_UNAVAILABLE_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===bM.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===gr.VERSION_CONFLICT_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,EM.isFailureAfterPrimaryWrite)(w)?w:new Z.VersionConflictError(d,f,(c=h?.etag)!==null&&c!==void 0?c:null,null,w.message)};throw b?Lae(w):w}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new Z.SdkError("ARTIFACT_LANGUAGE_MISMATCH",`Refusing to push ${t} '${r}': it was fetched with languageCode ${n.languageCode} but this SDK is configured with ${this.languageCode}. Pushing would rewrite labels read in one language as labels in another. Re-fetch with languageCode ${this.languageCode}, or create the SDK with languageCode ${n.languageCode}.`)}assertProjectionMatches(t,r,n){var i;if(n&&n.projectionVersion!==ml.PROJECTION_VERSION)throw new Z.SdkError("ARTIFACT_PROJECTION_STALE",`Refusing to push ${t} '${r}': its workspace copy was produced by projection version ${(i=n.projectionVersion)!==null&&i!==void 0?i:"unknown (pre-versioning)"}, but this SDK produces version ${ml.PROJECTION_VERSION}. The parsers changed in between, so an unedited part of this artifact can no longer be told apart from an edited one and pushing could overwrite server content the caller never touched. Re-fetch it with fetchArtifact('${t}', '${r}') and re-apply any local edits.`)}async createWithMintedId(t,r,n,i,o){try{return{written:await t.api.create(this.dataverse,i,n)}}catch(a){let s=r==="form"?(0,Zv.readPrimaryCreateRefusal)(a):void 0;if(s?.status===404&&await(0,CM.formExistsAtId)(()=>t.api.get(this.dataverse,n),s.sent.formid)){let u=`the platform answered the create with ${a.message} \u2014 this build refuses a replayed create that way \u2014 but a read of that id finds the record`;throw(0,Z.attachCause)(new Z.SdkError(yr.ALREADY_EXISTS_CODE,rw(r,n,u)+(this.createRecovery==="adoptExact"?` ${TM(Gae)}`:"")),a)}if(!(a instanceof Z.SdkError)||a.code!==gr.VERSION_CONFLICT_CODE||(0,EM.isFailureAfterPrimaryWrite)(a))throw a;if(this.createRecovery==="adoptExact"&&s?.status===412){let l=await(0,CM.recoverFormCreate)({client:this.dataverse,read:()=>t.api.get(this.dataverse,n),sent:s.sent,authoredFormType:o.formType,project:u=>t.adapter.fromApiResponse(u)});if("adopted"in l)return{adopted:l.adopted};throw new Z.SdkError(yr.ALREADY_EXISTS_CODE,`${rw(r,n)} ${TM(l.refused)}`)}throw new Z.SdkError(yr.ALREADY_EXISTS_CODE,rw(r,n))}}async persistAdoption(t,r,n,i){let{artifact:o,etag:a}=i,s=!(0,vn.deepEqual)(o,n);return await this.versions.storeMeta(t,r,{etag:a,...s?{refreshGeneration:this.nextRefreshGeneration(t,r,null),observedGeneration:0}:{},languageCode:this.languageCode,projectionVersion:ml.PROJECTION_VERSION,fetchedAt:(0,gr.nowIso)(),snapshot:(0,pi.cloneJson)(o)},null),s&&await this.workspace.writeArtifact(t,r,o),{type:t,id:r,saved:!1,adoptedExisting:!0,shipped:!1,publish:{kind:"notRequested"},...s?{refreshed:!0}:{}}}async buildMetadataContext(t,r,n){var i,o,a,s;let l=(o=(i=t.metadataNeeds)===null||i===void 0?void 0:i.call(t,r,n))!==null&&o!==void 0?o:[],u=new Set(l.map(k=>k.entityLogicalName).filter(k=>!!k)),c=new Set(l.filter(k=>k.needsColumnDetail).map(k=>k.entityLogicalName)),d=new Set(l.filter(k=>k.needsColumnDetail||!k.fieldName).map(k=>k.entityLogicalName)),f=k=>l.filter(I=>I.entityLogicalName===k).every(I=>I.fetchRequired===!1),m=new Map,p=new Map;for(let k of u){let I=await this.readCachedEntityMetadata(k);if(I&&c.has(k)&&(I.columnDetailComplete!==!0||!(typeof I.columnDetailVersion=="number"&&I.columnDetailVersion>=hl.COLUMN_DETAIL_VERSION)||I.attributes.some(D=>typeof D.attributeTypeName!="string"))&&(I=null),!I&&!d.has(k)){if(!f(k)){let D=l.filter(P=>P.entityLogicalName===k).map(P=>P.fieldName);try{let P=await(0,hl.readColumnHints)(this.dataverse,k,D);p.set(k,new Map(P.map(x=>[x.logicalName,x])))}catch{}}continue}if(!I&&!f(k))try{await this.loadMissedEntityMetadata(k),I=await this.readCachedEntityMetadata(k)}catch{}I&&m.set(k,I)}let h=(k,I)=>{var D,P,x;return(P=(D=m.get(k))===null||D===void 0?void 0:D.attributes.find(K=>K.logicalName===I))!==null&&P!==void 0?P:(x=p.get(k))===null||x===void 0?void 0:x.get(I)},g=this.languageCode,w=l.some(k=>{if(!k.needsLabel||!k.fieldName)return!1;let I=h(k.entityLogicalName,k.fieldName);return I?.localizedDisplayName!==void 0&&!I.localizedDisplayName[g]})?await this.readBaseLanguage():void 0,C=!((a=t.needsBaseLanguage)===null||a===void 0)&&a.call(t,r)?await this.readBaseLanguage():void 0,S=(s=t.customControlNeeds)===null||s===void 0?void 0:s.call(t,r,n),O=S&&(S.controls.length>0||S.columns.length>0)?await this.readPcfNeeds(S):void 0;return{resolveField:(k,I)=>{let D=h(k,I);return D?{displayName:Hae(D,g,w),attributeType:D.attributeType}:void 0},resolveEntity:k=>m.get(k),loadTypeScript:()=>this.compiler.load(),...C!==void 0?{baseLanguageCode:C}:{},...O?{pcf:O}:{}}}async readPcfNeeds(t){let r=new Map;for(let i of t.controls)r.set(i,await(0,wM.readControlManifest)(this.dataverse,i));let n=new Map;for(let i of t.columns)n.set(i,await(0,wM.readPcfColumn)(this.dataverse,t.entityLogicalName,i,t.requireCreateEligibility?{requireCreateEligibility:!0}:void 0));return{control:i=>r.get(i),column:(i,o)=>i===t.entityLogicalName?n.get(o):void 0}}readBaseLanguage(){if(!this.baseLanguage){let t=(async()=>{var r,n,i;try{let o=await this.dataverse.get("/organizations?$select=languagecode");if(o.status<200||o.status>=300)return;let a=Number((i=(n=(r=o.body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.languagecode);return Number.isInteger(a)&&a>0?a:void 0}catch{return}})();this.baseLanguage=t,t.then(r=>{r===void 0&&this.baseLanguage===t&&(this.baseLanguage=void 0)})}return this.baseLanguage}async pushAll(){let t=await this.getDirtyArtifacts();await this.warmBatchMetadata(t);let r=new Map,n=new Map;for(let o=0;o<t.length;o+=1){let a=t[o];try{await this.withArtifactLock(a.type,a.id,()=>this.prepareArtifactUnlocked(a.type,a.id,r))}catch(s){n.set(o,{type:a.type,id:a.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Ro(s)})}}if(n.size>0)return t.map((o,a)=>{var s;return(s=n.get(a))!==null&&s!==void 0?s:{type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new Z.SdkError(yr.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${n.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let i=[];for(let o of t)try{i.push(await this.withArtifactLock(o.type,o.id,()=>this.pushArtifactUnlocked(o.type,o.id,r)))}catch(a){i.push({type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Ro(a)})}return i}async warmBatchMetadata(t){var r,n,i;let o=new Set;for(let a of t){let s=this.registrations.get(a.type);if(!s)continue;let l;try{l=await this.readLocal(a.type,a.id)}catch{continue}let u=l.entityLogicalName;u&&o.add(u);for(let c of(i=(n=(r=s.adapter).metadataNeeds)===null||n===void 0?void 0:n.call(r,l))!==null&&i!==void 0?i:[])c.entityLogicalName&&o.add(c.entityLogicalName)}for(let a of o)if(!await this.readCachedEntityMetadata(a))try{await this.loadMissedEntityMetadata(a)}catch{}}async getDirtyArtifacts(){return(await this.withDirtyFlags(await this.workspace.listArtifacts())).filter(r=>r.isDirty)}async diffArtifact(t,r){return this.versions.diff(t,r)}assignMissingIds(t,r){let n=this.registrations.get(t);return n?n.adapter.assignMissingIds(r):(0,lm.assignMissingIds)(r)}async resolveComponentType(t){if(t.genPage)return"genPage";switch(t.componentType){case rr.SolutionComponentType.SavedQuery:return"view";case rr.SolutionComponentType.SavedQueryVisualization:return"chart";case rr.SolutionComponentType.AppModule:return"app";case rr.SolutionComponentType.Workflow:return this.workflowArtifactType(t);case rr.SolutionComponentType.SystemForm:return this.systemFormArtifactType(t.objectId);default:return}}async systemFormArtifactType(t){let r=await(0,am.readSystemFormType)(this.dataverse,t);if(Number.isNaN(r))throw new Z.SdkError(tw,`System form '${t}' answered without a readable type, so whether it is a form or a dashboard cannot be told.`);return(0,am.systemFormKindOf)(r)}async workflowArtifactType(t){let r=(0,La.normalizeGuid)(t.objectId,"workflowId"),n=`/workflows(${r})${(0,La.odataQuery)([["$select","category,businessprocesstype"]])}`,o=(0,gr.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)).body,a=(0,am.decodeCode)(o?.category);if(Number.isNaN(a))throw new Z.SdkError(tw,`Workflow '${r}' answered without a readable category, so its kind cannot be told.`);if(t.workflowCategory=a,a===Fae)return"businessRule";if(a===Mae){let s=(0,am.decodeCode)(o?.businessprocesstype);if(Number.isNaN(s))throw new Z.SdkError(tw,`Workflow '${r}' (category 4) answered without a readable businessprocesstype, so whether it is a business process flow or a task flow cannot be told.`);return s===0?"bpf":void 0}}requireRegistration(t,r){let n=this.registrations.get(t);if(!n)throw new Z.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};yr.MakerSdk=um;function zae(e){return new um(e)}yr.createMakerSdk=zae;function Ro(e){return e instanceof Error?e:new Error(String(e))}function RM(e,t){let r=Object.keys(e??{}),n=Object.keys(t??{});return r.length===n.length&&r.every(i=>Object.prototype.hasOwnProperty.call(t??{},i))}function kM(e){return Object.values(e??{}).every(gr.isVersionToken)}function jae(e,t){return RM(e,t)&&kM(e)&&Object.keys(e??{}).every(r=>t?.[r]===e?.[r])}function TM(e){return`createRecovery 'adoptExact' did not adopt it: ${e}.`}function rw(e,t,r){return`Cannot create ${e} '${t}': a record already exists at that id${r?` (${r})`:""}, so an earlier push of this artifact committed before its local version metadata was saved. No duplicate was created. Run fetchArtifact('${e}', '${t}', { overwrite: true }) to adopt the existing record's identity, etag and snapshot \u2014 the overwrite is required, because this local copy has never been pushed, so a plain fetch keeps it and adopts nothing; it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push again: a conditional update, provided the adopted record is complete. If the earlier push committed only PART of a multi-row artifact (e.g. an app's appmodule without its sitemap), that update refuses, naming what is missing and how to remove the partial record. This is not done automatically because the only recovery available here would be an UNCONDITIONAL overwrite, which would destroy any edit made to the record in the meantime.`}function Hae(e,t,r){let n=e.localizedDisplayName;return n?.[t]||(r===void 0?void 0:n?.[r])||e.displayName}function Ki(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function DM(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function IM(e){e.length===0||!e.every(t=>Ki(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function Kae(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=>Ki(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>Ki(n)&&n.id===t.after);return r<0?e.length:r+1}});var $M=v(cm=>{"use strict";Object.defineProperty(cm,"__esModule",{value:!0});cm.ARTIFACT_TYPES=void 0;cm.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var FM=v(xM=>{"use strict";Object.defineProperty(xM,"__esModule",{value:!0})});var UM=v(MM=>{"use strict";Object.defineProperty(MM,"__esModule",{value:!0})});var qM=v(BM=>{"use strict";Object.defineProperty(BM,"__esModule",{value:!0})});var GM=v(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0})});var zM=v(WM=>{"use strict";Object.defineProperty(WM,"__esModule",{value:!0})});var HM=v(jM=>{"use strict";Object.defineProperty(jM,"__esModule",{value:!0})});var JM=v(KM=>{"use strict";Object.defineProperty(KM,"__esModule",{value:!0})});var QM=v(YM=>{"use strict";Object.defineProperty(YM,"__esModule",{value:!0})});var ZM=v(XM=>{"use strict";Object.defineProperty(XM,"__esModule",{value:!0})});var tU=v(eU=>{"use strict";Object.defineProperty(eU,"__esModule",{value:!0})});var nU=v(rU=>{"use strict";Object.defineProperty(rU,"__esModule",{value:!0})});var oU=v(iU=>{"use strict";Object.defineProperty(iU,"__esModule",{value:!0})});var sU=v(aU=>{"use strict";Object.defineProperty(aU,"__esModule",{value:!0})});var uU=v(lU=>{"use strict";Object.defineProperty(lU,"__esModule",{value:!0})});var dU=v(cU=>{"use strict";Object.defineProperty(cU,"__esModule",{value:!0})});var pU=v(fU=>{"use strict";Object.defineProperty(fU,"__esModule",{value:!0})});var hU=v(mU=>{"use strict";Object.defineProperty(mU,"__esModule",{value:!0})});var yU=v(gU=>{"use strict";Object.defineProperty(gU,"__esModule",{value:!0})});var vU=v(bU=>{"use strict";Object.defineProperty(bU,"__esModule",{value:!0})});var CU=v(wU=>{"use strict";Object.defineProperty(wU,"__esModule",{value:!0})});var AU=v(EU=>{"use strict";Object.defineProperty(EU,"__esModule",{value:!0})});var NU=v(pe=>{"use strict";var Jae=pe&&pe.__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]})),Ge=pe&&pe.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Jae(t,e,r)};Object.defineProperty(pe,"__esModule",{value:!0});pe.projectConnectorOperationSchema=pe.projectConnectorOperations=pe.createMakerSdk=void 0;var Yae=LM();Object.defineProperty(pe,"createMakerSdk",{enumerable:!0,get:function(){return Yae.createMakerSdk}});Ge($M(),pe);Ge(FM(),pe);Ge(UM(),pe);Ge(qM(),pe);Ge(GM(),pe);Ge(zM(),pe);Ge(HM(),pe);Ge(JM(),pe);Ge(QM(),pe);Ge(ZM(),pe);Ge(tU(),pe);Ge(nU(),pe);Ge(oU(),pe);Ge(sU(),pe);Ge(uU(),pe);Ge(Ud(),pe);Ge(dU(),pe);Ge(pU(),pe);Ge(hU(),pe);Ge(yU(),pe);Ge(vU(),pe);Ge(CU(),pe);Ge(AU(),pe);Ge(Q(),pe);var SU=Tl();Object.defineProperty(pe,"projectConnectorOperations",{enumerable:!0,get:function(){return SU.projectConnectorOperations}});Object.defineProperty(pe,"projectConnectorOperationSchema",{enumerable:!0,get:function(){return SU.projectConnectorOperationSchema}})});var iw=v(mi=>{"use strict";var Qae=mi&&mi.__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]})),Xae=mi&&mi.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),DU=mi&&mi.__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)&&Qae(t,e,r);return Xae(t,e),t};Object.defineProperty(mi,"__esModule",{value:!0});mi.NodeFileSystemStorage=void 0;var Ct=DU(require("fs")),nr=DU(require("path")),_U=Q(),TU=Bm();async function IU(e){let t;try{t=await Ct.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await Ct.promises.unlink(e)}catch{await Ct.promises.rmdir(e)}return}if(!t.isDirectory()){await Ct.promises.unlink(e);return}for(let r of await Ct.promises.readdir(e))await IU(nr.join(e,r));await Ct.promises.rmdir(e)}var nw=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(nr.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!Ct.existsSync(r);){n.unshift(nr.basename(r));let i=nr.dirname(r);if(i===r)return nr.resolve(t);r=i}return nr.resolve(Ct.realpathSync(r),...n)}assertWithinRoot(t,r){let n=nr.resolve(this.root),i=nr.resolve(t);if(i!==n&&!i.startsWith(n+nr.sep))throw new _U.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(n),a=r?this.realPathThroughNearestAncestor(i):nr.resolve(this.realPathThroughNearestAncestor(nr.dirname(i)),nr.basename(i));if(a!==o&&!a.startsWith(o+nr.sep))throw new _U.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!Ct.existsSync(r))return null;try{return await(0,TU.retryTransientIoAsync)(()=>Ct.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=nr.dirname(n);await Ct.promises.mkdir(i,{recursive:!0});let o=nr.join(i,`.${nr.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await Ct.promises.writeFile(o,r,"utf8"),await(0,TU.retryTransientIoAsync)(()=>Ct.promises.rename(o,n))}catch(a){try{Ct.existsSync(o)&&await Ct.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let r=this.pathFor(t);Ct.existsSync(r)&&await Ct.promises.unlink(r)}async deleteByPrefix(t){await IU(this.pathFor(t,!1))}async ensureContainer(t){await Ct.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return Ct.existsSync(this.pathFor(t))}};mi.NodeFileSystemStorage=nw});var OU=v(Ur=>{"use strict";var Zae=Ur&&Ur.__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]})),ese=Ur&&Ur.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),tse=Ur&&Ur.__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)&&Zae(t,e,r);return ese(t,e),t};Object.defineProperty(Ur,"__esModule",{value:!0});Ur.loadNodeTypeScript=Ur.createNodeWorkspaceStorage=Ur.NodeFileSystemStorage=void 0;var rse=iw(),nse=iw();Object.defineProperty(Ur,"NodeFileSystemStorage",{enumerable:!0,get:function(){return nse.NodeFileSystemStorage}});function ise(e){return new rse.NodeFileSystemStorage(e)}Ur.createNodeWorkspaceStorage=ise;async function ose(){return await Promise.resolve().then(()=>tse(require("typescript")))}Ur.loadNodeTypeScript=ose});var Ji={};module.exports=Br(Ji);Yi(Ji,Ae(NU()),module.exports);Yi(Ji,Ae(OU()),module.exports);
diff --git a/plugins/model-apps/scripts/verify-model-app.js b/plugins/model-apps/scripts/verify-model-app.js
index 00ed38040..0c01bb9c4 100644
--- a/plugins/model-apps/scripts/verify-model-app.js
+++ b/plugins/model-apps/scripts/verify-model-app.js
@@ -62,6 +62,7 @@ const { assertSafeOutputDir } = require('./lib/safe-fs.js');
const { depthFromMask } = require('./lib/role-privileges.js');
const { appEntityComponentsFor, appMainFormsFor, appComponentRows } = require('./lib/app-components.js');
const { readChoiceAttributes } = require('./lib/view-filter-labels.js');
+const { readStatusReasons, readAlternateKeys } = require('./lib/status-reasons-keys.js');
const { sameFormXmlAcrossLayers } = require('./lib/formxml-layers.js');
// The app's id and the ids of the roles associated with it live in lib/app-roles.js: the design document reads the same relationship. Still exported from here.
const { appIdFor, appRoleIdsFor } = require('./lib/app-roles.js');
@@ -267,6 +268,11 @@ function readerFor(sdk, appUnique, opts) {
const items = await sdk.resolveArtifact('command', { entity: String(entity).toLowerCase() });
return !!(items && items[0] && items[0].id);
},
+ // statusReasons(entity) / alternateKeys(entity): the table's status reasons, with their states, and its alternate keys, with their
+ // columns — one narrow read each, made only for a table that declares any (lib/status-reasons-keys.js). They never throw: a read that
+ // fails answers { state: 'error', why }, which verify reports on the checks it was for.
+ statusReasons: (logical) => readStatusReasons(sdk.dataverse, logical),
+ alternateKeys: (logical) => readAlternateKeys(sdk.dataverse, logical),
// rolePrivileges(roleId): what the deployed role actually GRANTS, as [{ privilegeId, depth }].
// The `roleprivileges` intersect row carries `privilegedepthmask` — a BITMASK (1 Basic /
// 2 Local / 4 Deep / 8 Global), which is NOT the same encoding as the `Depth` name the SDK
@@ -636,7 +642,10 @@ async function main() {
// each column exists — so the spec of an app an earlier release built from a value they refuse (an AutoNumber column made as plain text, a
// `required: "true"` made not required) must still reach its deployment. The warning names the column and the fix for the next build. Not the
// structural profile: that would also skip the checks of pages and forms that verification relies on.
- const v = validateAppSpec(spec, { profile: 'deploy', relationshipCollisions: 'warn', columnValues: 'warn' });
+ // `fieldOptionKeys: 'warn'` is the same arrangement for a key a form's `fieldOptions` entry does not take: the build refuses one, because it
+ // would drop it and never apply the option, but a release before that check accepted it and built the form without the option — and
+ // verification only reads that deployment. Every other finding about the entry stays an error.
+ const v = validateAppSpec(spec, { profile: 'deploy', relationshipCollisions: 'warn', columnValues: 'warn', fieldOptionKeys: 'warn' });
// A warning is printed for a person and kept for the result JSON in one step, so the two cannot differ: a caller that reads only the JSON must not
// lose what stderr says. The spec's are found before it is judged, so a spec that is refused reports the warnings it also has.
const warnings = [];
diff --git a/plugins/model-apps/scripts/write-app-spec-doc.js b/plugins/model-apps/scripts/write-app-spec-doc.js
index 73e3fe4fc..d4dc425f0 100644
--- a/plugins/model-apps/scripts/write-app-spec-doc.js
+++ b/plugins/model-apps/scripts/write-app-spec-doc.js
@@ -12,8 +12,9 @@
//
// Output: { "ok": true, "docPath": "...", "bytes": N, "warnings": [...] }
// `warnings` echoes the design gaps rendered into the document (no jobs, unmapped jobs, no pages, a new table no role is
-// given access to, and — with --env — what the environment says about who can open the app) so the orchestrator can
-// surface them in chat rather than leaving them buried in a file the user may not open.
+// given access to, a roleGrants[] entry the build refuses — in lint's words — and, with --env, what the environment says
+// about who can open the app) so the orchestrator can surface them in chat rather than leaving them buried in a file the
+// user may not open.
//
// --env <orgUrl> labels the document with the environment AND reads, read-only, which security roles the app has associated
// with it there (lib/app-roles.js), so the document can say who can already open the app and keep that apart from the privileges
@@ -27,7 +28,7 @@ const { assertSafeOutputDir, writeFileSafe } = require('./lib/safe-fs.js');
const { parseArgs, validateFlags, readJsonArg, emitResult, requireDataverseOrigin } = require('./lib/dataverse-auth.js');
const { migrateAppSpec } = require('./lib/app-spec.js');
const { renderAppSpecDoc } = require('./lib/app-spec-doc.js');
-const { appAccessModel, uncoveredTables, uncoveredTablesWarning } = require('./lib/app-access.js');
+const { appAccessModel, roleGrantRefusals, uncoveredTables, uncoveredTablesWarning } = require('./lib/app-access.js');
const { withThrowawaySdk } = require('./lib/throwaway-sdk.js');
const { appRolesOf } = require('./lib/app-roles.js');
const { makeWritesBlocking } = require('./lib/output-redaction.js');
@@ -67,6 +68,9 @@ function designGaps(spec, opts = {}) {
}
const withoutAccess = uncoveredTables(s);
if (withoutAccess.length) out.push(uncoveredTablesWarning(withoutAccess));
+ // A roleGrants[] entry that does not name exactly one role, in the words lint-app-spec.js reports it in (roleGrantRefusals): the build
+ // refuses the spec, and the document shows the entry as that refusal rather than as a grant.
+ for (const { messages } of roleGrantRefusals(s)) out.push(...messages);
// What the environment said (--env), from the same model the document is written from. The administrator-only conclusion is drawn here, and only here, on that
// evidence: the app has no role (or does not exist yet) AND no persona of this spec gets it — a persona that opts out (`appAccess: false`) is a role the build
diff --git a/plugins/model-apps/skills/app-builder/SKILL.md b/plugins/model-apps/skills/app-builder/SKILL.md
index b90c7564f..b543136f0 100644
--- a/plugins/model-apps/skills/app-builder/SKILL.md
+++ b/plugins/model-apps/skills/app-builder/SKILL.md
@@ -62,7 +62,8 @@ prod-ready** app; don't under-build (a bare table list) or over-build (surfaces
`100000003`, because they are assigned per publisher. Resolve by label via `getOptions()`
(see `references/app-spec-schema-advanced.md` → webResources). Note also that command and web-resource
**edits do not redeploy on rebuild** — the phases reuse what exists, so changing a button or a
- script means deleting it first.
+ script means deleting it first. This does not apply to recovery of the build's own
+ `WEB_RESOURCE_UNVERIFIED` row: keep that row and the same build workspace, then follow its halt.
- **Form logic without code** — `businessRules[]`: show/hide, lock/unlock, set-required and
set-value, driven by a condition on the record. **Reach for a business rule before form JS** when
the requirement is field-level and declarative — it is visible in the maker, survives solution
@@ -326,9 +327,10 @@ After plan-mode approval (before the full build):
The plan's `## Environment` carries `Mode: app-builder` and every page row carries a **Key**, so
the worker emits `"PAGEREF_<key>"` for cross-page navigation (never a file-derived token — a
downloaded page's `codeFile` is a path, not its identity). Custom nav ids go in `data:` — never
- `recordId`. `Connectors: none` and `Telemetry: disabled` are constants here: the App Spec has no
- connector-binding concept (so the projected plan always says `No connector bindings.`), and
- `/app-builder` never runs the Phase 4.7 `custom-telemetry` probe. Both are stated explicitly
+ `recordId`. `Connectors: none` and `Telemetry: disabled` are constants here: `/app-builder` writes no
+ connector code (the App Spec's `connectorBindings` / `actionBindings` are lists a downloaded page already
+ holds, carried through a rebuild and never authored here, so the projected plan always says
+ `No connector bindings.`), and `/app-builder` never runs the Phase 4.7 `custom-telemetry` probe. Both are stated explicitly
rather than omitted — the page-builder treats a missing line as the same fail-closed value, but
an explicit line is what makes the dispatch contract checkable.
@@ -463,7 +465,7 @@ fails. A form whose read carries no label at all is not such a case: the caption
Narrate progress as it runs. Transient env errors (a 429 or 503, a customization lock, a concurrent-operation
guard or a SQL timeout the service names by its error code, a timeout or reset of the connection) are
**auto-retried** with backoff on `--apply` (the build is idempotent, so a retry reuses what's already created).
-A throttled service is waited for as long as it asks (`Retry-After`) — by the HTTP client's re-sends of a throttled read or publish, by the page writes and by the build's own re-runs of a phase — inside one budget of five minutes per run for all the waiting
+A throttled service is waited for as long as it asks (`Retry-After`) — by the HTTP client's re-sends of a throttled read or service-protection-limited publish, by the page writes and by the build's own re-runs of a phase — inside one budget of five minutes per run for all the waiting
a throttle costs: when the next wait does not fit, the build stops with a `throttle-budget-exhausted`
halt that says what the service asked — run it again later and it continues. (A 5xx, a reset connection or a deadlock is not a throttle: those keep their own, shorter schedule and are not counted in it.) If the build still **halts** (`BuildHalt`) on an
unrecoverable error, surface it and ask the user how to proceed via `AskUserQuestion` (adjust the
@@ -475,7 +477,12 @@ targeted artifact so the change takes effect (see *Notes & limits*).
**Recovery from a failed or halted build: run the full build again.** The build is idempotent — every
phase re-uses what's already created and only fills the gaps. SDK metadata is persisted under
`<working-dir>/.maker-workspace/` (override with `--workspace`). There is no apply-safe
-`--from <phase>` shortcut; a full rerun is the correct and safe recovery path. One exception: an
+`--from <phase>` shortcut; a full rerun is the correct and safe recovery path — after a `WEB_RESOURCE_UNVERIFIED`
+halt too: a web resource was written but its publication could not be confirmed (often because another customization
+held the environment's lock), the build recorded it, and a rerun using the **same writable workspace** writes it
+again by its id; do not delete or rename it. If the halt says its recovery record could not be saved, or reports
+a conflicting name/id, follow that explicit resolution instead — automatic retry is unsafe without the identity.
+One exception: an
`already-exists` halt recurs on a rerun until that workspace directory is deleted — follow its message.
Another: that workspace belongs to the environment it was first opened for. Only `--apply` opens it — a dry
run works in a temporary workspace, so it binds nothing, previews from any folder, and warns when an `--apply`
@@ -569,7 +576,9 @@ failed, so a re-run can still tell, keeps the page manifest while the generative
re-run still finds the pages the app authored, and keeps a table — with its icon web resource and a global choice its
columns bind, which the platform refuses to delete while the table exists, and its relationship to itself — while a
business rule on it could not be deleted (the rule's activated copy can never be deleted once its table is gone), so
-a re-run deletes the rule first, then the table and what was kept with it. **Dry-run by default**; add `--apply
+a re-run deletes the rule first, then the table and what was kept with it. It never deletes the solution's
+**publisher** (the build reuses one by prefix, and other solutions may share it); its closing summary says so in one line,
+so tell the user the publisher stays and can be removed in Maker once nothing uses it. **Dry-run by default**; add `--apply
--allow-destructive` to actually delete (`--clear-workspace` also prunes `.maker-workspace/`).
**`--allow-destructive` is required for `teardown --apply`** — without it teardown refuses and
touches nothing.
@@ -686,7 +695,8 @@ This reconstructs the app into `<working-dir>/app-spec.json`. **Round-trip scope
not everything:**
- **Round-trips:** the sitemap → `appShell` (all subareas + icons), **every** generative page (read
through the SDK; the pages are the sitemap's `GenPage` subareas, so Maker-added pages
- are included, and each keeps its own name and model) into `pages[]` + their `.tsx`, the referenced
+ are included, and each keeps its own name, model, and connector and Custom API bindings —
+ `connectorBindings` / `actionBindings`) into `pages[]` + their `.tsx`, the referenced
entities (minimal — the build reuses existing tables), **classic dashboards** (id-passthrough tiles
carrying the deployed view/chart ids), the icon web resources, and the solution.
- **Does NOT round-trip:** `forms[]`, `views[]`, `charts[]`, `commands[]` — they come back empty.
@@ -700,6 +710,30 @@ not everything:**
the design document name each new table no persona and no grant covers, and `write-app-spec-doc.js
--env` lists the roles the app has.
+**Page bindings and another environment.** A page's connector and Custom API bindings are in the spec, by the
+properties the references document — `logicalName`, `connectorId`, `dataset`, `tables`, `tableDisplayNames`,
+`operations` for a connector binding; `name`, `isFunction`, `boundEntityLogicalName`, `displayName`,
+`parameterKinds` for a Custom API binding — each with a value of a shape known to be safe, and by nothing else,
+so a rebuild writes them back into this environment and into another one. A list in which any binding holds
+anything else (a connection id, a credential, a property no spec states, a URL with a query) is **not** in the
+spec at all: the pull's `pageBindings.notCarried` names the page, the list and the entry's place (never a value),
+and the page keeps that list as it is. Tell the user, and that the page folder's own `config.json` still holds
+everything — they must not commit or share that folder if a value there is a credential. A spec that states such
+a binding is refused. A rebuild cannot make what the bindings *name*. When the pull's result carries
+`pageBindings`, tell the user what it says before any rebuild into another environment: `neededInTarget` lists
+the connection references (and the connections behind them), the Custom APIs and the service resources (a
+SharePoint site and its list ids, say) that environment must already have, and `notCarried` the lists the spec
+could not state (a rebuild into the same environment leaves those as they are; into another one, they are bound
+with `/genpage`). The rebuild itself reads that environment's references before it writes anything: it **stops**
+(`pages-binding-reference-conflict`, nothing written) at a connection reference of that name that is for another
+connector — give the binding the logical name of a reference that is for the right connector, or set the
+binding's `connectorId` to the one that environment has, and never pick a reference for the user — and its
+warnings say by name each reference or Custom API that is not there yet, a reference that has no connection, an
+operation the custom connector there does not define, and what it could NOT check (a row that did not say its
+connector or connection, or operations no custom connector definition could prove): relay them. Do not write bindings into a
+spec yourself — they come from a page a pull read — and when you reset a page to `intent` to regenerate it, delete
+its bindings from the spec: the generator writes no connector code.
+
Then:
1. **Always pull fresh at the start of an edit session** — someone may have changed the app in Maker. The
@@ -769,7 +803,9 @@ the SDK rewrites the sitemap once to add the `GenPage` subareas) → **AI featur
**security** (one role per `personas[]` entry, sized from its jobs' declared access; injects an
app-module read privilege and associates the app to each role so it opens for that persona) →
publish (opt-in). When the app has generative-page subareas the app module is created first WITHOUT
-them (they can't resolve until the pages upload), then the pages phase rewrites the sitemap. All
+them (they can't resolve until the pages upload), then the pages phase rewrites the sitemap — except for a
+new app whose navigation holds ONLY page subareas: its pages are created first, and then the app, with them
+already in its first sitemap. All
Dataverse access goes through the SDK, so the downloaded metadata lands in `.maker-workspace/`.
Independent ops (columns, views/charts/forms) run with bounded parallelism; publish is one
round-trip per entity + the app. Views/charts build **before** forms so a sub-grid can reference the
@@ -823,9 +859,10 @@ child view id. Each step emits `[n/total]`.
independently).
**To apply one of those edits, change it in Maker, or `teardown --apply` then rebuild fresh.**
`--verify` catches what is **missing** — a spec view column, filter condition or sort key (authored
- sort keys must also keep their order), a relationship, command or dashboard — as a loud
- `verify FAIL`. It tolerates **extra** deployed content, so a view column, filter or sort key you
- removed from the spec still passes, just as one a maker added by hand does.
+ sort keys must also keep their order), a relationship, a table's command bar, a status reason, an alternate key
+ or a dashboard — as a loud `verify FAIL`. It tolerates **extra** deployed content, so
+ a view column, filter or sort key you removed from the spec still passes, just as one a maker added
+ by hand does. Individual command controls are not verified.
- Not in scope (later): **conditional** command visibility (Power-Fx-only), **titled
command groups** (from-scratch — needs an SDK-synthesized parent row), lookup/associated views,
multi-area sitemaps, **column-level (field) security**, and **access teams / hierarchy security**
diff --git a/plugins/pcf/CHANGELOG.md b/plugins/pcf/CHANGELOG.md
index 246a921bb..d48008d45 100644
--- a/plugins/pcf/CHANGELOG.md
+++ b/plugins/pcf/CHANGELOG.md
@@ -13,9 +13,10 @@ First preview release: ships the `/pcf:pcf` skill, matrix-pinned templates and r
### Changed
-- The bundled SDK is the one model-apps 2.17.0 ships (power-platform-ux d603c799); it no longer carries the SDK's PCF control registration, which this plugin never called.
+- The bundled SDK is the one model-apps 2.18.0 ships (power-platform-ux a3443479), beside model-apps 2.18.0's HTTP client; the SDK no longer carries its PCF control registration, which this plugin never called. What changed in them — a web resource's published content read back, an app's sitemap found by its component, a publish sent once — is in requests this plugin does not make: it only reads through them and publishes through PAC, so what it does is unchanged.
### Fixed
- The push receipt (`pcf-receipt.json`) no longer carries an access token that a refused confirmation read quoted, and every file the SDK writes into a push's workspace goes through the same output guard as model-apps' scripts.
- A large result is no longer cut short on Linux and macOS: `emitResult`, the printer of an uncaught error, `check-auth.js`, the result printers of `pcf-inventory.js`, `verify-pcf.js` and `lint-pcf.js`, every script's usage error and the write-safety hook's message make their writes blocking before the process exits. What is printed and every exit status are unchanged; Windows was never affected.
+- The output guard (the same module model-apps 2.18.0 ships) also keeps an access token out of bytes written to stdout or stderr, masked with `*` byte for byte so framed output keeps its length, out of the token's base64, percent-encoded and HTML spellings, and out of a token that `util.inspect` or an ellipsis cut short or that was split between two writes (each piece of 24 characters or more), keeping an escape split between two writes whole. Still left: a piece shorter than 24 characters, the middle piece of a token written in three or more writes, a short piece on the far side of a split escape, base64 of a part of the token, and bytes written to a file.
diff --git a/plugins/pcf/scripts/lib/output-redaction.js b/plugins/pcf/scripts/lib/output-redaction.js
index 04441224d..cc0572b4b 100644
--- a/plugins/pcf/scripts/lib/output-redaction.js
+++ b/plugins/pcf/scripts/lib/output-redaction.js
@@ -20,9 +20,12 @@
//
// EVERY OUTPUT PATH (sink), and what covers it:
// - stdout and stderr: `process.stdout.write` and `process.stderr.write` are wrapped (guardStream) the moment the first token is obtained — never before, so a process that has no token is untouched. Every `console.*` call
-// (in colours too), every script's result printer and warning printer, the build's progress lines, a library's own `console.warn` and the SDK bundle's end there. A text is cleaned as a STRING; bytes (a Buffer) are passed
-// as they are: nothing in the plugin writes bytes to a stream, and a test runner's own frames are bytes. `emitResult` (lib/dataverse-auth.js) also cleans its own text, so a result is clean where a caller has replaced the
-// stream's `write`. The writes a `process.exit` follows at once are made blocking first (makeWritesBlocking), so that what is written there is whole when the process ends — not only clean.
+// (in colours too), every script's result printer and warning printer, the build's progress lines, a library's own `console.warn` and the SDK bundle's end there. A text is cleaned as a STRING. BYTES (a Buffer, a
+// Uint8Array, or a string given with an encoding the stream decodes into bytes: `write(text, 'base64')`) are read byte for byte for every needle and spelling below, and a hit is masked in a COPY with as many `*` as
+// it has bytes — never decoded into text and encoded back, never shorter or longer: a test runner's own frames are bytes, and the length a frame declares must stay true — while bytes that hold none are the very object
+// given. Each write is read on its own, and nothing is held back to wait for the next one, so a token written in two pieces is two texts: the end of a write that BEGINS a needle and the start of one that ENDS a
+// needle are taken out too (EDGES, below) — never part of an escape cut between the two writes. `emitResult` (lib/dataverse-auth.js) also cleans its own text, so a result is clean where a caller has replaced the stream's `write`. The writes a `process.exit` follows at
+// once are made blocking first (makeWritesBlocking), so that what is written there is whole when the process ends — not only clean.
// - what Node itself prints when an error ends the process (an uncaught exception, an unhandled rejection): it never passes through `process.stderr.write`, so a handler prints it, cleaned, when nothing else handles the error
// (guardFatalErrors).
// - the files the plugin writes: `writeFileSafe` and `appendFileSafe` (lib/safe-fs.js: the build's journal and status file, a download's spec and pages, a page's file and its deployed copy, the plan, the settings template),
@@ -30,9 +33,14 @@
// `writeTextAtomic` (lib/maker-sdk.js wraps it: guardWorkspaceStorage). tests/output-token-writers.test.js lists every other write in the plugin and says why none of them can carry a token.
// - in the pcf plugin (which carries a copy of this module): its streams and its fatal errors as above (its scripts note their tokens through the same lib/dataverse-auth.js), the receipt `pcf-push.js` writes
// (`pcf-receipt.json`) and the SDK workspace `makePcfSdk` makes; pcf's tests/pcf-push-token.test.js lists every other write of pcf and says why none of them can carry a token.
-// - not covered, by design: bytes (a Buffer given to a writer is written as it is); a token another process obtained (`pac` has its own); another encoding of a token (percent-encoding, base64 of a whole header, HTML
-// entities — nothing is known to quote a token in one, and a reader that guessed at them would blank ordinary text); a token written in two separate calls to `write` (no script writes a message in pieces); a token a
-// formatter CUT SHORT (util.inspect prints at most 10,000 characters of a string, and the end of a part cut off there is not the part); a raw control character other than white space and ESC between two of its characters.
+// - not covered, by design: a token another process obtained (`pac` has its own); a piece of a token SHORTER than MIN_TOKEN_PART_LENGTH at the edge of a write or before a cut (it would be taken out of ordinary words — a
+// token written in two pieces leaves the shorter piece when it is under 24 characters; the first one is written before the second exists); a piece from the MIDDLE of a token that neither begins nor ends a needle (a
+// token written in three pieces or more, or cut at both ends); the start of a write read through an escape's letters (it is read on the first reading only: a literal backslash before its first letter leaves that letter);
+// the piece of a token that an escape cut between two writes leaves on its far side when that piece is shorter than 24 characters (the escape stays whole, so its characters count for neither piece);
+// a spelling other than those below (a partial percent-encoding, a numeric entity for every character, base64 of a part alone, hex, a token spelled backwards — a reader that guessed at them would blank ordinary data);
+// a cut other than util.inspect's, an ellipsis or the end of a text the process writes; inside BYTES only whole needles and the edges of a write are read (no cut, no fold, no escape); bytes given to a FILE writer (the
+// writers below clean text); the cuts and edges of a token searched for literally (one with white space, a backslash or an ESC of its own — no token a service issues); a raw control character other than white space
+// and ESC between two of its characters.
//
// A TOKEN AS A TEXT SPELLS IT. A token is looked for as the text spells it, one character at a time: a character is itself, or an escape of it (`\u0073` for `s`, in either case of hex; `\x73`; `\/` for `/`), and between
// two characters of the token there may be a fold — any white space, a line break and its indentation (the obsolete line folding of https://www.rfc-editor.org/rfc/rfc9112#section-5.2, a column a gateway wrapped), spelled as
@@ -42,11 +50,26 @@
// the token. The span from the token's first character to its last — the folds and escapes inside it included, an escape always whole — becomes `<token>`, and the white space before and after it stays. In JSON text the
// span is always inside one string and never leaves half of an escape, so what was JSON is still JSON (the baseline and the journal are read back by the next run).
//
-// COST. Every needle (the token, and each of its parts of 24 characters or more: needlesOf) is searched in ONE pass over the characters the text spells, as Knuth-Morris-Pratt does, in lockstep, so a text of any size takes time
-// that grows with its size and a near miss of a long needle over and over costs no more than any other text; an escape read the other way starts a reading that is followed next to the pass, and at most MAX_READINGS of them
-// per needle are alive at once — a real token keeps one or two — so no text makes the search backtrack or grow faster than the text. A text that would need more is not guessed at: the search fails, and every caller fails
-// closed (tests/output-redaction.test.js measures all of it). A text that holds no token comes back as the very string.
-const { inspect } = require('node:util');
+// OTHER SPELLINGS of a token the process obtained are needles of their own, read the same way (spellingsOf): its base64, standard and URL-safe, at each of the three byte alignments it can have inside a longer value (a
+// whole `Authorization` header, a body encoded once more), and its percent-encoded and HTML spellings where they differ from it. Exact spellings of a KNOWN token — nothing in a text is decoded to look inside it.
+//
+// A TOKEN CUT SHORT. A formatter that cuts a long text keeps its beginning, and the end of what it kept can be the beginning of a token: util.inspect prints at most 10,000 characters of a string and then says how many it
+// left out (`'Rejected bearer syntheticHeaderPartNotA'... 9876 more characters`), and a text cut to a length by hand ends with an ellipsis (`...`, `…`). Where a text says it was cut, the run before it that BEGINS a needle — 24
+// characters or more of it, read with every rule above — is taken out too, from its first character to its last (cutsHere, takePrefixes).
+//
+// EDGES. A write is read on its own and nothing is held back for the next one, so a token written in two pieces is two texts, each with a piece of it at one end. A text the process writes (redactOutput: a stream's write,
+// a file, a result) loses a run of 24 characters or more at its END that begins a needle, and one at its START that ends a needle (takeLeadingSuffix: on the first reading — an escape there is the character it stands
+// for). An escape is never cut by this: a text that ends inside one (`\`, `\u00`, `\x7`) is read up to where it begins, and a guarded stream remembers it — a few characters, not output — so that its next write, which
+// begins by finishing it, is read from after it (unfinishedEscape, finishEscape). The escape stays whole where it was written, and the pieces of the token on either side of it go each on its own: JSON written in two
+// pieces is JSON together. A text a caller only asks about (redactTokens) is read this way when it asks for `edges` (and `from`).
+//
+// COST. Every needle (the token, each of its parts of 24 characters or more: needlesOf, and each spelling: spellingsOf) is searched in ONE pass over the characters the text spells, as Knuth-Morris-Pratt does, in lockstep, so
+// a text of any size takes time that grows with its size and a near miss of a long needle over and over costs no more than any other text; an escape read the other way starts a reading that is followed next to the pass,
+// and at most MAX_READINGS of them per needle are alive at once — a real token keeps one or two — so no text makes the search backtrack or grow faster than the text. A cut is looked at where the pass already is (a quote,
+// a dot, an ellipsis, while a needle is being read), and its pieces are the alignments the pass already follows; the start of a text is read for at most the longest needle's length; bytes are read in one pass of the
+// same kind, needle by needle in lockstep. A text that would need more is not guessed at: the search fails, and every caller fails closed (tests/output-redaction.test.js and tests/output-token-forms.test.js measure
+// all of it). A text that holds no token comes back as the very string, and bytes as the very bytes.
+const { inspect, types: { isUint8Array } } = require('node:util');
// What takes the place of a token, or of a part of one, in a text.
const TOKEN_MARKER = '<token>';
@@ -63,6 +86,58 @@ function needlesOf(token) {
return [...needles].sort((a, b) => b.length - a.length);
}
+// The characters a percent-encoded text leaves as they are: the unreserved ones of https://www.rfc-editor.org/rfc/rfc3986#section-2.3 (`A-Z a-z 0-9 - . _ ~`). `encodeURIComponent` also leaves `! ' ( ) *` — none of
+// which a base64 or base64url token holds, so the two agree on every token a service issues.
+const unreserved = (byte) => (byte >= 0x41 && byte <= 0x5a) || (byte >= 0x61 && byte <= 0x7a) || (byte >= 0x30 && byte <= 0x39) || byte === 0x2d || byte === 0x2e || byte === 0x5f || byte === 0x7e;
+
+// `text` percent-encoded (https://www.rfc-editor.org/rfc/rfc3986#section-2.1): every UTF-8 byte that is not unreserved as `%` and two hex digits — upper case, which the RFC asks for, or lower case, which some encoders
+// write (`%2b`). A standard-base64 token in a query string: `abc+def/ghi=` → `abc%2Bdef%2Fghi%3D`.
+function percentSpelling(text, upper) {
+ let out = '';
+ for (const byte of Buffer.from(text, 'utf8')) {
+ if (unreserved(byte)) out += String.fromCharCode(byte);
+ else out += `%${(upper ? byte.toString(16).toUpperCase() : byte.toString(16)).padStart(2, '0')}`;
+ }
+ return out;
+}
+
+// The characters HTML text and attribute values spell as entities (https://html.spec.whatwg.org/multipage/parsing.html#escapingString, and `'` for an attribute in single quotes), as an HTML error page quotes a value.
+const HTML_ENTITIES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
+
+/**
+ * The other spellings of `token` that are taken out of what the process writes, each an exact needle read as any needle is (with folds and escapes in it):
+ * - its base64, standard and URL-safe (https://www.rfc-editor.org/rfc/rfc4648#section-4 and #section-5), as it is spelled INSIDE a longer value: base64 spells three bytes as four characters of six bits, so the token's
+ * first byte can stand at any of three places in a group and each place spells it differently. Of each, only the characters made of the token's own bits — a character that also holds bits of the byte before or
+ * after it changes with that byte, so it is left out at either end;
+ * - its percent-encoded spelling (upper- and lower-case hex) and its HTML spelling, and those of each of its parts of 24 characters or more — only where they differ from it: a JWT is base64url and dots, which
+ * neither changes, so a JWT has base64 spellings only.
+ * Each is kept only when it is MIN_TOKEN_PART_LENGTH characters or more, as a part is; a spelling that is already a needle of the token is not repeated. The longest first.
+ * @param {string} token
+ * @returns {string[]}
+ */
+function spellingsOf(token) {
+ if (typeof token !== 'string' || token === '') return [];
+ const plain = needlesOf(token);
+ const spellings = new Set();
+ const keep = (spelled) => {
+ if (spelled.length >= MIN_TOKEN_PART_LENGTH && !plain.includes(spelled)) spellings.add(spelled);
+ };
+ const bytes = Buffer.from(token, 'utf8');
+ for (let offset = 0; offset < 3; offset += 1) {
+ // With `offset` bytes before the token, its bits are bits [8 * offset, 8 * (offset + n)) of the value, and character i holds bits [6i, 6i + 6): the characters from ceil(8 * offset / 6) to floor(8 * (offset + n) / 6)
+ // hold the token's bits and nothing else.
+ const standard = Buffer.concat([Buffer.alloc(offset), bytes]).toString('base64').slice(Math.ceil((4 * offset) / 3), Math.floor((4 * (offset + bytes.length)) / 3));
+ keep(standard);
+ keep(standard.replace(/\+/g, '-').replace(/\//g, '_'));
+ }
+ for (const needle of plain) {
+ keep(percentSpelling(needle, true));
+ keep(percentSpelling(needle, false));
+ keep(needle.replace(/[&<>"']/g, (char) => HTML_ENTITIES[char]));
+ }
+ return [...spellings].sort((a, b) => b.length - a.length);
+}
+
// ---- Reading a text as it spells a token ----------------------------------------------------------------------------------------------------------------------------------------------------------
// White space as a regular expression's `\s` reads it: a fold can be made of any of it, and the plugin's own tests normalize a text with that class.
@@ -202,16 +277,32 @@ function readSpelled(text, at, skip) {
}
// The longest proper prefix of `needle.slice(0, i + 1)` that is also its suffix, for each i: where a search for the needle goes on after a mismatch, so that it never reads a character twice
-// (https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm).
-function failureTable(needle) {
- const table = new Int32Array(needle.length);
- for (let i = 1, k = 0; i < needle.length; i += 1) {
- while (k > 0 && needle.charCodeAt(i) !== needle.charCodeAt(k)) k = table[k - 1];
- if (needle.charCodeAt(i) === needle.charCodeAt(k)) k += 1;
+// (https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm). `unitAt(i)` is the needle's unit i, so that the same table is made for a needle read forwards, read backwards, or as bytes.
+function borders(size, unitAt) {
+ const table = new Int32Array(size);
+ for (let i = 1, k = 0; i < size; i += 1) {
+ const unit = unitAt(i);
+ while (k > 0 && unit !== unitAt(k)) k = table[k - 1];
+ if (unit === unitAt(k)) k += 1;
table[i] = k;
}
return table;
}
+const failureTable = (needle) => borders(needle.length, (i) => needle.charCodeAt(i));
+// The same of the needle read from its end: what the start of a text is matched against (endsAtStart).
+const reversedFailureTable = (needle) => borders(needle.length, (i) => needle.charCodeAt(needle.length - 1 - i));
+
+// How many units at the START of a sequence are the END of a needle: KMP over the needle read backwards (`reversed`, its table), fed the first `length` units of the sequence backwards, so that the state it is left in is
+// the longest end of the needle that the sequence begins with (the needle may also be found whole: then it is the needle's length). `needleUnit(i)` and `unitAt(i)` give unit i of the needle and of the sequence.
+function endsAtStart(size, needleUnit, reversed, length, unitAt) {
+ let state = 0;
+ for (let i = length - 1; i >= 0; i -= 1) {
+ const unit = unitAt(i);
+ while (state > 0 && (state === size || needleUnit(size - 1 - state) !== unit)) state = reversed[state - 1];
+ if (state < size && needleUnit(size - 1 - state) === unit) state += 1;
+ }
+ return state;
+}
// How many readings of ONE needle that took an escape's letters (and not the escape) the search follows at once. A random token keeps one or two alive on any text, and a needle that is one letter over and over keeps
// one per letter; more than this needs a text made to match the needle almost everywhere — i.e. made by someone who has the token. The bound keeps the cost linear on any text: past it the search does not guess which
@@ -219,35 +310,50 @@ function failureTable(needle) {
const MAX_READINGS = 128;
const TOO_MANY_READINGS = 'output-redaction: a text holds too many ways to read a token for it to be checked';
-// Everything the search needs of a set of tokens, made once and not for each text: the needles it can read and each one's failure table, the first character of each (a text is only looked at closely where one could start,
-// or where a needle is already being matched), what the reader skips, and the tokens that still need a literal search for a needle of their own that the reader cannot read.
+// Everything the search needs of a set of tokens, made once and not for each text: the needles it can read (the tokens, their parts and their spellings) and each one's failure tables, the first character of each (a text is
+// only looked at closely where one could start, or where a needle is already being matched), what the reader skips, and the needles that still need a literal search because the reader cannot read them — every needle
+// of a token that has one such (as before), and a spelling that is one.
function prepare(tokens) {
const live = [...new Set(tokens.filter((token) => typeof token === 'string' && token !== ''))];
if (live.length === 0) return null;
- const needles = [...new Set(live.flatMap(needlesOf))].filter((needle) => !unreadable(needle));
+ const plain = [...new Set(live.flatMap(needlesOf))];
+ const spelled = [...new Set(live.flatMap(spellingsOf))].filter((spelling) => !plain.includes(spelling));
+ const every = [...plain, ...spelled];
+ const needles = every.filter((needle) => !unreadable(needle));
const skip = new Uint8Array(128);
for (const unit of [0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x20]) skip[unit] = 1;
for (const unit of [0x22, 0x27, 0x60]) skip[unit] = 2;
skip[0x1b] = 3;
const firstUnits = new Uint8Array(65536);
+ // Every character any needle holds: a text whose first characters are not all among them cannot begin with the end of one (takeLeadingSuffix).
+ const inNeedles = new Uint8Array(65536);
for (const needle of needles) {
firstUnits[needle.charCodeAt(0)] = 1;
for (let i = 0; i < needle.length; i += 1) {
const unit = needle.charCodeAt(i);
+ inNeedles[unit] = 1;
if (unit < 128) skip[unit] = 0;
}
}
+ const longest = needles.reduce((length, needle) => Math.max(length, needle.length), 0);
return {
needles,
+ every,
tables: needles.map(failureTable),
- longest: needles.reduce((length, needle) => Math.max(length, needle.length), 0),
+ reversedTables: needles.map(reversedFailureTable),
+ longest,
firstUnits,
+ inNeedles,
skip,
- literal: live.filter((token) => needlesOf(token).some(unreadable)),
+ literal: [...live.filter((token) => needlesOf(token).some(unreadable)).flatMap(needlesOf), ...spelled.filter(unreadable)],
// The search's working memory, kept with what it is made for: a stream is written in many small pieces, and an array of the longest needle's length made for each would cost more than the search. The search
// never calls out and never starts another, so one set at a time is all there is.
- starts: new Int32Array(needles.reduce((length, needle) => Math.max(length, needle.length), 1)),
+ starts: new Int32Array(Math.max(longest, 1)),
states: new Int32Array(needles.length),
+ // The first characters a text spells, where each begins and ends: what its start is matched against (takeLeadingSuffix).
+ lead: { codes: new Int32Array(Math.max(longest, 1)), begins: new Int32Array(Math.max(longest, 1)), ends: new Int32Array(Math.max(longest, 1)) },
+ // The same needles as bytes, made the first time bytes are read (bytesOf).
+ bytes: null,
// For each needle, the readings that took an escape's letters: how far each is (`states`) and where it began (`begins`), with a second pair the next set is made in, and `slot` — for a state, 1 + its index in the next
// set — so that two readings that have come equally far are kept once, with the earlier beginning (whatever the later one would find, the earlier one finds with a span that holds it).
readings: needles.map((needle) => ({
@@ -328,25 +434,166 @@ function forkReadings(text, begin, end, prepared, read, spans) {
return alive;
}
+// The most digits of the count util.inspect prints after a cut: a string's length is below 2^53, which has 16 digits; a bound keeps the look at a cut from reading on.
+const MAX_COUNT_DIGITS = 16;
+
+// ---- An escape cut between two writes ----------------------------------------------------------------------------------------------------------------------------------------------------------------
+
+// Where an escape that a write ENDS inside begins — a run of backslashes at its end, or such a run and `u` with fewer than four hex digits after it, or `x` with fewer than two (readEscape's items, cut short) — or
+// `length` when it ends on no such thing. `unitAt(i)` is unit i of the write (a character, or a byte: an escape is ASCII either way), read from `from` on. The edges of a write stop there, and the guard on a stream
+// remembers it, so that the piece of a token before it and the one after it are each taken out and the escape is never cut in two: `{"error":"…\` and `/…"}` — a JSON `\/` written in two pieces — stay `\` and `/`.
+function unfinishedEscape(unitAt, from, length) {
+ const runStart = (at) => {
+ let start = at;
+ while (start - 1 >= from && unitAt(start - 1) === 0x5c) start -= 1;
+ return start;
+ };
+ let digitsFrom = length;
+ while (digitsFrom > from && digitsFrom > length - 3 && hexValue(unitAt(digitsFrom - 1)) >= 0) digitsFrom -= 1;
+ for (let letterAt = digitsFrom - 1; letterAt < length; letterAt += 1) {
+ if (letterAt - 1 < from) continue;
+ const letter = unitAt(letterAt);
+ const digits = length - letterAt - 1;
+ if (((letter === 0x75 && digits <= 3) || (letter === 0x78 && digits <= 1)) && unitAt(letterAt - 1) === 0x5c) return runStart(letterAt - 1);
+ }
+ if (length - 1 >= from && unitAt(length - 1) === 0x5c) return runStart(length - 1);
+ return length;
+}
+
+// The escape a write ended inside, kept as the stream's only memory of it: one backslash for its whole run (a run of any length is one item to readEscape) and what followed it — at most `\u` and three digits.
+function openEscapeOf(unitAt, start, length) {
+ let at = start;
+ while (at < length && unitAt(at) === 0x5c) at += 1;
+ let open = '\\';
+ for (let i = at; i < length; i += 1) open += String.fromCharCode(unitAt(i));
+ return open;
+}
+
+// How many units at the start of a write finish the escape the last write ended inside (`open`), and the escape still open after it when the write ends inside it too. `head` is the write's first units as a string
+// (latin1 for bytes), as many as can belong to the escape: its leading backslashes and six more.
+function finishEscape(open, head, wholeLength) {
+ const joined = open + head;
+ if (head.length === wholeLength && unfinishedEscape((i) => joined.charCodeAt(i), 0, joined.length) === 0) return { rest: wholeLength, open: openEscapeOf((i) => joined.charCodeAt(i), 0, joined.length) };
+ readEscape(joined, 0);
+ return { rest: Math.min(wholeLength, Math.max(0, spelledWidth - open.length)), open: null };
+}
+
+// Whether the text says, at `at`, that what stands before it was CUT SHORT:
+// - util.inspect prints at most `maxStringLength` (10,000) characters of a string and then, after the closing quote — in colours, after the code that ends the string's colour — how many it left out
+// (https://nodejs.org/api/util.html#utilinspectobject-options):
+// body: 'Rejected bearer syntheticHeaderPartNotA'... 9876 more characters body: \u001b[32m'Rejected bearer syntheticHe'\u001b[39m... 1 more character
+// with `"` or a backtick for the quote when the string holds a `'`;
+// - a text cut to a length by hand ends with an ellipsis: `...` (the plugin's own `briefReason`, lib/entity-provision.js, cuts a platform message to 297 characters and adds it), or `…`.
+// Only an item that can begin one of them is looked at, and only while a needle is being read; the codes after a quote are read once, by the one quote before them, so the look costs no more than the text.
+function cutsHere(text, at) {
+ const unit = text.charCodeAt(at);
+ if (unit === 0x2026) return true;
+ if (unit === 0x2e) return text.charCodeAt(at + 1) === 0x2e && text.charCodeAt(at + 2) === 0x2e;
+ if (unit !== 0x22 && unit !== 0x27 && unit !== 0x60) return false;
+ let i = at + 1;
+ while (text.charCodeAt(i) === 0x1b) {
+ const end = codeEnd(text, i);
+ if (end < 0) return false;
+ i = end;
+ }
+ if (!text.startsWith('... ', i)) return false;
+ const digits = i + 4;
+ let j = digits;
+ while (j - digits < MAX_COUNT_DIGITS && text.charCodeAt(j) >= 0x30 && text.charCodeAt(j) <= 0x39) j += 1;
+ return j > digits && text.startsWith(' more character', j);
+}
+
+// A needle CUT SHORT where the search now is (a cut, or the end of a whole write): every alignment still being read — the search's own (its state; the shorter alignments in its failure chain end where it ends and
+// begin later, so they are inside it) and every reading that took an escape's letters — that has come MIN_TOKEN_PART_LENGTH characters or more into a needle is that needle's beginning, from where it began to `end`,
+// the end of the last item that spelled a character. They all end there, so one span from the earliest of them holds them all. The readings are at most MAX_READINGS a needle, as for every other item the search reads.
+function takePrefixes(prepared, read, end, spans) {
+ const { needles, longest, starts, states, readings: all } = prepared;
+ let earliest = -1;
+ for (let n = 0; n < needles.length; n += 1) {
+ const state = states[n];
+ if (state >= MIN_TOKEN_PART_LENGTH) {
+ const begin = starts[(read - state) % longest];
+ if (earliest < 0 || begin < earliest) earliest = begin;
+ }
+ const readings = all[n];
+ for (let i = 0; i < readings.count; i += 1) {
+ if (readings.states[i] >= MIN_TOKEN_PART_LENGTH && (earliest < 0 || readings.begins[i] < earliest)) earliest = readings.begins[i];
+ }
+ }
+ if (earliest >= 0) spans.push([earliest, end]);
+}
+
+// A whole write that BEGINS with the end of a needle — what is left of a token whose first piece an earlier write took: the first characters the text spells, on the first reading (an escape is the character it stands for,
+// or nothing; its letters are not followed here), and for each needle the longest of its ends that they are (endsAtStart). One of MIN_TOKEN_PART_LENGTH characters or more is taken out, from the first character spelled
+// to the last of it: the white space before it stays. Such an end begins with MIN_TOKEN_PART_LENGTH characters that stand somewhere in its needle, so only a needle that holds the text's first ones is matched, and only
+// as many characters are read as the longest of those needles has: a write of ordinary words costs one short look.
+function takeLeadingSuffix(text, prepared, spans, from, to) {
+ const { needles, reversedTables, skip, lead } = prepared;
+ const { codes, begins, ends } = lead;
+ let count = 0;
+ let at = from;
+ const readUpTo = (limit) => {
+ while (at < to && count < limit) {
+ const begin = at;
+ let code = readSpelled(text, at, skip);
+ at += spelledWidth;
+ if (code === DUAL) code = primaryCode;
+ if (code === -1) continue;
+ codes[count] = code;
+ begins[count] = begin;
+ ends[count] = at;
+ count += 1;
+ }
+ };
+ readUpTo(MIN_TOKEN_PART_LENGTH);
+ if (count < MIN_TOKEN_PART_LENGTH) return;
+ for (let i = 0; i < MIN_TOKEN_PART_LENGTH; i += 1) if (prepared.inNeedles[codes[i]] === 0) return;
+ const first = String.fromCharCode(...codes.subarray(0, MIN_TOKEN_PART_LENGTH));
+ let reach = 0;
+ for (const needle of needles) if (needle.length > reach && needle.includes(first)) reach = needle.length;
+ if (reach === 0) return;
+ readUpTo(reach);
+ let longestEnd = 0;
+ for (let n = 0; n < needles.length; n += 1) {
+ const needle = needles[n];
+ if (!needle.includes(first)) continue;
+ const length = endsAtStart(needle.length, (i) => needle.charCodeAt(i), reversedTables[n], Math.min(count, needle.length), (i) => codes[i]);
+ if (length > longestEnd) longestEnd = length;
+ }
+ if (longestEnd >= MIN_TOKEN_PART_LENGTH) spans.push([begins[0], ends[longestEnd - 1]]);
+}
+
// Every needle searched for in ONE pass over the items the text spells, in time that grows with the text: a search that starts again at every character takes seconds on a text that is a needle's first thousand
// characters over and over. A needle's state is how many of its first characters the last items spell — on the escapes' first readings (as the character an escape stands for, or nothing), as Knuth-Morris-Pratt does it.
// An escape that can also be its letters (a literal backslash before an `n`) starts readings that the search follows next to it, a bounded set (forkReadings). A match runs from where the first of its characters is
// spelled to where its last ends — the folds and escapes between them are inside it, and the white space before and after is not. `starts` remembers where each of the last items began, in a ring as long as the longest
-// needle, which is all a match can reach back over; an item that cannot start a match while no needle is being matched is counted and not stored, because no match will ever ask for its start. The spans of all the
-// needles are then merged where they overlap (a token and its parts do) and each merged span is replaced by one marker; two spans that only touch stay two, as two tokens written one after the other are two.
-function takeOutSpelled(text, prepared) {
+// needle, which is all a match can reach back over; an item that cannot start a match while no needle is being matched is counted and not stored, because no match will ever ask for its start. Where the text says it was cut
+// (cutsHere), and — with `edges` — at its end, the alignments still being read that have come MIN_TOKEN_PART_LENGTH characters or more are a needle cut short (takePrefixes); with `edges`, a needle's end at the start of
+// the text is one too (takeLeadingSuffix). The spans of all the needles are then merged where they overlap (a token and its parts do) and each merged span is replaced by one marker; two spans that only touch stay two,
+// as two tokens written one after the other are two. With `edges`, the text is read from `from` (where an escape the last write ended inside is finished: see unfinishedEscape) up to an escape it ends inside, so that
+// no span ever takes part of an escape.
+function takeOutSpelled(text, prepared, edges, start = 0) {
const { needles, tables, longest, firstUnits, skip, starts, states, readings: all } = prepared;
const count = needles.length;
+ const stop = edges ? unfinishedEscape((i) => text.charCodeAt(i), start, text.length) : text.length;
states.fill(0);
for (const readings of all) readings.count = 0;
const spans = [];
let read = 0;
let matching = false;
- for (let at = 0; at < text.length;) {
+ // Where the last item that spells a character — or may: an escape read two ways — ends. A needle cut short ends there; the white space, colour codes and stray backslashes after it stay, as they do after a match.
+ let lastEnd = 0;
+ for (let at = start; at < stop;) {
+ if (matching) {
+ // Only a quote, a dot or an ellipsis can begin a cut: looked for here, and not in a call for every character of a token.
+ const unit = text.charCodeAt(at);
+ if ((unit === 0x27 || unit === 0x2e || unit === 0x22 || unit === 0x60 || unit === 0x2026) && cutsHere(text, at)) takePrefixes(prepared, read, lastEnd, spans);
+ }
const begin = at;
let code = readSpelled(text, at, skip);
at += spelledWidth;
if (code === -1) continue;
+ lastEnd = at;
let forked = false;
if (code === DUAL) {
code = primaryCode;
@@ -367,6 +614,8 @@ function takeOutSpelled(text, prepared) {
for (let n = 0; n < count; n += 1) {
const needle = needles[n];
const readings = all[n];
+ // A needle that is not being read and does not begin here stays as it is: nothing below would change it. The spellings make the needles of a token several, and a token's text runs this loop for each of them.
+ if (states[n] === 0 && readings.count === 0 && needle.charCodeAt(0) !== code) continue;
if (!forked && readings.count > 0) {
let kept = 0;
for (let i = 0; i < readings.count; i += 1) {
@@ -396,6 +645,10 @@ function takeOutSpelled(text, prepared) {
}
read += 1;
}
+ if (edges) {
+ if (matching) takePrefixes(prepared, read, lastEnd, spans);
+ takeLeadingSuffix(text, prepared, spans, start, stop);
+ }
if (spans.length === 0) return text;
spans.sort((a, b) => a[0] - b[0] || b[1] - a[1]);
let out = '';
@@ -414,27 +667,116 @@ function takeOutSpelled(text, prepared) {
return out + text.slice(kept);
}
-// `text` with the tokens `prepared` stands for taken out: what the reader finds, and then — only for a token that has a needle the reader cannot read (white space, a backslash or an ESC in it) — a literal search, as the Dataverse
-// client's scrubber does it. The reader first, so that a token spelled in one piece is one marker: a literal search first would take out the parts of a token whose dots are inside a fold, and leave `<token>.<token>`
-// where the reader finds the whole.
-function redactWith(prepared, text) {
+// `text` with the tokens `prepared` stands for taken out: what the reader finds, and then — only for a needle the reader cannot read (white space, a backslash or an ESC in it), with the other needles of its token — a literal
+// search, as the Dataverse client's scrubber does it. The reader first, so that a token spelled in one piece is one marker: a literal search first would take out the parts of a token whose dots are inside a fold, and leave
+// `<token>.<token>` where the reader finds the whole. `edges`: the text is a whole write (see EDGES above), read from `from`; nothing before `from` is changed, by the reader or the literal search.
+function redactWith(prepared, text, edges = false, from = 0) {
let out = text;
- if (prepared.needles.length > 0) out = takeOutSpelled(out, prepared);
- for (const token of prepared.literal) out = needlesOf(token).reduce((current, needle) => current.split(needle).join(TOKEN_MARKER), out);
- return out;
+ if (prepared.needles.length > 0) out = takeOutSpelled(out, prepared, edges, from);
+ if (prepared.literal.length === 0) return out;
+ // The reader leaves the units before `from` as they were, so they are the start of `out` too.
+ let rest = out.slice(from);
+ for (const needle of prepared.literal) rest = rest.split(needle).join(TOKEN_MARKER);
+ return from === 0 ? rest : out.slice(0, from) + rest;
+}
+
+// ---- Bytes ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+
+// What stands in the place of each byte of a token in bytes: one byte for one, so that bytes keep their length — a test runner's frames say how many bytes follow them.
+const MASK_BYTE = 0x2a;
+
+// The needles of `prepared` as the bytes they are written as (UTF-8): every one of them, read literally — bytes are not a text a formatter made, so no fold and no escape is read in them. Made the first time bytes are read.
+function bytesOf(prepared) {
+ if (prepared.bytes !== null) return prepared.bytes;
+ const needles = prepared.every.map((needle) => Buffer.from(needle, 'utf8'));
+ const firstBytes = new Uint8Array(256);
+ const inNeedles = new Uint8Array(256);
+ for (const needle of needles) {
+ firstBytes[needle[0]] = 1;
+ for (const byte of needle) inNeedles[byte] = 1;
+ }
+ prepared.bytes = {
+ needles,
+ tables: needles.map((needle) => borders(needle.length, (i) => needle[i])),
+ reversed: needles.map((needle) => borders(needle.length, (i) => needle[needle.length - 1 - i])),
+ firstBytes,
+ inNeedles,
+ states: new Int32Array(needles.length),
+ };
+ return prepared.bytes;
+}
+
+// `bytes` with every needle in them — and, with `edges`, a run of MIN_TOKEN_PART_LENGTH bytes or more at their end that begins a needle and at their start that ends one — masked, in a COPY: the bytes given are the
+// caller's (a frame it may write again, a pooled buffer). The very bytes when nothing is found. One pass, every needle in lockstep as Knuth-Morris-Pratt does it, the start read for at most each needle's length.
+function maskWith(prepared, bytes, edges, from = 0) {
+ const { needles, tables, reversed, firstBytes, inNeedles, states } = bytesOf(prepared);
+ const to = edges ? unfinishedEscape((i) => bytes[i], from, bytes.length) : bytes.length;
+ states.fill(0);
+ const spans = [];
+ let matching = false;
+ for (let i = from; i < to; i += 1) {
+ const unit = bytes[i];
+ if (!matching && firstBytes[unit] === 0) continue;
+ matching = false;
+ for (let n = 0; n < needles.length; n += 1) {
+ const needle = needles[n];
+ let state = states[n];
+ while (state > 0 && needle[state] !== unit) state = tables[n][state - 1];
+ if (needle[state] === unit) state += 1;
+ if (state === needle.length) {
+ spans.push(i + 1 - state, i + 1);
+ state = tables[n][state - 1];
+ }
+ states[n] = state;
+ if (state > 0) matching = true;
+ }
+ }
+ if (edges) {
+ // The start: an end of a needle of MIN_TOKEN_PART_LENGTH bytes or more begins with bytes that stand somewhere in that needle — each of them a byte some needle holds — so only a needle that holds the first ones
+ // is matched. The start and the end are those of the write less an escape cut at either of them (see unfinishedEscape).
+ let first = to - from >= MIN_TOKEN_PART_LENGTH ? bytes.subarray(from, from + MIN_TOKEN_PART_LENGTH) : null;
+ for (let i = 0; first !== null && i < MIN_TOKEN_PART_LENGTH; i += 1) if (inNeedles[bytes[from + i]] === 0) first = null;
+ for (let n = 0; n < needles.length; n += 1) {
+ const needle = needles[n];
+ if (states[n] >= MIN_TOKEN_PART_LENGTH) spans.push(to - states[n], to);
+ if (first === null || needle.indexOf(first) < 0) continue;
+ const length = endsAtStart(needle.length, (i) => needle[i], reversed[n], Math.min(to - from, needle.length), (i) => bytes[from + i]);
+ if (length >= MIN_TOKEN_PART_LENGTH) spans.push(from, from + length);
+ }
+ }
+ if (spans.length === 0) return bytes;
+ const copy = Buffer.from(bytes);
+ for (let i = 0; i < spans.length; i += 2) copy.fill(MASK_BYTE, spans[i], spans[i + 1]);
+ return copy;
}
/**
- * `text` with every token in `tokens` taken out of it — whole, and by each of its parts of 24 characters or more — wherever the text spells it: plainly, with a fold in it, with an escape in it (or a stray backslash), or
- * printed over several lines the way `util.inspect` prints a long string, in colours or not. A text that holds none is returned as the same string. Throws a RangeError for a text that holds too many ways to read a token
- * to be checked (MAX_READINGS): a caller must then not write the text.
+ * `text` with every token in `tokens` taken out of it — whole, by each of its parts of 24 characters or more, and by each of its other spellings (spellingsOf) — wherever the text spells it: plainly, with a fold in it, with
+ * an escape in it (or a stray backslash), or printed over several lines the way `util.inspect` prints a long string, in colours or not; and the beginning of one, 24 characters or more, where the text says it was cut.
+ * With `edges`, the text is read as a whole write is: a needle's beginning at its end, and a needle's end at its start, are taken out too. A text that holds none is returned as the same string. Throws a RangeError for a
+ * text that holds too many ways to read a token to be checked (MAX_READINGS): a caller must then not write the text. `from` (with `edges`): where an escape the last write ended inside is finished — nothing before it is read.
* @param {string} text
* @param {string[]} tokens
+ * @param {{ edges?: boolean, from?: number }} [options]
* @returns {string}
*/
-function redactTokens(text, tokens) {
+function redactTokens(text, tokens, { edges = false, from = 0 } = {}) {
const prepared = prepare(Array.isArray(tokens) ? tokens : []);
- return prepared === null || typeof text !== 'string' || text === '' ? text : redactWith(prepared, text);
+ return prepared === null || typeof text !== 'string' || text === '' ? text : redactWith(prepared, text, edges === true, edges === true ? from : 0);
+}
+
+/**
+ * `bytes` (a Buffer or a Uint8Array) with every token in `tokens` masked — each needle and spelling of it, byte for byte, with as many `*` — in a copy; with `edges`, also a needle's beginning of 24 bytes or more at their
+ * end and a needle's end at their start (from `from`, as for redactTokens). The very bytes when they hold none, and anything that is not bytes as it is.
+ * @template T
+ * @param {T} bytes
+ * @param {string[]} tokens
+ * @param {{ edges?: boolean, from?: number }} [options]
+ * @returns {T | Buffer}
+ */
+function maskTokenBytes(bytes, tokens, { edges = false, from = 0 } = {}) {
+ const prepared = prepare(Array.isArray(tokens) ? tokens : []);
+ return prepared === null || !isUint8Array(bytes) || bytes.length === 0 ? bytes : maskWith(prepared, bytes, edges === true, edges === true ? from : 0);
}
// ---- The tokens this process obtained -------------------------------------------------------------------------------------------------------------------------------------------------------------
@@ -461,17 +803,37 @@ function obtainedTokens() {
return [...obtained];
}
+// What is prepared from the tokens obtained so far, made again only when one has joined.
+function preparedNow() {
+ if (preparedFor.version !== version) preparedFor = { version, prepared: prepare([...obtained]) };
+ return preparedFor.prepared;
+}
+
/**
- * `text` with every token this process has obtained taken out of it. Anything that is not a string — bytes, a number — is returned as it is, and so is a text when no token has been obtained yet. Throws as `redactTokens`
- * does for a text that cannot be checked; every caller then fails closed (the guard on a stream writes a notice instead of the text, a file writer writes nothing and reports the failure).
+ * `text` with every token this process has obtained taken out of it, as a whole text the process writes is read (`edges`: a needle's beginning at its end and a needle's end at its start go too — a write, a file, a result).
+ * Anything that is not a string — bytes, a number — is returned as it is, and so is a text when no token has been obtained yet. Throws as `redactTokens` does for a text that cannot be checked; every caller then fails
+ * closed (the guard on a stream writes a notice instead of the text, a file writer writes nothing and reports the failure).
* @template T
* @param {T} text
* @returns {T}
*/
function redactOutput(text) {
if (typeof text !== 'string' || obtained.size === 0 || text === '') return text;
- if (preparedFor.version !== version) preparedFor = { version, prepared: prepare([...obtained]) };
- return redactWith(preparedFor.prepared, text);
+ return redactWith(preparedNow(), text, true);
+}
+
+/**
+ * What a guarded stream writes in place of `chunk`: a text as `redactOutput` makes it, and bytes with every token this process has obtained masked (maskTokenBytes, with the edges of the write) — the very bytes when they
+ * hold none. `from`: where an escape the stream's last write ended inside is finished (guardStream). Anything else is returned as it is.
+ * @template T
+ * @param {T} chunk
+ * @param {{ from?: number }} [options]
+ * @returns {T | Buffer}
+ */
+function redactWritten(chunk, { from = 0 } = {}) {
+ if (obtained.size === 0) return chunk;
+ if (typeof chunk === 'string') return chunk === '' ? chunk : redactWith(preparedNow(), chunk, true, from);
+ return isUint8Array(chunk) && chunk.length > 0 ? maskWith(preparedNow(), chunk, true, from) : chunk;
}
// ---- The streams, an error that ends the process, and the SDK's workspace --------------------------------------------------------------------------------------------------------------------------
@@ -480,29 +842,79 @@ function redactOutput(text) {
const GUARDED = Symbol.for('power-platform-skills.output-redaction.guarded');
// What is written where a text could not be cleaned (the cleaning itself failed): not the text, which may hold the token — a failure here is rare enough to be loud.
const WITHHELD = '[output withheld: it could not be checked for an access token]\n';
-// A string given with one of these encodings is not text (`write('6162', 'hex')`), so it is not read as text.
+// A string given with one of these encodings is not text (`write('6162', 'hex')`): the stream decodes it into the bytes it writes, so those bytes are what is read.
const BINARY_ENCODINGS = /^(?:hex|base64|base64url)$/i;
/**
- * Makes `stream.write` take the tokens out of every string it is given. The wrapper is the stream's own `write` property, put where the original was: whatever replaces it later replaces it whole, and a caller that wraps it
- * (`const write = stream.write; stream.write = …`) wraps it with the guard inside. Bytes are passed on as they are. Returns false for a stream that is already guarded or has no `write`.
+ * Makes `stream.write` take the tokens out of everything it is given. The wrapper is the stream's own `write` property, put where the original was: whatever replaces it later replaces it whole, and a caller that wraps it
+ * (`const write = stream.write; stream.write = …`) wraps it with the guard inside. A text is given to `redact`; so are bytes — a Buffer or a Uint8Array, and the bytes a string in a binary encoding stands for (decoded as
+ * the stream would decode it) — and where `redact` hands back other bytes, those are written in their place, with the same encoding argument (a stream ignores it for bytes): never a text made of bytes and turned back.
+ * The callback and what `write` returns are the stream's own. A write that ends inside an escape is remembered (a few characters), and the next write is read from after the units that finish it, with `{ from }` given
+ * to `redact`. Returns false for a stream that is already guarded or has no `write`.
* @param {{ write: Function }} stream
- * @param {(text: string) => string} [redact]
+ * @param {(chunk: string | Uint8Array, options: { from: number }) => (string | Uint8Array)} [redact]
* @returns {boolean}
*/
-function guardStream(stream, redact = redactOutput) {
+function guardStream(stream, redact = redactWritten) {
if (!stream || typeof stream.write !== 'function' || stream.write[GUARDED]) return false;
const write = stream.write;
+ // The escape the last write ended inside (`\`, `\u00`, …), or null: the stream's only memory of what it wrote — a few characters, no output — so that the next write, which begins by finishing it, is read from after
+ // it. Without it each write is read on its own, and a JSON `\/` written as `…\` and `/…` lost its `/` to the piece of the token after it: `\<token>`, which is no JSON (see unfinishedEscape).
+ let open = null;
+ const escapeIn = (unitAt, length, head) => {
+ let from = 0;
+ let carried = null;
+ if (open !== null) ({ rest: from, open: carried } = finishEscape(open, head, length));
+ if (carried === null) {
+ const start = unfinishedEscape(unitAt, from, length);
+ if (start < length) carried = openEscapeOf(unitAt, start, length);
+ }
+ return { from, carried };
+ };
+ // The units a finished escape can take at the start of a write: its leading backslashes and six more.
+ const headOf = (unitAt, length, slice) => {
+ let at = 0;
+ while (at < length && unitAt(at) === 0x5c) at += 1;
+ return slice(Math.min(length, at + 6));
+ };
+ // Bumped by every write, so that a write the stream refuses can tell whether a write made inside it (a callback the stream called at once) has moved the memory on since.
+ let writes = 0;
const guarded = function writeWithoutTokens(chunk, ...rest) {
+ const before = open;
let given = chunk;
- if (typeof chunk === 'string' && !(typeof rest[0] === 'string' && BINARY_ENCODINGS.test(rest[0]))) {
- try {
- given = redact(chunk);
- } catch {
- given = WITHHELD;
+ try {
+ let bytes = null;
+ if (typeof chunk === 'string' && typeof rest[0] === 'string' && BINARY_ENCODINGS.test(rest[0])) bytes = Buffer.from(chunk, rest[0]);
+ else if (isUint8Array(chunk)) bytes = chunk;
+ if (bytes !== null) {
+ const unitAt = (i) => bytes[i];
+ const { from, carried } = escapeIn(unitAt, bytes.length, headOf(unitAt, bytes.length, (end) => Buffer.from(bytes.buffer, bytes.byteOffset, end).toString('latin1')));
+ const masked = redact(bytes, { from });
+ open = carried;
+ if (masked !== bytes) given = masked;
+ } else if (typeof chunk === 'string') {
+ const unitAt = (i) => chunk.charCodeAt(i);
+ const { from, carried } = escapeIn(unitAt, chunk.length, headOf(unitAt, chunk.length, (end) => chunk.slice(0, end)));
+ given = redact(chunk, { from });
+ open = carried;
+ } else {
+ open = null;
}
+ } catch {
+ open = null;
+ given = WITHHELD;
+ }
+ // The memory is this write's before the stream takes it, so that a callback the stream calls at once, and writes from, reads on from it. A write the stream REFUSES — it throws (an encoding it does not know, a
+ // chunk that is no text and no bytes, a stream already ended) — wrote nothing, so the memory goes back to what the last written one left, unless a write made inside it has moved it on; the error is the
+ // stream's own. A write that returns false was taken (the stream asks the writer to wait): its memory stands.
+ writes += 1;
+ const mine = writes;
+ try {
+ return write.call(this, given, ...rest);
+ } catch (error) {
+ if (writes === mine) open = before;
+ throw error;
}
- return write.call(this, given, ...rest);
};
guarded[GUARDED] = true;
stream.write = guarded;
@@ -626,9 +1038,11 @@ function guardWorkspaceStorage(storage, redact = redactOutput) {
module.exports = {
TOKEN_MARKER,
needlesOf,
+ spellingsOf,
noteToken,
obtainedTokens,
redactTokens,
+ maskTokenBytes,
redactOutput,
guardStream,
makeWritesBlocking,
diff --git a/plugins/pcf/scripts/lib/sdk-http-client.js b/plugins/pcf/scripts/lib/sdk-http-client.js
index f7d57df3e..2d14267f5 100644
--- a/plugins/pcf/scripts/lib/sdk-http-client.js
+++ b/plugins/pcf/scripts/lib/sdk-http-client.js
@@ -29,7 +29,7 @@ const { needlesOf, noteToken, TOKEN_MARKER } = require('./output-redaction.js');
// as the next number, so a message that repeats the marker tens of thousands of times is read in linear time, not quadratic.
// The vendored SDK matches the marker anywhere in a 500's body for its own re-send (1 s / 2 s / 4 s) of reads, an app create,
// PublishXml, a form create, a view create and a publisher create — requests this client has already re-sent by
-// then, because it re-sends every 5xx that is not a record delete or a $batch (TRANSIENT, below). So a deadlock the
+// then (all but PublishXml, below), because it re-sends every 5xx that is not a record delete, a $batch or a publish (TRANSIENT, below). So a deadlock the
// client clears costs one re-send in all and the SDK's never fires; one that never clears is attempted up to the
// client's six times per SDK attempt (24 in all, measured on a form create and on a view create), a ceiling on a
// pathological case. A record DELETE and a conditional-delete $batch are the exception: this client re-sends their
@@ -40,6 +40,11 @@ const { needlesOf, noteToken, TOKEN_MARKER } = require('./output-redaction.js');
// one re-send in all and one that never clears at most 16 attempts (this client's four per SDK attempt). All of it
// is pinned against the real bundle in sdk-resend-layers.test.js.
//
+// A PUBLISH (`POST …/PublishXml`, or `PublishAllXml` should anything send it) is the other exception, the other way round: this client
+// sends it ONCE and leaves a deadlock victim to the one layer above it that re-sends one — the SDK's publishXml (its resendDeadlockVictim)
+// for a publish the SDK makes, and postPublishXml (lib/publish-xml.js) for the plugin's own — so no publish is sent again by two layers
+// at once. See `publishOnce` in `call` for what it is never sent again for, and why.
+//
// The one other `$batch` this client sends again is a change set that only CREATES columns (a new table's ordinary columns, see
// isColumnCreateBatch), and only after a 429: the platform refused to start it, so nothing in it committed (a change set is
// atomic) and it goes out again on the throttle schedule. After any other answer, a deadlock included, it is sent once, because a
@@ -48,6 +53,24 @@ const { needlesOf, noteToken, TOKEN_MARKER } = require('./output-redaction.js');
const SQL_DEADLOCK_VICTIM = /\bSql Number:\s*1205\b(?:(?!\bSql Number:\s*\d)[\s\S])*$/i;
// At most this many re-sends of a deadlock victim, 1 s / 2 s / 4 s apart — the SDK's own schedule.
const DEADLOCK_RESENDS = 3;
+
+// A publish, addressed by the action's name as the last segment of the path, bare or with its namespace — an unbound action of the Web API:
+// POST https://contoso.crm.dynamics.com/api/data/v9.2/PublishXml { "ParameterXml": "<importexportxml>…</importexportxml>" }
+// POST https://contoso.crm.dynamics.com/api/data/v9.2/Microsoft.Dynamics.CRM.PublishAllXml {}
+// A custom action whose name merely ends the same way (`new_PublishXml`) is another segment, and not a publish.
+// See https://learn.microsoft.com/power-apps/developer/data-platform/webapi/reference/publishxml and …/reference/publishallxml
+const PUBLISH_ACTION = /\/(?:Microsoft\.Dynamics\.CRM\.)?Publish(?:All)?Xml$/i;
+const isPublishRequest = (method, url) => method === 'POST' && PUBLISH_ACTION.test(new URL(url).pathname);
+
+// The error codes of Dataverse's SERVICE PROTECTION limits — the only 429s the platform documents as a refusal to START a request,
+// which asks the caller to wait for `Retry-After` and send it again (https://learn.microsoft.com/power-apps/developer/data-platform/api-limits):
+// 0x80072322 Number of requests "Number of requests exceeded the limit of 6000 over time window of 300 seconds."
+// 0x80072321 Execution time "Combined execution time of incoming requests exceeded limit of 1,200,000 milliseconds over time window of 300 seconds. …"
+// 0x80072326 Concurrent requests "Number of concurrent requests exceeded the limit of 52."
+// Read from the `error.code` of the answer, never from its words. A 429 with any other code — the customization lock (`0x80071151`
+// "Cannot start the requested operation [Publish] because there is another [WorkflowSetState] running…", and the other lock codes
+// lib/retry-policy.js lists) — or with none is not one of these.
+const SERVICE_PROTECTION_CODES = Object.freeze(new Set(['0x80072322', '0x80072321', '0x80072326']));
// The longest `Retry-After` honoured in full. Dataverse's service protection limits answer 429 with
// `Retry-After` in seconds and ask the caller to wait that long; a request sent sooner is refused again
// and spends one of the few attempts. The cap keeps a large value from stalling a build or a teardown
@@ -104,6 +127,21 @@ function isSqlDeadlockVictim(res) {
return SQL_DEADLOCK_VICTIM.test(typeof res.body === 'string' ? res.body : JSON.stringify(res.body));
}
+/**
+ * True when a raw transport response is a refusal by the service protection limits: HTTP 429 whose OData error code — the answer is
+ * `{"error":{"code":"0x80072322","message":"Number of requests exceeded the limit of 6000 over time window of 300 seconds."}}` — is one of
+ * SERVICE_PROTECTION_CODES. A body that is not that JSON (an HTML page from a gateway, a code that is not a string) is not one.
+ */
+function isServiceProtectionRefusal(res) {
+ if (!res || res.statusCode !== 429) return false;
+ let body = res.body;
+ if (typeof body === 'string') {
+ try { body = JSON.parse(body); } catch { return false; }
+ }
+ const code = body && typeof body === 'object' && body.error && typeof body.error === 'object' ? body.error.code : undefined;
+ return typeof code === 'string' && SERVICE_PROTECTION_CODES.has(code.toLowerCase());
+}
+
/**
* The operations a `$batch` REQUEST carries, as `{ method, url, ifMatch }` in the order sent, read from the request lines
* (`<METHOD> <url> HTTP/1.1`) the SDK renders — see isConditionalDeleteBatch and isColumnCreateBatch for the shapes. `ifMatch` is the
@@ -602,7 +640,7 @@ function createAzHttpClient(orgUrl, deps = {}) {
const random = deps.random || Math.random;
const now = deps.now || Date.now;
// Transient HTTP statuses worth retrying with backoff — throttling, gateway hiccups, and
- // SQL deadlocks (Dataverse surfaces deadlock 1205 as a 500 from PublishXml under load).
+ // SQL deadlocks (Dataverse surfaces deadlock 1205 as a 500 under load). A publish is the exception (`publishOnce`, in `call`).
//
// ⚠ 502/503/504 come from an INTERMEDIARY, so the write behind them may have COMMITTED — and this
// retry then re-sends it. For a CONDITIONAL write (every SDK form, view, chart, dashboard and app
@@ -617,8 +655,12 @@ function createAzHttpClient(orgUrl, deps = {}) {
// policy stays.
// It is NOT safe for a write whose failure path must know whether the first attempt landed: the
// SDK's business-process-flow `update`/`delete` settle an ambiguous deactivate by re-reading the
- // row, and this retry pre-empts that. Nothing in this plugin issues those today; exempt such
- // writes from the retry before anything does.
+ // row, and this retry pre-empts that. The plugin reaches neither cycle: its stage edits of a flow it
+ // reuses (applyBpfStages, lib/sdk-build.js) are the SDK's in-place writes — an Active flow's ONE
+ // `$batch` change set of PATCHes on `/workflows(<id>)` under `If-Match`, which this client sends once
+ // (a `$batch`, below) and the SDK re-sends itself while the customization lock refuses it, bound by
+ // the same `If-Match`; a Draft flow's one PATCH under `If-Match` — and teardown deactivates and deletes a
+ // flow's row through the record surface (lib/sdk-teardown.js). Exempt such writes from the retry before anything issues them.
const TRANSIENT = new Set([429, 500, 502, 503, 504]);
// How long to wait for an answer before giving up. A WRITE gets far longer than a read, because a
// write we stop waiting for is not a failed write — the server may still be executing it, so its
@@ -739,6 +781,20 @@ function createAzHttpClient(orgUrl, deps = {}) {
// the caller's to look up. The exceptions of a record DELETE and a `$batch` stay what they were for every request the caller does not name.
const once = sendOnce(method_, url) === true;
const noRetry = recordDelete || isBatch || once;
+ // A PUBLISH (`POST …/PublishXml`, `…/PublishAllXml`) is sent ONCE on a 5xx, on a transport failure and on a 429 — but for the two answers that prove
+ // the platform never started it: a 401 (refused before it ran: the token is refreshed and the publish sent again, as any request is) and a 429 of the
+ // service protection limits (isServiceProtectionRefusal: waited out like any throttled request, inside the run's budget when the client has one).
+ // MEASURED on a test environment (four probe runs, 2026-10-20, the customization lock held by six concurrent business-process-flow activations): a
+ // publish the lock refused — HTTP 429 `0x80071151` "Cannot start the requested operation [Publish] because there is another [WorkflowSetState] running…",
+ // answered after 33-66 s — is NOT shown to change nothing. Of 7 web-resource writes whose publish it refused at least once, a later ACCEPTED publish
+ // published the OLD content in 4; an accepted re-send answered 204 while publishing the old content; and an app was seen published right after its
+ // publish was refused. So a re-send turns a loud refusal into a quiet stale publish — which the SDK reads back for a web resource (WEB_RESOURCE_UNVERIFIED)
+ // and for an app, form, view or dashboard nothing does — and it is the SDK's rule that a publish is never re-sent but as a SQL deadlock victim, which
+ // this client's re-send underneath it defeated. A deadlock victim (rolled back) is re-sent by the layer above: see SQL_DEADLOCK_VICTIM. A 5xx from a
+ // gateway (502, 503, 504) may sit in front of a publish that ran, and a transport failure in front of one that is still running: neither is re-sent.
+ // In 15 live builds, no-op rebuilds and teardowns of the release before this one, the plugin sent 30 publishes and none was answered 429 or 5xx: this
+ // bites only under real contention.
+ const publishOnce = !once && isPublishRequest(method_, url);
const isWrite = method_ !== 'GET';
// A CONDITIONAL write that got NO answer (a timeout or a dropped connection) is never re-sent.
// It may still commit — and if it does, the re-send carries a token the first attempt already
@@ -808,7 +864,7 @@ function createAzHttpClient(orgUrl, deps = {}) {
if (res.incompleteResponse && method_ === 'POST') {
throw transportError(res, `Request failed: ${scrubText(res.error)} — the server had already answered ${res.statusCode}, so this POST may have been applied; it was not re-sent. Re-run to reconcile.`);
}
- if (last || noRetry || !isTransientTransportFailure(res.error, res.code)) throw transportError(res, `Request failed: ${scrubText(res.error)}`);
+ if (last || noRetry || publishOnce || !isTransientTransportFailure(res.error, res.code)) throw transportError(res, `Request failed: ${scrubText(res.error)}`);
await sleep(backoffMs(attempt));
continue;
}
@@ -822,7 +878,7 @@ function createAzHttpClient(orgUrl, deps = {}) {
}
continue;
}
- if (TRANSIENT.has(res.statusCode) && !last && !noRetry) {
+ if (TRANSIENT.has(res.statusCode) && !last && !noRetry && (!publishOnce || isServiceProtectionRefusal(res))) {
// A throttle (HTTP 429) is waited out inside the run's budget when the client has one, and handed back as it came when the wait does not fit (waitOutThrottle). What else is re-sent here — a customization lock or a deadlock
// victim (500), a gateway (502, 503, 504) — is not throttling, and keeps its own schedule.
if (throttle && res.statusCode === 429) {
@@ -908,4 +964,4 @@ function createAzHttpClient(orgUrl, deps = {}) {
};
}
-module.exports = { createAzHttpClient, SQL_DEADLOCK_VICTIM, isBatchDeadlockVictim, isBatchThrottled, completeBatchStatus, batchRetryAfterMs, isConditionalDeleteBatch, isColumnCreateBatch, isTransientTransportFailure, TRANSIENT_TRANSPORT_CODES, retryAfterMs, throttleBackoffMs, RETRY_AFTER_CAP_MS, scrub, scrubAnswer, scrubBearer, MIN_SCRUBBED_TOKEN_LENGTH };
+module.exports = { createAzHttpClient, SQL_DEADLOCK_VICTIM, DEADLOCK_RESENDS, isSqlDeadlockVictim, isBatchDeadlockVictim, isBatchThrottled, completeBatchStatus, batchRetryAfterMs, isConditionalDeleteBatch, isColumnCreateBatch, isTransientTransportFailure, TRANSIENT_TRANSPORT_CODES, SERVICE_PROTECTION_CODES, isServiceProtectionRefusal, retryAfterMs, throttleBackoffMs, RETRY_AFTER_CAP_MS, scrub, scrubAnswer, scrubBearer, MIN_SCRUBBED_TOKEN_LENGTH };
diff --git a/plugins/pcf/scripts/vendor/PROVENANCE.json b/plugins/pcf/scripts/vendor/PROVENANCE.json
index 8f172d545..8e3124815 100644
--- a/plugins/pcf/scripts/vendor/PROVENANCE.json
+++ b/plugins/pcf/scripts/vendor/PROVENANCE.json
@@ -1,13 +1,13 @@
{
- "commit": "d603c7996f7918da669b3ef16c6fa63f5b9fb7a0",
+ "commit": "a3443479b88ec538be2e74293fa92230c4ef1aab",
"dirtySdkPackage": 0,
- "libBuiltAt": "2026-10-20T01:32:45.044Z",
- "newestSrcAt": "2026-10-20T01:31:52.361Z",
+ "libBuiltAt": "2026-10-20T20:18:04.982Z",
+ "newestSrcAt": "2026-10-20T19:21:12.668Z",
"libIsStale": false,
"nostub": false,
"esbuildVersion": "0.28.1",
- "nodeVersion": "v20.20.2",
- "builtAt": "2026-10-20T01:34:40.388Z",
- "bundleSha256": "16246ee08fe653de994989f08fbf4a8e243f4d3cbe961a7c89c40be37bef1a88",
- "bundleBytes": 1020302
+ "nodeVersion": "v24.21.0",
+ "builtAt": "2026-10-20T20:20:30.581Z",
+ "bundleSha256": "eebd70a2a7f6e12e45d18744640fd803479a738bc936b8e0dce1a9f97a0a4f8c",
+ "bundleBytes": 1029451
}
diff --git a/plugins/pcf/scripts/vendor/cds-maker-sdk.cjs b/plugins/pcf/scripts/vendor/cds-maker-sdk.cjs
index c8ac6679b..6f798fd8d 100644
--- a/plugins/pcf/scripts/vendor/cds-maker-sdk.cjs
+++ b/plugins/pcf/scripts/vendor/cds-maker-sdk.cjs
@@ -25,33 +25,33 @@
}
globalThis.document=globalThis.document||globalThis.window.document;
})();
-var AU=Object.create;var bc=Object.defineProperty;var SU=Object.getOwnPropertyDescriptor;var NU=Object.getOwnPropertyNames;var _U=Object.getPrototypeOf,TU=Object.prototype.hasOwnProperty;var k=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var v=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Hr=(e,t)=>{for(var r in t)bc(e,r,{get:t[r],enumerable:!0})},yc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of NU(t))!TU.call(e,i)&&i!==r&&bc(e,i,{get:()=>t[i],enumerable:!(n=SU(t,i))||n.enumerable});return e},Ji=(e,t,r)=>(yc(e,t,"default"),r&&yc(r,t,"default")),Ee=(e,t,r)=>(r=e!=null?AU(_U(e)):{},yc(t||!e||!e.__esModule?bc(r,"default",{value:e,enumerable:!0}):r,e)),Fr=e=>yc(bc({},"__esModule",{value:!0}),e);var Yi=v(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.DateTimeBehavior=T.PrecisionSource=T.StringFormatName=T.SourceType=T.ImeMode=T.SolutionEntityTypeCodeExtToComponentTypeCode=T.SolutionComponentTypeCodeToEntityTypeCodeExt=T.SolutionComponentVirtualAttributeSubtype=T.EntityTypeCode=T.SolutionComponentTypeCodeExt=T.RootComponentBehavior=T.SolutionComponentTypeCode=T.EntityKeyIndexStatus=T.ViewStateCode=T.ViewStatusCode=T.RelationshipSecurityTypes=T.CascadeType=T.RelationshipTypeExt=T.RelationshipType=T.AppSubType=T.BusinessProcessType=T.WorkflowCategory=T.WorkflowScope=T.WorkflowTypeCode=T.StatusCodeEnabledDisabled=T.StateCodeEnabledDisabled=T.StatusCode=T.StateCode=T.OptionSetType=T.AttributeTypeCodeNum=T.AttributeFormatName=T.AttributeFormatCode=T.AttributeTypeName=T.AttributeTypeCode=T.PluginSourceType=T.AuthType=T.PluginIsolationMode=T.ComponentState=T.ChartType=T.ChartsType=T.ViewType=T.AttributeType=T.ActivationState=T.FormPresentation=T.FormType=T.TableTypeCode=T.TableTypes=T.ActivityTypeMask=T.PrincipalType=T.OwnershipTypes=void 0;T.QueryType=T.KnownCustomSolutionComponentEntitySetName=T.TeamTypeEnum=T.EnvironmentVariableDefinitionTypeEnum=T.ConnectorTypeEnum=T.RoleInheritance=T.DefaultRoleTemplates=T.DeleteDependencyErrorCode=T.ServiceEndpointConnectionMode=T.ServiceEndpointContract=T.ServiceNamespaceFormat=T.ConnectionRoleCategory=T.ReportTypeCode=T.SdkMessageProcessingMode=T.SupportedDeployment=T.SdkMessageProcessingStage=T.WebResourceTypeCode=T.IntegerFormat=T.DateTimeFormat=void 0;var Yv;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(Yv||(T.OwnershipTypes=Yv={}));var Qv;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(Qv||(T.PrincipalType=Qv={}));var Xv;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(Xv||(T.ActivityTypeMask=Xv={}));var Zv;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(Zv||(T.TableTypes=Zv={}));var ew;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(ew||(T.TableTypeCode=ew={}));var tw;(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"})(tw||(T.FormType=tw={}));var rw;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(rw||(T.FormPresentation=rw={}));var nw;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(nw||(T.ActivationState=nw={}));var iw;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(iw||(T.AttributeType=iw={}));var ow;(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"})(ow||(T.ViewType=ow={}));var aw;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(aw||(T.ChartsType=aw={}));var sw;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(sw||(T.ChartType=sw={}));var lw;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(lw||(T.ComponentState=lw={}));var uw;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(uw||(T.PluginIsolationMode=uw={}));var cw;(function(e){e[e.BasicAuth=0]="BasicAuth"})(cw||(T.AuthType=cw={}));var dw;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(dw||(T.PluginSourceType=dw={}));var fw;(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"})(fw||(T.AttributeTypeCode=fw={}));var pw;(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"})(pw||(T.AttributeTypeName=pw={}));var mw;(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"})(mw||(T.AttributeFormatCode=mw={}));var hw;(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"})(hw||(T.AttributeFormatName=hw={}));var gw;(function(e){e[e.Boolean=0]="Boolean",e[e.Customer=1]="Customer",e[e.DateTime=2]="DateTime",e[e.Decimal=3]="Decimal",e[e.Double=4]="Double",e[e.Integer=5]="Integer",e[e.Lookup=6]="Lookup",e[e.Memo=7]="Memo",e[e.Money=8]="Money",e[e.Owner=9]="Owner",e[e.PartyList=10]="PartyList",e[e.Picklist=11]="Picklist",e[e.State=12]="State",e[e.Status=13]="Status",e[e.String=14]="String",e[e.Uniqueidentifier=15]="Uniqueidentifier",e[e.CalendarRules=16]="CalendarRules",e[e.Virtual=17]="Virtual",e[e.BigInt=18]="BigInt",e[e.ManagedProperty=19]="ManagedProperty",e[e.EntityName=20]="EntityName"})(gw||(T.AttributeTypeCodeNum=gw={}));var yw;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(yw||(T.OptionSetType=yw={}));var bw;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(bw||(T.StateCode=bw={}));var vw;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(vw||(T.StatusCode=vw={}));var ww;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(ww||(T.StateCodeEnabledDisabled=ww={}));var Cw;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(Cw||(T.StatusCodeEnabledDisabled=Cw={}));var Ew;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(Ew||(T.WorkflowTypeCode=Ew={}));var Aw;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(Aw||(T.WorkflowScope=Aw={}));var Sw;(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"})(Sw||(T.WorkflowCategory=Sw={}));var Nw;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(Nw||(T.BusinessProcessType=Nw={}));var _w;(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"})(_w||(T.AppSubType=_w={}));var Tw;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Tw||(T.RelationshipType=Tw={}));var Dw;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Dw||(T.RelationshipTypeExt=Dw={}));var Iw;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(Iw||(T.CascadeType=Iw={}));var Ow;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(Ow||(T.RelationshipSecurityTypes=Ow={}));var Pw;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(Pw||(T.ViewStatusCode=Pw={}));var Rw;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(Rw||(T.ViewStateCode=Rw={}));var Lw;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(Lw||(T.EntityKeyIndexStatus=Lw={}));var kw;(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"})(kw||(T.SolutionComponentTypeCode=kw={}));var $w;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})($w||(T.RootComponentBehavior=$w={}));var vc;(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"})(vc||(T.SolutionComponentTypeCodeExt=vc={}));var wc;(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"})(wc||(T.EntityTypeCode=wc={}));var xw;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(xw||(T.SolutionComponentVirtualAttributeSubtype=xw={}));function DU(e){let t=vc[e];return wc[t]}T.SolutionComponentTypeCodeToEntityTypeCodeExt=DU;function IU(e){let t=wc[e];return vc[t]}T.SolutionEntityTypeCodeExtToComponentTypeCode=IU;var Fw;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(Fw||(T.ImeMode=Fw={}));var Mw;(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"})(Mw||(T.SourceType=Mw={}));var Uw;(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"})(Uw||(T.StringFormatName=Uw={}));var Bw;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(Bw||(T.PrecisionSource=Bw={}));var qw;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(qw||(T.DateTimeBehavior=qw={}));var Vw;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(Vw||(T.DateTimeFormat=Vw={}));var Gw;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(Gw||(T.IntegerFormat=Gw={}));var Ww;(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"})(Ww||(T.WebResourceTypeCode=Ww={}));var zw;(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"})(zw||(T.SdkMessageProcessingStage=zw={}));var jw;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(jw||(T.SupportedDeployment=jw={}));var Hw;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(Hw||(T.SdkMessageProcessingMode=Hw={}));var Kw;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(Kw||(T.ReportTypeCode=Kw={}));var Jw;(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"})(Jw||(T.ConnectionRoleCategory=Jw={}));var Yw;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(Yw||(T.ServiceNamespaceFormat=Yw={}));var Qw;(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"})(Qw||(T.ServiceEndpointContract=Qw={}));var Xw;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(Xw||(T.ServiceEndpointConnectionMode=Xw={}));var Zw;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(Zw||(T.DeleteDependencyErrorCode=Zw={}));var eC;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(eC||(T.DefaultRoleTemplates=eC={}));var tC;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(tC||(T.RoleInheritance=tC={}));var rC;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(rC||(T.ConnectorTypeEnum=rC={}));var nC;(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"})(nC||(T.EnvironmentVariableDefinitionTypeEnum=nC={}));var iC;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(iC||(T.TeamTypeEnum=iC={}));var oC;(function(e){e.Bots="bots"})(oC||(T.KnownCustomSolutionComponentEntitySetName=oC={}));var aC;(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"})(aC||(T.QueryType=aC={}))});var Q=v(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.IncompatibleWorkspaceError=X.PathTraversalError=X.AmbiguousArtifactError=X.JsonPointerError=X.NotImplementedError=X.WorkspaceOrgMismatchError=X.WorkspaceNotInitializedError=X.attachCause=X.ConnectionError=X.VersionConflictError=X.LocalEditsWouldBeLostError=X.StaleArtifactError=X.InvalidArgumentError=X.ValidationError=X.PathNotFoundError=X.ArtifactNotFoundError=X.readCleanupWarnings=X.withCleanupWarnings=X.readPartialEnrichment=X.withPartialEnrichment=X.readPartialTokens=X.withPartialTokens=X.SdkError=void 0;var wt=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};X.SdkError=wt;var sC=Symbol.for("cds-maker-sdk.partialWriteTokens");function OU(e,t){return typeof e=="object"&&e!==null&&(e[sC]=t),e}X.withPartialTokens=OU;function PU(e){return wm(e,sC)}X.readPartialTokens=PU;function wm(e,t){let r=e;for(let n=0;r&&typeof r=="object"&&n<8;n++){let i=r[t];if(i&&typeof i=="object")return i;r=r.cause}}var lC=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function RU(e,t){return typeof e=="object"&&e!==null&&(e[lC]=t),e}X.withPartialEnrichment=RU;function LU(e){return wm(e,lC)}X.readPartialEnrichment=LU;var im=Symbol.for("cds-maker-sdk.cleanupWarnings");function kU(e,t){if(typeof e=="object"&&e!==null&&t.length>0){let r=e,n=r[im];r[im]=[...Array.isArray(n)?n:[],...t]}return e}X.withCleanupWarnings=kU;function $U(e){let t=wm(e,im);return t?[...t]:void 0}X.readCleanupWarnings=$U;var om=class extends wt{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};X.ArtifactNotFoundError=om;var am=class extends wt{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};X.PathNotFoundError=am;var sm=class extends wt{constructor(t,r,n,i){var o,a,s,l;let u=Array.isArray(n)?n:[{pointer:n,rule:i??"invalid",message:i??"invalid"}];super("VALIDATION_ERROR",`Validation failed for ${t}/${r}:
+var kU=Object.create;var Nc=Object.defineProperty;var LU=Object.getOwnPropertyDescriptor;var $U=Object.getOwnPropertyNames;var xU=Object.getPrototypeOf,FU=Object.prototype.hasOwnProperty;var L=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var v=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Jr=(e,t)=>{for(var r in t)Nc(e,r,{get:t[r],enumerable:!0})},Sc=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of $U(t))!FU.call(e,i)&&i!==r&&Nc(e,i,{get:()=>t[i],enumerable:!(n=LU(t,i))||n.enumerable});return e},Yi=(e,t,r)=>(Sc(e,t,"default"),r&&Sc(r,t,"default")),Ae=(e,t,r)=>(r=e!=null?kU(xU(e)):{},Sc(t||!e||!e.__esModule?Nc(r,"default",{value:e,enumerable:!0}):r,e)),Br=e=>Sc(Nc({},"__esModule",{value:!0}),e);var Qi=v(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.DateTimeBehavior=T.PrecisionSource=T.StringFormatName=T.SourceType=T.ImeMode=T.SolutionEntityTypeCodeExtToComponentTypeCode=T.SolutionComponentTypeCodeToEntityTypeCodeExt=T.SolutionComponentVirtualAttributeSubtype=T.EntityTypeCode=T.SolutionComponentTypeCodeExt=T.RootComponentBehavior=T.SolutionComponentTypeCode=T.EntityKeyIndexStatus=T.ViewStateCode=T.ViewStatusCode=T.RelationshipSecurityTypes=T.CascadeType=T.RelationshipTypeExt=T.RelationshipType=T.AppSubType=T.BusinessProcessType=T.WorkflowCategory=T.WorkflowScope=T.WorkflowTypeCode=T.StatusCodeEnabledDisabled=T.StateCodeEnabledDisabled=T.StatusCode=T.StateCode=T.OptionSetType=T.AttributeTypeCodeNum=T.AttributeFormatName=T.AttributeFormatCode=T.AttributeTypeName=T.AttributeTypeCode=T.PluginSourceType=T.AuthType=T.PluginIsolationMode=T.ComponentState=T.ChartType=T.ChartsType=T.ViewType=T.AttributeType=T.ActivationState=T.FormPresentation=T.FormType=T.TableTypeCode=T.TableTypes=T.ActivityTypeMask=T.PrincipalType=T.OwnershipTypes=void 0;T.QueryType=T.KnownCustomSolutionComponentEntitySetName=T.TeamTypeEnum=T.EnvironmentVariableDefinitionTypeEnum=T.ConnectorTypeEnum=T.RoleInheritance=T.DefaultRoleTemplates=T.DeleteDependencyErrorCode=T.ServiceEndpointConnectionMode=T.ServiceEndpointContract=T.ServiceNamespaceFormat=T.ConnectionRoleCategory=T.ReportTypeCode=T.SdkMessageProcessingMode=T.SupportedDeployment=T.SdkMessageProcessingStage=T.WebResourceTypeCode=T.IntegerFormat=T.DateTimeFormat=void 0;var ow;(function(e){e.None="None",e.UserOwned="UserOwned",e.TeamOwned="TeamOwned",e.BusinessOwned="BusinessOwned",e.OrganizationOwned="OrganizationOwned",e.BusinessParented="BusinessParented",e.Filtered="Filtered"})(ow||(T.OwnershipTypes=ow={}));var aw;(function(e){e.User="Microsoft.Dynamics.CRM.systemuser",e.Team="Microsoft.Dynamics.CRM.team"})(aw||(T.PrincipalType=aw={}));var sw;(function(e){e[e.DoNotDisplayInActivityMenus=0]="DoNotDisplayInActivityMenus",e[e.DisplayInActivityMenus=1]="DisplayInActivityMenus"})(sw||(T.ActivityTypeMask=sw={}));var lw;(function(e){e.Activity="Activity",e.Virtual="Virtual",e.Standard="Standard",e.Elastic="Elastic"})(lw||(T.TableTypes=lw={}));var uw;(function(e){e.Standard="Standard",e.Virtual="Virtual",e.Elastic="Elastic"})(uw||(T.TableTypeCode=uw={}));var cw;(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"})(cw||(T.FormType=cw={}));var dw;(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(dw||(T.FormPresentation=dw={}));var fw;(function(e){e[e.Inactive=0]="Inactive",e[e.Active=1]="Active"})(fw||(T.ActivationState=fw={}));var pw;(function(e){e[e.String=0]="String",e[e.Number=1]="Number",e[e.Picklist=2]="Picklist"})(pw||(T.AttributeType=pw={}));var mw;(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"})(mw||(T.ViewType=mw={}));var hw;(function(e){e[e.ASPChart=0]="ASPChart",e[e.PowerBI=1]="PowerBI"})(hw||(T.ChartsType=hw={}));var gw;(function(e){e[e.DataAndInteractionCentric=0]="DataAndInteractionCentric",e[e.InteractionCentric=1]="InteractionCentric"})(gw||(T.ChartType=gw={}));var yw;(function(e){e[e.Published=0]="Published",e[e.Unpublished=1]="Unpublished",e[e.Deleted=2]="Deleted",e[e.DeletedUnpublished=3]="DeletedUnpublished"})(yw||(T.ComponentState=yw={}));var bw;(function(e){e[e.None=1]="None",e[e.Sandbox=2]="Sandbox",e[e.External=3]="External"})(bw||(T.PluginIsolationMode=bw={}));var vw;(function(e){e[e.BasicAuth=0]="BasicAuth"})(vw||(T.AuthType=vw={}));var ww;(function(e){e[e.Database=0]="Database",e[e.Disk=1]="Disk",e[e.Normal=2]="Normal",e[e.AzureWebApp=3]="AzureWebApp"})(ww||(T.PluginSourceType=ww={}));var Cw;(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"})(Cw||(T.AttributeTypeCode=Cw={}));var Ew;(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"})(Ew||(T.AttributeTypeName=Ew={}));var Aw;(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"})(Aw||(T.AttributeFormatCode=Aw={}));var Sw;(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"})(Sw||(T.AttributeFormatName=Sw={}));var Nw;(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"})(Nw||(T.AttributeTypeCodeNum=Nw={}));var _w;(function(e){e.Picklist="Picklist",e.State="State",e.Status="Status",e.Boolean="Boolean"})(_w||(T.OptionSetType=_w={}));var Tw;(function(e){e[e.Draft=0]="Draft",e[e.Activated=1]="Activated"})(Tw||(T.StateCode=Tw={}));var Dw;(function(e){e[e.Draft=1]="Draft",e[e.Activated=2]="Activated"})(Dw||(T.StatusCode=Dw={}));var Iw;(function(e){e[e.Enabled=0]="Enabled",e[e.Disabled=1]="Disabled"})(Iw||(T.StateCodeEnabledDisabled=Iw={}));var Ow;(function(e){e[e.Enabled=1]="Enabled",e[e.Disabled=2]="Disabled"})(Ow||(T.StatusCodeEnabledDisabled=Ow={}));var Pw;(function(e){e[e.Definition=1]="Definition",e[e.Activation=2]="Activation",e[e.Template=3]="Template"})(Pw||(T.WorkflowTypeCode=Pw={}));var Rw;(function(e){e[e.User=1]="User",e[e.BusinessUnit=2]="BusinessUnit",e[e.ParentChildBusinessUnit=3]="ParentChildBusinessUnit",e[e.Organization=4]="Organization"})(Rw||(T.WorkflowScope=Rw={}));var kw;(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"})(kw||(T.WorkflowCategory=kw={}));var Lw;(function(e){e[e.None=-1]="None",e[e.BusinessFlow=0]="BusinessFlow",e[e.TaskFlow=1]="TaskFlow"})(Lw||(T.BusinessProcessType=Lw={}));var $w;(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"})($w||(T.AppSubType=$w={}));var xw;(function(e){e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(xw||(T.RelationshipType=xw={}));var Fw;(function(e){e.ManyToOneRelationship="ManyToOneRelationship",e.OneToManyRelationship="OneToManyRelationship",e.ManyToManyRelationship="ManyToManyRelationship"})(Fw||(T.RelationshipTypeExt=Fw={}));var Mw;(function(e){e.NoCascade="NoCascade",e.Cascade="Cascade",e.Active="Active",e.UserOwned="UserOwned",e.RemoveLink="RemoveLink",e.Restrict="Restrict"})(Mw||(T.CascadeType=Mw={}));var Uw;(function(e){e.None="None",e.Append="Append",e.ParentChild="ParentChild",e.Pointer="Pointer",e.Inheritance="Inheritance"})(Uw||(T.RelationshipSecurityTypes=Uw={}));var Bw;(function(e){e[e.Active=1]="Active",e[e.Inactive=2]="Inactive"})(Bw||(T.ViewStatusCode=Bw={}));var qw;(function(e){e[e.Active=0]="Active",e[e.Inactive=1]="Inactive"})(qw||(T.ViewStateCode=qw={}));var Vw;(function(e){e.Active="Active",e.Failed="Failed",e.InProgress="InProgress",e.Pending="Pending"})(Vw||(T.EntityKeyIndexStatus=Vw={}));var Gw;(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"})(Gw||(T.SolutionComponentTypeCode=Gw={}));var Ww;(function(e){e[e.IncludeSubcomponents=0]="IncludeSubcomponents",e[e.DoNotIncludeSubcomponents=1]="DoNotIncludeSubcomponents",e[e.IncludeAsShellOnly=2]="IncludeAsShellOnly"})(Ww||(T.RootComponentBehavior=Ww={}));var _c;(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"})(_c||(T.SolutionComponentTypeCodeExt=_c={}));var Tc;(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"})(Tc||(T.EntityTypeCode=Tc={}));var zw;(function(e){e.MultiSelectPicklist="MultiSelectPicklist",e.File="File",e.Image="Image"})(zw||(T.SolutionComponentVirtualAttributeSubtype=zw={}));function MU(e){let t=_c[e];return Tc[t]}T.SolutionComponentTypeCodeToEntityTypeCodeExt=MU;function UU(e){let t=Tc[e];return _c[t]}T.SolutionEntityTypeCodeExtToComponentTypeCode=UU;var jw;(function(e){e.Active="Active",e.Auto="Auto",e.Disabled="Disabled",e.Inactive="Inactive"})(jw||(T.ImeMode=jw={}));var Hw;(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"})(Hw||(T.SourceType=Hw={}));var Kw;(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"})(Kw||(T.StringFormatName=Kw={}));var Jw;(function(e){e[e.PrecisionProperty=0]="PrecisionProperty",e[e.Organization=1]="Organization",e[e.TransactionCurrency=2]="TransactionCurrency"})(Jw||(T.PrecisionSource=Jw={}));var Yw;(function(e){e.UserLocal="UserLocal",e.DateOnly="DateOnly",e.TimeZoneIndependent="TimeZoneIndependent"})(Yw||(T.DateTimeBehavior=Yw={}));var Qw;(function(e){e.DateOnly="DateOnly",e.DateAndTime="DateAndTime"})(Qw||(T.DateTimeFormat=Qw={}));var Xw;(function(e){e.None="None",e.Duration="Duration",e.TimeZone="TimeZone",e.Language="Language",e.Locale="Locale"})(Xw||(T.IntegerFormat=Xw={}));var Zw;(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"})(Zw||(T.WebResourceTypeCode=Zw={}));var eC;(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"})(eC||(T.SdkMessageProcessingStage=eC={}));var tC;(function(e){e[e.ServerOnly=0]="ServerOnly",e[e.OutlookClientOnly=1]="OutlookClientOnly",e[e.Both=2]="Both"})(tC||(T.SupportedDeployment=tC={}));var rC;(function(e){e[e.Synchronous=0]="Synchronous",e[e.Asynchronous=1]="Asynchronous"})(rC||(T.SdkMessageProcessingMode=rC={}));var nC;(function(e){e[e.ReportingServicesReport=1]="ReportingServicesReport",e[e.OtherReport=2]="OtherReport",e[e.LinkedReport=3]="LinkedReport"})(nC||(T.ReportTypeCode=nC={}));var iC;(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"})(iC||(T.ConnectionRoleCategory=iC={}));var oC;(function(e){e[e.Name=1]="Name",e[e.Address=2]="Address"})(oC||(T.ServiceNamespaceFormat=oC={}));var aC;(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"})(aC||(T.ServiceEndpointContract=aC={}));var sC;(function(e){e[e.Normal=1]="Normal",e[e.Federated=2]="Federated"})(sC||(T.ServiceEndpointConnectionMode=sC={}));var lC;(function(e){e.CannotDeleteInUseComponent="0x8004f01f",e.CannotDeleteInUseAttribute="0x80048418",e.CannotDeleteInUseOptionSet="0x80048417",e.CannotDeleteInUseEntity="0x80048420",e.CannotUninstallWithDependencies="0x8004F01D"})(lC||(T.DeleteDependencyErrorCode=lC={}));var uC;(function(e){e.SystemAdministrator="627090FF-40A3-4053-8790-584EDC5BE201",e.SystemCustomizer="119F245C-3CC8-4B62-B31C-D1A046CED15D"})(uC||(T.DefaultRoleTemplates=uC={}));var cC;(function(e){e[e.DefaultTeamPrivilege=0]="DefaultTeamPrivilege",e[e.DirectUserAndTeamPrivilege=1]="DirectUserAndTeamPrivilege"})(cC||(T.RoleInheritance=cC={}));var dC;(function(e){e[e.NotSpecified=0]="NotSpecified",e[e.CustomConnector=1]="CustomConnector"})(dC||(T.ConnectorTypeEnum=dC={}));var fC;(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"})(fC||(T.EnvironmentVariableDefinitionTypeEnum=fC={}));var pC;(function(e){e[e.Owner=0]="Owner",e[e.Access=1]="Access",e[e.AADSecurityGroup=2]="AADSecurityGroup",e[e.AADOfficeGroup=3]="AADOfficeGroup"})(pC||(T.TeamTypeEnum=pC={}));var mC;(function(e){e.Bots="bots"})(mC||(T.KnownCustomSolutionComponentEntitySetName=mC={}));var hC;(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"})(hC||(T.QueryType=hC={}))});var Q=v(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.IncompatibleWorkspaceError=X.PathTraversalError=X.AmbiguousArtifactError=X.JsonPointerError=X.NotImplementedError=X.WorkspaceOrgMismatchError=X.WorkspaceNotInitializedError=X.attachCause=X.WebResourceUnverifiedError=X.ConnectionError=X.VersionConflictError=X.LocalEditsWouldBeLostError=X.StaleArtifactError=X.InvalidArgumentError=X.ValidationError=X.PathNotFoundError=X.ArtifactNotFoundError=X.readCleanupWarnings=X.withCleanupWarnings=X.readPartialEnrichment=X.withPartialEnrichment=X.readPartialTokens=X.withPartialTokens=X.SdkError=void 0;var dt=class extends Error{constructor(t,r){super(r),this.code=t,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name}};X.SdkError=dt;var gC=Symbol.for("cds-maker-sdk.partialWriteTokens");function BU(e,t){return typeof e=="object"&&e!==null&&(e[gC]=t),e}X.withPartialTokens=BU;function qU(e){return Dm(e,gC)}X.readPartialTokens=qU;function Dm(e,t){let r=e;for(let n=0;r&&typeof r=="object"&&n<8;n++){let i=r[t];if(i&&typeof i=="object")return i;r=r.cause}}var yC=Symbol.for("cds-maker-sdk.partialDefaultViewEnrichment");function VU(e,t){return typeof e=="object"&&e!==null&&(e[yC]=t),e}X.withPartialEnrichment=VU;function GU(e){return Dm(e,yC)}X.readPartialEnrichment=GU;var dm=Symbol.for("cds-maker-sdk.cleanupWarnings");function WU(e,t){if(typeof e=="object"&&e!==null&&t.length>0){let r=e,n=r[dm];r[dm]=[...Array.isArray(n)?n:[],...t]}return e}X.withCleanupWarnings=WU;function zU(e){let t=Dm(e,dm);return t?[...t]:void 0}X.readCleanupWarnings=zU;var fm=class extends dt{constructor(t,r){super("ARTIFACT_NOT_FOUND",`Artifact ${t}/${r} not found in workspace`),this.type=t,this.id=r}};X.ArtifactNotFoundError=fm;var pm=class extends dt{constructor(t,r,n){super("PATH_NOT_FOUND",`Path ${n} not found in ${t}/${r}`),this.type=t,this.id=r,this.pointer=n}};X.PathNotFoundError=pm;var mm=class extends dt{constructor(t,r,n,i){var o,a,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=(a=(o=u[0])===null||o===void 0?void 0:o.pointer)!==null&&a!==void 0?a:"",this.rule=(l=(s=u[0])===null||s===void 0?void 0:s.rule)!==null&&l!==void 0?l:"invalid"}};X.ValidationError=sm;var lm=class extends wt{constructor(t){super("INVALID_ARGUMENT",t)}};X.InvalidArgumentError=lm;var um=class extends wt{constructor(t,r,n,i="revalidated"){super("STALE_ARTIFACT",i==="pushed"?`Cannot apply the edit at ${n} to ${t}/${r}: a push made after this pointer's copy was read replaced the local copy with the record the server holds, which differs from that copy (ids and defaults the SDK filled in at save, a rewrite the platform made on save, or another writer's save), so the pointer may now identify a different node. Read the whole artifact (getArtifact), re-derive the pointer, and retry.`:`Cannot apply the edit at ${n} to ${t}/${r}: the cached copy was stale and the server copy has since changed, so any pointer derived from the old copy may now identify a different node. The local copy has been refreshed \u2014 re-read the artifact, re-derive the pointer, and retry.`),this.type=t,this.id=r,this.pointer=n,this.reason=i}};X.StaleArtifactError=um;var cm=class extends wt{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}};X.LocalEditsWouldBeLostError=cm;var dm=class extends wt{constructor(t,r,n,i,o){super("VERSION_CONFLICT",`Version conflict for ${t}/${r}: local=${n??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.${o?` ${o}`:""}`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i,this.detail=o}};X.VersionConflictError=dm;var fm=class extends wt{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,Object.defineProperty(this,"cause",{value:i,enumerable:!1,writable:!1,configurable:!0})}};X.ConnectionError=fm;function xU(e,t){return typeof e=="object"&&e!==null&&Object.defineProperty(e,"cause",{value:t,enumerable:!1,writable:!0,configurable:!0}),e}X.attachCause=xU;var pm=class extends wt{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};X.WorkspaceNotInitializedError=pm;var mm=class extends wt{constructor(t,r){super("WORKSPACE_ORG_MISMATCH",`This workspace belongs to ${t?`'${t}'`:"no recorded org"}, but this SDK targets '${r}'. Its local copies, baselines and cached metadata are that org's, so nothing was read or written. Use one workspace per org, or call cleanWorkspace() to discard this workspace's contents and bind it to '${r}'.`),this.workspaceInstanceUrl=t,this.instanceUrl=r}};X.WorkspaceOrgMismatchError=mm;var hm=class extends wt{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};X.NotImplementedError=hm;var gm=class extends wt{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};X.JsonPointerError=gm;var ym=class extends wt{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}};X.AmbiguousArtifactError=ym;var bm=class extends wt{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}};X.PathTraversalError=bm;var vm=class extends wt{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}};X.IncompatibleWorkspaceError=vm});var se=v(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.odataQuery=rt.normalizeGuid=rt.createSafeXmlElement=rt.assertNoControlChars=rt.assertODataName=rt.assertXmlName=rt.xmlText=rt.odataPathLiteral=rt.odataLiteral=void 0;var Cc=Q();function uC(e){return String(e??"").replace(/'/g,"''")}rt.odataLiteral=uC;function FU(e){return encodeURIComponent(uC(e))}rt.odataPathLiteral=FU;function MU(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}rt.xmlText=MU;function cC(e,t){let r=String(e??""),n=/^[A-Za-z_][0-9A-Za-z_.-]*$/,i=r.split(":");if(!(i.length<=2&&i.every(a=>n.test(a))&&!/^xmlns/i.test(r)))throw new Cc.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}rt.assertXmlName=cC;function UU(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new Cc.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}rt.assertODataName=UU;function BU(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new Cc.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}rt.assertNoControlChars=BU;function qU(e,t,r){return e.createElement(cC(t,r))}rt.createSafeXmlElement=qU;var VU=/^[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 GU(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!VU.test(n))throw new Cc.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}rt.normalizeGuid=GU;function WU(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}rt.odataQuery=WU});var ye=v(j=>{"use strict";Object.defineProperty(j,"__esModule",{value:!0});j.nowIso=j.isAlreadyDeleted=j.deleteRecord=j.resendAppSearchIndexRace=j.resendDeadlockVictim=j.resendWhile=j.isAppSearchIndexRace=j.namesAppSearchIndexRace=j.isTransactionNotStarted=j.TRANSACTION_NOT_STARTED_CODE=j.LOCK_BACKOFF_MS=j.isConcurrencyLockRefusal=j.CONCURRENCY_LOCK_CODE=j.AMBIGUOUS_WRITE_STATUSES=j.DEADLOCK_BACKOFF_MS=j.isSqlDeadlockVictim=j.ensureSuccess=j.resolveCreatedId=j.requireCreatedId=j.withClientMintedId=j.readCreatedId=j.readRowEtag=j.readEtag=j.requireEtag=j.isVersionToken=j.echoWrite=j.UPDATE_NO_ETAG_CODE=j.VERSION_CONFLICT_CODE=void 0;var Pa=Q(),Ra=se();j.VERSION_CONFLICT_CODE="VERSION_CONFLICT";j.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function zU(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}j.echoWrite=zU;function dC(e){return typeof e=="string"&&e.trim()!==""&&e.trim()!=="*"}j.isVersionToken=dC;function jU(e,t,r){if(!dC(e))throw new Pa.SdkError(j.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${r}': ${e?`the concurrency token held for it ('${e}') is not a version`:"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}j.requireEtag=jU;function fC(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}j.readEtag=fC;async function HU(e,t,r,n){let i=`/${t}(${n})${(0,Ra.odataQuery)([["$select",r]])}`;return fC(Em(await e.get(i),e.apiUrl(i)))}j.readRowEtag=HU;function Cm(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,Ra.normalizeGuid)(n[t],t);let i=(r=e.headers)!==null&&r!==void 0?r:{};for(let o of Object.keys(i))if(o.toLowerCase()==="odata-entityid"){let a=/\(([0-9a-fA-F-]{36})\)/.exec(i[o]);if(a)return(0,Ra.normalizeGuid)(a[1],t)}return null}j.readCreatedId=Cm;function KU(e,t,r){return r?{...e,[t]:(0,Ra.normalizeGuid)(r,t)}:e}j.withClientMintedId=KU;function JU(e,t,r){let n=Cm(e,t);if(!n)throw new Pa.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}j.requireCreatedId=JU;function YU(e,t,r,n){let i=Cm(e,t);if(i)return i;if(n)return(0,Ra.normalizeGuid)(n,t);throw new Pa.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}j.resolveCreatedId=YU;function Em(e,t){if(e.status===412)throw new Pa.SdkError(j.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new Pa.ConnectionError(t,e.status,rB(e.body),e.body);return e}j.ensureSuccess=Em;function pC(e){if(e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/\bSql Number:\s*1205\b/i.test(t)}j.isSqlDeadlockVictim=pC;j.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];j.AMBIGUOUS_WRITE_STATUSES=new Set([408,502,503,504]);j.CONCURRENCY_LOCK_CODE="0x80071151";function QU(e){var t,r;if(e.status!==429)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.CONCURRENCY_LOCK_CODE}j.isConcurrencyLockRefusal=QU;j.LOCK_BACKOFF_MS=[2e3,3e3,...Array.from({length:35},()=>5e3)];j.TRANSACTION_NOT_STARTED_CODE="0x80040251";function XU(e){var t,r;if(e.status!==500)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===j.TRANSACTION_NOT_STARTED_CODE}j.isTransactionNotStarted=XU;var ZU=/(?:^|[^a-z0-9_])AppModule_DVTableSearch_M365AppModuleId(?![a-z0-9_])/i;function mC(e){return ZU.test(e)&&/\bSql Number:\s*547\b/i.test(e)}j.namesAppSearchIndexRace=mC;function hC(e){return e.status!==400||e.body===void 0||e.body===null?!1:mC(typeof e.body=="string"?e.body:JSON.stringify(e.body))}j.isAppSearchIndexRace=hC;async function Am(e,t,r=j.DEADLOCK_BACKOFF_MS){for(let n=0;;n+=1){let i=await t();if(n>=r.length||!e(i))return i;await new Promise(o=>setTimeout(o,r[n]))}}j.resendWhile=Am;function eB(e){return Am(pC,e,j.DEADLOCK_BACKOFF_MS)}j.resendDeadlockVictim=eB;function tB(e){return Am(hC,e,j.DEADLOCK_BACKOFF_MS)}j.resendAppSearchIndexRace=tB;function rB(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 nB(e,t,r,n){let i=(0,Ra.normalizeGuid)(r,"id"),o=`/${t}(${i})`;Em(await e.delete(o,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(o))}j.deleteRecord=nB;function iB(e){return e instanceof Pa.ConnectionError&&e.statusCode===404}j.isAlreadyDeleted=iB;function oB(){return new Date().toISOString()}j.nowIso=oB});var Lt=v(La=>{"use strict";Object.defineProperty(La,"__esModule",{value:!0});La.describeMalformedValue=La.collectPages=void 0;var gC=ye(),Sm=Q();async function aB(e,t,r,n,i){let o=[],a=new Set,s=e.apiUrl(t),l=(0,gC.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new Sm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${Nm(c)}; refusing to return partial results.`);for(let f of c)o.push(f);let d=u?.["@odata.nextLink"];if(d==null)break;if(typeof d!="string"||d.length===0)throw new Sm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${Nm(d)}); cannot follow it, and refusing to return partial results.`);if(a.has(d))throw new Sm.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);a.add(d),s=d,l=(0,gC.ensureSuccess)(await e.getAbsolute(d,i),d)}return o}La.collectPages=aB;function Nm(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}La.describeMalformedValue=Nm});var _m=v(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.assertWorkflowKind=Lo.WORKFLOW_KIND_MISMATCH_CODE=void 0;var Ro=Yi(),sB=Q(),yC=ye(),lB=se();Lo.WORKFLOW_KIND_MISMATCH_CODE="WORKFLOW_KIND_MISMATCH";var bC={[Ro.WorkflowCategory.Workflow]:"classic workflow",[Ro.WorkflowCategory.Dialog]:"dialog",[Ro.WorkflowCategory.BusinessRule]:"business rule",[Ro.WorkflowCategory.Action]:"custom action",[Ro.WorkflowCategory.BusinessProcessFlow]:"business process flow",[Ro.WorkflowCategory.Flow]:"cloud flow",[Ro.WorkflowCategory.UIFlow]:"desktop flow"};async function uB(e,t,r){var n,i;let o=`/workflows(${t})${(0,lB.odataQuery)([["$select","category"]])}`,a=await e.get(o);if(a.status===404)return null;(0,yC.ensureSuccess)(a,e.apiUrl(o));let s=(n=a.body)===null||n===void 0?void 0:n.category,l=typeof s=="number"?s:typeof s=="string"&&s!==""?Number(s):NaN;if(l!==r){let u=Number.isFinite(l)?`a ${(i=bC[l])!==null&&i!==void 0?i:"process"} (category ${l})`:"a process whose category could not be read";throw new sB.SdkError(Lo.WORKFLOW_KIND_MISMATCH_CODE,`Refusing to delete workflow '${t}' as a ${bC[r]}: it is ${u}. Nothing was changed. Check the id.`)}return(0,yC.readEtag)(a)}Lo.assertWorkflowKind=uB});var Dm=v(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.deleteWorkflowResending=Kr.isWorkflowDeleteUnsettled=Kr.failedAfterResend=Kr.WORKFLOW_DELETE_UNSETTLED_CODE=void 0;var ml=Q(),mi=ye(),wC=se();Kr.WORKFLOW_DELETE_UNSETTLED_CODE="WORKFLOW_DELETE_UNSETTLED";var CC=new WeakSet;function Tm(e){return typeof e=="object"&&e!==null&&CC.add(e),e}function cB(e){return typeof e=="object"&&e!==null&&CC.has(e)}Kr.failedAfterResend=cB;function dB(e){return e instanceof ml.SdkError&&e.code===Kr.WORKFLOW_DELETE_UNSETTLED_CODE}Kr.isWorkflowDeleteUnsettled=dB;function fB(e,t){try{(0,mi.ensureSuccess)(e,t)}catch(r){return r}}function pB(e){return(0,mi.isSqlDeadlockVictim)(e)?"lost a SQL deadlock (HTTP 500, Sql Number 1205)":`lost its transaction (HTTP 500 ${mi.TRANSACTION_NOT_STARTED_CODE})`}async function vC(e,t){try{return(await e.get(`/workflows(${t})${(0,wC.odataQuery)([["$select","workflowid"]])}`)).status===404}catch{return!1}}async function mB(e,t,{bindingToken:r,kindName:n,deactivated:i=!1,resendDeadlockVictim:o=!1,ifMatchOnFirst:a=!1}){let s=(0,wC.normalizeGuid)(t,"id");if(a&&!r)throw new ml.InvalidArgumentError(`Refusing to delete ${n} '${s}': its delete must be conditional on a token this operation holds, and it holds none.`);let l=`/workflows(${s})`,u=e.apiUrl(l),c=p=>(0,mi.isTransactionNotStarted)(p)||o&&(0,mi.isSqlDeadlockVictim)(p),d=0,f,m;try{m=await(0,mi.resendWhile)(c,async()=>{d+=1;let p=d>1||a,h=await e.delete(l,p?{headers:{"If-Match":r}}:void 0);return f=f??h,h},r?mi.DEADLOCK_BACKOFF_MS:[])}catch(p){if(p instanceof ml.ConnectionError&&p.statusCode===0&&r&&await vC(e,s))return;throw d>1?Tm(p):p}if(!(d>1&&m.status===404)){if(d>1&&m.status===412){let p=pB(f),h=new ml.SdkError(Kr.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting ${n} '${s}' ${p}, and its re-send was refused (HTTP 412): the row at that id is no longer the version this delete checked \u2014 it was edited, or deleted and re-created at the same id \u2014 so nothing more was deleted. `+(i?"This delete had deactivated the process first and has NOT re-activated it: it MAY be left DISABLED. ":"")+"Read the row before deleting it again.");throw Tm((0,ml.attachCause)(h,fB(f,u)))}if(!(r&&mi.AMBIGUOUS_WRITE_STATUSES.has(m.status)&&await vC(e,s)))try{(0,mi.ensureSuccess)(m,u)}catch(p){throw d>1?Tm(p):p}}}Kr.deleteWorkflowResending=mB});var Im=v(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.businessRuleApi=Un.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=Un.WFOM_API_UNAVAILABLE_CODE=void 0;var Mn=Yi(),hB=Lt(),gB=_m(),yB=Dm(),Vt=ye(),hi=se(),Ac=Q();Un.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";Un.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function EC(e,t,r,n){let i=`/workflows(${wB})/Microsoft.Dynamics.CRM.${t}`;try{return(0,Vt.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new Ac.SdkError(Un.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 bB(e,t){let r=`/workflows(${t})${(0,hi.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,Vt.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function vB(e,t,r){let n=await bB(e,t);if(n===null||n.etag===null)throw new Ac.SdkError(Vt.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 Ac.SdkError(Vt.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 wB="00000000-0000-0000-0000-000000000000",Ec={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},CB="workflowid,name,description,primaryentity,statecode,category,type",EB="category eq 2 and type eq 1";async function AC(e,t,r){var n;if(r==="Draft")return null;let i=(0,hi.normalizeGuid)(t,"workflowid"),o=r==="Active",a={statecode:o?Mn.StateCode.Activated:Mn.StateCode.Draft,statuscode:o?Mn.StatusCode.Activated:Mn.StatusCode.Draft},s=`/workflows(${i})`,l=(0,Vt.ensureSuccess)(await e.patch(s,a,{headers:Ec}),e.apiUrl(s));return(n=(0,Vt.readEtag)(l))!==null&&n!==void 0?n:await hl(e,i)}async function hl(e,t){let r=`/workflows(${t})${(0,hi.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,Vt.readEtag)(n):null}catch{return null}}async function AB(e,t,r){let n=await hl(e,t),i=await r(),o=(0,Vt.readEtag)(i);if(o)return{response:i,etag:o};let a=await hl(e,t);return{response:i,etag:n!==null&&n===a?a:null}}Un.businessRuleApi={async get(e,t){let r=(0,hi.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await AB(e,r,async()=>(0,Vt.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:o}},async list(e,t){let r=[EB];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,hi.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,hi.odataQuery)([["$select",CB],["$filter",r.join(" and ")]])}`;return(await(0,hB.collectPages)(e,n,"listArtifacts('businessRule')")).map(o=>{var a,s;return{type:"businessRule",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){var r;let n=t,i=(0,hi.normalizeGuid)(n.Entity.workflowid,"workflowid"),o=await EC(e,"CreateProcessWithWfomJson",n,Ec),a=(0,Vt.resolveCreatedId)(o,"workflowid","business rule",i),s=null;try{s=await AC(e,a,n.status)}catch(l){try{await(0,Vt.deleteRecord)(e,"workflows",a)}catch{}throw l}return{id:a,etag:(r=s??(0,Vt.readEtag)(o))!==null&&r!==void 0?r:await hl(e,a)}},async update(e,t,r,n){var i,o;let a=r,s=(0,hi.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...Ec,"If-Match":(0,Vt.requireEtag)(n,"business rule",s)},c=await vB(e,s,u["If-Match"]),d=c.statecode===Mn.StateCode.Activated;d&&(0,Vt.ensureSuccess)(await e.patch(l,{statecode:Mn.StateCode.Draft,statuscode:Mn.StatusCode.Draft},{headers:u}),e.apiUrl(l));let f;try{f=await EC(e,"UpdateProcessWithWfomJson",a,u)}catch(p){if(d)try{(0,Vt.ensureSuccess)(await e.patch(l,{statecode:Mn.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:Mn.StatusCode.Activated},{headers:Ec}),e.apiUrl(l))}catch(h){throw new Ac.SdkError(Un.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: ${p instanceof Error?p.message:String(p)}. Restore failure: ${h instanceof Error?h.message:String(h)}`)}throw p}let m=await AC(e,s,a.status);return{id:s,etag:(o=m??(0,Vt.readEtag)(f))!==null&&o!==void 0?o:await hl(e,s)}},async delete(e,t){let r=(0,hi.normalizeGuid)(t,"id"),n=await(0,gB.assertWorkflowKind)(e,r,Mn.WorkflowCategory.BusinessRule);return(0,yB.deleteWorkflowResending)(e,r,{bindingToken:n,kindName:"business rule"})}}});var Jr=v(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.publishBoundEntity=Ct.boundEntityPublishScope=Ct.publishGenPageById=Ct.publishDashboardById=Ct.publishWebResourceById=Ct.publishEntity=Ct.publishAppModule=Ct.publishXml=void 0;var SC=ye(),gl=se(),NC="/PublishXml";async function ka(e,t){(0,SC.ensureSuccess)(await(0,SC.resendDeadlockVictim)(()=>e.post(NC,{ParameterXml:t})),e.apiUrl(NC))}Ct.publishXml=ka;function SB(e,t){return ka(e,`<importexportxml><appmodules><appmodule>${(0,gl.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}Ct.publishAppModule=SB;function _C(e,t){return ka(e,`<importexportxml><entities><entity>${(0,gl.xmlText)(t)}</entity></entities></importexportxml>`)}Ct.publishEntity=_C;function NB(e,t){return ka(e,`<importexportxml><webresources><webresource>${(0,gl.xmlText)(t)}</webresource></webresources></importexportxml>`)}Ct.publishWebResourceById=NB;function _B(e,t){return ka(e,`<importexportxml><dashboards><dashboard>${(0,gl.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}Ct.publishDashboardById=_B;function TB(e,t){return ka(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,gl.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}Ct.publishGenPageById=TB;function DB(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}Ct.boundEntityPublishScope=DB;function IB(e,t){let r=t?.entityLogicalName;return r?_C(e,r):Promise.resolve()}Ct.publishBoundEntity=IB});var $a=v(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});Nc.JsonPointer=void 0;var Mr=Q(),Sc=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 Mr.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new Mr.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 o of n)if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0)return;i=i[a]}else if(i!==null&&typeof i=="object"){let a=i;if(e.isReservedToken(o)||!Object.prototype.hasOwnProperty.call(a,o))return;i=a[o]}else return;return i}static set(t,r,n){let i=e.parse(r);if(i.length===0)throw new Mr.JsonPointerError(r,"cannot set the document root");let{parent:o,lastToken:a}=e.resolveParent(t,i,r);if(Array.isArray(o)){let s=e.toArrayIndex(a,o.length);if(s===void 0)throw new Mr.JsonPointerError(r,`'${a}' is not a valid array index`);if(s>o.length)throw new Mr.JsonPointerError(r,`array index '${a}' is out of range`);o[s]=n}else{if(e.isReservedToken(a))throw new Mr.JsonPointerError(r,`refusing to write reserved property '${a}'`);o[a]=n}}static remove(t,r){let n=e.parse(r);if(n.length===0)throw new Mr.JsonPointerError(r,"cannot remove the document root");let{parent:i,lastToken:o}=e.resolveParent(t,n,r);if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0||a>=i.length)throw new Mr.JsonPointerError(r,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new Mr.JsonPointerError(r,`refusing to remove reserved property '${o}'`);delete i[o]}}static add(t,r,n,i){let o=e.parse(r);if(o.length>0&&o[o.length-1]==="-"){let l=e.compile(o.slice(0,-1)),u=e.resolve(t,l);if(!Array.isArray(u))throw new Mr.JsonPointerError(r,"add target must be an array");u.push(n);return}let a=e.resolve(t,r);if(!Array.isArray(a))throw new Mr.JsonPointerError(r,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new Mr.JsonPointerError(r,`insert index ${s} is out of range`);a.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],o=e.compile(r.slice(0,-1)),a=e.resolve(t,o);if(a===null||typeof a!="object")throw new Mr.JsonPointerError(n,"parent path does not resolve to an object or array");return{parent:a,lastToken:i}}static toArrayIndex(t,r){if(t==="-")return r;if(/^(0|[1-9][0-9]*)$/.test(t))return Number(t)}};Nc.JsonPointer=Sc;Sc.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var DC=v(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.findElements=void 0;var TC=$a();function OB(e,t){let r=[];return Om(e,"",t,r),r}_c.findElements=OB;function Om(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,o)=>{Om(i,TC.JsonPointer.append(t,o),r,n)});else for(let i of Object.keys(e))Om(e[i],TC.JsonPointer.append(t,i),r,n)}});var Pm=v(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.assertMutationResult=Bn.assertExistsResult=Bn.assertReadResult=Bn.assertStorageContract=void 0;var PB=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],RB=["ensureContainer","exists"];function LB(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of PB)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of RB){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}Bn.assertStorageContract=LB;function kB(e,t){if(e===null||typeof e=="string")return e;throw new Error(`workspaceStorage.readText must resolve to a string or null for ${t}; got ${typeof e}. Absence is null \u2014 resolving undefined would make a present value look absent.`)}Bn.assertReadResult=kB;function $B(e,t){if(typeof e=="boolean")return e;throw new Error(`workspaceStorage.exists must resolve to a boolean for ${t}; got ${typeof e}. A truthy non-boolean would make an absent value look present.`)}Bn.assertExistsResult=$B;function xB(e,t){if(e!==void 0)throw new Error(`workspaceStorage.${t} must resolve to undefined; got ${typeof e}. A status-returning implementation would let a failed write be reported as a completed one.`)}Bn.assertMutationResult=xB});var Rm=v(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.retryTransientIoAsync=xa.retryTransientIo=void 0;var FB=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),MB=5,IC=10;function UB(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!OC(r,t))throw r;qB(IC*t)}}xa.retryTransientIo=UB;async function BB(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!OC(r,t))throw r;await new Promise(n=>setTimeout(n,IC*t))}}xa.retryTransientIoAsync=BB;function OC(e,t){let r=e.code;return t<MB&&!!r&&FB.has(r)}function qB(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var $C=v(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.canonicalArtifactId=Ur.WorkspaceManager=Ur.WORKSPACE_SCHEMA_VERSION=Ur.retryTransientIo=void 0;var Gt=Pm(),qn=Q(),VB=Rm();Object.defineProperty(Ur,"retryTransientIo",{enumerable:!0,get:function(){return VB.retryTransientIo}});function PC(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Ur.WORKSPACE_SCHEMA_VERSION=1;var Qi={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},GB="manifest.json",Fa=".metadata",Lm="entities";function RC(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}function km(e){if(e.schemaVersion!==void 0&&e.schemaVersion>Ur.WORKSPACE_SCHEMA_VERSION)throw new qn.IncompatibleWorkspaceError(e.schemaVersion,Ur.WORKSPACE_SCHEMA_VERSION)}function LC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tc(e){return e.trim().toLowerCase().replace(/\/+$/,"")}var $m=class{withManifest(t){let r=this.manifestQueue.then(t,t);return this.manifestQueue=r.then(()=>{},()=>{}),r}constructor(t,r,n){if(this.workspaceLabel=t,this.instanceUrl=r,this.manifestQueue=Promise.resolve(),this.bound=!1,n==null)throw new Error("WorkspaceManager requires a WorkspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'.");this.storage=n}artifactKey(t,r){return this.assertSafeId(r),[Qi[t],`${yl(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[Fa,Qi[t],`${yl(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[Fa,Lm,`${t.toLowerCase()}.json`]}fsStore(){let t=PC(this.storage);if(!t)throw new Error("This workspace is not filesystem-backed, so it has no physical paths. Use the artifact/metadata/manifest accessors instead of the path helpers.");return t}getRoot(){let t=PC(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([Qi[t]])}getArtifactFilePath(t,r){return this.fsStore().pathFor(this.artifactKey(t,r))}getMetaFilePath(t,r){return this.fsStore().pathFor(this.metaKey(t,r))}getEntityMetaFilePath(t){return this.fsStore().pathFor(this.entityKey(t))}assertSafeId(t){if(typeof t!="string"||t.length===0||/[\u0000-\u001f]/.test(t)||t.includes("/")||t.includes("\\")||t.includes(":")||t==="."||t===".."||t.includes(".."))throw new qn.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[GB]}assertDataKey(t,r){if(!Array.isArray(t)||t.length<2)throw new qn.InvalidArgumentError(`${r} writes only inside the workspace's folders; '${String(t)}' is at its root, where only the manifest lives \u2014 and the manifest is changed only by the workspace itself.`);t.forEach(n=>this.assertSafeId(n))}async init(){let t=await this.withManifest(async()=>{let r=await this.readStoredManifest();return r.present&&this.assertBoundHere(r.value),r.present});await this.ensureLayout(),t||await this.withManifest(async()=>{let r=await this.readStoredManifest();if(r.present){this.assertBoundHere(r.value);return}let n={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};await this.writeManifest(n)}),this.bound=!0}async readStoredManifest(){let t=(0,Gt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json");return t===null?{present:!1}:{present:!0,value:JSON.parse(t)}}async ensureLayout(){if(!this.storage.ensureContainer)return;let t=this.storage.ensureContainer.bind(this.storage),r=[[Fa,Lm]];for(let i of Object.keys(Qi))r.push([Qi[i]],[Fa,Qi[i]]);let n=await Promise.allSettled(r.map(i=>RC(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,Gt.assertMutationResult)(i.value,"ensureContainer")}}async isInitialized(){return this.storage.exists?(0,Gt.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,Gt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json")!==null}async ensureInitialized(){if(!this.bound){await this.verifyBinding();return}if(!await this.isInitialized())throw new qn.WorkspaceNotInitializedError(this.workspaceLabel)}async ensureReady(){await this.ensureInitialized()}async ensureBound(){this.bound||await this.verifyBinding()}verifyBinding(){if(!this.verifying){let t=()=>{this.verifying=void 0};this.verifying=this.readAndCheckBinding().then(t,r=>{throw t(),r})}return this.verifying}async readAndCheckBinding(){let t=await this.readStoredManifest();if(!t.present)throw new qn.WorkspaceNotInitializedError(this.workspaceLabel);this.assertBoundHere(t.value),this.bound=!0}assertBoundHere(t){if(!LC(t))throw new qn.WorkspaceOrgMismatchError("",this.instanceUrl);km(t);let r=typeof t.instanceUrl=="string"?t.instanceUrl.trim():"",n=Tc(r);if(!n||n!==Tc(this.instanceUrl))throw new qn.WorkspaceOrgMismatchError(r,this.instanceUrl)}async clean(){let t=await this.readStoredManifest();if(!t.present||!LC(t.value))throw new qn.WorkspaceNotInitializedError(this.workspaceLabel);let r=t.value;km(r);let n=Object.keys(Qi).map(o=>[Qi[o]]);n.push([Fa]);let i=await Promise.allSettled(n.map(o=>RC(()=>this.storage.deleteByPrefix(o))));for(let o of i){if(o.status==="rejected")throw o.reason;(0,Gt.assertMutationResult)(o.value,"deleteByPrefix")}await this.ensureLayout(),await this.withManifest(()=>this.writeManifest({...r,instanceUrl:this.instanceUrl,artifacts:[],lastSyncAt:void 0})),this.bound=!0}async readArtifact(t,r){return await this.ensureInitialized(),this.readJsonUnchecked(this.artifactKey(t,r))}async readArtifactWithText(t,r){await this.ensureInitialized();let n=this.artifactKey(t,r),i=(0,Gt.assertReadResult)(await this.storage.readText(n),n.join("/"));return i===null?null:{artifact:JSON.parse(i),text:i}}async writeArtifact(t,r,n,i){await this.ensureInitialized();let o=kC(n);if(i!==void 0&&o===i){await this.upsertManifestEntry(t,r,n,{unlessCurrent:!0});return}(0,Gt.assertMutationResult)(await this.storage.writeTextAtomic(this.artifactKey(t,r),o),"writeTextAtomic"),await this.upsertManifestEntry(t,r,n)}async deleteArtifact(t,r){await this.ensureInitialized(),(0,Gt.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,Gt.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=yl(r);await this.withManifest(async()=>{let i=await this.getManifest();i.artifacts=i.artifacts.filter(o=>!(o.type===t&&o.id===n)),await this.writeManifest(i)})}async readMeta(t,r){return await this.ensureBound(),this.readJsonUnchecked(this.metaKey(t,r))}async writeMeta(t,r,n){await this.ensureBound(),await this.writeJsonUnchecked(this.metaKey(t,r),n)}async listArtifacts(t,r){return await this.ensureInitialized(),(await this.getManifest()).artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}async readEntityMetadata(t){await this.ensureInitialized();let r=await this.readJsonUnchecked(this.entityKey(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}async writeEntityMetadata(t,r){await this.ensureInitialized(),await this.writeJsonUnchecked(this.entityKey(t),r)}async dropEntityMetadata(t){if(await this.ensureInitialized(),t===void 0){(0,Gt.assertMutationResult)(await this.storage.deleteByPrefix([Fa,Lm]),"deleteByPrefix");return}(0,Gt.assertMutationResult)(await this.storage.deleteFile(this.entityKey(t)),"deleteFile")}async getManifest(){await this.ensureInitialized();let t=await this.readJsonUnchecked(this.manifestKey);if(!t)throw new qn.WorkspaceNotInitializedError(this.workspaceLabel);return km(t),t}async writeManifest(t){await this.writeJsonUnchecked(this.manifestKey,{...t,schemaVersion:Ur.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();if(t.instanceUrl!==void 0&&Tc(String(t.instanceUrl))!==Tc(r.instanceUrl))throw new qn.InvalidArgumentError("updateManifest cannot change the workspace's org: it is bound to the org it was created for. cleanWorkspace() discards its contents and binds it to the org of the SDK that calls it.");await this.writeManifest({...r,...t,instanceUrl:r.instanceUrl})})}async upsertManifestEntry(t,r,n,i={}){await this.withManifest(async()=>{let o=await this.getManifest(),a=yl(r),s=n,l=typeof s.name=="string"?s.name:`${t}:${a}`,u=typeof s.entityLogicalName=="string"?s.entityLogicalName:void 0,c=o.artifacts.find(d=>d.type===t&&d.id===a);i.unlessCurrent&&c?.name===l&&c.entityLogicalName===u||(c?(c.name=l,c.entityLogicalName=u):o.artifacts.push({type:t,id:a,name:l,entityLogicalName:u,isDirty:!1}),await this.writeManifest(o))})}async readJson(t){return await this.ensureBound(),this.readJsonUnchecked(t)}async writeJson(t,r){this.assertDataKey(t,"writeJson"),await this.ensureBound(),await this.writeJsonUnchecked(t,r)}async removeFile(t){this.assertDataKey(t,"removeFile"),await this.ensureBound(),(0,Gt.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return await this.ensureBound(),this.storage.exists?(0,Gt.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,Gt.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}async readJsonUnchecked(t){let r=(0,Gt.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJsonUnchecked(t,r){(0,Gt.assertMutationResult)(await this.storage.writeTextAtomic(t,kC(r)),"writeTextAtomic")}};Ur.WorkspaceManager=$m;function kC(e){return`${JSON.stringify(e,null,2)}
-`}function yl(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()}Ur.canonicalArtifactId=yl});var xm=v(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.deepEqual=Ma.deepDiff=void 0;var WB=$a();function zB(e,t){let r=[];return FC(e,t,"",r,0),r}Ma.deepDiff=zB;var Dc=Symbol("missing"),Ic=512;function FC(e,t,r,n,i){if(e===t)return;if(i>Ic)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${Ic}`);let o=Oc(e),a=Oc(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=jB(e,t);for(let l of s){let u=xC(e,l),c=xC(t,l),d=WB.JsonPointer.append(r,l);u===Dc?n.push({pointer:d,type:"added",newValue:c}):c===Dc?n.push({pointer:d,type:"removed",oldValue:u}):FC(u,c,d,n,i+1)}return}MC(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function Oc(e){return e!==null&&typeof e=="object"}function jB(e,t){if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length),i=[];for(let o=0;o<n;o++)i.push(String(o));return i}let r=new Set([...Object.keys(e),...Object.keys(t)]);return Array.from(r)}function xC(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:Dc}return t in e?e[t]:Dc}function MC(e,t){return UC(e,t,0)}Ma.deepEqual=MC;function UC(e,t,r){if(e===t)return!0;if(r>Ic)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${Ic}`);if(!Oc(e)||!Oc(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(o=>o in t&&UC(e[o],t[o],r+1))}});var qC=v(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.VersionManager=Ua.PROJECTION_VERSION=void 0;var BC=xm(),HB=ye();Ua.PROJECTION_VERSION=8;var Fm=class{constructor(t){this.workspace=t}async storeMeta(t,r,n,i){var o;let a=i===void 0?await this.getMeta(t,r):i,s=((o=n.snapshot)===null||o===void 0?void 0:o.status)==="Active",l=a?.everActivated===!0||s;await this.workspace.writeMeta(t,r,l?{...n,everActivated:l}:n)}async getMeta(t,r){return this.workspace.readMeta(t,r)}async isDirty(t,r,n){let i=await this.workspace.readArtifact(t,r);if(i===null)return!1;let o=n===void 0?await this.getMeta(t,r):n;return o?!(0,BC.deepEqual)(o.snapshot,i):!0}async diff(t,r){let n=await this.workspace.readArtifact(t,r),i=await this.getMeta(t,r),o;return n===null?o=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?o=(0,BC.deepDiff)(i.snapshot,n):o=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:o}}async checkConflict(t,r,n){let i=await this.getMeta(t,r);return!i||!(0,HB.isVersionToken)(i.etag)?!0:i.etag!==n}};Ua.VersionManager=Fm});var GC=v((Mm,VC)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof Mm=="object"?VC.exports=t():e.compareVersions=t()})(Mm,function(){var e=/^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;function t(o,a){return o.indexOf(a)===-1?o.length:o.indexOf(a)}function r(o){var a=o.replace(/^v/,"").replace(/\+.*$/,""),s=t(a,"-"),l=a.substring(0,s).split(".");return l.push(a.substring(s+1)),l}function n(o){return isNaN(Number(o))?o:Number(o)}function i(o){if(typeof o!="string")throw new TypeError("Invalid argument expected string");if(!e.test(o))throw new Error("Invalid argument not valid semver ('"+o+"' received)")}return function(a,s){[a,s].forEach(i);for(var l=r(a),u=r(s),c=0;c<Math.max(l.length-1,u.length-1);c++){var d=parseInt(l[c]||0,10),f=parseInt(u[c]||0,10);if(d>f)return 1;if(f>d)return-1}var m=l[l.length-1],p=u[u.length-1];if(m&&p){var h=m.split(".").map(n),g=p.split(".").map(n);for(c=0;c<Math.max(h.length,g.length);c++){if(h[c]===void 0||typeof g[c]=="string"&&typeof h[c]=="number")return-1;if(g[c]===void 0||typeof h[c]=="string"&&typeof g[c]=="number"||h[c]>g[c])return 1;if(g[c]>h[c])return-1}}else if(m||p)return m?-1:1;return 0}})});var KC=v(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.EnvironmentFlowHostingType=Ke.EnvironmentDisableReasonCode=Ke.EnvironmentMigrationConstants=Ke.EnvironmentProvisioningStates=Ke.EnvironmentLocations=Ke.EnvironmentCreationTypeConstants=Ke.EnvironmentType=Ke.EnvironmentSkuConstants=Ke.environmentPermissions=Ke.DatabaseType=void 0;var WC;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(WC||(Ke.DatabaseType=WC={}));Ke.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"};Ke.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var zC;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(zC||(Ke.EnvironmentType=zC={}));Ke.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};Ke.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"};Ke.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};Ke.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var jC;(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"})(jC||(Ke.EnvironmentDisableReasonCode=jC={}));var HC;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(HC||(Ke.EnvironmentFlowHostingType=HC={}))});var rE=v(_=>{"use strict";var KB=_&&_.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(_,"__esModule",{value:!0});_.hasCommonDataServiceDatabase=_.getEnvironmentDiscoveryUrl=_.getEnvironmentWebApiUrl=_.getEnvironmentInstanceApiUrl=_.getEnvironmentLanguageCode=_.getEnvironmentUpdateCadence=_.checkVersions=_.isCds2EnvironmentVersionAtLeast=_.getSecurityOrConnectedGroupId=_.hasSecurityGroupId=_.doesCds2VersionSupportApiVersion9_1=_.doesCds2EnvironmentSupportApiVersion9_1=_.cdsVersionSupportingOSColorEdit=_.getEnvironmentDisplayName=_.getEnvironmentName=_.isEnvironmentInFirstReleaseCluster=_.isEnvironmentInPreprodCluster=_.isEnvironmentInTestCluster=_.isLiteEnvironmentUpgrading=_.isEnvironmentExpired=_.isEnvironmentInDeletedState=_.isEnvironmentInCreatingState=_.isDatabaseInProvisioningState=_.canUserCreateDatabase=_.isDisabledEnvironment=_.isDefaultEnvironment=_.isTrialEnvironment=_.isPlatformEnvironment=_.isTeamsEnvironment=_.isSandboxEnvironment=_.isProdEnvironment=_.isDevEnvironment=_.getEnvironmentType=_.getCrmInstanceName=_.getCrmInstanceUrl=_.getCrmAppDesignerUrl=_.getDevResourcesUrl=_.isEnvironmentInSuccessfulState=_.getAllThemesUrl=_.getAllPublishersUrl=_.getAllSolutionsUrl=_.getSecurityRolesUrl=_.getSecurityUsersUrl=_.environmentHasCds2Database=_.DEFAULT_SOLUTION_UNIQUE_NAME=_.DEFAULT_SOLUTION_ID=_.crmBapSolutionId=_.doesUserHavePermission=_.getLinkedEnvironmentMetadata=_.getCrmVersion=void 0;_.doesUserHaveFlowRunOnlyPermission=_.isUserPautoMakerWithoutDataAccess=_.isUserPautoMakerWithDataAccess=_.doesUserHaveCreateFlowPermission=_.equalsIgnoreCase=_.doesUserHaveCreateDatabasePermission=_.doesUserHaveDatabaseTablePermissions=_.isUserMakerWithoutDataAccess=_.isUserMakerWithDataAccess=_.doesUserHaveCreateAppPermission=_.doesUserHaveAdminPermission=void 0;var JB=KB(GC()),Oe=KC(),bl=Bm();function YB(e){let t=yi(e);return t&&t.version}_.getCrmVersion=YB;function yi(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}_.getLinkedEnvironmentMetadata=yi;function gi(e,t){return e?!!e[t]:!1}_.doesUserHavePermission=gi;_.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";_.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";_.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function ko(e){return!!yi(e)&&JC(e)}_.environmentHasCds2Database=ko;function QB(e){if(e&&ko(e)){let t=Xi(e);return(0,bl.getCrmAdminSecurityRolesUrl)(t)}return""}_.getSecurityUsersUrl=QB;function XB(e){if(e&&ko(e)){let t=Xi(e);return(0,bl.getCrmAdminSecurityUsersUrl)(t)}return""}_.getSecurityRolesUrl=XB;function ZB(e){if(e&&ko(e)){let t=Xi(e);(0,bl.getCrmAllSolutionsUrl)(t)}return""}_.getAllSolutionsUrl=ZB;function eq(e){if(e&&ko(e)){let t=Xi(e);return(0,bl.getCrmAllPublishersUrl)(t)}return""}_.getAllPublishersUrl=eq;function tq(e){return e&&ko(e)?Xi(e):""}_.getAllThemesUrl=tq;function JC(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===Oe.EnvironmentProvisioningStates.Succeeded.toUpperCase()}_.isEnvironmentInSuccessfulState=JC;function rq(e){if(e&&ko(e)){let t=Xi(e);return(0,bl.getCrmDevResourcesUrl)(t)}return""}_.getDevResourcesUrl=rq;function nq(e){return`${e}designer/app/{${_.crmBapSolutionId}}/CreateNewApp}}`}_.getCrmAppDesignerUrl=nq;function Xi(e){let t=yi(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}_.getCrmInstanceUrl=Xi;function iq(e){let t=yi(e);return t?t.uniqueName:""}_.getCrmInstanceName=iq;function oq(e){return yi(e)?Oe.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?Oe.EnvironmentType.CDS1:Oe.EnvironmentType.Empty}_.getEnvironmentType=oq;function aq(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Developer}_.isDevEnvironment=aq;function sq(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Production}_.isProdEnvironment=sq;function lq(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Sandbox}_.isSandboxEnvironment=lq;function vl(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Teams}_.isTeamsEnvironment=vl;function uq(e){return e&&e.properties&&e.properties.environmentSku===Oe.EnvironmentSkuConstants.Platform}_.isPlatformEnvironment=uq;var cq=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===Oe.EnvironmentSkuConstants.Trial};_.isTrialEnvironment=cq;function dq(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===Oe.EnvironmentCreationTypeConstants.DefaultTenant)}_.isDefaultEnvironment=dq;function fq(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}_.isDisabledEnvironment=fq;function pq(e){return e&&e.properties&&gi(e.properties.permissions,Oe.environmentPermissions.CreateDatabase)}_.canUserCreateDatabase=pq;function mq(e){return!!(e&&e.properties&&e.properties.provisioningState&&tE(e.properties.provisioningState,Oe.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}_.isDatabaseInProvisioningState=mq;function hq(e){return!!e&&!!e.properties&&e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Creating}_.isEnvironmentInCreatingState=hq;function gq(e){return e&&e.properties&&(e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===Oe.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===Oe.EnvironmentProvisioningStates.FailedDeleting)}_.isEnvironmentInDeletedState=gq;function yq(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}_.isEnvironmentExpired=yq;function bq(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"}_.isLiteEnvironmentUpgrading=bq;function vq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}_.isEnvironmentInTestCluster=vq;function wq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}_.isEnvironmentInPreprodCluster=wq;function Cq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}_.isEnvironmentInFirstReleaseCluster=Cq;function Eq(e){return e&&e.name||""}_.getEnvironmentName=Eq;function Aq(e){return e&&e.properties&&e.properties.displayName||""}_.getEnvironmentDisplayName=Aq;var YC="9.1.0.8202";_.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function Sq(e){return ZC(e,YC)}_.doesCds2EnvironmentSupportApiVersion9_1=Sq;function Nq(e){return Um(e,YC)}_.doesCds2VersionSupportApiVersion9_1=Nq;function QC(e){let t=yi(e);if(t)return t.securityGroupId}function XC(e){return e&&e.properties&&e.properties.connectedGroups}function _q(e,t){let r=XC(e);return!!r&&!!r.find(n=>n.id===t)||QC(e)===t}_.hasSecurityGroupId=_q;function Tq(e){let t=XC(e);return t&&t.length>0&&t[0].id?t[0].id:QC(e)}_.getSecurityOrConnectedGroupId=Tq;function ZC(e,t){let r=e.version;return r?Um(r,t):!1}_.isCds2EnvironmentVersionAtLeast=ZC;function Um(e,t){return t?e?(0,JB.default)(e,t)>=0:!1:!0}_.checkVersions=Um;function Dq(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}_.getEnvironmentUpdateCadence=Dq;function Iq(e){let t=yi(e);return t?Number(t.baseLanguage):0}_.getEnvironmentLanguageCode=Iq;function eE(e){let t=yi(e);return t?t.instanceApiUrl:void 0}_.getEnvironmentInstanceApiUrl=eE;function Oq(e){let t=eE(e);return t?t+"/api/data/v9.2":""}_.getEnvironmentWebApiUrl=Oq;function Pq(e){let t=Xi(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"}_.getEnvironmentDiscoveryUrl=Pq;var Rq=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===Oe.DatabaseType.CommonDataService};_.hasCommonDataServiceDatabase=Rq;var Lq=e=>{var t;return gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.AdminReadEnvironment)};_.doesUserHaveAdminPermission=Lq;var kq=e=>{var t;return gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreatePowerApp)};_.doesUserHaveCreateAppPermission=kq;var $q=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateAppPermission)(e)?vl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserMakerWithDataAccess=$q;var xq=e=>(0,_.doesUserHaveCreateAppPermission)(e)&&!vl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserMakerWithoutDataAccess=xq;var Fq=e=>[Oe.environmentPermissions.CreateDatabaseEntities,Oe.environmentPermissions.ListDatabaseEntities,Oe.environmentPermissions.UpdateDatabaseEntities,Oe.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return gi((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});_.doesUserHaveDatabaseTablePermissions=Fq;var Mq=e=>{var t;return gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateDatabase)};_.doesUserHaveCreateDatabasePermission=Mq;function tE(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}_.equalsIgnoreCase=tE;var Uq=e=>{var t;return gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateFlow)};_.doesUserHaveCreateFlowPermission=Uq;var Bq=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateFlowPermission)(e)?vl(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserPautoMakerWithDataAccess=Bq;var qq=e=>(0,_.doesUserHaveCreateFlowPermission)(e)&&!vl(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserPautoMakerWithoutDataAccess=qq;var Vq=e=>{var t,r;return!gi((t=e.properties)===null||t===void 0?void 0:t.permissions,Oe.environmentPermissions.CreateFlow)&&gi((r=e.properties)===null||r===void 0?void 0:r.permissions,Oe.environmentPermissions.ReadEnvironment)};_.doesUserHaveFlowRunOnlyPermission=Vq});var Bm=v(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.getRequiredComponentsQueryUrl=A.solutionComponentCountSummariesQueryUrl=A.solutionComponentSummariesQueryUrl=A.solutionComponentConfigurationsQueryUrl=A.chartsQueryUrl=A.workflowsQueryUrl=A.entityDefinitionsQueryUrl=A.solutionComponentDefinitionsQueryUrl=A.getCreateNewArticleTemplateUrl=A.getCreateNewPublisherUrl=A.getEnableSecurityRolesUrl=A.getArticleTemplateUrl=A.getFieldSecurityProfileDesignerUrl=A.getSecurityRoleDesignerUrl=A.getMailMergeTemplateDesignerUrl=A.getEmailTemplateDesignerUrl=A.getConnectionRoleDesignerUrl=A.getSiteMapDesignerUrl=A.getWebResourceFileUrl=A.getWebResourceDesignerUrl=A.getReportDesignerUrl=A.getBusinessProcessFlowDesignerUrl=A.getProcessShareUrl=A.getProcessDesignerUrl=A.getChartDesignerUrl=A.getOpenModernEntityDashboardUrl=A.getNewModernEntityDashboardUrl=A.getNewModernDashboardUrl=A.getOpenModernDashboardUrl=A.getDashboardDesignerUrl=A.getAppModuleDesignerUrl=A.privilegesQueryUrls=A.xrmApiUrl=A.getPlayAppModuleUrl=A.getCrmAdminSecurityUsersUrl=A.getCrmAdminSecurityRolesUrl=A.getCrmMyAppsUrl=A.getCrmAppDesignerUrl=A.getCrmDevResourcesUrl=A.getCrmAllPublishersUrl=A.getCrmAllSolutionsUrl=A.getSolutionPublisherUrl=A.getExportTranslationFileName=A.getExportSolutionTranslationUrl=A.getImportSolutionTranslationUrl=A.getShowSolutionDependenciesUrl=A.getShowComponentDependenciesUrl=A.cdsServiceUrl=A.ODATA_NEXT_LINK=A.ODATA_MAX_PAGE_SIZE=void 0;A.retrieveOrganizationResources=A.getUCIEntityRecordEditUrl=A.getUCIEntityRecordBaseUrl=A.getBusinessRuleDesignerUri=A.retrieveUnpublishedSuffix=A.getSavePowerSettingUri=A.getPowerSettingUri=A.getPowerSettingsUri=A.RetrievePlatform=A.getAppSettingOverrideUri=A.AppSettingOverrideName=A.getOrgSettingOverrideUri=A.OrgSettingOverrideName=A.getSettingDefinitionsUri=A.retrieveFeatureControlSettingsByNamespaceUrl=A.retrieveDeploymentPipelineConfigAppUrl=A.SPNPrincipalIdUrl=A.retrieveDeploymentEnvironmentInfoUrl=A.devSolutionInfoUrl=A.deployOperationStatusUrl=A.getAIGeneratedDeploymentNotesUrl=A.deploymentStageRunUrl=A.validatePackageAsyncUrl=A.deployPackageAsyncUrl=A.updateDeploymentStageRunUrl=A.createDeploymentStageRunUrl=A.retrieveDeploymentStagesUrl=A.retrievePipelinesUrl=A.retrieveDeploymentPipelineInfoUrl=A.getDeploymentStageRunsUrl=A.appDeploymentUrls=A.getProvisionLanguageUrl=A.getSolutionQueryUrl=A.getSolutionsByUniqueNameQueryUrl=A.solutionsQueryUrl=A.getDependentComponentsWithMetadataQueryUrl=void 0;var nE=rE();A.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";A.ODATA_NEXT_LINK="@odata.nextLink";A.cdsServiceUrl="https://cds-org/";var Cl;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Cl||(Cl={}));function Gq(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}A.getShowComponentDependenciesUrl=Gq;function Wq(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}A.getShowSolutionDependenciesUrl=Wq;function zq(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}A.getImportSolutionTranslationUrl=zq;function jq(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}A.getExportSolutionTranslationUrl=jq;function Hq(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}A.getExportTranslationFileName=Hq;function Kq(e,t,r){return r?`${e}tools/publisher/edit.aspx?appSolutionId=%7b${r}%7d&id=%7b${t}%7d`:`${e}tools/publisher/edit.aspx?id=%7b${t}%7d`}A.getSolutionPublisherUrl=Kq;function qm(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function Jq(e){return qm(e,Cl.AllSolutions)}A.getCrmAllSolutionsUrl=Jq;function Yq(e){return qm(e,Cl.AllPublishers)}A.getCrmAllPublishersUrl=Yq;function Qq(e){return qm(e,Cl.DevResources)}A.getCrmDevResourcesUrl=Qq;function Xq(e,t=nE.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}A.getCrmAppDesignerUrl=Xq;function Zq(e){return`${e}apps`}A.getCrmMyAppsUrl=Zq;function e3(e){return iE(e,"role")+"&forceUCI=0"}A.getCrmAdminSecurityRolesUrl=e3;function t3(e){return`${iE(e,"systemuser")}&forceclassic=1`}A.getCrmAdminSecurityUsersUrl=t3;function iE(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function r3(e,t){return`${e}main.aspx?appid=${t}`}A.getPlayAppModuleUrl=r3;A.xrmApiUrl="api/data/v9.0";A.privilegesQueryUrls={systemUserInfo:e=>`${e}${A.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${A.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${A.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function n3(e,t,r=nE.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}A.getAppModuleDesignerUrl=n3;function i3(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}A.getDashboardDesignerUrl=i3;function o3(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}A.getOpenModernDashboardUrl=o3;function a3(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}A.getNewModernDashboardUrl=a3;function s3(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}A.getNewModernEntityDashboardUrl=s3;function l3(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}A.getOpenModernEntityDashboardUrl=l3;function u3(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}A.getChartDesignerUrl=u3;function c3(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessDesignerUrl=c3;function d3(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessShareUrl=d3;function f3(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}A.getBusinessProcessFlowDesignerUrl=f3;function p3(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}A.getReportDesignerUrl=p3;function m3(e,t,r){return`${e}main.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&etc=9333&id=%7b${t}%7d&pagetype=webresourceedit`}A.getWebResourceDesignerUrl=m3;function h3(e,t){return`${e}WebResources/${t}`}A.getWebResourceFileUrl=h3;function g3(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}A.getSiteMapDesignerUrl=g3;function y3(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getConnectionRoleDesignerUrl=y3;function b3(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getEmailTemplateDesignerUrl=b3;function v3(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getMailMergeTemplateDesignerUrl=v3;function w3(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getSecurityRoleDesignerUrl=w3;function C3(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getFieldSecurityProfileDesignerUrl=C3;function E3(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}A.getArticleTemplateUrl=E3;function A3(e,t,r,n){return`${e}tools/FormEditor/Dialogs/FormRoleAssignment.aspx?appSolutionId=%7b${t}%7d&dType=1&formId=%7b${r}%7d&objectTypeCode=0&type=${n}`}A.getEnableSecurityRolesUrl=A3;function S3(e){return`${e}tools/publisher/edit.aspx`}A.getCreateNewPublisherUrl=S3;function N3(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}A.getCreateNewArticleTemplateUrl=N3;A.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";A.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";A.workflowsQueryUrl="api/data/v9.0/workflows";A.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";A.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";A.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";A.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function _3(e,t){return`${A.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}A.getRequiredComponentsQueryUrl=_3;function T3(e,t){return`${A.cdsServiceUrl}${A.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}A.getDependentComponentsWithMetadataQueryUrl=T3;A.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function D3(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}A.getSolutionsByUniqueNameQueryUrl=D3;function I3(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}A.getSolutionQueryUrl=I3;function O3(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}A.getProvisionLanguageUrl=O3;A.appDeploymentUrls={associateEnvironmentToPipelineUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})/deploymentpipeline_deploymentenvironment/$ref`,deploymentArtifactsUrl:"/api/data/v9.0/deploymentartifacts",deploymentEnvironmentUrl:"/api/data/v9.0/deploymentenvironments",deploymentPipelinesUrl:"/api/data/v9.0/deploymentpipelines",deploymentStagesUrl:"/api/data/v9.0/deploymentstages",retrieveDeploymentPipelinesUrl:e=>`/api/data/v9.0/RetrieveDeploymentPipelines(SourceEnvironmentId='${e}')`,deletePipelinesUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})`};function P3(e,t,r,n=!1,i=!1,o=!1,a=!1,s=!1,l=!1,u=!1){return`/api/data/v9.1/deploymentstageruns
+`)),this.type=t,this.id=r,this.issues=u,this.pointer=(a=(o=u[0])===null||o===void 0?void 0:o.pointer)!==null&&a!==void 0?a:"",this.rule=(l=(s=u[0])===null||s===void 0?void 0:s.rule)!==null&&l!==void 0?l:"invalid"}};X.ValidationError=mm;var hm=class extends dt{constructor(t){super("INVALID_ARGUMENT",t)}};X.InvalidArgumentError=hm;var gm=class extends dt{constructor(t,r,n,i="revalidated"){super("STALE_ARTIFACT",i==="pushed"?`Cannot apply the edit at ${n} to ${t}/${r}: a push made after this pointer's copy was read replaced the local copy with the record the server holds, which differs from that copy (ids and defaults the SDK filled in at save, a rewrite the platform made on save, or another writer's save), so the pointer may now identify a different node. Read the whole artifact (getArtifact), re-derive the pointer, and retry.`:`Cannot apply the edit at ${n} to ${t}/${r}: the cached copy was stale and the server copy has since changed, so any pointer derived from the old copy may now identify a different node. The local copy has been refreshed \u2014 re-read the artifact, re-derive the pointer, and retry.`),this.type=t,this.id=r,this.pointer=n,this.reason=i}};X.StaleArtifactError=gm;var ym=class extends dt{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}};X.LocalEditsWouldBeLostError=ym;var bm=class extends dt{constructor(t,r,n,i,o){super("VERSION_CONFLICT",`Version conflict for ${t}/${r}: local=${n??"(none)"}, server=${i??"(none)"}. Re-fetch and reapply changes.${o?` ${o}`:""}`),this.type=t,this.id=r,this.localEtag=n,this.serverEtag=i,this.detail=o}};X.VersionConflictError=bm;var vm=class extends dt{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,Object.defineProperty(this,"cause",{value:i,enumerable:!1,writable:!1,configurable:!0})}};X.ConnectionError=vm;var wm=class extends dt{constructor(t,r,n){super("WEB_RESOURCE_UNVERIFIED",n),this.id=t,this.webResourceName=r}};X.WebResourceUnverifiedError=wm;function jU(e,t){return typeof e=="object"&&e!==null&&Object.defineProperty(e,"cause",{value:t,enumerable:!1,writable:!0,configurable:!0}),e}X.attachCause=jU;var Cm=class extends dt{constructor(t){super("WORKSPACE_NOT_INITIALIZED",`Workspace not initialized at ${t}. Call initWorkspace() first.`),this.workspacePath=t}};X.WorkspaceNotInitializedError=Cm;var Em=class extends dt{constructor(t,r){super("WORKSPACE_ORG_MISMATCH",`This workspace belongs to ${t?`'${t}'`:"no recorded org"}, but this SDK targets '${r}'. Its local copies, baselines and cached metadata are that org's, so nothing was read or written. Use one workspace per org, or call cleanWorkspace() to discard this workspace's contents and bind it to '${r}'.`),this.workspaceInstanceUrl=t,this.instanceUrl=r}};X.WorkspaceOrgMismatchError=Em;var Am=class extends dt{constructor(t,r){super("NOT_IMPLEMENTED",`Operation '${t}' is not implemented yet${r?`: ${r}`:""}.`),this.operation=t}};X.NotImplementedError=Am;var Sm=class extends dt{constructor(t,r){super("INVALID_JSON_POINTER",`Invalid JSON Pointer '${t}': ${r}`),this.pointer=t}};X.JsonPointerError=Sm;var Nm=class extends dt{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}};X.AmbiguousArtifactError=Nm;var _m=class extends dt{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}};X.PathTraversalError=_m;var Tm=class extends dt{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}};X.IncompatibleWorkspaceError=Tm});var le=v(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.odataQuery=nt.normalizeGuid=nt.createSafeXmlElement=nt.assertNoControlChars=nt.assertODataName=nt.assertXmlName=nt.xmlText=nt.odataPathLiteral=nt.odataLiteral=void 0;var Dc=Q();function bC(e){return String(e??"").replace(/'/g,"''")}nt.odataLiteral=bC;function HU(e){return encodeURIComponent(bC(e))}nt.odataPathLiteral=HU;function KU(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}nt.xmlText=KU;function vC(e,t){let r=String(e??""),n=/^[A-Za-z_][0-9A-Za-z_.-]*$/,i=r.split(":");if(!(i.length<=2&&i.every(a=>n.test(a))&&!/^xmlns/i.test(r)))throw new Dc.InvalidArgumentError(`${t} must be a valid XML element name (got '${e}')`);return e}nt.assertXmlName=vC;function JU(e,t){let r=String(e??"");if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new Dc.InvalidArgumentError(`${t} must be a valid OData identifier (letters, digits, underscore): got '${e}'`);return e}nt.assertODataName=JU;function YU(e,t){if(/[\u0000-\u001F\u007F]/.test(String(e??"")))throw new Dc.InvalidArgumentError(`${t} must not contain control characters (including CR/LF): they would inject additional lines into the request`);return e}nt.assertNoControlChars=YU;function QU(e,t,r){return e.createElement(vC(t,r))}nt.createSafeXmlElement=QU;var XU=/^[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 ZU(e,t){let r=String(e??""),n=r.length===38&&r.startsWith("{")&&r.endsWith("}")?r.slice(1,-1):r;if(!XU.test(n))throw new Dc.InvalidArgumentError(`${t} must be a valid GUID (got '${e}')`);return n.toLowerCase()}nt.normalizeGuid=ZU;function eB(e){let t=[];for(let[r,n]of e)n!=null&&n!==""&&t.push(`${r}=${encodeURIComponent(String(n))}`);return t.length>0?`?${t.join("&")}`:""}nt.odataQuery=eB});var ye=v(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.nowIso=z.isAlreadyDeleted=z.deleteRecord=z.resendAppSearchIndexRace=z.resendDeadlockVictim=z.resendWhile=z.isAppSearchIndexRace=z.namesAppSearchIndexRace=z.isTransactionNotStarted=z.TRANSACTION_NOT_STARTED_CODE=z.LOCK_BACKOFF_MS=z.isConcurrencyLockRefusalError=z.isConcurrencyLockRefusal=z.CONCURRENCY_LOCK_CODE=z.AMBIGUOUS_WRITE_STATUSES=z.DEADLOCK_BACKOFF_MS=z.isSqlDeadlockVictim=z.ensureSuccess=z.resolveCreatedId=z.requireCreatedId=z.withClientMintedId=z.readCreatedId=z.readRowEtag=z.readEtag=z.requireEtag=z.isVersionToken=z.echoWrite=z.UPDATE_NO_ETAG_CODE=z.VERSION_CONFLICT_CODE=void 0;var ko=Q(),$a=le();z.VERSION_CONFLICT_CODE="VERSION_CONFLICT";z.UPDATE_NO_ETAG_CODE="ARTIFACT_UPDATE_NO_ETAG";function tB(e,t){return{query:`?$select=${encodeURIComponent(e)}`,options:{headers:{...t??{},Prefer:"return=representation"}}}}z.echoWrite=tB;function wC(e){return typeof e=="string"&&e.trim()!==""&&e.trim()!=="*"}z.isVersionToken=wC;function rB(e,t,r){if(!wC(e))throw new ko.SdkError(z.UPDATE_NO_ETAG_CODE,`Refusing to push ${t} '${r}': ${e?`the concurrency token held for it ('${e}') is not a version`:"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}z.requireEtag=rB;function CC(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}z.readEtag=CC;async function nB(e,t,r,n){let i=`/${t}(${n})${(0,$a.odataQuery)([["$select",r]])}`;return CC(Om(await e.get(i),e.apiUrl(i)))}z.readRowEtag=nB;function Im(e,t){var r;let n=e.body;if(n&&typeof n[t]=="string")return(0,$a.normalizeGuid)(n[t],t);let i=(r=e.headers)!==null&&r!==void 0?r:{};for(let o of Object.keys(i))if(o.toLowerCase()==="odata-entityid"){let a=/\(([0-9a-fA-F-]{36})\)/.exec(i[o]);if(a)return(0,$a.normalizeGuid)(a[1],t)}return null}z.readCreatedId=Im;function iB(e,t,r){return r?{...e,[t]:(0,$a.normalizeGuid)(r,t)}:e}z.withClientMintedId=iB;function oB(e,t,r){let n=Im(e,t);if(!n)throw new ko.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`);return n}z.requireCreatedId=oB;function aB(e,t,r,n){let i=Im(e,t);if(i)return i;if(n)return(0,$a.normalizeGuid)(n,t);throw new ko.InvalidArgumentError(`Dataverse did not return an id for the created ${r}`)}z.resolveCreatedId=aB;function Om(e,t){if(e.status===412)throw new ko.SdkError(z.VERSION_CONFLICT_CODE,`Version conflict (412) from ${t}`);if(e.status<200||e.status>=300)throw new ko.ConnectionError(t,e.status,fB(e.body),e.body);return e}z.ensureSuccess=Om;function EC(e){if(e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/\bSql Number:\s*1205\b/i.test(t)}z.isSqlDeadlockVictim=EC;z.DEADLOCK_BACKOFF_MS=[1e3,2e3,4e3];z.AMBIGUOUS_WRITE_STATUSES=new Set([408,502,503,504]);z.CONCURRENCY_LOCK_CODE="0x80071151";function AC(e){var t,r;if(e.status!==429)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===z.CONCURRENCY_LOCK_CODE}z.isConcurrencyLockRefusal=AC;function sB(e){return e instanceof ko.ConnectionError&&e.statusCode===429&&AC({status:429,headers:{},body:e.cause})}z.isConcurrencyLockRefusalError=sB;z.LOCK_BACKOFF_MS=[2e3,3e3,...Array.from({length:35},()=>5e3)];z.TRANSACTION_NOT_STARTED_CODE="0x80040251";function lB(e){var t,r;if(e.status!==500)return!1;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return typeof n=="string"&&n.toLowerCase()===z.TRANSACTION_NOT_STARTED_CODE}z.isTransactionNotStarted=lB;var uB=/(?:^|[^a-z0-9_])AppModule_DVTableSearch_M365AppModuleId(?![a-z0-9_])/i;function SC(e){return uB.test(e)&&/\bSql Number:\s*547\b/i.test(e)}z.namesAppSearchIndexRace=SC;function NC(e){return e.status!==400||e.body===void 0||e.body===null?!1:SC(typeof e.body=="string"?e.body:JSON.stringify(e.body))}z.isAppSearchIndexRace=NC;async function Pm(e,t,r=z.DEADLOCK_BACKOFF_MS){for(let n=0;;n+=1){let i=await t();if(n>=r.length||!e(i))return i;await new Promise(o=>setTimeout(o,r[n]))}}z.resendWhile=Pm;function cB(e){return Pm(EC,e,z.DEADLOCK_BACKOFF_MS)}z.resendDeadlockVictim=cB;function dB(e){return Pm(NC,e,z.DEADLOCK_BACKOFF_MS)}z.resendAppSearchIndexRace=dB;function fB(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 pB(e,t,r,n){let i=(0,$a.normalizeGuid)(r,"id"),o=`/${t}(${i})`;Om(await e.delete(o,n?{headers:{"If-Match":n}}:void 0),e.apiUrl(o))}z.deleteRecord=pB;function mB(e){return e instanceof ko.ConnectionError&&e.statusCode===404}z.isAlreadyDeleted=mB;function hB(){return new Date().toISOString()}z.nowIso=hB});var Lt=v(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.describeMalformedValue=xa.collectPages=void 0;var _C=ye(),Rm=Q();async function gB(e,t,r,n,i){let o=[],a=new Set,s=e.apiUrl(t),l=(0,_C.ensureSuccess)(await e.get(t,i),s);for(n?.(l);;){let u=l.body,c=u?.value;if(!Array.isArray(c))throw new Rm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed page \u2014 expected an OData 'value' array but got ${km(c)}; refusing to return partial results.`);for(let f of c)o.push(f);let d=u?.["@odata.nextLink"];if(d==null)break;if(typeof d!="string"||d.length===0)throw new Rm.ConnectionError(s,l.status,`${r}: paginated read returned a malformed @odata.nextLink (${km(d)}); cannot follow it, and refusing to return partial results.`);if(a.has(d))throw new Rm.InvalidArgumentError(`${r}: aborting pagination \u2014 the server returned a repeated @odata.nextLink ('${d}'), which would loop indefinitely.`);a.add(d),s=d,l=(0,_C.ensureSuccess)(await e.getAbsolute(d,i),d)}return o}xa.collectPages=gB;function km(e){return e===null?"null":e===void 0?"undefined (missing)":`a ${typeof e}`}xa.describeMalformedValue=km});var Lm=v($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.assertWorkflowKind=$o.WORKFLOW_KIND_MISMATCH_CODE=void 0;var Lo=Qi(),yB=Q(),TC=ye(),bB=le();$o.WORKFLOW_KIND_MISMATCH_CODE="WORKFLOW_KIND_MISMATCH";var DC={[Lo.WorkflowCategory.Workflow]:"classic workflow",[Lo.WorkflowCategory.Dialog]:"dialog",[Lo.WorkflowCategory.BusinessRule]:"business rule",[Lo.WorkflowCategory.Action]:"custom action",[Lo.WorkflowCategory.BusinessProcessFlow]:"business process flow",[Lo.WorkflowCategory.Flow]:"cloud flow",[Lo.WorkflowCategory.UIFlow]:"desktop flow"};async function vB(e,t,r){var n,i;let o=`/workflows(${t})${(0,bB.odataQuery)([["$select","category"]])}`,a=await e.get(o);if(a.status===404)return null;(0,TC.ensureSuccess)(a,e.apiUrl(o));let s=(n=a.body)===null||n===void 0?void 0:n.category,l=typeof s=="number"?s:typeof s=="string"&&s!==""?Number(s):NaN;if(l!==r){let u=Number.isFinite(l)?`a ${(i=DC[l])!==null&&i!==void 0?i:"process"} (category ${l})`:"a process whose category could not be read";throw new yB.SdkError($o.WORKFLOW_KIND_MISMATCH_CODE,`Refusing to delete workflow '${t}' as a ${DC[r]}: it is ${u}. Nothing was changed. Check the id.`)}return(0,TC.readEtag)(a)}$o.assertWorkflowKind=vB});var xm=v(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.deleteWorkflowResending=Yr.isWorkflowDeleteUnsettled=Yr.failedAfterResend=Yr.WORKFLOW_DELETE_UNSETTLED_CODE=void 0;var bl=Q(),hi=ye(),OC=le();Yr.WORKFLOW_DELETE_UNSETTLED_CODE="WORKFLOW_DELETE_UNSETTLED";var PC=new WeakSet;function $m(e){return typeof e=="object"&&e!==null&&PC.add(e),e}function wB(e){return typeof e=="object"&&e!==null&&PC.has(e)}Yr.failedAfterResend=wB;function CB(e){return e instanceof bl.SdkError&&e.code===Yr.WORKFLOW_DELETE_UNSETTLED_CODE}Yr.isWorkflowDeleteUnsettled=CB;function EB(e,t){try{(0,hi.ensureSuccess)(e,t)}catch(r){return r}}function AB(e){return(0,hi.isSqlDeadlockVictim)(e)?"lost a SQL deadlock (HTTP 500, Sql Number 1205)":`lost its transaction (HTTP 500 ${hi.TRANSACTION_NOT_STARTED_CODE})`}async function IC(e,t){try{return(await e.get(`/workflows(${t})${(0,OC.odataQuery)([["$select","workflowid"]])}`)).status===404}catch{return!1}}async function SB(e,t,{bindingToken:r,kindName:n,deactivated:i=!1,resendDeadlockVictim:o=!1,ifMatchOnFirst:a=!1}){let s=(0,OC.normalizeGuid)(t,"id");if(a&&!r)throw new bl.InvalidArgumentError(`Refusing to delete ${n} '${s}': its delete must be conditional on a token this operation holds, and it holds none.`);let l=`/workflows(${s})`,u=e.apiUrl(l),c=p=>(0,hi.isTransactionNotStarted)(p)||o&&(0,hi.isSqlDeadlockVictim)(p),d=0,f,m;try{m=await(0,hi.resendWhile)(c,async()=>{d+=1;let p=d>1||a,h=await e.delete(l,p?{headers:{"If-Match":r}}:void 0);return f=f??h,h},r?hi.DEADLOCK_BACKOFF_MS:[])}catch(p){if(p instanceof bl.ConnectionError&&p.statusCode===0&&r&&await IC(e,s))return;throw d>1?$m(p):p}if(!(d>1&&m.status===404)){if(d>1&&m.status===412){let p=AB(f),h=new bl.SdkError(Yr.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting ${n} '${s}' ${p}, and its re-send was refused (HTTP 412): the row at that id is no longer the version this delete checked \u2014 it was edited, or deleted and re-created at the same id \u2014 so nothing more was deleted. `+(i?"This delete had deactivated the process first and has NOT re-activated it: it MAY be left DISABLED. ":"")+"Read the row before deleting it again.");throw $m((0,bl.attachCause)(h,EB(f,u)))}if(!(r&&hi.AMBIGUOUS_WRITE_STATUSES.has(m.status)&&await IC(e,s)))try{(0,hi.ensureSuccess)(m,u)}catch(p){throw d>1?$m(p):p}}}Yr.deleteWorkflowResending=SB});var Fm=v(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.businessRuleApi=Bn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE=Bn.WFOM_API_UNAVAILABLE_CODE=void 0;var Un=Qi(),NB=Lt(),_B=Lm(),TB=xm(),Gt=ye(),gi=le(),Oc=Q();Bn.WFOM_API_UNAVAILABLE_CODE="BUSINESS_RULE_API_UNAVAILABLE";Bn.BUSINESS_RULE_LEFT_DEACTIVATED_CODE="BUSINESS_RULE_LEFT_DEACTIVATED";async function RC(e,t,r,n){let i=`/workflows(${OB})/Microsoft.Dynamics.CRM.${t}`;try{return(0,Gt.ensureSuccess)(await e.post(i,{Entity:r.Entity,WfomJson:r.WfomJson},{headers:n}),e.apiUrl(i))}catch(o){throw o?.statusCode!==404?o:new Oc.SdkError(Bn.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 DB(e,t){let r=`/workflows(${t})${(0,gi.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,Gt.readEtag)(n),statecode:typeof i?.statecode=="number"?i.statecode:null,statuscode:typeof i?.statuscode=="number"?i.statuscode:null}}catch{return null}}async function IB(e,t,r){let n=await DB(e,t);if(n===null||n.etag===null)throw new Oc.SdkError(Gt.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 Oc.SdkError(Gt.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 OB="00000000-0000-0000-0000-000000000000",Ic={"Content-Type":"application/json",Accept:"application/json","OData-Version":"4.0","OData-MaxVersion":"4.0"},PB="workflowid,name,description,primaryentity,statecode,category,type",RB="category eq 2 and type eq 1";async function kC(e,t,r){var n;if(r==="Draft")return null;let i=(0,gi.normalizeGuid)(t,"workflowid"),o=r==="Active",a={statecode:o?Un.StateCode.Activated:Un.StateCode.Draft,statuscode:o?Un.StatusCode.Activated:Un.StatusCode.Draft},s=`/workflows(${i})`,l=(0,Gt.ensureSuccess)(await e.patch(s,a,{headers:Ic}),e.apiUrl(s));return(n=(0,Gt.readEtag)(l))!==null&&n!==void 0?n:await vl(e,i)}async function vl(e,t){let r=`/workflows(${t})${(0,gi.odataQuery)([["$select","workflowid"]])}`;try{let n=await e.get(r);return n.status>=200&&n.status<300?(0,Gt.readEtag)(n):null}catch{return null}}async function kB(e,t,r){let n=await vl(e,t),i=await r(),o=(0,Gt.readEtag)(i);if(o)return{response:i,etag:o};let a=await vl(e,t);return{response:i,etag:n!==null&&n===a?a:null}}Bn.businessRuleApi={async get(e,t){let r=(0,gi.normalizeGuid)(t,"id"),n=`/workflows(${r})/Microsoft.Dynamics.CRM.RetrieveProcessWithWfomJson`,{response:i,etag:o}=await kB(e,r,async()=>(0,Gt.ensureSuccess)(await e.get(n),e.apiUrl(n)));return{raw:i.body,etag:o}},async list(e,t){let r=[RB];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,gi.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,gi.odataQuery)([["$select",PB],["$filter",r.join(" and ")]])}`;return(await(0,NB.collectPages)(e,n,"listArtifacts('businessRule')")).map(o=>{var a,s;return{type:"businessRule",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){var r;let n=t,i=(0,gi.normalizeGuid)(n.Entity.workflowid,"workflowid"),o=await RC(e,"CreateProcessWithWfomJson",n,Ic),a=(0,Gt.resolveCreatedId)(o,"workflowid","business rule",i),s=null;try{s=await kC(e,a,n.status)}catch(l){try{await(0,Gt.deleteRecord)(e,"workflows",a)}catch{}throw l}return{id:a,etag:(r=s??(0,Gt.readEtag)(o))!==null&&r!==void 0?r:await vl(e,a)}},async update(e,t,r,n){var i,o;let a=r,s=(0,gi.normalizeGuid)(t,"id"),l=`/workflows(${s})`,u={...Ic,"If-Match":(0,Gt.requireEtag)(n,"business rule",s)},c=await IB(e,s,u["If-Match"]),d=c.statecode===Un.StateCode.Activated;d&&(0,Gt.ensureSuccess)(await e.patch(l,{statecode:Un.StateCode.Draft,statuscode:Un.StatusCode.Draft},{headers:u}),e.apiUrl(l));let f;try{f=await RC(e,"UpdateProcessWithWfomJson",a,u)}catch(p){if(d)try{(0,Gt.ensureSuccess)(await e.patch(l,{statecode:Un.StateCode.Activated,statuscode:(i=c.statuscode)!==null&&i!==void 0?i:Un.StatusCode.Activated},{headers:Ic}),e.apiUrl(l))}catch(h){throw new Oc.SdkError(Bn.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: ${p instanceof Error?p.message:String(p)}. Restore failure: ${h instanceof Error?h.message:String(h)}`)}throw p}let m=await kC(e,s,a.status);return{id:s,etag:(o=m??(0,Gt.readEtag)(f))!==null&&o!==void 0?o:await vl(e,s)}},async delete(e,t){let r=(0,gi.normalizeGuid)(t,"id"),n=await(0,_B.assertWorkflowKind)(e,r,Un.WorkflowCategory.BusinessRule);return(0,TB.deleteWorkflowResending)(e,r,{bindingToken:n,kindName:"business rule"})}}});var Qr=v(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.publishBoundEntity=Et.boundEntityPublishScope=Et.publishGenPageById=Et.publishDashboardById=Et.publishWebResourceById=Et.publishEntity=Et.publishAppModule=Et.publishXml=void 0;var LC=ye(),wl=le(),$C="/PublishXml";async function Fa(e,t){(0,LC.ensureSuccess)(await(0,LC.resendDeadlockVictim)(()=>e.post($C,{ParameterXml:t})),e.apiUrl($C))}Et.publishXml=Fa;function LB(e,t){return Fa(e,`<importexportxml><appmodules><appmodule>${(0,wl.xmlText)(t)}</appmodule></appmodules></importexportxml>`)}Et.publishAppModule=LB;function xC(e,t){return Fa(e,`<importexportxml><entities><entity>${(0,wl.xmlText)(t)}</entity></entities></importexportxml>`)}Et.publishEntity=xC;function $B(e,t){return Fa(e,`<importexportxml><webresources><webresource>${(0,wl.xmlText)(t)}</webresource></webresources></importexportxml>`)}Et.publishWebResourceById=$B;function xB(e,t){return Fa(e,`<importexportxml><dashboards><dashboard>${(0,wl.xmlText)(t)}</dashboard></dashboards></importexportxml>`)}Et.publishDashboardById=xB;function FB(e,t){return Fa(e,`<importexportxml><uxagentprojects><uxagentproject>${(0,wl.xmlText)(t)}</uxagentproject></uxagentprojects></importexportxml>`)}Et.publishGenPageById=FB;function MB(e){let t=e?.entityLogicalName;return t?{envelope:"entity",entityLogicalName:t,blastRadiusWarning:"ENTITY_ENVELOPE_ALSO_SHIPS_UNRELATED_UNPUBLISHED_CHANGES"}:{envelope:"entity"}}Et.boundEntityPublishScope=MB;function UB(e,t){let r=t?.entityLogicalName;return r?xC(e,r):Promise.resolve()}Et.publishBoundEntity=UB});var Ma=v(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});Rc.JsonPointer=void 0;var qr=Q(),Pc=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 qr.JsonPointerError(t,'non-empty pointers must start with "/"');return t.substring(1).split("/").map(r=>{if(/~(?![01])/.test(r))throw new qr.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 o of n)if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0)return;i=i[a]}else if(i!==null&&typeof i=="object"){let a=i;if(e.isReservedToken(o)||!Object.prototype.hasOwnProperty.call(a,o))return;i=a[o]}else return;return i}static set(t,r,n){let i=e.parse(r);if(i.length===0)throw new qr.JsonPointerError(r,"cannot set the document root");let{parent:o,lastToken:a}=e.resolveParent(t,i,r);if(Array.isArray(o)){let s=e.toArrayIndex(a,o.length);if(s===void 0)throw new qr.JsonPointerError(r,`'${a}' is not a valid array index`);if(s>o.length)throw new qr.JsonPointerError(r,`array index '${a}' is out of range`);o[s]=n}else{if(e.isReservedToken(a))throw new qr.JsonPointerError(r,`refusing to write reserved property '${a}'`);o[a]=n}}static remove(t,r){let n=e.parse(r);if(n.length===0)throw new qr.JsonPointerError(r,"cannot remove the document root");let{parent:i,lastToken:o}=e.resolveParent(t,n,r);if(Array.isArray(i)){let a=e.toArrayIndex(o,i.length);if(a===void 0||a>=i.length)throw new qr.JsonPointerError(r,`array index '${o}' is out of range`);i.splice(a,1)}else{if(e.isReservedToken(o))throw new qr.JsonPointerError(r,`refusing to remove reserved property '${o}'`);delete i[o]}}static add(t,r,n,i){let o=e.parse(r);if(o.length>0&&o[o.length-1]==="-"){let l=e.compile(o.slice(0,-1)),u=e.resolve(t,l);if(!Array.isArray(u))throw new qr.JsonPointerError(r,"add target must be an array");u.push(n);return}let a=e.resolve(t,r);if(!Array.isArray(a))throw new qr.JsonPointerError(r,"add target must be an array");let s=i===void 0?a.length:i;if(s<0||s>a.length)throw new qr.JsonPointerError(r,`insert index ${s} is out of range`);a.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],o=e.compile(r.slice(0,-1)),a=e.resolve(t,o);if(a===null||typeof a!="object")throw new qr.JsonPointerError(n,"parent path does not resolve to an object or array");return{parent:a,lastToken:i}}static toArrayIndex(t,r){if(t==="-")return r;if(/^(0|[1-9][0-9]*)$/.test(t))return Number(t)}};Rc.JsonPointer=Pc;Pc.RESERVED_TOKENS=new Set(["__proto__","prototype","constructor"])});var MC=v(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});kc.findElements=void 0;var FC=Ma();function BB(e,t){let r=[];return Mm(e,"",t,r),r}kc.findElements=BB;function Mm(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,o)=>{Mm(i,FC.JsonPointer.append(t,o),r,n)});else for(let i of Object.keys(e))Mm(e[i],FC.JsonPointer.append(t,i),r,n)}});var Um=v(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.assertMutationResult=qn.assertExistsResult=qn.assertReadResult=qn.assertStorageContract=void 0;var qB=["readText","writeTextAtomic","deleteFile","deleteByPrefix"],VB=["ensureContainer","exists"];function GB(e){if(typeof e!="object"||e===null)throw new Error("workspaceStorage must be an object implementing WorkspaceStorage.");for(let t of qB)if(typeof e[t]!="function")throw new Error(`workspaceStorage is missing the required method '${t}'.`);for(let t of VB){let r=e[t];if(r!==void 0&&typeof r!="function")throw new Error(`workspaceStorage.${t} must be a function when present.`)}return e}qn.assertStorageContract=GB;function WB(e,t){if(e===null||typeof e=="string")return e;throw new Error(`workspaceStorage.readText must resolve to a string or null for ${t}; got ${typeof e}. Absence is null \u2014 resolving undefined would make a present value look absent.`)}qn.assertReadResult=WB;function zB(e,t){if(typeof e=="boolean")return e;throw new Error(`workspaceStorage.exists must resolve to a boolean for ${t}; got ${typeof e}. A truthy non-boolean would make an absent value look present.`)}qn.assertExistsResult=zB;function jB(e,t){if(e!==void 0)throw new Error(`workspaceStorage.${t} must resolve to undefined; got ${typeof e}. A status-returning implementation would let a failed write be reported as a completed one.`)}qn.assertMutationResult=jB});var Bm=v(Ua=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});Ua.retryTransientIoAsync=Ua.retryTransientIo=void 0;var HB=new Set(["EPERM","EACCES","EBUSY","UNKNOWN"]),KB=5,UC=10;function JB(e){for(let t=1;;t+=1)try{return e()}catch(r){if(!BC(r,t))throw r;QB(UC*t)}}Ua.retryTransientIo=JB;async function YB(e){for(let t=1;;t+=1)try{return await e()}catch(r){if(!BC(r,t))throw r;await new Promise(n=>setTimeout(n,UC*t))}}Ua.retryTransientIoAsync=YB;function BC(e,t){let r=e.code;return t<KB&&!!r&&HB.has(r)}function QB(e){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}catch{let t=Date.now()+e;for(;Date.now()<t;);}}});var zC=v(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.canonicalArtifactId=Vr.WorkspaceManager=Vr.WORKSPACE_SCHEMA_VERSION=Vr.retryTransientIo=void 0;var Wt=Um(),Vn=Q(),XB=Bm();Object.defineProperty(Vr,"retryTransientIo",{enumerable:!0,get:function(){return XB.retryTransientIo}});function qC(e){let t=e;return typeof t.pathFor=="function"&&typeof t.getRoot=="function"?e:null}Vr.WORKSPACE_SCHEMA_VERSION=1;var Xi={form:"forms",view:"views",businessRule:"business-rules",app:"apps",command:"commands",chart:"charts",dashboard:"dashboards",genPage:"gen-pages",bpf:"business-process-flows"},ZB="manifest.json",Ba=".metadata",qm="entities";function VC(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t)}}function Vm(e){if(e.schemaVersion!==void 0&&e.schemaVersion>Vr.WORKSPACE_SCHEMA_VERSION)throw new Vn.IncompatibleWorkspaceError(e.schemaVersion,Vr.WORKSPACE_SCHEMA_VERSION)}function GC(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Lc(e){return e.trim().toLowerCase().replace(/\/+$/,"")}var Gm=class{withManifest(t){let r=this.manifestQueue.then(t,t);return this.manifestQueue=r.then(()=>{},()=>{}),r}constructor(t,r,n){if(this.workspaceLabel=t,this.instanceUrl=r,this.manifestQueue=Promise.resolve(),this.bound=!1,n==null)throw new Error("WorkspaceManager requires a WorkspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'.");this.storage=n}artifactKey(t,r){return this.assertSafeId(r),[Xi[t],`${Cl(r)}.json`]}metaKey(t,r){return this.assertSafeId(r),[Ba,Xi[t],`${Cl(r)}.meta.json`]}entityKey(t){return this.assertSafeId(t),[Ba,qm,`${t.toLowerCase()}.json`]}fsStore(){let t=qC(this.storage);if(!t)throw new Error("This workspace is not filesystem-backed, so it has no physical paths. Use the artifact/metadata/manifest accessors instead of the path helpers.");return t}getRoot(){let t=qC(this.storage);return t?t.getRoot():this.workspaceLabel}getArtifactDir(t){return this.fsStore().pathFor([Xi[t]])}getArtifactFilePath(t,r){return this.fsStore().pathFor(this.artifactKey(t,r))}getMetaFilePath(t,r){return this.fsStore().pathFor(this.metaKey(t,r))}getEntityMetaFilePath(t){return this.fsStore().pathFor(this.entityKey(t))}assertSafeId(t){if(typeof t!="string"||t.length===0||/[\u0000-\u001f]/.test(t)||t.includes("/")||t.includes("\\")||t.includes(":")||t==="."||t===".."||t.includes(".."))throw new Vn.PathTraversalError(String(t),this.workspaceLabel)}get manifestKey(){return[ZB]}assertDataKey(t,r){if(!Array.isArray(t)||t.length<2)throw new Vn.InvalidArgumentError(`${r} writes only inside the workspace's folders; '${String(t)}' is at its root, where only the manifest lives \u2014 and the manifest is changed only by the workspace itself.`);t.forEach(n=>this.assertSafeId(n))}async init(){let t=await this.withManifest(async()=>{let r=await this.readStoredManifest();return r.present&&this.assertBoundHere(r.value),r.present});await this.ensureLayout(),t||await this.withManifest(async()=>{let r=await this.readStoredManifest();if(r.present){this.assertBoundHere(r.value);return}let n={instanceUrl:this.instanceUrl,createdAt:new Date().toISOString(),artifacts:[]};await this.writeManifest(n)}),this.bound=!0}async readStoredManifest(){let t=(0,Wt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json");return t===null?{present:!1}:{present:!0,value:JSON.parse(t)}}async ensureLayout(){if(!this.storage.ensureContainer)return;let t=this.storage.ensureContainer.bind(this.storage),r=[[Ba,qm]];for(let i of Object.keys(Xi))r.push([Xi[i]],[Ba,Xi[i]]);let n=await Promise.allSettled(r.map(i=>VC(()=>t(i))));for(let i of n){if(i.status==="rejected")throw i.reason;(0,Wt.assertMutationResult)(i.value,"ensureContainer")}}async isInitialized(){return this.storage.exists?(0,Wt.assertExistsResult)(await this.storage.exists(this.manifestKey),"manifest.json"):(0,Wt.assertReadResult)(await this.storage.readText(this.manifestKey),"manifest.json")!==null}async ensureInitialized(){if(!this.bound){await this.verifyBinding();return}if(!await this.isInitialized())throw new Vn.WorkspaceNotInitializedError(this.workspaceLabel)}async ensureReady(){await this.ensureInitialized()}async ensureBound(){this.bound||await this.verifyBinding()}verifyBinding(){if(!this.verifying){let t=()=>{this.verifying=void 0};this.verifying=this.readAndCheckBinding().then(t,r=>{throw t(),r})}return this.verifying}async readAndCheckBinding(){let t=await this.readStoredManifest();if(!t.present)throw new Vn.WorkspaceNotInitializedError(this.workspaceLabel);this.assertBoundHere(t.value),this.bound=!0}assertBoundHere(t){if(!GC(t))throw new Vn.WorkspaceOrgMismatchError("",this.instanceUrl);Vm(t);let r=typeof t.instanceUrl=="string"?t.instanceUrl.trim():"",n=Lc(r);if(!n||n!==Lc(this.instanceUrl))throw new Vn.WorkspaceOrgMismatchError(r,this.instanceUrl)}async clean(){let t=await this.readStoredManifest();if(!t.present||!GC(t.value))throw new Vn.WorkspaceNotInitializedError(this.workspaceLabel);let r=t.value;Vm(r);let n=Object.keys(Xi).map(o=>[Xi[o]]);n.push([Ba]);let i=await Promise.allSettled(n.map(o=>VC(()=>this.storage.deleteByPrefix(o))));for(let o of i){if(o.status==="rejected")throw o.reason;(0,Wt.assertMutationResult)(o.value,"deleteByPrefix")}await this.ensureLayout(),await this.withManifest(()=>this.writeManifest({...r,instanceUrl:this.instanceUrl,artifacts:[],lastSyncAt:void 0})),this.bound=!0}async readArtifact(t,r){return await this.ensureInitialized(),this.readJsonUnchecked(this.artifactKey(t,r))}async readArtifactWithText(t,r){await this.ensureInitialized();let n=this.artifactKey(t,r),i=(0,Wt.assertReadResult)(await this.storage.readText(n),n.join("/"));return i===null?null:{artifact:JSON.parse(i),text:i}}async writeArtifact(t,r,n,i){await this.ensureInitialized();let o=WC(n);if(i!==void 0&&o===i){await this.upsertManifestEntry(t,r,n,{unlessCurrent:!0});return}(0,Wt.assertMutationResult)(await this.storage.writeTextAtomic(this.artifactKey(t,r),o),"writeTextAtomic"),await this.upsertManifestEntry(t,r,n)}async deleteArtifact(t,r){await this.ensureInitialized(),(0,Wt.assertMutationResult)(await this.storage.deleteFile(this.artifactKey(t,r)),"deleteFile"),(0,Wt.assertMutationResult)(await this.storage.deleteFile(this.metaKey(t,r)),"deleteFile");let n=Cl(r);await this.withManifest(async()=>{let i=await this.getManifest();i.artifacts=i.artifacts.filter(o=>!(o.type===t&&o.id===n)),await this.writeManifest(i)})}async readMeta(t,r){return await this.ensureBound(),this.readJsonUnchecked(this.metaKey(t,r))}async writeMeta(t,r,n){await this.ensureBound(),await this.writeJsonUnchecked(this.metaKey(t,r),n)}async listArtifacts(t,r){return await this.ensureInitialized(),(await this.getManifest()).artifacts.filter(n=>!(t&&n.type!==t||r?.entityLogicalName&&n.entityLogicalName!==r.entityLogicalName))}async readEntityMetadata(t){await this.ensureInitialized();let r=await this.readJsonUnchecked(this.entityKey(t));return!r||typeof r.schemaName!="string"||typeof r.primaryNameAttribute!="string"||typeof r.primaryIdAttribute!="string"||typeof r.isCustomEntity!="boolean"?null:r}async writeEntityMetadata(t,r){await this.ensureInitialized(),await this.writeJsonUnchecked(this.entityKey(t),r)}async dropEntityMetadata(t){if(await this.ensureInitialized(),t===void 0){(0,Wt.assertMutationResult)(await this.storage.deleteByPrefix([Ba,qm]),"deleteByPrefix");return}(0,Wt.assertMutationResult)(await this.storage.deleteFile(this.entityKey(t)),"deleteFile")}async getManifest(){await this.ensureInitialized();let t=await this.readJsonUnchecked(this.manifestKey);if(!t)throw new Vn.WorkspaceNotInitializedError(this.workspaceLabel);return Vm(t),t}async writeManifest(t){await this.writeJsonUnchecked(this.manifestKey,{...t,schemaVersion:Vr.WORKSPACE_SCHEMA_VERSION})}async updateManifest(t){await this.withManifest(async()=>{let r=await this.getManifest();if(t.instanceUrl!==void 0&&Lc(String(t.instanceUrl))!==Lc(r.instanceUrl))throw new Vn.InvalidArgumentError("updateManifest cannot change the workspace's org: it is bound to the org it was created for. cleanWorkspace() discards its contents and binds it to the org of the SDK that calls it.");await this.writeManifest({...r,...t,instanceUrl:r.instanceUrl})})}async upsertManifestEntry(t,r,n,i={}){await this.withManifest(async()=>{let o=await this.getManifest(),a=Cl(r),s=n,l=typeof s.name=="string"?s.name:`${t}:${a}`,u=typeof s.entityLogicalName=="string"?s.entityLogicalName:void 0,c=o.artifacts.find(d=>d.type===t&&d.id===a);i.unlessCurrent&&c?.name===l&&c.entityLogicalName===u||(c?(c.name=l,c.entityLogicalName=u):o.artifacts.push({type:t,id:a,name:l,entityLogicalName:u,isDirty:!1}),await this.writeManifest(o))})}async readJson(t){return await this.ensureBound(),this.readJsonUnchecked(t)}async writeJson(t,r){this.assertDataKey(t,"writeJson"),await this.ensureBound(),await this.writeJsonUnchecked(t,r)}async removeFile(t){this.assertDataKey(t,"removeFile"),await this.ensureBound(),(0,Wt.assertMutationResult)(await this.storage.deleteFile(t),"deleteFile")}async exists(t){return await this.ensureBound(),this.storage.exists?(0,Wt.assertExistsResult)(await this.storage.exists(t),t.join("/")):(0,Wt.assertReadResult)(await this.storage.readText(t),t.join("/"))!==null}async readJsonUnchecked(t){let r=(0,Wt.assertReadResult)(await this.storage.readText(t),t.join("/"));return r===null?null:JSON.parse(r)}async writeJsonUnchecked(t,r){(0,Wt.assertMutationResult)(await this.storage.writeTextAtomic(t,WC(r)),"writeTextAtomic")}};Vr.WorkspaceManager=Gm;function WC(e){return`${JSON.stringify(e,null,2)}
+`}function Cl(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()}Vr.canonicalArtifactId=Cl});var Wm=v(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.deepEqual=qa.deepDiff=void 0;var eq=Ma();function tq(e,t){let r=[];return HC(e,t,"",r,0),r}qa.deepDiff=tq;var $c=Symbol("missing"),xc=512;function HC(e,t,r,n,i){if(e===t)return;if(i>xc)throw new RangeError(`deepDiff exceeded the maximum supported depth of ${xc}`);let o=Fc(e),a=Fc(t);if(o&&a&&Array.isArray(e)===Array.isArray(t)){let s=rq(e,t);for(let l of s){let u=jC(e,l),c=jC(t,l),d=eq.JsonPointer.append(r,l);u===$c?n.push({pointer:d,type:"added",newValue:c}):c===$c?n.push({pointer:d,type:"removed",oldValue:u}):HC(u,c,d,n,i+1)}return}KC(e,t)||n.push({pointer:r,type:"modified",oldValue:e,newValue:t})}function Fc(e){return e!==null&&typeof e=="object"}function rq(e,t){if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length),i=[];for(let o=0;o<n;o++)i.push(String(o));return i}let r=new Set([...Object.keys(e),...Object.keys(t)]);return Array.from(r)}function jC(e,t){if(Array.isArray(e)){let r=Number(t);return r<e.length?e[r]:$c}return t in e?e[t]:$c}function KC(e,t){return JC(e,t,0)}qa.deepEqual=KC;function JC(e,t,r){if(e===t)return!0;if(r>xc)throw new RangeError(`deepEqual exceeded the maximum supported depth of ${xc}`);if(!Fc(e)||!Fc(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(o=>o in t&&JC(e[o],t[o],r+1))}});var QC=v(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.VersionManager=Va.PROJECTION_VERSION=void 0;var YC=Wm(),nq=ye();Va.PROJECTION_VERSION=8;var zm=class{constructor(t){this.workspace=t}async storeMeta(t,r,n,i){var o;let a=i===void 0?await this.getMeta(t,r):i,s=((o=n.snapshot)===null||o===void 0?void 0:o.status)==="Active",l=a?.everActivated===!0||s;await this.workspace.writeMeta(t,r,l?{...n,everActivated:l}:n)}async getMeta(t,r){return this.workspace.readMeta(t,r)}async isDirty(t,r,n){let i=await this.workspace.readArtifact(t,r);if(i===null)return!1;let o=n===void 0?await this.getMeta(t,r):n;return o?!(0,YC.deepEqual)(o.snapshot,i):!0}async diff(t,r){let n=await this.workspace.readArtifact(t,r),i=await this.getMeta(t,r),o;return n===null?o=i?[{pointer:"",type:"removed",oldValue:i.snapshot}]:[]:i?o=(0,YC.deepDiff)(i.snapshot,n):o=[{pointer:"",type:"added",newValue:n}],{artifactType:t,artifactId:r,changes:o}}async checkConflict(t,r,n){let i=await this.getMeta(t,r);return!i||!(0,nq.isVersionToken)(i.etag)?!0:i.etag!==n}};Va.VersionManager=zm});var ZC=v((jm,XC)=>{(function(e,t){typeof define=="function"&&define.amd?define([],t):typeof jm=="object"?XC.exports=t():e.compareVersions=t()})(jm,function(){var e=/^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i;function t(o,a){return o.indexOf(a)===-1?o.length:o.indexOf(a)}function r(o){var a=o.replace(/^v/,"").replace(/\+.*$/,""),s=t(a,"-"),l=a.substring(0,s).split(".");return l.push(a.substring(s+1)),l}function n(o){return isNaN(Number(o))?o:Number(o)}function i(o){if(typeof o!="string")throw new TypeError("Invalid argument expected string");if(!e.test(o))throw new Error("Invalid argument not valid semver ('"+o+"' received)")}return function(a,s){[a,s].forEach(i);for(var l=r(a),u=r(s),c=0;c<Math.max(l.length-1,u.length-1);c++){var d=parseInt(l[c]||0,10),f=parseInt(u[c]||0,10);if(d>f)return 1;if(f>d)return-1}var m=l[l.length-1],p=u[u.length-1];if(m&&p){var h=m.split(".").map(n),g=p.split(".").map(n);for(c=0;c<Math.max(h.length,g.length);c++){if(h[c]===void 0||typeof g[c]=="string"&&typeof h[c]=="number")return-1;if(g[c]===void 0||typeof h[c]=="string"&&typeof g[c]=="number"||h[c]>g[c])return 1;if(g[c]>h[c])return-1}}else if(m||p)return m?-1:1;return 0}})});var iE=v(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.EnvironmentFlowHostingType=He.EnvironmentDisableReasonCode=He.EnvironmentMigrationConstants=He.EnvironmentProvisioningStates=He.EnvironmentLocations=He.EnvironmentCreationTypeConstants=He.EnvironmentType=He.EnvironmentSkuConstants=He.environmentPermissions=He.DatabaseType=void 0;var eE;(function(e){e.CommonDataService="CommonDataService",e.None="None"})(eE||(He.DatabaseType=eE={}));He.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"};He.EnvironmentSkuConstants={NotSpecified:"NotSpecified",Standard:"Standard",Premium:"Premium",Developer:"Developer",Basic:"Basic",Production:"Production",Sandbox:"Sandbox",Trial:"Trial",Default:"Default",Teams:"Teams",Platform:"Platform"};var tE;(function(e){e[e.CDS2=0]="CDS2",e[e.CDS1=1]="CDS1",e[e.Empty=2]="Empty"})(tE||(He.EnvironmentType=tE={}));He.EnvironmentCreationTypeConstants={NotSpecified:"NotSpecified",Legacy:"Legacy",DefaultTenant:"DefaultTenant",User:"User",CommonDataModelLegacy:"CommonDataModelLegacy"};He.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"};He.EnvironmentProvisioningStates={NotSpecified:"NotSpecified",Succeeded:"Succeeded",Deleting:"Deleting",Deleted:"Deleted",FailedDeleting:"FailedDeleting",LinkedDatabaseProvisioning:"LinkedDatabaseProvisioning",LinkedDatabaseFailedProvisioning:"LinkedDatabaseFailedProvisioning",LinkedDatabaseFailedConfiguring:"LinkedDatabaseFailedConfiguring",LinkedDatabaseUnavailable:"LinkedDatabaseUnavailable",Creating:"Creating"};He.EnvironmentMigrationConstants={phases:{completed:"Completed"}};var rE;(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"})(rE||(He.EnvironmentDisableReasonCode=rE={}));var nE;(function(e){e.LogicApps="LogicApps",e.SelfHostSingleTenant="SelfHostSingleTenant",e.SelfHostMultiTenant="SelfHostMultiTenant"})(nE||(He.EnvironmentFlowHostingType=nE={}))});var fE=v(_=>{"use strict";var iq=_&&_.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(_,"__esModule",{value:!0});_.hasCommonDataServiceDatabase=_.getEnvironmentDiscoveryUrl=_.getEnvironmentWebApiUrl=_.getEnvironmentInstanceApiUrl=_.getEnvironmentLanguageCode=_.getEnvironmentUpdateCadence=_.checkVersions=_.isCds2EnvironmentVersionAtLeast=_.getSecurityOrConnectedGroupId=_.hasSecurityGroupId=_.doesCds2VersionSupportApiVersion9_1=_.doesCds2EnvironmentSupportApiVersion9_1=_.cdsVersionSupportingOSColorEdit=_.getEnvironmentDisplayName=_.getEnvironmentName=_.isEnvironmentInFirstReleaseCluster=_.isEnvironmentInPreprodCluster=_.isEnvironmentInTestCluster=_.isLiteEnvironmentUpgrading=_.isEnvironmentExpired=_.isEnvironmentInDeletedState=_.isEnvironmentInCreatingState=_.isDatabaseInProvisioningState=_.canUserCreateDatabase=_.isDisabledEnvironment=_.isDefaultEnvironment=_.isTrialEnvironment=_.isPlatformEnvironment=_.isTeamsEnvironment=_.isSandboxEnvironment=_.isProdEnvironment=_.isDevEnvironment=_.getEnvironmentType=_.getCrmInstanceName=_.getCrmInstanceUrl=_.getCrmAppDesignerUrl=_.getDevResourcesUrl=_.isEnvironmentInSuccessfulState=_.getAllThemesUrl=_.getAllPublishersUrl=_.getAllSolutionsUrl=_.getSecurityRolesUrl=_.getSecurityUsersUrl=_.environmentHasCds2Database=_.DEFAULT_SOLUTION_UNIQUE_NAME=_.DEFAULT_SOLUTION_ID=_.crmBapSolutionId=_.doesUserHavePermission=_.getLinkedEnvironmentMetadata=_.getCrmVersion=void 0;_.doesUserHaveFlowRunOnlyPermission=_.isUserPautoMakerWithoutDataAccess=_.isUserPautoMakerWithDataAccess=_.doesUserHaveCreateFlowPermission=_.equalsIgnoreCase=_.doesUserHaveCreateDatabasePermission=_.doesUserHaveDatabaseTablePermissions=_.isUserMakerWithoutDataAccess=_.isUserMakerWithDataAccess=_.doesUserHaveCreateAppPermission=_.doesUserHaveAdminPermission=void 0;var oq=iq(ZC()),Pe=iE(),El=Km();function aq(e){let t=bi(e);return t&&t.version}_.getCrmVersion=aq;function bi(e){return e&&e.properties&&e.properties.linkedEnvironmentMetadata}_.getLinkedEnvironmentMetadata=bi;function yi(e,t){return e?!!e[t]:!1}_.doesUserHavePermission=yi;_.crmBapSolutionId="00000001-0000-0000-0001-00000000009b";_.DEFAULT_SOLUTION_ID="fd140aaf-4df4-11dd-bd17-0019b9312238";_.DEFAULT_SOLUTION_UNIQUE_NAME="Default";function xo(e){return!!bi(e)&&oE(e)}_.environmentHasCds2Database=xo;function sq(e){if(e&&xo(e)){let t=Zi(e);return(0,El.getCrmAdminSecurityRolesUrl)(t)}return""}_.getSecurityUsersUrl=sq;function lq(e){if(e&&xo(e)){let t=Zi(e);return(0,El.getCrmAdminSecurityUsersUrl)(t)}return""}_.getSecurityRolesUrl=lq;function uq(e){if(e&&xo(e)){let t=Zi(e);(0,El.getCrmAllSolutionsUrl)(t)}return""}_.getAllSolutionsUrl=uq;function cq(e){if(e&&xo(e)){let t=Zi(e);return(0,El.getCrmAllPublishersUrl)(t)}return""}_.getAllPublishersUrl=cq;function dq(e){return e&&xo(e)?Zi(e):""}_.getAllThemesUrl=dq;function oE(e){return!!e&&e.properties&&!!e.properties.provisioningState&&e.properties.provisioningState.toUpperCase()===Pe.EnvironmentProvisioningStates.Succeeded.toUpperCase()}_.isEnvironmentInSuccessfulState=oE;function fq(e){if(e&&xo(e)){let t=Zi(e);return(0,El.getCrmDevResourcesUrl)(t)}return""}_.getDevResourcesUrl=fq;function pq(e){return`${e}designer/app/{${_.crmBapSolutionId}}/CreateNewApp}}`}_.getCrmAppDesignerUrl=pq;function Zi(e){let t=bi(e);if(t){let r=t.instanceUrl;return r?r.endsWith("/")?r:r+"/":""}return""}_.getCrmInstanceUrl=Zi;function mq(e){let t=bi(e);return t?t.uniqueName:""}_.getCrmInstanceName=mq;function hq(e){return bi(e)?Pe.EnvironmentType.CDS2:e&&e.properties&&e.properties.namespace?Pe.EnvironmentType.CDS1:Pe.EnvironmentType.Empty}_.getEnvironmentType=hq;function gq(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Developer}_.isDevEnvironment=gq;function yq(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Production}_.isProdEnvironment=yq;function bq(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Sandbox}_.isSandboxEnvironment=bq;function Al(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Teams}_.isTeamsEnvironment=Al;function vq(e){return e&&e.properties&&e.properties.environmentSku===Pe.EnvironmentSkuConstants.Platform}_.isPlatformEnvironment=vq;var wq=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.environmentSku)===Pe.EnvironmentSkuConstants.Trial};_.isTrialEnvironment=wq;function Cq(e){return e&&e.properties&&(e.properties.isDefault||e.properties.creationType===Pe.EnvironmentCreationTypeConstants.DefaultTenant)}_.isDefaultEnvironment=Cq;function Eq(e){return e&&e.properties&&!!e.properties.states&&!!e.properties.states.runtime&&e.properties.states.runtime.id==="Disabled"}_.isDisabledEnvironment=Eq;function Aq(e){return e&&e.properties&&yi(e.properties.permissions,Pe.environmentPermissions.CreateDatabase)}_.canUserCreateDatabase=Aq;function Sq(e){return!!(e&&e.properties&&e.properties.provisioningState&&dE(e.properties.provisioningState,Pe.EnvironmentProvisioningStates.LinkedDatabaseProvisioning))}_.isDatabaseInProvisioningState=Sq;function Nq(e){return!!e&&!!e.properties&&e.properties.provisioningState===Pe.EnvironmentProvisioningStates.Creating}_.isEnvironmentInCreatingState=Nq;function _q(e){return e&&e.properties&&(e.properties.provisioningState===Pe.EnvironmentProvisioningStates.Deleted||e.properties.provisioningState===Pe.EnvironmentProvisioningStates.Deleting||e.properties.provisioningState===Pe.EnvironmentProvisioningStates.FailedDeleting)}_.isEnvironmentInDeletedState=_q;function Tq(e){return!!e&&!!e.properties&&!!e.properties.expirationTime&&Date.parse(e.properties.expirationTime)<Date.now()}_.isEnvironmentExpired=Tq;function Dq(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"}_.isLiteEnvironmentUpgrading=Dq;function Iq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Test"}_.isEnvironmentInTestCluster=Iq;function Oq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="Preprod"}_.isEnvironmentInPreprodCluster=Oq;function Pq(e){return!!e&&!!e.properties&&!!e.properties.cluster&&e.properties.cluster.category==="FirstRelease"}_.isEnvironmentInFirstReleaseCluster=Pq;function Rq(e){return e&&e.name||""}_.getEnvironmentName=Rq;function kq(e){return e&&e.properties&&e.properties.displayName||""}_.getEnvironmentDisplayName=kq;var aE="9.1.0.8202";_.cdsVersionSupportingOSColorEdit="9.1.0000.20708";function Lq(e){return uE(e,aE)}_.doesCds2EnvironmentSupportApiVersion9_1=Lq;function $q(e){return Hm(e,aE)}_.doesCds2VersionSupportApiVersion9_1=$q;function sE(e){let t=bi(e);if(t)return t.securityGroupId}function lE(e){return e&&e.properties&&e.properties.connectedGroups}function xq(e,t){let r=lE(e);return!!r&&!!r.find(n=>n.id===t)||sE(e)===t}_.hasSecurityGroupId=xq;function Fq(e){let t=lE(e);return t&&t.length>0&&t[0].id?t[0].id:sE(e)}_.getSecurityOrConnectedGroupId=Fq;function uE(e,t){let r=e.version;return r?Hm(r,t):!1}_.isCds2EnvironmentVersionAtLeast=uE;function Hm(e,t){return t?e?(0,oq.default)(e,t)>=0:!1:!0}_.checkVersions=Hm;function Mq(e){return e&&e.properties&&e.properties.updateCadence&&e.properties.updateCadence.id||"NotSpecified"}_.getEnvironmentUpdateCadence=Mq;function Uq(e){let t=bi(e);return t?Number(t.baseLanguage):0}_.getEnvironmentLanguageCode=Uq;function cE(e){let t=bi(e);return t?t.instanceApiUrl:void 0}_.getEnvironmentInstanceApiUrl=cE;function Bq(e){let t=cE(e);return t?t+"/api/data/v9.2":""}_.getEnvironmentWebApiUrl=Bq;function qq(e){let t=Zi(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"}_.getEnvironmentDiscoveryUrl=qq;var Vq=e=>{var t;return((t=e.properties)===null||t===void 0?void 0:t.databaseType)===Pe.DatabaseType.CommonDataService};_.hasCommonDataServiceDatabase=Vq;var Gq=e=>{var t;return yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.AdminReadEnvironment)};_.doesUserHaveAdminPermission=Gq;var Wq=e=>{var t;return yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.CreatePowerApp)};_.doesUserHaveCreateAppPermission=Wq;var zq=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateAppPermission)(e)?Al(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserMakerWithDataAccess=zq;var jq=e=>(0,_.doesUserHaveCreateAppPermission)(e)&&!Al(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserMakerWithoutDataAccess=jq;var Hq=e=>[Pe.environmentPermissions.CreateDatabaseEntities,Pe.environmentPermissions.ListDatabaseEntities,Pe.environmentPermissions.UpdateDatabaseEntities,Pe.environmentPermissions.DeleteDatabaseEntities].every(t=>{var r;return yi((r=e.properties)===null||r===void 0?void 0:r.permissions,t)});_.doesUserHaveDatabaseTablePermissions=Hq;var Kq=e=>{var t;return yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.CreateDatabase)};_.doesUserHaveCreateDatabasePermission=Kq;function dE(e,t){return!e&&!t?!0:!e||!t?!1:e.toUpperCase()===t.toUpperCase()}_.equalsIgnoreCase=dE;var Jq=e=>{var t;return yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.CreateFlow)};_.doesUserHaveCreateFlowPermission=Jq;var Yq=e=>(0,_.doesUserHaveAdminPermission)(e)&&(0,_.hasCommonDataServiceDatabase)(e)?!0:(0,_.doesUserHaveCreateFlowPermission)(e)?Al(e)||(0,_.doesUserHaveDatabaseTablePermissions)(e):!1;_.isUserPautoMakerWithDataAccess=Yq;var Qq=e=>(0,_.doesUserHaveCreateFlowPermission)(e)&&!Al(e)&&!(0,_.doesUserHaveDatabaseTablePermissions)(e)&&(!(0,_.doesUserHaveAdminPermission)(e)||!(0,_.hasCommonDataServiceDatabase)(e));_.isUserPautoMakerWithoutDataAccess=Qq;var Xq=e=>{var t,r;return!yi((t=e.properties)===null||t===void 0?void 0:t.permissions,Pe.environmentPermissions.CreateFlow)&&yi((r=e.properties)===null||r===void 0?void 0:r.permissions,Pe.environmentPermissions.ReadEnvironment)};_.doesUserHaveFlowRunOnlyPermission=Xq});var Km=v(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.getRequiredComponentsQueryUrl=A.solutionComponentCountSummariesQueryUrl=A.solutionComponentSummariesQueryUrl=A.solutionComponentConfigurationsQueryUrl=A.chartsQueryUrl=A.workflowsQueryUrl=A.entityDefinitionsQueryUrl=A.solutionComponentDefinitionsQueryUrl=A.getCreateNewArticleTemplateUrl=A.getCreateNewPublisherUrl=A.getEnableSecurityRolesUrl=A.getArticleTemplateUrl=A.getFieldSecurityProfileDesignerUrl=A.getSecurityRoleDesignerUrl=A.getMailMergeTemplateDesignerUrl=A.getEmailTemplateDesignerUrl=A.getConnectionRoleDesignerUrl=A.getSiteMapDesignerUrl=A.getWebResourceFileUrl=A.getWebResourceDesignerUrl=A.getReportDesignerUrl=A.getBusinessProcessFlowDesignerUrl=A.getProcessShareUrl=A.getProcessDesignerUrl=A.getChartDesignerUrl=A.getOpenModernEntityDashboardUrl=A.getNewModernEntityDashboardUrl=A.getNewModernDashboardUrl=A.getOpenModernDashboardUrl=A.getDashboardDesignerUrl=A.getAppModuleDesignerUrl=A.privilegesQueryUrls=A.xrmApiUrl=A.getPlayAppModuleUrl=A.getCrmAdminSecurityUsersUrl=A.getCrmAdminSecurityRolesUrl=A.getCrmMyAppsUrl=A.getCrmAppDesignerUrl=A.getCrmDevResourcesUrl=A.getCrmAllPublishersUrl=A.getCrmAllSolutionsUrl=A.getSolutionPublisherUrl=A.getExportTranslationFileName=A.getExportSolutionTranslationUrl=A.getImportSolutionTranslationUrl=A.getShowSolutionDependenciesUrl=A.getShowComponentDependenciesUrl=A.cdsServiceUrl=A.ODATA_NEXT_LINK=A.ODATA_MAX_PAGE_SIZE=void 0;A.retrieveOrganizationResources=A.getUCIEntityRecordEditUrl=A.getUCIEntityRecordBaseUrl=A.getBusinessRuleDesignerUri=A.retrieveUnpublishedSuffix=A.getSavePowerSettingUri=A.getPowerSettingUri=A.getPowerSettingsUri=A.RetrievePlatform=A.getAppSettingOverrideUri=A.AppSettingOverrideName=A.getOrgSettingOverrideUri=A.OrgSettingOverrideName=A.getSettingDefinitionsUri=A.retrieveFeatureControlSettingsByNamespaceUrl=A.retrieveDeploymentPipelineConfigAppUrl=A.SPNPrincipalIdUrl=A.retrieveDeploymentEnvironmentInfoUrl=A.devSolutionInfoUrl=A.deployOperationStatusUrl=A.getAIGeneratedDeploymentNotesUrl=A.deploymentStageRunUrl=A.validatePackageAsyncUrl=A.deployPackageAsyncUrl=A.updateDeploymentStageRunUrl=A.createDeploymentStageRunUrl=A.retrieveDeploymentStagesUrl=A.retrievePipelinesUrl=A.retrieveDeploymentPipelineInfoUrl=A.getDeploymentStageRunsUrl=A.appDeploymentUrls=A.getProvisionLanguageUrl=A.getSolutionQueryUrl=A.getSolutionsByUniqueNameQueryUrl=A.solutionsQueryUrl=A.getDependentComponentsWithMetadataQueryUrl=void 0;var pE=fE();A.ODATA_MAX_PAGE_SIZE="odata.maxpagesize";A.ODATA_NEXT_LINK="@odata.nextLink";A.cdsServiceUrl="https://cds-org/";var Nl;(function(e){e.AllSolutions="11",e.AllPublishers="10",e.DevResources="05"})(Nl||(Nl={}));function Zq(e,t,r,n){return`${e}tools/dependency/dependencyviewdialog.aspx?appSolutionId=%7b${t}%7d&dType=1&objectid=%7b${r}%7d&objecttype=${n}&operationtype=showdependency`}A.getShowComponentDependenciesUrl=Zq;function e3(e,t){let r=`dType=1&isproactivecheck=true&objecttype=7100&operationtype=dependenciesforuninstall&objectid=${t}`;return`${e}tools/dependency/dependencyviewdialog.aspx?${r}`}A.getShowSolutionDependenciesUrl=e3;function t3(e,t){return`${e}tools/muiProvisioning/Dialogs/LangTranslationsImport.aspx?dType=1&appSolutionId=${t}`}A.getImportSolutionTranslationUrl=t3;function r3(e,t){return`${e}_grid/cmds/dlg_exportsolution.aspx?command=exporttranslation&appSolutionId=${t}`}A.getExportSolutionTranslationUrl=r3;function n3(e,t){return e!==void 0&&t!==void 0&&`CrmTranslations_${e}_${t.replace(/[.]/g,"_")}.zip`||""}A.getExportTranslationFileName=n3;function i3(e,t,r){return r?`${e}tools/publisher/edit.aspx?appSolutionId=%7b${r}%7d&id=%7b${t}%7d`:`${e}tools/publisher/edit.aspx?id=%7b${t}%7d`}A.getSolutionPublisherUrl=i3;function Jm(e,t){return`${e}tools/systemcustomization/systemCustomization.aspx?pid=${t}`}function o3(e){return Jm(e,Nl.AllSolutions)}A.getCrmAllSolutionsUrl=o3;function a3(e){return Jm(e,Nl.AllPublishers)}A.getCrmAllPublishersUrl=a3;function s3(e){return Jm(e,Nl.DevResources)}A.getCrmDevResourcesUrl=s3;function l3(e,t=pE.crmBapSolutionId){return`${e}designer/app/${t}#/CreateNewApp`}A.getCrmAppDesignerUrl=l3;function u3(e){return`${e}apps`}A.getCrmMyAppsUrl=u3;function c3(e){return mE(e,"role")+"&forceUCI=0"}A.getCrmAdminSecurityRolesUrl=c3;function d3(e){return`${mE(e,"systemuser")}&forceclassic=1`}A.getCrmAdminSecurityUsersUrl=d3;function mE(e,t){return`${e}main.aspx?pagetype=entitylist&etn=${t}`}function f3(e,t){return`${e}main.aspx?appid=${t}`}A.getPlayAppModuleUrl=f3;A.xrmApiUrl="api/data/v9.0";A.privilegesQueryUrls={systemUserInfo:e=>`${e}${A.xrmApiUrl}/WhoAmI`,userPrivileges:(e,t)=>`${e}${A.xrmApiUrl}/systemusers(${t})/Microsoft.Dynamics.CRM.RetrieveUserPrivileges`,systemPrivileges:e=>`${e}${A.xrmApiUrl}/privileges/Microsoft.Dynamics.CRM.RetrievePrivilegeSet`};function p3(e,t,r=pE.crmBapSolutionId){return`${e}designer/app/${r}/${t}/AppDesignerCanvas/${t}`}A.getAppModuleDesignerUrl=p3;function m3(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${r}%7d&extraqs=%26formId%3d%7b${t}%7d%26dashboardType%3d1030&pagetype=${`${n?"ic":""}dashboardeditor`}`}A.getDashboardDesignerUrl=m3;function h3(e,t,r){return`/e/${e}/s/${t}/dashboard/${r}`}A.getOpenModernDashboardUrl=h3;function g3(e,t,r){let n=r!==void 0?r.toString():void 0;return`/e/${e}/s/${t}/dashboard/new${n?`/${n}`:""}`}A.getNewModernDashboardUrl=g3;function y3(e,t,r,n){let i=n!==void 0?n.toString():void 0;return`/e/${e}/s/${t}/n/${r}/dashboard/new${i?`/${i}`:""}`}A.getNewModernEntityDashboardUrl=y3;function b3(e,t,r,n){return`/e/${e}/s/${t}/n/${r}/dashboard/${n}`}A.getOpenModernEntityDashboardUrl=b3;function v3(e,t,r,n){return`${e}main.aspx?appSolutionId=%7b${t}%7d&extraqs=etc=${r||""}`+(n?`%26id=${n}`:"")+"&pagetype=vizdesigner"}A.getChartDesignerUrl=v3;function w3(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessDesignerUrl=w3;function C3(e,t,r){return`${e}sfa/workflow/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getProcessShareUrl=C3;function E3(e,t){return`${e}Tools/ProcessControl/UnifiedProcessDesigner.aspx?id=${t}`}A.getBusinessProcessFlowDesignerUrl=E3;function A3(e,t,r){return`${e}CRMReports/reportproperty.aspx?appSolutionId=%7b${r}%7d&disablePersonal=true&id=%7b${t}%7d`}A.getReportDesignerUrl=A3;function S3(e,t,r){return`${e}main.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&etc=9333&id=%7b${t}%7d&pagetype=webresourceedit`}A.getWebResourceDesignerUrl=S3;function N3(e,t){return`${e}WebResources/${t}`}A.getWebResourceFileUrl=N3;function _3(e,t,r){return`${e}designer/sitemap/${r}/${t}/SiteMapHome/${t}`}A.getSiteMapDesignerUrl=_3;function T3(e,t,r){return`${e}connections/connectionroles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getConnectionRoleDesignerUrl=T3;function D3(e,t,r){return`${e}tools/emailtemplateeditor/emailtemplateeditor.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getEmailTemplateDesignerUrl=D3;function I3(e,t,r){return`${e}tools/mailmerge/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getMailMergeTemplateDesignerUrl=I3;function O3(e,t,r){return`${e}biz/roles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getSecurityRoleDesignerUrl=O3;function P3(e,t,r){return`${e}biz/fieldsecurityprofiles/edit.aspx?_CreateFromId=%7b${r}%7d&_CreateFromType=7100&appSolutionId=%7b${r}%7d&id=%7b${t}%7d`}A.getFieldSecurityProfileDesignerUrl=P3;function R3(e,t,r){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?_CreateFromId=%7b${t}%7d&_CreateFromType=7100&appSolutionId=%7b${t}%7d&id=%7b${r}%7d`}A.getArticleTemplateUrl=R3;function k3(e,t,r,n){return`${e}tools/FormEditor/Dialogs/FormRoleAssignment.aspx?appSolutionId=%7b${t}%7d&dType=1&formId=%7b${r}%7d&objectTypeCode=0&type=${n}`}A.getEnableSecurityRolesUrl=k3;function L3(e){return`${e}tools/publisher/edit.aspx`}A.getCreateNewPublisherUrl=L3;function $3(e,t){return`${e}tools/kbtemplateeditor/kbtemplateeditor.aspx?appSolutionId=${t}`}A.getCreateNewArticleTemplateUrl=$3;A.solutionComponentDefinitionsQueryUrl="api/data/v9.0/solutioncomponentdefinitions";A.entityDefinitionsQueryUrl="api/data/v9.0/EntityDefinitions?$select=EntitySetName,DisplayName,LogicalName&$filter=";A.workflowsQueryUrl="api/data/v9.0/workflows";A.chartsQueryUrl="/api/data/v9.0/savedqueryvisualizations";A.solutionComponentConfigurationsQueryUrl="/api/data/v9.1/solutioncomponentconfigurations?$filter=isdisplayable eq true&$select=name";A.solutionComponentSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentsummaries";A.solutionComponentCountSummariesQueryUrl="/api/data/v9.0/msdyn_solutioncomponentcountsummaries";function x3(e,t){return`${A.xrmApiUrl}/RetrieveRequiredComponents(ObjectId=${e},ComponentType=${t})`}A.getRequiredComponentsQueryUrl=x3;function F3(e,t){return`${A.cdsServiceUrl}${A.xrmApiUrl}/RetrieveDependentComponentsWithMetadata(ObjectId=${e},ComponentType=${t})`}A.getDependentComponentsWithMetadataQueryUrl=F3;A.solutionsQueryUrl="/api/data/v9.0/solutions?$expand=publisherid&$filter=(isvisible eq true)";function M3(e){return`/api/data/v9.0/solutions?$expand=publisherid&$filter=(uniquename eq '${e}')`}A.getSolutionsByUniqueNameQueryUrl=M3;function U3(e){return`/api/data/v9.0/solutions(${e})?$expand=publisherid`}A.getSolutionQueryUrl=U3;function B3(e){return`${e}api/data/v9.1/ProvisionLanguageForUser`}A.getProvisionLanguageUrl=B3;A.appDeploymentUrls={associateEnvironmentToPipelineUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})/deploymentpipeline_deploymentenvironment/$ref`,deploymentArtifactsUrl:"/api/data/v9.0/deploymentartifacts",deploymentEnvironmentUrl:"/api/data/v9.0/deploymentenvironments",deploymentPipelinesUrl:"/api/data/v9.0/deploymentpipelines",deploymentStagesUrl:"/api/data/v9.0/deploymentstages",retrieveDeploymentPipelinesUrl:e=>`/api/data/v9.0/RetrieveDeploymentPipelines(SourceEnvironmentId='${e}')`,deletePipelinesUrl:e=>`/api/data/v9.0/deploymentpipelines(${e})`};function q3(e,t,r,n=!1,i=!1,o=!1,a=!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,${o?"predeploymentstepnotes,":""}validationresults,${a?"approvalcomments,":""}_devdeploymentenvironment_value,_targetdeploymentenvironment_value
&$expand=deploymentstageid($select=deploymentstageid,name,_deploymentpipelineid_value),targetdeploymentenvironment($select=deploymentenvironmentid,environmentid,name),createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)${l?",RetryUser($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}
&$filter=deploymentstageid/_deploymentpipelineid_value eq ${e} and devenvironmentid eq '${t}' and artifactname eq '${r}' and ((operation ne 200000201) or (operation eq 200000201 and operationstatus eq 200000003))
- &$orderby=starttime desc`}A.getDeploymentStageRunsUrl=P3;function R3(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}A.retrieveDeploymentPipelineInfoUrl=R3;function L3(e){return`/api/data/v9.0/deploymentenvironments
+ &$orderby=starttime desc`}A.getDeploymentStageRunsUrl=q3;function V3(e,t,r){return`/api/data/v9.1/RetrieveDeploymentPipelineInfo(DeploymentPipelineId=${e},SourceEnvironmentId='${t}',ArtifactName='${r}')`}A.retrieveDeploymentPipelineInfoUrl=V3;function G3(e){return`/api/data/v9.0/deploymentenvironments
?$select=deploymentenvironmentid,environmentid,environmenttype,name
&$expand=deploymentpipeline_deploymentenvironment($select=name,description,deploymentpipelineid;$orderby=name asc)
- &$filter=(environmentid eq '${e}')`}A.retrievePipelinesUrl=L3;function k3(e){return`/api/data/v9.0/deploymentstages
+ &$filter=(environmentid eq '${e}')`}A.retrievePipelinesUrl=G3;function W3(e){return`/api/data/v9.0/deploymentstages
?$filter=(_deploymentpipelineid_value eq ${e})
&$select=name,description,deploymentstageid,_previousdeploymentstageid_value
- &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}A.retrieveDeploymentStagesUrl=k3;function $3(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}A.createDeploymentStageRunUrl=$3;function x3(e){return`/api/data/v9.0/deploymentstageruns(${e})`}A.updateDeploymentStageRunUrl=x3;function F3(){return"/api/data/v9.0/DeployPackageAsync"}A.deployPackageAsyncUrl=F3;function M3(){return"/api/data/v9.0/ValidatePackageAsync"}A.validatePackageAsyncUrl=M3;function U3(e,t=!1,r=!1){return`/api/data/v9.0/deploymentstageruns(${e})
- ?$select=deploymentstagerunid,stagerunstatus,errormessage,operation,operationdetails,operationstatus,${t?"scheduledtime,":""}targetenvironmentid,validationresults,artifactname,deploymentsettingsjson${r?"&$expand=createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}`}A.deploymentStageRunUrl=U3;function B3(e){return`/api/data/v9.0/deploymentstageruns(${e})
- ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}A.getAIGeneratedDeploymentNotesUrl=B3;function q3(e){let t="";for(let r=0;r<e.length;r++)r===e.length-1?t=t.concat(`deploymentstagerunid eq ${e[r]}`):t=t.concat(`deploymentstagerunid eq ${e[r]} or `);return`/api/data/v9.0/deploymentstageruns
+ &$expand=targetdeploymentenvironmentid($select=deploymentenvironmentid,environmentid,name)`}A.retrieveDeploymentStagesUrl=W3;function z3(){return"/api/data/v9.0/deploymentstageruns?$select=deploymentstagerunid"}A.createDeploymentStageRunUrl=z3;function j3(e){return`/api/data/v9.0/deploymentstageruns(${e})`}A.updateDeploymentStageRunUrl=j3;function H3(){return"/api/data/v9.0/DeployPackageAsync"}A.deployPackageAsyncUrl=H3;function K3(){return"/api/data/v9.0/ValidatePackageAsync"}A.validatePackageAsyncUrl=K3;function J3(e,t=!1,r=!1){return`/api/data/v9.0/deploymentstageruns(${e})
+ ?$select=deploymentstagerunid,stagerunstatus,errormessage,operation,operationdetails,operationstatus,${t?"scheduledtime,":""}targetenvironmentid,validationresults,artifactname,deploymentsettingsjson${r?"&$expand=createdby($select=azureactivedirectoryobjectid,fullname,ownerid,systemuserid)":""}`}A.deploymentStageRunUrl=J3;function Y3(e){return`/api/data/v9.0/deploymentstageruns(${e})
+ ?$select=aigenerateddeploymentnotes,deploymentstagerunid`}A.getAIGeneratedDeploymentNotesUrl=Y3;function Q3(e){let t="";for(let r=0;r<e.length;r++)r===e.length-1?t=t.concat(`deploymentstagerunid eq ${e[r]}`):t=t.concat(`deploymentstagerunid eq ${e[r]} or `);return`/api/data/v9.0/deploymentstageruns
?$filter=(${t})
- &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}A.deployOperationStatusUrl=q3;function V3(e){return`/api/data/v9.0/solutions(${e})
- ?$select=solutionid,uniquename,version`}A.devSolutionInfoUrl=V3;function G3(e){return`/api/data/v9.0/deploymentenvironments
+ &$select=_deploymentstageid_value,deploymentstagerunid,stagerunstatus,operation,operationstatus,suboperation,artifactname`}A.deployOperationStatusUrl=Q3;function X3(e){return`/api/data/v9.0/solutions(${e})
+ ?$select=solutionid,uniquename,version`}A.devSolutionInfoUrl=X3;function Z3(e){return`/api/data/v9.0/deploymentenvironments
?$select=deploymentenvironmentid,environmentid,environmenttype,name
- &$filter=(environmentid eq '${e}')`}A.retrieveDeploymentEnvironmentInfoUrl=G3;var W3=e=>`/api/data/v9.0/systemusers
+ &$filter=(environmentid eq '${e}')`}A.retrieveDeploymentEnvironmentInfoUrl=Z3;var eV=e=>`/api/data/v9.0/systemusers
?$select=azureactivedirectoryobjectid
- &$filter=(applicationid eq '${e}')`;A.SPNPrincipalIdUrl=W3;function z3(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}A.retrieveDeploymentPipelineConfigAppUrl=z3;A.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function j3(e){return`/api/data/v9.0/settingdefinitions${e}`}A.getSettingDefinitionsUri=j3;A.OrgSettingOverrideName="organizationsettings";function H3(e,t=!1){let r=`/api/data/v9.0/${A.OrgSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl}${r}`:r}A.getOrgSettingOverrideUri=H3;A.AppSettingOverrideName="appsettings";function K3(e,t=!1){let r=`/api/data/v9.0/${A.AppSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl.replace("/$","")}${r}`:r}A.getAppSettingOverrideUri=K3;var wl;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(wl||(A.RetrievePlatform=wl={}));function J3(e,t,r,n=wl.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),r&&o.push(`RetrieveHiddenSettings=${r}`),n!==wl.All&&o.push(`RetrievePlatformSettings=${n===wl.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${A.cdsServiceUrl}${a}`:a}A.getPowerSettingsUri=J3;function Y3(e,t,r,n=!1){let i=[`SettingName='${e}'`];t!==void 0&&i.push(`SolutionName='${t}'`),r!==void 0&&i.push(`AppUniqueName='${r}'`);let o="/api/data/v9.0/RetrieveUnpublishedSettingInfo";return i.length&&(o=`${o}(${i.join(",")})`),n?`${A.cdsServiceUrl}${o}`:o}A.getPowerSettingUri=Y3;function Q3(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${A.cdsServiceUrl}${t}`:t}A.getSavePowerSettingUri=Q3;A.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function X3(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}A.getBusinessRuleDesignerUri=X3;function oE({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}A.getUCIEntityRecordBaseUrl=oE;function Z3({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||oE({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}A.getUCIEntityRecordEditUrl=Z3;A.retrieveOrganizationResources=`${A.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var lE=v(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});Pc.DataverseClient=void 0;var eV=Bm(),$o=Q(),aE=ye(),tV=new Set(["entitydefinitions","relationshipdefinitions","globaloptionsetdefinitions"]);function rV(e){var t,r,n,i;let o=e.split("?")[0].split("/").filter(l=>l!==""),a=((t=o[0])===null||t===void 0?void 0:t.toLowerCase())==="api"&&((r=o[1])===null||r===void 0?void 0:r.toLowerCase())==="data"&&/^v\d/i.test((n=o[2])!==null&&n!==void 0?n:""),s=((i=o[a?3:0])!==null&&i!==void 0?i:"").split("(")[0].toLowerCase();return tV.has(s)}function nV(e){let t=e.indexOf("://"),r=t===-1?"":e.slice(t+3),n=r.search(/[/?#]/),i=n===-1?"":r.slice(n),o=i.search(/[?#]/);return o===-1?i:i.slice(0,o)}function sE(e,t){var r;if(!rV(e))return t;let n=(r=t?.headers)!==null&&r!==void 0?r:{};return Object.keys(n).some(i=>i.toLowerCase()==="consistency")?t:{...t,headers:{...n,Consistency:"Strong"}}}var Vm=class e{constructor(t,r,n,i=1){this.instanceUrl=t,this.httpClient=r,this.solutionUniqueName=n,this.readConcurrency=i}withSolutionScope(t){return new e(this.instanceUrl,this.httpClient,t,this.readConcurrency)}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}/${eV.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof $o.SdkError?n:new $o.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t),i=sE(t,r);return(0,aE.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,i)))}getAbsolute(t,r){this.assertSameOrigin(t);let n=sE(nV(t),r);return(0,aE.resendDeadlockVictim)(()=>this.send(t,()=>this.httpClient.get(t,n)))}assertSameOrigin(t){let r,n;try{r=new URL(t),n=new URL(this.instanceUrl)}catch{throw new $o.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new $o.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 supportsPut(){return typeof this.httpClient.put=="function"}get solutionName(){return this.solutionUniqueName}postBatch(t,r,n){if(!this.httpClient.postRaw)throw new $o.InvalidArgumentError("The injected HttpClient does not implement postRaw(), required for atomic $batch change sets");let i=this.apiUrl("/$batch"),o={...n,headers:{...n?.headers,"Content-Type":`multipart/mixed;boundary=${r}`}};return this.send(i,()=>this.httpClient.postRaw(i,t,o))}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 $o.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 $o.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)))}};Pc.DataverseClient=Vm});var dE=v(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.findColumns=rr.findTables=rr.readCheckColumns=rr.readColumnHints=rr.fetchEntityMetadataFromApi=rr.COLUMN_DETAIL_VERSION=void 0;var kc=ye(),hr=se();function Yr(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}rr.COLUMN_DETAIL_VERSION=2;function Gm(e){var t,r;return typeof((t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)=="string"||((r=e?.LocalizedLabels)!==null&&r!==void 0?r:[]).some(n=>typeof n?.Label=="string")}function xo(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 Rc(e,t){return(await $c(e,t)).rows}async function $c(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?{rows:[],ok:!1}:{rows:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[],ok:!0}}function Br(e){return`/EntityDefinitions(LogicalName='${(0,hr.odataPathLiteral)(e)}')`}async function iV(e,t,r){let n=await Rc(e,`${Br(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,hr.odataQuery)([["$select","LogicalName,MaxLength"]])}`);for(let i of n){let o=r.get(i.LogicalName);o&&typeof i.MaxLength=="number"&&(o.maxLength=i.MaxLength)}}function oV(e){return`${Br(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,hr.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function aV(e,t){var r;let{rows:n}=await e;for(let i of n){let o=t.get(i.LogicalName);o&&(!((r=i.OptionSet)===null||r===void 0)&&r.Options)&&(o.options=i.OptionSet.Options.map(a=>{var s;return{value:(s=a.Value)!==null&&s!==void 0?s:0,label:Yr(a.Label),...xo(a.Label)?{localizedLabel:xo(a.Label)}:{}}}))}}function Wm(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:Yr(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function sV(e,t,r){var n;let i=c=>$c(e,c).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([r.catch(()=>({rows:[],ok:!1})),...o.map(c=>i(`${Br(t)}/Attributes/Microsoft.Dynamics.CRM.${c}${(0,hr.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`))]),s=new Map,l=!0;for(let{rows:c}of a)for(let d of c)!((n=d.OptionSet)===null||n===void 0)&&n.Options&&(l=l&&d.OptionSet.Options.every(f=>Gm(f.Label)),s.set(d.LogicalName,d.OptionSet.Options.map(Wm)));let u=await i(`${Br(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,hr.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let c of u.rows){let d=c.OptionSet;d?.TrueOption&&d.FalseOption&&(l=l&&Gm(d.TrueOption.Label)&&Gm(d.FalseOption.Label),s.set(c.LogicalName,[Wm(d.FalseOption),Wm(d.TrueOption)]))}return{byColumn:s,complete:l&&u.ok&&a.every(c=>c.ok)}}async function lV(e,t,r){let{rows:n,ok:i}=await $c(e,`${Br(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,hr.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let o of n){let a=r.get(o.LogicalName);a&&o.Targets&&(a.targets=o.Targets)}return i}function Lc(e,t){return e<t?-1:e>t?1:0}var uE={OneToMany:0,ManyToOne:1,ManyToMany:2};function uV(e,t){return uE[e.type]-uE[t.type]||Lc(e.schemaName,t.schemaName)||Lc(e.relatedEntity,t.relatedEntity)||Lc(e.relatedAttribute,t.relatedAttribute)}async function cV(e,t){var r,n,i,o;let a=[],s=await Rc(e,`${Br(t)}/OneToManyRelationships${(0,hr.odataQuery)([["$select","SchemaName,ReferencingEntity,ReferencingAttribute"]])}`);for(let c of s)a.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 Rc(e,`${Br(t)}/ManyToOneRelationships${(0,hr.odataQuery)([["$select","SchemaName,ReferencedEntity,ReferencedAttribute"]])}`);for(let c of l)a.push({schemaName:c.SchemaName,type:"ManyToOne",relatedEntity:(i=c.ReferencedEntity)!==null&&i!==void 0?i:"",relatedAttribute:(o=c.ReferencedAttribute)!==null&&o!==void 0?o:""});let u=await Rc(e,`${Br(t)}/ManyToManyRelationships${(0,hr.odataQuery)([["$select","SchemaName,Entity1LogicalName,Entity2LogicalName"]])}`);for(let c of u){let d=c.Entity1LogicalName===t?c.Entity2LogicalName:c.Entity1LogicalName;a.push({schemaName:c.SchemaName,type:"ManyToMany",relatedEntity:d??"",relatedAttribute:""})}return a.sort(uV)}async function dV(e,t){var r,n,i,o,a;let s=`${Br(t)}`+(0,hr.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf)"]]),u=(0,kc.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(g=>{var b,w,E;return{logicalName:g.LogicalName,displayName:Yr(g.DisplayName),...xo(g.DisplayName)?{localizedDisplayName:xo(g.DisplayName)}:{},attributeType:(b=g.AttributeType)!==null&&b!==void 0?b:"Unknown",isCustomAttribute:!!g.IsCustomAttribute,attributeTypeName:(E=(w=g.AttributeTypeName)===null||w===void 0?void 0:w.Value)!==null&&E!==void 0?E:"",...typeof g.IsValidForUpdate=="boolean"?{isValidForUpdate:g.IsValidForUpdate}:{},...typeof g.IsValidForRead=="boolean"?{isValidForRead:g.IsValidForRead}:{},...g.AttributeOf?{attributeOf:g.AttributeOf}:{},...Yr(g.Description)?{description:Yr(g.Description)}:{}}}).sort((g,b)=>Lc(g.logicalName,b.logicalName)),d=new Map(c.map(g=>[g.logicalName,g])),f=$c(e,oV(t)),[,,m,p,h]=await Promise.all([iV(e,t,d),aV(f,d),sV(e,t,f),lV(e,t,d),cV(e,t)]);for(let g of c){let b=m.byColumn.get(g.logicalName);b&&(g.choices=b)}return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:Yr(u.DisplayName),...xo(u.DisplayName)?{localizedDisplayName:xo(u.DisplayName)}:{},entitySetName:(i=u.EntitySetName)!==null&&i!==void 0?i:"",primaryNameAttribute:(o=u.PrimaryNameAttribute)!==null&&o!==void 0?o:"",primaryIdAttribute:(a=u.PrimaryIdAttribute)!==null&&a!==void 0?a:"",...u.PrimaryImageAttribute?{primaryImageAttribute:u.PrimaryImageAttribute}:{},isCustomEntity:!!u.IsCustomEntity,...Yr(u.Description)?{description:Yr(u.Description)}:{},columnDetailComplete:m.complete&&p,columnDetailVersion:rr.COLUMN_DETAIL_VERSION,attributes:c,relationships:h}}rr.fetchEntityMetadataFromApi=dV;var cE=40;async function zm(e,t,r,n){var i,o;let a=[...new Set(n.filter(l=>l!==""))],s=[];for(let l=0;l<a.length;l+=cE){let u=a.slice(l,l+cE).map(f=>`LogicalName eq '${(0,hr.odataLiteral)(f)}'`).join(" or "),c=t+(0,hr.odataQuery)([["$select",r],["$filter",u]]),d=(0,kc.ensureSuccess)(await e.get(c),e.apiUrl(c));s.push(...(o=(i=d.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[])}return s}async function fV(e,t,r){return(await zm(e,`${Br(t)}/Attributes`,"LogicalName,AttributeType,DisplayName",r)).map(i=>{var o;let a=xo(i.DisplayName);return{logicalName:i.LogicalName,displayName:Yr(i.DisplayName),...a?{localizedDisplayName:a}:{},attributeType:(o=i.AttributeType)!==null&&o!==void 0?o:"Unknown"}})}rr.readColumnHints=fV;async function pV(e,t,r){let i=(await zm(e,`${Br(t)}/Attributes`,"LogicalName,AttributeType,DisplayName,IsCustomAttribute",r)).map(s=>{var l;return{logicalName:s.LogicalName,displayName:Yr(s.DisplayName),attributeType:(l=s.AttributeType)!==null&&l!==void 0?l:"Unknown",isCustomAttribute:!!s.IsCustomAttribute}}),o=new Map(i.filter(s=>s.attributeType==="String").map(s=>[s.logicalName,s])),a=await zm(e,`${Br(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata`,"LogicalName,MaxLength",[...o.keys()]);for(let s of a){let l=o.get(s.LogicalName);l&&typeof s.MaxLength=="number"&&(l.maxLength=s.MaxLength)}return i}rr.readCheckColumns=pV;async function mV(e,t,r){var n,i;let o=`/EntityDefinitions${(0,hr.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,kc.ensureSuccess)(await e.get(o),e.apiUrl(o)).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,f;return{logicalName:c.LogicalName,schemaName:(d=c.SchemaName)!==null&&d!==void 0?d:c.LogicalName,displayName:Yr(c.DisplayName),entitySetName:(f=c.EntitySetName)!==null&&f!==void 0?f:"",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}rr.findTables=mV;async function hV(e,t,r,n){var i,o;let a=`${Br(t)}/Attributes`+(0,hr.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(o=(i=(0,kc.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[],u=(r??"").toLowerCase(),c=l.map(d=>{var f,m;return{logicalName:d.LogicalName,schemaName:(f=d.SchemaName)!==null&&f!==void 0?f:d.LogicalName,displayName:Yr(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}rr.findColumns=hV});var Km=v(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.renderTypeRegistrations=gr.buildGenPageLegacyEnums=gr.renderGenPageAuthoringTypes=gr.buildGenPageRuntimeTypes=gr.toDesignerEntity=gr.TABLE_LOGICAL_NAME=void 0;gr.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function jm(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var gV=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function xc(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function mE(e){var t,r;let n=e.choices;if(!n||n.length===0)return;let i=xc(e)==="boolean",o={};for(let a of n)o[a.value]={text:(r=(t=a.invariantName)!==null&&t!==void 0?t:a.label)!==null&&r!==void 0?r:"",value:a.value,...!i&&a.color?{color:a.color}:{}};return o}function fE(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function hE(e){return!gV.has(e.logicalName)&&(!e.attributeOf||xc(e)==="image")&&e.isValidForRead!==!1}var pE=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function gE(e){let t=e.primaryImageAttribute,r=new Set([e.primaryIdAttribute,e.primaryNameAttribute,t,t?`${t}_url`:void 0,"processid","statecode","statuscode"].filter(o=>!!o)),n=e.attributes.filter(o=>r.has(o.logicalName)).sort(fE),i=e.attributes.filter(o=>!r.has(o.logicalName)).sort(fE);return[...n,...i]}function Hm(e){var t;let r=[],n=new Set,i=gE(e);for(let o of i){let a=xc(o),s=a==="image";hE(o)&&(s&&o.attributeOf&&n.add(o.attributeOf),r.push({AttributeTypeName:a,IsReadOnly:!o.isValidForUpdate,LogicalName:o.logicalName,OptionSet:mE(o),Targets:o.targets,Description:o.description,MaxLength:o.maxLength}))}return{Description:(t=e.description)!==null&&t!==void 0?t:"",LogicalName:e.logicalName,PrimaryIdAttribute:e.primaryIdAttribute,Attributes:r.filter(o=>!n.has(o.LogicalName))}}gr.toDesignerEntity=Hm;function yE(e,t="None"){let r={};for(let n of e)r[n.logicalName]=Hm(n);return wE(r,t)}gr.buildGenPageRuntimeTypes=yE;var bE=`export interface TableRegistrations extends BaseTableRegistrations {
-`,vE=`export interface EnumRegistrations extends BaseEnumRegistrations {
-`;function yV(e,t){return e.length>0?yE(e,t).text:EE(`${bE}}
-`,`${vE}}
-`,"","")}gr.renderGenPageAuthoringTypes=yV;function bV(e){let t=new Set;for(let n of e)for(let i of Hm(n).Attributes)pE.has(i.AttributeTypeName)&&t.add(`${n.logicalName}_${i.LogicalName}`);let r=new Map;for(let n of e)for(let i of gE(n)){let o=`${n.logicalName}_${i.logicalName}`,a=mE(i);if(hE(i)||!pE.has(xc(i))||!a||t.has(o)||r.has(o))continue;let s={name:o,runtime:{},labels:new Map};r.set(o,{declaration:CE(o,a,!1,s),model:s})}return r}gr.buildGenPageLegacyEnums=bV;function wE(e,t="None"){var r,n;let i=new Map,o=Object.values(e);if(o.length===0)return{text:"",enums:i};let a=t==="ColorsDefaultsConstraints"||t==="ColorsDefaultsConstraintsDescriptions",s=t==="ColorsDefaultsConstraintsDescriptions",l=bE,u=vE,c="",d="";for(let f of o){s&&f.Description&&(c+=`// ${jm(f.Description)}
+ &$filter=(applicationid eq '${e}')`;A.SPNPrincipalIdUrl=eV;function tV(){return"/api/data/v9.0/appmodules?$filter=(uniquename eq 'AppDeploymentConfiguration')"}A.retrieveDeploymentPipelineConfigAppUrl=tV;A.retrieveFeatureControlSettingsByNamespaceUrl="/api/data/v9.1/RetrieveFeatureControlSettingsByNamespace";function rV(e){return`/api/data/v9.0/settingdefinitions${e}`}A.getSettingDefinitionsUri=rV;A.OrgSettingOverrideName="organizationsettings";function nV(e,t=!1){let r=`/api/data/v9.0/${A.OrgSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl}${r}`:r}A.getOrgSettingOverrideUri=nV;A.AppSettingOverrideName="appsettings";function iV(e,t=!1){let r=`/api/data/v9.0/${A.AppSettingOverrideName}${e}`;return t?`${A.cdsServiceUrl.replace("/$","")}${r}`:r}A.getAppSettingOverrideUri=iV;var Sl;(function(e){e[e.All=0]="All",e[e.IsPlatformOnly=1]="IsPlatformOnly",e[e.NotPlatformOnly=2]="NotPlatformOnly"})(Sl||(A.RetrievePlatform=Sl={}));function oV(e,t,r,n=Sl.All,i=!1){let o=[];e&&o.push(`AppUniqueName='${e}'`),t!=null&&o.push(`ReleaseLevel=${t}`),r&&o.push(`RetrieveHiddenSettings=${r}`),n!==Sl.All&&o.push(`RetrievePlatformSettings=${n===Sl.IsPlatformOnly?1:0}`);let a="/api/data/v9.0/RetrieveUnpublishedOverridableSettingsInfo";return o.length&&(a=`${a}(${o.join(",")})`),i?`${A.cdsServiceUrl}${a}`:a}A.getPowerSettingsUri=oV;function aV(e,t,r,n=!1){let i=[`SettingName='${e}'`];t!==void 0&&i.push(`SolutionName='${t}'`),r!==void 0&&i.push(`AppUniqueName='${r}'`);let o="/api/data/v9.0/RetrieveUnpublishedSettingInfo";return i.length&&(o=`${o}(${i.join(",")})`),n?`${A.cdsServiceUrl}${o}`:o}A.getPowerSettingUri=aV;function sV(e=!1){let t="/api/data/v9.0/SaveSettingValue()";return e?`${A.cdsServiceUrl}${t}`:t}A.getSavePowerSettingUri=sV;A.retrieveUnpublishedSuffix="Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()";function lV(e){return`tools/systemcustomization/businessrules/businessRulesDesigner.aspx?BRlaunchpoint=BRGrid&appSolutionId={${e}}`}A.getBusinessRuleDesignerUri=lV;function hE({environmentInstanceUrl:e,entityLogicalName:t}){return e&&t?`${e}main.aspx?cmdbar=true&forceUCI=1&navbar=off&newWindow=true&pageType=entityRecord&etn=${t}`:void 0}A.getUCIEntityRecordBaseUrl=hE;function uV({baseUrl:e,environmentInstanceUrl:t,entityLogicalName:r,recordId:n}){let i=e||hE({environmentInstanceUrl:t,entityLogicalName:r});return i&&n?`${i}&id=${n}`:void 0}A.getUCIEntityRecordEditUrl=uV;A.retrieveOrganizationResources=`${A.cdsServiceUrl}api/data/v9.0/RetrieveOrganizationResources`});var bE=v(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});Mc.DataverseClient=void 0;var cV=Km(),Fo=Q(),gE=ye(),dV=new Set(["entitydefinitions","relationshipdefinitions","globaloptionsetdefinitions"]);function fV(e){var t,r,n,i;let o=e.split("?")[0].split("/").filter(l=>l!==""),a=((t=o[0])===null||t===void 0?void 0:t.toLowerCase())==="api"&&((r=o[1])===null||r===void 0?void 0:r.toLowerCase())==="data"&&/^v\d/i.test((n=o[2])!==null&&n!==void 0?n:""),s=((i=o[a?3:0])!==null&&i!==void 0?i:"").split("(")[0].toLowerCase();return dV.has(s)}function pV(e){let t=e.indexOf("://"),r=t===-1?"":e.slice(t+3),n=r.search(/[/?#]/),i=n===-1?"":r.slice(n),o=i.search(/[?#]/);return o===-1?i:i.slice(0,o)}function yE(e,t){var r;if(!fV(e))return t;let n=(r=t?.headers)!==null&&r!==void 0?r:{};return Object.keys(n).some(i=>i.toLowerCase()==="consistency")?t:{...t,headers:{...n,Consistency:"Strong"}}}var Ym=class{constructor(t,r,n,i=1){this.instanceUrl=t,this.httpClient=r,this.solutionUniqueName=n,this.readConcurrency=i}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}/${cV.xrmApiUrl}${n}`}async send(t,r){try{return await r()}catch(n){throw n instanceof Fo.SdkError?n:new Fo.ConnectionError(t,0,n instanceof Error?n.message:String(n),n)}}get(t,r){let n=this.apiUrl(t),i=yE(t,r);return(0,gE.resendDeadlockVictim)(()=>this.send(n,()=>this.httpClient.get(n,i)))}getAbsolute(t,r){this.assertSameOrigin(t);let n=yE(pV(t),r);return(0,gE.resendDeadlockVictim)(()=>this.send(t,()=>this.httpClient.get(t,n)))}assertSameOrigin(t){let r,n;try{r=new URL(t),n=new URL(this.instanceUrl)}catch{throw new Fo.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${t}'`)}if(r.protocol!==n.protocol||r.host!==n.host)throw new Fo.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 supportsPut(){return typeof this.httpClient.put=="function"}get solutionName(){return this.solutionUniqueName}postBatch(t,r,n){if(!this.httpClient.postRaw)throw new Fo.InvalidArgumentError("The injected HttpClient does not implement postRaw(), required for atomic $batch change sets");let i=this.apiUrl("/$batch"),o={...n,headers:{...n?.headers,"Content-Type":`multipart/mixed;boundary=${r}`}};return this.send(i,()=>this.httpClient.postRaw(i,t,o))}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 Fo.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 Fo.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)))}};Mc.DataverseClient=Ym});var CE=v(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.findColumns=or.findTables=or.readCheckColumns=or.readColumnHints=or.fetchEntityMetadataFromApi=or.COLUMN_DETAIL_VERSION=void 0;var qc=ye(),br=le();function Xr(e){var t,r;return(r=(t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)!==null&&r!==void 0?r:""}or.COLUMN_DETAIL_VERSION=2;function Qm(e){var t,r;return typeof((t=e?.UserLocalizedLabel)===null||t===void 0?void 0:t.Label)=="string"||((r=e?.LocalizedLabels)!==null&&r!==void 0?r:[]).some(n=>typeof n?.Label=="string")}function Mo(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 Uc(e,t){return(await Vc(e,t)).rows}async function Vc(e,t){var r,n;let i=await e.get(t);return i.status<200||i.status>=300?{rows:[],ok:!1}:{rows:(n=(r=i.body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[],ok:!0}}function Gr(e){return`/EntityDefinitions(LogicalName='${(0,br.odataPathLiteral)(e)}')`}async function mV(e,t,r){let n=await Uc(e,`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata${(0,br.odataQuery)([["$select","LogicalName,MaxLength"]])}`);for(let i of n){let o=r.get(i.LogicalName);o&&typeof i.MaxLength=="number"&&(o.maxLength=i.MaxLength)}}function hV(e){return`${Gr(e)}/Attributes/Microsoft.Dynamics.CRM.PicklistAttributeMetadata${(0,br.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`}async function gV(e,t){var r;let{rows:n}=await e;for(let i of n){let o=t.get(i.LogicalName);o&&(!((r=i.OptionSet)===null||r===void 0)&&r.Options)&&(o.options=i.OptionSet.Options.map(a=>{var s;return{value:(s=a.Value)!==null&&s!==void 0?s:0,label:Xr(a.Label),...Mo(a.Label)?{localizedLabel:Mo(a.Label)}:{}}}))}}function Xm(e){var t;return{value:(t=e.Value)!==null&&t!==void 0?t:0,label:Xr(e.Label),...e.InvariantName?{invariantName:e.InvariantName}:{},...e.Color?{color:e.Color}:{}}}async function yV(e,t,r){var n;let i=c=>Vc(e,c).catch(()=>({rows:[],ok:!1})),o=["MultiSelectPicklistAttributeMetadata","StateAttributeMetadata","StatusAttributeMetadata"],a=await Promise.all([r.catch(()=>({rows:[],ok:!1})),...o.map(c=>i(`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.${c}${(0,br.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=Options)"]])}`))]),s=new Map,l=!0;for(let{rows:c}of a)for(let d of c)!((n=d.OptionSet)===null||n===void 0)&&n.Options&&(l=l&&d.OptionSet.Options.every(f=>Qm(f.Label)),s.set(d.LogicalName,d.OptionSet.Options.map(Xm)));let u=await i(`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.BooleanAttributeMetadata${(0,br.odataQuery)([["$select","LogicalName"],["$expand","OptionSet($select=TrueOption,FalseOption)"]])}`);for(let c of u.rows){let d=c.OptionSet;d?.TrueOption&&d.FalseOption&&(l=l&&Qm(d.TrueOption.Label)&&Qm(d.FalseOption.Label),s.set(c.LogicalName,[Xm(d.FalseOption),Xm(d.TrueOption)]))}return{byColumn:s,complete:l&&u.ok&&a.every(c=>c.ok)}}async function bV(e,t,r){let{rows:n,ok:i}=await Vc(e,`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.LookupAttributeMetadata${(0,br.odataQuery)([["$select","LogicalName,Targets"]])}`);for(let o of n){let a=r.get(o.LogicalName);a&&o.Targets&&(a.targets=o.Targets)}return i}function Bc(e,t){return e<t?-1:e>t?1:0}var vE={OneToMany:0,ManyToOne:1,ManyToMany:2};function vV(e,t){return vE[e.type]-vE[t.type]||Bc(e.schemaName,t.schemaName)||Bc(e.relatedEntity,t.relatedEntity)||Bc(e.relatedAttribute,t.relatedAttribute)}async function wV(e,t){var r,n,i,o;let a=[],s=await Uc(e,`${Gr(t)}/OneToManyRelationships${(0,br.odataQuery)([["$select","SchemaName,ReferencingEntity,ReferencingAttribute"]])}`);for(let c of s)a.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 Uc(e,`${Gr(t)}/ManyToOneRelationships${(0,br.odataQuery)([["$select","SchemaName,ReferencedEntity,ReferencedAttribute"]])}`);for(let c of l)a.push({schemaName:c.SchemaName,type:"ManyToOne",relatedEntity:(i=c.ReferencedEntity)!==null&&i!==void 0?i:"",relatedAttribute:(o=c.ReferencedAttribute)!==null&&o!==void 0?o:""});let u=await Uc(e,`${Gr(t)}/ManyToManyRelationships${(0,br.odataQuery)([["$select","SchemaName,Entity1LogicalName,Entity2LogicalName"]])}`);for(let c of u){let d=c.Entity1LogicalName===t?c.Entity2LogicalName:c.Entity1LogicalName;a.push({schemaName:c.SchemaName,type:"ManyToMany",relatedEntity:d??"",relatedAttribute:""})}return a.sort(vV)}async function CV(e,t){var r,n,i,o,a;let s=`${Gr(t)}`+(0,br.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,Description,EntitySetName,IsCustomEntity,PrimaryNameAttribute,PrimaryIdAttribute,PrimaryImageAttribute"],["$expand","Attributes($select=LogicalName,DisplayName,Description,AttributeType,AttributeTypeName,IsCustomAttribute,IsValidForUpdate,IsValidForRead,AttributeOf)"]]),u=(0,qc.ensureSuccess)(await e.get(s),e.apiUrl(s)).body,c=((r=u.Attributes)!==null&&r!==void 0?r:[]).map(g=>{var b,w,C;return{logicalName:g.LogicalName,displayName:Xr(g.DisplayName),...Mo(g.DisplayName)?{localizedDisplayName:Mo(g.DisplayName)}:{},attributeType:(b=g.AttributeType)!==null&&b!==void 0?b:"Unknown",isCustomAttribute:!!g.IsCustomAttribute,attributeTypeName:(C=(w=g.AttributeTypeName)===null||w===void 0?void 0:w.Value)!==null&&C!==void 0?C:"",...typeof g.IsValidForUpdate=="boolean"?{isValidForUpdate:g.IsValidForUpdate}:{},...typeof g.IsValidForRead=="boolean"?{isValidForRead:g.IsValidForRead}:{},...g.AttributeOf?{attributeOf:g.AttributeOf}:{},...Xr(g.Description)?{description:Xr(g.Description)}:{}}}).sort((g,b)=>Bc(g.logicalName,b.logicalName)),d=new Map(c.map(g=>[g.logicalName,g])),f=Vc(e,hV(t)),[,,m,p,h]=await Promise.all([mV(e,t,d),gV(f,d),yV(e,t,f),bV(e,t,d),wV(e,t)]);for(let g of c){let b=m.byColumn.get(g.logicalName);b&&(g.choices=b)}return{logicalName:u.LogicalName,schemaName:(n=u.SchemaName)!==null&&n!==void 0?n:u.LogicalName,displayName:Xr(u.DisplayName),...Mo(u.DisplayName)?{localizedDisplayName:Mo(u.DisplayName)}:{},entitySetName:(i=u.EntitySetName)!==null&&i!==void 0?i:"",primaryNameAttribute:(o=u.PrimaryNameAttribute)!==null&&o!==void 0?o:"",primaryIdAttribute:(a=u.PrimaryIdAttribute)!==null&&a!==void 0?a:"",...u.PrimaryImageAttribute?{primaryImageAttribute:u.PrimaryImageAttribute}:{},isCustomEntity:!!u.IsCustomEntity,...Xr(u.Description)?{description:Xr(u.Description)}:{},columnDetailComplete:m.complete&&p,columnDetailVersion:or.COLUMN_DETAIL_VERSION,attributes:c,relationships:h}}or.fetchEntityMetadataFromApi=CV;var wE=40;async function Zm(e,t,r,n){var i,o;let a=[...new Set(n.filter(l=>l!==""))],s=[];for(let l=0;l<a.length;l+=wE){let u=a.slice(l,l+wE).map(f=>`LogicalName eq '${(0,br.odataLiteral)(f)}'`).join(" or "),c=t+(0,br.odataQuery)([["$select",r],["$filter",u]]),d=(0,qc.ensureSuccess)(await e.get(c),e.apiUrl(c));s.push(...(o=(i=d.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[])}return s}async function EV(e,t,r){return(await Zm(e,`${Gr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName",r)).map(i=>{var o;let a=Mo(i.DisplayName);return{logicalName:i.LogicalName,displayName:Xr(i.DisplayName),...a?{localizedDisplayName:a}:{},attributeType:(o=i.AttributeType)!==null&&o!==void 0?o:"Unknown"}})}or.readColumnHints=EV;async function AV(e,t,r){let i=(await Zm(e,`${Gr(t)}/Attributes`,"LogicalName,AttributeType,DisplayName,IsCustomAttribute",r)).map(s=>{var l;return{logicalName:s.LogicalName,displayName:Xr(s.DisplayName),attributeType:(l=s.AttributeType)!==null&&l!==void 0?l:"Unknown",isCustomAttribute:!!s.IsCustomAttribute}}),o=new Map(i.filter(s=>s.attributeType==="String").map(s=>[s.logicalName,s])),a=await Zm(e,`${Gr(t)}/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata`,"LogicalName,MaxLength",[...o.keys()]);for(let s of a){let l=o.get(s.LogicalName);l&&typeof s.MaxLength=="number"&&(l.maxLength=s.MaxLength)}return i}or.readCheckColumns=AV;async function SV(e,t,r){var n,i;let o=`/EntityDefinitions${(0,br.odataQuery)([["$select","LogicalName,SchemaName,EntitySetName,DisplayName,IsCustomEntity"]])}`,s=(i=(n=(0,qc.ensureSuccess)(await e.get(o),e.apiUrl(o)).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,f;return{logicalName:c.LogicalName,schemaName:(d=c.SchemaName)!==null&&d!==void 0?d:c.LogicalName,displayName:Xr(c.DisplayName),entitySetName:(f=c.EntitySetName)!==null&&f!==void 0?f:"",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}or.findTables=SV;async function NV(e,t,r,n){var i,o;let a=`${Gr(t)}/Attributes`+(0,br.odataQuery)([["$select","LogicalName,SchemaName,DisplayName,AttributeType,IsCustomAttribute"]]),l=(o=(i=(0,qc.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[],u=(r??"").toLowerCase(),c=l.map(d=>{var f,m;return{logicalName:d.LogicalName,schemaName:(f=d.SchemaName)!==null&&f!==void 0?f:d.LogicalName,displayName:Xr(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}or.findColumns=NV});var rh=v(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.renderTypeRegistrations=vr.buildGenPageLegacyEnums=vr.renderGenPageAuthoringTypes=vr.buildGenPageRuntimeTypes=vr.toDesignerEntity=vr.TABLE_LOGICAL_NAME=void 0;vr.TABLE_LOGICAL_NAME=/^[a-z_][a-z0-9_]*$/;function eh(e){return e.replace(/[\r\n\u2028\u2029]+/g," ")}var _V=new Set(["createdby","createdon","createdonbehalfby","importsequencenumber","modifiedby","modifiedon","modifiedonbehalfby","overriddencreatedon","ownerid","owningbusinessunit","owningteam","owninguser","timezoneruleversionnumber","utcconversiontimezonecode","versionnumber"]);function Gc(e){var t;return((t=e.attributeTypeName)!==null&&t!==void 0?t:"").replace(/Type$/,"").toLowerCase()}function SE(e){var t,r;let n=e.choices;if(!n||n.length===0)return;let i=Gc(e)==="boolean",o={};for(let a of n)o[a.value]={text:(r=(t=a.invariantName)!==null&&t!==void 0?t:a.label)!==null&&r!==void 0?r:"",value:a.value,...!i&&a.color?{color:a.color}:{}};return o}function EE(e,t){return e.logicalName<t.logicalName?-1:e.logicalName>t.logicalName?1:0}function NE(e){return!_V.has(e.logicalName)&&(!e.attributeOf||Gc(e)==="image")&&e.isValidForRead!==!1}var AE=new Set(["boolean","picklist","multiselectpicklist","state","status"]);function _E(e){let t=e.primaryImageAttribute,r=new Set([e.primaryIdAttribute,e.primaryNameAttribute,t,t?`${t}_url`:void 0,"processid","statecode","statuscode"].filter(o=>!!o)),n=e.attributes.filter(o=>r.has(o.logicalName)).sort(EE),i=e.attributes.filter(o=>!r.has(o.logicalName)).sort(EE);return[...n,...i]}function th(e){var t;let r=[],n=new Set,i=_E(e);for(let o of i){let a=Gc(o),s=a==="image";NE(o)&&(s&&o.attributeOf&&n.add(o.attributeOf),r.push({AttributeTypeName:a,IsReadOnly:!o.isValidForUpdate,LogicalName:o.logicalName,OptionSet:SE(o),Targets:o.targets,Description:o.description,MaxLength:o.maxLength}))}return{Description:(t=e.description)!==null&&t!==void 0?t:"",LogicalName:e.logicalName,PrimaryIdAttribute:e.primaryIdAttribute,Attributes:r.filter(o=>!n.has(o.LogicalName))}}vr.toDesignerEntity=th;function TE(e,t="None"){let r={};for(let n of e)r[n.logicalName]=th(n);return OE(r,t)}vr.buildGenPageRuntimeTypes=TE;var DE=`export interface TableRegistrations extends BaseTableRegistrations {
+`,IE=`export interface EnumRegistrations extends BaseEnumRegistrations {
+`;function TV(e,t){return e.length>0?TE(e,t).text:RE(`${DE}}
+`,`${IE}}
+`,"","")}vr.renderGenPageAuthoringTypes=TV;function DV(e){let t=new Set;for(let n of e)for(let i of th(n).Attributes)AE.has(i.AttributeTypeName)&&t.add(`${n.logicalName}_${i.LogicalName}`);let r=new Map;for(let n of e)for(let i of _E(n)){let o=`${n.logicalName}_${i.logicalName}`,a=SE(i);if(NE(i)||!AE.has(Gc(i))||!a||t.has(o)||r.has(o))continue;let s={name:o,runtime:{},labels:new Map};r.set(o,{declaration:PE(o,a,!1,s),model:s})}return r}vr.buildGenPageLegacyEnums=DV;function OE(e,t="None"){var r,n;let i=new Map,o=Object.values(e);if(o.length===0)return{text:"",enums:i};let a=t==="ColorsDefaultsConstraints"||t==="ColorsDefaultsConstraintsDescriptions",s=t==="ColorsDefaultsConstraintsDescriptions",l=DE,u=IE,c="",d="";for(let f of o){s&&f.Description&&(c+=`// ${eh(f.Description)}
`),c+=`export type ${f.LogicalName} = TableRow<{
// Primary Key Column
readonly ${f.PrimaryIdAttribute}: string,
@@ -62,19 +62,19 @@ var AU=Object.create;var bc=Object.defineProperty;var SU=Object.getOwnPropertyDe
`;break;case"customer":case"lookup":{let g=(r=m.Targets)!==null&&r!==void 0?r:m.AttributeTypeName==="customer"?["account","contact"]:void 0;if(!g||g.length===0){h=!1;break}p=` // Foreign Key Column
${m.IsReadOnly||g.every(w=>!e[w])?" readonly ":""}_${m.LogicalName}_value: `;let b="";for(let w of g)b+=`${b.length===0?"":" | "}\`/${w}(\${string})\``;p+=`${b},
`;break}case"boolean":case"picklist":case"multiselectpicklist":case"state":case"status":{let g=`${f.LogicalName}_${m.LogicalName}`;p+=`: ${g},
-`;let b=(n=i.get(g))!==null&&n!==void 0?n:{name:g,runtime:{},labels:new Map};i.set(g,b),d+=CE(g,m.OptionSet,a,b),u+=` "${f.LogicalName}-${m.LogicalName}": ${g},
+`;let b=(n=i.get(g))!==null&&n!==void 0?n:{name:g,runtime:{},labels:new Map};i.set(g,b),d+=PE(g,m.OptionSet,a,b),u+=` "${f.LogicalName}-${m.LogicalName}": ${g},
`;break}case"image":c+=` // This is an image encoded as a base64 string
`,p+=`: string,
-`;break;default:h=!1}h&&(s&&m.Description&&(c+=` // ${jm(m.Description)}
+`;break;default:h=!1}h&&(s&&m.Description&&(c+=` // ${eh(m.Description)}
`),a&&m.MaxLength&&(c+=" // Maximum length: "+m.MaxLength+`
`),c+=` ${p}`)}c+=`}>
`}return l+=`}
`,u+=`}
-`,{text:EE(l,u,c,d),enums:i}}gr.renderTypeRegistrations=wE;function CE(e,t,r,n){var i;let o=`const enum ${e} {
-`;for(let a of Object.values(t??{}))if(a){r&&(o+=`${a.color?`// Option Color: ${jm(a.color)}
+`,{text:RE(l,u,c,d),enums:i}}vr.renderTypeRegistrations=OE;function PE(e,t,r,n){var i;let o=`const enum ${e} {
+`;for(let a of Object.values(t??{}))if(a){r&&(o+=`${a.color?`// Option Color: ${eh(a.color)}
`:""}`),o+=`${JSON.stringify(a.text)} = ${a.value},
`,n.runtime[a.text]=a.value,n.runtime[String(a.value)]=a.text;let s=(i=n.labels.get(a.text))!==null&&i!==void 0?i:[];s.includes(a.value)||s.push(a.value),n.labels.set(a.text,s)}return`${o}}
-`}function EE(e,t,r,n){return`
+`}function RE(e,t,r,n){return`
// ---------------- Type Definitions which can be imported from ./RuntimeTypes -------------------------
${e}
${t}
@@ -345,23 +345,23 @@ export interface GeneratedComponentProps {
dataApi: UxAgentDataApi;
pageInput?: PageInput;
}
-`}});var NE=v(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});Fc.generateGenPageRuntimeTypes=void 0;var SE=Km(),Fo=Q(),AE=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),Mo="generateGenPageRuntimeTypes";async function vV(e,t,r){let n=wV(t),i=CV(r),o=[];for(let a of n){let s=await e(a);if(s.columnDetailComplete!==!0)throw new Fo.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${Mo}: the column metadata of data source '${a}' could not be read completely (a choice or lookup read failed, or returned options with no label), so its RuntimeTypes would lack enums a page can use. Retry.`);o.push(s)}return(0,SE.renderGenPageAuthoringTypes)(o,i)}Fc.generateGenPageRuntimeTypes=vV;function wV(e){if(!Array.isArray(e))throw new Fo.InvalidArgumentError(`${Mo}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!SE.TABLE_LOGICAL_NAME.test(r))throw new Fo.InvalidArgumentError(`${Mo}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new Fo.InvalidArgumentError(`${Mo}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function CV(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Fo.InvalidArgumentError(`${Mo}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new Fo.InvalidArgumentError(`${Mo}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!AE.has(r))throw new Fo.InvalidArgumentError(`${Mo}: detail must be one of ${[...AE].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var PE=v(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.getEnvironmentLanguages=Uo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE=void 0;var EV=Q(),DE=ye();Uo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE="ENVIRONMENT_LANGUAGES_UNREADABLE";var _E="/organizations?$select=languagecode",AV="/RetrieveProvisionedLanguages()",SV="/RetrieveAvailableLanguages()";function IE(e,t){return new EV.SdkError(Uo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE,`The org's languages could not be read: ${e} ${t}. Nothing is assumed in its place \u2014 retry, or check the caller's access to the org.`)}function OE(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}async function TE(e,t,r,n){let i=(0,DE.ensureSuccess)(await e.get(t),e.apiUrl(t)).body,o=i?.[r];if(!Array.isArray(o)||o.length===0||!o.every(OE))throw IE(n,`answered no list of language codes in '${r}'`);return[...new Set(o)]}async function NV(e){var t;let r=(0,DE.ensureSuccess)(await e.get(_E),e.apiUrl(_E)).body,n=r?.value,i=Array.isArray(n)&&n.length===1?(t=n[0])===null||t===void 0?void 0:t.languagecode:void 0;if(!OE(i))throw IE("the organization read","did not answer one row with a language code");let o=await TE(e,AV,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages"),a=await TE(e,SV,"LocaleIds","RetrieveAvailableLanguages");return{baseLanguage:i,available:a,provisioned:o}}Uo.getEnvironmentLanguages=NV});var Al=v(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.projectConnectorOperationSchema=nt.projectConnectorOperations=nt.validateConnectorSwagger=nt.CONNECTOR_SCHEMA_TOO_LARGE_CODE=nt.CONNECTOR_OPERATION_NOT_FOUND_CODE=nt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE=nt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE=void 0;var El=Q();nt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE="CONNECTIVITY_RESPONSE_UNREADABLE";nt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE="CONNECTOR_SWAGGER_UNSUPPORTED";nt.CONNECTOR_OPERATION_NOT_FOUND_CODE="CONNECTOR_OPERATION_NOT_FOUND";nt.CONNECTOR_SCHEMA_TOO_LARGE_CODE="CONNECTOR_SCHEMA_TOO_LARGE";var RE=64,LE=128,kE=2e5,$E=4e6,_V=new Set(["get","put","post","delete","patch","head","options"]),TV=new Set(["query","header","path","formData","body"]);function Qr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Et(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Xe(e){return e.length>80?`'${e.slice(0,80)}\u2026'`:`'${e}'`}function ke(e,t){return new El.SdkError(nt.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`The connector's swagger could not be read: ${e} ${t}. Nothing was skipped or assumed in its place.`)}function Zi(e,t){return new El.SdkError(nt.CONNECTOR_SWAGGER_UNSUPPORTED_CODE,`The connector's swagger is outside the supported contract (Swagger 2.0 as the Power Apps API serves it): ${e} ${t}.`)}function DV(e,t){let r=e;for(let n of t.slice(2).split("/")){let i=n.replace(/~1/g,"/").replace(/~0/g,"~");if(typeof r!="object"||r===null||!vn(r,i))return{found:!1};r=r[i]}return{found:!0,value:r}}function Qm(e,t,r){if(!t.startsWith("#/"))throw Zi(r,`has a $ref that is not a local '#/\u2026' pointer (${Xe(t)})`);if(t.includes("%"))throw Zi(r,`has a $ref with a percent-encoded character (${Xe(t)}), which is not decoded`);if(/~(?![01])/.test(t))throw ke(r,`has a $ref with a malformed escape (${Xe(t)}): a '~' not followed by 0 or 1`);let n=DV(e,t);if(!n.found)throw ke(r,`has a $ref that does not resolve (${Xe(t)})`);return n.value}function Mc(e,t){if(vn(e,"$ref")){if(typeof e.$ref!="string")throw ke(t,`has a $ref that is ${Et(e.$ref)}, not a string`);return e.$ref}}function IV(e,t,r){if(!Qr(t))throw ke(r,`is ${Et(t)}, not a parameter object`);let n=t,i=Mc(t,r);if(i!==void 0){let s=Qm(e,i,r);if(!Qr(s))throw ke(r,`has a $ref (${Xe(i)}) that resolves to ${Et(s)}, not a parameter object`);if(Mc(s,`${r} \u2192 ${Xe(i)}`)!==void 0)throw Zi(r,`has a $ref (${Xe(i)}) to a parameter that is itself a $ref`);n=s}if(typeof n.name!="string")throw ke(r,"has no string name");let o=n.in;if(typeof o!="string"||!TV.has(o))throw ke(r,`has an in that is ${typeof o=="string"?Xe(o):Et(o)}, not one of query, header, path, formData or body`);if(vn(n,"required")&&typeof n.required!="boolean")throw ke(r,`has a required that is ${Et(n.required)}, not a boolean`);let a=n["x-ms-visibility"];if(vn(n,"x-ms-visibility")&&typeof a!="string")throw ke(r,`has an x-ms-visibility that is ${Et(a)}, not a string`);return{name:n.name,in:o,required:n.required===!0,internal:a==="internal"}}function Jm(e){return`${e.in}:${e.name}`}function FE(e,t,r){if(!vn(t,"parameters"))return[];let n=t.parameters;if(!Array.isArray(n))throw ke(r,`has parameters that are ${Et(n)}, not an array`);let i=new Set;return n.map((o,a)=>{let s=`${r} parameters[${a}]`,l=IV(e,o,s),u=Jm(l);if(i.has(u))throw ke(s,`repeats the parameter ${Xe(l.name)} in ${Xe(l.in)}, which must be unique in its list`);return i.add(u),l})}function ME(e,t,r){let n=t.responses;if(!vn(n,"200"))return;let i=`${r} response 200`,o=n[200];if(!Qr(o))throw ke(i,`is ${Et(o)}, not a response object`);let a=o,s=Mc(o,i);if(s!==void 0){if(s.startsWith("#/")&&!/^#\/responses\/[^/]+$/.test(s))throw ke(i,`has a $ref (${Xe(s)}) that does not name a response ('#/responses/<name>')`);let l=Qm(e,s,i);if(!Qr(l))throw ke(i,`has a $ref (${Xe(s)}) that resolves to ${Et(l)}, not a response object`);if(Mc(l,`${i} \u2192 ${Xe(s)}`)!==void 0)throw Zi(i,`has a $ref (${Xe(s)}) to a response that is itself a $ref`);a=l}if(vn(a,"content"))throw Zi(i,"is an OpenAPI 3 response (it has content), not a Swagger 2.0 one");if(vn(a,"schema")){if(!Qr(a.schema))throw ke(i,`has a schema that is ${Et(a.schema)}, not an object`);return a.schema}}function xE(e,t,r){if(!vn(e,t))return;let n=e[t];if(typeof n!="string")throw ke(r,`has a ${t} that is ${Et(n)}, not a string`);return n}function OV(e,t,r,n,i){if(!Qr(t))throw ke(r,`is ${Et(t)}, not an operation object`);let o=t.operationId;if(typeof o!="string")throw ke(r,`has no string operationId (${Et(o)})`);if(n.has(o))throw ke(r,`repeats the operationId ${Xe(o)}, which must be unique in the document`);n.add(o);let a=xE(t,"summary",r),s=xE(t,"description",r),l=FE(e,t,r);if(!Qr(t.responses))throw ke(r,`has no responses object (${Et(t.responses)})`);return ME(e,t,r),{id:o,summary:a,description:s,node:t,where:r,parameters:l,pathParameters:i}}function Xm(e){if(!Qr(e))throw ke("the document",`is ${Et(e)}, not an object`);if(vn(e,"openapi"))throw Zi("the document","is OpenAPI 3 (it has an openapi member), not Swagger 2.0");if(!vn(e,"swagger"))throw ke("the document","names no Swagger version");if(e.swagger!=="2.0")throw Zi("the document",`declares swagger ${Xe(String(e.swagger))}, not 2.0`);let t=e.paths;if(!Qr(t))throw ke("the document",`has paths that are ${Et(t)}, not an object`);let r=[],n=new Set;for(let i of Object.keys(t)){let o=t[i],a=`paths[${Xe(i)}]`;if(!Qr(o))throw ke(a,`is ${Et(o)}, not a path item object`);let s=[];for(let l of Object.keys(o))if(_V.has(l.toLowerCase()))r.push(OV(e,o[l],`${a}.${l}`,n,s));else if(l==="parameters")for(let u of FE(e,o,a))s.push(u);else if(!l.startsWith("x-"))throw Zi(a,`has a ${Xe(l)} member; a path item may hold only HTTP methods, parameters and x- extensions`)}return{document:e,operations:r}}function PV(e){Xm(e)}nt.validateConnectorSwagger=PV;var Ym=class{constructor(t,r){this.root=t,this.where=r,this.nodes=0,this.characters=0,this.path=[]}run(t){return this.visit(t,0)}tooLarge(t){return new El.SdkError(nt.CONNECTOR_SCHEMA_TOO_LARGE_CODE,`The response schema of ${this.where} is too large to return: it has ${t}. That is far above any connector measured, so this one is not read.`)}node(){if(this.nodes+=1,this.nodes>kE)throw this.tooLarge(`more than ${kE} nodes`)}text(t){if(this.characters+=t,this.characters>$E)throw this.tooLarge(`more than ${$E} characters of strings and keys`)}checkDepth(t){if(t>LE)throw this.tooLarge(`nesting deeper than ${LE} levels`)}visit(t,r){if(this.checkDepth(r),Array.isArray(t)){this.node();let n=[];for(let i of t)n.push(this.visit(i,r+1));return n}if(Qr(t)){if(typeof t.$ref=="string")return this.reference(t.$ref,r);this.node();let n={};for(let i of Object.keys(t))this.text(i.length),Object.defineProperty(n,i,{value:this.visit(t[i],r+1),enumerable:!0,writable:!0,configurable:!0});return n}return this.node(),typeof t=="string"&&this.text(t.length),t}reference(t,r){if(this.path.includes(t)){this.checkDepth(r+1);let o=t.slice(t.lastIndexOf("/")+1);return this.node(),this.text(4),this.node(),this.text(o.length),{$ref:o}}if(this.path.length>=RE)throw this.tooLarge(`a $ref chain of more than ${RE} references`);let n=Qm(this.root,t,this.where);if(!Qr(n))throw ke(this.where,`has a schema $ref (${Xe(t)}) that resolves to ${Et(n)}, not a schema object`);this.path.push(t);let i=this.visit(n,r);return this.path.pop(),i}};function RV(e){let{operations:t}=Xm(e);return{operations:t.map(r=>{var n,i;return{name:r.id,summary:(i=(n=r.summary)!==null&&n!==void 0?n:r.description)!==null&&i!==void 0?i:null}})}}nt.projectConnectorOperations=RV;function LV(e,t){if(typeof t!="string"||t==="")throw new El.InvalidArgumentError("operationId must be a non-empty string.");let{document:r,operations:n}=Xm(e),i=n.find(u=>u.id===t);if(!i)throw new El.SdkError(nt.CONNECTOR_OPERATION_NOT_FOUND_CODE,`The connector has no operation with the id ${Xe(t)} (ids are matched exactly, case included). List the connector\u2019s operations to see its ids.`);let o=new Set(i.parameters.map(Jm)),a=[...i.parameters,...i.pathParameters.filter(u=>!o.has(Jm(u)))].filter(u=>!u.internal).map(({name:u,required:c})=>({name:u,required:c})),s=ME(r,i.node,i.where),l=s===void 0?{}:new Ym(r,`${i.where} (${Xe(i.id)})`).run(s);return{operation:i.id,parameters:a,response:l}}nt.projectConnectorOperationSchema=LV});var Bo=v(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.readEnvironmentName=J.readConnection=J.connectorShortName=J.CONNECTOR_PREFIX=J.connectivityUnauthorized=J.errorCodeOf=J.messageOf=J.environmentFilter=J.unreadable=J.connectivityCloudOf=J.sameOrigin=J.parseUrl=J.bounded=J.kindOf=J.isObject=J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE=J.CONNECTOR_NOT_TABULAR_CODE=J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=J.CONNECTIVITY_UNAUTHORIZED_CODE=J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=J.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var Sl=Q(),kV=ye(),$V=Al();J.CONNECTIVITY_NOT_CONFIGURED_CODE="CONNECTIVITY_NOT_CONFIGURED";J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE="CONNECTIVITY_CLOUD_UNSUPPORTED";J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE="CONNECTIVITY_ENVIRONMENT_UNVERIFIED";J.CONNECTIVITY_UNAUTHORIZED_CODE="CONNECTIVITY_UNAUTHORIZED";J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE="CONNECTIVITY_ROUTE_DECOMMISSIONED";J.CONNECTOR_NOT_TABULAR_CODE="CONNECTOR_NOT_TABULAR";J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE="CONNECTOR_RUNTIME_UNSUPPORTED";function yr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}J.isObject=yr;function Ba(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}J.kindOf=Ba;function qa(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}J.bounded=qa;function BE(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}J.parseUrl=BE;function xV(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}J.sameOrigin=xV;var FV=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,MV=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/;function UV(e){let t=BE(e),r=t?t.host.toLowerCase():"";if(MV.test(r))return"Test";let n=FV.exec(r);return n&&n[1]!=="9"?"Public":"Unsupported"}J.connectivityCloudOf=UV;function Vn(e,t){return new Sl.SdkError($V.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}J.unreadable=Vn;function BV(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}J.environmentFilter=BV;function qV(e){if(typeof e=="string"&&e.length>0)return qa(e,500);if(yr(e)){let t=yr(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return qa(r,500)}return"request failed"}J.messageOf=qV;function qE(e){return yr(e)&&yr(e.error)?e.error.code:void 0}J.errorCodeOf=qE;function VV(e){if(yr(e)&&yr(e.error)&&yr(e.error.innererror))return e.error.innererror.code}function GV(e,t,r){let n=[],i=qE(t);typeof i=="string"&&i.length>0&&n.push(qa(i,80));let o=VV(t);typeof o=="string"&&o.length>0&&n.push(qa(o,80));let a=n.length>0?` (${n.join("; ")})`:"";return(0,Sl.attachCause)(new Sl.SdkError(J.CONNECTIVITY_UNAUTHORIZED_CODE,`A connectivity request was refused with HTTP ${e}${a}: the token's audience, scopes, expiry, or access was rejected. Supply a valid token for this route, or fall back to pac.`),r)}J.connectivityUnauthorized=GV;J.CONNECTOR_PREFIX="/providers/Microsoft.PowerApps/apis/";var WV=/^[A-Za-z0-9_.-]{1,128}$/,zV=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]);function jV(e){if(typeof e=="string"){let r=e.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()===J.CONNECTOR_PREFIX.toLowerCase()?e.slice(J.CONNECTOR_PREFIX.length):e;if(WV.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Sl.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${J.CONNECTOR_PREFIX}shared_office365users'); got ${typeof e=="string"?`'${qa(e,80)}'`:Ba(e)}.`)}J.connectorShortName=jV;function HV(e,t,r){let n=`Connection row ${t}`;if(!yr(e))throw Vn(n,`it is ${Ba(e)}, not an object`);let i=e.properties;if(!yr(i))throw Vn(n,`its properties are ${Ba(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()!==J.CONNECTOR_PREFIX.toLowerCase())throw Vn(n,`its apiId is not '${J.CONNECTOR_PREFIX}<connector>'`);let a=o.slice(J.CONNECTOR_PREFIX.length);if(a===""||a.includes("/"))throw Vn(n,"its apiId names no single connector");if(zV.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Vn(n,"it has no name");let l=i.environment,u=yr(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Vn(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Vn(n,`its displayName is ${Ba(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Vn(n,`its statuses are ${Ba(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=yr(f)?f.status:void 0;if(typeof m!="string")throw Vn(n,"one of its statuses has no string status");return m})}}J.readConnection=HV;var UE="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'";async function KV(e){let t=(0,kV.ensureSuccess)(await e.get(UE),e.apiUrl(UE)).body,r=yr(t)?t.Detail:void 0,n=yr(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw new Sl.SdkError(J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,"The environment of this org could not be verified: the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId).");return n}J.readEnvironmentName=KV});var KE=v(br=>{"use strict";Object.defineProperty(br,"__esModule",{value:!0});br.ConnectivityApi=br.CONNECTIVITY_UNAUTHORIZED_CODE=br.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=br.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=br.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=br.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var Wt=Q(),JV=ye(),Bc=Al(),_l=Bo(),Tl=Bo();Object.defineProperty(br,"CONNECTIVITY_NOT_CONFIGURED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_NOT_CONFIGURED_CODE}});Object.defineProperty(br,"CONNECTIVITY_CLOUD_UNSUPPORTED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE}});Object.defineProperty(br,"CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE}});Object.defineProperty(br,"CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE}});Object.defineProperty(br,"CONNECTIVITY_UNAUTHORIZED_CODE",{enumerable:!0,get:function(){return Tl.CONNECTIVITY_UNAUTHORIZED_CODE}});var VE="2016-11-01",YV="2021-04-01",QV="https://api.bap.microsoft.com",XV="https://test.api.bap.microsoft.com",ZV=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,e4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,GE="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'",bi="/providers/Microsoft.PowerApps/apis/",t4=/^[A-Za-z0-9_.-]{1,128}$/,r4=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]),n4="ServiceDecommissioned";function ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function eo(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Gn(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Nl(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}function WE(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}function i4(e){return/^[a-z0-9][a-z0-9.-]*$/.test(e)&&(e==="api.powerapps.com"||e.endsWith(".api.powerapps.com"))}function Xr(e,t){return new Wt.SdkError(Bc.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}function Uc(e){return new Wt.SdkError(_l.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: ${e}. The Power Apps service was not asked about it.`)}function zE(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}function jE(e){if(typeof e=="string"&&e.length>0)return Gn(e,500);if(ct(e)){let t=ct(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Gn(r,500)}return"request failed"}function o4(e){return ct(e)&&ct(e.error)?e.error.code:void 0}function HE(e){if(typeof e=="string"){let r=e.slice(0,bi.length).toLowerCase()===bi.toLowerCase()?e.slice(bi.length):e;if(t4.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Wt.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${bi}shared_office365users'); got ${typeof e=="string"?`'${Gn(e,80)}'`:eo(e)}.`)}function a4(e,t,r){let n=`Connection row ${t}`;if(!ct(e))throw Xr(n,`it is ${eo(e)}, not an object`);let i=e.properties;if(!ct(i))throw Xr(n,`its properties are ${eo(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,bi.length).toLowerCase()!==bi.toLowerCase())throw Xr(n,`its apiId is not '${bi}<connector>'`);let a=o.slice(bi.length);if(a===""||a.includes("/"))throw Xr(n,"its apiId names no single connector");if(r4.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Xr(n,"it has no name");let l=i.environment,u=ct(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Xr(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Xr(n,`its displayName is ${eo(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Xr(n,`its statuses are ${eo(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=ct(f)?f.status:void 0;if(typeof m!="string")throw Xr(n,"one of its statuses has no string status");return m})}}var Zm=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.service=n,this.swaggers=new Map}async listConnections(){let t=this.requireService(),r=await this.resolveEnvironment(t),n=[],i=new Set,o=`${r.origin}/providers/Microsoft.PowerApps/connections?api-version=${VE}&$filter=${zE(r.id)}`,a=await this.send(t,o,!0),s=1,l=0;for(;;){let u=`Page ${s} of the connections`,c=a.body,d=c?.value;if(!Array.isArray(d))throw Xr(u,`its value is ${eo(d)}, not an array`);for(let m of d){let p=a4(m,l,r.id);l+=1,p&&n.push(p)}let f=c?.nextLink;if(f==null)return n;if(typeof f!="string"||f.length===0)throw Xr(u,`its nextLink is ${f===""?"an empty string":eo(f)}, not a non-empty string`);if(i.has(f))throw new Wt.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${Gn(f)}'), which would loop indefinitely.`);i.add(f),this.assertSameOrigin(f,r.parsed),a=await this.send(t,f,!0),s+=1}}async listConnectorOperations(t){let r=this.requireService(),n=HE(t);return(0,Bc.projectConnectorOperations)(await this.swagger(r,n))}async getConnectorOperationSchema(t,r){let n=this.requireService(),i=HE(t);if(typeof r!="string"||r==="")throw new Wt.InvalidArgumentError("operationId must be a non-empty string.");return(0,Bc.projectConnectorOperationSchema)(await this.swagger(n,i),r)}requireService(){if(!this.service)throw new Wt.SdkError(_l.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a powerAppsServiceClient (MakerSdkOptions), so it cannot read connections or connectors: it needs an HttpClient that authenticates for https://service.powerapps.com/ and does not follow redirects. Nothing was requested.");return this.service}resolveEnvironment(t){if(!this.environment){let r=this.verifyEnvironment(t);this.environment=r,r.catch(()=>{this.environment===r&&(this.environment=void 0)})}return this.environment}async verifyEnvironment(t){let r=this.candidateBapOrigin(),n=await this.readEnvironmentId(),i=`${r}/providers/Microsoft.BusinessAppPlatform/environments/${encodeURIComponent(n)}?api-version=${YV}`,o=(await this.send(t,i,!1)).body,a=ct(o)?o.properties:void 0,s=ct(o)?o.name:void 0;if(typeof s!="string"||s.toLowerCase()!==n.toLowerCase())throw Uc(`BAP's environment row is not the one named '${Gn(n,80)}' (its name)`);let l=ct(a)&&ct(a.linkedEnvironmentMetadata)?a.linkedEnvironmentMetadata.instanceUrl:void 0,u=typeof l=="string"?Nl(l):void 0,c=Nl(this.instanceUrl);if(!u||!c||!WE(u,c))throw Uc("BAP's row is not linked to this org (its linkedEnvironmentMetadata.instanceUrl is another origin)");let d=ct(a)?a.runtimeEndpoints:void 0,f=ct(d)?d["microsoft.PowerApps"]:void 0,m=typeof f=="string"?Nl(f):void 0;if(!m||m.protocol!=="https:"||!i4(m.host.toLowerCase()))throw Uc("BAP's Power Apps runtime endpoint is not an https host of api.powerapps.com (runtimeEndpoints['microsoft.PowerApps'])");return{id:n,origin:m.origin.toLowerCase(),parsed:m}}candidateBapOrigin(){let t=Nl(this.instanceUrl),r=t?t.host.toLowerCase():"",n=ZV.exec(r);if(n&&n[1]!=="9")return QV;if(e4.test(r))return XV;throw new Wt.SdkError(_l.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The org's host is not one of the clouds this reads in (${t?`'${Gn(t.host,80)}'`:`'${Gn(this.instanceUrl,80)}', which is not a URL`}): a Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are not supported. Nothing was requested.`)}async readEnvironmentId(){let t=(0,JV.ensureSuccess)(await this.org.get(GE),this.org.apiUrl(GE)).body,r=ct(t)?t.Detail:void 0,n=ct(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw Uc("the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId)");return n}swagger(t,r){let n=r.toLowerCase(),i=this.swaggers.get(n);if(!i){let o=this.readSwagger(t,r);i=o,this.swaggers.set(n,o),o.catch(()=>{this.swaggers.get(n)===o&&this.swaggers.delete(n)})}return i}async readSwagger(t,r){let n=await this.resolveEnvironment(t),i=encodeURIComponent(r),o=`${n.origin}${bi}${i}?api-version=${VE}&$filter=${zE(n.id)}`,a=(await this.send(t,o,!0)).body,s=ct(a)?a.properties:void 0,l=ct(s)?s.swagger:void 0;if(!ct(l))throw Xr(`The connector '${Gn(r,80)}'`,`its properties.swagger is ${eo(l)}, not an object`);return(0,Bc.validateConnectorSwagger)(l),l}assertSameOrigin(t,r){let n=Nl(t);if(!n)throw new Wt.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${Gn(t)}'`);if(!WE(n,r))throw new Wt.InvalidArgumentError(`Refusing to follow a cross-origin link ('${Gn(n.origin,120)}' is not the environment's Power Apps endpoint '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n){let i;try{i=await t.get(r)}catch(o){throw o instanceof Wt.ConnectionError&&typeof o.statusCode=="number"&&o.statusCode>0?this.mapNon2xx(r,o.statusCode,void 0,n,o):o instanceof Wt.SdkError?o:new Wt.ConnectionError(r,0,o instanceof Error?o.message:String(o),o)}if(!i||typeof i.status!="number")throw new Wt.ConnectionError(r,0,"the transport returned no HTTP response");if(i.status>=200&&i.status<300)return i;throw this.mapNon2xx(r,i.status,i.body,n)}mapNon2xx(t,r,n,i,o){let a=o??new Wt.ConnectionError(t,r,jE(n),n);return i&&r===410&&o4(n)===n4?(0,Wt.attachCause)(new Wt.SdkError(_l.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE,`The Power Apps API this reads through is decommissioned for this environment: ${jE(n)} Fall back to pac, or to the Power Platform API when the host has a client for it; the SDK does not fall back.`),a):r===401||r===403?(0,_l.connectivityUnauthorized)(r,n,a):a}};br.ConnectivityApi=Zm});var ih=v(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.projectConnectorTableSchema=Me.projectConnectorTables=Me.tableSchemaSuffix=Me.tablesSuffix=Me.encodeTable=Me.encodeDataset=Me.checkTabularConnection=Me.runtimeAuthority=Me.tabularRevision=Me.checkTableSchemaArguments=Me.checkListTablesArguments=void 0;var qo=Q(),M=Bo(),s4=/^[A-Za-z0-9_.-]{1,128}$/,Vo=/^\.{1,2}$/,l4="shared_sharepointonline",u4=/^[0-9]{1,9}$/,c4=/^[A-Za-z0-9._~-]+$/,d4=/^\/apim\/([A-Za-z0-9._-]+)\/?$/,f4=/^\/connectors\/runtime\/invoke\/scalegroups\/([A-Za-z0-9._-]+)\/(scaleunits|shards)\/([A-Za-z0-9._-]+)\/apis\/([A-Za-z0-9._-]+)\/connections\/?$/,p4=/^[A-Za-z0-9._~!'()*-]$/,m4=/^[0-9A-Fa-f]{2}$/;function vi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Dl(e){return typeof e=="string"?`'${(0,M.bounded)(e,80)}'`:(0,M.kindOf)(e)}function eh(e,t){return new qo.SdkError(M.CONNECTOR_NOT_TABULAR_CODE,`The connector '${(0,M.bounded)(e,80)}' has no tables: ${t}.`)}function qc(e,t){return new qo.SdkError(M.CONNECTOR_RUNTIME_UNSUPPORTED_CODE,`The connector '${(0,M.bounded)(e,80)}' runs where this SDK does not send a token: ${t}. Nothing was sent to it.`)}function h4(e){if(typeof e=="string"&&s4.test(e)&&!Vo.test(e))return e;throw new qo.InvalidArgumentError(`connectionId must be a connection's name (letters, digits, '_', '.', '-'; at most 128; not '.' or '..'); got ${Dl(e)}.`)}function g4(e){if(e!=null){if(typeof e=="string"&&e!==""&&e.split(",").find(r=>r===""||Vo.test(r))===void 0)return e;throw new qo.InvalidArgumentError(`dataset must be a non-empty string (a SharePoint site URL, a SQL 'server,database', \u2026) none of whose ','-separated parts is empty, '.' or '..', or absent for a connector without datasets; got ${Dl(e)}.`)}}function y4(e){if(typeof e=="string"&&e!==""&&!Vo.test(e))return e;throw new qo.InvalidArgumentError(`table must be a non-empty string other than '.' and '..'; got ${Dl(e)}.`)}function YE(e,t,r){return{short:(0,M.connectorShortName)(e),connectionId:h4(t),dataset:g4(r)}}Me.checkListTablesArguments=YE;function b4(e,t,r,n){return{...YE(e,t,r),table:y4(n)}}Me.checkTableSchemaArguments=b4;function v4(e,t){let r=`The connector '${(0,M.bounded)(t,80)}'`,n=e.properties;if(!(0,M.isObject)(n))throw(0,M.unreadable)(r,`its properties are ${(0,M.kindOf)(n)}, not an object`);if(!vi(n,"interfaces"))throw eh(t,"it declares no interfaces");let i=n.interfaces;if(!(0,M.isObject)(i))throw(0,M.unreadable)(r,`its properties.interfaces are ${(0,M.kindOf)(i)}, not an object`);if(!vi(i,"CDPTabular1"))throw eh(t,"it declares no CDPTabular1 interface");let o=i.CDPTabular1;if(!(0,M.isObject)(o))throw(0,M.unreadable)(r,`its CDPTabular1 interface is ${(0,M.kindOf)(o)}, not an object`);let a=o.revisions;if(!(0,M.isObject)(a))throw(0,M.unreadable)(r,`its CDPTabular1 revisions are ${(0,M.kindOf)(a)}, not an object`);let s,l=new Map;for(let u of Object.keys(a)){let c=a[u],d=`its CDPTabular1 revision '${(0,M.bounded)(u,40)}'`;if(!(0,M.isObject)(c)||typeof c.status!="string")throw(0,M.unreadable)(r,`${d} is not an object with a string status`);if(c.status!=="Production")continue;if(!u4.test(u))throw(0,M.unreadable)(r,`${d} is a Production revision whose key is not a decimal integer of 1\u20139 digits`);let f=w4(c.baseUrl);if(f===void 0)throw(0,M.unreadable)(r,`${d} has a baseUrl that is not '/' or '/'-separated [A-Za-z0-9._~-] segments`);let m=Number(u),p=l.get(m);if(p!==void 0)throw(0,M.unreadable)(r,`its Production revisions '${p}' and '${(0,M.bounded)(u,40)}' have the same number`);l.set(m,u),(!s||m>s.revisionNumber)&&(s={revisionNumber:m,revision:f})}if(!s)throw eh(t,"its CDPTabular1 interface has no Production revision");return s.revision}Me.tabularRevision=v4;function w4(e){if(typeof e!="string")return;let t=e.replace(/^\/+/,"").replace(/\/+$/,"");return t===""?"":t.split("/").every(i=>c4.test(i)&&!Vo.test(i))?t:void 0}function C4(e,t,r){let n=(0,M.isObject)(e.properties)?e.properties:void 0,i=n?n.primaryRuntimeUrl:void 0;if(typeof i!="string")throw qc(r,`its primaryRuntimeUrl is ${(0,M.kindOf)(i)}, not a string`);let o=t.cloud==="Test",a=(o?`https://${t.name}.tip2-001.tip2.azure-apihub.net`:t.origin).toLowerCase(),s=(0,M.parseUrl)(i);if(!s||s.protocol!=="https:"||s.origin.toLowerCase()!==a)throw qc(r,`its runtime ('${(0,M.bounded)(i,120)}') is not ${o?"this environment's measured API Hub host (<environment name>.tip2-001.tip2.azure-apihub.net)":"under this environment's own Power Platform API origin"} over https`);let l=i.slice(0,a.length).toLowerCase()===a?i.slice(a.length):void 0;if(o){let c=l===void 0?null:d4.exec(l);if(!c||Vo.test(c[1]))throw qc(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <host>/apim/<connector>`);return{transport:"invoke",origin:a,path:`/apim/${c[1]}`}}let u=l===void 0?null:f4.exec(l);if(!u||[u[1],u[3],u[4]].some(c=>Vo.test(c)))throw qc(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <origin>/connectors/runtime/invoke/scalegroups/<group>/(scaleunits|shards)/<unit>/apis/<api>/connections`);return{transport:"direct",origin:a,path:`/connectors/runtime/invoke/scalegroups/${u[1]}/${u[2]}/${u[3]}/apis/${u[4]}/connections`}}Me.runtimeAuthority=C4;function E4(e,t,r,n){let i=`The connection '${(0,M.bounded)(t,128)}'`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(i,`it is ${(0,M.kindOf)(e)}, not an object`);if(e.name!==t)throw(0,M.unreadable)(i,`its name is ${Dl(e.name)}, not the requested connection`);let o=e.properties;if(!(0,M.isObject)(o))throw(0,M.unreadable)(i,`its properties are ${(0,M.kindOf)(o)}, not an object`);let a=o.apiId;if(typeof a!="string"||a.toLowerCase()!==`${M.CONNECTOR_PREFIX}${r}`.toLowerCase())throw(0,M.unreadable)(i,`its apiId is ${Dl(a)}, not the connector '${(0,M.bounded)(r,80)}'`);let s=o.environment,l=(0,M.isObject)(s)?s.name:void 0;if(typeof l!="string"||l.toLowerCase()!==n.toLowerCase())throw(0,M.unreadable)(i,"it is not a connection of this environment (properties.environment.name)");return t}Me.checkTabularConnection=E4;function JE(e){return encodeURIComponent(e).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}function A4(e){if(e==="")return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="%"){if(!m4.test(e.slice(t+1,t+3)))return!1;t+=2}else if(!p4.test(e[t]))return!1;return!0}function QE(e,t){let r,n,i;try{r=JE(e),n=JE(r),i=decodeURIComponent(n)}catch{throw new qo.InvalidArgumentError(`${t} is not well-formed Unicode (it has a lone surrogate), so it cannot be sent.`)}if(!A4(n)||Vo.test(n)||i!==r)throw new qo.InvalidArgumentError(`${t} cannot be sent as one path segment.`);return n}function nh(e){return e.split(",").map((t,r)=>QE(t,`dataset part ${r}`)).join(",")}Me.encodeDataset=nh;function XE(e){return QE(e,"table")}Me.encodeTable=XE;function S4(e,t){if(t===void 0)return"/tables";let r=e.toLowerCase()===l4?"allTables":"tables";return`/datasets/${nh(t)}/${r}`}Me.tablesSuffix=S4;function N4(e,t){return`/$metadata.json${e===void 0?"":`/datasets/${nh(e)}`}/tables/${XE(t)}`}Me.tableSchemaSuffix=N4;function Va(e,t){let r=t.toLowerCase();for(let n of Object.keys(e))if(n.toLowerCase()===r)return{found:!0,value:e[n]};return{found:!1}}function _4(e){let t="The table list",r;if(Array.isArray(e))r=e;else if((0,M.isObject)(e)){for(let o of["nextLink","@odata.nextLink"])if(Va(e,o).found)throw(0,M.unreadable)(t,`it carries a ${o} \u2014 a paged answer is refused, never read as a partial list`);let n=Va(e,"value"),i=n.found?n:Va(e,"tables");if(!i.found)throw(0,M.unreadable)(t,"it is an object with neither a value nor a tables member");if(!Array.isArray(i.value))throw(0,M.unreadable)(t,`its ${n.found?"value":"tables"} is ${(0,M.kindOf)(i.value)}, not an array`);r=i.value}else throw(0,M.unreadable)(t,`it is ${(0,M.kindOf)(e)}, not an array or an object`);return{tables:r.map((n,i)=>T4(n,i))}}Me.projectConnectorTables=_4;function T4(e,t){let r=`Table row ${t}`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=Va(e,"name");if(!n.found||typeof n.value!="string"||n.value==="")throw(0,M.unreadable)(r,"it has no non-empty string name");let i=Va(e,"displayName");if(i.found&&typeof i.value!="string")throw(0,M.unreadable)(r,`its displayName is ${(0,M.kindOf)(i.value)}, not a string`);let o=Va(e,"id");if(o.found&&(typeof o.value!="string"||o.value===""))throw(0,M.unreadable)(r,`its id is ${o.value===""?"an empty string":(0,M.kindOf)(o.value)}, not a non-empty string`);return{name:n.value,displayName:i.found?i.value:null,id:o.found?o.value:n.value}}function th(e,t,r){if(!vi(e,t))return;let n=e[t];if(!(0,M.isObject)(n))throw(0,M.unreadable)("The table schema",`its ${r} is ${(0,M.kindOf)(n)}, not an object`);return n}function rh(e,t,r){if(!vi(e,t))return;let n=e[t];if(typeof n!="string")throw(0,M.unreadable)(r,`its ${t} is ${(0,M.kindOf)(n)}, not a string`);return n}function D4(e,t){var r,n;if(vi(e,"$ref"))throw(0,M.unreadable)(t,"it is a $ref, whose type is not guessed");let i=rh(e,"type",t),o=rh(e,"format",t),a=(r=i??o)!==null&&r!==void 0?r:"object";if(!vi(e,"items"))return a;let s=e.items;if(!(0,M.isObject)(s))throw(0,M.unreadable)(t,`its items are ${(0,M.kindOf)(s)}, not an object`);if(vi(s,"$ref"))throw(0,M.unreadable)(t,"its items are a $ref, whose type is not guessed");return`${a}<${(n=rh(s,"type",`${t} items`))!==null&&n!==void 0?n:"object"}>`}function I4(e,t){let r="The table schema";if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=th(e,"items","items"),i=th(e,"schema","schema"),o=i?th(i,"items","schema.items"):void 0,a=[[e,"the answer"],[n,"items"],[i,"schema"],[o,"schema.items"]],s=new Set;for(let[c,d]of a)if(c&&vi(c,"required")){let f=c.required;if(!Array.isArray(f))throw(0,M.unreadable)(r,`the required of ${d} is ${(0,M.kindOf)(f)}, not an array`);f.forEach(m=>{if(typeof m!="string")throw(0,M.unreadable)(r,`the required of ${d} has an entry that is ${(0,M.kindOf)(m)}, not a string`);s.add(m.toLowerCase())})}let l;for(let[c,d]of a)if(c&&vi(c,"properties")){if(!(0,M.isObject)(c.properties))throw(0,M.unreadable)(r,`the properties of ${d} are ${(0,M.kindOf)(c.properties)}, not an object`);l=c.properties;break}if(!l)throw(0,M.unreadable)(r,"it has no properties, items.properties, schema.properties or schema.items.properties");let u=Object.keys(l).map(c=>{let d=`Column '${(0,M.bounded)(c,80)}'`,f=l[c];if(!(0,M.isObject)(f))throw(0,M.unreadable)(d,`it is ${(0,M.kindOf)(f)}, not an object`);return{name:c,type:D4(f,d),required:s.has(c.toLowerCase())}});return{table:t,columns:u}}Me.projectConnectorTableSchema=I4});var ZE=v(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.PowerPlatformApiDiscovery=void 0;var oh=class{constructor(t){this.clusterCategory=t}getTokenAudience(){return`https://${this._getEnvironmentApiHostNameSuffix()}`}getTokenEndpointHost(){return this._getEnvironmentApiHostNameSuffix()}getTenantEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant")}getTenantIslandClusterEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant","il-")}getEnvironmentEndpoint(t){return this._generatePowerPlatformApiDomain(t,"environment")}_generatePowerPlatformApiDomain(t,r,n=""){if(!/^[a-zA-Z0-9\-]+$/g.test(t))throw new Error(`Cannot generate Power Platform API endpoint because the ${r} identifier contains invalid host name characters, only alphanumeric and dash characters are expected: ${t}`);let i=this._getHexApiSuffixLength(),o=t.toLowerCase().replace(/-/g,"");if(i>=o.length)throw new Error(`Cannot generate Power Platform API endpoint because the normalized ${r} identifier must be at least ${i+1} characters in length: ${o}`);let a=o.substring(o.length-i),s=o.substring(0,o.length-i),l=this._getEnvironmentApiHostNameSuffix();return`${n}${s}.${a}.${r}.${l}`}_getHexApiSuffixLength(){switch(this.clusterCategory){case"firstrelease":case"prod":return 2;default:return 1}}_getEnvironmentApiHostNameSuffix(){switch(this.clusterCategory){case"local":return"api.powerplatform.localhost";case"dev":return"api.dev.powerplatform.com";case"test":return"api.test.powerplatform.com";case"preprod":return"api.preprod.powerplatform.com";case"firstrelease":case"prod":return"api.powerplatform.com";case"gov":return"api.gov.powerplatform.microsoft.us";case"high":return"api.high.powerplatform.microsoft.us";case"dod":return"api.appsplatform.us";case"mooncake":return"api.powerplatform.partner.microsoftonline.cn";case"ex":return"api.powerplatform.eaglex.ic.gov";case"rx":return"api.powerplatform.microsoft.scloud";default:throw new Error(`Invalid ClusterCategory value: ${this.clusterCategory}`)}}};Vc.PowerPlatformApiDiscovery=oh});var eA=v(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});Gc.PowerPlatformApiDiscovery=void 0;var O4=ZE();Object.defineProperty(Gc,"PowerPlatformApiDiscovery",{enumerable:!0,get:function(){return O4.PowerPlatformApiDiscovery}})});var iA=v(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.platformTokenAudience=to.platformEnvironment=to.platformClusterOf=void 0;var tA=eA(),rA=Q(),nA=Bo(),P4=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,R4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,L4=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,k4=/^default-/i;function ah(e,t=80){return e.length>t?`${e.slice(0,t)}\u2026`:e}function $4(e){try{return new URL(e).host.toLowerCase()}catch{return}}function x4(e){let t=$4(e);if(t){if(R4.test(t))return{cloud:"Test",category:"test"};let r=P4.exec(t);if(r&&r[1]!=="9")return{cloud:"Public",category:"prod"}}throw new rA.SdkError(nA.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The Power Platform API route is built for the Test and Public clouds; this org (${t?`'${ah(t)}'`:`'${ah(e)}', which is not a URL`}) is another cloud. A Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are pending or out of scope. Nothing was requested.`)}to.platformClusterOf=x4;function F4(e,t){let r=k4.test(e)?e.slice(8):e;if(!L4.test(r))throw new rA.SdkError(nA.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: its name ('${ah(e)}') is neither a GUID nor 'Default-<GUID>', the forms this route is measured for. The Power Platform API was not asked about it.`);return{origin:`https://${new tA.PowerPlatformApiDiscovery(t).getEnvironmentEndpoint(e)}`,guid:r.toLowerCase()}}to.platformEnvironment=F4;function M4(e){return new tA.PowerPlatformApiDiscovery(e).getTokenAudience()}to.platformTokenAudience=M4});var aA=v(Ga=>{"use strict";Object.defineProperty(Ga,"__esModule",{value:!0});Ga.PlatformConnectivityApi=Ga.assertTabularCloud=void 0;var wn=Q(),sh=Al(),fe=Bo(),oA=iA(),wi=ih(),lh="1";function uh(e){let t=(0,fe.connectivityCloudOf)(e);if(t!=="Test"&&t!=="Public")throw new wn.SdkError(fe.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"Connector tables are read in the Test and Public clouds; this org's cloud is neither (GCC, GCC High and DoD are pending). Nothing was requested.")}Ga.assertTabularCloud=uh;var ch=class{constructor(t,r,n,i){this.org=t,this.instanceUrl=r,this.client=n,this.runtime=i,this.records=new Map,this.swaggers=new Map}async listConnections(){let t=await this.resolveEnvironment(),r=[],n=new Set,i=await this.send(this.client,"GET",`${t.origin}/connectivity/connections?api-version=${lh}`,[401,403]),o=1,a=0;for(;;){let s=`Page ${o} of the connections`,l=i.body,u=l?.value;if(!Array.isArray(u))throw(0,fe.unreadable)(s,`its value is ${(0,fe.kindOf)(u)}, not an array`);for(let d of u){let f=(0,fe.readConnection)(d,a,t.name);a+=1,f&&r.push(f)}let c=l?.nextLink;if(c==null)return r;if(typeof c!="string"||c.length===0)throw(0,fe.unreadable)(s,`its nextLink is ${c===""?"an empty string":(0,fe.kindOf)(c)}, not a non-empty string`);if(n.has(c))throw new wn.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${(0,fe.bounded)(c)}'), which would loop indefinitely.`);n.add(c),this.assertSameOrigin(c,t.parsed),i=await this.send(this.client,"GET",c,[401,403]),o+=1}}async listConnectorOperations(t){let r=(0,fe.connectorShortName)(t);return(0,sh.projectConnectorOperations)(await this.swagger(r))}async getConnectorOperationSchema(t,r){let n=(0,fe.connectorShortName)(t);if(typeof r!="string"||r==="")throw new wn.InvalidArgumentError("operationId must be a non-empty string.");return(0,sh.projectConnectorOperationSchema)(await this.swagger(n),r)}async listConnectorTables(t,r,n){uh(this.instanceUrl);let i=(0,wi.checkListTablesArguments)(t,r,n),o=(0,wi.tablesSuffix)(i.short,i.dataset);return(0,wi.projectConnectorTables)(await this.invokeTabular(i,o))}async getConnectorTableSchema(t,r,n,i){uh(this.instanceUrl);let o=(0,wi.checkTableSchemaArguments)(t,r,n,i),a=(0,wi.tableSchemaSuffix)(o.dataset,o.table);return(0,wi.projectConnectorTableSchema)(await this.invokeTabular(o,a),o.table)}async invokeTabular(t,r){let n=this.requireRuntime(),i=await this.resolveEnvironment(),o=await this.record(t.short),a=(0,wi.tabularRevision)(o,t.short),s=(0,wi.runtimeAuthority)(o,{cloud:i.cloud,name:i.name,origin:i.origin},t.short),l=`${i.origin}/connectivity/connectors/${encodeURIComponent(t.short)}/connections/${encodeURIComponent(t.connectionId)}?$filter=${(0,fe.environmentFilter)(i.name)}&api-version=${lh}`,u=(await this.send(this.client,"GET",l,[401,403])).body,c=(0,wi.checkTabularConnection)(u,t.connectionId,t.short,i.name),d=`${s.path}/${c}${a===""?"":`/${a}`}${r}`;return(s.transport==="invoke"?await this.send(n,"POST",`${s.origin}/invoke`,[401],{"X-Ms-Request-Url":d,"X-Ms-Request-Method":"GET"}):await this.send(n,"GET",`${s.origin}${d}`,[401])).body}requireRuntime(){if(!this.runtime)throw new wn.SdkError(fe.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a connectorRuntimeClient (MakerSdkOptions), so it cannot read connector tables: it needs an HttpClient that authenticates for API Hub (https://apihub.azure.com) and does not follow redirects. Nothing was requested.");return this.runtime}resolveEnvironment(){if(!this.environment){let t=this.readEnvironment();this.environment=t,t.catch(()=>{this.environment===t&&(this.environment=void 0)})}return this.environment}async readEnvironment(){let{cloud:t,category:r}=(0,oA.platformClusterOf)(this.instanceUrl),n=await(0,fe.readEnvironmentName)(this.org),{origin:i,guid:o}=(0,oA.platformEnvironment)(n,r),a=(0,fe.parseUrl)(i);if(!a)throw(0,fe.unreadable)("The Power Platform API origin",`'${(0,fe.bounded)(i)}' is not a URL`);return{cloud:t,origin:i,parsed:a,name:n,guid:o}}cached(t,r,n){let i=t.get(r);if(!i){let o=n();i=o,t.set(r,o),o.catch(()=>{t.get(r)===o&&t.delete(r)})}return i}record(t){return this.cached(this.records,t.toLowerCase(),()=>this.readRecord(t))}async readRecord(t){let r=await this.resolveEnvironment(),n=`${r.origin}/connectivity/connectors/${encodeURIComponent(t)}?$filter=${(0,fe.environmentFilter)(r.name)}&api-version=${lh}`,i=(await this.send(this.client,"GET",n,[401,403])).body,o=(0,fe.isObject)(i)?i.name:void 0;if(!(0,fe.isObject)(i)||typeof o!="string"||o.toLowerCase()!==t.toLowerCase())throw(0,fe.unreadable)(`The connector '${(0,fe.bounded)(t,80)}'`,`the record's name is ${typeof o=="string"?`'${(0,fe.bounded)(o,80)}'`:(0,fe.kindOf)(o)}, not the requested connector`);return i}swagger(t){return this.cached(this.swaggers,t.toLowerCase(),async()=>{let n=(await this.record(t)).properties,i=(0,fe.isObject)(n)?n.swagger:void 0;if(!(0,fe.isObject)(i))throw(0,fe.unreadable)(`The connector '${(0,fe.bounded)(t,80)}'`,`its properties.swagger is ${(0,fe.kindOf)(i)}, not an object`);return(0,sh.validateConnectorSwagger)(i),i})}assertSameOrigin(t,r){let n=(0,fe.parseUrl)(t);if(!n)throw new wn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${(0,fe.bounded)(t)}'`);if(!(0,fe.sameOrigin)(n,r))throw new wn.InvalidArgumentError(`Refusing to follow a cross-origin link ('${(0,fe.bounded)(n.origin,120)}' is not the environment's Power Platform API origin '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n,i,o){let a;try{a=r==="GET"?await t.get(n):await t.post(n,void 0,{headers:o})}catch(s){throw s instanceof wn.ConnectionError&&typeof s.statusCode=="number"&&s.statusCode>0?this.non2xx(n,s.statusCode,void 0,i,s):s instanceof wn.SdkError?s:new wn.ConnectionError(n,0,s instanceof Error?s.message:String(s),s)}if(!a||typeof a.status!="number")throw new wn.ConnectionError(n,0,"the transport returned no HTTP response");if(a.status>=200&&a.status<300)return a;throw this.non2xx(n,a.status,a.body,i)}non2xx(t,r,n,i,o){let a=o??new wn.ConnectionError(t,r,(0,fe.messageOf)(n),n);return i.includes(r)?(0,fe.connectivityUnauthorized)(r,n,a):a}};Ga.PlatformConnectivityApi=ch});var lA=v(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});zc.ConnectivityRouter=void 0;var dh=Q(),U4=KE(),Wc=Bo(),sA=ih(),fh=aA(),ph=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.clients=n}async listConnections(){return this.route().listConnections()}async listConnectorOperations(t){return this.route().listConnectorOperations(t)}async getConnectorOperationSchema(t,r){return this.route().getConnectorOperationSchema(t,r)}async listConnectorTables(t,r,n){return(0,fh.assertTabularCloud)(this.instanceUrl),(0,sA.checkListTablesArguments)(t,r,n),this.tabularRoute().listConnectorTables(t,r,n)}async getConnectorTableSchema(t,r,n,i){return(0,fh.assertTabularCloud)(this.instanceUrl),(0,sA.checkTableSchemaArguments)(t,r,n,i),this.tabularRoute().getConnectorTableSchema(t,r,n,i)}route(){return this.delegate||(this.delegate=this.select()),this.delegate}platformRoute(t){return this.platform||(this.platform=new fh.PlatformConnectivityApi(this.org,this.instanceUrl,t,this.clients.connectorRuntimeClient)),this.platform}tabularRoute(){let{powerPlatformApiClient:t,connectorRuntimeClient:r}=this.clients,n=[t?void 0:"powerPlatformApiClient (the Power Platform API)",r?void 0:"connectorRuntimeClient (API Hub, https://apihub.azure.com)"].filter(i=>i!==void 0);if(n.length>0||!t)throw new dh.SdkError(Wc.CONNECTIVITY_NOT_CONFIGURED_CODE,`Connector tables are read through the Power Platform API and the connector runtime: this SDK was created without MakerSdkOptions.${n.join(" or MakerSdkOptions.")}, an HttpClient that does not follow redirects. Nothing was requested.`);return this.platformRoute(t)}select(){let t=(0,Wc.connectivityCloudOf)(this.instanceUrl),{powerAppsServiceClient:r,powerPlatformApiClient:n}=this.clients;if(t==="Unsupported")throw new dh.SdkError(Wc.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"This org's cloud has no connection/connector route: the Test and Public clouds are served (through the Power Platform API, or the classic route for Public); GCC, GCC High and DoD are pending. Nothing was requested.");if(n)return this.platformRoute(n);if(t==="Public"&&r)return new U4.ConnectivityApi(this.org,this.instanceUrl,r);throw new dh.SdkError(Wc.CONNECTIVITY_NOT_CONFIGURED_CODE,t==="Test"?"This org is in the Test cloud, whose connection and connector reads go through the Power Platform API: supply MakerSdkOptions.powerPlatformApiClient (an HttpClient that authenticates for the Power Platform API and does not follow redirects). Nothing was requested.":"This org is in the Public cloud: supply MakerSdkOptions.powerPlatformApiClient (the Power Platform API route) or powerAppsServiceClient (the classic route). Neither was given, so nothing was requested.")}};zc.ConnectivityRouter=ph});var Wa=v(Ci=>{"use strict";function B4(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 hh(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function q4(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 uA=hh({HTML:"text/html",isHTML:function(e){return e===uA.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),cA=hh({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===cA.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),jc=/[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]/,mh=new RegExp("[\\-\\.0-9"+jc.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),V4=new RegExp("^"+jc.source+mh.source+"*(?::"+jc.source+mh.source+"*)?$");Ci.assign=q4;Ci.find=B4;Ci.freeze=hh;Ci.MIME_TYPE=uA;Ci.NAMESPACE=cA;Ci.nameStartChar=jc;Ci.nameChar=mh;Ci.tagNamePattern=V4});var Th=v(Ni=>{var gh=Wa(),Wn=gh.find,Ol=gh.NAMESPACE,za=gh.tagNamePattern;function G4(e){return e!==""}function W4(e){return e?e.split(/[\t\n\f\r ]+/).filter(G4):[]}function z4(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function dA(e){if(!e)return[];var t=W4(e);return Object.keys(t.reduce(z4,{}))}function j4(e){return function(t){return e&&e.indexOf(t)!==-1}}function Rl(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function wr(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,Rl(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Cr={},Zr=Cr.ELEMENT_NODE=1,ja=Cr.ATTRIBUTE_NODE=2,Il=Cr.TEXT_NODE=3,vA=Cr.CDATA_SECTION_NODE=4,wA=Cr.ENTITY_REFERENCE_NODE=5,H4=Cr.ENTITY_NODE=6,yh=Cr.PROCESSING_INSTRUCTION_NODE=7,bh=Cr.COMMENT_NODE=8,CA=Cr.DOCUMENT_NODE=9,EA=Cr.DOCUMENT_TYPE_NODE=10,Ei=Cr.DOCUMENT_FRAGMENT_NODE=11,K4=Cr.NOTATION_NODE=12,zt={},St={},Ise=zt.INDEX_SIZE_ERR=(St[1]="Index size error",1),Ose=zt.DOMSTRING_SIZE_ERR=(St[2]="DOMString size error",2),vr=zt.HIERARCHY_REQUEST_ERR=(St[3]="Hierarchy request error",3),Pse=zt.WRONG_DOCUMENT_ERR=(St[4]="Wrong document",4),fA=zt.INVALID_CHARACTER_ERR=(St[5]="Invalid character",5),Rse=zt.NO_DATA_ALLOWED_ERR=(St[6]="No data allowed",6),Lse=zt.NO_MODIFICATION_ALLOWED_ERR=(St[7]="No modification allowed",7),AA=zt.NOT_FOUND_ERR=(St[8]="Not found",8),kse=zt.NOT_SUPPORTED_ERR=(St[9]="Not supported",9),pA=zt.INUSE_ATTRIBUTE_ERR=(St[10]="Attribute in use",10),Cn=zt.INVALID_STATE_ERR=(St[11]="Invalid state",11),$se=zt.SYNTAX_ERR=(St[12]="Syntax error",12),xse=zt.INVALID_MODIFICATION_ERR=(St[13]="Invalid modification",13),Fse=zt.NAMESPACE_ERR=(St[14]="Invalid namespace",14),Mse=zt.INVALID_ACCESS_ERR=(St[15]="Invalid access",15);function pe(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,St[e]),this.message=St[e],Error.captureStackTrace&&Error.captureStackTrace(this,pe);return r.code=e,t&&(this.message=this.message+": "+t),r}pe.prototype=Error.prototype;Rl(zt,pe);function Ai(){}Ai.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=[],o=0;o<this.length;o++)_h(this[o],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 Ha(e,t){this._node=e,this._refresh=t,vh(this)}function vh(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(xA(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];Rl(r,e),e._inc=t}}Ha.prototype.item=function(e){return vh(this),this[e]||null};wr(Ha,Ai);function Kc(){this._nameIndex=Object.create(null)}function SA(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function J4(e,t){e._nameIndex[t.nodeName]=t}function NA(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function mA(e,t,r,n){if(n?(t[SA(t,n)]=r,NA(t,n)):t[t.length++]=r,J4(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&DA(i,e,n),Y4(i,e,r))}}function hA(e,t,r){var n=SA(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,NA(t,r),e){var o=e.ownerDocument;o&&(DA(o,e,r),r.ownerElement=null)}}else throw new pe(AA,new Error(e.tagName+"@"+r))}Kc.prototype={length:0,item:Ai.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 pe(pA);var r=this._nameIndex[e.nodeName];return mA(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new pe(pA);return r=this.getNamedItemNS(e.namespaceURI,e.localName),mA(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return hA(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return hA(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 _A(){}_A.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new Ll;if(n.implementation=this,n.childNodes=new Ai,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 Zc;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function De(){}De.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(e,t){return Yc(this,e,t)},replaceChild:function(e,t){Yc(this,e,t,OA),t&&this.removeChild(t)},removeChild:function(e){return IA(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return $A(this.ownerDocument||this,this,e)},normalize:function(){At(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===Il&&t.nodeType===Il){for(var n=[],i=r;i!==null&&i.nodeType===Il;)n.push(i.data),i=i.nextSibling;for(var o=t.nextSibling;o!==i;){var a=o.nextSibling;o.parentNode=null,o.previousSibling=null,o.nextSibling=null,o=a}t.nextSibling=i,i!==null?i.previousSibling=t:e.lastChild=t,t.appendData(n.join("")),Xc(e.ownerDocument,e),t=i}else t=r}return!0}})},isSupported:function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(e){for(var t=this;t;){var r=t._nsMap;if(r){for(var n in r)if(Object.prototype.hasOwnProperty.call(r,n)&&r[n]===e)return n}t=t.nodeType==ja?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==ja?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function TA(e){return e=="<"&&"&lt;"||e==">"&&"&gt;"||e=="&"&&"&amp;"||e=='"'&&"&quot;"||"&#"+e.charCodeAt()+";"}Rl(Cr,De);Rl(Cr,De.prototype);function Jc(e,t){return At(e,null,{enter:function(r){return t(r)?At.STOP:!0}})===At.STOP}function At(e,t,r){for(var n=[{node:e,context:t,phase:At.ENTER}];n.length>0;){var i=n.pop();if(i.phase===At.ENTER){var o=r.enter(i.node,i.context);if(o===At.STOP)return At.STOP;if(n.push({node:i.node,context:o,phase:At.EXIT}),o==null)continue;for(var a=i.node.lastChild;a;)n.push({node:a,context:o,phase:At.ENTER}),a=a.previousSibling}else r.exit&&r.exit(i.node,i.context)}}At.STOP=Symbol("walkDOM.STOP");At.ENTER=0;At.EXIT=1;function Ll(){this.ownerDocument=this}function Y4(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Ol.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function DA(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Ol.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function Xc(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,o=0;i;)n[o++]=i,i=i.nextSibling;n.length=o,delete n[n.length]}}}function IA(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,Xc(e.ownerDocument,e),t}function Q4(e){return e&&(e.nodeType===De.DOCUMENT_NODE||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.ELEMENT_NODE)}function X4(e){return e&&(zn(e)||wh(e)||Si(e)||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.COMMENT_NODE||e.nodeType===De.PROCESSING_INSTRUCTION_NODE)}function Si(e){return e&&e.nodeType===De.DOCUMENT_TYPE_NODE}function zn(e){return e&&e.nodeType===De.ELEMENT_NODE}function wh(e){return e&&e.nodeType===De.TEXT_NODE}function gA(e,t){var r=e.childNodes||[];if(Wn(r,zn)||Si(t))return!1;var n=Wn(r,Si);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function yA(e,t){var r=e.childNodes||[];function n(o){return zn(o)&&o!==t}if(Wn(r,n))return!1;var i=Wn(r,Si);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function Z4(e,t,r){if(!Q4(e))throw new pe(vr,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new pe(AA,"child not in parent");if(!X4(t)||Si(t)&&e.nodeType!==De.DOCUMENT_NODE)throw new pe(vr,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function eG(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(zn);if(o.length>1||Wn(i,wh))throw new pe(vr,"More than one element or text in fragment");if(o.length===1&&!gA(e,r))throw new pe(vr,"Element in fragment can not be inserted before doctype")}if(zn(t)&&!gA(e,r))throw new pe(vr,"Only one element can be added and only after doctype");if(Si(t)){if(Wn(n,Si))throw new pe(vr,"Only one doctype is allowed");var a=Wn(n,zn);if(r&&n.indexOf(a)<n.indexOf(r))throw new pe(vr,"Doctype can only be inserted before an element");if(!r&&a)throw new pe(vr,"Doctype can not be appended since element is present")}}function OA(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(zn);if(o.length>1||Wn(i,wh))throw new pe(vr,"More than one element or text in fragment");if(o.length===1&&!yA(e,r))throw new pe(vr,"Element in fragment can not be inserted before doctype")}if(zn(t)&&!yA(e,r))throw new pe(vr,"Only one element can be added and only after doctype");if(Si(t)){let l=function(u){return Si(u)&&u!==r};var s=l;if(Wn(n,l))throw new pe(vr,"Only one doctype is allowed");var a=Wn(n,zn);if(r&&n.indexOf(a)<n.indexOf(r))throw new pe(vr,"Doctype can only be inserted before an element")}}function Yc(e,t,r,n){Z4(e,t,r),e.nodeType===De.DOCUMENT_NODE&&(n||eG)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===Ei){var o=t.firstChild;if(o==null)return t;var a=t.lastChild}else o=a=t;var s=r?r.previousSibling:e.lastChild;o.previousSibling=s,a.nextSibling=r,s?s.nextSibling=o:e.firstChild=o,r==null?e.lastChild=a:r.previousSibling=a;do{o.parentNode=e;var l=e.ownerDocument||e;Pl(o,l)}while(o!==a&&(o=o.nextSibling));return Xc(e.ownerDocument||e,e),t.nodeType==Ei&&(t.firstChild=t.lastChild=null),t}function Pl(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===Zr&&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;)Pl(i,t),i=i.nextSibling}}function tG(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,Xc(e.ownerDocument,e,t);var r=e.ownerDocument||e;return Pl(t,r),t}Ll.prototype={nodeName:"#document",nodeType:CA,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==Ei){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return Yc(this,e,t),Pl(e,this),this.documentElement===null&&e.nodeType===Zr&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),IA(this,e)},replaceChild:function(e,t){Yc(this,e,t,OA),Pl(e,this),t&&this.removeChild(t),zn(e)&&(this.documentElement=e)},importNode:function(e,t){return rG(this,e,t)},getElementById:function(e){var t=null;return Jc(this.documentElement,function(r){if(r.nodeType==Zr&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=dA(e);return new Ha(this,function(r){var n=[];return t.length>0&&Jc(r.documentElement,function(i){if(i!==r&&i.nodeType===Zr){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=dA(o);a=t.every(j4(s))}a&&n.push(i)}}}),n})},createElement:function(e){var t=new Go;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new Ai;var r=t.attributes=new Kc;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new ed;return e.ownerDocument=this,e.childNodes=new Ai,e},createTextNode:function(e){var t=new Ch;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new Eh;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new pe(fA,'data contains "]]>"');var t=new Ah;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new Nh;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new Qc;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!za.test(e))throw new pe(fA,'not a valid xml name "'+e+'"');var t=new Sh;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new Go,n=t.split(":"),i=r.attributes=new Kc;return r.childNodes=new Ai,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 Qc,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}};wr(Ll,De);function Go(){this._nsMap={}}Go.prototype={nodeType:Zr,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===Ei?this.insertBefore(e,null):tG(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 Ha(this,function(t){var r=[];return Jc(t,function(n){n!==t&&n.nodeType==Zr&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new Ha(this,function(r){var n=[];return Jc(r,function(i){i!==r&&i.nodeType===Zr&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};Ll.prototype.getElementsByTagName=Go.prototype.getElementsByTagName;Ll.prototype.getElementsByTagNameNS=Go.prototype.getElementsByTagNameNS;wr(Go,De);function Qc(){}Qc.prototype.nodeType=ja;wr(Qc,De);function kl(){}kl.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(St[vr])},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}};wr(kl,De);function Ch(){}Ch.prototype={nodeName:"#text",nodeType:Il,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}};wr(Ch,kl);function Eh(){}Eh.prototype={nodeName:"#comment",nodeType:bh};wr(Eh,kl);function Ah(){}Ah.prototype={nodeName:"#cdata-section",nodeType:vA};wr(Ah,kl);function Zc(){}Zc.prototype.nodeType=EA;wr(Zc,De);function PA(){}PA.prototype.nodeType=K4;wr(PA,De);function RA(){}RA.prototype.nodeType=H4;wr(RA,De);function Sh(){}Sh.prototype.nodeType=wA;wr(Sh,De);function ed(){}ed.prototype.nodeName="#document-fragment";ed.prototype.nodeType=Ei;wr(ed,De);function Nh(){}Nh.prototype.nodeType=yh;wr(Nh,De);function LA(){}LA.prototype.serializeToString=function(e,t,r,n){return kA.call(e,t,r,n)};De.prototype.toString=kA;function kA(e,t,r){var n=!!r&&!!r.requireWellFormed,i=[],o=this.nodeType==9&&this.documentElement||this,a=o.prefix,s=o.namespaceURI;if(s&&a==null){var a=o.lookupPrefix(s);if(a==null)var l=[{namespace:s,prefix:null}]}return _h(this,i,e,t,l,n),i.join("")}function bA(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===Ol.XML||i===Ol.XMLNS)return!1;for(var o=r.length;o--;){var a=r[o];if(a.prefix===n)return a.namespace!==i}return!0}function Hc(e,t,r,n){if(n&&!za.test(t))throw new pe(Cn,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,TA),'"')}function _h(e,t,r,n,i,o){i||(i=[]),At(e,{ns:i,isHTML:r},{enter:function(a,s){var l=s.ns,u=s.isHTML;if(n)if(a=n(a),a){if(typeof a=="string")return t.push(a),null}else return null;switch(a.nodeType){case Zr:var c=a.attributes,d=c.length,f=a.tagName;u=Ol.isHTML(a.namespaceURI)||u;var m=f;if(!u&&!a.prefix&&a.namespaceURI){for(var p,h=0;h<c.length;h++)if(c.item(h).name==="xmlns"){p=c.item(h).value;break}if(!p)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.prefix===""&&b.namespace===a.namespaceURI){p=b.namespace;break}}if(p!==a.namespaceURI)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.namespace===a.namespaceURI){b.prefix&&(m=b.prefix+":"+f);break}}}if(o&&!za.test(m))throw new pe(Cn,'The element name "'+m+'" is not a valid XML QName');t.push("<",m);for(var w=l.slice(),E=0;E<d;E++){var S=c.item(E);S.prefix=="xmlns"?w.push({prefix:S.localName,namespace:S.value}):S.nodeName=="xmlns"&&w.push({prefix:"",namespace:S.value})}for(var E=0;E<d;E++){var S=c.item(E);if(bA(S,u,w)){var P=S.prefix||"",L=S.namespaceURI;Hc(t,P?"xmlns:"+P:"xmlns",L,o),w.push({prefix:P,namespace:L})}var I=n?n(S):S;I&&(typeof I=="string"?t.push(I):Hc(t,I.name,I.value,o))}if(f===m&&bA(a,u,w)){var D=a.prefix||"",L=a.namespaceURI;Hc(t,D?"xmlns:"+D:"xmlns",L,o),w.push({prefix:D,namespace:L})}var O=a.firstChild;if(O||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(f)){if(t.push(">"),u&&/^script$/i.test(f)){for(;O;)O.data?t.push(O.data):_h(O,t,u,n,w.slice(),o),O=O.nextSibling;return t.push("</",f,">"),null}return{ns:w,isHTML:u,tag:m}}else return t.push("/>"),null;case CA:case Ei:return{ns:l.slice(),isHTML:u,tag:null};case ja:return Hc(t,a.name,a.value,o),null;case Il:return t.push(a.data.replace(/[<&>]/g,TA)),null;case vA:if(o&&a.data.indexOf("]]>")!==-1)throw new pe(Cn,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case bh:if(o&&a.data.indexOf("-->")!==-1)throw new pe(Cn,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case EA:if(o){if(!za.test(a.name))throw new pe(Cn,'The doctype name "'+a.name+'" is not a valid XML Name');if(a.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(a.publicId))throw new pe(Cn,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new pe(Cn,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new pe(Cn,'DocumentType internalSubset contains "]>"')}var x=a.publicId,K=a.systemId;if(t.push("<!DOCTYPE ",a.name),x)t.push(" PUBLIC ",x),K&&K!="."&&t.push(" ",K),t.push(">");else if(K&&K!=".")t.push(" SYSTEM ",K,">");else{var Re=a.internalSubset;Re&&t.push(" [",Re,"]"),t.push(">")}return null;case yh:if(o){if(!za.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new pe(Cn,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new pe(Cn,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case wA:if(o&&!za.test(a.nodeName))throw new pe(Cn,'The entity reference name "'+a.nodeName+'" is not a valid XML Name');return t.push("&",a.nodeName,";"),null;default:return t.push("??",a.nodeName),null}},exit:function(a,s){s&&s.tag&&t.push("</",s.tag,">")}})}function rG(e,t,r){var n;return At(t,null,{enter:function(i,o){var a=i.cloneNode(!1);a.ownerDocument=e,a.parentNode=null,o===null?n=a:o.appendChild(a);var s=i.nodeType===ja||r;return s?a:null}}),n}function $A(e,t,r){var n;return At(t,null,{enter:function(i,o){var a=new i.constructor;for(var s in i)if(Object.prototype.hasOwnProperty.call(i,s)){var l=i[s];typeof l!="object"&&l!=a[s]&&(a[s]=l)}i.childNodes&&(a.childNodes=new Ai),a.ownerDocument=e;var u=r;switch(a.nodeType){case Zr:var c=i.attributes,d=a.attributes=new Kc,f=c.length;d._ownerElement=a;for(var m=0;m<f;m++)a.setAttributeNode($A(e,c.item(m),!0));break;case ja:u=!0}return o!==null?o.appendChild(a):n=a,u?a:null}}),n}function xA(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(Ha.prototype,"length",{get:function(){return vh(this),this.$$length}}),Object.defineProperty(De.prototype,"textContent",{get:function(){if(this.nodeType===Zr||this.nodeType===Ei){var e=[];return At(this,null,{enter:function(t){if(t.nodeType===Zr||t.nodeType===Ei)return!0;if(t.nodeType===yh||t.nodeType===bh)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case Zr:case Ei: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}}}),xA=function(e,t,r){e["$$"+t]=r})}catch{}Ni.DocumentType=Zc;Ni.DOMException=pe;Ni.DOMImplementation=_A;Ni.Element=Go;Ni.Node=De;Ni.NodeList=Ai;Ni.walkDOM=At;Ni.XMLSerializer=LA});var MA=v($l=>{"use strict";var FA=Wa().freeze;$l.XML_ENTITIES=FA({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});$l.HTML_ENTITIES=FA({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"});$l.entityMap=$l.HTML_ENTITIES});var GA=v(Ih=>{var Ml=Wa().NAMESPACE,Dh=Wa().tagNamePattern,Ka=0,ro=1,Ja=2,xl=3,Ya=4,Qa=5,Fl=6,td=7;function Xa(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,Xa)}Xa.prototype=new Error;Xa.prototype.name=Xa.name;function qA(){}qA.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),sG(t,t={}),nG(e,t,r,n,this.errorHandler),n.endDocument()}};function nG(e,t,r,n,i){function o(de){if(de>65535){de-=65536;var He=55296+(de>>10),bn=56320+(de&1023);return String.fromCharCode(He,bn)}else return String.fromCharCode(de)}function a(de){var He=de.slice(1,-1);return Object.hasOwnProperty.call(r,He)?r[He]:He.charAt(0)==="#"?o(parseInt(He.substr(1).replace("x","0x"))):(i.error("entity not found:"+de),de)}function s(de){if(de>h){var He=e.substring(h,de).replace(/&#?\w+;/g,a);f&&l(h),n.characters(He,0,de-h),h=de}}function l(de,He){for(;de>=c&&(He=d.exec(e));)u=He.index,c=u+He[0].length,f.lineNumber++;f.columnNumber=de-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,f=n.locator,m=[{currentNSMap:t}],p={},h=0;;){try{var g=e.indexOf("<",h);if(g<0){if(!e.substr(h).match(/^\s*$/)){var b=n.doc,w=b.createTextNode(e.substr(h));b.appendChild(w),n.currentElement=w}return}switch(g>h&&s(g),e.charAt(g+1)){case"/":var K=e.indexOf(">",g+3),E=e.substring(g+2,K).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),S=m.pop();K<0?(E=e.substring(g+2).replace(/[\s<].*/,""),i.error("end tag name: "+E+" is not complete:"+S.tagName),K=g+1+E.length):E.match(/\s</)?(E=E.replace(/[\s<].*/,""),i.error("end tag name: "+E+" maybe not complete"),K=g+1+E.length):/[ \t\n\r]/.test(E)&&Dh.test(E.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+E+'"');var P=S.localNSMap,L=S.tagName==E,I=L||S.tagName&&S.tagName.toLowerCase()==E.toLowerCase();if(I){if(n.endElement(S.uri,S.localName,E),P)for(var D in P)Object.prototype.hasOwnProperty.call(P,D)&&n.endPrefixMapping(D);L||i.fatalError("end tag name: "+E+" is not match the current start tagName:"+S.tagName)}else m.push(S);K++;break;case"?":f&&l(g),K=uG(e,g,n);break;case"!":f&&l(g),K=lG(e,g,n,i);break;default:f&&l(g);var O=new VA,x=m[m.length-1].currentNSMap,K=iG(e,g,O,x,a,i),Re=O.length;if(!O.closed&&aG(e,K,O.tagName,p)&&(O.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),f&&Re){for(var qt=UA(f,{}),ge=0;ge<Re;ge++){var je=O[ge];l(je.offset),je.locator=UA(f,{})}n.locator=qt,BA(O,n,x)&&m.push(O),n.locator=f}else BA(O,n,x)&&m.push(O);Ml.isHTML(O.uri)&&!O.closed?K=oG(e,K,O.tagName,a,n):K++}}catch(de){if(de instanceof Xa)throw de;i.error("element parse error: "+de),K=-1}K>h?h=K:s(Math.max(g,h)+1)}}function UA(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function iG(e,t,r,n,i,o){function a(m,p,h){r.attributeNames.hasOwnProperty(m)&&o.fatalError("Attribute "+m+" redefined"),r.addValue(m,p.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),h)}for(var s,l,u=++t,c=Ka;;){var d=e.charAt(u);if(c===Ka&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===ro)s=e.slice(t,u),c=xl;else if(c===Ja)c=xl;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===xl||c===ro)if(c===ro&&(o.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),a(s,l,t-1),c=Qa;else throw new Error("attribute value no end '"+d+"' match");else if(c==Ya)l=e.slice(t,u),a(s,l,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=Qa;else throw new Error('attribute value must after "="');break;case"/":switch(c){case Ka:r.setTagName(e.slice(t,u));case Qa:case Fl:case td:c=td,r.closed=!0;case Ya:case ro:break;case Ja:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==Ka&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case Ka:r.setTagName(e.slice(t,u));case Qa:case Fl:case td:break;case Ya:case ro:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case Ja:c===Ja&&(l=s),c==Ya?(o.warning('attribute "'+l+'" missed quot(")!'),a(s,l,t)):((!Ml.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),a(l,l,t));break;case xl:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case Ka:r.setTagName(e.slice(t,u)),c=Fl;break;case ro:s=e.slice(t,u),c=Ja;break;case Ya:var l=e.slice(t,u);o.warning('attribute "'+l+'" missed quot(")!!'),a(s,l,t);case Qa:c=Fl;break}else switch(c){case Ja:var f=r.tagName;(!Ml.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=u,c=ro;break;case Qa:o.warning('attribute space is required"'+s+'"!!');case Fl:c=ro,t=u;break;case xl:c=Ya,t=u;break;case td:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function BA(e,t,r){for(var n=e.tagName,i=null,d=e.length;d--;){var o=e[d],a=o.qName,s=o.value,f=a.indexOf(":");if(f>0)var l=o.prefix=a.slice(0,f),u=a.slice(f+1),c=l==="xmlns"&&u;else u=a,l=null,c=a==="xmlns"&&"";o.localName=u,c!==!1&&(i==null&&(i={},r=Object.create(r)),r[c]=i[c]=s,o.uri=Ml.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var l=o.prefix;l&&(l==="xml"&&(o.uri=Ml.XML),l!=="xmlns"&&(o.uri=r[l||""]))}var f=n.indexOf(":");f>0?(l=e.prefix=n.slice(0,f),u=e.localName=n.slice(f+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 oG(e,t,r,n,i){if(/^(?:script|textarea)$/i.test(r)){var o=e.indexOf("</"+r+">",t),a=e.substring(t+1,o);if(/[&<]/.test(a))return/^script$/i.test(r)?(i.characters(a,0,a.length),o):(a=a.replace(/&#?\w+;/g,n),i.characters(a,0,a.length),o)}return t+1}function aG(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 sG(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function lG(e,t,r,n){var i=e.charAt(t+2);switch(i){case"-":if(e.charAt(t+3)==="-"){var o=e.indexOf("-->",t+4);return o>t?(r.comment(e,t+4,o-t-4),o+3):(n.error("Unclosed comment"),-1)}else return-1;default:if(e.substr(t+3,6)=="CDATA["){var o=e.indexOf("]]>",t+9);return r.startCDATA(),r.characters(e,t+9,o-t-9),r.endCDATA(),o+3}var a=cG(e,t),s=a.length;if(s>1&&/!doctype/i.test(a[0][0])){var l=a[1][0],u=!1,c=!1;s>3&&(/^public$/i.test(a[2][0])?(u=a[3][0],c=s>4&&a[4][0]):/^system$/i.test(a[2][0])&&(c=a[3][0]));var d=a[s-1];return r.startDTD(l,u,c),r.endDTD(),d.index+d[0].length}}return-1}function uG(e,t,r){var n=e.indexOf("?>",t);if(n){var i=e.substring(t,n).match(/^<\?(\S*)\s*([\s\S]*?)$/);if(i){var o=i[0].length;return r.processingInstruction(i[1],i[2]),n+2}else return-1}return-1}function VA(){this.attributeNames={}}VA.prototype={setTagName:function(e){if(!Dh.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!Dh.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 cG(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}Ih.XMLReader=qA;Ih.ParseError=Xa});var YA=v(nd=>{var dG=Wa(),fG=Th(),WA=MA(),HA=GA(),pG=fG.DOMImplementation,zA=dG.NAMESPACE,mG=HA.ParseError,hG=HA.XMLReader;function KA(e){return e.replace(/\r[\n\u0085]/g,`
+`}});var $E=v(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});Wc.generateGenPageRuntimeTypes=void 0;var LE=rh(),Uo=Q(),kE=new Set(["None","ColorsDefaultsConstraints","ColorsDefaultsConstraintsDescriptions"]),Bo="generateGenPageRuntimeTypes";async function IV(e,t,r){let n=OV(t),i=PV(r),o=[];for(let a of n){let s=await e(a);if(s.columnDetailComplete!==!0)throw new Uo.SdkError("GENPAGE_DATA_SOURCE_INCOMPLETE",`${Bo}: the column metadata of data source '${a}' could not be read completely (a choice or lookup read failed, or returned options with no label), so its RuntimeTypes would lack enums a page can use. Retry.`);o.push(s)}return(0,LE.renderGenPageAuthoringTypes)(o,i)}Wc.generateGenPageRuntimeTypes=IV;function OV(e){if(!Array.isArray(e))throw new Uo.InvalidArgumentError(`${Bo}: dataSources must be an array of table logical names`);let t=new Set;for(let r of e){if(typeof r!="string"||!LE.TABLE_LOGICAL_NAME.test(r))throw new Uo.InvalidArgumentError(`${Bo}: a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(r)}'`);if(t.has(r))throw new Uo.InvalidArgumentError(`${Bo}: data source '${r}' is listed twice; a page's dataSources hold each table once`);t.add(r)}return[...t]}function PV(e){if(e===void 0)return"None";if(e===null||typeof e!="object"||Array.isArray(e))throw new Uo.InvalidArgumentError(`${Bo}: options must be an object`);let t=Object.keys(e).filter(n=>n!=="detail");if(t.length>0)throw new Uo.InvalidArgumentError(`${Bo}: unknown option '${t[0]}' (the only option is 'detail')`);let r=e.detail===void 0?"None":e.detail;if(typeof r!="string"||!kE.has(r))throw new Uo.InvalidArgumentError(`${Bo}: detail must be one of ${[...kE].map(n=>`'${n}'`).join(", ")}, got '${String(r)}'`);return r}});var qE=v(qo=>{"use strict";Object.defineProperty(qo,"__esModule",{value:!0});qo.getEnvironmentLanguages=qo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE=void 0;var RV=Q(),ME=ye();qo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE="ENVIRONMENT_LANGUAGES_UNREADABLE";var xE="/organizations?$select=languagecode",kV="/RetrieveProvisionedLanguages()",LV="/RetrieveAvailableLanguages()";function UE(e,t){return new RV.SdkError(qo.ENVIRONMENT_LANGUAGES_UNREADABLE_CODE,`The org's languages could not be read: ${e} ${t}. Nothing is assumed in its place \u2014 retry, or check the caller's access to the org.`)}function BE(e){return typeof e=="number"&&Number.isInteger(e)&&e>0}async function FE(e,t,r,n){let i=(0,ME.ensureSuccess)(await e.get(t),e.apiUrl(t)).body,o=i?.[r];if(!Array.isArray(o)||o.length===0||!o.every(BE))throw UE(n,`answered no list of language codes in '${r}'`);return[...new Set(o)]}async function $V(e){var t;let r=(0,ME.ensureSuccess)(await e.get(xE),e.apiUrl(xE)).body,n=r?.value,i=Array.isArray(n)&&n.length===1?(t=n[0])===null||t===void 0?void 0:t.languagecode:void 0;if(!BE(i))throw UE("the organization read","did not answer one row with a language code");let o=await FE(e,kV,"RetrieveProvisionedLanguages","RetrieveProvisionedLanguages"),a=await FE(e,LV,"LocaleIds","RetrieveAvailableLanguages");return{baseLanguage:i,available:a,provisioned:o}}qo.getEnvironmentLanguages=$V});var Tl=v(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.projectConnectorOperationSchema=it.projectConnectorOperations=it.validateConnectorSwagger=it.CONNECTOR_SCHEMA_TOO_LARGE_CODE=it.CONNECTOR_OPERATION_NOT_FOUND_CODE=it.CONNECTOR_SWAGGER_UNSUPPORTED_CODE=it.CONNECTIVITY_RESPONSE_UNREADABLE_CODE=void 0;var _l=Q();it.CONNECTIVITY_RESPONSE_UNREADABLE_CODE="CONNECTIVITY_RESPONSE_UNREADABLE";it.CONNECTOR_SWAGGER_UNSUPPORTED_CODE="CONNECTOR_SWAGGER_UNSUPPORTED";it.CONNECTOR_OPERATION_NOT_FOUND_CODE="CONNECTOR_OPERATION_NOT_FOUND";it.CONNECTOR_SCHEMA_TOO_LARGE_CODE="CONNECTOR_SCHEMA_TOO_LARGE";var VE=64,GE=128,WE=2e5,zE=4e6,xV=new Set(["get","put","post","delete","patch","head","options"]),FV=new Set(["query","header","path","formData","body"]);function Zr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function wn(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function At(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Ze(e){return e.length>80?`'${e.slice(0,80)}\u2026'`:`'${e}'`}function Le(e,t){return new _l.SdkError(it.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`The connector's swagger could not be read: ${e} ${t}. Nothing was skipped or assumed in its place.`)}function eo(e,t){return new _l.SdkError(it.CONNECTOR_SWAGGER_UNSUPPORTED_CODE,`The connector's swagger is outside the supported contract (Swagger 2.0 as the Power Apps API serves it): ${e} ${t}.`)}function MV(e,t){let r=e;for(let n of t.slice(2).split("/")){let i=n.replace(/~1/g,"/").replace(/~0/g,"~");if(typeof r!="object"||r===null||!wn(r,i))return{found:!1};r=r[i]}return{found:!0,value:r}}function oh(e,t,r){if(!t.startsWith("#/"))throw eo(r,`has a $ref that is not a local '#/\u2026' pointer (${Ze(t)})`);if(t.includes("%"))throw eo(r,`has a $ref with a percent-encoded character (${Ze(t)}), which is not decoded`);if(/~(?![01])/.test(t))throw Le(r,`has a $ref with a malformed escape (${Ze(t)}): a '~' not followed by 0 or 1`);let n=MV(e,t);if(!n.found)throw Le(r,`has a $ref that does not resolve (${Ze(t)})`);return n.value}function zc(e,t){if(wn(e,"$ref")){if(typeof e.$ref!="string")throw Le(t,`has a $ref that is ${At(e.$ref)}, not a string`);return e.$ref}}function UV(e,t,r){if(!Zr(t))throw Le(r,`is ${At(t)}, not a parameter object`);let n=t,i=zc(t,r);if(i!==void 0){let s=oh(e,i,r);if(!Zr(s))throw Le(r,`has a $ref (${Ze(i)}) that resolves to ${At(s)}, not a parameter object`);if(zc(s,`${r} \u2192 ${Ze(i)}`)!==void 0)throw eo(r,`has a $ref (${Ze(i)}) to a parameter that is itself a $ref`);n=s}if(typeof n.name!="string")throw Le(r,"has no string name");let o=n.in;if(typeof o!="string"||!FV.has(o))throw Le(r,`has an in that is ${typeof o=="string"?Ze(o):At(o)}, not one of query, header, path, formData or body`);if(wn(n,"required")&&typeof n.required!="boolean")throw Le(r,`has a required that is ${At(n.required)}, not a boolean`);let a=n["x-ms-visibility"];if(wn(n,"x-ms-visibility")&&typeof a!="string")throw Le(r,`has an x-ms-visibility that is ${At(a)}, not a string`);return{name:n.name,in:o,required:n.required===!0,internal:a==="internal"}}function nh(e){return`${e.in}:${e.name}`}function HE(e,t,r){if(!wn(t,"parameters"))return[];let n=t.parameters;if(!Array.isArray(n))throw Le(r,`has parameters that are ${At(n)}, not an array`);let i=new Set;return n.map((o,a)=>{let s=`${r} parameters[${a}]`,l=UV(e,o,s),u=nh(l);if(i.has(u))throw Le(s,`repeats the parameter ${Ze(l.name)} in ${Ze(l.in)}, which must be unique in its list`);return i.add(u),l})}function KE(e,t,r){let n=t.responses;if(!wn(n,"200"))return;let i=`${r} response 200`,o=n[200];if(!Zr(o))throw Le(i,`is ${At(o)}, not a response object`);let a=o,s=zc(o,i);if(s!==void 0){if(s.startsWith("#/")&&!/^#\/responses\/[^/]+$/.test(s))throw Le(i,`has a $ref (${Ze(s)}) that does not name a response ('#/responses/<name>')`);let l=oh(e,s,i);if(!Zr(l))throw Le(i,`has a $ref (${Ze(s)}) that resolves to ${At(l)}, not a response object`);if(zc(l,`${i} \u2192 ${Ze(s)}`)!==void 0)throw eo(i,`has a $ref (${Ze(s)}) to a response that is itself a $ref`);a=l}if(wn(a,"content"))throw eo(i,"is an OpenAPI 3 response (it has content), not a Swagger 2.0 one");if(wn(a,"schema")){if(!Zr(a.schema))throw Le(i,`has a schema that is ${At(a.schema)}, not an object`);return a.schema}}function jE(e,t,r){if(!wn(e,t))return;let n=e[t];if(typeof n!="string")throw Le(r,`has a ${t} that is ${At(n)}, not a string`);return n}function BV(e,t,r,n,i){if(!Zr(t))throw Le(r,`is ${At(t)}, not an operation object`);let o=t.operationId;if(typeof o!="string")throw Le(r,`has no string operationId (${At(o)})`);if(n.has(o))throw Le(r,`repeats the operationId ${Ze(o)}, which must be unique in the document`);n.add(o);let a=jE(t,"summary",r),s=jE(t,"description",r),l=HE(e,t,r);if(!Zr(t.responses))throw Le(r,`has no responses object (${At(t.responses)})`);return KE(e,t,r),{id:o,summary:a,description:s,node:t,where:r,parameters:l,pathParameters:i}}function ah(e){if(!Zr(e))throw Le("the document",`is ${At(e)}, not an object`);if(wn(e,"openapi"))throw eo("the document","is OpenAPI 3 (it has an openapi member), not Swagger 2.0");if(!wn(e,"swagger"))throw Le("the document","names no Swagger version");if(e.swagger!=="2.0")throw eo("the document",`declares swagger ${Ze(String(e.swagger))}, not 2.0`);let t=e.paths;if(!Zr(t))throw Le("the document",`has paths that are ${At(t)}, not an object`);let r=[],n=new Set;for(let i of Object.keys(t)){let o=t[i],a=`paths[${Ze(i)}]`;if(!Zr(o))throw Le(a,`is ${At(o)}, not a path item object`);let s=[];for(let l of Object.keys(o))if(xV.has(l.toLowerCase()))r.push(BV(e,o[l],`${a}.${l}`,n,s));else if(l==="parameters")for(let u of HE(e,o,a))s.push(u);else if(!l.startsWith("x-"))throw eo(a,`has a ${Ze(l)} member; a path item may hold only HTTP methods, parameters and x- extensions`)}return{document:e,operations:r}}function qV(e){ah(e)}it.validateConnectorSwagger=qV;var ih=class{constructor(t,r){this.root=t,this.where=r,this.nodes=0,this.characters=0,this.path=[]}run(t){return this.visit(t,0)}tooLarge(t){return new _l.SdkError(it.CONNECTOR_SCHEMA_TOO_LARGE_CODE,`The response schema of ${this.where} is too large to return: it has ${t}. That is far above any connector measured, so this one is not read.`)}node(){if(this.nodes+=1,this.nodes>WE)throw this.tooLarge(`more than ${WE} nodes`)}text(t){if(this.characters+=t,this.characters>zE)throw this.tooLarge(`more than ${zE} characters of strings and keys`)}checkDepth(t){if(t>GE)throw this.tooLarge(`nesting deeper than ${GE} levels`)}visit(t,r){if(this.checkDepth(r),Array.isArray(t)){this.node();let n=[];for(let i of t)n.push(this.visit(i,r+1));return n}if(Zr(t)){if(typeof t.$ref=="string")return this.reference(t.$ref,r);this.node();let n={};for(let i of Object.keys(t))this.text(i.length),Object.defineProperty(n,i,{value:this.visit(t[i],r+1),enumerable:!0,writable:!0,configurable:!0});return n}return this.node(),typeof t=="string"&&this.text(t.length),t}reference(t,r){if(this.path.includes(t)){this.checkDepth(r+1);let o=t.slice(t.lastIndexOf("/")+1);return this.node(),this.text(4),this.node(),this.text(o.length),{$ref:o}}if(this.path.length>=VE)throw this.tooLarge(`a $ref chain of more than ${VE} references`);let n=oh(this.root,t,this.where);if(!Zr(n))throw Le(this.where,`has a schema $ref (${Ze(t)}) that resolves to ${At(n)}, not a schema object`);this.path.push(t);let i=this.visit(n,r);return this.path.pop(),i}};function VV(e){let{operations:t}=ah(e);return{operations:t.map(r=>{var n,i;return{name:r.id,summary:(i=(n=r.summary)!==null&&n!==void 0?n:r.description)!==null&&i!==void 0?i:null}})}}it.projectConnectorOperations=VV;function GV(e,t){if(typeof t!="string"||t==="")throw new _l.InvalidArgumentError("operationId must be a non-empty string.");let{document:r,operations:n}=ah(e),i=n.find(u=>u.id===t);if(!i)throw new _l.SdkError(it.CONNECTOR_OPERATION_NOT_FOUND_CODE,`The connector has no operation with the id ${Ze(t)} (ids are matched exactly, case included). List the connector\u2019s operations to see its ids.`);let o=new Set(i.parameters.map(nh)),a=[...i.parameters,...i.pathParameters.filter(u=>!o.has(nh(u)))].filter(u=>!u.internal).map(({name:u,required:c})=>({name:u,required:c})),s=KE(r,i.node,i.where),l=s===void 0?{}:new ih(r,`${i.where} (${Ze(i.id)})`).run(s);return{operation:i.id,parameters:a,response:l}}it.projectConnectorOperationSchema=GV});var Vo=v(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.readEnvironmentName=J.readConnection=J.connectorShortName=J.CONNECTOR_PREFIX=J.connectivityUnauthorized=J.errorCodeOf=J.messageOf=J.environmentFilter=J.unreadable=J.connectivityCloudOf=J.sameOrigin=J.parseUrl=J.bounded=J.kindOf=J.isObject=J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE=J.CONNECTOR_NOT_TABULAR_CODE=J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=J.CONNECTIVITY_UNAUTHORIZED_CODE=J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=J.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var Dl=Q(),WV=ye(),zV=Tl();J.CONNECTIVITY_NOT_CONFIGURED_CODE="CONNECTIVITY_NOT_CONFIGURED";J.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE="CONNECTIVITY_CLOUD_UNSUPPORTED";J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE="CONNECTIVITY_ENVIRONMENT_UNVERIFIED";J.CONNECTIVITY_UNAUTHORIZED_CODE="CONNECTIVITY_UNAUTHORIZED";J.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE="CONNECTIVITY_ROUTE_DECOMMISSIONED";J.CONNECTOR_NOT_TABULAR_CODE="CONNECTOR_NOT_TABULAR";J.CONNECTOR_RUNTIME_UNSUPPORTED_CODE="CONNECTOR_RUNTIME_UNSUPPORTED";function wr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}J.isObject=wr;function Ga(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}J.kindOf=Ga;function Wa(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}J.bounded=Wa;function YE(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}J.parseUrl=YE;function jV(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}J.sameOrigin=jV;var HV=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,KV=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/;function JV(e){let t=YE(e),r=t?t.host.toLowerCase():"";if(KV.test(r))return"Test";let n=HV.exec(r);return n&&n[1]!=="9"?"Public":"Unsupported"}J.connectivityCloudOf=JV;function Gn(e,t){return new Dl.SdkError(zV.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}J.unreadable=Gn;function YV(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}J.environmentFilter=YV;function QV(e){if(typeof e=="string"&&e.length>0)return Wa(e,500);if(wr(e)){let t=wr(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Wa(r,500)}return"request failed"}J.messageOf=QV;function QE(e){return wr(e)&&wr(e.error)?e.error.code:void 0}J.errorCodeOf=QE;function XV(e){if(wr(e)&&wr(e.error)&&wr(e.error.innererror))return e.error.innererror.code}function ZV(e,t,r){let n=[],i=QE(t);typeof i=="string"&&i.length>0&&n.push(Wa(i,80));let o=XV(t);typeof o=="string"&&o.length>0&&n.push(Wa(o,80));let a=n.length>0?` (${n.join("; ")})`:"";return(0,Dl.attachCause)(new Dl.SdkError(J.CONNECTIVITY_UNAUTHORIZED_CODE,`A connectivity request was refused with HTTP ${e}${a}: the token's audience, scopes, expiry, or access was rejected. Supply a valid token for this route, or fall back to pac.`),r)}J.connectivityUnauthorized=ZV;J.CONNECTOR_PREFIX="/providers/Microsoft.PowerApps/apis/";var e4=/^[A-Za-z0-9_.-]{1,128}$/,t4=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]);function r4(e){if(typeof e=="string"){let r=e.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()===J.CONNECTOR_PREFIX.toLowerCase()?e.slice(J.CONNECTOR_PREFIX.length):e;if(e4.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new Dl.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${J.CONNECTOR_PREFIX}shared_office365users'); got ${typeof e=="string"?`'${Wa(e,80)}'`:Ga(e)}.`)}J.connectorShortName=r4;function n4(e,t,r){let n=`Connection row ${t}`;if(!wr(e))throw Gn(n,`it is ${Ga(e)}, not an object`);let i=e.properties;if(!wr(i))throw Gn(n,`its properties are ${Ga(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,J.CONNECTOR_PREFIX.length).toLowerCase()!==J.CONNECTOR_PREFIX.toLowerCase())throw Gn(n,`its apiId is not '${J.CONNECTOR_PREFIX}<connector>'`);let a=o.slice(J.CONNECTOR_PREFIX.length);if(a===""||a.includes("/"))throw Gn(n,"its apiId names no single connector");if(t4.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw Gn(n,"it has no name");let l=i.environment,u=wr(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw Gn(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw Gn(n,`its displayName is ${Ga(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw Gn(n,`its statuses are ${Ga(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=wr(f)?f.status:void 0;if(typeof m!="string")throw Gn(n,"one of its statuses has no string status");return m})}}J.readConnection=n4;var JE="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'";async function i4(e){let t=(0,WV.ensureSuccess)(await e.get(JE),e.apiUrl(JE)).body,r=wr(t)?t.Detail:void 0,n=wr(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw new Dl.SdkError(J.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,"The environment of this org could not be verified: the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId).");return n}J.readEnvironmentName=i4});var iA=v(Cr=>{"use strict";Object.defineProperty(Cr,"__esModule",{value:!0});Cr.ConnectivityApi=Cr.CONNECTIVITY_UNAUTHORIZED_CODE=Cr.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE=Cr.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE=Cr.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE=Cr.CONNECTIVITY_NOT_CONFIGURED_CODE=void 0;var zt=Q(),o4=ye(),Hc=Tl(),Ol=Vo(),Pl=Vo();Object.defineProperty(Cr,"CONNECTIVITY_NOT_CONFIGURED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_NOT_CONFIGURED_CODE}});Object.defineProperty(Cr,"CONNECTIVITY_CLOUD_UNSUPPORTED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE}});Object.defineProperty(Cr,"CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE}});Object.defineProperty(Cr,"CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE}});Object.defineProperty(Cr,"CONNECTIVITY_UNAUTHORIZED_CODE",{enumerable:!0,get:function(){return Pl.CONNECTIVITY_UNAUTHORIZED_CODE}});var XE="2016-11-01",a4="2021-04-01",s4="https://api.bap.microsoft.com",l4="https://test.api.bap.microsoft.com",u4=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,c4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,ZE="/RetrieveCurrentOrganization(AccessType=@p1)?@p1=Microsoft.Dynamics.CRM.EndpointAccessType'Default'",vi="/providers/Microsoft.PowerApps/apis/",d4=/^[A-Za-z0-9_.-]{1,128}$/,f4=new Set(["shared_logicflows","shared_powerflows","shared_pqogenericconnector"]),p4="ServiceDecommissioned";function ft(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function to(e){return e===void 0?"absent":e===null?"null":Array.isArray(e)?"an array":`a ${typeof e}`}function Wn(e,t=200){return e.length>t?`${e.slice(0,t)}\u2026`:e}function Il(e){try{let t=new URL(e);return{protocol:t.protocol,host:t.host,origin:t.origin}}catch{return}}function eA(e,t){return e.protocol===t.protocol&&e.host.toLowerCase()===t.host.toLowerCase()}function m4(e){return/^[a-z0-9][a-z0-9.-]*$/.test(e)&&(e==="api.powerapps.com"||e.endsWith(".api.powerapps.com"))}function en(e,t){return new zt.SdkError(Hc.CONNECTIVITY_RESPONSE_UNREADABLE_CODE,`${e} could not be read: ${t}. Nothing was skipped or assumed in its place.`)}function jc(e){return new zt.SdkError(Ol.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: ${e}. The Power Apps service was not asked about it.`)}function tA(e){return encodeURIComponent(`environment eq '${e.replace(/'/g,"''")}'`)}function rA(e){if(typeof e=="string"&&e.length>0)return Wn(e,500);if(ft(e)){let t=ft(e.error)?e.error.message:void 0;for(let r of[t,e.Message,e.message])if(typeof r=="string")return Wn(r,500)}return"request failed"}function h4(e){return ft(e)&&ft(e.error)?e.error.code:void 0}function nA(e){if(typeof e=="string"){let r=e.slice(0,vi.length).toLowerCase()===vi.toLowerCase()?e.slice(vi.length):e;if(d4.test(r)&&!/^\.{1,2}$/.test(r))return r}throw new zt.InvalidArgumentError(`connector must be a connector's short name ('shared_office365users') or its full API id ('${vi}shared_office365users'); got ${typeof e=="string"?`'${Wn(e,80)}'`:to(e)}.`)}function g4(e,t,r){let n=`Connection row ${t}`;if(!ft(e))throw en(n,`it is ${to(e)}, not an object`);let i=e.properties;if(!ft(i))throw en(n,`its properties are ${to(i)}, not an object`);let o=i.apiId;if(typeof o!="string"||o.slice(0,vi.length).toLowerCase()!==vi.toLowerCase())throw en(n,`its apiId is not '${vi}<connector>'`);let a=o.slice(vi.length);if(a===""||a.includes("/"))throw en(n,"its apiId names no single connector");if(f4.has(a.toLowerCase()))return;let s=e.name;if(typeof s!="string"||s==="")throw en(n,"it has no name");let l=i.environment,u=ft(l)?l.name:void 0;if(typeof u!="string"||u.toLowerCase()!==r.toLowerCase())throw en(n,"it is not a connection of this environment (properties.environment.name)");let c=i.displayName;if(typeof c!="string")throw en(n,`its displayName is ${to(c)}, not a string`);let d=i.statuses;if(!Array.isArray(d))throw en(n,`its statuses are ${to(d)}, not an array`);return{connectionId:s,displayName:c,connectorId:o,connectorName:a,statuses:d.map(f=>{let m=ft(f)?f.status:void 0;if(typeof m!="string")throw en(n,"one of its statuses has no string status");return m})}}var sh=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.service=n,this.swaggers=new Map}async listConnections(){let t=this.requireService(),r=await this.resolveEnvironment(t),n=[],i=new Set,o=`${r.origin}/providers/Microsoft.PowerApps/connections?api-version=${XE}&$filter=${tA(r.id)}`,a=await this.send(t,o,!0),s=1,l=0;for(;;){let u=`Page ${s} of the connections`,c=a.body,d=c?.value;if(!Array.isArray(d))throw en(u,`its value is ${to(d)}, not an array`);for(let m of d){let p=g4(m,l,r.id);l+=1,p&&n.push(p)}let f=c?.nextLink;if(f==null)return n;if(typeof f!="string"||f.length===0)throw en(u,`its nextLink is ${f===""?"an empty string":to(f)}, not a non-empty string`);if(i.has(f))throw new zt.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${Wn(f)}'), which would loop indefinitely.`);i.add(f),this.assertSameOrigin(f,r.parsed),a=await this.send(t,f,!0),s+=1}}async listConnectorOperations(t){let r=this.requireService(),n=nA(t);return(0,Hc.projectConnectorOperations)(await this.swagger(r,n))}async getConnectorOperationSchema(t,r){let n=this.requireService(),i=nA(t);if(typeof r!="string"||r==="")throw new zt.InvalidArgumentError("operationId must be a non-empty string.");return(0,Hc.projectConnectorOperationSchema)(await this.swagger(n,i),r)}requireService(){if(!this.service)throw new zt.SdkError(Ol.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a powerAppsServiceClient (MakerSdkOptions), so it cannot read connections or connectors: it needs an HttpClient that authenticates for https://service.powerapps.com/ and does not follow redirects. Nothing was requested.");return this.service}resolveEnvironment(t){if(!this.environment){let r=this.verifyEnvironment(t);this.environment=r,r.catch(()=>{this.environment===r&&(this.environment=void 0)})}return this.environment}async verifyEnvironment(t){let r=this.candidateBapOrigin(),n=await this.readEnvironmentId(),i=`${r}/providers/Microsoft.BusinessAppPlatform/environments/${encodeURIComponent(n)}?api-version=${a4}`,o=(await this.send(t,i,!1)).body,a=ft(o)?o.properties:void 0,s=ft(o)?o.name:void 0;if(typeof s!="string"||s.toLowerCase()!==n.toLowerCase())throw jc(`BAP's environment row is not the one named '${Wn(n,80)}' (its name)`);let l=ft(a)&&ft(a.linkedEnvironmentMetadata)?a.linkedEnvironmentMetadata.instanceUrl:void 0,u=typeof l=="string"?Il(l):void 0,c=Il(this.instanceUrl);if(!u||!c||!eA(u,c))throw jc("BAP's row is not linked to this org (its linkedEnvironmentMetadata.instanceUrl is another origin)");let d=ft(a)?a.runtimeEndpoints:void 0,f=ft(d)?d["microsoft.PowerApps"]:void 0,m=typeof f=="string"?Il(f):void 0;if(!m||m.protocol!=="https:"||!m4(m.host.toLowerCase()))throw jc("BAP's Power Apps runtime endpoint is not an https host of api.powerapps.com (runtimeEndpoints['microsoft.PowerApps'])");return{id:n,origin:m.origin.toLowerCase(),parsed:m}}candidateBapOrigin(){let t=Il(this.instanceUrl),r=t?t.host.toLowerCase():"",n=u4.exec(r);if(n&&n[1]!=="9")return s4;if(c4.test(r))return l4;throw new zt.SdkError(Ol.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The org's host is not one of the clouds this reads in (${t?`'${Wn(t.host,80)}'`:`'${Wn(this.instanceUrl,80)}', which is not a URL`}): a Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are not supported. Nothing was requested.`)}async readEnvironmentId(){let t=(0,o4.ensureSuccess)(await this.org.get(ZE),this.org.apiUrl(ZE)).body,r=ft(t)?t.Detail:void 0,n=ft(r)?r.EnvironmentId:void 0;if(typeof n!="string"||n==="")throw jc("the org answered no environment id (RetrieveCurrentOrganization, Detail.EnvironmentId)");return n}swagger(t,r){let n=r.toLowerCase(),i=this.swaggers.get(n);if(!i){let o=this.readSwagger(t,r);i=o,this.swaggers.set(n,o),o.catch(()=>{this.swaggers.get(n)===o&&this.swaggers.delete(n)})}return i}async readSwagger(t,r){let n=await this.resolveEnvironment(t),i=encodeURIComponent(r),o=`${n.origin}${vi}${i}?api-version=${XE}&$filter=${tA(n.id)}`,a=(await this.send(t,o,!0)).body,s=ft(a)?a.properties:void 0,l=ft(s)?s.swagger:void 0;if(!ft(l))throw en(`The connector '${Wn(r,80)}'`,`its properties.swagger is ${to(l)}, not an object`);return(0,Hc.validateConnectorSwagger)(l),l}assertSameOrigin(t,r){let n=Il(t);if(!n)throw new zt.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${Wn(t)}'`);if(!eA(n,r))throw new zt.InvalidArgumentError(`Refusing to follow a cross-origin link ('${Wn(n.origin,120)}' is not the environment's Power Apps endpoint '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n){let i;try{i=await t.get(r)}catch(o){throw o instanceof zt.ConnectionError&&typeof o.statusCode=="number"&&o.statusCode>0?this.mapNon2xx(r,o.statusCode,void 0,n,o):o instanceof zt.SdkError?o:new zt.ConnectionError(r,0,o instanceof Error?o.message:String(o),o)}if(!i||typeof i.status!="number")throw new zt.ConnectionError(r,0,"the transport returned no HTTP response");if(i.status>=200&&i.status<300)return i;throw this.mapNon2xx(r,i.status,i.body,n)}mapNon2xx(t,r,n,i,o){let a=o??new zt.ConnectionError(t,r,rA(n),n);return i&&r===410&&h4(n)===p4?(0,zt.attachCause)(new zt.SdkError(Ol.CONNECTIVITY_ROUTE_DECOMMISSIONED_CODE,`The Power Apps API this reads through is decommissioned for this environment: ${rA(n)} Fall back to pac, or to the Power Platform API when the host has a client for it; the SDK does not fall back.`),a):r===401||r===403?(0,Ol.connectivityUnauthorized)(r,n,a):a}};Cr.ConnectivityApi=sh});var fh=v(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.projectConnectorTableSchema=Me.projectConnectorTables=Me.tableSchemaSuffix=Me.tablesSuffix=Me.encodeTable=Me.encodeDataset=Me.checkTabularConnection=Me.runtimeAuthority=Me.tabularRevision=Me.checkTableSchemaArguments=Me.checkListTablesArguments=void 0;var Go=Q(),M=Vo(),y4=/^[A-Za-z0-9_.-]{1,128}$/,Wo=/^\.{1,2}$/,b4="shared_sharepointonline",v4=/^[0-9]{1,9}$/,w4=/^[A-Za-z0-9._~-]+$/,C4=/^\/apim\/([A-Za-z0-9._-]+)\/?$/,E4=/^\/connectors\/runtime\/invoke\/scalegroups\/([A-Za-z0-9._-]+)\/(scaleunits|shards)\/([A-Za-z0-9._-]+)\/apis\/([A-Za-z0-9._-]+)\/connections\/?$/,A4=/^[A-Za-z0-9._~!'()*-]$/,S4=/^[0-9A-Fa-f]{2}$/;function wi(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Rl(e){return typeof e=="string"?`'${(0,M.bounded)(e,80)}'`:(0,M.kindOf)(e)}function lh(e,t){return new Go.SdkError(M.CONNECTOR_NOT_TABULAR_CODE,`The connector '${(0,M.bounded)(e,80)}' has no tables: ${t}.`)}function Kc(e,t){return new Go.SdkError(M.CONNECTOR_RUNTIME_UNSUPPORTED_CODE,`The connector '${(0,M.bounded)(e,80)}' runs where this SDK does not send a token: ${t}. Nothing was sent to it.`)}function N4(e){if(typeof e=="string"&&y4.test(e)&&!Wo.test(e))return e;throw new Go.InvalidArgumentError(`connectionId must be a connection's name (letters, digits, '_', '.', '-'; at most 128; not '.' or '..'); got ${Rl(e)}.`)}function _4(e){if(e!=null){if(typeof e=="string"&&e!==""&&e.split(",").find(r=>r===""||Wo.test(r))===void 0)return e;throw new Go.InvalidArgumentError(`dataset must be a non-empty string (a SharePoint site URL, a SQL 'server,database', \u2026) none of whose ','-separated parts is empty, '.' or '..', or absent for a connector without datasets; got ${Rl(e)}.`)}}function T4(e){if(typeof e=="string"&&e!==""&&!Wo.test(e))return e;throw new Go.InvalidArgumentError(`table must be a non-empty string other than '.' and '..'; got ${Rl(e)}.`)}function aA(e,t,r){return{short:(0,M.connectorShortName)(e),connectionId:N4(t),dataset:_4(r)}}Me.checkListTablesArguments=aA;function D4(e,t,r,n){return{...aA(e,t,r),table:T4(n)}}Me.checkTableSchemaArguments=D4;function I4(e,t){let r=`The connector '${(0,M.bounded)(t,80)}'`,n=e.properties;if(!(0,M.isObject)(n))throw(0,M.unreadable)(r,`its properties are ${(0,M.kindOf)(n)}, not an object`);if(!wi(n,"interfaces"))throw lh(t,"it declares no interfaces");let i=n.interfaces;if(!(0,M.isObject)(i))throw(0,M.unreadable)(r,`its properties.interfaces are ${(0,M.kindOf)(i)}, not an object`);if(!wi(i,"CDPTabular1"))throw lh(t,"it declares no CDPTabular1 interface");let o=i.CDPTabular1;if(!(0,M.isObject)(o))throw(0,M.unreadable)(r,`its CDPTabular1 interface is ${(0,M.kindOf)(o)}, not an object`);let a=o.revisions;if(!(0,M.isObject)(a))throw(0,M.unreadable)(r,`its CDPTabular1 revisions are ${(0,M.kindOf)(a)}, not an object`);let s,l=new Map;for(let u of Object.keys(a)){let c=a[u],d=`its CDPTabular1 revision '${(0,M.bounded)(u,40)}'`;if(!(0,M.isObject)(c)||typeof c.status!="string")throw(0,M.unreadable)(r,`${d} is not an object with a string status`);if(c.status!=="Production")continue;if(!v4.test(u))throw(0,M.unreadable)(r,`${d} is a Production revision whose key is not a decimal integer of 1\u20139 digits`);let f=O4(c.baseUrl);if(f===void 0)throw(0,M.unreadable)(r,`${d} has a baseUrl that is not '/' or '/'-separated [A-Za-z0-9._~-] segments`);let m=Number(u),p=l.get(m);if(p!==void 0)throw(0,M.unreadable)(r,`its Production revisions '${p}' and '${(0,M.bounded)(u,40)}' have the same number`);l.set(m,u),(!s||m>s.revisionNumber)&&(s={revisionNumber:m,revision:f})}if(!s)throw lh(t,"its CDPTabular1 interface has no Production revision");return s.revision}Me.tabularRevision=I4;function O4(e){if(typeof e!="string")return;let t=e.replace(/^\/+/,"").replace(/\/+$/,"");return t===""?"":t.split("/").every(i=>w4.test(i)&&!Wo.test(i))?t:void 0}function P4(e,t,r){let n=(0,M.isObject)(e.properties)?e.properties:void 0,i=n?n.primaryRuntimeUrl:void 0;if(typeof i!="string")throw Kc(r,`its primaryRuntimeUrl is ${(0,M.kindOf)(i)}, not a string`);let o=t.cloud==="Test",a=(o?`https://${t.name}.tip2-001.tip2.azure-apihub.net`:t.origin).toLowerCase(),s=(0,M.parseUrl)(i);if(!s||s.protocol!=="https:"||s.origin.toLowerCase()!==a)throw Kc(r,`its runtime ('${(0,M.bounded)(i,120)}') is not ${o?"this environment's measured API Hub host (<environment name>.tip2-001.tip2.azure-apihub.net)":"under this environment's own Power Platform API origin"} over https`);let l=i.slice(0,a.length).toLowerCase()===a?i.slice(a.length):void 0;if(o){let c=l===void 0?null:C4.exec(l);if(!c||Wo.test(c[1]))throw Kc(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <host>/apim/<connector>`);return{transport:"invoke",origin:a,path:`/apim/${c[1]}`}}let u=l===void 0?null:E4.exec(l);if(!u||[u[1],u[3],u[4]].some(c=>Wo.test(c)))throw Kc(r,`its runtime ('${(0,M.bounded)(i,120)}') is not <origin>/connectors/runtime/invoke/scalegroups/<group>/(scaleunits|shards)/<unit>/apis/<api>/connections`);return{transport:"direct",origin:a,path:`/connectors/runtime/invoke/scalegroups/${u[1]}/${u[2]}/${u[3]}/apis/${u[4]}/connections`}}Me.runtimeAuthority=P4;function R4(e,t,r,n){let i=`The connection '${(0,M.bounded)(t,128)}'`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(i,`it is ${(0,M.kindOf)(e)}, not an object`);if(e.name!==t)throw(0,M.unreadable)(i,`its name is ${Rl(e.name)}, not the requested connection`);let o=e.properties;if(!(0,M.isObject)(o))throw(0,M.unreadable)(i,`its properties are ${(0,M.kindOf)(o)}, not an object`);let a=o.apiId;if(typeof a!="string"||a.toLowerCase()!==`${M.CONNECTOR_PREFIX}${r}`.toLowerCase())throw(0,M.unreadable)(i,`its apiId is ${Rl(a)}, not the connector '${(0,M.bounded)(r,80)}'`);let s=o.environment,l=(0,M.isObject)(s)?s.name:void 0;if(typeof l!="string"||l.toLowerCase()!==n.toLowerCase())throw(0,M.unreadable)(i,"it is not a connection of this environment (properties.environment.name)");return t}Me.checkTabularConnection=R4;function oA(e){return encodeURIComponent(e).replace(/[!'()*]/g,t=>`%${t.charCodeAt(0).toString(16).toUpperCase()}`)}function k4(e){if(e==="")return!1;for(let t=0;t<e.length;t+=1)if(e[t]==="%"){if(!S4.test(e.slice(t+1,t+3)))return!1;t+=2}else if(!A4.test(e[t]))return!1;return!0}function sA(e,t){let r,n,i;try{r=oA(e),n=oA(r),i=decodeURIComponent(n)}catch{throw new Go.InvalidArgumentError(`${t} is not well-formed Unicode (it has a lone surrogate), so it cannot be sent.`)}if(!k4(n)||Wo.test(n)||i!==r)throw new Go.InvalidArgumentError(`${t} cannot be sent as one path segment.`);return n}function dh(e){return e.split(",").map((t,r)=>sA(t,`dataset part ${r}`)).join(",")}Me.encodeDataset=dh;function lA(e){return sA(e,"table")}Me.encodeTable=lA;function L4(e,t){if(t===void 0)return"/tables";let r=e.toLowerCase()===b4?"allTables":"tables";return`/datasets/${dh(t)}/${r}`}Me.tablesSuffix=L4;function $4(e,t){return`/$metadata.json${e===void 0?"":`/datasets/${dh(e)}`}/tables/${lA(t)}`}Me.tableSchemaSuffix=$4;function za(e,t){let r=t.toLowerCase();for(let n of Object.keys(e))if(n.toLowerCase()===r)return{found:!0,value:e[n]};return{found:!1}}function x4(e){let t="The table list",r;if(Array.isArray(e))r=e;else if((0,M.isObject)(e)){for(let o of["nextLink","@odata.nextLink"])if(za(e,o).found)throw(0,M.unreadable)(t,`it carries a ${o} \u2014 a paged answer is refused, never read as a partial list`);let n=za(e,"value"),i=n.found?n:za(e,"tables");if(!i.found)throw(0,M.unreadable)(t,"it is an object with neither a value nor a tables member");if(!Array.isArray(i.value))throw(0,M.unreadable)(t,`its ${n.found?"value":"tables"} is ${(0,M.kindOf)(i.value)}, not an array`);r=i.value}else throw(0,M.unreadable)(t,`it is ${(0,M.kindOf)(e)}, not an array or an object`);return{tables:r.map((n,i)=>F4(n,i))}}Me.projectConnectorTables=x4;function F4(e,t){let r=`Table row ${t}`;if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=za(e,"name");if(!n.found||typeof n.value!="string"||n.value==="")throw(0,M.unreadable)(r,"it has no non-empty string name");let i=za(e,"displayName");if(i.found&&typeof i.value!="string")throw(0,M.unreadable)(r,`its displayName is ${(0,M.kindOf)(i.value)}, not a string`);let o=za(e,"id");if(o.found&&(typeof o.value!="string"||o.value===""))throw(0,M.unreadable)(r,`its id is ${o.value===""?"an empty string":(0,M.kindOf)(o.value)}, not a non-empty string`);return{name:n.value,displayName:i.found?i.value:null,id:o.found?o.value:n.value}}function uh(e,t,r){if(!wi(e,t))return;let n=e[t];if(!(0,M.isObject)(n))throw(0,M.unreadable)("The table schema",`its ${r} is ${(0,M.kindOf)(n)}, not an object`);return n}function ch(e,t,r){if(!wi(e,t))return;let n=e[t];if(typeof n!="string")throw(0,M.unreadable)(r,`its ${t} is ${(0,M.kindOf)(n)}, not a string`);return n}function M4(e,t){var r,n;if(wi(e,"$ref"))throw(0,M.unreadable)(t,"it is a $ref, whose type is not guessed");let i=ch(e,"type",t),o=ch(e,"format",t),a=(r=i??o)!==null&&r!==void 0?r:"object";if(!wi(e,"items"))return a;let s=e.items;if(!(0,M.isObject)(s))throw(0,M.unreadable)(t,`its items are ${(0,M.kindOf)(s)}, not an object`);if(wi(s,"$ref"))throw(0,M.unreadable)(t,"its items are a $ref, whose type is not guessed");return`${a}<${(n=ch(s,"type",`${t} items`))!==null&&n!==void 0?n:"object"}>`}function U4(e,t){let r="The table schema";if(!(0,M.isObject)(e))throw(0,M.unreadable)(r,`it is ${(0,M.kindOf)(e)}, not an object`);let n=uh(e,"items","items"),i=uh(e,"schema","schema"),o=i?uh(i,"items","schema.items"):void 0,a=[[e,"the answer"],[n,"items"],[i,"schema"],[o,"schema.items"]],s=new Set;for(let[c,d]of a)if(c&&wi(c,"required")){let f=c.required;if(!Array.isArray(f))throw(0,M.unreadable)(r,`the required of ${d} is ${(0,M.kindOf)(f)}, not an array`);f.forEach(m=>{if(typeof m!="string")throw(0,M.unreadable)(r,`the required of ${d} has an entry that is ${(0,M.kindOf)(m)}, not a string`);s.add(m.toLowerCase())})}let l;for(let[c,d]of a)if(c&&wi(c,"properties")){if(!(0,M.isObject)(c.properties))throw(0,M.unreadable)(r,`the properties of ${d} are ${(0,M.kindOf)(c.properties)}, not an object`);l=c.properties;break}if(!l)throw(0,M.unreadable)(r,"it has no properties, items.properties, schema.properties or schema.items.properties");let u=Object.keys(l).map(c=>{let d=`Column '${(0,M.bounded)(c,80)}'`,f=l[c];if(!(0,M.isObject)(f))throw(0,M.unreadable)(d,`it is ${(0,M.kindOf)(f)}, not an object`);return{name:c,type:M4(f,d),required:s.has(c.toLowerCase())}});return{table:t,columns:u}}Me.projectConnectorTableSchema=U4});var uA=v(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.PowerPlatformApiDiscovery=void 0;var ph=class{constructor(t){this.clusterCategory=t}getTokenAudience(){return`https://${this._getEnvironmentApiHostNameSuffix()}`}getTokenEndpointHost(){return this._getEnvironmentApiHostNameSuffix()}getTenantEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant")}getTenantIslandClusterEndpoint(t){return this._generatePowerPlatformApiDomain(t,"tenant","il-")}getEnvironmentEndpoint(t){return this._generatePowerPlatformApiDomain(t,"environment")}_generatePowerPlatformApiDomain(t,r,n=""){if(!/^[a-zA-Z0-9\-]+$/g.test(t))throw new Error(`Cannot generate Power Platform API endpoint because the ${r} identifier contains invalid host name characters, only alphanumeric and dash characters are expected: ${t}`);let i=this._getHexApiSuffixLength(),o=t.toLowerCase().replace(/-/g,"");if(i>=o.length)throw new Error(`Cannot generate Power Platform API endpoint because the normalized ${r} identifier must be at least ${i+1} characters in length: ${o}`);let a=o.substring(o.length-i),s=o.substring(0,o.length-i),l=this._getEnvironmentApiHostNameSuffix();return`${n}${s}.${a}.${r}.${l}`}_getHexApiSuffixLength(){switch(this.clusterCategory){case"firstrelease":case"prod":return 2;default:return 1}}_getEnvironmentApiHostNameSuffix(){switch(this.clusterCategory){case"local":return"api.powerplatform.localhost";case"dev":return"api.dev.powerplatform.com";case"test":return"api.test.powerplatform.com";case"preprod":return"api.preprod.powerplatform.com";case"firstrelease":case"prod":return"api.powerplatform.com";case"gov":return"api.gov.powerplatform.microsoft.us";case"high":return"api.high.powerplatform.microsoft.us";case"dod":return"api.appsplatform.us";case"mooncake":return"api.powerplatform.partner.microsoftonline.cn";case"ex":return"api.powerplatform.eaglex.ic.gov";case"rx":return"api.powerplatform.microsoft.scloud";default:throw new Error(`Invalid ClusterCategory value: ${this.clusterCategory}`)}}};Jc.PowerPlatformApiDiscovery=ph});var cA=v(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});Yc.PowerPlatformApiDiscovery=void 0;var B4=uA();Object.defineProperty(Yc,"PowerPlatformApiDiscovery",{enumerable:!0,get:function(){return B4.PowerPlatformApiDiscovery}})});var mA=v(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.platformTokenAudience=ro.platformEnvironment=ro.platformClusterOf=void 0;var dA=cA(),fA=Q(),pA=Vo(),q4=/^[a-z0-9-]+\.crm(\d*)\.dynamics\.com$/,V4=/^[a-z0-9-]+\.crmtest\.dynamics\.com$/,G4=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,W4=/^default-/i;function mh(e,t=80){return e.length>t?`${e.slice(0,t)}\u2026`:e}function z4(e){try{return new URL(e).host.toLowerCase()}catch{return}}function j4(e){let t=z4(e);if(t){if(V4.test(t))return{cloud:"Test",category:"test"};let r=q4.exec(t);if(r&&r[1]!=="9")return{cloud:"Public",category:"prod"}}throw new fA.SdkError(pA.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,`The Power Platform API route is built for the Test and Public clouds; this org (${t?`'${mh(t)}'`:`'${mh(e)}', which is not a URL`}) is another cloud. A Public org is <name>.crm[N].dynamics.com (N other than 9) and a Test org <name>.crmtest.dynamics.com. GCC (crm9), GCC High, DoD, China, ports and custom domains are pending or out of scope. Nothing was requested.`)}ro.platformClusterOf=j4;function H4(e,t){let r=W4.test(e)?e.slice(8):e;if(!G4.test(r))throw new fA.SdkError(pA.CONNECTIVITY_ENVIRONMENT_UNVERIFIED_CODE,`The environment of this org could not be verified: its name ('${mh(e)}') is neither a GUID nor 'Default-<GUID>', the forms this route is measured for. The Power Platform API was not asked about it.`);return{origin:`https://${new dA.PowerPlatformApiDiscovery(t).getEnvironmentEndpoint(e)}`,guid:r.toLowerCase()}}ro.platformEnvironment=H4;function K4(e){return new dA.PowerPlatformApiDiscovery(e).getTokenAudience()}ro.platformTokenAudience=K4});var gA=v(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.PlatformConnectivityApi=ja.assertTabularCloud=void 0;var Cn=Q(),hh=Tl(),me=Vo(),hA=mA(),Ci=fh(),gh="1";function yh(e){let t=(0,me.connectivityCloudOf)(e);if(t!=="Test"&&t!=="Public")throw new Cn.SdkError(me.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"Connector tables are read in the Test and Public clouds; this org's cloud is neither (GCC, GCC High and DoD are pending). Nothing was requested.")}ja.assertTabularCloud=yh;var bh=class{constructor(t,r,n,i){this.org=t,this.instanceUrl=r,this.client=n,this.runtime=i,this.records=new Map,this.swaggers=new Map}async listConnections(){let t=await this.resolveEnvironment(),r=[],n=new Set,i=await this.send(this.client,"GET",`${t.origin}/connectivity/connections?api-version=${gh}`,[401,403]),o=1,a=0;for(;;){let s=`Page ${o} of the connections`,l=i.body,u=l?.value;if(!Array.isArray(u))throw(0,me.unreadable)(s,`its value is ${(0,me.kindOf)(u)}, not an array`);for(let d of u){let f=(0,me.readConnection)(d,a,t.name);a+=1,f&&r.push(f)}let c=l?.nextLink;if(c==null)return r;if(typeof c!="string"||c.length===0)throw(0,me.unreadable)(s,`its nextLink is ${c===""?"an empty string":(0,me.kindOf)(c)}, not a non-empty string`);if(n.has(c))throw new Cn.InvalidArgumentError(`listConnections: aborting pagination \u2014 the server returned a repeated nextLink ('${(0,me.bounded)(c)}'), which would loop indefinitely.`);n.add(c),this.assertSameOrigin(c,t.parsed),i=await this.send(this.client,"GET",c,[401,403]),o+=1}}async listConnectorOperations(t){let r=(0,me.connectorShortName)(t);return(0,hh.projectConnectorOperations)(await this.swagger(r))}async getConnectorOperationSchema(t,r){let n=(0,me.connectorShortName)(t);if(typeof r!="string"||r==="")throw new Cn.InvalidArgumentError("operationId must be a non-empty string.");return(0,hh.projectConnectorOperationSchema)(await this.swagger(n),r)}async listConnectorTables(t,r,n){yh(this.instanceUrl);let i=(0,Ci.checkListTablesArguments)(t,r,n),o=(0,Ci.tablesSuffix)(i.short,i.dataset);return(0,Ci.projectConnectorTables)(await this.invokeTabular(i,o))}async getConnectorTableSchema(t,r,n,i){yh(this.instanceUrl);let o=(0,Ci.checkTableSchemaArguments)(t,r,n,i),a=(0,Ci.tableSchemaSuffix)(o.dataset,o.table);return(0,Ci.projectConnectorTableSchema)(await this.invokeTabular(o,a),o.table)}async invokeTabular(t,r){let n=this.requireRuntime(),i=await this.resolveEnvironment(),o=await this.record(t.short),a=(0,Ci.tabularRevision)(o,t.short),s=(0,Ci.runtimeAuthority)(o,{cloud:i.cloud,name:i.name,origin:i.origin},t.short),l=`${i.origin}/connectivity/connectors/${encodeURIComponent(t.short)}/connections/${encodeURIComponent(t.connectionId)}?$filter=${(0,me.environmentFilter)(i.name)}&api-version=${gh}`,u=(await this.send(this.client,"GET",l,[401,403])).body,c=(0,Ci.checkTabularConnection)(u,t.connectionId,t.short,i.name),d=`${s.path}/${c}${a===""?"":`/${a}`}${r}`;return(s.transport==="invoke"?await this.send(n,"POST",`${s.origin}/invoke`,[401],{"X-Ms-Request-Url":d,"X-Ms-Request-Method":"GET"}):await this.send(n,"GET",`${s.origin}${d}`,[401])).body}requireRuntime(){if(!this.runtime)throw new Cn.SdkError(me.CONNECTIVITY_NOT_CONFIGURED_CODE,"This SDK was created without a connectorRuntimeClient (MakerSdkOptions), so it cannot read connector tables: it needs an HttpClient that authenticates for API Hub (https://apihub.azure.com) and does not follow redirects. Nothing was requested.");return this.runtime}resolveEnvironment(){if(!this.environment){let t=this.readEnvironment();this.environment=t,t.catch(()=>{this.environment===t&&(this.environment=void 0)})}return this.environment}async readEnvironment(){let{cloud:t,category:r}=(0,hA.platformClusterOf)(this.instanceUrl),n=await(0,me.readEnvironmentName)(this.org),{origin:i,guid:o}=(0,hA.platformEnvironment)(n,r),a=(0,me.parseUrl)(i);if(!a)throw(0,me.unreadable)("The Power Platform API origin",`'${(0,me.bounded)(i)}' is not a URL`);return{cloud:t,origin:i,parsed:a,name:n,guid:o}}cached(t,r,n){let i=t.get(r);if(!i){let o=n();i=o,t.set(r,o),o.catch(()=>{t.get(r)===o&&t.delete(r)})}return i}record(t){return this.cached(this.records,t.toLowerCase(),()=>this.readRecord(t))}async readRecord(t){let r=await this.resolveEnvironment(),n=`${r.origin}/connectivity/connectors/${encodeURIComponent(t)}?$filter=${(0,me.environmentFilter)(r.name)}&api-version=${gh}`,i=(await this.send(this.client,"GET",n,[401,403])).body,o=(0,me.isObject)(i)?i.name:void 0;if(!(0,me.isObject)(i)||typeof o!="string"||o.toLowerCase()!==t.toLowerCase())throw(0,me.unreadable)(`The connector '${(0,me.bounded)(t,80)}'`,`the record's name is ${typeof o=="string"?`'${(0,me.bounded)(o,80)}'`:(0,me.kindOf)(o)}, not the requested connector`);return i}swagger(t){return this.cached(this.swaggers,t.toLowerCase(),async()=>{let n=(await this.record(t)).properties,i=(0,me.isObject)(n)?n.swagger:void 0;if(!(0,me.isObject)(i))throw(0,me.unreadable)(`The connector '${(0,me.bounded)(t,80)}'`,`its properties.swagger is ${(0,me.kindOf)(i)}, not an object`);return(0,hh.validateConnectorSwagger)(i),i})}assertSameOrigin(t,r){let n=(0,me.parseUrl)(t);if(!n)throw new Cn.InvalidArgumentError(`Refusing to follow a malformed absolute URL: '${(0,me.bounded)(t)}'`);if(!(0,me.sameOrigin)(n,r))throw new Cn.InvalidArgumentError(`Refusing to follow a cross-origin link ('${(0,me.bounded)(n.origin,120)}' is not the environment's Power Platform API origin '${r.origin}'); server-driven pagination must stay on that origin.`)}async send(t,r,n,i,o){let a;try{a=r==="GET"?await t.get(n):await t.post(n,void 0,{headers:o})}catch(s){throw s instanceof Cn.ConnectionError&&typeof s.statusCode=="number"&&s.statusCode>0?this.non2xx(n,s.statusCode,void 0,i,s):s instanceof Cn.SdkError?s:new Cn.ConnectionError(n,0,s instanceof Error?s.message:String(s),s)}if(!a||typeof a.status!="number")throw new Cn.ConnectionError(n,0,"the transport returned no HTTP response");if(a.status>=200&&a.status<300)return a;throw this.non2xx(n,a.status,a.body,i)}non2xx(t,r,n,i,o){let a=o??new Cn.ConnectionError(t,r,(0,me.messageOf)(n),n);return i.includes(r)?(0,me.connectivityUnauthorized)(r,n,a):a}};ja.PlatformConnectivityApi=bh});var bA=v(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});Xc.ConnectivityRouter=void 0;var vh=Q(),J4=iA(),Qc=Vo(),yA=fh(),wh=gA(),Ch=class{constructor(t,r,n){this.org=t,this.instanceUrl=r,this.clients=n}async listConnections(){return this.route().listConnections()}async listConnectorOperations(t){return this.route().listConnectorOperations(t)}async getConnectorOperationSchema(t,r){return this.route().getConnectorOperationSchema(t,r)}async listConnectorTables(t,r,n){return(0,wh.assertTabularCloud)(this.instanceUrl),(0,yA.checkListTablesArguments)(t,r,n),this.tabularRoute().listConnectorTables(t,r,n)}async getConnectorTableSchema(t,r,n,i){return(0,wh.assertTabularCloud)(this.instanceUrl),(0,yA.checkTableSchemaArguments)(t,r,n,i),this.tabularRoute().getConnectorTableSchema(t,r,n,i)}route(){return this.delegate||(this.delegate=this.select()),this.delegate}platformRoute(t){return this.platform||(this.platform=new wh.PlatformConnectivityApi(this.org,this.instanceUrl,t,this.clients.connectorRuntimeClient)),this.platform}tabularRoute(){let{powerPlatformApiClient:t,connectorRuntimeClient:r}=this.clients,n=[t?void 0:"powerPlatformApiClient (the Power Platform API)",r?void 0:"connectorRuntimeClient (API Hub, https://apihub.azure.com)"].filter(i=>i!==void 0);if(n.length>0||!t)throw new vh.SdkError(Qc.CONNECTIVITY_NOT_CONFIGURED_CODE,`Connector tables are read through the Power Platform API and the connector runtime: this SDK was created without MakerSdkOptions.${n.join(" or MakerSdkOptions.")}, an HttpClient that does not follow redirects. Nothing was requested.`);return this.platformRoute(t)}select(){let t=(0,Qc.connectivityCloudOf)(this.instanceUrl),{powerAppsServiceClient:r,powerPlatformApiClient:n}=this.clients;if(t==="Unsupported")throw new vh.SdkError(Qc.CONNECTIVITY_CLOUD_UNSUPPORTED_CODE,"This org's cloud has no connection/connector route: the Test and Public clouds are served (through the Power Platform API, or the classic route for Public); GCC, GCC High and DoD are pending. Nothing was requested.");if(n)return this.platformRoute(n);if(t==="Public"&&r)return new J4.ConnectivityApi(this.org,this.instanceUrl,r);throw new vh.SdkError(Qc.CONNECTIVITY_NOT_CONFIGURED_CODE,t==="Test"?"This org is in the Test cloud, whose connection and connector reads go through the Power Platform API: supply MakerSdkOptions.powerPlatformApiClient (an HttpClient that authenticates for the Power Platform API and does not follow redirects). Nothing was requested.":"This org is in the Public cloud: supply MakerSdkOptions.powerPlatformApiClient (the Power Platform API route) or powerAppsServiceClient (the classic route). Neither was given, so nothing was requested.")}};Xc.ConnectivityRouter=Ch});var Ha=v(Ei=>{"use strict";function Y4(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 Ah(e,t){return t===void 0&&(t=Object),t&&typeof t.freeze=="function"?t.freeze(e):e}function Q4(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 vA=Ah({HTML:"text/html",isHTML:function(e){return e===vA.HTML},XML_APPLICATION:"application/xml",XML_TEXT:"text/xml",XML_XHTML_APPLICATION:"application/xhtml+xml",XML_SVG_IMAGE:"image/svg+xml"}),wA=Ah({HTML:"http://www.w3.org/1999/xhtml",isHTML:function(e){return e===wA.HTML},SVG:"http://www.w3.org/2000/svg",XML:"http://www.w3.org/XML/1998/namespace",XMLNS:"http://www.w3.org/2000/xmlns/"}),Zc=/[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]/,Eh=new RegExp("[\\-\\.0-9"+Zc.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"),X4=new RegExp("^"+Zc.source+Eh.source+"*(?::"+Zc.source+Eh.source+"*)?$");Ei.assign=Q4;Ei.find=Y4;Ei.freeze=Ah;Ei.MIME_TYPE=vA;Ei.NAMESPACE=wA;Ei.nameStartChar=Zc;Ei.nameChar=Eh;Ei.tagNamePattern=X4});var $h=v(_i=>{var Sh=Ha(),zn=Sh.find,Ll=Sh.NAMESPACE,Ka=Sh.tagNamePattern;function Z4(e){return e!==""}function eG(e){return e?e.split(/[\t\n\f\r ]+/).filter(Z4):[]}function tG(e,t){return e.hasOwnProperty(t)||(e[t]=!0),e}function CA(e){if(!e)return[];var t=eG(e);return Object.keys(t.reduce(tG,{}))}function rG(e){return function(t){return e&&e.indexOf(t)!==-1}}function xl(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function Ar(e,t){var r=e.prototype;if(!(r instanceof t)){let i=function(){};var n=i;i.prototype=t.prototype,i=new i,xl(r,i),e.prototype=r=i}r.constructor!=e&&(typeof e!="function"&&console.error("unknown Class:"+e),r.constructor=e)}var Sr={},tn=Sr.ELEMENT_NODE=1,Ja=Sr.ATTRIBUTE_NODE=2,kl=Sr.TEXT_NODE=3,IA=Sr.CDATA_SECTION_NODE=4,OA=Sr.ENTITY_REFERENCE_NODE=5,nG=Sr.ENTITY_NODE=6,Nh=Sr.PROCESSING_INSTRUCTION_NODE=7,_h=Sr.COMMENT_NODE=8,PA=Sr.DOCUMENT_NODE=9,RA=Sr.DOCUMENT_TYPE_NODE=10,Ai=Sr.DOCUMENT_FRAGMENT_NODE=11,iG=Sr.NOTATION_NODE=12,jt={},Nt={},qse=jt.INDEX_SIZE_ERR=(Nt[1]="Index size error",1),Vse=jt.DOMSTRING_SIZE_ERR=(Nt[2]="DOMString size error",2),Er=jt.HIERARCHY_REQUEST_ERR=(Nt[3]="Hierarchy request error",3),Gse=jt.WRONG_DOCUMENT_ERR=(Nt[4]="Wrong document",4),EA=jt.INVALID_CHARACTER_ERR=(Nt[5]="Invalid character",5),Wse=jt.NO_DATA_ALLOWED_ERR=(Nt[6]="No data allowed",6),zse=jt.NO_MODIFICATION_ALLOWED_ERR=(Nt[7]="No modification allowed",7),kA=jt.NOT_FOUND_ERR=(Nt[8]="Not found",8),jse=jt.NOT_SUPPORTED_ERR=(Nt[9]="Not supported",9),AA=jt.INUSE_ATTRIBUTE_ERR=(Nt[10]="Attribute in use",10),En=jt.INVALID_STATE_ERR=(Nt[11]="Invalid state",11),Hse=jt.SYNTAX_ERR=(Nt[12]="Syntax error",12),Kse=jt.INVALID_MODIFICATION_ERR=(Nt[13]="Invalid modification",13),Jse=jt.NAMESPACE_ERR=(Nt[14]="Invalid namespace",14),Yse=jt.INVALID_ACCESS_ERR=(Nt[15]="Invalid access",15);function he(e,t){if(t instanceof Error)var r=t;else r=this,Error.call(this,Nt[e]),this.message=Nt[e],Error.captureStackTrace&&Error.captureStackTrace(this,he);return r.code=e,t&&(this.message=this.message+": "+t),r}he.prototype=Error.prototype;xl(jt,he);function Si(){}Si.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=[],o=0;o<this.length;o++)Lh(this[o],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 Ya(e,t){this._node=e,this._refresh=t,Th(this)}function Th(e){var t=e._node._inc||e._node.ownerDocument._inc;if(e._inc!==t){var r=e._refresh(e._node);if(jA(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];xl(r,e),e._inc=t}}Ya.prototype.item=function(e){return Th(this),this[e]||null};Ar(Ya,Si);function td(){this._nameIndex=Object.create(null)}function LA(e,t){for(var r=e.length;r--;)if(e[r]===t)return r}function oG(e,t){e._nameIndex[t.nodeName]=t}function $A(e,t){e._nameIndex[t.nodeName]===t&&delete e._nameIndex[t.nodeName]}function SA(e,t,r,n){if(n?(t[LA(t,n)]=r,$A(t,n)):t[t.length++]=r,oG(t,r),e){r.ownerElement=e;var i=e.ownerDocument;i&&(n&&MA(i,e,n),aG(i,e,r))}}function NA(e,t,r){var n=LA(t,r);if(n>=0){for(var i=t.length-1;n<i;)t[n]=t[++n];if(t.length=i,$A(t,r),e){var o=e.ownerDocument;o&&(MA(o,e,r),r.ownerElement=null)}}else throw new he(kA,new Error(e.tagName+"@"+r))}td.prototype={length:0,item:Si.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 he(AA);var r=this._nameIndex[e.nodeName];return SA(this._ownerElement,this,e,r),r},setNamedItemNS:function(e){var t=e.ownerElement,r;if(t&&t!=this._ownerElement)throw new he(AA);return r=this.getNamedItemNS(e.namespaceURI,e.localName),SA(this._ownerElement,this,e,r),r},removeNamedItem:function(e){var t=this.getNamedItem(e);return NA(this._ownerElement,this,t),t},removeNamedItemNS:function(e,t){var r=this.getNamedItemNS(e,t);return NA(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 xA(){}xA.prototype={hasFeature:function(e,t){return!0},createDocument:function(e,t,r){var n=new Fl;if(n.implementation=this,n.childNodes=new Si,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 ad;return n.name=e,n.nodeName=e,n.publicId=t||"",n.systemId=r||"",n}};function De(){}De.prototype={firstChild:null,lastChild:null,previousSibling:null,nextSibling:null,attributes:null,parentNode:null,childNodes:null,ownerDocument:null,nodeValue:null,namespaceURI:null,prefix:null,localName:null,insertBefore:function(e,t){return nd(this,e,t)},replaceChild:function(e,t){nd(this,e,t,BA),t&&this.removeChild(t)},removeChild:function(e){return UA(this,e)},appendChild:function(e){return this.insertBefore(e,null)},hasChildNodes:function(){return this.firstChild!=null},cloneNode:function(e){return zA(this.ownerDocument||this,this,e)},normalize:function(){St(this,null,{enter:function(e){for(var t=e.firstChild;t;){var r=t.nextSibling;if(r!==null&&r.nodeType===kl&&t.nodeType===kl){for(var n=[],i=r;i!==null&&i.nodeType===kl;)n.push(i.data),i=i.nextSibling;for(var o=t.nextSibling;o!==i;){var a=o.nextSibling;o.parentNode=null,o.previousSibling=null,o.nextSibling=null,o=a}t.nextSibling=i,i!==null?i.previousSibling=t:e.lastChild=t,t.appendData(n.join("")),od(e.ownerDocument,e),t=i}else t=r}return!0}})},isSupported:function(e,t){return this.ownerDocument.implementation.hasFeature(e,t)},hasAttributes:function(){return this.attributes.length>0},lookupPrefix:function(e){for(var t=this;t;){var r=t._nsMap;if(r){for(var n in r)if(Object.prototype.hasOwnProperty.call(r,n)&&r[n]===e)return n}t=t.nodeType==Ja?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==Ja?t.ownerDocument:t.parentNode}return null},isDefaultNamespace:function(e){var t=this.lookupPrefix(e);return t==null}};function FA(e){return e=="<"&&"&lt;"||e==">"&&"&gt;"||e=="&"&&"&amp;"||e=='"'&&"&quot;"||"&#"+e.charCodeAt()+";"}xl(Sr,De);xl(Sr,De.prototype);function rd(e,t){return St(e,null,{enter:function(r){return t(r)?St.STOP:!0}})===St.STOP}function St(e,t,r){for(var n=[{node:e,context:t,phase:St.ENTER}];n.length>0;){var i=n.pop();if(i.phase===St.ENTER){var o=r.enter(i.node,i.context);if(o===St.STOP)return St.STOP;if(n.push({node:i.node,context:o,phase:St.EXIT}),o==null)continue;for(var a=i.node.lastChild;a;)n.push({node:a,context:o,phase:St.ENTER}),a=a.previousSibling}else r.exit&&r.exit(i.node,i.context)}}St.STOP=Symbol("walkDOM.STOP");St.ENTER=0;St.EXIT=1;function Fl(){this.ownerDocument=this}function aG(e,t,r){e&&e._inc++;var n=r.namespaceURI;n===Ll.XMLNS&&(t._nsMap[r.prefix?r.localName:""]=r.value)}function MA(e,t,r,n){e&&e._inc++;var i=r.namespaceURI;i===Ll.XMLNS&&delete t._nsMap[r.prefix?r.localName:""]}function od(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,o=0;i;)n[o++]=i,i=i.nextSibling;n.length=o,delete n[n.length]}}}function UA(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,od(e.ownerDocument,e),t}function sG(e){return e&&(e.nodeType===De.DOCUMENT_NODE||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.ELEMENT_NODE)}function lG(e){return e&&(jn(e)||Dh(e)||Ni(e)||e.nodeType===De.DOCUMENT_FRAGMENT_NODE||e.nodeType===De.COMMENT_NODE||e.nodeType===De.PROCESSING_INSTRUCTION_NODE)}function Ni(e){return e&&e.nodeType===De.DOCUMENT_TYPE_NODE}function jn(e){return e&&e.nodeType===De.ELEMENT_NODE}function Dh(e){return e&&e.nodeType===De.TEXT_NODE}function _A(e,t){var r=e.childNodes||[];if(zn(r,jn)||Ni(t))return!1;var n=zn(r,Ni);return!(t&&n&&r.indexOf(n)>r.indexOf(t))}function TA(e,t){var r=e.childNodes||[];function n(o){return jn(o)&&o!==t}if(zn(r,n))return!1;var i=zn(r,Ni);return!(t&&i&&r.indexOf(i)>r.indexOf(t))}function uG(e,t,r){if(!sG(e))throw new he(Er,"Unexpected parent node type "+e.nodeType);if(r&&r.parentNode!==e)throw new he(kA,"child not in parent");if(!lG(t)||Ni(t)&&e.nodeType!==De.DOCUMENT_NODE)throw new he(Er,"Unexpected node type "+t.nodeType+" for parent node type "+e.nodeType)}function cG(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(jn);if(o.length>1||zn(i,Dh))throw new he(Er,"More than one element or text in fragment");if(o.length===1&&!_A(e,r))throw new he(Er,"Element in fragment can not be inserted before doctype")}if(jn(t)&&!_A(e,r))throw new he(Er,"Only one element can be added and only after doctype");if(Ni(t)){if(zn(n,Ni))throw new he(Er,"Only one doctype is allowed");var a=zn(n,jn);if(r&&n.indexOf(a)<n.indexOf(r))throw new he(Er,"Doctype can only be inserted before an element");if(!r&&a)throw new he(Er,"Doctype can not be appended since element is present")}}function BA(e,t,r){var n=e.childNodes||[],i=t.childNodes||[];if(t.nodeType===De.DOCUMENT_FRAGMENT_NODE){var o=i.filter(jn);if(o.length>1||zn(i,Dh))throw new he(Er,"More than one element or text in fragment");if(o.length===1&&!TA(e,r))throw new he(Er,"Element in fragment can not be inserted before doctype")}if(jn(t)&&!TA(e,r))throw new he(Er,"Only one element can be added and only after doctype");if(Ni(t)){let l=function(u){return Ni(u)&&u!==r};var s=l;if(zn(n,l))throw new he(Er,"Only one doctype is allowed");var a=zn(n,jn);if(r&&n.indexOf(a)<n.indexOf(r))throw new he(Er,"Doctype can only be inserted before an element")}}function nd(e,t,r,n){uG(e,t,r),e.nodeType===De.DOCUMENT_NODE&&(n||cG)(e,t,r);var i=t.parentNode;if(i&&i.removeChild(t),t.nodeType===Ai){var o=t.firstChild;if(o==null)return t;var a=t.lastChild}else o=a=t;var s=r?r.previousSibling:e.lastChild;o.previousSibling=s,a.nextSibling=r,s?s.nextSibling=o:e.firstChild=o,r==null?e.lastChild=a:r.previousSibling=a;do{o.parentNode=e;var l=e.ownerDocument||e;$l(o,l)}while(o!==a&&(o=o.nextSibling));return od(e.ownerDocument||e,e),t.nodeType==Ai&&(t.firstChild=t.lastChild=null),t}function $l(e,t){if(e.ownerDocument!==t){if(e.ownerDocument=t,e.nodeType===tn&&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;)$l(i,t),i=i.nextSibling}}function dG(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,od(e.ownerDocument,e,t);var r=e.ownerDocument||e;return $l(t,r),t}Fl.prototype={nodeName:"#document",nodeType:PA,doctype:null,documentElement:null,_inc:1,insertBefore:function(e,t){if(e.nodeType==Ai){for(var r=e.firstChild;r;){var n=r.nextSibling;this.insertBefore(r,t),r=n}return e}return nd(this,e,t),$l(e,this),this.documentElement===null&&e.nodeType===tn&&(this.documentElement=e),e},removeChild:function(e){return this.documentElement==e&&(this.documentElement=null),UA(this,e)},replaceChild:function(e,t){nd(this,e,t,BA),$l(e,this),t&&this.removeChild(t),jn(e)&&(this.documentElement=e)},importNode:function(e,t){return fG(this,e,t)},getElementById:function(e){var t=null;return rd(this.documentElement,function(r){if(r.nodeType==tn&&r.getAttribute("id")==e)return t=r,!0}),t},getElementsByClassName:function(e){var t=CA(e);return new Ya(this,function(r){var n=[];return t.length>0&&rd(r.documentElement,function(i){if(i!==r&&i.nodeType===tn){var o=i.getAttribute("class");if(o){var a=e===o;if(!a){var s=CA(o);a=t.every(rG(s))}a&&n.push(i)}}}),n})},createElement:function(e){var t=new zo;t.ownerDocument=this,t.nodeName=e,t.tagName=e,t.localName=e,t.childNodes=new Si;var r=t.attributes=new td;return r._ownerElement=t,t},createDocumentFragment:function(){var e=new sd;return e.ownerDocument=this,e.childNodes=new Si,e},createTextNode:function(e){var t=new Ih;return t.ownerDocument=this,t.appendData(e),t},createComment:function(e){var t=new Oh;return t.ownerDocument=this,t.appendData(e),t},createCDATASection:function(e){if(e.indexOf("]]>")!==-1)throw new he(EA,'data contains "]]>"');var t=new Ph;return t.ownerDocument=this,t.appendData(e),t},createProcessingInstruction:function(e,t){var r=new kh;return r.ownerDocument=this,r.tagName=r.nodeName=r.target=e,r.nodeValue=r.data=t,r},createAttribute:function(e){var t=new id;return t.ownerDocument=this,t.name=e,t.nodeName=e,t.localName=e,t.specified=!0,t},createEntityReference:function(e){if(!Ka.test(e))throw new he(EA,'not a valid xml name "'+e+'"');var t=new Rh;return t.ownerDocument=this,t.nodeName=e,t},createElementNS:function(e,t){var r=new zo,n=t.split(":"),i=r.attributes=new td;return r.childNodes=new Si,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 id,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}};Ar(Fl,De);function zo(){this._nsMap={}}zo.prototype={nodeType:tn,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===Ai?this.insertBefore(e,null):dG(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 Ya(this,function(t){var r=[];return rd(t,function(n){n!==t&&n.nodeType==tn&&(e==="*"||n.tagName==e)&&r.push(n)}),r})},getElementsByTagNameNS:function(e,t){return new Ya(this,function(r){var n=[];return rd(r,function(i){i!==r&&i.nodeType===tn&&(e==="*"||i.namespaceURI===e)&&(t==="*"||i.localName==t)&&n.push(i)}),n})}};Fl.prototype.getElementsByTagName=zo.prototype.getElementsByTagName;Fl.prototype.getElementsByTagNameNS=zo.prototype.getElementsByTagNameNS;Ar(zo,De);function id(){}id.prototype.nodeType=Ja;Ar(id,De);function Ml(){}Ml.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(Nt[Er])},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}};Ar(Ml,De);function Ih(){}Ih.prototype={nodeName:"#text",nodeType:kl,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}};Ar(Ih,Ml);function Oh(){}Oh.prototype={nodeName:"#comment",nodeType:_h};Ar(Oh,Ml);function Ph(){}Ph.prototype={nodeName:"#cdata-section",nodeType:IA};Ar(Ph,Ml);function ad(){}ad.prototype.nodeType=RA;Ar(ad,De);function qA(){}qA.prototype.nodeType=iG;Ar(qA,De);function VA(){}VA.prototype.nodeType=nG;Ar(VA,De);function Rh(){}Rh.prototype.nodeType=OA;Ar(Rh,De);function sd(){}sd.prototype.nodeName="#document-fragment";sd.prototype.nodeType=Ai;Ar(sd,De);function kh(){}kh.prototype.nodeType=Nh;Ar(kh,De);function GA(){}GA.prototype.serializeToString=function(e,t,r,n){return WA.call(e,t,r,n)};De.prototype.toString=WA;function WA(e,t,r){var n=!!r&&!!r.requireWellFormed,i=[],o=this.nodeType==9&&this.documentElement||this,a=o.prefix,s=o.namespaceURI;if(s&&a==null){var a=o.lookupPrefix(s);if(a==null)var l=[{namespace:s,prefix:null}]}return Lh(this,i,e,t,l,n),i.join("")}function DA(e,t,r){var n=e.prefix||"",i=e.namespaceURI;if(!i||n==="xml"&&i===Ll.XML||i===Ll.XMLNS)return!1;for(var o=r.length;o--;){var a=r[o];if(a.prefix===n)return a.namespace!==i}return!0}function ed(e,t,r,n){if(n&&!Ka.test(t))throw new he(En,'The attribute name "'+t+'" is not a valid XML QName');e.push(" ",t,'="',r.replace(/[<>&"\t\n\r]/g,FA),'"')}function Lh(e,t,r,n,i,o){i||(i=[]),St(e,{ns:i,isHTML:r},{enter:function(a,s){var l=s.ns,u=s.isHTML;if(n)if(a=n(a),a){if(typeof a=="string")return t.push(a),null}else return null;switch(a.nodeType){case tn:var c=a.attributes,d=c.length,f=a.tagName;u=Ll.isHTML(a.namespaceURI)||u;var m=f;if(!u&&!a.prefix&&a.namespaceURI){for(var p,h=0;h<c.length;h++)if(c.item(h).name==="xmlns"){p=c.item(h).value;break}if(!p)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.prefix===""&&b.namespace===a.namespaceURI){p=b.namespace;break}}if(p!==a.namespaceURI)for(var g=l.length-1;g>=0;g--){var b=l[g];if(b.namespace===a.namespaceURI){b.prefix&&(m=b.prefix+":"+f);break}}}if(o&&!Ka.test(m))throw new he(En,'The element name "'+m+'" is not a valid XML QName');t.push("<",m);for(var w=l.slice(),C=0;C<d;C++){var S=c.item(C);S.prefix=="xmlns"?w.push({prefix:S.localName,namespace:S.value}):S.nodeName=="xmlns"&&w.push({prefix:"",namespace:S.value})}for(var C=0;C<d;C++){var S=c.item(C);if(DA(S,u,w)){var O=S.prefix||"",k=S.namespaceURI;ed(t,O?"xmlns:"+O:"xmlns",k,o),w.push({prefix:O,namespace:k})}var I=n?n(S):S;I&&(typeof I=="string"?t.push(I):ed(t,I.name,I.value,o))}if(f===m&&DA(a,u,w)){var D=a.prefix||"",k=a.namespaceURI;ed(t,D?"xmlns:"+D:"xmlns",k,o),w.push({prefix:D,namespace:k})}var P=a.firstChild;if(P||u&&!/^(?:meta|link|img|br|hr|input)$/i.test(f)){if(t.push(">"),u&&/^script$/i.test(f)){for(;P;)P.data?t.push(P.data):Lh(P,t,u,n,w.slice(),o),P=P.nextSibling;return t.push("</",f,">"),null}return{ns:w,isHTML:u,tag:m}}else return t.push("/>"),null;case PA:case Ai:return{ns:l.slice(),isHTML:u,tag:null};case Ja:return ed(t,a.name,a.value,o),null;case kl:return t.push(a.data.replace(/[<&>]/g,FA)),null;case IA:if(o&&a.data.indexOf("]]>")!==-1)throw new he(En,'The CDATASection data contains "]]>"');return t.push("<![CDATA[",a.data.replace(/]]>/g,"]]]]><![CDATA[>"),"]]>"),null;case _h:if(o&&a.data.indexOf("-->")!==-1)throw new he(En,'The comment node data contains "-->"');return t.push("<!--",a.data,"-->"),null;case RA:if(o){if(!Ka.test(a.name))throw new he(En,'The doctype name "'+a.name+'" is not a valid XML Name');if(a.publicId&&!/^("[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%']*"|'[\x20\r\na-zA-Z0-9\-()+,.\/:=?;!*#@$_%'"]*')$/.test(a.publicId))throw new he(En,"DocumentType publicId is not a valid PubidLiteral");if(a.systemId&&!/^("[^"]*"|'[^']*')$/.test(a.systemId))throw new he(En,"DocumentType systemId is not a valid SystemLiteral");if(a.internalSubset&&a.internalSubset.indexOf("]>")!==-1)throw new he(En,'DocumentType internalSubset contains "]>"')}var x=a.publicId,K=a.systemId;if(t.push("<!DOCTYPE ",a.name),x)t.push(" PUBLIC ",x),K&&K!="."&&t.push(" ",K),t.push(">");else if(K&&K!=".")t.push(" SYSTEM ",K,">");else{var Oe=a.internalSubset;Oe&&t.push(" [",Oe,"]"),t.push(">")}return null;case Nh:if(o){if(!Ka.test(a.target)||a.target.indexOf(":")!==-1||a.target.toLowerCase()==="xml")throw new he(En,'The processing instruction target "'+a.target+'" is not a valid XML NCName or is reserved');if(a.data.indexOf("?>")!==-1)throw new he(En,'The ProcessingInstruction data contains "?>"')}return t.push("<?",a.target," ",a.data,"?>"),null;case OA:if(o&&!Ka.test(a.nodeName))throw new he(En,'The entity reference name "'+a.nodeName+'" is not a valid XML Name');return t.push("&",a.nodeName,";"),null;default:return t.push("??",a.nodeName),null}},exit:function(a,s){s&&s.tag&&t.push("</",s.tag,">")}})}function fG(e,t,r){var n;return St(t,null,{enter:function(i,o){var a=i.cloneNode(!1);a.ownerDocument=e,a.parentNode=null,o===null?n=a:o.appendChild(a);var s=i.nodeType===Ja||r;return s?a:null}}),n}function zA(e,t,r){var n;return St(t,null,{enter:function(i,o){var a=new i.constructor;for(var s in i)if(Object.prototype.hasOwnProperty.call(i,s)){var l=i[s];typeof l!="object"&&l!=a[s]&&(a[s]=l)}i.childNodes&&(a.childNodes=new Si),a.ownerDocument=e;var u=r;switch(a.nodeType){case tn:var c=i.attributes,d=a.attributes=new td,f=c.length;d._ownerElement=a;for(var m=0;m<f;m++)a.setAttributeNode(zA(e,c.item(m),!0));break;case Ja:u=!0}return o!==null?o.appendChild(a):n=a,u?a:null}}),n}function jA(e,t,r){e[t]=r}try{Object.defineProperty&&(Object.defineProperty(Ya.prototype,"length",{get:function(){return Th(this),this.$$length}}),Object.defineProperty(De.prototype,"textContent",{get:function(){if(this.nodeType===tn||this.nodeType===Ai){var e=[];return St(this,null,{enter:function(t){if(t.nodeType===tn||t.nodeType===Ai)return!0;if(t.nodeType===Nh||t.nodeType===_h)return null;e.push(t.nodeValue)}}),e.join("")}return this.nodeValue},set:function(e){switch(this.nodeType){case tn:case Ai: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}}}),jA=function(e,t,r){e["$$"+t]=r})}catch{}_i.DocumentType=ad;_i.DOMException=he;_i.DOMImplementation=xA;_i.Element=zo;_i.Node=De;_i.NodeList=Si;_i.walkDOM=St;_i.XMLSerializer=GA});var KA=v(Ul=>{"use strict";var HA=Ha().freeze;Ul.XML_ENTITIES=HA({amp:"&",apos:"'",gt:">",lt:"<",quot:'"'});Ul.HTML_ENTITIES=HA({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"});Ul.entityMap=Ul.HTML_ENTITIES});var ZA=v(Fh=>{var Vl=Ha().NAMESPACE,xh=Ha().tagNamePattern,Qa=0,no=1,Xa=2,Bl=3,Za=4,es=5,ql=6,ld=7;function ts(e,t){this.message=e,this.locator=t,Error.captureStackTrace&&Error.captureStackTrace(this,ts)}ts.prototype=new Error;ts.prototype.name=ts.name;function QA(){}QA.prototype={parse:function(e,t,r){var n=this.domBuilder;n.startDocument(),yG(t,t={}),pG(e,t,r,n,this.errorHandler),n.endDocument()}};function pG(e,t,r,n,i){function o(se){if(se>65535){se-=65536;var We=55296+(se>>10),ir=56320+(se&1023);return String.fromCharCode(We,ir)}else return String.fromCharCode(se)}function a(se){var We=se.slice(1,-1);return Object.hasOwnProperty.call(r,We)?r[We]:We.charAt(0)==="#"?o(parseInt(We.substr(1).replace("x","0x"))):(i.error("entity not found:"+se),se)}function s(se){if(se>h){var We=e.substring(h,se).replace(/&#?\w+;/g,a);f&&l(h),n.characters(We,0,se-h),h=se}}function l(se,We){for(;se>=c&&(We=d.exec(e));)u=We.index,c=u+We[0].length,f.lineNumber++;f.columnNumber=se-u+1}for(var u=0,c=0,d=/.*(?:\r\n?|\n)|.*$/g,f=n.locator,m=[{currentNSMap:t}],p={},h=0;;){try{var g=e.indexOf("<",h);if(g<0){if(!e.substr(h).match(/^\s*$/)){var b=n.doc,w=b.createTextNode(e.substr(h));b.appendChild(w),n.currentElement=w}return}switch(g>h&&s(g),e.charAt(g+1)){case"/":var K=e.indexOf(">",g+3),C=e.substring(g+2,K).replace(/^([\s\S]*?[^ \t\n\r])?[ \t\n\r]*$/,"$1"),S=m.pop();K<0?(C=e.substring(g+2).replace(/[\s<].*/,""),i.error("end tag name: "+C+" is not complete:"+S.tagName),K=g+1+C.length):C.match(/\s</)?(C=C.replace(/[\s<].*/,""),i.error("end tag name: "+C+" maybe not complete"),K=g+1+C.length):/[ \t\n\r]/.test(C)&&xh.test(C.split(/[ \t\n\r]/)[0])&&i.error('end tag name is followed by whitespace and trailing content: "'+C+'"');var O=S.localNSMap,k=S.tagName==C,I=k||S.tagName&&S.tagName.toLowerCase()==C.toLowerCase();if(I){if(n.endElement(S.uri,S.localName,C),O)for(var D in O)Object.prototype.hasOwnProperty.call(O,D)&&n.endPrefixMapping(D);k||i.fatalError("end tag name: "+C+" is not match the current start tagName:"+S.tagName)}else m.push(S);K++;break;case"?":f&&l(g),K=vG(e,g,n);break;case"!":f&&l(g),K=bG(e,g,n,i);break;default:f&&l(g);var P=new XA,x=m[m.length-1].currentNSMap,K=mG(e,g,P,x,a,i),Oe=P.length;if(!P.closed&&gG(e,K,P.tagName,p)&&(P.closed=!0,r.nbsp||i.warning("unclosed xml attribute")),f&&Oe){for(var Vt=JA(f,{}),Xe=0;Xe<Oe;Xe++){var Ne=P[Xe];l(Ne.offset),Ne.locator=JA(f,{})}n.locator=Vt,YA(P,n,x)&&m.push(P),n.locator=f}else YA(P,n,x)&&m.push(P);Vl.isHTML(P.uri)&&!P.closed?K=hG(e,K,P.tagName,a,n):K++}}catch(se){if(se instanceof ts)throw se;i.error("element parse error: "+se),K=-1}K>h?h=K:s(Math.max(g,h)+1)}}function JA(e,t){return t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber,t}function mG(e,t,r,n,i,o){function a(m,p,h){r.attributeNames.hasOwnProperty(m)&&o.fatalError("Attribute "+m+" redefined"),r.addValue(m,p.replace(/[\t\n\r]/g," ").replace(/&#?\w+;/g,i),h)}for(var s,l,u=++t,c=Qa;;){var d=e.charAt(u);if(c===Qa&&d==="<")throw new Error("unexpected < in tag name: "+e.slice(t,u));switch(d){case"=":if(c===no)s=e.slice(t,u),c=Bl;else if(c===Xa)c=Bl;else throw new Error("attribute equal must after attrName");break;case"'":case'"':if(c===Bl||c===no)if(c===no&&(o.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),a(s,l,t-1),c=es;else throw new Error("attribute value no end '"+d+"' match");else if(c==Za)l=e.slice(t,u),a(s,l,t),o.warning('attribute "'+s+'" missed start quot('+d+")!!"),t=u+1,c=es;else throw new Error('attribute value must after "="');break;case"/":switch(c){case Qa:r.setTagName(e.slice(t,u));case es:case ql:case ld:c=ld,r.closed=!0;case Za:case no:break;case Xa:r.closed=!0;break;default:throw new Error("attribute invalid close char('/')")}break;case"":return o.error("unexpected end of input"),c==Qa&&r.setTagName(e.slice(t,u)),u;case">":switch(c){case Qa:r.setTagName(e.slice(t,u));case es:case ql:case ld:break;case Za:case no:l=e.slice(t,u),l.slice(-1)==="/"&&(r.closed=!0,l=l.slice(0,-1));case Xa:c===Xa&&(l=s),c==Za?(o.warning('attribute "'+l+'" missed quot(")!'),a(s,l,t)):((!Vl.isHTML(n[""])||!l.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+l+'" missed value!! "'+l+'" instead!!'),a(l,l,t));break;case Bl:throw new Error("attribute value missed!!")}return u;case"\x80":d=" ";default:if(d<=" ")switch(c){case Qa:r.setTagName(e.slice(t,u)),c=ql;break;case no:s=e.slice(t,u),c=Xa;break;case Za:var l=e.slice(t,u);o.warning('attribute "'+l+'" missed quot(")!!'),a(s,l,t);case es:c=ql;break}else switch(c){case Xa:var f=r.tagName;(!Vl.isHTML(n[""])||!s.match(/^(?:disabled|checked|selected)$/i))&&o.warning('attribute "'+s+'" missed value!! "'+s+'" instead2!!'),a(s,s,t),t=u,c=no;break;case es:o.warning('attribute space is required"'+s+'"!!');case ql:c=no,t=u;break;case Bl:c=Za,t=u;break;case ld:throw new Error("elements closed character '/' and '>' must be connected to")}}u++}}function YA(e,t,r){for(var n=e.tagName,i=null,d=e.length;d--;){var o=e[d],a=o.qName,s=o.value,f=a.indexOf(":");if(f>0)var l=o.prefix=a.slice(0,f),u=a.slice(f+1),c=l==="xmlns"&&u;else u=a,l=null,c=a==="xmlns"&&"";o.localName=u,c!==!1&&(i==null&&(i={},r=Object.create(r)),r[c]=i[c]=s,o.uri=Vl.XMLNS,t.startPrefixMapping(c,s))}for(var d=e.length;d--;){o=e[d];var l=o.prefix;l&&(l==="xml"&&(o.uri=Vl.XML),l!=="xmlns"&&(o.uri=r[l||""]))}var f=n.indexOf(":");f>0?(l=e.prefix=n.slice(0,f),u=e.localName=n.slice(f+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 hG(e,t,r,n,i){if(/^(?:script|textarea)$/i.test(r)){var o=e.indexOf("</"+r+">",t),a=e.substring(t+1,o);if(/[&<]/.test(a))return/^script$/i.test(r)?(i.characters(a,0,a.length),o):(a=a.replace(/&#?\w+;/g,n),i.characters(a,0,a.length),o)}return t+1}function gG(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 yG(e,t){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}function bG(e,t,r,n){var i=e.charAt(t+2);switch(i){case"-":if(e.charAt(t+3)==="-"){var o=e.indexOf("-->",t+4);return o>t?(r.comment(e,t+4,o-t-4),o+3):(n.error("Unclosed comment"),-1)}else return-1;default:if(e.substr(t+3,6)=="CDATA["){var o=e.indexOf("]]>",t+9);return r.startCDATA(),r.characters(e,t+9,o-t-9),r.endCDATA(),o+3}var a=wG(e,t),s=a.length;if(s>1&&/!doctype/i.test(a[0][0])){var l=a[1][0],u=!1,c=!1;s>3&&(/^public$/i.test(a[2][0])?(u=a[3][0],c=s>4&&a[4][0]):/^system$/i.test(a[2][0])&&(c=a[3][0]));var d=a[s-1];return r.startDTD(l,u,c),r.endDTD(),d.index+d[0].length}}return-1}function vG(e,t,r){var n=e.indexOf("?>",t);if(n){var i=e.substring(t,n).match(/^<\?(\S*)\s*([\s\S]*?)$/);if(i){var o=i[0].length;return r.processingInstruction(i[1],i[2]),n+2}else return-1}return-1}function XA(){this.attributeNames={}}XA.prototype={setTagName:function(e){if(!xh.test(e))throw new Error("invalid tagName:"+e);this.tagName=e},addValue:function(e,t,r){if(!xh.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 wG(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}Fh.XMLReader=QA;Fh.ParseError=ts});var aS=v(cd=>{var CG=Ha(),EG=$h(),eS=KA(),nS=ZA(),AG=EG.DOMImplementation,tS=CG.NAMESPACE,SG=nS.ParseError,NG=nS.XMLReader;function iS(e){return e.replace(/\r[\n\u0085]/g,`
`).replace(/[\r\u0085\u2028]/g,`
-`)}function JA(e){this.options=e||{locator:{}}}JA.prototype.parseFromString=function(e,t){var r=this.options,n=new hG,i=r.domBuilder||new Ul,o=r.errorHandler,a=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?WA.HTML_ENTITIES:WA.XML_ENTITIES;a&&i.setDocumentLocator(a),n.errorHandler=gG(o,i,a),n.domBuilder=r.domBuilder||i,l&&(s[""]=zA.HTML),s.xml=s.xml||zA.XML;var c=r.normalizeLineEndings||KA;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function gG(e,t,r){if(!e){if(t instanceof Ul)return t;e=t}var n={},i=e instanceof Function;r=r||{};function o(a){var s=e[a];!s&&i&&(s=e.length==2?function(l){e(a,l)}:e),n[a]=s&&function(l){s("[xmldom "+a+"] "+l+Oh(r))}||function(){}}return o("warning"),o("error"),o("fatalError"),n}function Ul(){this.cdata=!1}function Za(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}Ul.prototype={startDocument:function(){this.doc=new pG().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,r,n){var i=this.doc,o=i.createElementNS(e,r||t),a=n.length;rd(this,o),this.currentElement=o,this.locator&&Za(this.locator,o);for(var s=0;s<a;s++){var e=n.getURI(s),l=n.getValue(s),r=n.getQName(s),u=i.createAttributeNS(e,r);this.locator&&Za(n.getLocator(s),u),u.value=u.nodeValue=l,o.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&&Za(this.locator,r),rd(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=jA.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&&Za(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=jA.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&Za(this.locator,n),rd(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&&Za(this.locator,i),rd(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,Oh(this.locator))},error:function(e){console.error("[xmldom error] "+e,Oh(this.locator))},fatalError:function(e){throw new mG(e,this.locator)}};function Oh(e){if(e)return`
-@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function jA(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){Ul.prototype[e]=function(){return null}});function rd(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}nd.__DOMHandler=Ul;nd.normalizeLineEndings=KA;nd.DOMParser=JA});var es=v(id=>{var QA=Th();id.DOMImplementation=QA.DOMImplementation;id.XMLSerializer=QA.XMLSerializer;id.DOMParser=YA().DOMParser});var ZA={};Hr(ZA,{CCFControlConstants:()=>XA,CCFPropertyConstants:()=>Rh,CustomControlDataType:()=>F,CustomControlNames:()=>_i,DefaultControlNameKeys:()=>Ph,ICCModeEnum:()=>no,JSONParametersConstants:()=>Lh,LookUpType:()=>od,ManifestXMLConstants:()=>jt,NumberType:()=>ad,Usage:()=>Wo});var XA,Rh,Lh,jt,F,Ph,_i,no,Wo,od,ad,zo=k(()=>{"use strict";XA={CCID:"CustomControlId",CCName:"DisplayName",Properties:"Properties",Mode:"ControlMode",AvailableOn:"AvailableOn",CCDescription:"description-key",ImageURL:"preview-image",TypeGroup:"type-group",DataSets:"DataSets",EntityNameKey:"EntityNameKey",NameSpace:"Name",OfTypeKey:"OfType"},Rh={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"},Lh={GroupDefinition:"GroupDefinition"},jt={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"})(F||(F={}));(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"})(Ph||(Ph={}));(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"})(_i||(_i={}));(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"})(no||(no={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(Wo||(Wo={}));od=[F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.LookupSimple],ad=[F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.FP,F.Decimal]});var ts,nr,Bl=k(()=>{"use strict";ts=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}},nr=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 eS={};Hr(eS,{AttributeDataSourceType:()=>ql,AttributeDataSourceTypeMask:()=>sd,AttributePrecisionSource:()=>Vl,EntityAttributeDataSourceType:()=>jo,EntityAttributeDateTimeBehavior:()=>xh,EntityAttributeImeMode:()=>$h,EntityAttributePrecisionSource:()=>Fh,EntityAttributeRequiredLevel:()=>io,EntityAttributeType:()=>$,EntityAttributeTypeFormat:()=>W,EntityMetadataLookUpBase:()=>Ti,EntityResxKeyLookUp:()=>ld,SourceTypeMask:()=>kh});var Ti,$,W,io,jo,kh,ql,sd,$h,xh,Fh,Vl,ld,rs=k(()=>{"use strict";Bl();Ti=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return ld.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"})($||($={}));(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"})(W||(W={}));io=class extends Ti{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},jo=class e extends Ti{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?ql.Persistent:parseInt(ql[this.name])}},kh=class e extends Ti{constructor(t){super(t),t||(this.name=e.Undefined)}static get Undefined(){return"Undefined"}static get Simple(){return"Simple"}static get Related(){return"Related"}static get Logical(){return"Logical"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}static get Invalid(){return"Invalid"}GetValue(){return parseInt(sd[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(ql||(ql={}));(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"})(sd||(sd={}));$h=class e extends Ti{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Auto(){return"Auto"}static get Inactive(){return"Inactive"}static get Active(){return"Active"}static get Disabled(){return"Disabled"}},xh=class e extends Ti{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get UserLocal(){return"UserLocal"}static get DateOnly(){return"DateOnly"}static get TimeZoneIndependent(){return"TimeZoneIndependent"}},Fh=class e extends Ti{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Attribute(){return"Attribute"}static get Organization(){return"Organization"}static get Currency(){return"Currency"}GetValue(){return this.name===e.None?Vl.Currency:parseInt(Vl[this.name])}};(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(Vl||(Vl={}));ld=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new ts;return t.add($.TwoOptions,"SystemCustomization.type.bit.label"),t.add($.Customer,"SystemCustomization.type.customer.label"),t.add($.CustomerType,"SystemCustomization.type.customer.label"),t.add($.DateTime,"SystemCustomization.type.datetime.label"),t.add($.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add($.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add($.WholeNumber,"SystemCustomization.type.int.label"),t.add($.LookupType,"SystemCustomization.type.lookup.label"),t.add($.Lookup,"SystemCustomization.type.lookup.label"),t.add($.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add($.Currency,"SystemCustomization.type.money.label"),t.add($.Owner,"SystemCustomization.type.owner.label"),t.add($.OwnerType,"SystemCustomization.type.owner.label"),t.add($.PartyList,"SystemCustomization.type.partylist.label"),t.add($.PartyListType,"SystemCustomization.type.partylist.label"),t.add($.OptionSet,"SystemCustomization.type.picklist.label"),t.add($.State,"SystemCustomization.type.state.label"),t.add($.Status,"SystemCustomization.type.status.label"),t.add($.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add($.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add($.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add($.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add($.VirtualType,"SystemCustomization.type.virtual.label"),t.add($.BigInt,"SystemCustomization.type.bigint.label"),t.add($.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add($.EntityNameType,"SystemCustomization.type.entityname.label"),t.add($.Image,"SystemCustomization.type.image.label"),t.add($.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add($.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add($.LookupType,"SystemCustomization.type.lookuptype.label"),t.add($.Subject,"SystemCustomization.type.subject.label"),t.add(W.Email,"SystemCustomization.String.Format.email"),t.add(W.Text,"SystemCustomization.String.Format.text"),t.add(W.TextArea,"SystemCustomization.String.Format.textarea"),t.add(W.Url,"SystemCustomization.String.Format.url"),t.add(W.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(W.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(W.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(W.Phone,"SystemCustomization.String.Format.phone"),t.add(W.None,"SystemCustomization.Integer.Format."),t.add(W.Duration,"SystemCustomization.Integer.Format.duration"),t.add(W.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(W.Language,"SystemCustomization.Integer.Format.language"),t.add(W.Locale,"SystemCustomization.Integer.Format.language"),t.add(W.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(W.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(W.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(jo.Persistent,"SystemCustomization.String.Source.persistent"),t.add(jo.Calculated,"SystemCustomization.String.Source.calculated"),t.add(jo.Rollup,"SystemCustomization.String.Source.rollup"),t.add(jo.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var Uh=v(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.parsePcfManifest=it.parseControlElement=it.parseManifestRoot=it.firstLevel=it.attr=it.elementChildren=it.manifestTypesForColumn=it.DEFAULT_TYPE_GROUPS=void 0;var yG=es(),H=(zo(),Fr(ZA)),we=(rs(),Fr(eS));it.DEFAULT_TYPE_GROUPS={numbers:[H.CustomControlDataType.WholeNone,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.Currency],text:[H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.Multiple],lookup:[H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding],dates:[H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime],allFields:[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.WholeNone,H.CustomControlDataType.WholeDuration,H.CustomControlDataType.WholeTimeZone,H.CustomControlDataType.WholeLanguage,H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding,H.CustomControlDataType.Multiple,H.CustomControlDataType.OptionSet,H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.SingleLineEmail,H.CustomControlDataType.SingleLineURL,H.CustomControlDataType.SingleLineTickerSymbol,H.CustomControlDataType.SingleLinePhone]};var bG="Phone";function vG(e,t,r){switch(e){case we.EntityAttributeType.TwoOptions:return[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.Boolean];case we.EntityAttributeType.Customer:case we.EntityAttributeType.CustomerType:return[H.CustomControlDataType.LookupCustomer];case we.EntityAttributeType.DateTime:return t===we.EntityAttributeTypeFormat.DateAndTime?[H.CustomControlDataType.DateAndTimeDateAndTime]:[H.CustomControlDataType.DateAndTimeDateOnly];case we.EntityAttributeType.DecimalNumber:return[H.CustomControlDataType.Decimal];case we.EntityAttributeType.FloatingPointNumber:return[H.CustomControlDataType.FP];case we.EntityAttributeType.File:return[H.CustomControlDataType.File];case we.EntityAttributeType.Image:return[H.CustomControlDataType.Image];case we.EntityAttributeType.WholeNumber:return t===we.EntityAttributeTypeFormat.Duration?[H.CustomControlDataType.WholeDuration]:t===we.EntityAttributeTypeFormat.Language?[H.CustomControlDataType.WholeLanguage]:t===we.EntityAttributeTypeFormat.TimeZone?[H.CustomControlDataType.WholeTimeZone]:[H.CustomControlDataType.WholeNone];case we.EntityAttributeType.LookupType:case we.EntityAttributeType.Lookup:return t===we.EntityAttributeTypeFormat.Regarding?[H.CustomControlDataType.LookupRegarding]:[H.CustomControlDataType.LookupSimple];case we.EntityAttributeType.MultipleLineofText:return[H.CustomControlDataType.Multiple];case we.EntityAttributeType.Currency:return[H.CustomControlDataType.Currency];case we.EntityAttributeType.Owner:case we.EntityAttributeType.OwnerType:return[H.CustomControlDataType.LookupOwner];case we.EntityAttributeType.PartyList:case we.EntityAttributeType.PartyListType:return[H.CustomControlDataType.LookupPartyList];case we.EntityAttributeType.Status:case we.EntityAttributeType.OptionSet:return[H.CustomControlDataType.OptionSet];case we.EntityAttributeType.SingleLineofText:switch(t){case we.EntityAttributeTypeFormat.Email:return[H.CustomControlDataType.SingleLineEmail];case we.EntityAttributeTypeFormat.Phone:return[H.CustomControlDataType.SingleLinePhone];case we.EntityAttributeTypeFormat.Text:return r===bG?[H.CustomControlDataType.SingleLinePhone]:[H.CustomControlDataType.SingleLineText];case we.EntityAttributeTypeFormat.TextArea:return[H.CustomControlDataType.SingleLineTextArea];case we.EntityAttributeTypeFormat.TickerSymbol:return[H.CustomControlDataType.SingleLineTickerSymbol];case we.EntityAttributeTypeFormat.Url:return[H.CustomControlDataType.SingleLineURL];default:return[H.CustomControlDataType.SingleLineText]}case we.EntityAttributeType.MultiSelectOptionSet:return[H.CustomControlDataType.MultiSelectOptionSet];default:return null}}it.manifestTypesForColumn=vG;function Mh(e){let t=[],r=e.childNodes;for(let n=0;n<r.length;n+=1)r[n].nodeType===1&&t.push(r[n]);return t}it.elementChildren=Mh;function En(e,t){return e.hasAttribute(t)?e.getAttribute(t):null}it.attr=En;function jn(e,...t){return Mh(e).filter(r=>t.includes(r.tagName))}it.firstLevel=jn;function wG(e){let t=new Map;for(let r of jn(e,"type-group"))t.set(String(En(r,"name")),jn(r,"type").map(n=>String(n.textContent)));for(let[r,n]of t)t.set(r,n.sort());return t}function CG(e){let t=e.getElementsByTagName("AvailableOn")[0];if(!t)return{web:!0,phone:!0,tablet:!0};let r=new Set(Mh(t).map(n=>n.tagName));return{web:r.has("web"),phone:r.has("phone"),tablet:r.has("tablet")}}var EG={input:"input",bound:"bound",output:"output"};function AG(e,t,r){let n=En(e,"usage"),i=n!==null&&EG[n]||"input",o=En(e,"default-value"),a=jn(e,"value").map(m=>{let p={name:En(m,"name"),value:String(m.textContent),isDefault:En(m,"default")==="true"};return p.isDefault&&(o=p.value),p}),s=En(e,"of-type-group"),l=s!==null?t.get(s):void 0,u=s!==null&&Object.prototype.hasOwnProperty.call(it.DEFAULT_TYPE_GROUPS,s)?it.DEFAULT_TYPE_GROUPS[s]:void 0,c=l?[...l]:u?[...u]:[],d=En(e,"of-type"),f=d!==null?d:c.length>0?c[0]:null;return{name:En(e,"name"),usage:i,ofType:d,typeGroupName:s,ofTypeGroup:c,defaultType:f||void 0,required:En(e,"required")==="true",hidden:En(e,"hidden")==="true",defaultValue:o,enumValues:a,isPrimary:r&&i==="bound"}}function tS(e){var t;let r=[],n=a=>s=>r.push(`${a}: ${s}`),i=new yG.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the control manifest does not parse cleanly${r.length>0?` (${r[0]})`:""}`);return o}it.parseManifestRoot=tS;function rS(e){let t=jn(tS(e),"control")[0];if(!t)throw new Error("the control manifest has no <control> element");return t}it.parseControlElement=rS;function SG(e){let t=rS(e),r=wG(t),n=jn(t,"data-set"),i=jn(t,"property"),o=jn(t,"groups"),a=[],s=!1;for(let u of i){let c=AG(u,r,n.length===0&&!s);s=s||c.isPrimary,a.push(c)}let l=n.length>0||(a.length>0?a[0].usage==="bound":o.some(u=>jn(u,"group").some(c=>jn(c,"data-set","property").length>0)));return{properties:a,hasDataset:n.length>0,hasGroups:o.length>0,isBound:l,availableOn:CG(t)}}it.parsePcfManifest=SG});var iS=v(is=>{"use strict";Object.defineProperty(is,"__esModule",{value:!0});is.readPcfColumn=is.readControlManifest=void 0;var ns=se(),NG=Uh();function Bh(e,t,r){var n;let i=(n=r?.error)===null||n===void 0?void 0:n.message;return new Error(`${e}: HTTP ${t}${typeof i=="string"?` ${i}`:""}`)}async function _G(e,t){var r;let n="/customcontrols"+(0,ns.odataQuery)([["$select","name,manifest"],["$filter",`name eq '${(0,ns.odataLiteral)(t)}'`]]);try{let i=await e.get(n);if(i.status<200||i.status>=300)return{kind:"unavailable",error:Bh(`reading control "${t}"`,i.status,i.body)};let o=(r=i.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(o)||o.some(l=>l===null||typeof l!="object"))return{kind:"unavailable",error:new Error(`reading control "${t}": the answer is unreadable \u2014 expected an OData 'value' array of rows`)};let a=o;if(a.length===0)return{kind:"missing"};if(a.length>1)return{kind:"ambiguous"};let s=a[0].manifest;return typeof s!="string"?{kind:"unavailable",error:new Error(`control "${t}" has no manifest`)}:{kind:"found",value:(0,NG.parsePcfManifest)(s)}}catch(i){return{kind:"unavailable",error:i instanceof Error?i:new Error(String(i))}}}is.readControlManifest=_G;var TG=new Map([["StringType",{cast:"StringAttributeMetadata",select:"Format,FormatName"}],["MemoType",{cast:"MemoAttributeMetadata",select:"Format"}],["IntegerType",{cast:"IntegerAttributeMetadata",select:"Format"}],["DateTimeType",{cast:"DateTimeAttributeMetadata",select:"Format"}],["LookupType",{cast:"LookupAttributeMetadata",select:"Format"}]]);function nS(e){let t=e?.Value;return typeof t=="string"?t:void 0}async function DG(e,t,r,n){var i;let o=`/EntityDefinitions(LogicalName='${(0,ns.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,ns.odataPathLiteral)(r)}')`,a=n?.requireCreateEligibility===!0;try{let s=await e.get(o+(0,ns.odataQuery)([["$select",`LogicalName,AttributeType,AttributeTypeName,IsValidForForm,IsPrimaryId${a?",IsValidForCreate":""}`]]));if(s.status===404)return{kind:"missing"};if(s.status<200||s.status>=300)return{kind:"unavailable",error:Bh(`reading column "${r}"`,s.status,s.body)};let l=(i=s.body)!==null&&i!==void 0?i:{},u=nS(l.AttributeTypeName);if(!u)return{kind:"unavailable",error:new Error(`column "${r}" has no AttributeTypeName`)};if(a&&typeof l.IsValidForCreate!="boolean")return{kind:"unavailable",error:new Error(`column "${r}" has no IsValidForCreate`)};let c={logicalName:typeof l.LogicalName=="string"?l.LogicalName:r,attributeTypeName:u,isValidForForm:l.IsValidForForm===!0,isPrimaryId:l.IsPrimaryId===!0,...a?{isValidForCreate:l.IsValidForCreate}:{}},d=TG.get(u);if(d){let f=await e.get(`${o}/Microsoft.Dynamics.CRM.${d.cast}`+(0,ns.odataQuery)([["$select",d.select]]));if(f.status<200||f.status>=300)return{kind:"unavailable",error:Bh(`reading the format of column "${r}"`,f.status,f.body)};let m=f.body;if(m===null||typeof m!="object"||m.Format!==null&&typeof m.Format!="string")return{kind:"unavailable",error:new Error(`reading the format of column "${r}": the answer is unreadable \u2014 expected its Format (a string or null)`)};typeof m.Format=="string"&&(c.format=m.Format);let p=nS(m.FormatName);p&&(c.formatName=p)}return{kind:"found",value:c}}catch(s){return{kind:"unavailable",error:s instanceof Error?s:new Error(String(s))}}}is.readPcfColumn=DG});var Ho=v(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});ud.DEFAULT_LCID=void 0;ud.DEFAULT_LCID=1033});var dt=v(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.assignMissingIds=Hn.pointerTouchesValueMap=Hn.isValueMapKey=Hn.newId=void 0;var IG=$a();function oS(){return globalThis.crypto.randomUUID().toLowerCase()}Hn.newId=oS;function OG(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Vh=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData","customControl"]);function PG(e){return Vh.has(e)}Hn.isValueMapKey=PG;function RG(e){return IG.JsonPointer.parse(e).some(t=>Vh.has(t))}Hn.pointerTouchesValueMap=RG;function LG(e){return qh(e),e}Hn.assignMissingIds=LG;function qh(e){if(Array.isArray(e)){e.forEach(t=>qh(t));return}if(OG(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=oS());for(let t of Object.keys(e))t==="id"||Vh.has(t)||qh(e[t])}}});var Wl=v(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.sendChangeSet=Er.partResponse=Er.postChangeSet=Er.parseChangeSetParts=Er.parseChangeSetStatuses=Er.renderChangeSet=void 0;var oo=Q(),Gh=ye(),aS=dt(),Gl=se();function Wh(e,t){let r=`batch_${(0,aS.newId)()}`,n=`changeset_${(0,aS.newId)()}`,i=t.map((s,l)=>String(l+1)),o=t.map((s,l)=>{var u,c;if(s.rawBody!==void 0&&s.contentType===void 0)throw new oo.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a raw body but no Content-Type`);let d=(u=s.rawBody)!==null&&u!==void 0?u:s.body===void 0?void 0:JSON.stringify(s.body);if(d!==void 0&&(d.includes(`--${n}`)||d.includes(`--${r}`)))throw new oo.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,Gl.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,Gl.assertNoControlChars)(s.etag,"batch operation etag");let f=Object.entries((c=s.headers)!==null&&c!==void 0?c:{});for(let[m,p]of f)if((0,Gl.assertNoControlChars)(m,"batch operation header name"),(0,Gl.assertNoControlChars)(p,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(m))throw new oo.InvalidArgumentError(`batch operation header name '${m}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,Gl.assertNoControlChars)(s.contentType,"batch operation content type"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...d===void 0?[]:[`Content-Type: ${s.rawBody!==void 0?s.contentType:"application/json;type=entry"}`],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],...f.map(([m,p])=>`${m}: ${p}`),"",...d===void 0?[]:[d]].join(`\r
+`)}function oS(e){this.options=e||{locator:{}}}oS.prototype.parseFromString=function(e,t){var r=this.options,n=new NG,i=r.domBuilder||new Gl,o=r.errorHandler,a=r.locator,s=r.xmlns||{},l=/\/x?html?$/.test(t),u=l?eS.HTML_ENTITIES:eS.XML_ENTITIES;a&&i.setDocumentLocator(a),n.errorHandler=_G(o,i,a),n.domBuilder=r.domBuilder||i,l&&(s[""]=tS.HTML),s.xml=s.xml||tS.XML;var c=r.normalizeLineEndings||iS;return e&&typeof e=="string"?n.parse(c(e),s,u):n.errorHandler.error("invalid doc source"),i.doc};function _G(e,t,r){if(!e){if(t instanceof Gl)return t;e=t}var n={},i=e instanceof Function;r=r||{};function o(a){var s=e[a];!s&&i&&(s=e.length==2?function(l){e(a,l)}:e),n[a]=s&&function(l){s("[xmldom "+a+"] "+l+Mh(r))}||function(){}}return o("warning"),o("error"),o("fatalError"),n}function Gl(){this.cdata=!1}function rs(e,t){t.lineNumber=e.lineNumber,t.columnNumber=e.columnNumber}Gl.prototype={startDocument:function(){this.doc=new AG().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(e,t,r,n){var i=this.doc,o=i.createElementNS(e,r||t),a=n.length;ud(this,o),this.currentElement=o,this.locator&&rs(this.locator,o);for(var s=0;s<a;s++){var e=n.getURI(s),l=n.getValue(s),r=n.getQName(s),u=i.createAttributeNS(e,r);this.locator&&rs(n.getLocator(s),u),u.value=u.nodeValue=l,o.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&&rs(this.locator,r),ud(this,r)},ignorableWhitespace:function(e,t,r){},characters:function(e,t,r){if(e=rS.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&&rs(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=rS.apply(this,arguments);var n=this.doc.createComment(e);this.locator&&rs(this.locator,n),ud(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&&rs(this.locator,i),ud(this,i),this.doc.doctype=i}},warning:function(e){console.warn("[xmldom warning] "+e,Mh(this.locator))},error:function(e){console.error("[xmldom error] "+e,Mh(this.locator))},fatalError:function(e){throw new SG(e,this.locator)}};function Mh(e){if(e)return`
+@`+(e.systemId||"")+"#[line:"+e.lineNumber+",col:"+e.columnNumber+"]"}function rS(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){Gl.prototype[e]=function(){return null}});function ud(e,t){e.currentElement?e.currentElement.appendChild(t):e.doc.appendChild(t)}cd.__DOMHandler=Gl;cd.normalizeLineEndings=iS;cd.DOMParser=oS});var ns=v(dd=>{var sS=$h();dd.DOMImplementation=sS.DOMImplementation;dd.XMLSerializer=sS.XMLSerializer;dd.DOMParser=aS().DOMParser});var uS={};Jr(uS,{CCFControlConstants:()=>lS,CCFPropertyConstants:()=>Bh,CustomControlDataType:()=>F,CustomControlNames:()=>Ti,DefaultControlNameKeys:()=>Uh,ICCModeEnum:()=>io,JSONParametersConstants:()=>qh,LookUpType:()=>fd,ManifestXMLConstants:()=>Ht,NumberType:()=>pd,Usage:()=>jo});var lS,Bh,qh,Ht,F,Uh,Ti,io,jo,fd,pd,Ho=L(()=>{"use strict";lS={CCID:"CustomControlId",CCName:"DisplayName",Properties:"Properties",Mode:"ControlMode",AvailableOn:"AvailableOn",CCDescription:"description-key",ImageURL:"preview-image",TypeGroup:"type-group",DataSets:"DataSets",EntityNameKey:"EntityNameKey",NameSpace:"Name",OfTypeKey:"OfType"},Bh={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"},qh={GroupDefinition:"GroupDefinition"},Ht={Control:"control",Resources:"resources",DisplayNameKey:"display-name-key",descriptionKey:"description-key",value:"value",name:"name",defaultKey:"default",groups:"groups",group:"group",property:"property",hidden:"hidden",required:"required",typeGroup:"type-group",type:"type",usage:"usage",ofType:"of-type",ofTypeGroup:"of-type-group",ImageURL:"preview-image",DefaultValue:"default-value",static:"static",dataset:"data-set",propertySet:"property-set",initialDatasetFetch:"initial-data-set-fetch",editable:"editable",cdsDatasetOptions:"cds-data-set-options",allowDefaultSelectedItems:"allow-default-selected-items",resettable:"resettable",isGroup:"isGroup",entityName:"entityname"};(function(e){e.Boolean="Boolean",e.Currency="Currency",e.DateAndTimeDateAndTime="DateAndTime.DateAndTime",e.DateAndTimeDateOnly="DateAndTime.DateOnly",e.Decimal="Decimal",e.Enum="Enum",e.FP="FP",e.File="File",e.Guid="Guid",e.Image="Image",e.LookupCustomer="Lookup.Customer",e.LookupOwner="Lookup.Owner",e.LookupPartyList="Lookup.PartyList",e.LookupRegarding="Lookup.Regarding",e.LookupSimple="Lookup.Simple",e.Multiple="Multiple",e.MultiSelectOptionSet="MultiSelectOptionSet",e.OptionSet="OptionSet",e.SingleLineEmail="SingleLine.Email",e.SingleLinePhone="SingleLine.Phone",e.SingleLineText="SingleLine.Text",e.SingleLineTextArea="SingleLine.TextArea",e.SingleLineTickerSymbol="SingleLine.Ticker",e.SingleLineURL="SingleLine.URL",e.TwoOptions="TwoOptions",e.WholeDuration="Whole.Duration",e.WholeLanguage="Whole.Language",e.WholeNone="Whole.None",e.WholeTimeZone="Whole.TimeZone",e.BusinessProcessFlow="BusinessProcessFlow",e.CardForm="Form.Card",e.Dashboard="Dashboard",e.FormMain="Form.Main",e.Grid="Grid",e.PowerBIReport="PowerBI.Report",e.QuickForm="Form.QuickForm",e.Search="Search",e.SearchWidget="SearchWidget",e.TimelineWall="TimelineWall",e.UnboundCustomControl="Unbound",e.WebResourceHtmlControl="WebResource.HTML"})(F||(F={}));(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"})(Uh||(Uh={}));(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"})(Ti||(Ti={}));(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"})(io||(io={}));(function(e){e[e.Bound=0]="Bound",e[e.Input=1]="Input",e[e.Output=2]="Output"})(jo||(jo={}));fd=[F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.LookupSimple],pd=[F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.FP,F.Decimal]});var is,ar,Wl=L(()=>{"use strict";is=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}},ar=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 cS={};Jr(cS,{AttributeDataSourceType:()=>zl,AttributeDataSourceTypeMask:()=>md,AttributePrecisionSource:()=>jl,EntityAttributeDataSourceType:()=>Ko,EntityAttributeDateTimeBehavior:()=>Wh,EntityAttributeImeMode:()=>Gh,EntityAttributePrecisionSource:()=>zh,EntityAttributeRequiredLevel:()=>oo,EntityAttributeType:()=>$,EntityAttributeTypeFormat:()=>W,EntityMetadataLookUpBase:()=>Di,EntityResxKeyLookUp:()=>hd,SourceTypeMask:()=>Vh});var Di,$,W,oo,Ko,Vh,zl,md,Gh,Wh,zh,jl,hd,os=L(()=>{"use strict";Wl();Di=class{name;constructor(t){this.name=t}toString(){return this.name}getName(){return this.name}getDisplayNameResourceKey(){return hd.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"})($||($={}));(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"})(W||(W={}));oo=class extends Di{constructor(t){super(t)}static get None(){return"None"}static get SystemRequired(){return"SystemRequired"}static get ApplicationRequired(){return"ApplicationRequired"}static get Recommended(){return"Recommended"}},Ko=class e extends Di{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?zl.Persistent:parseInt(zl[this.name])}},Vh=class e extends Di{constructor(t){super(t),t||(this.name=e.Undefined)}static get Undefined(){return"Undefined"}static get Simple(){return"Simple"}static get Related(){return"Related"}static get Logical(){return"Logical"}static get Calculated(){return"Calculated"}static get Rollup(){return"Rollup"}static get Invalid(){return"Invalid"}GetValue(){return parseInt(md[this.name])}};(function(e){e[e.Persistent=0]="Persistent",e[e.Calculated=1]="Calculated",e[e.Rollup=2]="Rollup"})(zl||(zl={}));(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"})(md||(md={}));Gh=class e extends Di{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Auto(){return"Auto"}static get Inactive(){return"Inactive"}static get Active(){return"Active"}static get Disabled(){return"Disabled"}},Wh=class e extends Di{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get UserLocal(){return"UserLocal"}static get DateOnly(){return"DateOnly"}static get TimeZoneIndependent(){return"TimeZoneIndependent"}},zh=class e extends Di{constructor(t){super(t),t||(this.name=e.None)}static get None(){return"None"}static get Attribute(){return"Attribute"}static get Organization(){return"Organization"}static get Currency(){return"Currency"}GetValue(){return this.name===e.None?jl.Currency:parseInt(jl[this.name])}};(function(e){e[e.Attribute=0]="Attribute",e[e.Organization=1]="Organization",e[e.Currency=2]="Currency"})(jl||(jl={}));hd=class e{static resourceKeyMap=e.initResourceKeyMap();static initResourceKeyMap(){let t=new is;return t.add($.TwoOptions,"SystemCustomization.type.bit.label"),t.add($.Customer,"SystemCustomization.type.customer.label"),t.add($.CustomerType,"SystemCustomization.type.customer.label"),t.add($.DateTime,"SystemCustomization.type.datetime.label"),t.add($.DecimalNumber,"SystemCustomization.type.decimal.label"),t.add($.FloatingPointNumber,"SystemCustomization.type.float.label"),t.add($.WholeNumber,"SystemCustomization.type.int.label"),t.add($.LookupType,"SystemCustomization.type.lookup.label"),t.add($.Lookup,"SystemCustomization.type.lookup.label"),t.add($.MultipleLineofText,"SystemCustomization.type.ntext.label"),t.add($.Currency,"SystemCustomization.type.money.label"),t.add($.Owner,"SystemCustomization.type.owner.label"),t.add($.OwnerType,"SystemCustomization.type.owner.label"),t.add($.PartyList,"SystemCustomization.type.partylist.label"),t.add($.PartyListType,"SystemCustomization.type.partylist.label"),t.add($.OptionSet,"SystemCustomization.type.picklist.label"),t.add($.State,"SystemCustomization.type.state.label"),t.add($.Status,"SystemCustomization.type.status.label"),t.add($.SingleLineofText,"SystemCustomization.type.nvarchar.label"),t.add($.UniqueIdentifier,"SystemCustomization.type.uniqueidentifier.label"),t.add($.UniqueIdentifierType,"SystemCustomization.type.uniqueidentifiertype.label"),t.add($.CalendarRulesType,"SystemCustomization.type.calendarrules.label"),t.add($.VirtualType,"SystemCustomization.type.virtual.label"),t.add($.BigInt,"SystemCustomization.type.bigint.label"),t.add($.ManagedPropertyType,"SystemCustomization.type.managedproperty.label"),t.add($.EntityNameType,"SystemCustomization.type.entityname.label"),t.add($.Image,"SystemCustomization.type.image.label"),t.add($.MultiSelectOptionSet,"SystemCustomization.type.multiselectpicklist.label"),t.add($.PrimaryNameAttributeType,"SystemCustomization.type.primaryname.label"),t.add($.LookupType,"SystemCustomization.type.lookuptype.label"),t.add($.Subject,"SystemCustomization.type.subject.label"),t.add(W.Email,"SystemCustomization.String.Format.email"),t.add(W.Text,"SystemCustomization.String.Format.text"),t.add(W.TextArea,"SystemCustomization.String.Format.textarea"),t.add(W.Url,"SystemCustomization.String.Format.url"),t.add(W.TickerSymbol,"SystemCustomization.String.Format.tickersymbol"),t.add(W.PhoneticGuide,"SystemCustomization.String.Format.phoneticguide"),t.add(W.VersionNumber,"SystemCustomization.String.Format.versionnumber"),t.add(W.Phone,"SystemCustomization.String.Format.phone"),t.add(W.None,"SystemCustomization.Integer.Format."),t.add(W.Duration,"SystemCustomization.Integer.Format.duration"),t.add(W.TimeZone,"SystemCustomization.Integer.Format.timezone"),t.add(W.Language,"SystemCustomization.Integer.Format.language"),t.add(W.Locale,"SystemCustomization.Integer.Format.language"),t.add(W.DateOnly,"SystemCustomization.DateTime.Format.date"),t.add(W.DateAndTime,"SystemCustomization.DateTime.Format.datetime"),t.add(W.Regarding,"SystemCustomization.Lookup.Format.regarding"),t.add(Ko.Persistent,"SystemCustomization.String.Source.persistent"),t.add(Ko.Calculated,"SystemCustomization.String.Source.calculated"),t.add(Ko.Rollup,"SystemCustomization.String.Source.rollup"),t.add(Ko.None,"SystemCustomization.String.Source.none"),t}static getDisplayNameResourceKey(t){return e.resourceKeyMap.getValue(t)}}});var Hh=v(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.parsePcfManifest=ot.parseControlElement=ot.parseManifestRoot=ot.firstLevel=ot.attr=ot.elementChildren=ot.manifestTypesForColumn=ot.DEFAULT_TYPE_GROUPS=void 0;var TG=ns(),H=(Ho(),Br(uS)),we=(os(),Br(cS));ot.DEFAULT_TYPE_GROUPS={numbers:[H.CustomControlDataType.WholeNone,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.Currency],text:[H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.Multiple],lookup:[H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding],dates:[H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime],allFields:[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.DateAndTimeDateOnly,H.CustomControlDataType.DateAndTimeDateAndTime,H.CustomControlDataType.FP,H.CustomControlDataType.Decimal,H.CustomControlDataType.WholeNone,H.CustomControlDataType.WholeDuration,H.CustomControlDataType.WholeTimeZone,H.CustomControlDataType.WholeLanguage,H.CustomControlDataType.LookupSimple,H.CustomControlDataType.LookupCustomer,H.CustomControlDataType.LookupOwner,H.CustomControlDataType.LookupPartyList,H.CustomControlDataType.LookupRegarding,H.CustomControlDataType.Multiple,H.CustomControlDataType.OptionSet,H.CustomControlDataType.SingleLineText,H.CustomControlDataType.SingleLineTextArea,H.CustomControlDataType.SingleLineEmail,H.CustomControlDataType.SingleLineURL,H.CustomControlDataType.SingleLineTickerSymbol,H.CustomControlDataType.SingleLinePhone]};var DG="Phone";function IG(e,t,r){switch(e){case we.EntityAttributeType.TwoOptions:return[H.CustomControlDataType.TwoOptions,H.CustomControlDataType.Boolean];case we.EntityAttributeType.Customer:case we.EntityAttributeType.CustomerType:return[H.CustomControlDataType.LookupCustomer];case we.EntityAttributeType.DateTime:return t===we.EntityAttributeTypeFormat.DateAndTime?[H.CustomControlDataType.DateAndTimeDateAndTime]:[H.CustomControlDataType.DateAndTimeDateOnly];case we.EntityAttributeType.DecimalNumber:return[H.CustomControlDataType.Decimal];case we.EntityAttributeType.FloatingPointNumber:return[H.CustomControlDataType.FP];case we.EntityAttributeType.File:return[H.CustomControlDataType.File];case we.EntityAttributeType.Image:return[H.CustomControlDataType.Image];case we.EntityAttributeType.WholeNumber:return t===we.EntityAttributeTypeFormat.Duration?[H.CustomControlDataType.WholeDuration]:t===we.EntityAttributeTypeFormat.Language?[H.CustomControlDataType.WholeLanguage]:t===we.EntityAttributeTypeFormat.TimeZone?[H.CustomControlDataType.WholeTimeZone]:[H.CustomControlDataType.WholeNone];case we.EntityAttributeType.LookupType:case we.EntityAttributeType.Lookup:return t===we.EntityAttributeTypeFormat.Regarding?[H.CustomControlDataType.LookupRegarding]:[H.CustomControlDataType.LookupSimple];case we.EntityAttributeType.MultipleLineofText:return[H.CustomControlDataType.Multiple];case we.EntityAttributeType.Currency:return[H.CustomControlDataType.Currency];case we.EntityAttributeType.Owner:case we.EntityAttributeType.OwnerType:return[H.CustomControlDataType.LookupOwner];case we.EntityAttributeType.PartyList:case we.EntityAttributeType.PartyListType:return[H.CustomControlDataType.LookupPartyList];case we.EntityAttributeType.Status:case we.EntityAttributeType.OptionSet:return[H.CustomControlDataType.OptionSet];case we.EntityAttributeType.SingleLineofText:switch(t){case we.EntityAttributeTypeFormat.Email:return[H.CustomControlDataType.SingleLineEmail];case we.EntityAttributeTypeFormat.Phone:return[H.CustomControlDataType.SingleLinePhone];case we.EntityAttributeTypeFormat.Text:return r===DG?[H.CustomControlDataType.SingleLinePhone]:[H.CustomControlDataType.SingleLineText];case we.EntityAttributeTypeFormat.TextArea:return[H.CustomControlDataType.SingleLineTextArea];case we.EntityAttributeTypeFormat.TickerSymbol:return[H.CustomControlDataType.SingleLineTickerSymbol];case we.EntityAttributeTypeFormat.Url:return[H.CustomControlDataType.SingleLineURL];default:return[H.CustomControlDataType.SingleLineText]}case we.EntityAttributeType.MultiSelectOptionSet:return[H.CustomControlDataType.MultiSelectOptionSet];default:return null}}ot.manifestTypesForColumn=IG;function jh(e){let t=[],r=e.childNodes;for(let n=0;n<r.length;n+=1)r[n].nodeType===1&&t.push(r[n]);return t}ot.elementChildren=jh;function An(e,t){return e.hasAttribute(t)?e.getAttribute(t):null}ot.attr=An;function Hn(e,...t){return jh(e).filter(r=>t.includes(r.tagName))}ot.firstLevel=Hn;function OG(e){let t=new Map;for(let r of Hn(e,"type-group"))t.set(String(An(r,"name")),Hn(r,"type").map(n=>String(n.textContent)));for(let[r,n]of t)t.set(r,n.sort());return t}function PG(e){let t=e.getElementsByTagName("AvailableOn")[0];if(!t)return{web:!0,phone:!0,tablet:!0};let r=new Set(jh(t).map(n=>n.tagName));return{web:r.has("web"),phone:r.has("phone"),tablet:r.has("tablet")}}var RG={input:"input",bound:"bound",output:"output"};function kG(e,t,r){let n=An(e,"usage"),i=n!==null&&RG[n]||"input",o=An(e,"default-value"),a=Hn(e,"value").map(m=>{let p={name:An(m,"name"),value:String(m.textContent),isDefault:An(m,"default")==="true"};return p.isDefault&&(o=p.value),p}),s=An(e,"of-type-group"),l=s!==null?t.get(s):void 0,u=s!==null&&Object.prototype.hasOwnProperty.call(ot.DEFAULT_TYPE_GROUPS,s)?ot.DEFAULT_TYPE_GROUPS[s]:void 0,c=l?[...l]:u?[...u]:[],d=An(e,"of-type"),f=d!==null?d:c.length>0?c[0]:null;return{name:An(e,"name"),usage:i,ofType:d,typeGroupName:s,ofTypeGroup:c,defaultType:f||void 0,required:An(e,"required")==="true",hidden:An(e,"hidden")==="true",defaultValue:o,enumValues:a,isPrimary:r&&i==="bound"}}function dS(e){var t;let r=[],n=a=>s=>r.push(`${a}: ${s}`),i=new TG.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the control manifest does not parse cleanly${r.length>0?` (${r[0]})`:""}`);return o}ot.parseManifestRoot=dS;function fS(e){let t=Hn(dS(e),"control")[0];if(!t)throw new Error("the control manifest has no <control> element");return t}ot.parseControlElement=fS;function LG(e){let t=fS(e),r=OG(t),n=Hn(t,"data-set"),i=Hn(t,"property"),o=Hn(t,"groups"),a=[],s=!1;for(let u of i){let c=kG(u,r,n.length===0&&!s);s=s||c.isPrimary,a.push(c)}let l=n.length>0||(a.length>0?a[0].usage==="bound":o.some(u=>Hn(u,"group").some(c=>Hn(c,"data-set","property").length>0)));return{properties:a,hasDataset:n.length>0,hasGroups:o.length>0,isBound:l,availableOn:PG(t)}}ot.parsePcfManifest=LG});var mS=v(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.readPcfColumn=ss.readControlManifest=void 0;var as=le(),$G=Hh();function Kh(e,t,r){var n;let i=(n=r?.error)===null||n===void 0?void 0:n.message;return new Error(`${e}: HTTP ${t}${typeof i=="string"?` ${i}`:""}`)}async function xG(e,t){var r;let n="/customcontrols"+(0,as.odataQuery)([["$select","name,manifest"],["$filter",`name eq '${(0,as.odataLiteral)(t)}'`]]);try{let i=await e.get(n);if(i.status<200||i.status>=300)return{kind:"unavailable",error:Kh(`reading control "${t}"`,i.status,i.body)};let o=(r=i.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(o)||o.some(l=>l===null||typeof l!="object"))return{kind:"unavailable",error:new Error(`reading control "${t}": the answer is unreadable \u2014 expected an OData 'value' array of rows`)};let a=o;if(a.length===0)return{kind:"missing"};if(a.length>1)return{kind:"ambiguous"};let s=a[0].manifest;return typeof s!="string"?{kind:"unavailable",error:new Error(`control "${t}" has no manifest`)}:{kind:"found",value:(0,$G.parsePcfManifest)(s)}}catch(i){return{kind:"unavailable",error:i instanceof Error?i:new Error(String(i))}}}ss.readControlManifest=xG;var FG=new Map([["StringType",{cast:"StringAttributeMetadata",select:"Format,FormatName"}],["MemoType",{cast:"MemoAttributeMetadata",select:"Format"}],["IntegerType",{cast:"IntegerAttributeMetadata",select:"Format"}],["DateTimeType",{cast:"DateTimeAttributeMetadata",select:"Format"}],["LookupType",{cast:"LookupAttributeMetadata",select:"Format"}]]);function pS(e){let t=e?.Value;return typeof t=="string"?t:void 0}async function MG(e,t,r,n){var i;let o=`/EntityDefinitions(LogicalName='${(0,as.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,as.odataPathLiteral)(r)}')`,a=n?.requireCreateEligibility===!0;try{let s=await e.get(o+(0,as.odataQuery)([["$select",`LogicalName,AttributeType,AttributeTypeName,IsValidForForm,IsPrimaryId${a?",IsValidForCreate":""}`]]));if(s.status===404)return{kind:"missing"};if(s.status<200||s.status>=300)return{kind:"unavailable",error:Kh(`reading column "${r}"`,s.status,s.body)};let l=(i=s.body)!==null&&i!==void 0?i:{},u=pS(l.AttributeTypeName);if(!u)return{kind:"unavailable",error:new Error(`column "${r}" has no AttributeTypeName`)};if(a&&typeof l.IsValidForCreate!="boolean")return{kind:"unavailable",error:new Error(`column "${r}" has no IsValidForCreate`)};let c={logicalName:typeof l.LogicalName=="string"?l.LogicalName:r,attributeTypeName:u,isValidForForm:l.IsValidForForm===!0,isPrimaryId:l.IsPrimaryId===!0,...a?{isValidForCreate:l.IsValidForCreate}:{}},d=FG.get(u);if(d){let f=await e.get(`${o}/Microsoft.Dynamics.CRM.${d.cast}`+(0,as.odataQuery)([["$select",d.select]]));if(f.status<200||f.status>=300)return{kind:"unavailable",error:Kh(`reading the format of column "${r}"`,f.status,f.body)};let m=f.body;if(m===null||typeof m!="object"||m.Format!==null&&typeof m.Format!="string")return{kind:"unavailable",error:new Error(`reading the format of column "${r}": the answer is unreadable \u2014 expected its Format (a string or null)`)};typeof m.Format=="string"&&(c.format=m.Format);let p=pS(m.FormatName);p&&(c.formatName=p)}return{kind:"found",value:c}}catch(s){return{kind:"unavailable",error:s instanceof Error?s:new Error(String(s))}}}ss.readPcfColumn=MG});var Jo=v(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});gd.DEFAULT_LCID=void 0;gd.DEFAULT_LCID=1033});var pt=v(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.assignMissingIds=Kn.pointerTouchesValueMap=Kn.isValueMapKey=Kn.newId=void 0;var UG=Ma();function hS(){return globalThis.crypto.randomUUID().toLowerCase()}Kn.newId=hS;function BG(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Yh=new Set(["parameters","bag","expression","rawExpression","lookupValue","stepLabels","genPage","inputData","customControl"]);function qG(e){return Yh.has(e)}Kn.isValueMapKey=qG;function VG(e){return UG.JsonPointer.parse(e).some(t=>Yh.has(t))}Kn.pointerTouchesValueMap=VG;function GG(e){return Jh(e),e}Kn.assignMissingIds=GG;function Jh(e){if(Array.isArray(e)){e.forEach(t=>Jh(t));return}if(BG(e)){(typeof e.id!="string"||e.id.length===0)&&(e.id=hS());for(let t of Object.keys(e))t==="id"||Yh.has(t)||Jh(e[t])}}});var Kl=v(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.sendChangeSet=Kt.isChangeSetLockRefusal=Kt.partResponse=Kt.postChangeSet=Kt.parseChangeSetParts=Kt.parseChangeSetStatuses=Kt.renderChangeSet=void 0;var Ii=Q(),Yo=ye(),gS=pt(),Hl=le();function Qh(e,t){let r=`batch_${(0,gS.newId)()}`,n=`changeset_${(0,gS.newId)()}`,i=t.map((s,l)=>String(l+1)),o=t.map((s,l)=>{var u,c;if(s.rawBody!==void 0&&s.contentType===void 0)throw new Ii.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a raw body but no Content-Type`);let d=(u=s.rawBody)!==null&&u!==void 0?u:s.body===void 0?void 0:JSON.stringify(s.body);if(d!==void 0&&(d.includes(`--${n}`)||d.includes(`--${r}`)))throw new Ii.InvalidArgumentError(`batch operation ${s.method} ${s.path} has a body containing the batch boundary`);(0,Hl.assertNoControlChars)(s.path,"batch operation path"),s.etag&&(0,Hl.assertNoControlChars)(s.etag,"batch operation etag");let f=Object.entries((c=s.headers)!==null&&c!==void 0?c:{});for(let[m,p]of f)if((0,Hl.assertNoControlChars)(m,"batch operation header name"),(0,Hl.assertNoControlChars)(p,"batch operation header value"),!/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/.test(m))throw new Ii.InvalidArgumentError(`batch operation header name '${m}' is not a valid HTTP token`);return s.contentType!==void 0&&(0,Hl.assertNoControlChars)(s.contentType,"batch operation content type"),[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${i[l]}`,"",`${s.method} ${e.apiUrl(s.path)} HTTP/1.1`,...d===void 0?[]:[`Content-Type: ${s.rawBody!==void 0?s.contentType:"application/json;type=entry"}`],...e.solutionName?[`MSCRM.SolutionUniqueName: ${e.solutionName}`]:[],...s.etag?[`If-Match: ${s.etag}`]:[],...f.map(([m,p])=>`${m}: ${p}`),"",...d===void 0?[]:[d]].join(`\r
`)});return{body:[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...o,`--${n}--`,`--${r}--`,""].join(`\r
-`),batchId:r,contentIds:i}}Er.renderChangeSet=Wh;function sS(e,t){var r;return(r=zh(e,t))===null||r===void 0?void 0:r.map(n=>n.status)}Er.parseChangeSetStatuses=sS;function zh(e,t){var r,n,i,o;if(typeof e!="string"||e.length===0)return;let a=(r=/^--(\S+)\r?\n/.exec(e))===null||r===void 0?void 0:r[1];if(a===void 0||!e.trimEnd().endsWith(`--${a}--`))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===a)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 f of l.slice(1)){if(f.startsWith("--"))break;let m=f.indexOf(`\r
+`),batchId:r,contentIds:i}}Kt.renderChangeSet=Qh;function bS(e,t){var r;return(r=yd(e,t))===null||r===void 0?void 0:r.map(n=>n.status)}Kt.parseChangeSetStatuses=bS;function yd(e,t){var r,n,i,o;if(typeof e!="string"||e.length===0)return;let a=(r=/^--(\S+)\r?\n/.exec(e))===null||r===void 0?void 0:r[1];if(a===void 0||!e.trimEnd().endsWith(`--${a}--`))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===a)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 f of l.slice(1)){if(f.startsWith("--"))break;let m=f.indexOf(`\r
\r
-`);if(m===-1)return;let p=f.slice(0,m),h=f.slice(m+4);if(!/^Content-Type:\s*application\/http\b/im.test(p))return;let g=/^HTTP\/1\.[01] (\d{3})\b/.exec(h);if(!g||((i=h.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let b=(o=/^Content-ID:\s*(\S+)/im.exec(p))===null||o===void 0?void 0:o[1];if(b===void 0||d.has(b)||!u.has(b))return;d.add(b),c.push({status:Number(g[1]),text:h,contentId:b})}return c.length===0?void 0:c}Er.parseChangeSetParts=zh;async function kG(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:o}=Wh(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,Gh.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new oo.ConnectionError(s,a.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=sS(a.body,o);if(l===void 0)throw new oo.ConnectionError(s,a.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 oo.ConnectionError(s,a.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 oo.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}Er.postChangeSet=kG;function lS(e){let t=e.text.replace(/\r\n/g,`
+`);if(m===-1)return;let p=f.slice(0,m),h=f.slice(m+4);if(!/^Content-Type:\s*application\/http\b/im.test(p))return;let g=/^HTTP\/1\.[01] (\d{3})\b/.exec(h);if(!g||((i=h.match(/^HTTP\/1\.[01] \d{3}\b/gm))!==null&&i!==void 0?i:[]).length!==1)return;let b=(o=/^Content-ID:\s*(\S+)/im.exec(p))===null||o===void 0?void 0:o[1];if(b===void 0||d.has(b)||!u.has(b))return;d.add(b),c.push({status:Number(g[1]),text:h,contentId:b})}return c.length===0?void 0:c}Kt.parseChangeSetParts=yd;async function WG(e,t,r){if(t.length===0)return;let{body:n,batchId:i,contentIds:o}=Qh(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch");if((0,Yo.ensureSuccess)(a,s),typeof a.body!="string"||a.body.length===0)throw new Ii.ConnectionError(s,a.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=bS(a.body,o);if(l===void 0)throw new Ii.ConnectionError(s,a.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 Ii.ConnectionError(s,a.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 Ii.ConnectionError(s,u,`atomic write of ${r} was rolled back: the change set reported HTTP ${u}`)}Kt.postChangeSet=WG;function Xh(e){let t=e.text.replace(/\r\n/g,`
`),r=t.indexOf(`
`),n=r===-1?t:t.slice(0,r),i=(r===-1?"":t.slice(r+2)).trim(),o={};for(let s of n.split(`
-`).slice(1)){let l=s.indexOf(":");l>0&&(o[s.slice(0,l).trim()]=s.slice(l+1).trim())}let a=i===""?void 0:i;if(i!=="")try{a=JSON.parse(i)}catch{}return{status:e.status,headers:o,body:a}}Er.partResponse=lS;async function $G(e,t,r){let{body:n,batchId:i,contentIds:o}=Wh(e,t),a=await e.postBatch(n,i),s=e.apiUrl("/$batch"),l=zh(a.body,o),u=l?.find(c=>c.status<200||c.status>=300);if(u&&(0,Gh.ensureSuccess)(lS(u),e.apiUrl(t[o.indexOf(u.contentId)].path)),(0,Gh.ensureSuccess)(a,s),!l||l.length!==t.length)throw new oo.ConnectionError(s,a.status,`atomic write of ${r} cannot be confirmed: the $batch response ${l?`reported ${l.length} result(s) for ${t.length} operation(s)`:"could not be parsed"}, so the outcome is unknown`);return o.map(c=>l.find(d=>d.contentId===c))}Er.sendChangeSet=$G});var cd=v(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.updateTable=ie.deleteAlternateKey=ie.createAlternateKey=ie.deleteGlobalOptionSet=ie.createGlobalOptionSet=ie.deleteRelationship=ie.deleteColumn=ie.updateColumn=ie.deleteTable=ie.createRelationship=ie.insertStatusValue=ie.createCustomerColumn=ie.createColumns=ie.setColumnVisualization=ie.getColumnVisualization=ie.createColumn=ie.createTable=ie.resolveEntitySetName=ie.pluralFallback=void 0;var _e=ye(),te=se(),Kn=Ho(),me=Q(),xG=Wl(),FG={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 Ze(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:MG(e,t)}}var uS=65535;function MG(e,t){let r=(o,a)=>({"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:o,LanguageCode:a});if(typeof e=="string")return[r(e,t)];let n=Object.entries(e);if(!n.length)throw new me.InvalidArgumentError("a localized label must contain at least one language");let i=new Set;return n.map(([o,a])=>{if(!/^[1-9]\d*$/.test(o))throw new me.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>uS)throw new me.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${uS})`);if(i.has(s))throw new me.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new me.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(a,s)})}function mS(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new me.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}ie.pluralFallback=mS;function zl(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}var cS=["None","ApplicationRequired","Recommended"];function Kh(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function dS(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function jl(e){let t=(0,_e.readCreatedId)(e,"MetadataId");if(!t)throw new me.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function UG(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b,w,E,S,P,L,I,D,O,x;if(t.defaultValue!==void 0&&e!=="boolean")throw new me.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new me.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:(o=t.maxLength)!==null&&o!==void 0?o:2e3,Format:"TextArea"};case"integer":return{"@odata.type":"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",AttributeType:"Integer",AttributeTypeName:{Value:"IntegerType"},Format:(a=t.integerFormat)!==null&&a!==void 0?a:"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:(f=t.precision)!==null&&f!==void 0?f:2,MinValue:(m=t.minValue)!==null&&m!==void 0?m:-1e11,MaxValue:(p=t.maxValue)!==null&&p!==void 0?p:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(h=t.precision)!==null&&h!==void 0?h:2,PrecisionSource:2,MinValue:(g=t.minValue)!==null&&g!==void 0?g:0,MaxValue:(b=t.maxValue)!==null&&b!==void 0?b:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(w=t.defaultValue)!==null&&w!==void 0?w:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:Ze((E=t.trueLabel)!==null&&E!==void 0?E:"Yes",r)},FalseOption:{Value:0,Label:Ze((S=t.falseLabel)!==null&&S!==void 0?S:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(P=t.dateFormat)!==null&&P!==void 0?P:"DateAndTime"};case"choice":return fS(t,r,!1);case"multiChoice":return fS(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(L=t.maxSizeKb)!==null&&L!==void 0?L:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(I=t.isPrimaryImage)!==null&&I!==void 0?I:!1,MaxSizeInKB:(D=t.maxSizeKb)!==null&&D!==void 0?D:10240};case"autonumber":if(!(!((O=t.autoNumberFormat)===null||O===void 0)&&O.trim()))throw new me.InvalidArgumentError(`createColumn: an 'autonumber' column needs an 'autoNumberFormat' (e.g. 'CDS-{SEQNUM:5}'), but '${t.schemaName}' has none \u2014 without one Dataverse would create a plain text column.`);return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(x=t.maxLength)!==null&&x!==void 0?x:100,AutoNumberFormat:t.autoNumberFormat};default:throw new me.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function fS(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,te.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new me.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(o=>({Value:o.value,Label:Ze(o.label,t)}))},i}var jh=new WeakMap;async function BG(e,t){var r,n;let i=(r=jh.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')${(0,te.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new me.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,te.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=jh.get(e);return l||(l=new Map,jh.set(e,l)),l.set(t,s),s}ie.resolveEntitySetName=BG;async function qG(e,t){var r,n,i,o,a,s,l,u,c,d,f,m,p,h,g;let b=t.primaryColumnRequired;if(b!==void 0&&!cS.includes(b))throw new me.InvalidArgumentError(`createTable: 'primaryColumnRequired' must be one of ${cS.join(", ")}; got '${String(b)}'.`);let w=b!==void 0&&b!=="None";if(w&&!t.primaryColumnAutoNumberFormat&&!e.supportsPut)throw new me.InvalidArgumentError(`createTable: 'primaryColumnRequired: ${b}' on a plain text primary column needs an HttpClient that implements put(): the platform ignores the level in the create, so the SDK sets it with an update.`);let E=(r=t.languageCode)!==null&&r!==void 0?r:Kn.DEFAULT_LCID,S=Kh(t.schemaName),P=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${S}_Name`,L={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:P,RequiredLevel:zl(b??"None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:Ze((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",E),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(L.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&bS(t.columns,"createTable");let I={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:Ze(t.displayName,E),DisplayCollectionName:Ze((a=t.pluralName)!==null&&a!==void 0?a:mS(t.displayName),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:[L,...((c=t.columns)!==null&&c!==void 0?c:[]).map(bn=>Jh(bn,E))]};t.description&&(I.Description=Ze(t.description,E));let D="/EntityDefinitions",O=(0,_e.ensureSuccess)(await e.post(D,I),e.apiUrl(D)),x=jl(O),K=`/EntityDefinitions(${x})`+(0,te.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),Re=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),qt=Math.max(0,(f=t.readBackDelayMs)!==null&&f!==void 0?f:1e3),ge=w?` Its primary column's requirement level '${b}' was NOT applied or checked: once the table is readable, set it with updateColumn('${t.schemaName.toLowerCase()}', '${P.toLowerCase()}', { required: '${b}' }).`:"",je;try{je=await hS(e,K,Re,qt)}catch(bn){throw w?(0,me.attachCause)(new me.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}), but reading it back failed (${bn instanceof Error?bn.message:String(bn)}).${ge} Do NOT re-run the create \u2014 it will collide on the schema name.`),bn):bn}if(!je)throw new me.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}) but its metadata was still not readable after ${Re} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${x}) once the environment catches up, or raise 'readBackAttempts'.${ge}`);let de=je.body,He={logicalName:(m=de.LogicalName)!==null&&m!==void 0?m:t.schemaName.toLowerCase(),metadataId:x,entitySetName:(p=de.EntitySetName)!==null&&p!==void 0?p:"",primaryIdAttribute:(h=de.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=de.PrimaryNameAttribute)!==null&&g!==void 0?g:P.toLowerCase()};return w&&(He.primaryColumnRequired=await VG(e,t.schemaName,He,b,Re,qt)),He}ie.createTable=qG;async function hS(e,t,r,n){for(let i=1;i<=r;i+=1){let o=await e.get(t);if(o.status>=200&&o.status<300)return o;o.status!==404&&(0,_e.ensureSuccess)(o,e.apiUrl(t)),i<r&&n>0&&await new Promise(a=>setTimeout(a,n))}}async function VG(e,t,r,n,i,o){let a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(r.logicalName)}')/Attributes(LogicalName='${(0,te.odataPathLiteral)(r.primaryNameAttribute)}')`+(0,te.odataQuery)([["$select","RequiredLevel"]]),s=async()=>{var d,f;let m=await hS(e,a,i,o),p=(f=(d=m?.body)===null||d===void 0?void 0:d.RequiredLevel)===null||f===void 0?void 0:f.Value;return typeof p=="string"?p:void 0},l="read",u,c=d=>{let f=`its primary column '${r.primaryNameAttribute}'`,m=l==="read"?`${f} could not be read back`:l==="update"?`${f} read '${u??"(unreadable)"}' and the update to '${n}' failed, so it may or may not carry it`:u===void 0?`${f} was updated to '${n}' but could not be read back`:`${f} is still '${u}' after the update to '${n}'`;return new me.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t}' WAS CREATED (MetadataId ${r.metadataId}), but ${m}${d?` (${d})`:""}. Do NOT re-run the create \u2014 it will collide on the schema name. Check the level, and set it with updateColumn('${r.logicalName}', '${r.primaryNameAttribute}', { required: '${n}' }).`)};try{u=await s(),u!==n&&(l="update",await ES(e,r.logicalName,r.primaryNameAttribute,{required:n}),l="verify",u=await s())}catch(d){throw l==="verify"&&(u=void 0),(0,me.attachCause)(c(d instanceof Error?d.message:String(d)),d)}if(u!==n)throw c(u===void 0?"the answer had no RequiredLevel":void 0);return n}function Jh(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,o={...UG(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:zl((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:Ze(e.displayName,i)};return e.description&&(o.Description=Ze(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),gS(o,e),o}function gS(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 GG(e,t,r){var n;let i=Jh(r,(n=r.languageCode)!==null&&n!==void 0?n:Kn.DEFAULT_LCID),o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,a=(0,_e.ensureSuccess)(await e.post(o,i),e.apiUrl(o)),s={logicalName:r.schemaName.toLowerCase(),metadataId:jl(a)};if(r.visualization&&r.visualization!=="None")try{await CS(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new me.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(0,me.attachCause)(u,l),u}return s}ie.createColumn=GG;var os="/controlconfigurations",yS="CustomRenderersConfiguration",Hh={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 bS(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new me.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 vS(e){return JSON.stringify({type:Hh[e]})}function WG(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(Hh).find(i=>Hh[i]===r);return n??"None"}async function wS(e,t,r){var n,i;let o=`entitylogicalname eq '${(0,te.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,te.odataLiteral)(r)}'`,a=`${os}${(0,te.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",o]])}`,l=(i=(n=(0,_e.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],u=r.toLowerCase();return l.filter(c=>{var d,f;return((f=(d=c.Attribute)===null||d===void 0?void 0:d.logicalname)===null||f===void 0?void 0:f.toLowerCase())===u})}async function zG(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,a=(n=(0,_e.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!a)throw new me.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,te.normalizeGuid)(a,"MetadataId")}async function CS(e,t,r,n,i){let o={name:yS,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:vS(i),"[email protected]":`/attributes(${(0,te.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,_e.ensureSuccess)(await e.post(os,o),e.apiUrl(os))}async function jG(e,t,r){var n;let i=await wS(e,t,r);return WG((n=i[0])===null||n===void 0?void 0:n.metadatajson)}ie.getColumnVisualization=jG;async function HG(e,t,r,n){let o=(await wS(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of o){let c=`${os}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,_e.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,l=await zG(e,t,r);if(a){let u=`${os}(${(0,te.normalizeGuid)(a,"controlconfigurationid")})`,c={name:yS,metadatajson:vS(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,_e.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await CS(e,t,r,l,n);for(let u of s){let c=`${os}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,_e.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}ie.setColumnVisualization=HG;async function KG(e,t,r){if(r.length===0)return;if(bS(r,"createColumns"),!e.supportsAtomicBatch)throw new me.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,te.odataPathLiteral)(t)}')/Attributes`;await(0,xG.postChangeSet)(e,r.map(i=>{var o;return{method:"POST",path:n,body:Jh(i,(o=i.languageCode)!==null&&o!==void 0?o:Kn.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}ie.createColumns=KG;async function JG(e,t,r){var n,i,o,a;let s=(n=r.languageCode)!==null&&n!==void 0?n:Kn.DEFAULT_LCID,l=Kh(r.schemaName),u=(i=r.accountRelationshipName)!==null&&i!==void 0?i:`${l}_${t}_account`,c=(o=r.contactRelationshipName)!==null&&o!==void 0?o:`${l}_${t}_contact`,d={Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.ComplexLookupAttributeMetadata",SchemaName:r.schemaName,DisplayName:Ze(r.displayName,s),RequiredLevel:zl((a=r.required)!==null&&a!==void 0?a:"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,_e.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}ie.createCustomerColumn=JG;async function YG(e,t,r){var n,i,o,a,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:Kn.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:Ze(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,_e.ensureSuccess)(await e.post("/InsertStatusValue",u),e.apiUrl("/InsertStatusValue"));return Number((s=(a=(o=c.body)===null||o===void 0?void 0:o.NewOptionValue)!==null&&a!==void 0?a:r.value)!==null&&s!==void 0?s:0)}ie.insertStatusValue=YG;async function QG(e,t){var r,n,i,o,a;let s=(r=t.languageCode)!==null&&r!==void 0?r:Kn.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new me.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let f=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${Kh(t.schemaName)}_${t.referencedEntity}Id`;u=f.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:f,RequiredLevel:zl((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:Ze((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new me.InvalidArgumentError("ManyToMany relationship requires entity1 and entity2");l={"@odata.type":"Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata",SchemaName:t.schemaName,IntersectEntityName:(a=t.intersectEntityName)!==null&&a!==void 0?a:t.schemaName.toLowerCase(),Entity1LogicalName:t.entity1,Entity2LogicalName:t.entity2}}let c="/RelationshipDefinitions",d=(0,_e.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:jl(d),lookupLogicalName:u}}ie.createRelationship=QG;async function XG(e,t){let r=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`;(0,_e.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteTable=XG;async function ES(e,t,r,n){var i,o;let a=(i=n.languageCode)!==null&&i!==void 0?i:Kn.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,_e.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=FG[(o=c.AttributeType)!==null&&o!==void 0?o:""];if(!c.MetadataId||!d){let g=c.MetadataId?c.AttributeType?`type '${c.AttributeType}' not supported`:"the attribute read returned no AttributeType":"the attribute read returned no MetadataId";throw new me.InvalidArgumentError(`cannot update column '${r}' on '${t}' (${g})`)}let f=(0,te.normalizeGuid)(c.MetadataId,"MetadataId"),m=`${s}(${f})/${d}`,p=(0,_e.ensureSuccess)(await e.get(m),e.apiUrl(m)).body;for(let g of Object.keys(p))g.startsWith("@odata.")&&delete p[g];if(p["@odata.type"]=d,n.displayName!==void 0&&(p.DisplayName=Ze(n.displayName,a)),n.description!==void 0&&(p.Description=Ze(n.description,a)),n.required!==void 0&&(p.RequiredLevel=zl(n.required)),n.maxLength!==void 0&&(p.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(p.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new me.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 me.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(p.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(p.Format=n.integerFormat),gS(p,n);let h=`${s}(${f})`;(0,_e.ensureSuccess)(await e.put(h,p,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}ie.updateColumn=ES;async function ZG(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,o=`${i}(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new me.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,_e.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteColumn=ZG;async function e9(e,t){var r,n,i;let o=`/RelationshipDefinitions${(0,te.odataQuery)([["$filter",`SchemaName eq '${(0,te.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(n=(r=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).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 me.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,_e.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteRelationship=e9;async function pS(e,t){var r;let n=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(n);if(i.status===404)return;let a=(r=(0,_e.ensureSuccess)(i,e.apiUrl(n)).body)===null||r===void 0?void 0:r.MetadataId;return a?(0,te.normalizeGuid)(a,"MetadataId"):void 0}async function t9(e,t){var r;let n=t.name.toLowerCase(),i=await pS(e,n);if(i)return{name:n,metadataId:i};let o=(r=t.languageCode)!==null&&r!==void 0?r:Kn.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:Ze(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:Ze(l.label,o)}))};t.description&&(a.Description=Ze(t.description,o));let s="/GlobalOptionSetDefinitions";try{let l=(0,_e.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:n,metadataId:jl(l)}}catch(l){let u;try{u=await pS(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}ie.createGlobalOptionSet=t9;async function r9(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t.toLowerCase())}')`;(0,_e.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteGlobalOptionSet=r9;async function n9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Kn.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:Ze(r.displayName,i),KeyAttributes:r.keyAttributes},a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,s=(0,_e.ensureSuccess)(await e.post(a,o),e.apiUrl(a));return{logicalName:r.schemaName.toLowerCase(),metadataId:jl(s)}}ie.createAlternateKey=n9;async function i9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,o=`${i}(LogicalName='${(0,te.odataPathLiteral)(r.toLowerCase())}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new me.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,_e.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteAlternateKey=i9;async function o9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Kn.DEFAULT_LCID,o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`,s=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body,l=s.MetadataId;if(!l)throw new me.InvalidArgumentError(`table '${t}' not found`);let u=(0,te.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=Ze(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=Ze(r.pluralName,i)),r.description!==void 0&&(s.Description=Ze(r.description,i)),r.auditEnabled!==void 0&&dS(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&dS(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,_e.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}ie.updateTable=o9});var so=v(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.rebuildRaw=Ar.assembleChildren=Ar.spliceChildren=Ar.mergeAttrs=Ar.rawFromNode=Ar.emptyBag=void 0;var ao=Q(),AS=1e6,fd=512;function a9(){return{a:[],c:[]}}Ar.emptyBag=a9;function SS(e,t=0){if(t>fd)throw new ao.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${fd}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>SS(r,t+1))}}Ar.rawFromNode=SS;function s9(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))),o=new Set,a=[];for(let[s,l]of e)i.has(s)||(n.has(s)?a.push([s,n.get(s)]):a.push([s,l]),o.add(s));for(let[s,l]of t)o.has(s)||(a.push([s,l]),o.add(s));return a}Ar.mergeAttrs=s9;function dd(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>AS)throw new ao.InvalidArgumentError(`Bag child index must be an integer in [0, ${AS}] (got ${String(l)})`);if(r.has(l))throw new ao.InvalidArgumentError(`Duplicate bag child index ${l}`);r.add(l)}let n=[...e].sort((s,l)=>s.i-l.i),i=[],o=0,a=0;for(let s of n){for(;a<s.i&&o<t.length;)i.push(t[o]),o+=1,a+=1;a<s.i&&(a=s.i),i.push(s.node),a+=1}for(;o<t.length;)i.push(t[o]),o+=1;return i}Ar.spliceChildren=dd;function l9(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:dd(e.w.c,t)};return dd(e.c,[r])}return dd(e.c,t)}Ar.assembleChildren=l9;function NS(e,t,r,n=0){if(n>fd)throw new ao.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${fd}`);u9(e,n);let i=t.make(e.n,r);for(let[o,a]of e.a)t.setProp(i,o,a);for(let o of e.c)t.addChild(i,NS(o,t,i,n+1));return i}Ar.rebuildRaw=NS;function u9(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new ao.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new ao.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 ao.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 ao.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var lo=v(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});pd.installDomShim=void 0;var _S=es(),TS=!1,c9={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 d9(){if(TS)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=_S.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=_S.XMLSerializer),typeof e.Node>"u"&&(e.Node=c9),TS=!0}pd.installDomShim=d9});var uo=v(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.projectElementBag=et.serializeNode=et.domEngine=et.nodeLikeFromDom=et.parseXmlRoot=et.EMPTY_FORM_SENTINEL=et.TEXT_SENTINEL=void 0;var f9=so(),as=Q(),p9=lo();et.TEXT_SENTINEL="#text";et.EMPTY_FORM_SENTINEL="#empty";var hd=new WeakSet;function m9(e,t){(0,p9.installDomShim)();let r=e&&e.trim()!==""?e:t,n=new DOMParser().parseFromString(r,"text/xml"),i=n.documentElement;if(!i)throw new as.InvalidArgumentError("XML source has no root element (empty or malformed input)");return h9(r),y9(n),v9(i),w9(i),A9(i,r),i}et.parseXmlRoot=m9;function h9(e){let t=e.search(/\S/);if(t!==-1&&e[t]!=="<")throw IS(3)}var g9=["http://www.mozilla.org/newlayout/xml/parsererror.xml","http://www.w3.org/1999/xhtml"];function y9(e){var t;for(let r of g9){let n=e.getElementsByTagNameNS(r,"parsererror")[0];if(n){let i=((t=n.textContent)!==null&&t!==void 0?t:"").replace(/\s+/g," ").trim().slice(0,200);throw new as.InvalidArgumentError(`XML source is not well-formed (${i||"the XML parser reported an error"}), so it cannot be round-tripped`)}}}var b9=new Set([1,3]);function v9(e){let t=[e];for(;t.length>0;){let n=t.pop().childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];if(!b9.has(o.nodeType))throw new as.InvalidArgumentError(`Unsupported XML node type ${o.nodeType} (CDATA / comment / processing-instruction) is outside the hybrid projection's lossless grammar and cannot be round-tripped`);o.nodeType===1&&t.push(o)}}}function w9(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 o=0;o<i.length;o+=1){let a=i[o];if(a!==e&&!(a.nodeType===3&&((r=a.nodeValue)!==null&&r!==void 0?r:"").trim()===""))throw IS(a.nodeType)}}function IS(e){return new as.InvalidArgumentError(`Unsupported document-level XML node (type ${e}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}function C9(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 E9(e){let t=[],r=[e];for(;r.length>0;){let n=r.pop();t.push(n);let i=n.childNodes;for(let o=i.length-1;o>=0;o-=1){let a=i[o];a.nodeType===1&&r.push(a)}}return t}function OS(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 A9(e,t){let r=C9(t),n=E9(e),i=Math.min(r.length,n.length);for(let o=0;o<i;o+=1){if(r[o])continue;let a=n[o];OS(a)||hd.add(a)}}function Yh(e){let t=e.nodeType===3;return{getNodeName:()=>t?et.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:et.TEXT_SENTINEL,value:(r=e.nodeValue)!==null&&r!==void 0?r:""}];let n=e.attributes,i=[];for(let o=0;o<n.length;o+=1)i.push({key:n[o].name,value:n[o].value});return hd.has(e)&&!OS(e)&&i.push({key:et.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 o=n[i];(o.nodeType===1||o.nodeType===3)&&r.push(Yh(o))}return r}}}et.nodeLikeFromDom=Yh;function S9(e){return{make:t=>t===et.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===et.EMPTY_FORM_SENTINEL?hd.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}et.domEngine=S9;function PS(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 md(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw md(r);t+=1;continue}if(r>=56320&&r<=57343)throw md(r)}}function md(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new as.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 N9(e){return PS(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\r/g,"&#xD;").replace(/\n/g,"&#xA;").replace(/\t/g,"&#x9;")}function _9(e){return PS(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function T9(e){return RS(e,0)}et.serializeNode=T9;var DS=512;function RS(e,t){var r;if(t>DS)throw new as.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${DS}`);if(e.nodeType===3)return _9((r=e.nodeValue)!==null&&r!==void 0?r:"");let n=e,i="<"+n.tagName,o=n.attributes;for(let l=0;l<o.length;l+=1)i+=" "+o[l].name+'="'+N9(o[l].value)+'"';let a=[],s=n.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];(u.nodeType===1||u.nodeType===3)&&a.push(u)}if(a.length===0)return hd.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of a)i+=RS(l,t+1);return i+"</"+n.tagName+">"}function D9(e){let t=Yh(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,f9.rawFromNode)(r)}))}}et.projectElementBag=D9});var en=v(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.rejectUnknownKeys=Ht.childObjects=Ht.optionalGuidId=Ht.optionalEnum=Ht.eachObject=Ht.issue=Ht.isJsonObject=void 0;function LS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}Ht.isJsonObject=LS;function ss(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}Ht.issue=ss;function kS(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{LS(o)?i.push({node:o,index:a}):n.push(ss(`${t}/${a}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}Ht.eachObject=kS;function I9(e,t,r,n,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!r.includes(a))&&o.push(ss(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}Ht.optionalEnum=I9;var O9=/^(?:\{[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 P9(e,t,r,n,i){let o=e[t];typeof o=="string"&&o!==""&&!O9.test(o)&&i.push(ss(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${o}'`))}Ht.optionalGuidId=P9;function R9(e,t,r,n,i){let o=e[t],a=`${r}/${t}`;return o===void 0?[]:Array.isArray(o)?kS(o,a,n,i):(i.push(ss(a,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}Ht.childObjects=R9;function L9(e,t,r,n,i,o={}){var a,s;for(let l of Object.keys(e)){if(t.has(l))continue;let u=(a=o.elsewhere)===null||a===void 0?void 0:a[l],c=(s=o.unsupported)===null||s===void 0?void 0:s[l],d=u?` '${l}' is a ${u} key \u2014 set it on the ${u} instead.`:c?` ${c}`:` Put values the typed layer does not model in '${n}.bag', which round-trips them verbatim.`;i.push(ss(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}Ht.rejectUnknownKeys=L9});var wd=v(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.genPageEmbedIssues=B.setUniqueId=B.mintEmbedIdentity=B.authoredUniqueId=B.hasGenPage=B.applyEmbedCellDefaults=B.applyEmbedControlDefaults=B.mayCommitEmbedState=B.commitEmbedState=B.reconcileEmbedDescriptions=B.embedAppendIndex=B.activeEmbedBindings=B.projectGenPageEmbeds=B.isRecognizedEmbed=B.isUnbound=B.effectiveClassId=B.effectiveFormType=B.inputDataFrom=B.classifyBinding=B.isStaticParameter=B.entryParameter=B.pageEntries=B.descriptionFor=B.descriptionsRegion=B.controlUniqueIds=B.controlUniqueId=B.typedCellSites=B.typedCells=B.rawText=B.rawAttr=B.normGuid=B.GENPAGE_FORM_FACTORS=B.GENPAGE_EMBED_ROWSPAN=B.GENPAGE_CONTROL_NAME=B.CUSTOM_CONTROL_CLASS_ID=void 0;var k9=es(),$9=$a(),Qh=dt(),tn=en();B.CUSTOM_CONTROL_CLASS_ID="F9A8A302-114E-466A-B582-6771B2AE0D92";B.GENPAGE_CONTROL_NAME="MscrmControls.UxAgentControl";B.GENPAGE_EMBED_ROWSPAN=6;B.GENPAGE_FORM_FACTORS=["2","0","1"];var x9=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function Sr(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),x9.test(t)?t:""}B.normGuid=Sr;function co(e,t){let r=Ae(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=co;function Kl(e){return Ae(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=Kl;function Ae(e){return Array.isArray(e)?e:[]}function ng(e,t){let r=Ae(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function FS(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function MS(e){return An(e).map(t=>t.cell)}B.typedCells=MS;function An(e){let t=[];return Ae(e?.tabs).forEach((r,n)=>{Ae(Pe(r)?r.columns:void 0).forEach((i,o)=>{Ae(Pe(i)?i.sections:void 0).forEach((a,s)=>{Ae(Pe(a)?a.rows:void 0).forEach((l,u)=>{Ae(Pe(l)?l.cells:void 0).forEach((c,d)=>{Pe(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${o}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}B.typedCellSites=An;function Di(e){return Pe(e)?Sr(ng(e.bag,"uniqueid")):""}B.controlUniqueId=Di;function F9(e){let t=new Set;for(let{cell:r}of An(e)){let n=Yo(r.control)?Di(r.control):"";n&&t.add(n)}return t}function M9(e){let t=new Map;for(let{cell:r}of An(e)){let n=Pe(r.control)?Di(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function U9(e){return e!==void 0&&e.genPage===void 0&&(ag(e)!==B.CUSTOM_CONTROL_CLASS_ID||!vd(e))}function Xh(e,t){if(Pe(e)){t(e);for(let r of Ae(e.c))Xh(r,t)}}function Ko(e,t){var r;if(Pe(e)){for(let n of Ae(e.c))Xh(n?.node,t);for(let n of Ae((r=e.w)===null||r===void 0?void 0:r.c))Xh(n?.node,t)}}function yd(e){let t=new Map,r=i=>{var o;i&&t.set(i,((o=t.get(i))!==null&&o!==void 0?o:0)+1)},n=i=>{i.n==="control"&&r(Sr(co(i,"uniqueid")))};return Ko(e?.bag,n),Ae(e?.tabs).forEach(i=>{Pe(i)&&(Ko(i.bag,n),Ae(i.columns).forEach(o=>{Pe(o)&&(Ko(o.bag,n),Ae(o.sections).forEach(a=>{Pe(a)&&(Ko(a.bag,n),Ae(a.rows).forEach(s=>{Pe(s)&&(Ko(s.bag,n),Ae(s.cells).forEach(l=>{Pe(l)&&(Ko(l.bag,n),Pe(l.control)&&(r(Di(l.control)),Ko(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=yd;function ls(e){return Ae(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=ls;function Jo(e,t){var r;let n=Sr(t);if(n)return Ae((r=ls(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&Sr(co(i,"forControl"))===n)}B.descriptionFor=Jo;function Jl(e){return Ae(e.c).filter(US)}B.pageEntries=Jl;function US(e){return e?.n==="customControl"&&co(e,"name")===B.GENPAGE_CONTROL_NAME}function Zh(e,t){let r=Ae(e.c).find(n=>n?.n==="parameters");return Ae(r?.c).find(n=>n?.n===t)}B.entryParameter=Zh;function eg(e){return co(e,"static")==="true"}B.isStaticParameter=eg;function Yl(e){let t=Jl(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let o=Zh(t[i],"RefId");if(!o||!eg(o))return{kind:"unsupported"};let a=Sr(Kl(o));if(!a)return{kind:"unsupported"};let s=Zh(t[i],"PageInput");if(s&&!eg(s))return{kind:"unsupported"};let l=s?Kl(s):void 0;if(i===0)r=a,n=l;else if(a!==r||l!==n)return{kind:"unsupported"}}return n===void 0?{kind:"projectable",pageId:r}:{kind:"projectable",pageId:r,pageInputRaw:n}}B.classifyBinding=Yl;function Pe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ig(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return Pe(t)&&Pe(t.data)?t.data:void 0}B.inputDataFrom=ig;function og(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=og;function ag(e){return FS(e.classId!==void 0?e.classId:ng(e.bag,"classid"))}B.effectiveClassId=ag;function vd(e){return!e.fieldName}B.isUnbound=vd;function sg(e,t){if(og(e)!=="Main"||!vd(t)||ag(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=Di(t),n=r?Jo(e.bag,r):void 0;return n!==void 0&&Yl(n).kind==="projectable"}B.isRecognizedEmbed=sg;function B9(e){for(let t of MS(e)){let r=t.control;if(!r||!sg(e,r))continue;let n=Yl(Jo(e.bag,Di(r)));if(n.kind!=="projectable")continue;let i=ig(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=B9;var q9=new Set(["pageId","inputData"]);function Hl(e){let t=[];for(let r=0;r<e.childNodes.length;r+=1){let n=e.childNodes[r];n.nodeType===1&&t.push(n)}return t}function V9(e){var t;let r=[],n=c=>d=>r.push(`${c}: ${d}`),i=new k9.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the formxml does not parse cleanly${r.length>0?` (${r[0]})`:""}`);let a=new Set,s=o.getElementsByTagName("control");for(let c=0;c<s.length;c+=1){let d=Sr(s[c].getAttribute("uniqueid"));d&&a.add(d)}let l=Hl(o).find(c=>c.nodeName==="controlDescriptions"),u=new Map;for(let c of l?Hl(l):[]){let d=Sr(c.getAttribute("forControl"));if(!(c.nodeName!=="controlDescription"||!d||!a.has(d)))for(let f of Hl(c)){if(f.nodeName!=="customControl"||f.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let m=Hl(f).find(g=>g.nodeName==="parameters"),p=m?Hl(m).find(g=>g.nodeName==="RefId"):void 0,h=p&&p.getAttribute("static")==="true"?Sr(p.textContent):"";h&&u.set(`${d}|${h}`,[d,h])}}return[...u.values()]}B.activeEmbedBindings=V9;function gd(e){return{n:`<${e}`,a:[],c:[]}}function tg(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[gd(t)]}}function rg(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);Pe(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function G9(e,t,r){return{n:"controlDescription",a:[["forControl",e]],c:B.GENPAGE_FORM_FACTORS.map(n=>({n:"customControl",a:[["name",B.GENPAGE_CONTROL_NAME],["formFactor",n]],c:[{n:"parameters",a:[],c:[tg("RefId",t),...r===void 0?[]:[tg("PageInput",rg(r))]]}]}))}}function bd(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>bd(r,t[n]));if(Pe(e)&&Pe(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&bd(e[n],t[n]))}return e===t}function W9(e,t,r){let n=Ae(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&Sr(Kl(i))!==t&&(i.c=[gd(t)]);let o=n.c.findIndex(u=>u?.n==="PageInput"),a=o>=0?n.c[o]:void 0,s=a?Kl(a):void 0;if(bd(ig(s),r))return;if(r!==void 0){a?a.c=[gd(rg(r,s))]:n.c.push(tg("PageInput",rg(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(o,1):a.c=[gd(JSON.stringify(l))]}function lg(e){let t=Ae(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=lg;function z9(e,t){var r;let n=e.bag,i=ls(n);if(i&&t){let o=yd(t),a=yd(e),s=F9(t),l=M9(e),u=Ae(i.node.c),c=[];for(let d of u){let f=d?.n==="controlDescription"&&Jl(d).length>0?Sr(co(d,"forControl")):"";if(!f||!o.has(f))c.push(d);else if(a.has(f))if(s.has(f)&&U9(l.get(f))&&bd(d,Jo(t.bag,f))){let m=Ae(d.c).filter(p=>!US(p));m.length>0&&c.push({...d,c:m})}else c.push(d)}(c.length!==u.length||c.some((d,f)=>d!==u[f]))&&(i.node.c=c)}for(let{cell:o}of An(e)){let a=o.control;if(!Yo(a)||!Pe(a.genPage))continue;let s=Sr(a.genPage.pageId),l=a.genPage.inputData,u=Di(a);if(!u){if(Ql(a)!==void 0)continue;u=ug(a)}let c=Jo(n,u);if(c){for(let m of Jl(c))W9(m,s,l);continue}i||(i={i:lg(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=ng(a.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),f=d.startsWith("{")?d:`{${u}}`;i.node.c.push(G9(f,s,l))}}B.reconcileEmbedDescriptions=z9;function j9(e,t){let r=ls(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=An(e).some(({cell:a})=>Yo(a.control)&&(a.rowspan===void 0||a.control.classId===void 0||a.control.showLabel===void 0||a.control.label===void 0||a.control.fieldName===void 0));if(!n&&!i)return e;let o=JSON.parse(JSON.stringify(e));if(n){let a=JSON.parse(JSON.stringify(t)),s=ls(o.bag);s?s.node=a:(o.bag=Pe(o.bag)?o.bag:{a:[],c:[]},o.bag.c=Ae(o.bag.c),o.bag.c.push({i:lg(e.bag),node:a}))}for(let{cell:a}of An(o))Yo(a.control)&&(BS(a.control),qS(a));return o}B.commitEmbedState=j9;function H9(e){if(An(e).some(({cell:r})=>Yo(r.control)))return!0;let t=ls(e.bag);return Ae(t?.node.c).some(r=>r?.n==="controlDescription"&&Jl(r).length>0)}B.mayCommitEmbedState=H9;function BS(e){e.classId===void 0&&(e.classId=B.CUSTOM_CONTROL_CLASS_ID),e.showLabel===void 0&&(e.showLabel=!1),e.label===void 0&&(e.label=""),e.fieldName===void 0&&(e.fieldName=null)}B.applyEmbedControlDefaults=BS;function qS(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=qS;function Yo(e){return Pe(e)&&e.genPage!==void 0}B.hasGenPage=Yo;function $S(e){return Yo(e.control)&&(!e.control.id||!e.id||Ql(e.control)===void 0)}function Ql(e){let t=Ae(Pe(e.bag)?e.bag.a:void 0).find(n=>Array.isArray(n)&&n[0]==="uniqueid");if(!t)return;let r=t[1];return typeof r=="string"&&r.trim()===""?void 0:r}B.authoredUniqueId=Ql;function K9(e){if(!An(e).some(({cell:r})=>$S(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of An(t)){if(!$S(r))continue;let n=r.control;n.id||(n.id=(0,Qh.newId)()),r.id||(r.id=(0,Qh.newId)()),Ql(n)===void 0&&ug(n)}return t}B.mintEmbedIdentity=K9;function ug(e){let t=(0,Qh.newId)(),r=`{${t}}`;if(!Pe(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=Ae(e.bag.a),i=n.find(o=>Array.isArray(o)&&o[0]==="uniqueid");return i?i[1]=r:n.push(["uniqueid",r]),e.bag.a=n,e.bag.c=Ae(e.bag.c),t}B.setUniqueId=ug;function xS(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function J9(e){let t=Ae(e.c).filter(r=>r?.n==="customControl").map(r=>{var n,i;return(i=(n=co(r,"name"))!==null&&n!==void 0?n:co(r,"id"))!==null&&i!==void 0?i:"unnamed"});return[...new Set(t)].join(", ")||"no custom control"}function Y9(e){let t=[],r;for(let{cell:n,pointer:i}of An(e)){let o=n.control;if(!Pe(o))continue;let a=`${i}/control`;if(o.genPage===void 0){Q9(e,o,a,t);continue}r=r??yd(e),X9(e,o,a,r,t)}return t}B.genPageEmbedIssues=Y9;function Q9(e,t,r,n){if(!sg(e,t))return;let i=Yl(Jo(e.bag,Di(t)));n.push((0,tn.issue)(r,"genpage-embed-removed",`this control still embeds generative page ${i.pageId}: removing genPage alone would leave that binding on the form. To remove the embed, remove the cell (or set the cell's control to null); to change the page, edit genPage/pageId. A copy fetched by an older SDK (projection 3) shows no genPage at all \u2014 re-fetch the form.`))}function X9(e,t,r,n,i){var o;let a=`${r}/genPage`,s=t.genPage;if(!Pe(s))i.push((0,tn.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${xS(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!Sr(s.pageId))&&i.push((0,tn.issue)(`${a}/pageId`,"genpage-embed-shape",`genPage.pageId must be the id (a GUID) of a generative page, got ${s.pageId===void 0?"nothing":JSON.stringify(s.pageId)}`)),s.inputData!==void 0&&!Pe(s.inputData)&&i.push((0,tn.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${xS(s.inputData)}`));for(let m of Object.keys(s))q9.has(m)||i.push((0,tn.issue)($9.JsonPointer.append(a,m),"genpage-embed-unknown-key",`'${m}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}vd(t)||i.push((0,tn.issue)(`${r}/fieldName`,"genpage-embed-bound",`a generative-page embed is an unbound control, but this one is bound to column '${t.fieldName}'. Set fieldName to null, or embed the page in a new cell.`)),t.classId!==void 0&&FS(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,tn.issue)(`${r}/classId`,"genpage-embed-class-id",`a generative-page embed is the custom control {${B.CUSTOM_CONTROL_CLASS_ID}}, but classId is ${JSON.stringify(t.classId)}. Omit classId (the SDK defaults it) or set it to that class.`));let l=og(e);l!=="Main"&&i.push((0,tn.issue)(a,"genpage-embed-main-form-only",`a generative page can be embedded only in a Main form, as in the maker portal; this is a ${l} form.`));let u=Ql(t);u!==void 0&&!Sr(u)&&i.push((0,tn.issue)(`${r}/bag`,"genpage-embed-unique-id",`this embed's uniqueid ${JSON.stringify(u)} is not a GUID, and its page binding is keyed by it. Remove it from the bag (the SDK mints one) or set a GUID.`));let c=Di(t);if(!c)return;let d=Jo(e.bag,c),f=d?Yl(d):void 0;d&&f?.kind==="none"?i.push((0,tn.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${J9(d)}). genPage would have to delete that binding to take its place, so embed the page in a new cell instead.`)):f?.kind==="unsupported"&&i.push((0,tn.issue)(a,"genpage-embed-unsupported-binding","this control already embeds a page through a binding genPage cannot represent exactly \u2014 a RefId or PageInput bound to a column, a RefId that is not a page id, or form factors that disagree. Taking it over would silently turn it into a static binding, so embed the page in a new cell instead.")),((o=n.get(c))!==null&&o!==void 0?o:0)>1&&i.push((0,tn.issue)(`${r}/bag`,"genpage-embed-duplicate-unique-id",`this embed's uniqueid {${c}} is also carried by another control on the form, so both would share one binding. Author the copy without its bag and the SDK mints a new identity for it.`))}});var dg=v(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.findMissingGenPages=fo.GENPAGE_LOOKUP_CHUNK=void 0;var Z9=Lt(),cg=se();fo.GENPAGE_LOOKUP_CHUNK=50;async function e5(e,t,r){let n=[...new Set(t.map(o=>(0,cg.normalizeGuid)(o,"uxagentprojectid")))],i=new Set;for(let o=0;o<n.length;o+=fo.GENPAGE_LOOKUP_CHUNK){let a=n.slice(o,o+fo.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,cg.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,Z9.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,cg.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(o=>!i.has(o))}fo.findMissingGenPages=e5});var Xl=v(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.assertSystemFormKind=Nt.readSystemFormType=Nt.decodeCode=Nt.assertSystemFormRecordKind=Nt.describeSystemFormType=Nt.systemFormKindOf=Nt.SYSTEMFORM_KIND_MISMATCH_CODE=void 0;var GS=Q(),t5=ye(),VS=se();Nt.SYSTEMFORM_KIND_MISMATCH_CODE="SYSTEMFORM_KIND_MISMATCH";var r5={0:"dashboard",10:"dashboard",2:"form",6:"form",7:"form",11:"form"},n5={0:"dashboard",1:"appointment book",2:"Main form",3:"mini campaign form",4:"preview form",5:"mobile express form",6:"Quick View form",7:"Quick Create form",8:"dialog",9:"task flow form",10:"interactive dashboard",11:"card form",12:"interactive Main form",13:"contextual dashboard",100:"other form",101:"Main form backup",102:"appointment book backup",103:"Power BI dashboard"};function Cd(e){return Number.isInteger(e)?r5[e]:void 0}Nt.systemFormKindOf=Cd;function WS(e){var t;return Number.isFinite(e)?`a ${(t=n5[e])!==null&&t!==void 0?t:"systemform"} (type ${e})`:"a systemform whose type could not be read"}Nt.describeSystemFormType=WS;function zS(e,t,r,n){let i=WS(r),o=Cd(r);switch(n){case"fetch":return`Refusing to fetch systemform '${e}' as a ${t}: it is ${i}. Nothing was read into the workspace. `+(o?`Fetch it as a ${o}.`:Number.isFinite(r)?"The SDK does not model that kind: check the id.":"Check the id.");case"write":return`Refusing to write systemform '${e}' as a ${t}: it is ${i}. Nothing was written. Check the id: a local copy fetched by an SDK that did not check the kind can name a row of another kind \u2014 discard it with deleteArtifact('${t}', '${e}').`;case"delete":return`Refusing to delete systemform '${e}' as a ${t}: it is ${i}. Nothing was changed. Check the id.`;default:return`Refusing to ${n} systemform '${e}': it is ${i}, not a ${t}.`+(n==="set the security roles of"?" Nothing was written.":"")+" Check the id."}}function i5(e,t,r,n){let i=fg(e?.type);if(Cd(i)!==r)throw new GS.SdkError(Nt.SYSTEMFORM_KIND_MISMATCH_CODE,zS(t,r,i,n));return i}Nt.assertSystemFormRecordKind=i5;function fg(e){if(typeof e=="number")return Number.isInteger(e)?e:NaN;if(typeof e!="string"||!/^\s*-?\d+\s*$/.test(e))return NaN;let t=Number(e);return Number.isInteger(t)?t:NaN}Nt.decodeCode=fg;async function o5(e,t){return await jS(e,t,!1)}Nt.readSystemFormType=o5;async function a5(e,t){return jS(e,t,!0)}async function jS(e,t,r){var n;let o=`/systemforms(${(0,VS.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,VS.odataQuery)([["$select","type"]]),a=await e.get(o);if(!(r&&a.status===404))return(0,t5.ensureSuccess)(a,e.apiUrl(o)),fg((n=a.body)===null||n===void 0?void 0:n.type)}async function s5(e,t,r){let n=await a5(e,t);if(!(n===void 0||Cd(n)===r))throw new GS.SdkError(Nt.SYSTEMFORM_KIND_MISMATCH_CODE,zS(t,r,n,"delete"))}Nt.assertSystemFormKind=s5});var mg=v(qr=>{"use strict";Object.defineProperty(qr,"__esModule",{value:!0});qr.patchSystemForm=qr.assertSystemFormContentUnchanged=qr.readSystemFormRowEtag=qr.unpublishedSystemFormPath=qr.FORM_TYPE_IMMUTABLE_CODE=void 0;var rn=ye(),l5=se(),Ed=Q(),po=Xl();qr.FORM_TYPE_IMMUTABLE_CODE="FORM_TYPE_IMMUTABLE";function pg(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,l5.odataQuery)([["$select",t]])}qr.unpublishedSystemFormPath=pg;function HS(e,t){return(0,rn.readRowEtag)(e,"systemforms","formid",t)}qr.readSystemFormRowEtag=HS;async function KS(e,t,r,n,i){(0,rn.requireEtag)(i,r,t);let o=(0,rn.ensureSuccess)(await e.get(n),e.apiUrl(n)),a=(0,po.assertSystemFormRecordKind)(o.body,t,r,"write"),s=(0,rn.readEtag)(o);if(s===null)throw new Ed.SdkError(rn.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its current version could not be read, so the write could not be verified as conditional and would risk silently overwriting a concurrent edit.`);if(s!==i)throw new Ed.SdkError(rn.VERSION_CONFLICT_CODE,`Version conflict writing ${r} '${t}': its formxml changed on the server since it was read (held ${i}, server ${s}). Re-fetch the ${r} and re-apply the change.`);return a}qr.assertSystemFormContentUnchanged=KS;async function u5(e,t,r,n,i,o){(0,rn.requireEtag)(i,r,t);let a=await HS(e,t);if(a===null)throw new Ed.SdkError(rn.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its row version could not be read, so the write could not be made conditional and would risk silently overwriting a concurrent edit.`);let s=await KS(e,t,r,pg(t,"formid,type"),i);if(n.type!==void 0&&(0,po.decodeCode)(n.type)!==s)throw new Ed.SdkError(qr.FORM_TYPE_IMMUTABLE_CODE,`Refusing to push ${r} '${t}': it would change it from ${(0,po.describeSystemFormType)(s)} to ${(0,po.describeSystemFormType)((0,po.decodeCode)(n.type))}. The platform ignores a type change on an existing ${r}, so the push would report a change that did not happen. Nothing was written. Create a new ${r} of that type instead.`);let l=(0,rn.echoWrite)("formid",{"If-Match":a}),u=`/systemforms(${t})${l.query}`;return(0,rn.ensureSuccess)(await e.patch(u,n,l.options),e.apiUrl(u)),c5(e,t,r,o)}qr.patchSystemForm=u5;async function c5(e,t,r,n){let i;try{let o=pg(t,n.select),a=(0,rn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,l=(0,rn.readEtag)(a),u=typeof s?.formid=="string"&&s.formid.replace(/[{}]/g,"").toLowerCase()===t,c=typeof s?.formxml=="string"&&s.formxml.trim()!=="",d=n.required.filter(p=>s?.[p]===void 0||s?.[p]===null),f=(0,po.decodeCode)(s?.type),m=(0,po.systemFormKindOf)(f)===r;if(l&&u&&c&&d.length===0&&m)return{id:t,etag:l,readBack:s};i=l?!u||!c?`the read did not return this ${r}'s document`:d.length>0?`the read did not return its ${d.join(", ")}`:`the read returned ${(0,po.describeSystemFormType)(f)}, not a ${r}`:"the read returned no version"}catch(o){i=o instanceof Error?o.message:String(o)}return{id:t,etag:null,warnings:[`The ${r} was saved, but its new version could not be read (${i}). The SDK holds no version for it now, so the next push is refused: re-fetch the ${r} before editing it again.`]}}});var vg=v(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.getFormSecurityRoles=kt.setFormSecurityRoles=kt.formApi=kt.readPrimaryCreateRefusal=kt.FORM_GENPAGE_TARGET_UNVERIFIABLE=kt.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var d5=Lt(),_t=ye(),nn=se(),Qo=Q(),hg=uo(),YS=wd(),f5=dg(),gg=mg(),Zl=Xl();kt.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";kt.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var QS="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",p5={select:QS,required:["name","type","objecttypecode"]},m5="formid,name,type,objecttypecode",h5=2,g5={Main:h5,QuickView:6,QuickCreate:7,Card:11},XS=new WeakMap;function y5(e){return typeof e=="object"&&e!==null?XS.get(e):void 0}kt.readPrimaryCreateRefusal=y5;kt.formApi={async get(e,t){let r=(0,nn.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,nn.odataQuery)([["$select",QS]]),i=(0,_t.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,Zl.assertSystemFormRecordKind)(i.body,r,"form","fetch"),{raw:i.body,etag:(0,_t.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=>g5[u]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,nn.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,nn.odataQuery)([["$select",m5],["$filter",a.join(" and ")]])}`;return(await(0,d5.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=JS(t);n!==void 0&&await ZS(e,bg(n,"payload"),[]);let i=(0,_t.echoWrite)("formid"),o=`/systemforms${i.query}`,a=(0,_t.withClientMintedId)(t,"formid",r),s=Object.freeze({...a}),l=await(0,_t.resendDeadlockVictim)(()=>e.post(o,{...s},i.options));try{(0,_t.ensureSuccess)(l,e.apiUrl(o))}catch(u){throw typeof u=="object"&&u!==null&&XS.set(u,{status:l.status,sent:s,desiredId:r}),u}return{id:(0,_t.resolveCreatedId)(l,"formid","form",r),etag:(0,_t.readEtag)(l)}},async update(e,t,r,n){let i=(0,nn.normalizeGuid)(t,"id"),o=JS(r);return o!==void 0&&await v5(e,i,o,n),(0,gg.patchSystemForm)(e,i,"form",r,n,p5)},readContentThenToken(e,t){return kt.formApi.get(e,t)},async delete(e,t){let r=(0,nn.normalizeGuid)(t,"id");return await(0,Zl.assertSystemFormKind)(e,r,"form"),(0,_t.deleteRecord)(e,"systemforms",r)}};var yg="DisplayConditions";async function b5(e,t,r){var n,i,o,a;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new Qo.InvalidArgumentError("setFormSecurityRoles: `everyone` and `roleIds` are mutually exclusive \u2014 the platform models <Everyone /> as a replacement for the <Role> list, not an addition to it.");let s=(0,nn.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,nn.odataQuery)([["$select","formid,formxml,type"]]),u=(0,_t.ensureSuccess)(await e.get(l),e.apiUrl(l));(0,Zl.assertSystemFormRecordKind)(u.body,s,"form","set the security roles of");let c=(0,_t.readEtag)(u),d=u.body,f=d?.formxml;if(!f)throw new Qo.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let m=(0,hg.parseXmlRoot)(f,"<form/>"),p=m.ownerDocument;if(!p)throw new Qo.InvalidArgumentError(`form '${s}' produced no owner document`);let h=eN(m,yg),g=h?.hasAttribute("Order")&&(n=h.getAttribute("Order"))!==null&&n!==void 0?n:void 0,b=h?.getAttribute("FallbackForm")||void 0;h&&m.removeChild(h);let w=!!r.everyone||((o=(i=r.roleIds)===null||i===void 0?void 0:i.length)!==null&&o!==void 0?o:0)>0;if(!w&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!h)throw new Qo.InvalidArgumentError("setFormSecurityRoles: `order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to. Pass the roles as well.");r.order!==void 0&&h.setAttribute("Order",String(r.order)),r.fallbackForm!==void 0&&h.setAttribute("FallbackForm",String(r.fallbackForm)),m.appendChild(h)}else if(w){let I=p.createElement(yg),D=r.order!==void 0?String(r.order):g;D!==void 0&&I.setAttribute("Order",D);let O=r.fallbackForm!==void 0?String(r.fallbackForm):b??"false";if(I.setAttribute("FallbackForm",O),r.everyone)I.appendChild(p.createElement("Everyone"));else for(let x of(a=r.roleIds)!==null&&a!==void 0?a:[]){let K=p.createElement("Role");K.setAttribute("Id",`{${(0,nn.normalizeGuid)(x,"roleId")}}`),I.appendChild(K)}m.appendChild(I)}let S=(0,hg.serializeNode)(m);await(0,gg.assertSystemFormContentUnchanged)(e,s,"form",l,c);let P=await(0,gg.readSystemFormRowEtag)(e,s),L=`/systemforms(${s})`;(0,_t.ensureSuccess)(await e.patch(L,{formxml:S},{headers:{"Content-Type":"application/json","If-Match":(0,_t.requireEtag)(P,"form",s)}}),e.apiUrl(L))}kt.setFormSecurityRoles=b5;function JS(e){let t=e?.formxml;return typeof t=="string"&&t.includes(YS.GENPAGE_CONTROL_NAME)?t:void 0}function bg(e,t){try{return(0,YS.activeEmbedBindings)(e)}catch(r){throw new Qo.SdkError(kt.FORM_GENPAGE_TARGET_UNVERIFIABLE,`Refusing to push the form: the ${t} formxml could not be parsed, so the generative pages it embeds cannot be verified (${r instanceof Error?r.message:String(r)}).`)}}async function ZS(e,t,r){let n=new Set(r.map(([a,s])=>`${a}|${s}`)),i=t.filter(([a,s])=>!n.has(`${a}|${s}`)).map(([,a])=>a);if(i.length===0)return;let o=await(0,f5.findMissingGenPages)(e,i,"form generative-page preflight");if(o.length>0)throw new Qo.SdkError(kt.FORM_GENPAGE_TARGET_NOT_FOUND,`Refusing to push the form: it embeds generative page(s) ${o.map(a=>`'${a}'`).join(", ")} that do not exist in this environment. Push the page before the form that embeds it.`)}async function v5(e,t,r,n){var i;(0,_t.requireEtag)(n,"form",t);let o=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,nn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,_t.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,Zl.assertSystemFormRecordKind)(a.body,t,"form","write");let s=(0,_t.readEtag)(a);if(s===null||s!==n)throw new Qo.SdkError(_t.VERSION_CONFLICT_CODE,`Version conflict writing form '${t}': its formxml changed on the server since it was read (held ${n}, server ${s??"(unreadable)"}). Re-fetch the form and re-apply the change.`);let l=(i=a.body)===null||i===void 0?void 0:i.formxml,u=typeof l=="string"&&l!==""?bg(l,"server"):[];await ZS(e,bg(r,"payload"),u)}function eN(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 w5(e,t){var r,n;let i=(0,nn.normalizeGuid)(t,"formId"),o=`/systemforms(${i})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,nn.odataQuery)([["$select","formid,formxml,type"]]),a=(0,_t.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,Zl.assertSystemFormRecordKind)(a.body,i,"form","read the security roles of");let s=(r=a.body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,hg.parseXmlRoot)(s,"<form/>"),u=eN(l,yg);if(!u)return;let c=[],d=!1,f=u.childNodes;for(let p=0;p<f.length;p+=1){let h=f[p];if(h.nodeType!==1)continue;let g=h;if(g.tagName==="Everyone")d=!0;else if(g.tagName==="Role"){let b=(n=g.getAttribute("Id"))!==null&&n!==void 0?n:"";b&&c.push(b.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)}:{}}}kt.getFormSecurityRoles=w5});var wg=v(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.deleteSolution=be.getDeploymentSettingsTemplate=be.importSolution=be.exportSolution=be.removeSolutionComponent=be.addSolutionComponent=be.setSolutionVersion=be.createSolution=be.createPublisher=be.getSolution=be.fetchSolutionComponents=be.resolveGenPageComponentType=be.SolutionComponentType=void 0;var C5=Lt(),xt=ye(),ar=se(),E5=dt(),Kt=Q();be.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80};var A5=[be.SolutionComponentType.SavedQuery,be.SolutionComponentType.Workflow,be.SolutionComponentType.SavedQueryVisualization,be.SolutionComponentType.SystemForm,be.SolutionComponentType.AppModule],tN="uxagentproject",rN=new WeakMap;async function lN(e){var t;let r=rN.get(e);if(r!==void 0)return r;let n=`/EntityDefinitions(LogicalName='${tN}')${(0,ar.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status===404)return;(0,xt.ensureSuccess)(i,e.apiUrl(n));let o=(t=i.body)===null||t===void 0?void 0:t.ObjectTypeCode;if(typeof o!="number"||!Number.isInteger(o)||o<=0)throw new Kt.SdkError("GENPAGE_COMPONENT_TYPE_UNRESOLVED",`A generative page's solution component type \u2014 the ObjectTypeCode of '${tN}' \u2014 could not be read: its metadata answered without a usable value (${JSON.stringify(o)}). Without it a solution's generative pages cannot be told apart from other components. Retry.`);return rN.set(e,o),o}be.resolveGenPageComponentType=lN;var nN=1,iN=0;async function S5(e,t){let r=(0,ar.normalizeGuid)(t,"solutionId"),n=await lN(e),o=[nN,...A5,...n===void 0?[]:[n]].map(c=>`componenttype eq ${c}`).join(" or "),a=`/solutioncomponents${(0,ar.odataQuery)([["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${r} and (${o})`]])}`,s=await(0,C5.collectPages)(e,a,"fetchSolutionComponents"),l=[];for(let c of s){if(typeof c.objectid!="string")continue;let d=Number(c.componenttype);if(d===nN){let f=c.rootcomponentbehavior;(f===iN||f===String(iN))&&l.push({objectId:c.objectid,componentType:d,includesAllSubcomponents:!0});continue}l.push({objectId:c.objectid,componentType:d,...n!==void 0&&d===n?{genPage:!0}:{}})}let u=c=>c.objectId.toLowerCase().replace(/^\{|\}$/g,"");return l.sort((c,d)=>c.componentType-d.componentType||(u(c)<u(d)?-1:u(c)>u(d)?1:0))}be.fetchSolutionComponents=S5;function N5(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 _5(e,t){var r,n,i,o,a,s,l,u,c,d;let f=String(t??"").trim();if(!f)throw new Kt.InvalidArgumentError("getSolution: a solution unique name or id is required.");let m=N5(f)?`solutionid eq ${(0,ar.normalizeGuid)(f,"solutionId")}`:`uniquename eq '${(0,ar.odataLiteral)(f)}'`,p=`/solutions${(0,ar.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",m]])}`,b=((n=(r=(0,xt.ensureSuccess)(await e.get(p),e.apiUrl(p)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!b?.solutionid)throw new Kt.InvalidArgumentError(`No solution found for '${t}'.`);let w=b.publisherid;if(!w?.publisherid)throw new Kt.InvalidArgumentError(`Solution '${(i=b.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in w))throw new Kt.InvalidArgumentError(`Solution '${(o=b.uniquename)!==null&&o!==void 0?o:t}' returned a publisher without a customizationprefix property (partial expansion), so its prefix cannot be determined.`);return{solutionId:(0,ar.normalizeGuid)(b.solutionid,"solutionId"),uniqueName:(a=b.uniquename)!==null&&a!==void 0?a:"",friendlyName:(s=b.friendlyname)!==null&&s!==void 0?s:"",version:(l=b.version)!==null&&l!==void 0?l:"",isManaged:!!b.ismanaged,publisherId:(0,ar.normalizeGuid)(w.publisherid,"publisherId"),publisherUniqueName:(u=w.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=w.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=w.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}be.getSolution=_5;async function T5(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,xt.ensureSuccess)(await(0,xt.resendDeadlockVictim)(()=>e.post("/publishers",{...n})),e.apiUrl("/publishers")),o=(0,xt.readCreatedId)(i,"publisherid");if(!o)throw new Kt.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}be.createPublisher=T5;async function D5(e,t){var r;let n=(0,ar.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 o=(0,xt.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,xt.readCreatedId)(o,"solutionid");if(!a)throw new Kt.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}be.createSolution=D5;async function I5(e,t,r){let i=`/solutions(${(0,ar.normalizeGuid)(t,"solutionId")})`;(0,xt.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}be.setSolutionVersion=I5;async function O5(e,t){var r;let i={ComponentId:(0,ar.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,xt.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}be.addSolutionComponent=O5;async function P5(e,t,r,n){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,ar.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,xt.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}be.removeSolutionComponent=P5;async function R5(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},a=(n=(0,xt.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!a)throw new Kt.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}be.exportSolution=R5;async function L5(e,t){let r=[["overwriteUnmanagedCustomizations","overwrote unmanaged customizations made over the solution's components"],["publishWorkflows","activated the solution's workflows"]];for(let[a,s]of r)if(typeof t?.[a]!="boolean")throw new Kt.InvalidArgumentError(`importSolution: '${a}' is required and must be true or false (it was ${String(t?.[a])}). It used to default to true, which ${s} unless the caller said otherwise. Nothing was imported.`);let n=t.deploymentSettings===void 0?void 0:W5(t.deploymentSettings),i={OverwriteUnmanagedCustomizations:t.overwriteUnmanagedCustomizations,PublishWorkflows:t.publishWorkflows,CustomizationFile:t.base64,ImportJobId:t.importJobId?(0,ar.normalizeGuid)(t.importJobId,"importJobId"):(0,E5.newId)()};if(!n)return(0,xt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{};if(n.variables.length===0&&n.references.length===0)return(0,xt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:{environmentVariables:[],connectionReferences:[]}};let o=[];try{let a=await uN(e,t.base64,eu,o),{parameters:s,applied:l}=z5(a,n);return i.ComponentParameters=s,(0,xt.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:l,...o.length>0?{warnings:o}:{}}}catch(a){throw(0,Kt.withCleanupWarnings)(a,o)}}be.importSolution=L5;var eu="importSolution",oN="getDeploymentSettingsTemplate";async function k5(e,t){var r;let n=t?.base64;if(typeof n!="string"||n.length===0)throw new Kt.InvalidArgumentError(`${oN}: 'base64' must be the solution package \u2014 a non-empty base64 string, e.g. exportSolution's result (it was ${(r=JSON.stringify(n))!==null&&r!==void 0?r:String(n)})`);let i=[];try{let o=await uN(e,n,oN,i),a=Ad(o.variables,l=>l.SchemaName).map(({SchemaName:l,DefaultValue:u,TypeId:c,IsRequired:d})=>({SchemaName:l,Value:"",...u!==void 0?{DefaultValue:u}:{},...c!==void 0?{TypeId:c}:{},...d!==void 0?{IsRequired:d}:{}})),s=Ad(o.references,l=>l.LogicalName).map(({LogicalName:l,ConnectorId:u})=>({LogicalName:l,ConnectionId:"",...u!==void 0?{ConnectorId:u}:{}}));return{settings:{EnvironmentVariables:a,ConnectionReferences:s},...i.length>0?{warnings:i}:{}}}catch(o){throw(0,Kt.withCleanupWarnings)(o,i)}}be.getDeploymentSettingsTemplate=k5;function Ad(e,t){return[...e].sort((r,n)=>{let i=t(r).toLowerCase(),o=t(n).toLowerCase();return i<o?-1:i>o?1:0})}function Xo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $t(e,t=120){var r;let n=(r=JSON.stringify(e))!==null&&r!==void 0?r:String(e);return n.length>t?`${n.slice(0,t)}\u2026`:n}async function uN(e,t,r,n){var i;let a=(i=(0,xt.ensureSuccess)(await e.post("/StageSolution",{CustomizationFile:t}),e.apiUrl("/StageSolution")).body)===null||i===void 0?void 0:i.StageSolutionResults;try{return x5(a,r)}finally{await $5(e,Xo(a)?a.StageSolutionUploadId:void 0,n)}}async function $5(e,t,r){let n;try{n=(0,ar.normalizeGuid)(t,"StageSolutionUploadId")}catch{r.push(`StageSolution's reply named no usable staging upload id (${$t(t,60)}), so the staged copy of the package it may have stored (a stagesolutionupload row of yours) could not be deleted.`);return}let i=`/stagesolutionuploads(${n})`;try{let o=await e.delete(i);o.status!==404&&(0,xt.ensureSuccess)(o,e.apiUrl(i))}catch(o){r.push(`The staged copy of the package (stagesolutionupload ${n}) could not be deleted: ${o instanceof Error?o.message:String(o)}. It stays until it is deleted (DELETE ${i}).`)}}function or(e,t){return new Kt.SdkError("SOLUTION_STAGING_UNREADABLE",`${e}: StageSolution's reply could not be read \u2014 ${t}.${e===eu?" Nothing was imported.":""}`)}function aN(e){return!Array.isArray(e)||e.length===0?"none":`${e.slice(0,5).map(r=>Xo(r)&&typeof r.Message=="string"?r.Message:$t(r,200)).join("; ")}${e.length>5?` (+${e.length-5} more)`:""}`}function x5(e,t){if(!Xo(e))throw or(t,`it holds no StageSolutionResults (${$t(e,60)})`);let r=e.StageSolutionStatus;if(r==="Failed"||r===0)throw new Kt.SdkError("SOLUTION_STAGING_FAILED",`${t}: the package did not pass StageSolution in this environment (status ${$t(r)}). Missing dependencies: ${aN(e.MissingDependencies)}. Validation: ${aN(e.SolutionValidationResults)}.${t===eu?" Its components cannot be checked against deploymentSettings. Nothing was imported.":" Stage it in the environment it was exported from."}`);if(r!=="Passed"&&r!==1)throw or(t,`StageSolutionStatus is ${$t(r)}, neither "Passed" nor "Failed"`);let n=e.SolutionComponentsDetails;if(!Array.isArray(n))throw or(t,`SolutionComponentsDetails is not a list (${$t(n,60)})`);let i=[],o=[],a=new Set,s=new Set;return n.forEach((l,u)=>{let c=`SolutionComponentsDetails[${u}]`;if(!Xo(l))throw or(t,`${c} is not an object`);if(typeof l.ComponentTypeName!="string")throw or(t,`${c}.ComponentTypeName is not a string`);let d=l.ComponentTypeName.toLowerCase();if(d!=="environmentvariabledefinition"&&d!=="connectionreference")return;let f=F5(l.Attributes,`${c}.Attributes`,t),m=(p,h)=>{let g=f.get(p);if(g==null){if(h)throw or(t,`${c}.${p} is missing`);return}if(typeof g!="string"||h&&g.length===0)throw or(t,`${c}.${p} is not ${h?"a non-empty string":"a string"}`);return g};if(d==="environmentvariabledefinition"){let p=m("schemaname",!0);if(a.has(p.toLowerCase()))throw or(t,`${c}.schemaname '${p}' is listed twice`);a.add(p.toLowerCase());let h=m("defaultvalue",!1),g=M5(f.get("type"),`${c}.type`,t),b=U5(f.get("isrequired"),`${c}.isrequired`,t);i.push({SchemaName:p,...h!==void 0?{DefaultValue:h}:{},...g!==void 0?{TypeId:g}:{},...b!==void 0?{IsRequired:b}:{}})}else{let p=m("connectionreferencelogicalname",!0);if(s.has(p.toLowerCase()))throw or(t,`${c}.connectionreferencelogicalname '${p}' is listed twice`);s.add(p.toLowerCase());let h=m("connectorid",!1);o.push({LogicalName:p,...h!==void 0?{ConnectorId:h}:{}})}}),{variables:i,references:o}}function F5(e,t,r){if(!Xo(e)||!Array.isArray(e.Keys)||!Array.isArray(e.Values))throw or(r,`${t} is not { Keys: [...], Values: [...] }`);let{Keys:n,Values:i}=e;if(n.length!==i.length)throw or(r,`${t} has ${n.length} keys but ${i.length} values`);let o=new Map;return n.forEach((a,s)=>{if(typeof a!="string")throw or(r,`${t}.Keys[${s}] is not a string`);if(o.has(a))throw or(r,`${t}.Keys lists '${a}' twice`);o.set(a,i[s])}),o}function M5(e,t,r){if(e!=null){if(typeof e=="number"&&Number.isSafeInteger(e))return e;if(typeof e=="string"&&/^\d{1,15}$/.test(e))return Number(e);throw or(r,`${t} is not a whole number (${$t(e,40)})`)}}function U5(e,t,r){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"&&/^(true|false)$/i.test(e))return e.toLowerCase()==="true";throw or(r,`${t} is not true or false (${$t(e,40)})`)}}var B5=new Set(["EnvironmentVariables","ConnectionReferences","Workflows","CanvasApps","CopilotAgents","$schema"]),q5=["Workflows","CanvasApps","CopilotAgents"],V5=new Set(["SchemaName","Value","DefaultValue","TypeId","IsRequired","Name"]),G5=new Set(["LogicalName","ConnectionId","ConnectorId"]);function ir(e,t){return new Kt.InvalidArgumentError(`${eu}: deploymentSettings is not a deployment-settings file this SDK applies \u2014 ${e} ${t}. Nothing was imported.`)}function W5(e){let t="deploymentSettings";if(!Xo(e))throw ir(t,`must be an object \u2014 the settings file, parsed (it was ${$t(e,40)})`);for(let l of Object.keys(e))if(!B5.has(l))throw ir(`${t}.${l}`,"is not part of the format (EnvironmentVariables, ConnectionReferences; Workflows, CanvasApps and CopilotAgents only empty; $schema)");for(let l of q5){let u=e[l];if(u!==void 0&&!(Array.isArray(u)&&u.length===0))throw ir(`${t}.${l}`,"is a pac feature this SDK does not apply: only an empty list is accepted")}if(e.$schema!==void 0&&typeof e.$schema!="string")throw ir(`${t}.$schema`,"must be a string");let r=l=>{let u=e[l];if(u===void 0)return[];if(!Array.isArray(u))throw ir(`${t}.${l}`,`must be a list (it was ${$t(u,40)})`);return u.map((c,d)=>{if(!Xo(c))throw ir(`${t}.${l}[${d}]`,`must be an object (it was ${$t(c,40)})`);return c})},n=(l,u,c)=>{let d=l[u];if(typeof d!="string"||d.length===0)throw ir(c,`must be a non-empty string (it was ${$t(d,40)})`);if(d.trim()!==d)throw ir(c,`must not begin or end with whitespace (it was ${$t(d,60)})`);return d},i=(l,u,c)=>{if(l.has(u.toLowerCase()))throw ir(c,`names '${u}' a second time (names are case-insensitive)`);l.add(u.toLowerCase())},o={variables:[],references:[]},a=new Set;r("EnvironmentVariables").forEach((l,u)=>{let c=`${t}.EnvironmentVariables[${u}]`;for(let f of Object.keys(l))if(!V5.has(f))throw ir(`${c}.${f}`,"is not part of a variable (SchemaName, Value; DefaultValue, TypeId, IsRequired, Name)");let d=n(l,"SchemaName",`${c}.SchemaName`);if(i(a,d,`${c}.SchemaName`),typeof l.Value!="string")throw ir(`${c}.Value`,`must be a string \u2014 empty to override nothing (it was ${$t(l.Value,40)})`);l.Value.length>0&&o.variables.push({name:d,value:l.Value})});let s=new Set;return r("ConnectionReferences").forEach((l,u)=>{let c=`${t}.ConnectionReferences[${u}]`;for(let m of Object.keys(l))if(!G5.has(m))throw ir(`${c}.${m}`,m==="ConnectionInstance"?"is pac's connection-instance feature, which this SDK does not apply":"is not part of a connection reference (LogicalName, ConnectionId, ConnectorId)");let d=n(l,"LogicalName",`${c}.LogicalName`);i(s,d,`${c}.LogicalName`);let f=l.ConnectionId;if(typeof f!="string")throw ir(`${c}.ConnectionId`,`must be a string \u2014 empty to bind nothing (it was ${$t(f,40)})`);if(f.trim()!==f)throw ir(`${c}.ConnectionId`,`must not begin or end with whitespace (it was ${$t(f,60)})`);if(l.ConnectorId!==void 0&&typeof l.ConnectorId!="string")throw ir(`${c}.ConnectorId`,`must be a string (it was ${$t(l.ConnectorId,40)})`);f.length>0&&o.references.push({name:d,connectionId:f,...l.ConnectorId?{connectorId:l.ConnectorId}:{}})}),o}function sN(e,t=20){return e.length===0?"none":`${e.slice(0,t).join(", ")}${e.length>t?` (+${e.length-t} more)`:""}`}function z5(e,t){var r;let n=new Map(e.variables.map(l=>[l.SchemaName.toLowerCase(),l])),i=new Map(e.references.map(l=>[l.LogicalName.toLowerCase(),l])),o=[],a=[],s={environmentVariables:[],connectionReferences:[]};for(let l of t.variables){let u=n.get(l.name.toLowerCase());if(!u){o.push(`EnvironmentVariables: '${l.name}' is not a variable of the package`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.environmentvariablevalue",schemaname:u.SchemaName,value:l.value}),s.environmentVariables.push(u.SchemaName)}for(let l of t.references){let u=i.get(l.name.toLowerCase());if(!u){o.push(`ConnectionReferences: '${l.name}' is not a connection reference of the package`);continue}if(l.connectorId!==void 0&&l.connectorId.toLowerCase()!==((r=u.ConnectorId)===null||r===void 0?void 0:r.toLowerCase())){o.push(`ConnectionReferences: '${l.name}' names connector '${l.connectorId}', but the package's reference is for ${u.ConnectorId?`'${u.ConnectorId}'`:"no connector"}`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.connectionreference",connectionreferencelogicalname:u.LogicalName,connectionid:l.connectionId,...u.ConnectorId!==void 0?{connectorid:u.ConnectorId}:{}}),s.connectionReferences.push(u.LogicalName)}if(o.length>0){let l=o.join("; "),u=sN(Ad(e.variables,d=>d.SchemaName).map(d=>d.SchemaName)),c=sN(Ad(e.references,d=>d.LogicalName).map(d=>d.LogicalName));throw new Kt.InvalidArgumentError(`${eu}: deploymentSettings does not match the package \u2014 ${l}. The package's variables: ${u}; its connection references: ${c}. Nothing was imported.`)}return{parameters:a,applied:s}}async function j5(e,t){let n=`/solutions(${(0,ar.normalizeGuid)(t,"solutionId")})`;(0,xt.ensureSuccess)(await e.delete(n),e.apiUrl(n))}be.deleteSolution=j5});var hN=v(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.recoverFormCreate=ft.solutionMembershipProblem=ft.formWriteMismatches=ft.validateExistingForm=ft.formExistsAtId=ft.isFormRecordAt=ft.MAIN_FORM_TYPE=void 0;var us=se(),cN=Lt(),dN=wg();ft.MAIN_FORM_TYPE=2;function Sd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Nd(e){return e instanceof Error?e.message:String(e)}function Cg(e,t){if(typeof e!="string"||typeof t!="string")return!1;try{return(0,us.normalizeGuid)(e,"a GUID")===(0,us.normalizeGuid)(t,"a GUID")}catch{return!1}}function Eg(e,t){return Sd(e)&&Cg(e.formid,t)}ft.isFormRecordAt=Eg;async function H5(e,t){try{return Eg((await e()).raw,t)}catch{return!1}}ft.formExistsAtId=H5;function fN(e,t){let r=e.raw;if(!Sd(r))return{problem:"it is not a record"};if(!Eg(r,t))return{problem:"its formid is not the id this create sent"};if(r.type!==ft.MAIN_FORM_TYPE)return{problem:`its type is not ${ft.MAIN_FORM_TYPE} (a Main form)`};if(typeof r.objecttypecode!="string")return{problem:"its objecttypecode is not a string"};if(typeof r.name!="string")return{problem:"its name is not a string"};if(typeof r.formxml!="string"||r.formxml.length===0)return{problem:"its formxml is not a non-empty string"};if(typeof r.formpresentation!="number")return{problem:"its formpresentation is not a number"};if(typeof r.formactivationstate!="number")return{problem:"its formactivationstate is not a number"};for(let o of["uniquename","description"]){let a=r[o];if(a!=null&&typeof a!="string")return{problem:`its ${o} is neither a string nor null`}}let n=r["@odata.etag"];if(n!==void 0&&typeof n!="string")return{problem:"its @odata.etag is not a string"};if(n!==void 0&&e.etag!==null&&e.etag!==n)return{problem:"the ETag header and the @odata.etag of the body disagree"};let i=e.etag;return i===null?{problem:"the read carries no concurrency token"}:i.trim()===""||i.trim()==="*"?{problem:"its concurrency token is blank or a wildcard"}:{record:r,etag:i}}ft.validateExistingForm=fN;function pN(e,t){let r=[];for(let i of["formxml","name","objecttypecode","type"])e[i]!==t[i]&&r.push(i);let n=t.description;if(n!==void 0){let i=e.description;typeof n=="string"&&(n===""?i==null||i==="":i===n)||r.push("description")}return r}ft.formWriteMismatches=pN;async function mN(e,t){let r=e.solutionName;if(r)try{let n=await(0,cN.collectPages)(e,`/solutions${(0,us.odataQuery)([["$select","solutionid,uniquename"],["$filter",`uniquename eq '${(0,us.odataLiteral)(r)}'`]])}`,"createRecovery solution lookup");if(n.length!==1)return`the configured solution '${r}' resolves to ${n.length} solutions, not exactly one`;let[i]=n,o;return Sd(i)&&typeof i.uniquename=="string"&&typeof i.solutionid=="string"&&i.uniquename.toLowerCase()===r.toLowerCase()&&(o=(0,us.normalizeGuid)(i.solutionid,"solutionid")),o===void 0?`the configured solution '${r}' did not resolve to a valid solution of that name`:(await(0,cN.collectPages)(e,`/solutioncomponents${(0,us.odataQuery)([["$select","objectid,componenttype,_solutionid_value"],["$filter",`_solutionid_value eq ${o} and componenttype eq ${dN.SolutionComponentType.SystemForm} and objectid eq ${t}`]])}`,"createRecovery solution membership")).some(l=>Sd(l)&&l.componenttype===dN.SolutionComponentType.SystemForm&&Cg(l.objectid,t)&&Cg(l._solutionid_value,o))?void 0:`the form is not a component of the configured solution '${r}'`}catch(n){return`membership in the configured solution '${r}' could not be established (${Nd(n)})`}}ft.solutionMembershipProblem=mN;async function K5(e){try{return await J5(e)}catch(t){return{refused:`the recovery could not be completed (${Nd(t)})`}}}ft.recoverFormCreate=K5;async function J5(e){let{client:t,read:r,sent:n,authoredFormType:i,project:o}=e;if(i!=="Main"||n.type!==ft.MAIN_FORM_TYPE)return{refused:`only a Main form is adopted (this one is authored as ${String(i)})`};let a=n.formid;if(typeof a!="string")return{refused:"the create sent no formid to look for"};let s;try{s=await r()}catch(f){return{refused:`the existing row could not be read (${Nd(f)})`}}let l=fN(s,a);if("problem"in l)return{refused:`the existing row cannot be trusted: ${l.problem}`};let u=pN(l.record,n);if(u.length>0)return{refused:`the existing row is not what this create wrote (it differs in ${u.join(", ")})`};let c;try{c=o(l.record)}catch(f){return{refused:`the existing row could not be read into a form (${Nd(f)})`}}let d=await mN(t,a);return d!==void 0?{refused:d}:{adopted:{artifact:c,etag:l.etag}}}});var Td=v(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.disassociateRecords=Je.associateRecords=Je.createRecordsBulk=Je.upsertRecord=Je.queryAllRecords=Je.queryRecords=Je.getRecord=Je.deleteRecord=Je.updateRecord=Je.createRecord=void 0;var Ag=Lt(),Sn=ye(),Jt=se(),cs=Q(),Jn=cd();function _d(e){let t=e,r=!1,n={};for(let i of Object.keys(t)){let o=t[i];Array.isArray(o)&&o.every(a=>typeof a=="number")?(n[i]=o.join(","),r=!0):n[i]=o}return r?n:e}async function Y5(e,t,r){let i=`/${await(0,Jn.resolveEntitySetName)(e,t)}`,o=(0,Sn.ensureSuccess)(await e.post(i,_d(r)),e.apiUrl(i)),a=(0,Sn.readCreatedId)(o,`${t}id`);if(!a)throw new cs.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}Je.createRecord=Y5;async function Q5(e,t,r,n){let i=(0,Jt.normalizeGuid)(r,"id"),a=`/${await(0,Jn.resolveEntitySetName)(e,t)}(${i})`;(0,Sn.ensureSuccess)(await e.patch(a,_d(n)),e.apiUrl(a))}Je.updateRecord=Q5;async function X5(e,t,r){let n=(0,Jt.normalizeGuid)(r,"id"),o=`/${await(0,Jn.resolveEntitySetName)(e,t)}(${n})`;(0,Sn.ensureSuccess)(await e.delete(o),e.apiUrl(o))}Je.deleteRecord=X5;async function Z5(e,t,r,n){let i=(0,Jt.normalizeGuid)(r,"id"),o=await(0,Jn.resolveEntitySetName)(e,t),a=(0,Jt.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),s=`/${o}(${i})${a}`,l=(0,Sn.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=l.body;if(u===null||typeof u!="object"||Array.isArray(u))throw new cs.ConnectionError(e.apiUrl(s),l.status,`getRecord: read returned a malformed row \u2014 expected an OData entity object but got ${Array.isArray(u)?"an array":(0,Ag.describeMalformedValue)(u)}; refusing to read it as a row.`);return u}Je.getRecord=Z5;function e8(e){return e?.fetchXml?(0,Jt.odataQuery)([["fetchXml",e.fetchXml]]):(0,Jt.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 gN(e,t,r){var n;if(r?.paginate){if(r.top!==void 0)throw new cs.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 cs.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,Jn.resolveEntitySetName)(e,t)}${e8(r)}`;if(r?.paginate)return(0,Ag.collectPages)(e,o,"queryRecords");let a=(0,Sn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new cs.ConnectionError(e.apiUrl(o),a.status,`queryRecords: read returned a malformed page \u2014 expected an OData 'value' array but got ${(0,Ag.describeMalformedValue)(s)}; refusing to read it as rows.`);return s}Je.queryRecords=gN;async function t8(e,t,r){return gN(e,t,{...r,paginate:!0})}Je.queryAllRecords=t8;function r8(e){if("id"in e)return`(${(0,Jt.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,Jt.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,Jt.assertODataName)(e.key,"alternate key name")}=${t})`}async function n8(e,t,r,n){let i=r8(r),a=`/${await(0,Jn.resolveEntitySetName)(e,t)}${i}`,s=(0,Sn.ensureSuccess)(await e.patch(a,_d(n)),e.apiUrl(a)),l=s.status===201,u=(0,Sn.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,Jt.normalizeGuid)(r.id,"id"):""),created:l}}Je.upsertRecord=n8;async function i8(e,t,r){var n,i;if(r.length===0)return[];let o=await(0,Jn.resolveEntitySetName)(e,t),a=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,..._d(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Sn.ensureSuccess)(await e.post(s,{Targets:a}),e.apiUrl(s)).body)===null||n===void 0?void 0:n.Ids)!==null&&i!==void 0?i:[];if(u.length!==r.length)throw new cs.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Je.createRecordsBulk=i8;async function o8(e,t,r,n){let i=(0,Jt.normalizeGuid)(r,"id"),o=(0,Jt.normalizeGuid)(n.targetId,"targetId"),a=await(0,Jn.resolveEntitySetName)(e,t),s=await(0,Jn.resolveEntitySetName)(e,n.targetEntity),l=(0,Jt.assertODataName)(n.relationshipName,"relationshipName"),u=`/${a}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,Sn.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Je.associateRecords=o8;async function a8(e,t,r,n,i){let o=(0,Jt.normalizeGuid)(r,"id"),a=(0,Jt.normalizeGuid)(i,"targetId"),s=await(0,Jn.resolveEntitySetName)(e,t),l=(0,Jt.assertODataName)(n,"relationshipName"),u=`/${s}(${o})/${l}(${a})/$ref`;(0,Sn.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Je.disassociateRecords=a8});var Dd=v(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.base64ToUtf8=on.base64ToBytes=on.bytesToBase64=on.utf8ToBase64=on.utf8ToBytes=void 0;var Sg=32768,Nr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function tu(){return globalThis}function yN(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=r+1<e.length?e.charCodeAt(r+1):0;i>=56320&&i<=57343?(n=(n-55296<<10)+(i-56320)+65536,r+=1):n=65533}else n>=56320&&n<=57343&&(n=65533);n<128?t.push(n):n<2048?t.push(192|n>>6,128|n&63):n<65536?t.push(224|n>>12,128|n>>6&63,128|n&63):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return Uint8Array.from(t)}function s8(e){let t="";for(let r=0;r<e.length;r+=Sg)t+=String.fromCharCode(...e.subarray(r,r+Sg));return t}function l8(e){let t="";for(let r=0;r<e.length;r+=1){let n=String.fromCharCode(e.charCodeAt(r)&255);if(n==="=")break;n==="-"?t+="+":n==="_"?t+="/":Nr.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function u8(e){let t="",r=0;for(;r+2<e.length;r+=3){let i=e[r]<<16|e[r+1]<<8|e[r+2];t+=Nr[i>>18&63]+Nr[i>>12&63]+Nr[i>>6&63]+Nr[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Nr[i>>18&63]}${Nr[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,o=Nr[i>>18&63],a=Nr[i>>12&63],s=Nr[i>>6&63];t+=`${o}${a}${s}=`}return t}function c8(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0,r=e.length/4*3-t,n=new Uint8Array(r>0?r:0),i=0;for(let o=0;o<e.length;o+=4){let a=Nr.indexOf(e[o])<<18|Nr.indexOf(e[o+1])<<12|(e[o+2]==="="?0:Nr.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:Nr.indexOf(e[o+3]));i<r&&(n[i++]=a>>16&255),i<r&&(n[i++]=a>>8&255),i<r&&(n[i++]=a&255)}return n}function d8(e){let t=tu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"utf8"));let r=t.TextEncoder;return r?new r().encode(e):yN(e)}on.utf8ToBytes=d8;function f8(e){let t=tu();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return bN(r?new r().encode(e):yN(e))}on.utf8ToBase64=f8;function bN(e){let t=tu();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(s8(e)):u8(e)}on.bytesToBase64=bN;function vN(e){let t=tu();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=l8(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return c8(r)}on.base64ToBytes=vN;function p8(e){let t=[],r="",n=()=>{r+=String.fromCharCode(...t),t.length=0},i=a=>{if(a>65535){let s=a-65536;t.push(55296+(s>>10),56320+(s&1023))}else t.push(a);t.length>=Sg&&n()},o=0;for(;o<e.length;){let a=e[o],s=0,l=0,u=128,c=191;if(a<128){i(a),o+=1;continue}else if(a>=194&&a<=223)s=1,l=a&31;else if(a>=224&&a<=239)s=2,l=a&15,u=a===224?160:128,c=a===237?159:191;else if(a>=240&&a<=244)s=3,l=a&7,u=a===240?144:128,c=a===244?143:191;else{i(65533),o+=1;continue}let d=o+1,f=!0;for(let m=0;m<s;m+=1,d+=1){let p=d<e.length?e[d]:-1;if(p<u||p>c){f=!1;break}u=128,c=191,l=l<<6|p&63}f?(i(l),o=d):(i(65533),o=d)}return n(),r}function m8(e){let t=tu();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):p8(vN(e))}on.base64ToUtf8=m8});var AN=v(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.deleteWebResource=Yn.getWebResource=Yn.updateWebResource=Yn.createWebResource=void 0;var h8=Jr(),ru=ye(),Id=se(),g8=Dd(),wN=Q(),y8={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function CN(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,g8.utf8ToBase64)(e.content)}async function EN(e,t){return(0,h8.publishWebResourceById)(e,t)}async function b8(e,t){var r;let n=CN(t);if(n===void 0)throw new wN.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:y8[t.type],content:n};t.description&&(i.description=t.description);let o=(0,ru.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,ru.readCreatedId)(o,"webresourceid");if(!a)throw new wN.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&await EN(e,a),{id:a,name:t.name}}Yn.createWebResource=b8;async function v8(e,t,r){let n=(0,Id.normalizeGuid)(t,"id"),i={},o=CN(r);o!==void 0&&(i.content=o),r.displayName!==void 0&&(i.displayname=r.displayName),r.description!==void 0&&(i.description=r.description);let a=`/webresourceset(${n})`;(0,ru.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),r.publish!==!1&&await EN(e,n)}Yn.updateWebResource=v8;async function w8(e,t){var r;let i=`/webresourceset(${(0,Id.normalizeGuid)(t,"id")})${(0,Id.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,ru.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}Yn.getWebResource=w8;async function C8(e,t){let n=`/webresourceset(${(0,Id.normalizeGuid)(t,"id")})`;(0,ru.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Yn.deleteWebResource=C8});var Od=v(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.applyAppSettings=Tt.setAppSetting=Tt.readAppSettings=Tt.resolveSettingDefinitions=Tt.APP_SETTING_UNSET=Tt.APP_SETTING_OFF=Tt.APP_SETTING_ON=Tt.HEADER_AND_NAVIGATION_REFRESH=void 0;var ds=ye(),Ii=se();Tt.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";Tt.APP_SETTING_ON="2";Tt.APP_SETTING_OFF="1";Tt.APP_SETTING_UNSET="0";function _N(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ii.odataQuery)([["$select",e],["$filter",t]])}async function TN(e,t){var r,n;let i=[...new Set(t.filter(Boolean))],o=new Map;if(i.length===0)return o;let a=i.map(c=>`uniquename eq '${(0,Ii.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,Ii.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",a]])}`,u=((n=(r=(0,ds.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&&o.set(c.uniquename,c);return o}Tt.resolveSettingDefinitions=TN;async function E8(e,t){var r,n,i,o;let a=(0,Ii.normalizeGuid)(t,"App id"),s=_N("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${a}`),u=((n=(r=(0,ds.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(f=>f._settingdefinitionid_value).filter(Boolean))],d=new Map;if(c.length>0){let f=c.map(h=>`settingdefinitionid eq ${(0,Ii.normalizeGuid)(h,"Setting definition id")}`).join(" or "),m=`/settingdefinitions${(0,Ii.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",f]])}`,p=(0,ds.ensureSuccess)(await e.get(m),e.apiUrl(m));for(let h of((o=(i=p.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[]).filter(Boolean))h.settingdefinitionid&&d.set(h.settingdefinitionid.toLowerCase(),h)}return u.map(f=>{var m,p,h,g,b;let w=d.get(((m=f._settingdefinitionid_value)!==null&&m!==void 0?m:"").toLowerCase());return{id:(p=f.appsettingid)!==null&&p!==void 0?p:"",name:(g=(h=w?.uniquename)!==null&&h!==void 0?h:f._settingdefinitionid_value)!==null&&g!==void 0?g:"",value:(b=f.value)!==null&&b!==void 0?b:"",...w?.displayname?{displayName:w.displayname}:{}}})}Tt.readAppSettings=E8;async function SN(e,t,r){var n,i,o;let a=_N("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,ds.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(Boolean)[0];return l?.appsettingid?{id:l.appsettingid,value:(o=l.value)!==null&&o!==void 0?o:""}:void 0}async function DN(e,t,r,n){let i=(0,Ii.normalizeGuid)(t,"App id"),a=(await TN(e,[r])).get(r),s=a?.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,Ii.normalizeGuid)(s,"Setting definition id"),u=await SN(e,i,l);if(u)return NN(e,u,n);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${l})`,value:n},f,m;try{if(f=await e.post(c,d),f.status>=200&&f.status<300)return"created"}catch(h){m=h}let p;try{p=await SN(e,i,l)}catch{p=void 0}if(p)return NN(e,p,n);throw f&&(0,ds.ensureSuccess)(f,e.apiUrl(c)),m}Tt.setAppSetting=DN;async function NN(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,Ii.normalizeGuid)(t.id,"App setting id")})`;return(0,ds.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function A8(e,t,r){var n;let i=[];for(let[o,a]of Object.entries(r??{}))try{await DN(e,t,o,a)}catch(s){i.push(`App setting '${o}' was not applied: ${(n=s?.message)!==null&&n!==void 0?n:String(s)} The app was created; set it later with setAppSetting().`)}return i}Tt.applyAppSettings=A8});var Rd=v(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});Pd.HEADER_NAV_BOOLEAN_RULE=void 0;Pd.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var Tg=v(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.compileGenPage=Le.legacyEnumsNeeded=Le.createGenPageTypeScriptLoader=Le.acceptGenPageTypeScript=Le.isLoadableGenPageOutput=Le.runtimeTypesImportSpans=Le.GENPAGE_RUNTIME_TYPES_END=Le.GENPAGE_RUNTIME_TYPES_BEGIN=Le.GENPAGE_TYPESCRIPT_VERSION=void 0;var fs=Q();Le.GENPAGE_TYPESCRIPT_VERSION="5.8.3";Le.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";Le.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var Nn="./RuntimeTypes",S8="'\"`",IN=/\s/;function N8(e){return e===10||e===13||e===8232||e===8233}function _8(e,t){let r=[];e.lastIndex=0;for(let n=e.exec(t);n!==null;n=e.exec(t))r.push(n.index);return r}function LN(e){let t=[],r=Nn.length;for(let l=e.indexOf(Nn);l!==-1;l=e.indexOf(Nn,l+1)){let u=l-1;u>=0&&S8.includes(e[u])&&e[u+1+r]===e[u]&&t.push(u)}let n=[];if(t.length===0)return n;let i=-1,o=l=>{if(i<l)for(i=l;i<e.length&&e[i]!=="'"&&e[i]!=='"';)i+=1;return i},a=-1,s=l=>{for(;a+1<t.length&&t[a+1]<=l;)a+=1;return a>=0?t[a]:-1/0};for(let l=e.indexOf("import");l!==-1;){let u=l+1;if(l+6<e.length&&IN.test(e[l+6])){let c=s(o(l+6));if(c>=l+8){let d=c+2+r;for(e[d]===";"&&(d+=1);d<e.length&&IN.test(e[d]);)d+=1;n.push({start:l,end:d}),u=d}}l=e.indexOf("import",u)}return n}Le.runtimeTypesImportSpans=LN;var T8=/\b(?:import\s*['"]|export\s)/;function D8(e){let t=_8(/from\s+['"]/g,e);if(t.length===0)return!1;let r=/\bimport\s/g,n=-1,i=0;for(let o=r.exec(e);o!==null;o=r.exec(e)){let a=o.index+7;if(a>n)for(n=a;n<e.length&&!N8(e.charCodeAt(n));)n+=1;for(;i<t.length&&t[i]<a+1;)i+=1;if(i<t.length&&t[i]<n)return!0}return!1}function I8(e){return e!==void 0&&e!==""&&(T8.test(e)||D8(e))}Le.isLoadableGenPageOutput=I8;var ON=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function kN(e){var t;let r=s=>s!==null&&(typeof s=="object"||typeof s=="function")?s:void 0,n=r(e);n&&typeof n.transpileModule!="function"&&(n=(t=r(n.default))!==null&&t!==void 0?t:n);let i=n?ON.filter(s=>typeof n?.[s]!="function"):[...ON];if(!n||i.length>0)throw new fs.SdkError("GENPAGE_COMPILER_INVALID",`The TypeScript compiler supplied as MakerSdkOptions.typescript is not the typescript module (missing ${i.join(", ")}). Pass the 'typescript' package's module object, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node', or \u2014 in a bare engine \u2014 globalThis.ts after evaluating typescript@${Le.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof n.version=="string"?n.version:"",a=Le.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new fs.SdkError("GENPAGE_COMPILER_VERSION",`The TypeScript compiler supplied as MakerSdkOptions.typescript is version '${o||"unknown"}', but generative pages are compiled with ${a}.x \u2014 the version the maker portal itself uses (${Le.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${Le.GENPAGE_TYPESCRIPT_VERSION}.`);return n}Le.acceptGenPageTypeScript=kN;function O8(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new fs.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`This push must compile a generative page, but no TypeScript compiler was supplied. Pass MakerSdkOptions.typescript \u2014 in Node, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node'; in a bare engine, globalThis.ts after evaluating typescript@${Le.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(kN).catch(r=>{throw t=void 0,r instanceof fs.SdkError?r:new fs.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`The TypeScript compiler could not be loaded, so a generative page cannot be compiled (${r instanceof Error?r.message:String(r)}). Nothing was written.`)})}return t}}Le.createGenPageTypeScriptLoader=O8;var $N=e=>`${e.kind}:${e.pos}:${e.end}`;function P8(e,t){return()=>r=>{let n=i=>{let o=e.getParseTreeNode(i);o&&t.add($N(o)),e.forEachChild(i,n)};return n(r),r}}function _g(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}var R8=2301;function PN(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:_g(e),reportDiagnostics:!0,...r?{transformers:{after:[P8(e,r)]}}:{}}),o=((n=i.diagnostics)!==null&&n!==void 0?n:[]).filter(a=>a.category===e.DiagnosticCategory.Error).map(a=>{let s=a.file&&typeof a.start=="number"?a.file.getLineAndCharacterOfPosition(a.start):{line:0,character:0};return{line:s.line+1,column:s.character+1,rule:"genpage-source-syntax",code:a.code,message:e.flattenDiagnosticMessageText(a.messageText,`
-`)}});return{code:i.outputText,diagnostics:o}}var RN=e=>e.startsWith(".")||e.startsWith("/"),Ld={line:1,column:1};function Ng(e,t){let r=o=>{let a=t.getLineAndCharacterOfPosition(o.getStart(t));return{line:a.line+1,column:a.character+1}},n=o=>(e.isImportDeclaration(o)||e.isExportDeclaration(o))&&o.moduleSpecifier&&e.isStringLiteral(o.moduleSpecifier)?o.moduleSpecifier.text:void 0,i=o=>t.statements.filter(a=>e.isImportDeclaration(a)&&n(a)===o);return{statement(o,a){let s=t.statements.find(l=>n(l)===o&&(a==="import"?e.isImportDeclaration(l):e.isExportDeclaration(l)));return s?r(s):Ld},element(o,a){var s;for(let l of i(o)){let u=(s=l.importClause)===null||s===void 0?void 0:s.namedBindings,c=u&&e.isNamedImports(u)?u.elements.find(d=>d.name.text===a):void 0;if(c)return r(c)}return this.statement(o,"import")},binding(o){var a,s;for(let l of t.statements)if(e.isImportDeclaration(l)&&l.importClause){let u=l.importClause,c=u.namedBindings,d=((a=u.name)===null||a===void 0?void 0:a.text)===o?u.name:c&&e.isNamespaceImport(c)&&c.name.text===o?c.name:c&&e.isNamedImports(c)?c.elements.find(f=>f.name.text===o):void 0;if(d)return r(d)}else{if((e.isFunctionDeclaration(l)||e.isClassDeclaration(l))&&((s=l.name)===null||s===void 0?void 0:s.text)===o)return r(l.name);if(e.isVariableStatement(l)){let u=l.declarationList.declarations.find(c=>e.isIdentifier(c.name)&&c.name.text===o);if(u)return r(u.name)}}return Ld}}}function L8(e,t,r,n){var i,o;let a=[],s=Ng(e,r),l=(p,h,g)=>{a.push({...p,rule:h,code:0,message:g})},u=(p,h)=>{var g;return(e.canHaveModifiers(p)?(g=e.getModifiers(p))!==null&&g!==void 0?g:[]:[]).some(b=>b.kind===h)},c=(p,h)=>l(p,"genpage-relative-import",`'${h}' cannot resolve at runtime: the page is loaded as a single module from a blob URL, so the only relative import it may have is './RuntimeTypes'`),d="genpage-runtime-types-import-form",f=!1,m=new Set;for(let p of t.statements){if(e.isExportAssignment(p)){f=f||!p.isExportEquals;continue}if(e.isFunctionDeclaration(p)||e.isClassDeclaration(p)){u(p,e.SyntaxKind.ExportKeyword)&&u(p,e.SyntaxKind.DefaultKeyword)&&(f=!0),p.name&&m.add(p.name.text);continue}if(e.isExportDeclaration(p)){let w=p.exportClause;w&&e.isNamedExports(w)&&w.elements.some(S=>S.name.text==="default")&&(f=!0);let E=p.moduleSpecifier&&e.isStringLiteral(p.moduleSpecifier)?p.moduleSpecifier.text:void 0;E===Nn?l(s.statement(E,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):E!==void 0&&RN(E)&&c(s.statement(E,"export"),E);continue}if(!e.isImportDeclaration(p)||!e.isStringLiteral(p.moduleSpecifier))continue;let h=p.moduleSpecifier.text,g=p.importClause;if(h!==Nn){RN(h)&&c(s.statement(h,"import"),h),g?.name&&m.add(g.name.text);let w=g?.namedBindings;w&&e.isNamespaceImport(w)?m.add(w.name.text):w&&e.isNamedImports(w)&&w.elements.forEach(E=>m.add(E.name.text));continue}if(!g){l(s.statement(h,"import"),d,"a side-effect import of './RuntimeTypes' cannot resolve at runtime; import the names it declares");continue}g.name&&l(s.binding(g.name.text),d,"'./RuntimeTypes' has no default export at runtime; import its names");let b=g.namedBindings;if(b&&e.isNamespaceImport(b))l(s.binding(b.name.text),d,"a namespace import of './RuntimeTypes' is undefined at runtime \u2014 its enums are inlined under their own names; import the names instead");else if(b&&e.isNamedImports(b))for(let w of b.elements){let E=w.name.text,S=(o=(i=w.propertyName)===null||i===void 0?void 0:i.text)!==null&&o!==void 0?o:E,P=s.element(h,E);S!==E?l(P,d,`'${S} as ${E}' would be undefined at runtime: the enum is inlined as '${S}', so import it under its own name`):n?.text?n.enums.has(E)||l(P,"genpage-runtime-types-unresolved",`'${E}' is imported from './RuntimeTypes' as a VALUE, but the runtime types define no value of that name \u2014 only the choice enums of the page's data sources are values. Import a type with 'import type'.`):l(P,"genpage-runtime-types-unresolved",`'${E}' is imported from './RuntimeTypes' as a VALUE, but the page has no data sources, so no runtime types are inlined and the import reaches the runtime, which cannot load it. Import it with 'import type', or add the table it belongs to to dataSources.`)}}if(f||l(Ld,"genpage-no-default-export","the page has no default export \u2014 the runtime renders the module's default export as the page component"),n?.text)for(let p of m)n.enums.has(p)&&l(s.binding(p),"genpage-runtime-types-collision",`'${p}' is declared at the page's module scope and is also one of its inlined choice enums, so the compiled page would declare it twice and fail to load. Rename the page's binding, or import the enum from './RuntimeTypes'.`);return a}function xN(e,t,r){let n,i=()=>{if(!n){let p={getSourceFile:g=>g===t.fileName?t:void 0,getDefaultLibFileName:()=>"lib.d.ts",writeFile:()=>{},getCurrentDirectory:()=>"",getCanonicalFileName:g=>g,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>`
-`,fileExists:g=>g===t.fileName,readFile:()=>{},directoryExists:()=>!0,getDirectories:()=>[]},h={...r,noLib:!0,noResolve:!0,allowJs:!0,types:[],alwaysStrict:!0,moduleDetection:e.ModuleDetectionKind.Force};n=e.createProgram({rootNames:[t.fileName],options:h,host:p})}return n},o,a=()=>(o||(o=i().getTypeChecker()),o),s,l=()=>{if(!s){s=new Map;try{for(let p of i().getSemanticDiagnostics(t))p.code===R8&&typeof p.start=="number"&&s.set(p.start,e.flattenDiagnosticMessageText(p.messageText," "))}catch{}}return s},u=p=>e.isImportSpecifier(p)?p.parent.parent.parent:e.isImportClause(p)?p.parent:e.isNamespaceImport(p)?p.parent.parent:void 0,c=p=>{let h=u(p);return h!==void 0&&e.isImportDeclaration(h)&&e.isStringLiteral(h.moduleSpecifier)&&h.moduleSpecifier.text===Nn},d=p=>{var h;for(let g=p;g;g=g.parent)if(e.canHaveModifiers(g)&&((h=e.getModifiers(g))!==null&&h!==void 0?h:[]).some(b=>b.kind===e.SyntaxKind.DeclareKeyword))return!0;return!1},f=p=>d(p)||e.isImportEqualsDeclaration(p)&&(p.isTypeOnly||e.isExternalModuleReference(p.moduleReference))||e.isImportClause(p)&&p.isTypeOnly||e.isNamespaceImport(p)&&p.parent.isTypeOnly||e.isImportSpecifier(p)&&(p.isTypeOnly||p.parent.parent.isTypeOnly),m=p=>{var h;return((h=p?.declarations)!==null&&h!==void 0?h:[]).some(g=>!c(g)&&!f(g))};return{pageOwns:p=>{let h=p.parent;return m(e.isShorthandPropertyAssignment(h)&&h.name===p?a().getShorthandAssignmentValueSymbol(h):a().getSymbolAtLocation(p))},pageOwnsLocalExport:p=>m(a().getExportSpecifierLocalTargetSymbol(p)),initializerShadow:p=>l().get(p.getStart(t))}}function k8(e,t,r,n){let i=[],o=r?.enums;if(!o||o.size===0)return i;let a=(u,c,d)=>{let f=t.getLineAndCharacterOfPosition(u.getStart(t));i.push({line:f.line+1,column:f.character+1,rule:c,code:0,message:d})},s=xN(e,t,_g(e)),l=u=>{let c,d;if(e.isPropertyAccessExpression(u)&&e.isIdentifier(u.expression))c=u.expression,d=u.name.text;else if(e.isElementAccessExpression(u)&&e.isIdentifier(u.expression)){let m=u.argumentExpression;e.isStringLiteral(m)||e.isNoSubstitutionTemplateLiteral(m)?(c=u.expression,d=m.text):e.isNumericLiteral(m)&&(c=u.expression,d=String(Number(m.text)))}let f=c&&o.has(c.text)&&n.has($N(u))&&!s.pageOwns(c)?o.get(c.text):void 0;if(c&&f&&d!==void 0){let m=e.isPropertyAccessExpression(u)?`${f.name}.${d}`:`${f.name}[${JSON.stringify(d)}]`,p=Object.prototype.hasOwnProperty.call(f.runtime,d)?f.runtime[d]:void 0,h=f.labels.get(d),g;p===void 0?g={rule:"genpage-enum-member-unknown",message:`${m} is undefined at runtime: '${f.name}' has no member '${d}' in this environment's metadata \u2014 members are the column's choice labels, so a renamed or differently localized label no longer matches. Known: ${[...f.labels.keys()].map(w=>`'${w}'`).join(", ")}`}:h&&typeof p!="number"?g={rule:"genpage-enum-member-clobbered",message:`${m} is the string '${String(p)}' at runtime, not a choice value: the label '${d}' looks like a number, and another option's reverse mapping overwrites it. Use the choice's numeric value instead.`}:h&&h.length>1&&(g={rule:"genpage-enum-member-ambiguous",message:`${m} labels more than one choice (${h.join(", ")}); the compiled value is whichever option comes last. Use the choice's numeric value instead.`});let b=g?s.initializerShadow(c):void 0;g&&b!==void 0?a(u,"genpage-enum-initializer-shadowed",`${m} does not read the choice enum at runtime. ${b} (TS2301): the ES5 emit moves an instance field's initializer into the constructor, where that parameter or local shadows '${c.text}'. If you meant the constructor's '${c.text}', move the assignment into the constructor body, or make it a parameter property and read \`this.${c.text}\`. If you meant the choice enum, rename the constructor's parameter or local.`):g&&a(u,g.rule,g.message)}e.forEachChild(u,l)};return l(t),i}function $8(e,t){return e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!1,e.ScriptKind.JS).statements.some(n=>(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier!==void 0&&e.isStringLiteral(n.moduleSpecifier)&&n.moduleSpecifier.text===Nn)}function FN(e,t){return t.statements.filter(r=>e.isImportDeclaration(r)&&e.isStringLiteral(r.moduleSpecifier)&&r.moduleSpecifier.text===Nn).map(r=>r.getStart(t))}function x8(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=FN(e,r),i=new Set(n),o,a="",s=0;for(let l of LN(t))!o&&!i.has(l.start)&&(o={swallows:n.some(u=>u>l.start&&u<l.end),text:t.slice(l.start,l.end).trimEnd()}),a+=t.slice(s,l.start),s=l.end;return a+=t.slice(s),{code:a,inexact:o}}function F8(e,t,r){let n=new Set(FN(e,t));for(let i=t.text.indexOf(r);i!==-1;i=t.text.indexOf(r,i+1))if(!n.has(i)){let o=t.getLineAndCharacterOfPosition(i);return{line:o.line+1,column:o.character+1}}return Ld}function MN(e,t,r){if(!r||r.size===0)return[];let n=xN(e,t,{..._g(e),target:e.ScriptTarget.ESNext}),i=new Set,o=s=>{var l,u;let c=s.parent;if(e.isImportSpecifier(c)){let d=c.parent.parent.parent;e.isImportDeclaration(d)&&e.isStringLiteral(d.moduleSpecifier)&&d.moduleSpecifier.text===Nn&&((l=c.propertyName)!==null&&l!==void 0?l:c.name)===s&&i.add(s.text);return}if(e.isExportSpecifier(c)){!(c.parent.parent.moduleSpecifier!==void 0)&&((u=c.propertyName)!==null&&u!==void 0?u:c.name)===s&&!n.pageOwnsLocalExport(c)&&i.add(s.text);return}e.isPropertyAccessExpression(c)&&c.name===s||e.isBindingElement(c)&&c.propertyName===s||e.isLabeledStatement(c)||e.isBreakOrContinueStatement(c)||n.pageOwns(s)||i.add(s.text)},a=s=>{e.isIdentifier(s)&&r.has(s.text)&&o(s),e.forEachChild(s,a)};return a(t),[...r.keys()].filter(s=>i.has(s))}Le.legacyEnumsNeeded=MN;function M8(e,t,r){if(!e?.text||!t||r.length===0)return e;let n=new Map(e.enums),i=e.text;for(let o of r){let a=t.get(o);a&&(i+=a.declaration,n.set(o,a.model))}return{text:i,enums:n}}function U8(e,t,r,n){var i;let o=new Set,a=PN(e,t,o);if(a.diagnostics.length>0)return a;let s=e.createSourceFile("page.tsx",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.TSX),l=e.createSourceFile("page.js",a.code,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),u=M8(r,n,MN(e,l,n)),c=[...L8(e,l,s,u),...k8(e,s,u,o)];if(!u?.text)return{code:a.code,diagnostics:c};let d=PN(e,u.text);if(d.diagnostics.length>0)throw new fs.SdkError("GENPAGE_RUNTIME_TYPES_INVALID",`The generated runtime types do not compile (${d.diagnostics.map(h=>`${h.line}:${h.column} ${h.message}`).join("; ")}). This is an SDK defect: the page was not written.`);let f=x8(e,a.code),m=f.code;if(c.length===0&&(!((i=f.inexact)===null||i===void 0)&&i.swallows))c.push({...Ng(e,s).statement(Nn,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"the maker portal's patch would remove more than this './RuntimeTypes' import: a comment or other text before it contains the word 'import', and the pattern would delete from there \u2014 taking the code in between with it. Reword or move that text."});else if(c.length===0&&f.inexact){let{text:h}=f.inexact;c.push({...F8(e,s,h),rule:"genpage-runtime-types-import-form",code:0,message:`the maker portal's patch would delete \`${h.length>80?`${h.slice(0,79)}\u2026`:h}\` from text that only looks like an import of './RuntimeTypes' \u2014 in a string, a template or a comment \u2014 so the page it ships would differ from this source. Reword that text so it no longer reads as such an import.`})}else c.length===0&&$8(e,m)&&c.push({...Ng(e,s).statement(Nn,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"this './RuntimeTypes' import is not one the maker portal's patch can remove (a comment holding a quote inside it stops the pattern), so it would reach the runtime, which cannot load it. Write it on one line, as 'import { name } from './RuntimeTypes';'."});return{code:[Le.GENPAGE_RUNTIME_TYPES_BEGIN,d.code,Le.GENPAGE_RUNTIME_TYPES_END,m].join(`
+`).slice(1)){let l=s.indexOf(":");l>0&&(o[s.slice(0,l).trim()]=s.slice(l+1).trim())}let a=i===""?void 0:i;if(i!=="")try{a=JSON.parse(i)}catch{}return{status:e.status,headers:o,body:a}}Kt.partResponse=Xh;function yS(e){let t=e.path.indexOf("?");return t===-1?e.path:e.path.slice(0,t)}function zG(e,t){let r=e.find(n=>(0,Yo.isVersionToken)(n.etag));if(!r||e.some(n=>yS(n)!==yS(r)))throw new Ii.InvalidArgumentError(`the change set writing ${t} cannot be re-sent under the customization lock: it needs an operation conditioned on a version token and every operation writing that operation's row`)}function vS(e,t){var r;if(e.status!==429&&(e.status<200||e.status>=300))return!1;let n=(r=yd(e.body,t))===null||r===void 0?void 0:r.filter(i=>i.status<200||i.status>=300);return n!==void 0&&n.length>0&&n.every(i=>(0,Yo.isConcurrencyLockRefusal)(Xh(i)))}Kt.isChangeSetLockRefusal=vS;async function jG(e,t,r,n={}){n.resendWhileLockRefused&&zG(t,r);let{body:i,batchId:o,contentIds:a}=Qh(e,t),s=()=>e.postBatch(i,o),l=n.resendWhileLockRefused?await(0,Yo.resendWhile)(f=>vS(f,a),s,Yo.LOCK_BACKOFF_MS):await s(),u=e.apiUrl("/$batch"),c=yd(l.body,a),d=c?.find(f=>f.status<200||f.status>=300);if(d&&(0,Yo.ensureSuccess)(Xh(d),e.apiUrl(t[a.indexOf(d.contentId)].path)),(0,Yo.ensureSuccess)(l,u),!c||c.length!==t.length)throw new Ii.ConnectionError(u,l.status,`atomic write of ${r} cannot be confirmed: the $batch response ${c?`reported ${c.length} result(s) for ${t.length} operation(s)`:"could not be parsed"}, so the outcome is unknown`);return a.map(f=>c.find(m=>m.contentId===f))}Kt.sendChangeSet=jG});var bd=v(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.updateTable=ie.deleteAlternateKey=ie.createAlternateKey=ie.deleteGlobalOptionSet=ie.createGlobalOptionSet=ie.deleteRelationship=ie.deleteColumn=ie.updateColumn=ie.deleteTable=ie.createRelationship=ie.insertStatusValue=ie.createCustomerColumn=ie.createColumns=ie.setColumnVisualization=ie.getColumnVisualization=ie.createColumn=ie.createTable=ie.resolveEntitySetName=ie.pluralFallback=void 0;var _e=ye(),te=le(),Jn=Jo(),ge=Q(),HG=Kl(),KG={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 et(e,t){return{"@odata.type":"Microsoft.Dynamics.CRM.Label",LocalizedLabels:JG(e,t)}}var wS=65535;function JG(e,t){let r=(o,a)=>({"@odata.type":"Microsoft.Dynamics.CRM.LocalizedLabel",Label:o,LanguageCode:a});if(typeof e=="string")return[r(e,t)];let n=Object.entries(e);if(!n.length)throw new ge.InvalidArgumentError("a localized label must contain at least one language");let i=new Set;return n.map(([o,a])=>{if(!/^[1-9]\d*$/.test(o))throw new ge.InvalidArgumentError(`localized label key '${o}' is not an LCID (expected a canonical positive integer, e.g. 1033)`);let s=Number(o);if(s>wS)throw new ge.InvalidArgumentError(`localized label LCID ${s} is out of range (1-${wS})`);if(i.has(s))throw new ge.InvalidArgumentError(`localized label LCID ${s} is specified more than once`);if(i.add(s),typeof a!="string")throw new ge.InvalidArgumentError(`localized label for LCID ${s} must be a string`);return r(a,s)})}function NS(e){return typeof e=="string"?`${e}s`:Object.fromEntries(Object.entries(e).map(([t,r])=>{if(typeof r!="string")throw new ge.InvalidArgumentError(`localized label for LCID ${t} must be a string`);return[t,`${r}s`]}))}ie.pluralFallback=NS;function Jl(e){return{Value:e,CanBeChanged:!0,ManagedPropertyLogicalName:"canmodifyrequirementlevelsettings"}}var CS=["None","ApplicationRequired","Recommended"];function tg(e){let t=e.indexOf("_");return t>0?e.slice(0,t):e}function ES(e,t,r){let n=e[t];n&&typeof n=="object"?n.Value=r:e[t]={Value:r}}function Yl(e){let t=(0,_e.readCreatedId)(e,"MetadataId");if(!t)throw new ge.InvalidArgumentError("Dataverse did not return a MetadataId for the created metadata component");return t}function YG(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b,w,C,S,O,k,I,D,P,x;if(t.defaultValue!==void 0&&e!=="boolean")throw new ge.InvalidArgumentError(`createColumn: 'defaultValue' applies to boolean columns, but '${t.schemaName}' is of type '${e}'.`);if(t.integerFormat!==void 0&&e!=="integer")throw new ge.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:(o=t.maxLength)!==null&&o!==void 0?o:2e3,Format:"TextArea"};case"integer":return{"@odata.type":"Microsoft.Dynamics.CRM.IntegerAttributeMetadata",AttributeType:"Integer",AttributeTypeName:{Value:"IntegerType"},Format:(a=t.integerFormat)!==null&&a!==void 0?a:"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:(f=t.precision)!==null&&f!==void 0?f:2,MinValue:(m=t.minValue)!==null&&m!==void 0?m:-1e11,MaxValue:(p=t.maxValue)!==null&&p!==void 0?p:1e11};case"money":return{"@odata.type":"Microsoft.Dynamics.CRM.MoneyAttributeMetadata",AttributeType:"Money",AttributeTypeName:{Value:"MoneyType"},Precision:(h=t.precision)!==null&&h!==void 0?h:2,PrecisionSource:2,MinValue:(g=t.minValue)!==null&&g!==void 0?g:0,MaxValue:(b=t.maxValue)!==null&&b!==void 0?b:1e9};case"boolean":return{"@odata.type":"Microsoft.Dynamics.CRM.BooleanAttributeMetadata",AttributeType:"Boolean",AttributeTypeName:{Value:"BooleanType"},DefaultValue:(w=t.defaultValue)!==null&&w!==void 0?w:!1,OptionSet:{"@odata.type":"Microsoft.Dynamics.CRM.BooleanOptionSetMetadata",TrueOption:{Value:1,Label:et((C=t.trueLabel)!==null&&C!==void 0?C:"Yes",r)},FalseOption:{Value:0,Label:et((S=t.falseLabel)!==null&&S!==void 0?S:"No",r)}}};case"dateTime":return{"@odata.type":"Microsoft.Dynamics.CRM.DateTimeAttributeMetadata",AttributeType:"DateTime",AttributeTypeName:{Value:"DateTimeType"},Format:(O=t.dateFormat)!==null&&O!==void 0?O:"DateAndTime"};case"choice":return AS(t,r,!1);case"multiChoice":return AS(t,r,!0);case"file":return{"@odata.type":"Microsoft.Dynamics.CRM.FileAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"FileType"},MaxSizeInKB:(k=t.maxSizeKb)!==null&&k!==void 0?k:10240};case"image":return{"@odata.type":"Microsoft.Dynamics.CRM.ImageAttributeMetadata",AttributeType:"Virtual",AttributeTypeName:{Value:"ImageType"},IsPrimaryImage:(I=t.isPrimaryImage)!==null&&I!==void 0?I:!1,MaxSizeInKB:(D=t.maxSizeKb)!==null&&D!==void 0?D:10240};case"autonumber":if(!(!((P=t.autoNumberFormat)===null||P===void 0)&&P.trim()))throw new ge.InvalidArgumentError(`createColumn: an 'autonumber' column needs an 'autoNumberFormat' (e.g. 'CDS-{SEQNUM:5}'), but '${t.schemaName}' has none \u2014 without one Dataverse would create a plain text column.`);return{"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},FormatName:{Value:"Text"},MaxLength:(x=t.maxLength)!==null&&x!==void 0?x:100,AutoNumberFormat:t.autoNumberFormat};default:throw new ge.InvalidArgumentError(`unsupported column type '${String(e)}'`)}}function AS(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,te.normalizeGuid)(e.globalChoiceMetadataId,"globalChoiceMetadataId")})`,i;if(!e.options||e.options.length===0)throw new ge.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(o=>({Value:o.value,Label:et(o.label,t)}))},i}var Zh=new WeakMap;async function QG(e,t){var r,n;let i=(r=Zh.get(e))===null||r===void 0?void 0:r.get(t);if(i)return i;let o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')${(0,te.odataQuery)([["$select","EntitySetName"]])}`,s=(n=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.EntitySetName;if(!s)throw new ge.InvalidArgumentError(`could not resolve EntitySetName for '${t}'`);(0,te.assertODataName)(s,`server-derived EntitySetName for '${t}'`);let l=Zh.get(e);return l||(l=new Map,Zh.set(e,l)),l.set(t,s),s}ie.resolveEntitySetName=QG;async function XG(e,t){var r,n,i,o,a,s,l,u,c,d,f,m,p,h,g;let b=t.primaryColumnRequired;if(b!==void 0&&!CS.includes(b))throw new ge.InvalidArgumentError(`createTable: 'primaryColumnRequired' must be one of ${CS.join(", ")}; got '${String(b)}'.`);let w=b!==void 0&&b!=="None";if(w&&!t.primaryColumnAutoNumberFormat&&!e.supportsPut)throw new ge.InvalidArgumentError(`createTable: 'primaryColumnRequired: ${b}' on a plain text primary column needs an HttpClient that implements put(): the platform ignores the level in the create, so the SDK sets it with an update.`);let C=(r=t.languageCode)!==null&&r!==void 0?r:Jn.DEFAULT_LCID,S=tg(t.schemaName),O=(n=t.primaryColumnSchemaName)!==null&&n!==void 0?n:`${S}_Name`,k={"@odata.type":"Microsoft.Dynamics.CRM.StringAttributeMetadata",AttributeType:"String",AttributeTypeName:{Value:"StringType"},SchemaName:O,RequiredLevel:Jl(b??"None"),MaxLength:(i=t.primaryColumnMaxLength)!==null&&i!==void 0?i:100,FormatName:{Value:"Text"},DisplayName:et((o=t.primaryColumnDisplayName)!==null&&o!==void 0?o:"Name",C),IsPrimaryName:!0};t.primaryColumnAutoNumberFormat&&(k.AutoNumberFormat=t.primaryColumnAutoNumberFormat),t.columns&&IS(t.columns,"createTable");let I={"@odata.type":"Microsoft.Dynamics.CRM.EntityMetadata",SchemaName:t.schemaName,DisplayName:et(t.displayName,C),DisplayCollectionName:et((a=t.pluralName)!==null&&a!==void 0?a:NS(t.displayName),C),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:[k,...((c=t.columns)!==null&&c!==void 0?c:[]).map(ir=>rg(ir,C))]};t.description&&(I.Description=et(t.description,C));let D="/EntityDefinitions",P=(0,_e.ensureSuccess)(await e.post(D,I),e.apiUrl(D)),x=Yl(P),K=`/EntityDefinitions(${x})`+(0,te.odataQuery)([["$select","LogicalName,EntitySetName,PrimaryIdAttribute,PrimaryNameAttribute"]]),Oe=Math.max(1,Math.trunc((d=t.readBackAttempts)!==null&&d!==void 0?d:6)),Vt=Math.max(0,(f=t.readBackDelayMs)!==null&&f!==void 0?f:1e3),Xe=w?` Its primary column's requirement level '${b}' was NOT applied or checked: once the table is readable, set it with updateColumn('${t.schemaName.toLowerCase()}', '${O.toLowerCase()}', { required: '${b}' }).`:"",Ne;try{Ne=await _S(e,K,Oe,Vt)}catch(ir){throw w?(0,ge.attachCause)(new ge.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}), but reading it back failed (${ir instanceof Error?ir.message:String(ir)}).${Xe} Do NOT re-run the create \u2014 it will collide on the schema name.`),ir):ir}if(!Ne)throw new ge.SdkError("TABLE_METADATA_NOT_VISIBLE",`Table '${t.schemaName}' WAS CREATED (MetadataId ${x}) but its metadata was still not readable after ${Oe} attempt(s). Do NOT re-run the create \u2014 it will collide on the schema name. Re-read /EntityDefinitions(${x}) once the environment catches up, or raise 'readBackAttempts'.${Xe}`);let se=Ne.body,We={logicalName:(m=se.LogicalName)!==null&&m!==void 0?m:t.schemaName.toLowerCase(),metadataId:x,entitySetName:(p=se.EntitySetName)!==null&&p!==void 0?p:"",primaryIdAttribute:(h=se.PrimaryIdAttribute)!==null&&h!==void 0?h:`${t.schemaName.toLowerCase()}id`,primaryNameAttribute:(g=se.PrimaryNameAttribute)!==null&&g!==void 0?g:O.toLowerCase()};return w&&(We.primaryColumnRequired=await ZG(e,t.schemaName,We,b,Oe,Vt)),We}ie.createTable=XG;async function _S(e,t,r,n){for(let i=1;i<=r;i+=1){let o=await e.get(t);if(o.status>=200&&o.status<300)return o;o.status!==404&&(0,_e.ensureSuccess)(o,e.apiUrl(t)),i<r&&n>0&&await new Promise(a=>setTimeout(a,n))}}async function ZG(e,t,r,n,i,o){let a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(r.logicalName)}')/Attributes(LogicalName='${(0,te.odataPathLiteral)(r.primaryNameAttribute)}')`+(0,te.odataQuery)([["$select","RequiredLevel"]]),s=async()=>{var d,f;let m=await _S(e,a,i,o),p=(f=(d=m?.body)===null||d===void 0?void 0:d.RequiredLevel)===null||f===void 0?void 0:f.Value;return typeof p=="string"?p:void 0},l="read",u,c=d=>{let f=`its primary column '${r.primaryNameAttribute}'`,m=l==="read"?`${f} could not be read back`:l==="update"?`${f} read '${u??"(unreadable)"}' and the update to '${n}' failed, so it may or may not carry it`:u===void 0?`${f} was updated to '${n}' but could not be read back`:`${f} is still '${u}' after the update to '${n}'`;return new ge.SdkError("PRIMARY_COLUMN_REQUIRED_NOT_APPLIED",`Table '${t}' WAS CREATED (MetadataId ${r.metadataId}), but ${m}${d?` (${d})`:""}. Do NOT re-run the create \u2014 it will collide on the schema name. Check the level, and set it with updateColumn('${r.logicalName}', '${r.primaryNameAttribute}', { required: '${n}' }).`)};try{u=await s(),u!==n&&(l="update",await kS(e,r.logicalName,r.primaryNameAttribute,{required:n}),l="verify",u=await s())}catch(d){throw l==="verify"&&(u=void 0),(0,ge.attachCause)(c(d instanceof Error?d.message:String(d)),d)}if(u!==n)throw c(u===void 0?"the answer had no RequiredLevel":void 0);return n}function rg(e,t){var r,n;let i=(r=e.languageCode)!==null&&r!==void 0?r:t,o={...YG(e.type,e,i),SchemaName:e.schemaName,RequiredLevel:Jl((n=e.required)!==null&&n!==void 0?n:"None"),DisplayName:et(e.displayName,i)};return e.description&&(o.Description=et(e.description,i)),e.sourceType&&e.sourceType!=="Simple"&&(o.SourceType=e.sourceType==="Rollup"?2:1,e.formulaDefinition&&(o.FormulaDefinition=e.formulaDefinition)),TS(o,e),o}function TS(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 e9(e,t,r){var n;let i=rg(r,(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID),o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,a=(0,_e.ensureSuccess)(await e.post(o,i),e.apiUrl(o)),s={logicalName:r.schemaName.toLowerCase(),metadataId:Yl(a)};if(r.visualization&&r.visualization!=="None")try{await RS(e,t,s.logicalName,s.metadataId,r.visualization)}catch(l){let u=new ge.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(0,ge.attachCause)(u,l),u}return s}ie.createColumn=e9;var ls="/controlconfigurations",DS="CustomRenderersConfiguration",eg={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 IS(e,t){let r=e.find(n=>n.visualization&&n.visualization!=="None");if(r)throw new ge.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 OS(e){return JSON.stringify({type:eg[e]})}function t9(e){if(!e)return"None";let t;try{t=JSON.parse(e)}catch{return"None"}let r=t?.type,n=Object.keys(eg).find(i=>eg[i]===r);return n??"None"}async function PS(e,t,r){var n,i;let o=`entitylogicalname eq '${(0,te.odataLiteral)(t)}' and Attribute/logicalname eq '${(0,te.odataLiteral)(r)}'`,a=`${ls}${(0,te.odataQuery)([["$select","name,uniquename,metadatajson"],["$expand","Attribute($select=name,logicalname)"],["$filter",o]])}`,l=(i=(n=(0,_e.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[],u=r.toLowerCase();return l.filter(c=>{var d,f;return((f=(d=c.Attribute)===null||d===void 0?void 0:d.logicalname)===null||f===void 0?void 0:f.toLowerCase())===u})}async function r9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,a=(n=(0,_e.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)===null||n===void 0?void 0:n.MetadataId;if(!a)throw new ge.InvalidArgumentError(`cannot resolve column '${r}' on '${t}' to set its visualization`);return(0,te.normalizeGuid)(a,"MetadataId")}async function RS(e,t,r,n,i){let o={name:DS,uniquename:`msdyn_${t}_${r}_customrenderers`,metadatajson:OS(i),"[email protected]":`/attributes(${(0,te.normalizeGuid)(n,"MetadataId")})`,entitylogicalname:t};(0,_e.ensureSuccess)(await e.post(ls,o),e.apiUrl(ls))}async function n9(e,t,r){var n;let i=await PS(e,t,r);return t9((n=i[0])===null||n===void 0?void 0:n.metadatajson)}ie.getColumnVisualization=n9;async function i9(e,t,r,n){let o=(await PS(e,t,r)).map(u=>u.controlconfigurationid).filter(u=>!!u);if(n==="None"){for(let u of o){let c=`${ls}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,_e.ensureSuccess)(await e.delete(c),e.apiUrl(c))}return}let[a,...s]=o,l=await r9(e,t,r);if(a){let u=`${ls}(${(0,te.normalizeGuid)(a,"controlconfigurationid")})`,c={name:DS,metadatajson:OS(n),"[email protected]":`/attributes(${l})`,entitylogicalname:t};(0,_e.ensureSuccess)(await e.patch(u,c),e.apiUrl(u))}else await RS(e,t,r,l,n);for(let u of s){let c=`${ls}(${(0,te.normalizeGuid)(u,"controlconfigurationid")})`;(0,_e.ensureSuccess)(await e.delete(c),e.apiUrl(c))}}ie.setColumnVisualization=i9;async function o9(e,t,r){if(r.length===0)return;if(IS(r,"createColumns"),!e.supportsAtomicBatch)throw new ge.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,te.odataPathLiteral)(t)}')/Attributes`;await(0,HG.postChangeSet)(e,r.map(i=>{var o;return{method:"POST",path:n,body:rg(i,(o=i.languageCode)!==null&&o!==void 0?o:Jn.DEFAULT_LCID)}}),`${r.length} column(s) on '${t}'`)}ie.createColumns=o9;async function a9(e,t,r){var n,i,o,a;let s=(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID,l=tg(r.schemaName),u=(i=r.accountRelationshipName)!==null&&i!==void 0?i:`${l}_${t}_account`,c=(o=r.contactRelationshipName)!==null&&o!==void 0?o:`${l}_${t}_contact`,d={Lookup:{"@odata.type":"Microsoft.Dynamics.CRM.ComplexLookupAttributeMetadata",SchemaName:r.schemaName,DisplayName:et(r.displayName,s),RequiredLevel:Jl((a=r.required)!==null&&a!==void 0?a:"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,_e.ensureSuccess)(await e.post("/CreateCustomerRelationships",d),e.apiUrl("/CreateCustomerRelationships")),{logicalName:r.schemaName.toLowerCase(),metadataId:""}}ie.createCustomerColumn=a9;async function s9(e,t,r){var n,i,o,a,s;let l=(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID,u={EntityLogicalName:t,AttributeLogicalName:"statuscode",Label:et(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,_e.ensureSuccess)(await e.post("/InsertStatusValue",u),e.apiUrl("/InsertStatusValue"));return Number((s=(a=(o=c.body)===null||o===void 0?void 0:o.NewOptionValue)!==null&&a!==void 0?a:r.value)!==null&&s!==void 0?s:0)}ie.insertStatusValue=s9;async function l9(e,t){var r,n,i,o,a;let s=(r=t.languageCode)!==null&&r!==void 0?r:Jn.DEFAULT_LCID,l,u;if(t.type==="OneToMany"){if(!t.referencedEntity||!t.referencingEntity)throw new ge.InvalidArgumentError("OneToMany relationship requires referencedEntity and referencingEntity");let f=(n=t.lookupSchemaName)!==null&&n!==void 0?n:`${tg(t.schemaName)}_${t.referencedEntity}Id`;u=f.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:f,RequiredLevel:Jl((i=t.lookupRequired)!==null&&i!==void 0?i:"None"),DisplayName:et((o=t.lookupDisplayName)!==null&&o!==void 0?o:t.referencedEntity,s)}}}else{if(!t.entity1||!t.entity2)throw new ge.InvalidArgumentError("ManyToMany relationship requires entity1 and entity2");l={"@odata.type":"Microsoft.Dynamics.CRM.ManyToManyRelationshipMetadata",SchemaName:t.schemaName,IntersectEntityName:(a=t.intersectEntityName)!==null&&a!==void 0?a:t.schemaName.toLowerCase(),Entity1LogicalName:t.entity1,Entity2LogicalName:t.entity2}}let c="/RelationshipDefinitions",d=(0,_e.ensureSuccess)(await e.post(c,l),e.apiUrl(c));return{schemaName:t.schemaName,metadataId:Yl(d),lookupLogicalName:u}}ie.createRelationship=l9;async function u9(e,t){let r=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`;(0,_e.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteTable=u9;async function kS(e,t,r,n){var i,o;let a=(i=n.languageCode)!==null&&i!==void 0?i:Jn.DEFAULT_LCID,s=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,l=`${s}(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId,AttributeType"]])}`,c=(0,_e.ensureSuccess)(await e.get(l),e.apiUrl(l)).body,d=KG[(o=c.AttributeType)!==null&&o!==void 0?o:""];if(!c.MetadataId||!d){let g=c.MetadataId?c.AttributeType?`type '${c.AttributeType}' not supported`:"the attribute read returned no AttributeType":"the attribute read returned no MetadataId";throw new ge.InvalidArgumentError(`cannot update column '${r}' on '${t}' (${g})`)}let f=(0,te.normalizeGuid)(c.MetadataId,"MetadataId"),m=`${s}(${f})/${d}`,p=(0,_e.ensureSuccess)(await e.get(m),e.apiUrl(m)).body;for(let g of Object.keys(p))g.startsWith("@odata.")&&delete p[g];if(p["@odata.type"]=d,n.displayName!==void 0&&(p.DisplayName=et(n.displayName,a)),n.description!==void 0&&(p.Description=et(n.description,a)),n.required!==void 0&&(p.RequiredLevel=Jl(n.required)),n.maxLength!==void 0&&(p.MaxLength=n.maxLength),n.autoNumberFormat!==void 0&&(p.AutoNumberFormat=n.autoNumberFormat),n.defaultValue!==void 0&&c.AttributeType!=="Boolean")throw new ge.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 ge.InvalidArgumentError(`updateColumn: 'integerFormat' applies to Integer columns, but '${r}' on '${t}' is of type '${c.AttributeType}'.`);n.defaultValue!==void 0&&(p.DefaultValue=n.defaultValue),n.integerFormat!==void 0&&(p.Format=n.integerFormat),TS(p,n);let h=`${s}(${f})`;(0,_e.ensureSuccess)(await e.put(h,p,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(h))}ie.updateColumn=kS;async function c9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Attributes`,o=`${i}(LogicalName='${(0,te.odataPathLiteral)(r)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new ge.InvalidArgumentError(`column '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,_e.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteColumn=c9;async function d9(e,t){var r,n,i;let o=`/RelationshipDefinitions${(0,te.odataQuery)([["$filter",`SchemaName eq '${(0,te.odataLiteral)(t)}'`],["$select","MetadataId"]])}`,s=(i=(n=(r=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).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 ge.InvalidArgumentError(`relationship '${t}' not found`);let l=`/RelationshipDefinitions(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,_e.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteRelationship=d9;async function SS(e,t){var r;let n=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t)}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,i=await e.get(n);if(i.status===404)return;let a=(r=(0,_e.ensureSuccess)(i,e.apiUrl(n)).body)===null||r===void 0?void 0:r.MetadataId;return a?(0,te.normalizeGuid)(a,"MetadataId"):void 0}async function f9(e,t){var r;let n=t.name.toLowerCase(),i=await SS(e,n);if(i)return{name:n,metadataId:i};let o=(r=t.languageCode)!==null&&r!==void 0?r:Jn.DEFAULT_LCID,a={"@odata.type":"Microsoft.Dynamics.CRM.OptionSetMetadata",Name:n,DisplayName:et(t.displayName,o),IsGlobal:!0,OptionSetType:"Picklist",Options:t.options.map(l=>({Value:l.value,Label:et(l.label,o)}))};t.description&&(a.Description=et(t.description,o));let s="/GlobalOptionSetDefinitions";try{let l=(0,_e.ensureSuccess)(await e.post(s,a),e.apiUrl(s));return{name:n,metadataId:Yl(l)}}catch(l){let u;try{u=await SS(e,n)}catch{u=void 0}if(u)return{name:n,metadataId:u};throw l}}ie.createGlobalOptionSet=f9;async function p9(e,t){let r=`/GlobalOptionSetDefinitions(Name='${(0,te.odataPathLiteral)(t.toLowerCase())}')`;(0,_e.ensureSuccess)(await e.delete(r),e.apiUrl(r))}ie.deleteGlobalOptionSet=p9;async function m9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID,o={"@odata.type":"Microsoft.Dynamics.CRM.EntityKeyMetadata",SchemaName:r.schemaName,DisplayName:et(r.displayName,i),KeyAttributes:r.keyAttributes},a=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,s=(0,_e.ensureSuccess)(await e.post(a,o),e.apiUrl(a));return{logicalName:r.schemaName.toLowerCase(),metadataId:Yl(s)}}ie.createAlternateKey=m9;async function h9(e,t,r){var n;let i=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')/Keys`,o=`${i}(LogicalName='${(0,te.odataPathLiteral)(r.toLowerCase())}')${(0,te.odataQuery)([["$select","MetadataId"]])}`,s=(n=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body)===null||n===void 0?void 0:n.MetadataId;if(!s)throw new ge.InvalidArgumentError(`alternate key '${r}' not found on '${t}'`);let l=`${i}(${(0,te.normalizeGuid)(s,"MetadataId")})`;(0,_e.ensureSuccess)(await e.delete(l),e.apiUrl(l))}ie.deleteAlternateKey=h9;async function g9(e,t,r){var n;let i=(n=r.languageCode)!==null&&n!==void 0?n:Jn.DEFAULT_LCID,o=`/EntityDefinitions(LogicalName='${(0,te.odataPathLiteral)(t)}')`,s=(0,_e.ensureSuccess)(await e.get(o),e.apiUrl(o)).body,l=s.MetadataId;if(!l)throw new ge.InvalidArgumentError(`table '${t}' not found`);let u=(0,te.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=et(r.displayName,i)),r.pluralName!==void 0&&(s.DisplayCollectionName=et(r.pluralName,i)),r.description!==void 0&&(s.Description=et(r.description,i)),r.auditEnabled!==void 0&&ES(s,"IsAuditEnabled",r.auditEnabled),r.duplicateDetectionEnabled!==void 0&&ES(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,_e.ensureSuccess)(await e.put(c,s,{headers:{"MSCRM.MergeLabels":"true"}}),e.apiUrl(c))}ie.updateTable=g9});var so=v(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.rebuildRaw=Nr.assembleChildren=Nr.spliceChildren=Nr.mergeAttrs=Nr.rawFromNode=Nr.emptyBag=void 0;var ao=Q(),LS=1e6,wd=512;function y9(){return{a:[],c:[]}}Nr.emptyBag=y9;function $S(e,t=0){if(t>wd)throw new ao.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${wd}`);return{n:e.getNodeName(),a:e.getAllProperties().map(r=>[r.key,r.value]),c:e.getAllChildren().map(r=>$S(r,t+1))}}Nr.rawFromNode=$S;function b9(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))),o=new Set,a=[];for(let[s,l]of e)i.has(s)||(n.has(s)?a.push([s,n.get(s)]):a.push([s,l]),o.add(s));for(let[s,l]of t)o.has(s)||(a.push([s,l]),o.add(s));return a}Nr.mergeAttrs=b9;function vd(e,t){let r=new Set;for(let s of e){let l=s.i;if(!Number.isInteger(l)||l<0||l>LS)throw new ao.InvalidArgumentError(`Bag child index must be an integer in [0, ${LS}] (got ${String(l)})`);if(r.has(l))throw new ao.InvalidArgumentError(`Duplicate bag child index ${l}`);r.add(l)}let n=[...e].sort((s,l)=>s.i-l.i),i=[],o=0,a=0;for(let s of n){for(;a<s.i&&o<t.length;)i.push(t[o]),o+=1,a+=1;a<s.i&&(a=s.i),i.push(s.node),a+=1}for(;o<t.length;)i.push(t[o]),o+=1;return i}Nr.spliceChildren=vd;function v9(e,t){if(e.w){let r={n:e.w.n,a:e.w.a.map(n=>[n[0],n[1]]),c:vd(e.w.c,t)};return vd(e.c,[r])}return vd(e.c,t)}Nr.assembleChildren=v9;function xS(e,t,r,n=0){if(n>wd)throw new ao.InvalidArgumentError(`Artifact node tree exceeds the maximum depth of ${wd}`);w9(e,n);let i=t.make(e.n,r);for(let[o,a]of e.a)t.setProp(i,o,a);for(let o of e.c)t.addChild(i,xS(o,t,i,n+1));return i}Nr.rebuildRaw=xS;function w9(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new ao.InvalidArgumentError(`Malformed hybrid node at depth ${t}: expected a JSON object`);let r=e;if(typeof r.n!="string")throw new ao.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 ao.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 ao.InvalidArgumentError(`Malformed hybrid node '${r.n}': each attribute must be a [string, string] pair`)}});var lo=v(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});Cd.installDomShim=void 0;var FS=ns(),MS=!1,C9={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 E9(){if(MS)return;let e=globalThis;typeof e.DOMParser>"u"&&(e.DOMParser=FS.DOMParser),typeof e.XMLSerializer>"u"&&(e.XMLSerializer=FS.XMLSerializer),typeof e.Node>"u"&&(e.Node=C9),MS=!0}Cd.installDomShim=E9});var uo=v(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.projectElementBag=tt.serializeNode=tt.domEngine=tt.nodeLikeFromDom=tt.parseXmlRoot=tt.EMPTY_FORM_SENTINEL=tt.TEXT_SENTINEL=void 0;var A9=so(),us=Q(),S9=lo();tt.TEXT_SENTINEL="#text";tt.EMPTY_FORM_SENTINEL="#empty";var Ad=new WeakSet;function N9(e,t){(0,S9.installDomShim)();let r=e&&e.trim()!==""?e:t,n=new DOMParser().parseFromString(r,"text/xml"),i=n.documentElement;if(!i)throw new us.InvalidArgumentError("XML source has no root element (empty or malformed input)");return _9(r),D9(n),O9(i),P9(i),L9(i,r),i}tt.parseXmlRoot=N9;function _9(e){let t=e.search(/\S/);if(t!==-1&&e[t]!=="<")throw BS(3)}var T9=["http://www.mozilla.org/newlayout/xml/parsererror.xml","http://www.w3.org/1999/xhtml"];function D9(e){var t;for(let r of T9){let n=e.getElementsByTagNameNS(r,"parsererror")[0];if(n){let i=((t=n.textContent)!==null&&t!==void 0?t:"").replace(/\s+/g," ").trim().slice(0,200);throw new us.InvalidArgumentError(`XML source is not well-formed (${i||"the XML parser reported an error"}), so it cannot be round-tripped`)}}}var I9=new Set([1,3]);function O9(e){let t=[e];for(;t.length>0;){let n=t.pop().childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];if(!I9.has(o.nodeType))throw new us.InvalidArgumentError(`Unsupported XML node type ${o.nodeType} (CDATA / comment / processing-instruction) is outside the hybrid projection's lossless grammar and cannot be round-tripped`);o.nodeType===1&&t.push(o)}}}function P9(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 o=0;o<i.length;o+=1){let a=i[o];if(a!==e&&!(a.nodeType===3&&((r=a.nodeValue)!==null&&r!==void 0?r:"").trim()===""))throw BS(a.nodeType)}}function BS(e){return new us.InvalidArgumentError(`Unsupported document-level XML node (type ${e}: declaration / comment / processing-instruction outside the root element) cannot be round-tripped`)}function R9(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 k9(e){let t=[],r=[e];for(;r.length>0;){let n=r.pop();t.push(n);let i=n.childNodes;for(let o=i.length-1;o>=0;o-=1){let a=i[o];a.nodeType===1&&r.push(a)}}return t}function qS(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 L9(e,t){let r=R9(t),n=k9(e),i=Math.min(r.length,n.length);for(let o=0;o<i;o+=1){if(r[o])continue;let a=n[o];qS(a)||Ad.add(a)}}function ng(e){let t=e.nodeType===3;return{getNodeName:()=>t?tt.TEXT_SENTINEL:e.tagName,getAllProperties:()=>{var r;if(t)return[{key:tt.TEXT_SENTINEL,value:(r=e.nodeValue)!==null&&r!==void 0?r:""}];let n=e.attributes,i=[];for(let o=0;o<n.length;o+=1)i.push({key:n[o].name,value:n[o].value});return Ad.has(e)&&!qS(e)&&i.push({key:tt.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 o=n[i];(o.nodeType===1||o.nodeType===3)&&r.push(ng(o))}return r}}}tt.nodeLikeFromDom=ng;function $9(e){return{make:t=>t===tt.TEXT_SENTINEL?e.createTextNode(""):e.createElement(t),setProp:(t,r,n)=>{t.nodeType===3?t.nodeValue=n:r===tt.EMPTY_FORM_SENTINEL?Ad.add(t):t.setAttribute(r,n)},addChild:(t,r)=>{t.appendChild(r)}}}tt.domEngine=$9;function VS(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 Ed(r);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))throw Ed(r);t+=1;continue}if(r>=56320&&r<=57343)throw Ed(r)}}function Ed(e){let t=e.toString(16).toUpperCase().padStart(4,"0");return new us.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 x9(e){return VS(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\r/g,"&#xD;").replace(/\n/g,"&#xA;").replace(/\t/g,"&#x9;")}function F9(e){return VS(e),String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function M9(e){return GS(e,0)}tt.serializeNode=M9;var US=512;function GS(e,t){var r;if(t>US)throw new us.InvalidArgumentError(`XML nesting exceeds the maximum supported depth of ${US}`);if(e.nodeType===3)return F9((r=e.nodeValue)!==null&&r!==void 0?r:"");let n=e,i="<"+n.tagName,o=n.attributes;for(let l=0;l<o.length;l+=1)i+=" "+o[l].name+'="'+x9(o[l].value)+'"';let a=[],s=n.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];(u.nodeType===1||u.nodeType===3)&&a.push(u)}if(a.length===0)return Ad.has(n)?i+"></"+n.tagName+">":i+" />";i+=">";for(let l of a)i+=GS(l,t+1);return i+"</"+n.tagName+">"}function U9(e){let t=ng(e);return{a:t.getAllProperties().map(r=>[r.key,r.value]),c:t.getAllChildren().map((r,n)=>({i:n,node:(0,A9.rawFromNode)(r)}))}}tt.projectElementBag=U9});var rn=v(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.rejectUnknownKeys=Jt.childObjects=Jt.optionalGuidId=Jt.optionalEnum=Jt.eachObject=Jt.issue=Jt.isJsonObject=void 0;function WS(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}Jt.isJsonObject=WS;function cs(e,t,r,n){return n?{pointer:e,rule:t,message:r,fatal:n}:{pointer:e,rule:t,message:r}}Jt.issue=cs;function zS(e,t,r,n){if(!Array.isArray(e))return[];let i=[];return e.forEach((o,a)=>{WS(o)?i.push({node:o,index:a}):n.push(cs(`${t}/${a}`,`${r}-must-be-object`,`a ${r} must be a JSON object, got ${o===null?"null":typeof o}`))}),i}Jt.eachObject=zS;function B9(e,t,r,n,i,o){let a=e[t];a!==void 0&&(typeof a!="string"||!r.includes(a))&&o.push(cs(`${n}/${t}`,i,`${t} must be one of ${r.map(s=>`'${s}'`).join(", ")}, got ${JSON.stringify(a)}`))}Jt.optionalEnum=B9;var q9=/^(?:\{[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 V9(e,t,r,n,i){let o=e[t];typeof o=="string"&&o!==""&&!q9.test(o)&&i.push(cs(`${r}/${t}`,n,`${t} must be a GUID or empty, got '${o}'`))}Jt.optionalGuidId=V9;function G9(e,t,r,n,i){let o=e[t],a=`${r}/${t}`;return o===void 0?[]:Array.isArray(o)?zS(o,a,n,i):(i.push(cs(a,`${n}-list-must-be-array`,`${t} must be an array when present, got ${typeof o}`)),[])}Jt.childObjects=G9;function W9(e,t,r,n,i,o={}){var a,s;for(let l of Object.keys(e)){if(t.has(l))continue;let u=(a=o.elsewhere)===null||a===void 0?void 0:a[l],c=(s=o.unsupported)===null||s===void 0?void 0:s[l],d=u?` '${l}' is a ${u} key \u2014 set it on the ${u} instead.`:c?` ${c}`:` Put values the typed layer does not model in '${n}.bag', which round-trips them verbatim.`;i.push(cs(`${r}/${l}`,`${n}-unknown-key`,`'${l}' is not a ${n} property, and would be SILENTLY DROPPED at serialization.${d}`))}}Jt.rejectUnknownKeys=W9});var Dd=v(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.genPageEmbedIssues=B.setUniqueId=B.mintEmbedIdentity=B.authoredUniqueId=B.hasGenPage=B.applyEmbedCellDefaults=B.applyEmbedControlDefaults=B.mayCommitEmbedState=B.commitEmbedState=B.reconcileEmbedDescriptions=B.embedAppendIndex=B.activeEmbedBindings=B.projectGenPageEmbeds=B.isRecognizedEmbed=B.isUnbound=B.effectiveClassId=B.effectiveFormType=B.inputDataFrom=B.classifyBinding=B.isStaticParameter=B.entryParameter=B.pageEntries=B.descriptionFor=B.descriptionsRegion=B.controlUniqueIds=B.controlUniqueId=B.typedCellSites=B.typedCells=B.rawText=B.rawAttr=B.normGuid=B.GENPAGE_FORM_FACTORS=B.GENPAGE_EMBED_ROWSPAN=B.GENPAGE_CONTROL_NAME=B.CUSTOM_CONTROL_CLASS_ID=void 0;var z9=ns(),j9=Ma(),ig=pt(),nn=rn();B.CUSTOM_CONTROL_CLASS_ID="F9A8A302-114E-466A-B582-6771B2AE0D92";B.GENPAGE_CONTROL_NAME="MscrmControls.UxAgentControl";B.GENPAGE_EMBED_ROWSPAN=6;B.GENPAGE_FORM_FACTORS=["2","0","1"];var H9=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function _r(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase();return t.startsWith("{")&&t.endsWith("}")&&(t=t.slice(1,-1)),H9.test(t)?t:""}B.normGuid=_r;function co(e,t){let r=Se(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}B.rawAttr=co;function Xl(e){return Se(e?.c).filter(t=>typeof t?.n=="string"&&t.n.startsWith("<")).map(t=>t.n.slice(1)).join("")}B.rawText=Xl;function Se(e){return Array.isArray(e)?e:[]}function cg(e,t){let r=Se(e?.a).find(n=>Array.isArray(n)&&n[0]===t);return r?r[1]:void 0}function KS(e){return typeof e=="string"?e.trim().replace(/^\{|\}$/g,"").toUpperCase():""}function JS(e){return Sn(e).map(t=>t.cell)}B.typedCells=JS;function Sn(e){let t=[];return Se(e?.tabs).forEach((r,n)=>{Se(Re(r)?r.columns:void 0).forEach((i,o)=>{Se(Re(i)?i.sections:void 0).forEach((a,s)=>{Se(Re(a)?a.rows:void 0).forEach((l,u)=>{Se(Re(l)?l.cells:void 0).forEach((c,d)=>{Re(c)&&t.push({cell:c,pointer:`/tabs/${n}/columns/${o}/sections/${s}/rows/${u}/cells/${d}`})})})})})}),t}B.typedCellSites=Sn;function Oi(e){return Re(e)?_r(cg(e.bag,"uniqueid")):""}B.controlUniqueId=Oi;function K9(e){let t=new Set;for(let{cell:r}of Sn(e)){let n=Zo(r.control)?Oi(r.control):"";n&&t.add(n)}return t}function J9(e){let t=new Map;for(let{cell:r}of Sn(e)){let n=Re(r.control)?Oi(r.control):"";n&&!t.has(n)&&t.set(n,r.control)}return t}function Y9(e){return e!==void 0&&e.genPage===void 0&&(pg(e)!==B.CUSTOM_CONTROL_CLASS_ID||!Td(e))}function og(e,t){if(Re(e)){t(e);for(let r of Se(e.c))og(r,t)}}function Qo(e,t){var r;if(Re(e)){for(let n of Se(e.c))og(n?.node,t);for(let n of Se((r=e.w)===null||r===void 0?void 0:r.c))og(n?.node,t)}}function Nd(e){let t=new Map,r=i=>{var o;i&&t.set(i,((o=t.get(i))!==null&&o!==void 0?o:0)+1)},n=i=>{i.n==="control"&&r(_r(co(i,"uniqueid")))};return Qo(e?.bag,n),Se(e?.tabs).forEach(i=>{Re(i)&&(Qo(i.bag,n),Se(i.columns).forEach(o=>{Re(o)&&(Qo(o.bag,n),Se(o.sections).forEach(a=>{Re(a)&&(Qo(a.bag,n),Se(a.rows).forEach(s=>{Re(s)&&(Qo(s.bag,n),Se(s.cells).forEach(l=>{Re(l)&&(Qo(l.bag,n),Re(l.control)&&(r(Oi(l.control)),Qo(l.control.bag,n)))}))}))}))}))}),t}B.controlUniqueIds=Nd;function ds(e){return Se(e?.c).find(t=>{var r;return((r=t?.node)===null||r===void 0?void 0:r.n)==="controlDescriptions"})}B.descriptionsRegion=ds;function Xo(e,t){var r;let n=_r(t);if(n)return Se((r=ds(e))===null||r===void 0?void 0:r.node.c).find(i=>i?.n==="controlDescription"&&_r(co(i,"forControl"))===n)}B.descriptionFor=Xo;function Zl(e){return Se(e.c).filter(YS)}B.pageEntries=Zl;function YS(e){return e?.n==="customControl"&&co(e,"name")===B.GENPAGE_CONTROL_NAME}function ag(e,t){let r=Se(e.c).find(n=>n?.n==="parameters");return Se(r?.c).find(n=>n?.n===t)}B.entryParameter=ag;function sg(e){return co(e,"static")==="true"}B.isStaticParameter=sg;function eu(e){let t=Zl(e);if(t.length===0)return{kind:"none"};let r,n;for(let i=0;i<t.length;i+=1){let o=ag(t[i],"RefId");if(!o||!sg(o))return{kind:"unsupported"};let a=_r(Xl(o));if(!a)return{kind:"unsupported"};let s=ag(t[i],"PageInput");if(s&&!sg(s))return{kind:"unsupported"};let l=s?Xl(s):void 0;if(i===0)r=a,n=l;else if(a!==r||l!==n)return{kind:"unsupported"}}return n===void 0?{kind:"projectable",pageId:r}:{kind:"projectable",pageId:r,pageInputRaw:n}}B.classifyBinding=eu;function Re(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dg(e){if(e===void 0)return;let t;try{t=JSON.parse(e)}catch{return}return Re(t)&&Re(t.data)?t.data:void 0}B.inputDataFrom=dg;function fg(e){var t;return(t=e.formType)!==null&&t!==void 0?t:"Main"}B.effectiveFormType=fg;function pg(e){return KS(e.classId!==void 0?e.classId:cg(e.bag,"classid"))}B.effectiveClassId=pg;function Td(e){return!e.fieldName}B.isUnbound=Td;function mg(e,t){if(fg(e)!=="Main"||!Td(t)||pg(t)!==B.CUSTOM_CONTROL_CLASS_ID)return!1;let r=Oi(t),n=r?Xo(e.bag,r):void 0;return n!==void 0&&eu(n).kind==="projectable"}B.isRecognizedEmbed=mg;function Q9(e){for(let t of JS(e)){let r=t.control;if(!r||!mg(e,r))continue;let n=eu(Xo(e.bag,Oi(r)));if(n.kind!=="projectable")continue;let i=dg(n.pageInputRaw);r.genPage=i===void 0?{pageId:n.pageId}:{pageId:n.pageId,inputData:i}}}B.projectGenPageEmbeds=Q9;var X9=new Set(["pageId","inputData"]);function Ql(e){let t=[];for(let r=0;r<e.childNodes.length;r+=1){let n=e.childNodes[r];n.nodeType===1&&t.push(n)}return t}function Z9(e){var t;let r=[],n=c=>d=>r.push(`${c}: ${d}`),i=new z9.DOMParser({errorHandler:{warning:n("warning"),error:n("error"),fatalError:n("fatalError")}}).parseFromString(e,"text/xml"),o=(t=i?.documentElement)!==null&&t!==void 0?t:null;if(!o||r.length>0)throw new Error(`the formxml does not parse cleanly${r.length>0?` (${r[0]})`:""}`);let a=new Set,s=o.getElementsByTagName("control");for(let c=0;c<s.length;c+=1){let d=_r(s[c].getAttribute("uniqueid"));d&&a.add(d)}let l=Ql(o).find(c=>c.nodeName==="controlDescriptions"),u=new Map;for(let c of l?Ql(l):[]){let d=_r(c.getAttribute("forControl"));if(!(c.nodeName!=="controlDescription"||!d||!a.has(d)))for(let f of Ql(c)){if(f.nodeName!=="customControl"||f.getAttribute("name")!==B.GENPAGE_CONTROL_NAME)continue;let m=Ql(f).find(g=>g.nodeName==="parameters"),p=m?Ql(m).find(g=>g.nodeName==="RefId"):void 0,h=p&&p.getAttribute("static")==="true"?_r(p.textContent):"";h&&u.set(`${d}|${h}`,[d,h])}}return[...u.values()]}B.activeEmbedBindings=Z9;function Sd(e){return{n:`<${e}`,a:[],c:[]}}function lg(e,t){return{n:e,a:[["type","SingleLine.Text"],["static","true"]],c:[Sd(t)]}}function ug(e,t){let r={};if(t!==void 0)try{let n=JSON.parse(t);Re(n)&&(r=n)}catch{}return JSON.stringify({...r,data:e})}function eW(e,t,r){return{n:"controlDescription",a:[["forControl",e]],c:B.GENPAGE_FORM_FACTORS.map(n=>({n:"customControl",a:[["name",B.GENPAGE_CONTROL_NAME],["formFactor",n]],c:[{n:"parameters",a:[],c:[lg("RefId",t),...r===void 0?[]:[lg("PageInput",ug(r))]]}]}))}}function _d(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>_d(r,t[n]));if(Re(e)&&Re(t)){let r=Object.keys(e);return r.length===Object.keys(t).length&&r.every(n=>n in t&&_d(e[n],t[n]))}return e===t}function tW(e,t,r){let n=Se(e.c).find(u=>u?.n==="parameters");if(!n||!Array.isArray(n.c))return;let i=n.c.find(u=>u?.n==="RefId");i&&_r(Xl(i))!==t&&(i.c=[Sd(t)]);let o=n.c.findIndex(u=>u?.n==="PageInput"),a=o>=0?n.c[o]:void 0,s=a?Xl(a):void 0;if(_d(dg(s),r))return;if(r!==void 0){a?a.c=[Sd(ug(r,s))]:n.c.push(lg("PageInput",ug(r)));return}let l=JSON.parse(s);delete l.data,Object.keys(l).length===0?n.c.splice(o,1):a.c=[Sd(JSON.stringify(l))]}function hg(e){let t=Se(e?.c),r=t.reduce((n,i)=>i.i>n?i.i:n,-1);return Math.max(r,t.length)+1}B.embedAppendIndex=hg;function rW(e,t){var r;let n=e.bag,i=ds(n);if(i&&t){let o=Nd(t),a=Nd(e),s=K9(t),l=J9(e),u=Se(i.node.c),c=[];for(let d of u){let f=d?.n==="controlDescription"&&Zl(d).length>0?_r(co(d,"forControl")):"";if(!f||!o.has(f))c.push(d);else if(a.has(f))if(s.has(f)&&Y9(l.get(f))&&_d(d,Xo(t.bag,f))){let m=Se(d.c).filter(p=>!YS(p));m.length>0&&c.push({...d,c:m})}else c.push(d)}(c.length!==u.length||c.some((d,f)=>d!==u[f]))&&(i.node.c=c)}for(let{cell:o}of Sn(e)){let a=o.control;if(!Zo(a)||!Re(a.genPage))continue;let s=_r(a.genPage.pageId),l=a.genPage.inputData,u=Oi(a);if(!u){if(tu(a)!==void 0)continue;u=gg(a)}let c=Xo(n,u);if(c){for(let m of Zl(c))tW(m,s,l);continue}i||(i={i:hg(n),node:{n:"controlDescriptions",a:[],c:[]}},n.c.push(i));let d=((r=cg(a.bag,"uniqueid"))!==null&&r!==void 0?r:"").trim(),f=d.startsWith("{")?d:`{${u}}`;i.node.c.push(eW(f,s,l))}}B.reconcileEmbedDescriptions=rW;function nW(e,t){let r=ds(e.bag),n=t!==void 0&&(r===void 0||JSON.stringify(r.node)!==JSON.stringify(t)),i=Sn(e).some(({cell:a})=>Zo(a.control)&&(a.rowspan===void 0||a.control.classId===void 0||a.control.showLabel===void 0||a.control.label===void 0||a.control.fieldName===void 0));if(!n&&!i)return e;let o=JSON.parse(JSON.stringify(e));if(n){let a=JSON.parse(JSON.stringify(t)),s=ds(o.bag);s?s.node=a:(o.bag=Re(o.bag)?o.bag:{a:[],c:[]},o.bag.c=Se(o.bag.c),o.bag.c.push({i:hg(e.bag),node:a}))}for(let{cell:a}of Sn(o))Zo(a.control)&&(QS(a.control),XS(a));return o}B.commitEmbedState=nW;function iW(e){if(Sn(e).some(({cell:r})=>Zo(r.control)))return!0;let t=ds(e.bag);return Se(t?.node.c).some(r=>r?.n==="controlDescription"&&Zl(r).length>0)}B.mayCommitEmbedState=iW;function QS(e){e.classId===void 0&&(e.classId=B.CUSTOM_CONTROL_CLASS_ID),e.showLabel===void 0&&(e.showLabel=!1),e.label===void 0&&(e.label=""),e.fieldName===void 0&&(e.fieldName=null)}B.applyEmbedControlDefaults=QS;function XS(e){e.rowspan===void 0&&(e.rowspan=B.GENPAGE_EMBED_ROWSPAN)}B.applyEmbedCellDefaults=XS;function Zo(e){return Re(e)&&e.genPage!==void 0}B.hasGenPage=Zo;function jS(e){return Zo(e.control)&&(!e.control.id||!e.id||tu(e.control)===void 0)}function tu(e){let t=Se(Re(e.bag)?e.bag.a:void 0).find(n=>Array.isArray(n)&&n[0]==="uniqueid");if(!t)return;let r=t[1];return typeof r=="string"&&r.trim()===""?void 0:r}B.authoredUniqueId=tu;function oW(e){if(!Sn(e).some(({cell:r})=>jS(r)))return e;let t=JSON.parse(JSON.stringify(e));for(let{cell:r}of Sn(t)){if(!jS(r))continue;let n=r.control;n.id||(n.id=(0,ig.newId)()),r.id||(r.id=(0,ig.newId)()),tu(n)===void 0&&gg(n)}return t}B.mintEmbedIdentity=oW;function gg(e){let t=(0,ig.newId)(),r=`{${t}}`;if(!Re(e.bag))return e.bag={a:[["uniqueid",r]],c:[]},t;let n=Se(e.bag.a),i=n.find(o=>Array.isArray(o)&&o[0]==="uniqueid");return i?i[1]=r:n.push(["uniqueid",r]),e.bag.a=n,e.bag.c=Se(e.bag.c),t}B.setUniqueId=gg;function HS(e){return e===null?"null":Array.isArray(e)?"an array":typeof e}function aW(e){let t=Se(e.c).filter(r=>r?.n==="customControl").map(r=>{var n,i;return(i=(n=co(r,"name"))!==null&&n!==void 0?n:co(r,"id"))!==null&&i!==void 0?i:"unnamed"});return[...new Set(t)].join(", ")||"no custom control"}function sW(e){let t=[],r;for(let{cell:n,pointer:i}of Sn(e)){let o=n.control;if(!Re(o))continue;let a=`${i}/control`;if(o.genPage===void 0){lW(e,o,a,t);continue}r=r??Nd(e),uW(e,o,a,r,t)}return t}B.genPageEmbedIssues=sW;function lW(e,t,r,n){if(!mg(e,t))return;let i=eu(Xo(e.bag,Oi(t)));n.push((0,nn.issue)(r,"genpage-embed-removed",`this control still embeds generative page ${i.pageId}: removing genPage alone would leave that binding on the form. To remove the embed, remove the cell (or set the cell's control to null); to change the page, edit genPage/pageId. A copy fetched by an older SDK (projection 3) shows no genPage at all \u2014 re-fetch the form.`))}function uW(e,t,r,n,i){var o;let a=`${r}/genPage`,s=t.genPage;if(!Re(s))i.push((0,nn.issue)(a,"genpage-embed-shape",`genPage must be an object { pageId, inputData? }, got ${HS(s)}.`+(s===null?" To remove an embed, remove the cell (or set the cell's control to null).":"")));else{(typeof s.pageId!="string"||!_r(s.pageId))&&i.push((0,nn.issue)(`${a}/pageId`,"genpage-embed-shape",`genPage.pageId must be the id (a GUID) of a generative page, got ${s.pageId===void 0?"nothing":JSON.stringify(s.pageId)}`)),s.inputData!==void 0&&!Re(s.inputData)&&i.push((0,nn.issue)(`${a}/inputData`,"genpage-embed-shape",`genPage.inputData must be a JSON object \u2014 the page reads it as pageInput.data \u2014 got ${HS(s.inputData)}`));for(let m of Object.keys(s))X9.has(m)||i.push((0,nn.issue)(j9.JsonPointer.append(a,m),"genpage-embed-unknown-key",`'${m}' is not a genPage property (pageId, inputData), and would be SILENTLY DROPPED at serialization.`))}Td(t)||i.push((0,nn.issue)(`${r}/fieldName`,"genpage-embed-bound",`a generative-page embed is an unbound control, but this one is bound to column '${t.fieldName}'. Set fieldName to null, or embed the page in a new cell.`)),t.classId!==void 0&&KS(t.classId)!==B.CUSTOM_CONTROL_CLASS_ID&&i.push((0,nn.issue)(`${r}/classId`,"genpage-embed-class-id",`a generative-page embed is the custom control {${B.CUSTOM_CONTROL_CLASS_ID}}, but classId is ${JSON.stringify(t.classId)}. Omit classId (the SDK defaults it) or set it to that class.`));let l=fg(e);l!=="Main"&&i.push((0,nn.issue)(a,"genpage-embed-main-form-only",`a generative page can be embedded only in a Main form, as in the maker portal; this is a ${l} form.`));let u=tu(t);u!==void 0&&!_r(u)&&i.push((0,nn.issue)(`${r}/bag`,"genpage-embed-unique-id",`this embed's uniqueid ${JSON.stringify(u)} is not a GUID, and its page binding is keyed by it. Remove it from the bag (the SDK mints one) or set a GUID.`));let c=Oi(t);if(!c)return;let d=Xo(e.bag,c),f=d?eu(d):void 0;d&&f?.kind==="none"?i.push((0,nn.issue)(a,"genpage-embed-other-control",`this control is already bound to another custom control (${aW(d)}). genPage would have to delete that binding to take its place, so embed the page in a new cell instead.`)):f?.kind==="unsupported"&&i.push((0,nn.issue)(a,"genpage-embed-unsupported-binding","this control already embeds a page through a binding genPage cannot represent exactly \u2014 a RefId or PageInput bound to a column, a RefId that is not a page id, or form factors that disagree. Taking it over would silently turn it into a static binding, so embed the page in a new cell instead.")),((o=n.get(c))!==null&&o!==void 0?o:0)>1&&i.push((0,nn.issue)(`${r}/bag`,"genpage-embed-duplicate-unique-id",`this embed's uniqueid {${c}} is also carried by another control on the form, so both would share one binding. Author the copy without its bag and the SDK mints a new identity for it.`))}});var bg=v(fo=>{"use strict";Object.defineProperty(fo,"__esModule",{value:!0});fo.findMissingGenPages=fo.GENPAGE_LOOKUP_CHUNK=void 0;var cW=Lt(),yg=le();fo.GENPAGE_LOOKUP_CHUNK=50;async function dW(e,t,r){let n=[...new Set(t.map(o=>(0,yg.normalizeGuid)(o,"uxagentprojectid")))],i=new Set;for(let o=0;o<n.length;o+=fo.GENPAGE_LOOKUP_CHUNK){let a=n.slice(o,o+fo.GENPAGE_LOOKUP_CHUNK),s="/uxagentprojects/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,yg.odataQuery)([["$select","uxagentprojectid"],["$filter",a.map(u=>`uxagentprojectid eq ${u}`).join(" or ")]]),l=await(0,cW.collectPages)(e,s,r);for(let u of l){let c=u.uxagentprojectid;typeof c=="string"&&c.trim()!==""&&i.add((0,yg.normalizeGuid)(c,"uxagentprojectid"))}}return n.filter(o=>!i.has(o))}fo.findMissingGenPages=dW});var ru=v(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.assertSystemFormKind=_t.readSystemFormType=_t.decodeCode=_t.assertSystemFormRecordKind=_t.describeSystemFormType=_t.systemFormKindOf=_t.SYSTEMFORM_KIND_MISMATCH_CODE=void 0;var eN=Q(),fW=ye(),ZS=le();_t.SYSTEMFORM_KIND_MISMATCH_CODE="SYSTEMFORM_KIND_MISMATCH";var pW={0:"dashboard",10:"dashboard",2:"form",6:"form",7:"form",11:"form"},mW={0:"dashboard",1:"appointment book",2:"Main form",3:"mini campaign form",4:"preview form",5:"mobile express form",6:"Quick View form",7:"Quick Create form",8:"dialog",9:"task flow form",10:"interactive dashboard",11:"card form",12:"interactive Main form",13:"contextual dashboard",100:"other form",101:"Main form backup",102:"appointment book backup",103:"Power BI dashboard"};function Id(e){return Number.isInteger(e)?pW[e]:void 0}_t.systemFormKindOf=Id;function tN(e){var t;return Number.isFinite(e)?`a ${(t=mW[e])!==null&&t!==void 0?t:"systemform"} (type ${e})`:"a systemform whose type could not be read"}_t.describeSystemFormType=tN;function rN(e,t,r,n){let i=tN(r),o=Id(r);switch(n){case"fetch":return`Refusing to fetch systemform '${e}' as a ${t}: it is ${i}. Nothing was read into the workspace. `+(o?`Fetch it as a ${o}.`:Number.isFinite(r)?"The SDK does not model that kind: check the id.":"Check the id.");case"write":return`Refusing to write systemform '${e}' as a ${t}: it is ${i}. Nothing was written. Check the id: a local copy fetched by an SDK that did not check the kind can name a row of another kind \u2014 discard it with deleteArtifact('${t}', '${e}').`;case"delete":return`Refusing to delete systemform '${e}' as a ${t}: it is ${i}. Nothing was changed. Check the id.`;default:return`Refusing to ${n} systemform '${e}': it is ${i}, not a ${t}.`+(n==="set the security roles of"?" Nothing was written.":"")+" Check the id."}}function hW(e,t,r,n){let i=vg(e?.type);if(Id(i)!==r)throw new eN.SdkError(_t.SYSTEMFORM_KIND_MISMATCH_CODE,rN(t,r,i,n));return i}_t.assertSystemFormRecordKind=hW;function vg(e){if(typeof e=="number")return Number.isInteger(e)?e:NaN;if(typeof e!="string"||!/^\s*-?\d+\s*$/.test(e))return NaN;let t=Number(e);return Number.isInteger(t)?t:NaN}_t.decodeCode=vg;async function gW(e,t){return await nN(e,t,!1)}_t.readSystemFormType=gW;async function yW(e,t){return nN(e,t,!0)}async function nN(e,t,r){var n;let o=`/systemforms(${(0,ZS.normalizeGuid)(t,"formId")})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,ZS.odataQuery)([["$select","type"]]),a=await e.get(o);if(!(r&&a.status===404))return(0,fW.ensureSuccess)(a,e.apiUrl(o)),vg((n=a.body)===null||n===void 0?void 0:n.type)}async function bW(e,t,r){let n=await yW(e,t);if(!(n===void 0||Id(n)===r))throw new eN.SdkError(_t.SYSTEMFORM_KIND_MISMATCH_CODE,rN(t,r,n,"delete"))}_t.assertSystemFormKind=bW});var Cg=v(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.patchSystemForm=Wr.assertSystemFormContentUnchanged=Wr.readSystemFormRowEtag=Wr.unpublishedSystemFormPath=Wr.FORM_TYPE_IMMUTABLE_CODE=void 0;var on=ye(),vW=le(),Od=Q(),po=ru();Wr.FORM_TYPE_IMMUTABLE_CODE="FORM_TYPE_IMMUTABLE";function wg(e,t="formid"){return`/systemforms(${e})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,vW.odataQuery)([["$select",t]])}Wr.unpublishedSystemFormPath=wg;function iN(e,t){return(0,on.readRowEtag)(e,"systemforms","formid",t)}Wr.readSystemFormRowEtag=iN;async function oN(e,t,r,n,i){(0,on.requireEtag)(i,r,t);let o=(0,on.ensureSuccess)(await e.get(n),e.apiUrl(n)),a=(0,po.assertSystemFormRecordKind)(o.body,t,r,"write"),s=(0,on.readEtag)(o);if(s===null)throw new Od.SdkError(on.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its current version could not be read, so the write could not be verified as conditional and would risk silently overwriting a concurrent edit.`);if(s!==i)throw new Od.SdkError(on.VERSION_CONFLICT_CODE,`Version conflict writing ${r} '${t}': its formxml changed on the server since it was read (held ${i}, server ${s}). Re-fetch the ${r} and re-apply the change.`);return a}Wr.assertSystemFormContentUnchanged=oN;async function wW(e,t,r,n,i,o){(0,on.requireEtag)(i,r,t);let a=await iN(e,t);if(a===null)throw new Od.SdkError(on.VERSION_CONFLICT_CODE,`Refusing to write ${r} '${t}': its row version could not be read, so the write could not be made conditional and would risk silently overwriting a concurrent edit.`);let s=await oN(e,t,r,wg(t,"formid,type"),i);if(n.type!==void 0&&(0,po.decodeCode)(n.type)!==s)throw new Od.SdkError(Wr.FORM_TYPE_IMMUTABLE_CODE,`Refusing to push ${r} '${t}': it would change it from ${(0,po.describeSystemFormType)(s)} to ${(0,po.describeSystemFormType)((0,po.decodeCode)(n.type))}. The platform ignores a type change on an existing ${r}, so the push would report a change that did not happen. Nothing was written. Create a new ${r} of that type instead.`);let l=(0,on.echoWrite)("formid",{"If-Match":a}),u=`/systemforms(${t})${l.query}`;return(0,on.ensureSuccess)(await e.patch(u,n,l.options),e.apiUrl(u)),CW(e,t,r,o)}Wr.patchSystemForm=wW;async function CW(e,t,r,n){let i;try{let o=wg(t,n.select),a=(0,on.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=a.body,l=(0,on.readEtag)(a),u=typeof s?.formid=="string"&&s.formid.replace(/[{}]/g,"").toLowerCase()===t,c=typeof s?.formxml=="string"&&s.formxml.trim()!=="",d=n.required.filter(p=>s?.[p]===void 0||s?.[p]===null),f=(0,po.decodeCode)(s?.type),m=(0,po.systemFormKindOf)(f)===r;if(l&&u&&c&&d.length===0&&m)return{id:t,etag:l,readBack:s};i=l?!u||!c?`the read did not return this ${r}'s document`:d.length>0?`the read did not return its ${d.join(", ")}`:`the read returned ${(0,po.describeSystemFormType)(f)}, not a ${r}`:"the read returned no version"}catch(o){i=o instanceof Error?o.message:String(o)}return{id:t,etag:null,warnings:[`The ${r} was saved, but its new version could not be read (${i}). The SDK holds no version for it now, so the next push is refused: re-fetch the ${r} before editing it again.`]}}});var _g=v($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.getFormSecurityRoles=$t.setFormSecurityRoles=$t.formApi=$t.readPrimaryCreateRefusal=$t.FORM_GENPAGE_TARGET_UNVERIFIABLE=$t.FORM_GENPAGE_TARGET_NOT_FOUND=void 0;var EW=Lt(),Tt=ye(),an=le(),ea=Q(),Eg=uo(),sN=Dd(),AW=bg(),Ag=Cg(),nu=ru();$t.FORM_GENPAGE_TARGET_NOT_FOUND="FORM_GENPAGE_TARGET_NOT_FOUND";$t.FORM_GENPAGE_TARGET_UNVERIFIABLE="FORM_GENPAGE_TARGET_UNVERIFIABLE";var lN="formid,formxml,name,type,objecttypecode,formpresentation,formactivationstate,uniquename,description,versionnumber",SW={select:lN,required:["name","type","objecttypecode"]},NW="formid,name,type,objecttypecode",_W=2,TW={Main:_W,QuickView:6,QuickCreate:7,Card:11},uN=new WeakMap;function DW(e){return typeof e=="object"&&e!==null?uN.get(e):void 0}$t.readPrimaryCreateRefusal=DW;$t.formApi={async get(e,t){let r=(0,an.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,an.odataQuery)([["$select",lN]]),i=(0,Tt.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,nu.assertSystemFormRecordKind)(i.body,r,"form","fetch"),{raw:i.body,etag:(0,Tt.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=>TW[u]))],a=[i.length===1?`type eq ${i[0]}`:`(${i.map(u=>`type eq ${u}`).join(" or ")})`];t?.entityLogicalName&&a.push(`objecttypecode eq '${(0,an.odataLiteral)(t.entityLogicalName)}'`);let s=`/systemforms${(0,an.odataQuery)([["$select",NW],["$filter",a.join(" and ")]])}`;return(await(0,EW.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=aN(t);n!==void 0&&await cN(e,Ng(n,"payload"),[]);let i=(0,Tt.echoWrite)("formid"),o=`/systemforms${i.query}`,a=(0,Tt.withClientMintedId)(t,"formid",r),s=Object.freeze({...a}),l=await(0,Tt.resendDeadlockVictim)(()=>e.post(o,{...s},i.options));try{(0,Tt.ensureSuccess)(l,e.apiUrl(o))}catch(u){throw typeof u=="object"&&u!==null&&uN.set(u,{status:l.status,sent:s,desiredId:r}),u}return{id:(0,Tt.resolveCreatedId)(l,"formid","form",r),etag:(0,Tt.readEtag)(l)}},async update(e,t,r,n){let i=(0,an.normalizeGuid)(t,"id"),o=aN(r);return o!==void 0&&await OW(e,i,o,n),(0,Ag.patchSystemForm)(e,i,"form",r,n,SW)},readContentThenToken(e,t){return $t.formApi.get(e,t)},async delete(e,t){let r=(0,an.normalizeGuid)(t,"id");return await(0,nu.assertSystemFormKind)(e,r,"form"),(0,Tt.deleteRecord)(e,"systemforms",r)}};var Sg="DisplayConditions";async function IW(e,t,r){var n,i,o,a;if(r.everyone&&r.roleIds&&r.roleIds.length>0)throw new ea.InvalidArgumentError("setFormSecurityRoles: `everyone` and `roleIds` are mutually exclusive \u2014 the platform models <Everyone /> as a replacement for the <Role> list, not an addition to it.");let s=(0,an.normalizeGuid)(t,"formId"),l=`/systemforms(${s})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,an.odataQuery)([["$select","formid,formxml,type"]]),u=(0,Tt.ensureSuccess)(await e.get(l),e.apiUrl(l));(0,nu.assertSystemFormRecordKind)(u.body,s,"form","set the security roles of");let c=(0,Tt.readEtag)(u),d=u.body,f=d?.formxml;if(!f)throw new ea.InvalidArgumentError(`form '${s}' returned no formxml, so its roles cannot be set`);let m=(0,Eg.parseXmlRoot)(f,"<form/>"),p=m.ownerDocument;if(!p)throw new ea.InvalidArgumentError(`form '${s}' produced no owner document`);let h=dN(m,Sg),g=h?.hasAttribute("Order")&&(n=h.getAttribute("Order"))!==null&&n!==void 0?n:void 0,b=h?.getAttribute("FallbackForm")||void 0;h&&m.removeChild(h);let w=!!r.everyone||((o=(i=r.roleIds)===null||i===void 0?void 0:i.length)!==null&&o!==void 0?o:0)>0;if(!w&&(r.order!==void 0||r.fallbackForm!==void 0)){if(!h)throw new ea.InvalidArgumentError("setFormSecurityRoles: `order`/`fallbackForm` were supplied without `roleIds` or `everyone`, but this form has no <DisplayConditions> to attach them to. Pass the roles as well.");r.order!==void 0&&h.setAttribute("Order",String(r.order)),r.fallbackForm!==void 0&&h.setAttribute("FallbackForm",String(r.fallbackForm)),m.appendChild(h)}else if(w){let I=p.createElement(Sg),D=r.order!==void 0?String(r.order):g;D!==void 0&&I.setAttribute("Order",D);let P=r.fallbackForm!==void 0?String(r.fallbackForm):b??"false";if(I.setAttribute("FallbackForm",P),r.everyone)I.appendChild(p.createElement("Everyone"));else for(let x of(a=r.roleIds)!==null&&a!==void 0?a:[]){let K=p.createElement("Role");K.setAttribute("Id",`{${(0,an.normalizeGuid)(x,"roleId")}}`),I.appendChild(K)}m.appendChild(I)}let S=(0,Eg.serializeNode)(m);await(0,Ag.assertSystemFormContentUnchanged)(e,s,"form",l,c);let O=await(0,Ag.readSystemFormRowEtag)(e,s),k=`/systemforms(${s})`;(0,Tt.ensureSuccess)(await e.patch(k,{formxml:S},{headers:{"Content-Type":"application/json","If-Match":(0,Tt.requireEtag)(O,"form",s)}}),e.apiUrl(k))}$t.setFormSecurityRoles=IW;function aN(e){let t=e?.formxml;return typeof t=="string"&&t.includes(sN.GENPAGE_CONTROL_NAME)?t:void 0}function Ng(e,t){try{return(0,sN.activeEmbedBindings)(e)}catch(r){throw new ea.SdkError($t.FORM_GENPAGE_TARGET_UNVERIFIABLE,`Refusing to push the form: the ${t} formxml could not be parsed, so the generative pages it embeds cannot be verified (${r instanceof Error?r.message:String(r)}).`)}}async function cN(e,t,r){let n=new Set(r.map(([a,s])=>`${a}|${s}`)),i=t.filter(([a,s])=>!n.has(`${a}|${s}`)).map(([,a])=>a);if(i.length===0)return;let o=await(0,AW.findMissingGenPages)(e,i,"form generative-page preflight");if(o.length>0)throw new ea.SdkError($t.FORM_GENPAGE_TARGET_NOT_FOUND,`Refusing to push the form: it embeds generative page(s) ${o.map(a=>`'${a}'`).join(", ")} that do not exist in this environment. Push the page before the form that embeds it.`)}async function OW(e,t,r,n){var i;(0,Tt.requireEtag)(n,"form",t);let o=`/systemforms(${t})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,an.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Tt.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,nu.assertSystemFormRecordKind)(a.body,t,"form","write");let s=(0,Tt.readEtag)(a);if(s===null||s!==n)throw new ea.SdkError(Tt.VERSION_CONFLICT_CODE,`Version conflict writing form '${t}': its formxml changed on the server since it was read (held ${n}, server ${s??"(unreadable)"}). Re-fetch the form and re-apply the change.`);let l=(i=a.body)===null||i===void 0?void 0:i.formxml,u=typeof l=="string"&&l!==""?Ng(l,"server"):[];await cN(e,Ng(r,"payload"),u)}function dN(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 PW(e,t){var r,n;let i=(0,an.normalizeGuid)(t,"formId"),o=`/systemforms(${i})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,an.odataQuery)([["$select","formid,formxml,type"]]),a=(0,Tt.ensureSuccess)(await e.get(o),e.apiUrl(o));(0,nu.assertSystemFormRecordKind)(a.body,i,"form","read the security roles of");let s=(r=a.body)===null||r===void 0?void 0:r.formxml;if(!s)return;let l=(0,Eg.parseXmlRoot)(s,"<form/>"),u=dN(l,Sg);if(!u)return;let c=[],d=!1,f=u.childNodes;for(let p=0;p<f.length;p+=1){let h=f[p];if(h.nodeType!==1)continue;let g=h;if(g.tagName==="Everyone")d=!0;else if(g.tagName==="Role"){let b=(n=g.getAttribute("Id"))!==null&&n!==void 0?n:"";b&&c.push(b.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)}:{}}}$t.getFormSecurityRoles=PW});var Tg=v(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.deleteSolution=be.getDeploymentSettingsTemplate=be.importSolution=be.exportSolution=be.removeSolutionComponent=be.addSolutionComponent=be.setSolutionVersion=be.createSolution=be.createPublisher=be.getSolution=be.fetchSolutionComponents=be.resolveGenPageComponentType=be.SolutionComponentType=void 0;var RW=Lt(),Ft=ye(),ur=le(),kW=pt(),Yt=Q();be.SolutionComponentType={SavedQuery:26,Workflow:29,SavedQueryVisualization:59,SystemForm:60,AppModule:80};var LW=[be.SolutionComponentType.SavedQuery,be.SolutionComponentType.Workflow,be.SolutionComponentType.SavedQueryVisualization,be.SolutionComponentType.SystemForm,be.SolutionComponentType.AppModule],fN="uxagentproject",pN=new WeakMap;async function vN(e){var t;let r=pN.get(e);if(r!==void 0)return r;let n=`/EntityDefinitions(LogicalName='${fN}')${(0,ur.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status===404)return;(0,Ft.ensureSuccess)(i,e.apiUrl(n));let o=(t=i.body)===null||t===void 0?void 0:t.ObjectTypeCode;if(typeof o!="number"||!Number.isInteger(o)||o<=0)throw new Yt.SdkError("GENPAGE_COMPONENT_TYPE_UNRESOLVED",`A generative page's solution component type \u2014 the ObjectTypeCode of '${fN}' \u2014 could not be read: its metadata answered without a usable value (${JSON.stringify(o)}). Without it a solution's generative pages cannot be told apart from other components. Retry.`);return pN.set(e,o),o}be.resolveGenPageComponentType=vN;var mN=1,hN=0;async function $W(e,t){let r=(0,ur.normalizeGuid)(t,"solutionId"),n=await vN(e),o=[mN,...LW,...n===void 0?[]:[n]].map(c=>`componenttype eq ${c}`).join(" or "),a=`/solutioncomponents${(0,ur.odataQuery)([["$select","objectid,componenttype,rootcomponentbehavior"],["$filter",`_solutionid_value eq ${r} and (${o})`]])}`,s=await(0,RW.collectPages)(e,a,"fetchSolutionComponents"),l=[];for(let c of s){if(typeof c.objectid!="string")continue;let d=Number(c.componenttype);if(d===mN){let f=c.rootcomponentbehavior;(f===hN||f===String(hN))&&l.push({objectId:c.objectid,componentType:d,includesAllSubcomponents:!0});continue}l.push({objectId:c.objectid,componentType:d,...n!==void 0&&d===n?{genPage:!0}:{}})}let u=c=>c.objectId.toLowerCase().replace(/^\{|\}$/g,"");return l.sort((c,d)=>c.componentType-d.componentType||(u(c)<u(d)?-1:u(c)>u(d)?1:0))}be.fetchSolutionComponents=$W;function xW(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 FW(e,t){var r,n,i,o,a,s,l,u,c,d;let f=String(t??"").trim();if(!f)throw new Yt.InvalidArgumentError("getSolution: a solution unique name or id is required.");let m=xW(f)?`solutionid eq ${(0,ur.normalizeGuid)(f,"solutionId")}`:`uniquename eq '${(0,ur.odataLiteral)(f)}'`,p=`/solutions${(0,ur.odataQuery)([["$select","solutionid,uniquename,friendlyname,version,ismanaged"],["$expand","publisherid($select=publisherid,uniquename,customizationprefix,customizationoptionvalueprefix)"],["$filter",m]])}`,b=((n=(r=(0,Ft.ensureSuccess)(await e.get(p),e.apiUrl(p)).body)===null||r===void 0?void 0:r.value)!==null&&n!==void 0?n:[])[0];if(!b?.solutionid)throw new Yt.InvalidArgumentError(`No solution found for '${t}'.`);let w=b.publisherid;if(!w?.publisherid)throw new Yt.InvalidArgumentError(`Solution '${(i=b.uniquename)!==null&&i!==void 0?i:t}' returned no owning publisher, so its customization prefix cannot be determined; refusing to report an empty prefix that could be mistaken for "no prefix".`);if(!("customizationprefix"in w))throw new Yt.InvalidArgumentError(`Solution '${(o=b.uniquename)!==null&&o!==void 0?o:t}' returned a publisher without a customizationprefix property (partial expansion), so its prefix cannot be determined.`);return{solutionId:(0,ur.normalizeGuid)(b.solutionid,"solutionId"),uniqueName:(a=b.uniquename)!==null&&a!==void 0?a:"",friendlyName:(s=b.friendlyname)!==null&&s!==void 0?s:"",version:(l=b.version)!==null&&l!==void 0?l:"",isManaged:!!b.ismanaged,publisherId:(0,ur.normalizeGuid)(w.publisherid,"publisherId"),publisherUniqueName:(u=w.uniquename)!==null&&u!==void 0?u:"",publisherPrefix:(c=w.customizationprefix)!==null&&c!==void 0?c:"",publisherOptionValuePrefix:(d=w.customizationoptionvalueprefix)!==null&&d!==void 0?d:0}}be.getSolution=FW;async function MW(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,Ft.ensureSuccess)(await(0,Ft.resendDeadlockVictim)(()=>e.post("/publishers",{...n})),e.apiUrl("/publishers")),o=(0,Ft.readCreatedId)(i,"publisherid");if(!o)throw new Yt.InvalidArgumentError(`Dataverse did not return an id for publisher '${t.uniqueName}'`);return{id:o,uniqueName:t.uniqueName}}be.createPublisher=MW;async function UW(e,t){var r;let n=(0,ur.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 o=(0,Ft.ensureSuccess)(await e.post("/solutions",i),e.apiUrl("/solutions")),a=(0,Ft.readCreatedId)(o,"solutionid");if(!a)throw new Yt.InvalidArgumentError(`Dataverse did not return an id for solution '${t.uniqueName}'`);return{id:a,uniqueName:t.uniqueName}}be.createSolution=UW;async function BW(e,t,r){let i=`/solutions(${(0,ur.normalizeGuid)(t,"solutionId")})`;(0,Ft.ensureSuccess)(await e.patch(i,{version:r}),e.apiUrl(i))}be.setSolutionVersion=BW;async function qW(e,t){var r;let i={ComponentId:(0,ur.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,Ft.ensureSuccess)(await e.post("/AddSolutionComponent",i),e.apiUrl("/AddSolutionComponent"))}be.addSolutionComponent=qW;async function VW(e,t,r,n){let o={SolutionComponent:{"@odata.type":"Microsoft.Dynamics.CRM.solutioncomponent",solutioncomponentid:(0,ur.normalizeGuid)(t,"componentId")},ComponentType:r,SolutionUniqueName:n};(0,Ft.ensureSuccess)(await e.post("/RemoveSolutionComponent",o),e.apiUrl("/RemoveSolutionComponent"))}be.removeSolutionComponent=VW;async function GW(e,t){var r,n;let i={SolutionName:t.solutionName,Managed:(r=t.managed)!==null&&r!==void 0?r:!1},a=(n=(0,Ft.ensureSuccess)(await e.post("/ExportSolution",i),e.apiUrl("/ExportSolution")).body)===null||n===void 0?void 0:n.ExportSolutionFile;if(!a)throw new Yt.InvalidArgumentError(`ExportSolution returned no file for '${t.solutionName}'`);return{base64:a}}be.exportSolution=GW;async function WW(e,t){let r=[["overwriteUnmanagedCustomizations","overwrote unmanaged customizations made over the solution's components"],["publishWorkflows","activated the solution's workflows"]];for(let[a,s]of r)if(typeof t?.[a]!="boolean")throw new Yt.InvalidArgumentError(`importSolution: '${a}' is required and must be true or false (it was ${String(t?.[a])}). It used to default to true, which ${s} unless the caller said otherwise. Nothing was imported.`);let n=t.deploymentSettings===void 0?void 0:t5(t.deploymentSettings),i={OverwriteUnmanagedCustomizations:t.overwriteUnmanagedCustomizations,PublishWorkflows:t.publishWorkflows,CustomizationFile:t.base64,ImportJobId:t.importJobId?(0,ur.normalizeGuid)(t.importJobId,"importJobId"):(0,kW.newId)()};if(!n)return(0,Ft.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{};if(n.variables.length===0&&n.references.length===0)return(0,Ft.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:{environmentVariables:[],connectionReferences:[]}};let o=[];try{let a=await wN(e,t.base64,iu,o),{parameters:s,applied:l}=r5(a,n);return i.ComponentParameters=s,(0,Ft.ensureSuccess)(await e.post("/ImportSolution",i),e.apiUrl("/ImportSolution")),{appliedSettings:l,...o.length>0?{warnings:o}:{}}}catch(a){throw(0,Yt.withCleanupWarnings)(a,o)}}be.importSolution=WW;var iu="importSolution",gN="getDeploymentSettingsTemplate";async function zW(e,t){var r;let n=t?.base64;if(typeof n!="string"||n.length===0)throw new Yt.InvalidArgumentError(`${gN}: 'base64' must be the solution package \u2014 a non-empty base64 string, e.g. exportSolution's result (it was ${(r=JSON.stringify(n))!==null&&r!==void 0?r:String(n)})`);let i=[];try{let o=await wN(e,n,gN,i),a=Pd(o.variables,l=>l.SchemaName).map(({SchemaName:l,DefaultValue:u,TypeId:c,IsRequired:d})=>({SchemaName:l,Value:"",...u!==void 0?{DefaultValue:u}:{},...c!==void 0?{TypeId:c}:{},...d!==void 0?{IsRequired:d}:{}})),s=Pd(o.references,l=>l.LogicalName).map(({LogicalName:l,ConnectorId:u})=>({LogicalName:l,ConnectionId:"",...u!==void 0?{ConnectorId:u}:{}}));return{settings:{EnvironmentVariables:a,ConnectionReferences:s},...i.length>0?{warnings:i}:{}}}catch(o){throw(0,Yt.withCleanupWarnings)(o,i)}}be.getDeploymentSettingsTemplate=zW;function Pd(e,t){return[...e].sort((r,n)=>{let i=t(r).toLowerCase(),o=t(n).toLowerCase();return i<o?-1:i>o?1:0})}function ta(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xt(e,t=120){var r;let n=(r=JSON.stringify(e))!==null&&r!==void 0?r:String(e);return n.length>t?`${n.slice(0,t)}\u2026`:n}async function wN(e,t,r,n){var i;let a=(i=(0,Ft.ensureSuccess)(await e.post("/StageSolution",{CustomizationFile:t}),e.apiUrl("/StageSolution")).body)===null||i===void 0?void 0:i.StageSolutionResults;try{return HW(a,r)}finally{await jW(e,ta(a)?a.StageSolutionUploadId:void 0,n)}}async function jW(e,t,r){let n;try{n=(0,ur.normalizeGuid)(t,"StageSolutionUploadId")}catch{r.push(`StageSolution's reply named no usable staging upload id (${xt(t,60)}), so the staged copy of the package it may have stored (a stagesolutionupload row of yours) could not be deleted.`);return}let i=`/stagesolutionuploads(${n})`;try{let o=await e.delete(i);o.status!==404&&(0,Ft.ensureSuccess)(o,e.apiUrl(i))}catch(o){r.push(`The staged copy of the package (stagesolutionupload ${n}) could not be deleted: ${o instanceof Error?o.message:String(o)}. It stays until it is deleted (DELETE ${i}).`)}}function lr(e,t){return new Yt.SdkError("SOLUTION_STAGING_UNREADABLE",`${e}: StageSolution's reply could not be read \u2014 ${t}.${e===iu?" Nothing was imported.":""}`)}function yN(e){return!Array.isArray(e)||e.length===0?"none":`${e.slice(0,5).map(r=>ta(r)&&typeof r.Message=="string"?r.Message:xt(r,200)).join("; ")}${e.length>5?` (+${e.length-5} more)`:""}`}function HW(e,t){if(!ta(e))throw lr(t,`it holds no StageSolutionResults (${xt(e,60)})`);let r=e.StageSolutionStatus;if(r==="Failed"||r===0)throw new Yt.SdkError("SOLUTION_STAGING_FAILED",`${t}: the package did not pass StageSolution in this environment (status ${xt(r)}). Missing dependencies: ${yN(e.MissingDependencies)}. Validation: ${yN(e.SolutionValidationResults)}.${t===iu?" Its components cannot be checked against deploymentSettings. Nothing was imported.":" Stage it in the environment it was exported from."}`);if(r!=="Passed"&&r!==1)throw lr(t,`StageSolutionStatus is ${xt(r)}, neither "Passed" nor "Failed"`);let n=e.SolutionComponentsDetails;if(!Array.isArray(n))throw lr(t,`SolutionComponentsDetails is not a list (${xt(n,60)})`);let i=[],o=[],a=new Set,s=new Set;return n.forEach((l,u)=>{let c=`SolutionComponentsDetails[${u}]`;if(!ta(l))throw lr(t,`${c} is not an object`);if(typeof l.ComponentTypeName!="string")throw lr(t,`${c}.ComponentTypeName is not a string`);let d=l.ComponentTypeName.toLowerCase();if(d!=="environmentvariabledefinition"&&d!=="connectionreference")return;let f=KW(l.Attributes,`${c}.Attributes`,t),m=(p,h)=>{let g=f.get(p);if(g==null){if(h)throw lr(t,`${c}.${p} is missing`);return}if(typeof g!="string"||h&&g.length===0)throw lr(t,`${c}.${p} is not ${h?"a non-empty string":"a string"}`);return g};if(d==="environmentvariabledefinition"){let p=m("schemaname",!0);if(a.has(p.toLowerCase()))throw lr(t,`${c}.schemaname '${p}' is listed twice`);a.add(p.toLowerCase());let h=m("defaultvalue",!1),g=JW(f.get("type"),`${c}.type`,t),b=YW(f.get("isrequired"),`${c}.isrequired`,t);i.push({SchemaName:p,...h!==void 0?{DefaultValue:h}:{},...g!==void 0?{TypeId:g}:{},...b!==void 0?{IsRequired:b}:{}})}else{let p=m("connectionreferencelogicalname",!0);if(s.has(p.toLowerCase()))throw lr(t,`${c}.connectionreferencelogicalname '${p}' is listed twice`);s.add(p.toLowerCase());let h=m("connectorid",!1);o.push({LogicalName:p,...h!==void 0?{ConnectorId:h}:{}})}}),{variables:i,references:o}}function KW(e,t,r){if(!ta(e)||!Array.isArray(e.Keys)||!Array.isArray(e.Values))throw lr(r,`${t} is not { Keys: [...], Values: [...] }`);let{Keys:n,Values:i}=e;if(n.length!==i.length)throw lr(r,`${t} has ${n.length} keys but ${i.length} values`);let o=new Map;return n.forEach((a,s)=>{if(typeof a!="string")throw lr(r,`${t}.Keys[${s}] is not a string`);if(o.has(a))throw lr(r,`${t}.Keys lists '${a}' twice`);o.set(a,i[s])}),o}function JW(e,t,r){if(e!=null){if(typeof e=="number"&&Number.isSafeInteger(e))return e;if(typeof e=="string"&&/^\d{1,15}$/.test(e))return Number(e);throw lr(r,`${t} is not a whole number (${xt(e,40)})`)}}function YW(e,t,r){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string"&&/^(true|false)$/i.test(e))return e.toLowerCase()==="true";throw lr(r,`${t} is not true or false (${xt(e,40)})`)}}var QW=new Set(["EnvironmentVariables","ConnectionReferences","Workflows","CanvasApps","CopilotAgents","$schema"]),XW=["Workflows","CanvasApps","CopilotAgents"],ZW=new Set(["SchemaName","Value","DefaultValue","TypeId","IsRequired","Name"]),e5=new Set(["LogicalName","ConnectionId","ConnectorId"]);function sr(e,t){return new Yt.InvalidArgumentError(`${iu}: deploymentSettings is not a deployment-settings file this SDK applies \u2014 ${e} ${t}. Nothing was imported.`)}function t5(e){let t="deploymentSettings";if(!ta(e))throw sr(t,`must be an object \u2014 the settings file, parsed (it was ${xt(e,40)})`);for(let l of Object.keys(e))if(!QW.has(l))throw sr(`${t}.${l}`,"is not part of the format (EnvironmentVariables, ConnectionReferences; Workflows, CanvasApps and CopilotAgents only empty; $schema)");for(let l of XW){let u=e[l];if(u!==void 0&&!(Array.isArray(u)&&u.length===0))throw sr(`${t}.${l}`,"is a pac feature this SDK does not apply: only an empty list is accepted")}if(e.$schema!==void 0&&typeof e.$schema!="string")throw sr(`${t}.$schema`,"must be a string");let r=l=>{let u=e[l];if(u===void 0)return[];if(!Array.isArray(u))throw sr(`${t}.${l}`,`must be a list (it was ${xt(u,40)})`);return u.map((c,d)=>{if(!ta(c))throw sr(`${t}.${l}[${d}]`,`must be an object (it was ${xt(c,40)})`);return c})},n=(l,u,c)=>{let d=l[u];if(typeof d!="string"||d.length===0)throw sr(c,`must be a non-empty string (it was ${xt(d,40)})`);if(d.trim()!==d)throw sr(c,`must not begin or end with whitespace (it was ${xt(d,60)})`);return d},i=(l,u,c)=>{if(l.has(u.toLowerCase()))throw sr(c,`names '${u}' a second time (names are case-insensitive)`);l.add(u.toLowerCase())},o={variables:[],references:[]},a=new Set;r("EnvironmentVariables").forEach((l,u)=>{let c=`${t}.EnvironmentVariables[${u}]`;for(let f of Object.keys(l))if(!ZW.has(f))throw sr(`${c}.${f}`,"is not part of a variable (SchemaName, Value; DefaultValue, TypeId, IsRequired, Name)");let d=n(l,"SchemaName",`${c}.SchemaName`);if(i(a,d,`${c}.SchemaName`),typeof l.Value!="string")throw sr(`${c}.Value`,`must be a string \u2014 empty to override nothing (it was ${xt(l.Value,40)})`);l.Value.length>0&&o.variables.push({name:d,value:l.Value})});let s=new Set;return r("ConnectionReferences").forEach((l,u)=>{let c=`${t}.ConnectionReferences[${u}]`;for(let m of Object.keys(l))if(!e5.has(m))throw sr(`${c}.${m}`,m==="ConnectionInstance"?"is pac's connection-instance feature, which this SDK does not apply":"is not part of a connection reference (LogicalName, ConnectionId, ConnectorId)");let d=n(l,"LogicalName",`${c}.LogicalName`);i(s,d,`${c}.LogicalName`);let f=l.ConnectionId;if(typeof f!="string")throw sr(`${c}.ConnectionId`,`must be a string \u2014 empty to bind nothing (it was ${xt(f,40)})`);if(f.trim()!==f)throw sr(`${c}.ConnectionId`,`must not begin or end with whitespace (it was ${xt(f,60)})`);if(l.ConnectorId!==void 0&&typeof l.ConnectorId!="string")throw sr(`${c}.ConnectorId`,`must be a string (it was ${xt(l.ConnectorId,40)})`);f.length>0&&o.references.push({name:d,connectionId:f,...l.ConnectorId?{connectorId:l.ConnectorId}:{}})}),o}function bN(e,t=20){return e.length===0?"none":`${e.slice(0,t).join(", ")}${e.length>t?` (+${e.length-t} more)`:""}`}function r5(e,t){var r;let n=new Map(e.variables.map(l=>[l.SchemaName.toLowerCase(),l])),i=new Map(e.references.map(l=>[l.LogicalName.toLowerCase(),l])),o=[],a=[],s={environmentVariables:[],connectionReferences:[]};for(let l of t.variables){let u=n.get(l.name.toLowerCase());if(!u){o.push(`EnvironmentVariables: '${l.name}' is not a variable of the package`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.environmentvariablevalue",schemaname:u.SchemaName,value:l.value}),s.environmentVariables.push(u.SchemaName)}for(let l of t.references){let u=i.get(l.name.toLowerCase());if(!u){o.push(`ConnectionReferences: '${l.name}' is not a connection reference of the package`);continue}if(l.connectorId!==void 0&&l.connectorId.toLowerCase()!==((r=u.ConnectorId)===null||r===void 0?void 0:r.toLowerCase())){o.push(`ConnectionReferences: '${l.name}' names connector '${l.connectorId}', but the package's reference is for ${u.ConnectorId?`'${u.ConnectorId}'`:"no connector"}`);continue}a.push({"@odata.type":"Microsoft.Dynamics.CRM.connectionreference",connectionreferencelogicalname:u.LogicalName,connectionid:l.connectionId,...u.ConnectorId!==void 0?{connectorid:u.ConnectorId}:{}}),s.connectionReferences.push(u.LogicalName)}if(o.length>0){let l=o.join("; "),u=bN(Pd(e.variables,d=>d.SchemaName).map(d=>d.SchemaName)),c=bN(Pd(e.references,d=>d.LogicalName).map(d=>d.LogicalName));throw new Yt.InvalidArgumentError(`${iu}: deploymentSettings does not match the package \u2014 ${l}. The package's variables: ${u}; its connection references: ${c}. Nothing was imported.`)}return{parameters:a,applied:s}}async function n5(e,t){let n=`/solutions(${(0,ur.normalizeGuid)(t,"solutionId")})`;(0,Ft.ensureSuccess)(await e.delete(n),e.apiUrl(n))}be.deleteSolution=n5});var _N=v(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.recoverFormCreate=mt.solutionMembershipProblem=mt.formWriteMismatches=mt.validateExistingForm=mt.formExistsAtId=mt.isFormRecordAt=mt.MAIN_FORM_TYPE=void 0;var fs=le(),CN=Lt(),EN=Tg();mt.MAIN_FORM_TYPE=2;function Rd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kd(e){return e instanceof Error?e.message:String(e)}function Dg(e,t){if(typeof e!="string"||typeof t!="string")return!1;try{return(0,fs.normalizeGuid)(e,"a GUID")===(0,fs.normalizeGuid)(t,"a GUID")}catch{return!1}}function Ig(e,t){return Rd(e)&&Dg(e.formid,t)}mt.isFormRecordAt=Ig;async function i5(e,t){try{return Ig((await e()).raw,t)}catch{return!1}}mt.formExistsAtId=i5;function AN(e,t){let r=e.raw;if(!Rd(r))return{problem:"it is not a record"};if(!Ig(r,t))return{problem:"its formid is not the id this create sent"};if(r.type!==mt.MAIN_FORM_TYPE)return{problem:`its type is not ${mt.MAIN_FORM_TYPE} (a Main form)`};if(typeof r.objecttypecode!="string")return{problem:"its objecttypecode is not a string"};if(typeof r.name!="string")return{problem:"its name is not a string"};if(typeof r.formxml!="string"||r.formxml.length===0)return{problem:"its formxml is not a non-empty string"};if(typeof r.formpresentation!="number")return{problem:"its formpresentation is not a number"};if(typeof r.formactivationstate!="number")return{problem:"its formactivationstate is not a number"};for(let o of["uniquename","description"]){let a=r[o];if(a!=null&&typeof a!="string")return{problem:`its ${o} is neither a string nor null`}}let n=r["@odata.etag"];if(n!==void 0&&typeof n!="string")return{problem:"its @odata.etag is not a string"};if(n!==void 0&&e.etag!==null&&e.etag!==n)return{problem:"the ETag header and the @odata.etag of the body disagree"};let i=e.etag;return i===null?{problem:"the read carries no concurrency token"}:i.trim()===""||i.trim()==="*"?{problem:"its concurrency token is blank or a wildcard"}:{record:r,etag:i}}mt.validateExistingForm=AN;function SN(e,t){let r=[];for(let i of["formxml","name","objecttypecode","type"])e[i]!==t[i]&&r.push(i);let n=t.description;if(n!==void 0){let i=e.description;typeof n=="string"&&(n===""?i==null||i==="":i===n)||r.push("description")}return r}mt.formWriteMismatches=SN;async function NN(e,t){let r=e.solutionName;if(r)try{let n=await(0,CN.collectPages)(e,`/solutions${(0,fs.odataQuery)([["$select","solutionid,uniquename"],["$filter",`uniquename eq '${(0,fs.odataLiteral)(r)}'`]])}`,"createRecovery solution lookup");if(n.length!==1)return`the configured solution '${r}' resolves to ${n.length} solutions, not exactly one`;let[i]=n,o;return Rd(i)&&typeof i.uniquename=="string"&&typeof i.solutionid=="string"&&i.uniquename.toLowerCase()===r.toLowerCase()&&(o=(0,fs.normalizeGuid)(i.solutionid,"solutionid")),o===void 0?`the configured solution '${r}' did not resolve to a valid solution of that name`:(await(0,CN.collectPages)(e,`/solutioncomponents${(0,fs.odataQuery)([["$select","objectid,componenttype,_solutionid_value"],["$filter",`_solutionid_value eq ${o} and componenttype eq ${EN.SolutionComponentType.SystemForm} and objectid eq ${t}`]])}`,"createRecovery solution membership")).some(l=>Rd(l)&&l.componenttype===EN.SolutionComponentType.SystemForm&&Dg(l.objectid,t)&&Dg(l._solutionid_value,o))?void 0:`the form is not a component of the configured solution '${r}'`}catch(n){return`membership in the configured solution '${r}' could not be established (${kd(n)})`}}mt.solutionMembershipProblem=NN;async function o5(e){try{return await a5(e)}catch(t){return{refused:`the recovery could not be completed (${kd(t)})`}}}mt.recoverFormCreate=o5;async function a5(e){let{client:t,read:r,sent:n,authoredFormType:i,project:o}=e;if(i!=="Main"||n.type!==mt.MAIN_FORM_TYPE)return{refused:`only a Main form is adopted (this one is authored as ${String(i)})`};let a=n.formid;if(typeof a!="string")return{refused:"the create sent no formid to look for"};let s;try{s=await r()}catch(f){return{refused:`the existing row could not be read (${kd(f)})`}}let l=AN(s,a);if("problem"in l)return{refused:`the existing row cannot be trusted: ${l.problem}`};let u=SN(l.record,n);if(u.length>0)return{refused:`the existing row is not what this create wrote (it differs in ${u.join(", ")})`};let c;try{c=o(l.record)}catch(f){return{refused:`the existing row could not be read into a form (${kd(f)})`}}let d=await NN(t,a);return d!==void 0?{refused:d}:{adopted:{artifact:c,etag:l.etag}}}});var $d=v(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.disassociateRecords=Ke.associateRecords=Ke.createRecordsBulk=Ke.upsertRecord=Ke.queryAllRecords=Ke.queryRecords=Ke.getRecord=Ke.deleteRecord=Ke.updateRecord=Ke.createRecord=void 0;var Og=Lt(),Nn=ye(),Qt=le(),ps=Q(),Yn=bd();function Ld(e){let t=e,r=!1,n={};for(let i of Object.keys(t)){let o=t[i];Array.isArray(o)&&o.every(a=>typeof a=="number")?(n[i]=o.join(","),r=!0):n[i]=o}return r?n:e}async function s5(e,t,r){let i=`/${await(0,Yn.resolveEntitySetName)(e,t)}`,o=(0,Nn.ensureSuccess)(await e.post(i,Ld(r)),e.apiUrl(i)),a=(0,Nn.readCreatedId)(o,`${t}id`);if(!a)throw new ps.InvalidArgumentError(`Dataverse did not return an id for the created '${t}' row`);return{id:a,entityType:t}}Ke.createRecord=s5;async function l5(e,t,r,n){let i=(0,Qt.normalizeGuid)(r,"id"),a=`/${await(0,Yn.resolveEntitySetName)(e,t)}(${i})`;(0,Nn.ensureSuccess)(await e.patch(a,Ld(n)),e.apiUrl(a))}Ke.updateRecord=l5;async function u5(e,t,r){let n=(0,Qt.normalizeGuid)(r,"id"),o=`/${await(0,Yn.resolveEntitySetName)(e,t)}(${n})`;(0,Nn.ensureSuccess)(await e.delete(o),e.apiUrl(o))}Ke.deleteRecord=u5;async function c5(e,t,r,n){let i=(0,Qt.normalizeGuid)(r,"id"),o=await(0,Yn.resolveEntitySetName)(e,t),a=(0,Qt.odataQuery)([["$select",n&&n.length>0?n.join(","):void 0]]),s=`/${o}(${i})${a}`,l=(0,Nn.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=l.body;if(u===null||typeof u!="object"||Array.isArray(u))throw new ps.ConnectionError(e.apiUrl(s),l.status,`getRecord: read returned a malformed row \u2014 expected an OData entity object but got ${Array.isArray(u)?"an array":(0,Og.describeMalformedValue)(u)}; refusing to read it as a row.`);return u}Ke.getRecord=c5;function d5(e){return e?.fetchXml?(0,Qt.odataQuery)([["fetchXml",e.fetchXml]]):(0,Qt.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 TN(e,t,r){var n;if(r?.paginate){if(r.top!==void 0)throw new ps.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 ps.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,Yn.resolveEntitySetName)(e,t)}${d5(r)}`;if(r?.paginate)return(0,Og.collectPages)(e,o,"queryRecords");let a=(0,Nn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new ps.ConnectionError(e.apiUrl(o),a.status,`queryRecords: read returned a malformed page \u2014 expected an OData 'value' array but got ${(0,Og.describeMalformedValue)(s)}; refusing to read it as rows.`);return s}Ke.queryRecords=TN;async function f5(e,t,r){return TN(e,t,{...r,paginate:!0})}Ke.queryAllRecords=f5;function p5(e){if("id"in e)return`(${(0,Qt.normalizeGuid)(e.id,"id")})`;let t=typeof e.value=="string"?`'${(0,Qt.odataPathLiteral)(e.value)}'`:e.value;return`(${(0,Qt.assertODataName)(e.key,"alternate key name")}=${t})`}async function m5(e,t,r,n){let i=p5(r),a=`/${await(0,Yn.resolveEntitySetName)(e,t)}${i}`,s=(0,Nn.ensureSuccess)(await e.patch(a,Ld(n)),e.apiUrl(a)),l=s.status===201,u=(0,Nn.readCreatedId)(s,`${t}id`);return{id:u??("id"in r?(0,Qt.normalizeGuid)(r.id,"id"):""),created:l}}Ke.upsertRecord=m5;async function h5(e,t,r){var n,i;if(r.length===0)return[];let o=await(0,Yn.resolveEntitySetName)(e,t),a=r.map(c=>({"@odata.type":`Microsoft.Dynamics.CRM.${t}`,...Ld(c)})),s=`/${o}/Microsoft.Dynamics.CRM.CreateMultiple`,u=(i=(n=(0,Nn.ensureSuccess)(await e.post(s,{Targets:a}),e.apiUrl(s)).body)===null||n===void 0?void 0:n.Ids)!==null&&i!==void 0?i:[];if(u.length!==r.length)throw new ps.InvalidArgumentError(`CreateMultiple on '${t}' returned ${u.length} id(s) for ${r.length} row(s)`);return u}Ke.createRecordsBulk=h5;async function g5(e,t,r,n){let i=(0,Qt.normalizeGuid)(r,"id"),o=(0,Qt.normalizeGuid)(n.targetId,"targetId"),a=await(0,Yn.resolveEntitySetName)(e,t),s=await(0,Yn.resolveEntitySetName)(e,n.targetEntity),l=(0,Qt.assertODataName)(n.relationshipName,"relationshipName"),u=`/${a}(${i})/${l}/$ref`,c={"@odata.id":e.apiUrl(`/${s}(${o})`)};(0,Nn.ensureSuccess)(await e.post(u,c),e.apiUrl(u))}Ke.associateRecords=g5;async function y5(e,t,r,n,i){let o=(0,Qt.normalizeGuid)(r,"id"),a=(0,Qt.normalizeGuid)(i,"targetId"),s=await(0,Yn.resolveEntitySetName)(e,t),l=(0,Qt.assertODataName)(n,"relationshipName"),u=`/${s}(${o})/${l}(${a})/$ref`;(0,Nn.ensureSuccess)(await e.delete(u),e.apiUrl(u))}Ke.disassociateRecords=y5});var xd=v(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.base64ToUtf8=sn.base64ToBytes=sn.bytesToBase64=sn.utf8ToBase64=sn.utf8ToBytes=void 0;var Pg=32768,Tr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function ou(){return globalThis}function DN(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e.charCodeAt(r);if(n>=55296&&n<=56319){let i=r+1<e.length?e.charCodeAt(r+1):0;i>=56320&&i<=57343?(n=(n-55296<<10)+(i-56320)+65536,r+=1):n=65533}else n>=56320&&n<=57343&&(n=65533);n<128?t.push(n):n<2048?t.push(192|n>>6,128|n&63):n<65536?t.push(224|n>>12,128|n>>6&63,128|n&63):t.push(240|n>>18,128|n>>12&63,128|n>>6&63,128|n&63)}return Uint8Array.from(t)}function b5(e){let t="";for(let r=0;r<e.length;r+=Pg)t+=String.fromCharCode(...e.subarray(r,r+Pg));return t}function v5(e){let t="";for(let r=0;r<e.length;r+=1){let n=String.fromCharCode(e.charCodeAt(r)&255);if(n==="=")break;n==="-"?t+="+":n==="_"?t+="/":Tr.indexOf(n)>=0&&(t+=n)}for(t.length%4===1&&(t=t.slice(0,-1));t.length%4!==0;)t+="=";return t}function w5(e){let t="",r=0;for(;r+2<e.length;r+=3){let i=e[r]<<16|e[r+1]<<8|e[r+2];t+=Tr[i>>18&63]+Tr[i>>12&63]+Tr[i>>6&63]+Tr[i&63]}let n=e.length-r;if(n===1){let i=e[r]<<16;t+=`${Tr[i>>18&63]}${Tr[i>>12&63]}==`}else if(n===2){let i=e[r]<<16|e[r+1]<<8,o=Tr[i>>18&63],a=Tr[i>>12&63],s=Tr[i>>6&63];t+=`${o}${a}${s}=`}return t}function C5(e){let t=e.endsWith("==")?2:e.endsWith("=")?1:0,r=e.length/4*3-t,n=new Uint8Array(r>0?r:0),i=0;for(let o=0;o<e.length;o+=4){let a=Tr.indexOf(e[o])<<18|Tr.indexOf(e[o+1])<<12|(e[o+2]==="="?0:Tr.indexOf(e[o+2]))<<6|(e[o+3]==="="?0:Tr.indexOf(e[o+3]));i<r&&(n[i++]=a>>16&255),i<r&&(n[i++]=a>>8&255),i<r&&(n[i++]=a&255)}return n}function E5(e){let t=ou();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"utf8"));let r=t.TextEncoder;return r?new r().encode(e):DN(e)}sn.utf8ToBytes=E5;function A5(e){let t=ou();if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");let r=t.TextEncoder;return IN(r?new r().encode(e):DN(e))}sn.utf8ToBase64=A5;function IN(e){let t=ou();return t.Buffer?t.Buffer.from(e).toString("base64"):t.btoa?t.btoa(b5(e)):w5(e)}sn.bytesToBase64=IN;function ON(e){let t=ou();if(t.Buffer)return new Uint8Array(t.Buffer.from(e,"base64"));let r=v5(e);if(t.atob){let n=t.atob(r);return Uint8Array.from(n,i=>i.charCodeAt(0))}return C5(r)}sn.base64ToBytes=ON;function S5(e){let t=[],r="",n=()=>{r+=String.fromCharCode(...t),t.length=0},i=a=>{if(a>65535){let s=a-65536;t.push(55296+(s>>10),56320+(s&1023))}else t.push(a);t.length>=Pg&&n()},o=0;for(;o<e.length;){let a=e[o],s=0,l=0,u=128,c=191;if(a<128){i(a),o+=1;continue}else if(a>=194&&a<=223)s=1,l=a&31;else if(a>=224&&a<=239)s=2,l=a&15,u=a===224?160:128,c=a===237?159:191;else if(a>=240&&a<=244)s=3,l=a&7,u=a===240?144:128,c=a===244?143:191;else{i(65533),o+=1;continue}let d=o+1,f=!0;for(let m=0;m<s;m+=1,d+=1){let p=d<e.length?e[d]:-1;if(p<u||p>c){f=!1;break}u=128,c=191,l=l<<6|p&63}f?(i(l),o=d):(i(65533),o=d)}return n(),r}function N5(e){let t=ou();return t.Buffer?t.Buffer.from(e,"base64").toString("utf8"):S5(ON(e))}sn.base64ToUtf8=N5});var $N=v(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.deleteWebResource=Qn.getWebResource=Qn.updateWebResource=Qn.createWebResource=void 0;var _5=Qr(),ra=ye(),au=le(),Rg=xd(),ms=Q(),T5={html:1,css:2,js:3,xml:4,png:5,jpg:6,gif:7,xsl:9,ico:10,svg:11,resx:12};function PN(e){if(e.contentBase64!==void 0)return e.contentBase64;if(e.content!==void 0)return(0,Rg.utf8ToBase64)(e.content)}async function RN(e,t){return(0,_5.publishWebResourceById)(e,t)}async function kN(e,t,r){try{await RN(e,t)}catch(n){let i=r?`Web resource '${r.name}' (${t})`:`Web resource ${t}`,o=`write its content again with updateWebResource('${t}', \u2026), which publishes and verifies again`+(r?" \u2014 it exists, and a second create of this name is refused":""),a=(0,ra.isConcurrencyLockRefusalError)(n)?`Another customization operation holds the environment's lock, and content has been observed missing after a publish the lock refused, so publishing again alone may not recover it: once the lock frees, ${o}.`:`Resolve that failure first, then ${o}.`;throw(0,ms.attachCause)(new ms.WebResourceUnverifiedError(t,r?.name,`${i} was written, but publishing it failed, so whether its published content is what was sent is unconfirmed (${n instanceof Error?n.message:String(n)}). ${a}`),n)}}function D5(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}async function LN(e,t,r,n){var i;let o=n?`Web resource '${n.name}' (${t})`:`Web resource ${t}`,a=n?`It exists: write its content again with updateWebResource('${t}', \u2026), which publishes and verifies again \u2014 a second create of this name is refused.`:"Writing it again is safe.",s=c=>new ms.WebResourceUnverifiedError(t,n?.name,`${o} ${c} ${a}`),l=`/webresourceset(${t})${(0,au.odataQuery)([["$select","content"]])}`,u;try{u=(i=(0,ra.ensureSuccess)(await e.get(l),e.apiUrl(l)).body)===null||i===void 0?void 0:i.content}catch(c){throw(0,ms.attachCause)(s("was written and published, but reading its published content back failed, so whether the write applied is unknown."),c)}if(typeof u!="string")throw s("was written and published, but the read-back carried no content, so whether the write applied is unknown.");if(!D5((0,Rg.base64ToBytes)(u),(0,Rg.base64ToBytes)(r)))throw s("was written and published, but the published content is not what was sent, so the write did not apply.")}async function I5(e,t){var r;let n=PN(t);if(n===void 0)throw new ms.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:T5[t.type],content:n};t.description&&(i.description=t.description);let o=(0,ra.ensureSuccess)(await e.post("/webresourceset",i),e.apiUrl("/webresourceset")),a=(0,ra.readCreatedId)(o,"webresourceid");if(!a)throw new ms.InvalidArgumentError(`Dataverse did not return an id for web resource '${t.name}'`);return t.publish!==!1&&(await kN(e,a,{name:t.name}),await LN(e,a,n,{name:t.name})),{id:a,name:t.name}}Qn.createWebResource=I5;async function O5(e,t,r){let n=(0,au.normalizeGuid)(t,"id"),i={},o=PN(r);o!==void 0&&(i.content=o),r.displayName!==void 0&&(i.displayname=r.displayName),r.description!==void 0&&(i.description=r.description);let a=`/webresourceset(${n})`;(0,ra.ensureSuccess)(await e.patch(a,i),e.apiUrl(a)),r.publish!==!1&&(o!==void 0?(await kN(e,n,void 0),await LN(e,n,o,void 0)):await RN(e,n))}Qn.updateWebResource=O5;async function P5(e,t){var r;let i=`/webresourceset(${(0,au.normalizeGuid)(t,"id")})${(0,au.odataQuery)([["$select","name,displayname,webresourcetype,content,description"]])}`;return(r=(0,ra.ensureSuccess)(await e.get(i),e.apiUrl(i)).body)!==null&&r!==void 0?r:{}}Qn.getWebResource=P5;async function R5(e,t){let n=`/webresourceset(${(0,au.normalizeGuid)(t,"id")})`;(0,ra.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Qn.deleteWebResource=R5});var Fd=v(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.applyAppSettings=Dt.setAppSetting=Dt.readAppSettings=Dt.resolveSettingDefinitions=Dt.APP_SETTING_UNSET=Dt.APP_SETTING_OFF=Dt.APP_SETTING_ON=Dt.HEADER_AND_NAVIGATION_REFRESH=void 0;var hs=ye(),Pi=le();Dt.HEADER_AND_NAVIGATION_REFRESH="HeaderAndNavigationRefresh";Dt.APP_SETTING_ON="2";Dt.APP_SETTING_OFF="1";Dt.APP_SETTING_UNSET="0";function MN(e,t){return"/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Pi.odataQuery)([["$select",e],["$filter",t]])}async function UN(e,t){var r,n;let i=[...new Set(t.filter(Boolean))],o=new Map;if(i.length===0)return o;let a=i.map(c=>`uniquename eq '${(0,Pi.odataLiteral)(c)}'`).join(" or "),s=`/settingdefinitions${(0,Pi.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",a]])}`,u=((n=(r=(0,hs.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&&o.set(c.uniquename,c);return o}Dt.resolveSettingDefinitions=UN;async function k5(e,t){var r,n,i,o;let a=(0,Pi.normalizeGuid)(t,"App id"),s=MN("appsettingid,value,_settingdefinitionid_value",`_parentappmoduleid_value eq ${a}`),u=((n=(r=(0,hs.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(f=>f._settingdefinitionid_value).filter(Boolean))],d=new Map;if(c.length>0){let f=c.map(h=>`settingdefinitionid eq ${(0,Pi.normalizeGuid)(h,"Setting definition id")}`).join(" or "),m=`/settingdefinitions${(0,Pi.odataQuery)([["$select","settingdefinitionid,uniquename,displayname"],["$filter",f]])}`,p=(0,hs.ensureSuccess)(await e.get(m),e.apiUrl(m));for(let h of((o=(i=p.body)===null||i===void 0?void 0:i.value)!==null&&o!==void 0?o:[]).filter(Boolean))h.settingdefinitionid&&d.set(h.settingdefinitionid.toLowerCase(),h)}return u.map(f=>{var m,p,h,g,b;let w=d.get(((m=f._settingdefinitionid_value)!==null&&m!==void 0?m:"").toLowerCase());return{id:(p=f.appsettingid)!==null&&p!==void 0?p:"",name:(g=(h=w?.uniquename)!==null&&h!==void 0?h:f._settingdefinitionid_value)!==null&&g!==void 0?g:"",value:(b=f.value)!==null&&b!==void 0?b:"",...w?.displayname?{displayName:w.displayname}:{}}})}Dt.readAppSettings=k5;async function xN(e,t,r){var n,i,o;let a=MN("appsettingid,value",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${r}`),l=((i=(n=(0,hs.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||n===void 0?void 0:n.value)!==null&&i!==void 0?i:[]).filter(Boolean)[0];return l?.appsettingid?{id:l.appsettingid,value:(o=l.value)!==null&&o!==void 0?o:""}:void 0}async function BN(e,t,r,n){let i=(0,Pi.normalizeGuid)(t,"App id"),a=(await UN(e,[r])).get(r),s=a?.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,Pi.normalizeGuid)(s,"Setting definition id"),u=await xN(e,i,l);if(u)return FN(e,u,n);let c="/appsettings",d={"[email protected]":`/appmodules(${i})`,"[email protected]":`/settingdefinitions(${l})`,value:n},f,m;try{if(f=await e.post(c,d),f.status>=200&&f.status<300)return"created"}catch(h){m=h}let p;try{p=await xN(e,i,l)}catch{p=void 0}if(p)return FN(e,p,n);throw f&&(0,hs.ensureSuccess)(f,e.apiUrl(c)),m}Dt.setAppSetting=BN;async function FN(e,t,r){if(t.value===r)return"unchanged";let n=`/appsettings(${(0,Pi.normalizeGuid)(t.id,"App setting id")})`;return(0,hs.ensureSuccess)(await e.patch(n,{value:r}),e.apiUrl(n)),"updated"}async function L5(e,t,r){var n;let i=[];for(let[o,a]of Object.entries(r??{}))try{await BN(e,t,o,a)}catch(s){i.push(`App setting '${o}' was not applied: ${(n=s?.message)!==null&&n!==void 0?n:String(s)} The app was created; set it later with setAppSetting().`)}return i}Dt.applyAppSettings=L5});var Ud=v(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});Md.HEADER_NAV_BOOLEAN_RULE=void 0;Md.HEADER_NAV_BOOLEAN_RULE="headerAndNavigationRefresh-must-be-boolean"});var $g=v(ke=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.compileGenPage=ke.legacyEnumsNeeded=ke.createGenPageTypeScriptLoader=ke.acceptGenPageTypeScript=ke.isLoadableGenPageOutput=ke.runtimeTypesImportSpans=ke.GENPAGE_RUNTIME_TYPES_END=ke.GENPAGE_RUNTIME_TYPES_BEGIN=ke.GENPAGE_TYPESCRIPT_VERSION=void 0;var gs=Q();ke.GENPAGE_TYPESCRIPT_VERSION="5.8.3";ke.GENPAGE_RUNTIME_TYPES_BEGIN="// --- BEGIN GENERATED RUNTIME TYPES ---";ke.GENPAGE_RUNTIME_TYPES_END="// --- END GENERATED RUNTIME TYPES ---";var _n="./RuntimeTypes",$5="'\"`",qN=/\s/;function x5(e){return e===10||e===13||e===8232||e===8233}function F5(e,t){let r=[];e.lastIndex=0;for(let n=e.exec(t);n!==null;n=e.exec(t))r.push(n.index);return r}function zN(e){let t=[],r=_n.length;for(let l=e.indexOf(_n);l!==-1;l=e.indexOf(_n,l+1)){let u=l-1;u>=0&&$5.includes(e[u])&&e[u+1+r]===e[u]&&t.push(u)}let n=[];if(t.length===0)return n;let i=-1,o=l=>{if(i<l)for(i=l;i<e.length&&e[i]!=="'"&&e[i]!=='"';)i+=1;return i},a=-1,s=l=>{for(;a+1<t.length&&t[a+1]<=l;)a+=1;return a>=0?t[a]:-1/0};for(let l=e.indexOf("import");l!==-1;){let u=l+1;if(l+6<e.length&&qN.test(e[l+6])){let c=s(o(l+6));if(c>=l+8){let d=c+2+r;for(e[d]===";"&&(d+=1);d<e.length&&qN.test(e[d]);)d+=1;n.push({start:l,end:d}),u=d}}l=e.indexOf("import",u)}return n}ke.runtimeTypesImportSpans=zN;var M5=/\b(?:import\s*['"]|export\s)/;function U5(e){let t=F5(/from\s+['"]/g,e);if(t.length===0)return!1;let r=/\bimport\s/g,n=-1,i=0;for(let o=r.exec(e);o!==null;o=r.exec(e)){let a=o.index+7;if(a>n)for(n=a;n<e.length&&!x5(e.charCodeAt(n));)n+=1;for(;i<t.length&&t[i]<a+1;)i+=1;if(i<t.length&&t[i]<n)return!0}return!1}function B5(e){return e!==void 0&&e!==""&&(M5.test(e)||U5(e))}ke.isLoadableGenPageOutput=B5;var VN=["transpileModule","createSourceFile","createProgram","getParseTreeNode","flattenDiagnosticMessageText","forEachChild","getModifiers","canHaveModifiers","isImportDeclaration","isExportDeclaration","isExportAssignment","isStringLiteral"];function jN(e){var t;let r=s=>s!==null&&(typeof s=="object"||typeof s=="function")?s:void 0,n=r(e);n&&typeof n.transpileModule!="function"&&(n=(t=r(n.default))!==null&&t!==void 0?t:n);let i=n?VN.filter(s=>typeof n?.[s]!="function"):[...VN];if(!n||i.length>0)throw new gs.SdkError("GENPAGE_COMPILER_INVALID",`The TypeScript compiler supplied as MakerSdkOptions.typescript is not the typescript module (missing ${i.join(", ")}). Pass the 'typescript' package's module object, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node', or \u2014 in a bare engine \u2014 globalThis.ts after evaluating typescript@${ke.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js.`);let o=typeof n.version=="string"?n.version:"",a=ke.GENPAGE_TYPESCRIPT_VERSION.split(".").slice(0,2).join(".");if(o.split(".").slice(0,2).join(".")!==a)throw new gs.SdkError("GENPAGE_COMPILER_VERSION",`The TypeScript compiler supplied as MakerSdkOptions.typescript is version '${o||"unknown"}', but generative pages are compiled with ${a}.x \u2014 the version the maker portal itself uses (${ke.GENPAGE_TYPESCRIPT_VERSION}). Another version can emit different JavaScript for the same page. Supply typescript@${ke.GENPAGE_TYPESCRIPT_VERSION}.`);return n}ke.acceptGenPageTypeScript=jN;function q5(e){let t;return()=>{if(!t){if(e===void 0)return Promise.reject(new gs.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`This push must compile a generative page, but no TypeScript compiler was supplied. Pass MakerSdkOptions.typescript \u2014 in Node, loadNodeTypeScript from '@maker-studio/cds-maker-sdk/node'; in a bare engine, globalThis.ts after evaluating typescript@${ke.GENPAGE_TYPESCRIPT_VERSION}'s lib/typescript.js. Nothing was written.`));t=Promise.resolve().then(()=>typeof e=="function"?e():e).then(jN).catch(r=>{throw t=void 0,r instanceof gs.SdkError?r:new gs.SdkError("GENPAGE_COMPILER_UNAVAILABLE",`The TypeScript compiler could not be loaded, so a generative page cannot be compiled (${r instanceof Error?r.message:String(r)}). Nothing was written.`)})}return t}}ke.createGenPageTypeScriptLoader=q5;var HN=e=>`${e.kind}:${e.pos}:${e.end}`;function V5(e,t){return()=>r=>{let n=i=>{let o=e.getParseTreeNode(i);o&&t.add(HN(o)),e.forEachChild(i,n)};return n(r),r}}function Lg(e){return{target:e.ScriptTarget.ES5,module:e.ModuleKind.ES2020,jsx:e.JsxEmit.React}}var G5=2301;function GN(e,t,r){var n;let i=e.transpileModule(t,{compilerOptions:Lg(e),reportDiagnostics:!0,...r?{transformers:{after:[V5(e,r)]}}:{}}),o=((n=i.diagnostics)!==null&&n!==void 0?n:[]).filter(a=>a.category===e.DiagnosticCategory.Error).map(a=>{let s=a.file&&typeof a.start=="number"?a.file.getLineAndCharacterOfPosition(a.start):{line:0,character:0};return{line:s.line+1,column:s.character+1,rule:"genpage-source-syntax",code:a.code,message:e.flattenDiagnosticMessageText(a.messageText,`
+`)}});return{code:i.outputText,diagnostics:o}}var WN=e=>e.startsWith(".")||e.startsWith("/"),Bd={line:1,column:1};function kg(e,t){let r=o=>{let a=t.getLineAndCharacterOfPosition(o.getStart(t));return{line:a.line+1,column:a.character+1}},n=o=>(e.isImportDeclaration(o)||e.isExportDeclaration(o))&&o.moduleSpecifier&&e.isStringLiteral(o.moduleSpecifier)?o.moduleSpecifier.text:void 0,i=o=>t.statements.filter(a=>e.isImportDeclaration(a)&&n(a)===o);return{statement(o,a){let s=t.statements.find(l=>n(l)===o&&(a==="import"?e.isImportDeclaration(l):e.isExportDeclaration(l)));return s?r(s):Bd},element(o,a){var s;for(let l of i(o)){let u=(s=l.importClause)===null||s===void 0?void 0:s.namedBindings,c=u&&e.isNamedImports(u)?u.elements.find(d=>d.name.text===a):void 0;if(c)return r(c)}return this.statement(o,"import")},binding(o){var a,s;for(let l of t.statements)if(e.isImportDeclaration(l)&&l.importClause){let u=l.importClause,c=u.namedBindings,d=((a=u.name)===null||a===void 0?void 0:a.text)===o?u.name:c&&e.isNamespaceImport(c)&&c.name.text===o?c.name:c&&e.isNamedImports(c)?c.elements.find(f=>f.name.text===o):void 0;if(d)return r(d)}else{if((e.isFunctionDeclaration(l)||e.isClassDeclaration(l))&&((s=l.name)===null||s===void 0?void 0:s.text)===o)return r(l.name);if(e.isVariableStatement(l)){let u=l.declarationList.declarations.find(c=>e.isIdentifier(c.name)&&c.name.text===o);if(u)return r(u.name)}}return Bd}}}function W5(e,t,r,n){var i,o;let a=[],s=kg(e,r),l=(p,h,g)=>{a.push({...p,rule:h,code:0,message:g})},u=(p,h)=>{var g;return(e.canHaveModifiers(p)?(g=e.getModifiers(p))!==null&&g!==void 0?g:[]:[]).some(b=>b.kind===h)},c=(p,h)=>l(p,"genpage-relative-import",`'${h}' cannot resolve at runtime: the page is loaded as a single module from a blob URL, so the only relative import it may have is './RuntimeTypes'`),d="genpage-runtime-types-import-form",f=!1,m=new Set;for(let p of t.statements){if(e.isExportAssignment(p)){f=f||!p.isExportEquals;continue}if(e.isFunctionDeclaration(p)||e.isClassDeclaration(p)){u(p,e.SyntaxKind.ExportKeyword)&&u(p,e.SyntaxKind.DefaultKeyword)&&(f=!0),p.name&&m.add(p.name.text);continue}if(e.isExportDeclaration(p)){let w=p.exportClause;w&&e.isNamedExports(w)&&w.elements.some(S=>S.name.text==="default")&&(f=!0);let C=p.moduleSpecifier&&e.isStringLiteral(p.moduleSpecifier)?p.moduleSpecifier.text:void 0;C===_n?l(s.statement(C,"export"),d,"a page cannot re-export from './RuntimeTypes': that module does not exist at runtime"):C!==void 0&&WN(C)&&c(s.statement(C,"export"),C);continue}if(!e.isImportDeclaration(p)||!e.isStringLiteral(p.moduleSpecifier))continue;let h=p.moduleSpecifier.text,g=p.importClause;if(h!==_n){WN(h)&&c(s.statement(h,"import"),h),g?.name&&m.add(g.name.text);let w=g?.namedBindings;w&&e.isNamespaceImport(w)?m.add(w.name.text):w&&e.isNamedImports(w)&&w.elements.forEach(C=>m.add(C.name.text));continue}if(!g){l(s.statement(h,"import"),d,"a side-effect import of './RuntimeTypes' cannot resolve at runtime; import the names it declares");continue}g.name&&l(s.binding(g.name.text),d,"'./RuntimeTypes' has no default export at runtime; import its names");let b=g.namedBindings;if(b&&e.isNamespaceImport(b))l(s.binding(b.name.text),d,"a namespace import of './RuntimeTypes' is undefined at runtime \u2014 its enums are inlined under their own names; import the names instead");else if(b&&e.isNamedImports(b))for(let w of b.elements){let C=w.name.text,S=(o=(i=w.propertyName)===null||i===void 0?void 0:i.text)!==null&&o!==void 0?o:C,O=s.element(h,C);S!==C?l(O,d,`'${S} as ${C}' would be undefined at runtime: the enum is inlined as '${S}', so import it under its own name`):n?.text?n.enums.has(C)||l(O,"genpage-runtime-types-unresolved",`'${C}' is imported from './RuntimeTypes' as a VALUE, but the runtime types define no value of that name \u2014 only the choice enums of the page's data sources are values. Import a type with 'import type'.`):l(O,"genpage-runtime-types-unresolved",`'${C}' is imported from './RuntimeTypes' as a VALUE, but the page has no data sources, so no runtime types are inlined and the import reaches the runtime, which cannot load it. Import it with 'import type', or add the table it belongs to to dataSources.`)}}if(f||l(Bd,"genpage-no-default-export","the page has no default export \u2014 the runtime renders the module's default export as the page component"),n?.text)for(let p of m)n.enums.has(p)&&l(s.binding(p),"genpage-runtime-types-collision",`'${p}' is declared at the page's module scope and is also one of its inlined choice enums, so the compiled page would declare it twice and fail to load. Rename the page's binding, or import the enum from './RuntimeTypes'.`);return a}function KN(e,t,r){let n,i=()=>{if(!n){let p={getSourceFile:g=>g===t.fileName?t:void 0,getDefaultLibFileName:()=>"lib.d.ts",writeFile:()=>{},getCurrentDirectory:()=>"",getCanonicalFileName:g=>g,useCaseSensitiveFileNames:()=>!0,getNewLine:()=>`
+`,fileExists:g=>g===t.fileName,readFile:()=>{},directoryExists:()=>!0,getDirectories:()=>[]},h={...r,noLib:!0,noResolve:!0,allowJs:!0,types:[],alwaysStrict:!0,moduleDetection:e.ModuleDetectionKind.Force};n=e.createProgram({rootNames:[t.fileName],options:h,host:p})}return n},o,a=()=>(o||(o=i().getTypeChecker()),o),s,l=()=>{if(!s){s=new Map;try{for(let p of i().getSemanticDiagnostics(t))p.code===G5&&typeof p.start=="number"&&s.set(p.start,e.flattenDiagnosticMessageText(p.messageText," "))}catch{}}return s},u=p=>e.isImportSpecifier(p)?p.parent.parent.parent:e.isImportClause(p)?p.parent:e.isNamespaceImport(p)?p.parent.parent:void 0,c=p=>{let h=u(p);return h!==void 0&&e.isImportDeclaration(h)&&e.isStringLiteral(h.moduleSpecifier)&&h.moduleSpecifier.text===_n},d=p=>{var h;for(let g=p;g;g=g.parent)if(e.canHaveModifiers(g)&&((h=e.getModifiers(g))!==null&&h!==void 0?h:[]).some(b=>b.kind===e.SyntaxKind.DeclareKeyword))return!0;return!1},f=p=>d(p)||e.isImportEqualsDeclaration(p)&&(p.isTypeOnly||e.isExternalModuleReference(p.moduleReference))||e.isImportClause(p)&&p.isTypeOnly||e.isNamespaceImport(p)&&p.parent.isTypeOnly||e.isImportSpecifier(p)&&(p.isTypeOnly||p.parent.parent.isTypeOnly),m=p=>{var h;return((h=p?.declarations)!==null&&h!==void 0?h:[]).some(g=>!c(g)&&!f(g))};return{pageOwns:p=>{let h=p.parent;return m(e.isShorthandPropertyAssignment(h)&&h.name===p?a().getShorthandAssignmentValueSymbol(h):a().getSymbolAtLocation(p))},pageOwnsLocalExport:p=>m(a().getExportSpecifierLocalTargetSymbol(p)),initializerShadow:p=>l().get(p.getStart(t))}}function z5(e,t,r,n){let i=[],o=r?.enums;if(!o||o.size===0)return i;let a=(u,c,d)=>{let f=t.getLineAndCharacterOfPosition(u.getStart(t));i.push({line:f.line+1,column:f.character+1,rule:c,code:0,message:d})},s=KN(e,t,Lg(e)),l=u=>{let c,d;if(e.isPropertyAccessExpression(u)&&e.isIdentifier(u.expression))c=u.expression,d=u.name.text;else if(e.isElementAccessExpression(u)&&e.isIdentifier(u.expression)){let m=u.argumentExpression;e.isStringLiteral(m)||e.isNoSubstitutionTemplateLiteral(m)?(c=u.expression,d=m.text):e.isNumericLiteral(m)&&(c=u.expression,d=String(Number(m.text)))}let f=c&&o.has(c.text)&&n.has(HN(u))&&!s.pageOwns(c)?o.get(c.text):void 0;if(c&&f&&d!==void 0){let m=e.isPropertyAccessExpression(u)?`${f.name}.${d}`:`${f.name}[${JSON.stringify(d)}]`,p=Object.prototype.hasOwnProperty.call(f.runtime,d)?f.runtime[d]:void 0,h=f.labels.get(d),g;p===void 0?g={rule:"genpage-enum-member-unknown",message:`${m} is undefined at runtime: '${f.name}' has no member '${d}' in this environment's metadata \u2014 members are the column's choice labels, so a renamed or differently localized label no longer matches. Known: ${[...f.labels.keys()].map(w=>`'${w}'`).join(", ")}`}:h&&typeof p!="number"?g={rule:"genpage-enum-member-clobbered",message:`${m} is the string '${String(p)}' at runtime, not a choice value: the label '${d}' looks like a number, and another option's reverse mapping overwrites it. Use the choice's numeric value instead.`}:h&&h.length>1&&(g={rule:"genpage-enum-member-ambiguous",message:`${m} labels more than one choice (${h.join(", ")}); the compiled value is whichever option comes last. Use the choice's numeric value instead.`});let b=g?s.initializerShadow(c):void 0;g&&b!==void 0?a(u,"genpage-enum-initializer-shadowed",`${m} does not read the choice enum at runtime. ${b} (TS2301): the ES5 emit moves an instance field's initializer into the constructor, where that parameter or local shadows '${c.text}'. If you meant the constructor's '${c.text}', move the assignment into the constructor body, or make it a parameter property and read \`this.${c.text}\`. If you meant the choice enum, rename the constructor's parameter or local.`):g&&a(u,g.rule,g.message)}e.forEachChild(u,l)};return l(t),i}function j5(e,t){return e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!1,e.ScriptKind.JS).statements.some(n=>(e.isImportDeclaration(n)||e.isExportDeclaration(n))&&n.moduleSpecifier!==void 0&&e.isStringLiteral(n.moduleSpecifier)&&n.moduleSpecifier.text===_n)}function JN(e,t){return t.statements.filter(r=>e.isImportDeclaration(r)&&e.isStringLiteral(r.moduleSpecifier)&&r.moduleSpecifier.text===_n).map(r=>r.getStart(t))}function H5(e,t){let r=e.createSourceFile("page.js",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),n=JN(e,r),i=new Set(n),o,a="",s=0;for(let l of zN(t))!o&&!i.has(l.start)&&(o={swallows:n.some(u=>u>l.start&&u<l.end),text:t.slice(l.start,l.end).trimEnd()}),a+=t.slice(s,l.start),s=l.end;return a+=t.slice(s),{code:a,inexact:o}}function K5(e,t,r){let n=new Set(JN(e,t));for(let i=t.text.indexOf(r);i!==-1;i=t.text.indexOf(r,i+1))if(!n.has(i)){let o=t.getLineAndCharacterOfPosition(i);return{line:o.line+1,column:o.character+1}}return Bd}function YN(e,t,r){if(!r||r.size===0)return[];let n=KN(e,t,{...Lg(e),target:e.ScriptTarget.ESNext}),i=new Set,o=s=>{var l,u;let c=s.parent;if(e.isImportSpecifier(c)){let d=c.parent.parent.parent;e.isImportDeclaration(d)&&e.isStringLiteral(d.moduleSpecifier)&&d.moduleSpecifier.text===_n&&((l=c.propertyName)!==null&&l!==void 0?l:c.name)===s&&i.add(s.text);return}if(e.isExportSpecifier(c)){!(c.parent.parent.moduleSpecifier!==void 0)&&((u=c.propertyName)!==null&&u!==void 0?u:c.name)===s&&!n.pageOwnsLocalExport(c)&&i.add(s.text);return}e.isPropertyAccessExpression(c)&&c.name===s||e.isBindingElement(c)&&c.propertyName===s||e.isLabeledStatement(c)||e.isBreakOrContinueStatement(c)||n.pageOwns(s)||i.add(s.text)},a=s=>{e.isIdentifier(s)&&r.has(s.text)&&o(s),e.forEachChild(s,a)};return a(t),[...r.keys()].filter(s=>i.has(s))}ke.legacyEnumsNeeded=YN;function J5(e,t,r){if(!e?.text||!t||r.length===0)return e;let n=new Map(e.enums),i=e.text;for(let o of r){let a=t.get(o);a&&(i+=a.declaration,n.set(o,a.model))}return{text:i,enums:n}}function Y5(e,t,r,n){var i;let o=new Set,a=GN(e,t,o);if(a.diagnostics.length>0)return a;let s=e.createSourceFile("page.tsx",t,e.ScriptTarget.ES2020,!0,e.ScriptKind.TSX),l=e.createSourceFile("page.js",a.code,e.ScriptTarget.ES2020,!0,e.ScriptKind.JS),u=J5(r,n,YN(e,l,n)),c=[...W5(e,l,s,u),...z5(e,s,u,o)];if(!u?.text)return{code:a.code,diagnostics:c};let d=GN(e,u.text);if(d.diagnostics.length>0)throw new gs.SdkError("GENPAGE_RUNTIME_TYPES_INVALID",`The generated runtime types do not compile (${d.diagnostics.map(h=>`${h.line}:${h.column} ${h.message}`).join("; ")}). This is an SDK defect: the page was not written.`);let f=H5(e,a.code),m=f.code;if(c.length===0&&(!((i=f.inexact)===null||i===void 0)&&i.swallows))c.push({...kg(e,s).statement(_n,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"the maker portal's patch would remove more than this './RuntimeTypes' import: a comment or other text before it contains the word 'import', and the pattern would delete from there \u2014 taking the code in between with it. Reword or move that text."});else if(c.length===0&&f.inexact){let{text:h}=f.inexact;c.push({...K5(e,s,h),rule:"genpage-runtime-types-import-form",code:0,message:`the maker portal's patch would delete \`${h.length>80?`${h.slice(0,79)}\u2026`:h}\` from text that only looks like an import of './RuntimeTypes' \u2014 in a string, a template or a comment \u2014 so the page it ships would differ from this source. Reword that text so it no longer reads as such an import.`})}else c.length===0&&j5(e,m)&&c.push({...kg(e,s).statement(_n,"import"),rule:"genpage-runtime-types-import-form",code:0,message:"this './RuntimeTypes' import is not one the maker portal's patch can remove (a comment holding a quote inside it stops the pattern), so it would reach the runtime, which cannot load it. Write it on one line, as 'import { name } from './RuntimeTypes';'."});return{code:[ke.GENPAGE_RUNTIME_TYPES_BEGIN,d.code,ke.GENPAGE_RUNTIME_TYPES_END,m].join(`
-`),diagnostics:c}}Le.compileGenPage=U8});var Dg=v(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.isFailureAfterPrimaryWrite=ps.failedAfterPrimaryWrite=void 0;var UN=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function B8(e){return typeof e=="object"&&e!==null&&(e[UN]=!0),e}ps.failedAfterPrimaryWrite=B8;function q8(e){return typeof e=="object"&&e!==null&&e[UN]===!0}ps.isFailureAfterPrimaryWrite=q8});var Ud=v(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.appApi=Qn.deleteAppResolvingOnce=Qn.mainFormSetShapeIssues=Qn.unpublishedAppModulesQuery=void 0;var ms=Lt(),V8=$g(),G8=dg(),BN=Jr(),W8=Od(),z8=Dg(),he=ye(),Ne=se(),Og=dt(),e_=Wl(),Se=Q(),j8=(0,Ne.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),Pg="appmoduleid,name,uniquename,description,aiappdescription";function xd(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ne.odataQuery)([["$select",e],["$filter",t],["$top",r]])}Qn.unpublishedAppModulesQuery=xd;function Rg(e,t){return xd(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function Fd(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ne.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function nu(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function H8(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Md(e,t){if(typeof e!="string")return!1;try{return(0,Ne.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function Zo(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function K8(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function t_(e,t){var r,n;let i=u=>{throw new Se.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 o=`/sitemaps${(0,Ne.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,Ne.odataLiteral)(t)}'`],["$top",1]])}`,a;try{a=await e.get(o)}catch(u){return i(`failed (${u.message})`)}if(a.status<200||a.status>=300)return i(`returned HTTP ${a.status}`);let s=(r=a.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 J8(e){let t=s=>{var l,u,c;return(c=(u=(l=s.body)===null||l===void 0?void 0:l.value)===null||u===void 0?void 0:u[0])===null||c===void 0?void 0:c.webresourceid},r=s=>`/webresourceset${(0,Ne.odataQuery)([["$select","webresourceid"],["$top",1],["$filter",s]])}`,n="(webresourcetype eq 5 or webresourcetype eq 6 or webresourcetype eq 7 or webresourcetype eq 10 or webresourcetype eq 11)",i=t(await e.get(r("webresourcetype eq 5 and ismanaged eq false and contains(name,'icon')")));if(i)return{id:i,managed:!1};let o=t(await e.get(r(`${n} and ismanaged eq false`)));if(o)return{id:o,managed:!1};let a=t(await e.get(r(n)));return a?{id:a,managed:!0}:void 0}var qN="627090ff-40a3-4053-8790-584edc5be201";function Oi(e){return e instanceof Error?e.message:String(e)}async function Y8(e,t){var r;try{let n=`/roles${(0,Ne.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${qN}`]])}`,i=await(0,ms.collectPages)(e,n,"the System Administrator role"),o=i.find(l=>typeof l.roleid=="string"&&typeof l._parentrootroleid_value=="string"&&l.roleid.toLowerCase()===l._parentrootroleid_value.toLowerCase()),a=(r=o??i.find(l=>typeof l.roleid=="string"))===null||r===void 0?void 0:r.roleid;if(!a)return`App roles: no 'System Administrator' role (template ${qN}) was found in this environment, so the SDK did not associate one with the app \u2014 it may not be visible or playable until a role is granted access to it.`;let s=`/appmodules(${t})/appmoduleroles_association/$ref`;return(0,he.ensureSuccess)(await e.post(s,{"@odata.id":e.apiUrl(`/roles(${a})`)}),e.apiUrl(s)),null}catch(n){return`App roles: could not associate the 'System Administrator' role with the app (${Oi(n)}); it will not be visible or playable until a role is granted access to it.`}}async function Q8(e,t,r=!0){let n=[];async function i(l,u,c){try{return(await(0,ms.collectPages)(e,l,`app assets (${c} for '${t}')`)).map(f=>String(f[u])).filter(f=>f&&f!=="undefined")}catch(d){return n.push(`App components: could not enumerate ${c} for table '${t}' (${Oi(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([r?i(`/systemforms${(0,Ne.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,Ne.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,Ne.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,Ne.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,Ne.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,Ne.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:n}}var VN=new WeakMap;async function X8(e,t){let r=VN.get(e);r||(r=new Map,VN.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await Z8(e,t);return i&&r.set(t,i),i}async function GN(e,t,r){let n=new Array(e.length),i=0;async function o(){for(let a=i;a<e.length;a=i)i=a+1,n[a]=await r(e[a])}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),n}async function Z8(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Ne.odataPathLiteral)(t)}')${(0,Ne.odataQuery)([["$select","MetadataId,EntitySetName"]])}`,n=await e.get(r);if(n.status>=200&&n.status<300){let i=n.body;if(i?.MetadataId&&i.EntitySetName)return{logicalName:t,metadataId:i.MetadataId,entitySetName:i.EntitySetName}}}async function WN(e,t,r){let n=[],i=Zo(t.entities),o=4,a=await GN(i,o,g=>X8(e,g)),s=i.filter((g,b)=>!a[b]);if(s.length>0)throw new Se.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${s.map(g=>`'${g}'`).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 l=a.filter(g=>!!g);for(let g of l)n.push({"@odata.id":`${g.entitySetName}(${g.metadataId})`});for(let g of Zo(t.components.forms))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of Zo(t.components.views))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of Zo(t.components.charts))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of Zo(t.components.dashboards))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});let u=new Set(t.components.forms),c=new Set(t.components.views),d=new Set(t.components.charts),f=new Map((r??[]).map(g=>[g.table,g])),m=await GN(i,o,g=>Q8(e,g,!f.has(g.toLowerCase()))),p=m.flatMap(g=>g.warnings),h=new Set([...Zo(t.components.forms),...Zo(t.components.dashboards)].map(Vr));return m.forEach((g,b)=>{let w=f.get(i[b].toLowerCase());if(w)for(let E of w.allowed)h.has(E)||(h.add(E),u.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:E}));else for(let E of g.forms)u.has(E)||(u.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:E}));for(let E of g.views)c.has(E)||(c.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:E}));for(let E of g.charts)d.has(E)||(d.add(E),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:E}))}),{components:n,tables:l,warnings:p}}function Vr(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var kg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Lg="/components/mainFormsByTable",zN=50;function r_(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function n_(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:Lg,rule:"app-main-form-set-shape",message:"must be an object mapping a table logical name to its Main form ids"}];let r=[],n=new Set(t.map(o=>o.toLowerCase())),i=new Set;for(let[o,a]of Object.entries(e)){let s=o.toLowerCase(),l=`${Lg}/${r_(o)}`;if(i.has(s)){r.push({pointer:l,rule:"app-main-form-set-shape",message:`table '${o}' is listed twice (logical names compare case-insensitively)`});continue}if(i.add(s),n.has(s)||r.push({pointer:l,rule:"app-main-form-set-table",message:`'${o}' is not a table this app's sitemap navigates to (Entity subareas: ${[...n].join(", ")||"none"})`}),!Array.isArray(a)){r.push({pointer:l,rule:"app-main-form-set-shape",message:"must be an array of Main form ids"});continue}if(a.length===0){r.push({pointer:l,rule:"app-main-form-set-empty",message:`an empty list is refused: an app with no Main form of '${o}' offers every form of the table`});continue}let u=new Set;a.forEach((c,d)=>{let f=`${l}/${d}`;typeof c!="string"||!kg.test(Vr(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):u.has(Vr(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):u.add(Vr(c))})}return r}Qn.mainFormSetShapeIssues=n_;async function jN(e,t,r){let n=t.components.mainFormsByTable;if(n===void 0)return;let i=n_(n,t.entities);if(i.length>0)throw new Se.ValidationError("app",r,i);if(Object.keys(n).length===0)return;let o=[],a=[];for(let[l,u]of Object.entries(n)){let c=l.toLowerCase(),d=await(0,ms.collectPages)(e,`/systemforms${(0,Ne.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,Ne.odataLiteral)(c)}' and type eq 2`]])}`,`app Main-form allow-list ('${c}')`),f=new Set,m=new Set;for(let h of d)typeof h.formid=="string"&&(f.add(Vr(h.formid)),Number(h.formactivationstate)===1&&m.add(Vr(h.formid)));let p=u.map(Vr);p.forEach((h,g)=>{let b=`${Lg}/${r_(l)}/${g}`;f.has(h)?m.has(h)||o.push({pointer:b,rule:"app-main-form-set-inactive",message:`Main form '${u[g]}' of '${c}' is inactive, so no app can offer it`}):o.push({pointer:b,rule:"app-main-form-set-not-main-form",message:`'${u[g]}' is not a Main form of '${c}'`})}),a.push({table:c,allowed:p,catalog:f})}let s=[...t.components.forms.map((l,u)=>({id:l,pointer:`/components/forms/${u}`})),...t.components.dashboards.map((l,u)=>({id:l,pointer:`/components/dashboards/${u}`}))];for(let l of s){let u=Vr(l.id);for(let c of a)c.catalog.has(u)&&!c.allowed.includes(u)&&o.push({pointer:l.pointer,rule:"app-main-form-set-conflict",message:`'${l.id}' is a Main form of '${c.table}' outside its allow-list, and this pin (an explicit form or dashboard, or a sitemap DashBoard subarea) would add it. Remove the pin, or list the form.`})}if(o.length>0)throw new Se.ValidationError("app",r,o);return a}async function eW(e,t){var r,n;let i=u=>({kind:"inconclusive",reason:u}),o=await e.get(xd("appmoduleid,appmoduleidunique,componentstate",`appmoduleid eq ${t}`));if(o.status<200||o.status>=300)return i(`reading the app returned HTTP ${o.status}`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a)||a.length===0)return i("reading the app returned no row");let s=a.length===1?a:a.filter(u=>Number(u?.componentstate)===1),l=s.length===1?(n=s[0])===null||n===void 0?void 0:n.appmoduleidunique:"";return typeof l!="string"||!kg.test(Vr(l))?i(`no single current layer among ${a.length} app row(s)`):{kind:"read",unique:Vr(l)}}function kd(e,t){let r;return()=>r??(r=eW(e,t))}async function i_(e,t,r,n=kd(e,t)){let i=m=>({kind:"inconclusive",reason:m}),o=await n();if(o.kind==="inconclusive")return o;let a=o.unique,s;try{let m=await(0,ms.collectPages)(e,`/appmodulecomponents${(0,Ne.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${Vr(a)} and componenttype eq 60`]])}`,`app Main-form membership ('${t}')`);if(m.some(p=>typeof p.objectid!="string"))return i("a form component carries no object id");s=m.map(p=>Vr(String(p.objectid)))}catch(m){return i(`reading its form components failed (${Oi(m)})`)}let l=new Map,u=[];for(let m of new Set(s)){let p=r.find(h=>h.catalog.has(m));p?l.set(m,p.table):u.push(m)}if(u.some(m=>!kg.test(m)))return i("a form component carries an object id that is not a GUID");let c=new Set(r.map(m=>m.table)),d=new Set;for(let m=0;m<u.length;m+=zN){let p=u.slice(m,m+zN);try{let h=await(0,ms.collectPages)(e,`/systemforms${(0,Ne.odataQuery)([["$select","formid,type,objecttypecode"],["$filter",p.map(g=>`formid eq ${g}`).join(" or ")]])}`,`app Main-form membership ('${t}': classifying components)`);for(let g of h){if(typeof g.formid!="string"||typeof g.type!="number"||g.type===2&&(typeof g.objecttypecode!="string"||g.objecttypecode===""))continue;let b=Vr(g.formid);d.add(b);let w=g.type===2?String(g.objecttypecode).toLowerCase():"";c.has(w)&&l.set(b,w)}}catch(h){return i(`classifying its form components failed (${Oi(h)})`)}}let f=u.filter(m=>!d.has(m));return f.length>0?i(`form component(s) ${f.join(", ")} could not be classified`):{kind:"read",tables:r.map(m=>{let p=[...l].filter(([,h])=>h===m.table).map(([h])=>h);return{table:m.table,members:p,extras:p.filter(h=>!m.allowed.includes(h)),missing:m.allowed.filter(h=>!p.includes(h))}})}}async function tW(e,t,r,n){let i=await i_(e,t,r,n);if(i.kind==="inconclusive")throw new Se.SdkError("APP_MAIN_FORM_SET_UNVERIFIED",`App '${t}': its Main-form allow-list was written but could not be verified \u2014 ${i.reason}.`);let o=i.tables.filter(a=>a.extras.length>0||a.missing.length>0);if(o.length>0)throw new Se.SdkError("APP_MAIN_FORM_SET_NOT_APPLIED",`App '${t}': its Main forms do not match the allow-list after the write \u2014 ${o.map(a=>`'${a.table}': unexpected [${a.extras.join(", ")}], missing [${a.missing.join(", ")}]`).join("; ")}.`)}async function rW(e,t,r,n){let i;try{i=await i_(e,t,r,n)}catch(a){i={kind:"inconclusive",reason:Oi(a)}}if(i.kind==="inconclusive")return[`Main-form membership of app '${t}' could not be verified (${i.reason}).`];let o=[];for(let a of i.tables)a.extras.length>0&&o.push(`Main-form components outside the allow-list remain for table '${a.table}': [${a.extras.join(", ")}]. This option controls additions only; it does not remove existing components. Runtime form availability has not been verified.`),a.missing.length>0&&o.push(`Allow-listed Main forms are not in app '${t}' after the push for table '${a.table}': [${a.missing.join(", ")}]; re-push to retry.`);return o}async function HN(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,he.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}async function KN(e,t,r,n=kd(e,t)){var i;if(r.length===0)return;let o=await n();if(o.kind==="inconclusive")throw new Se.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 ${o.reason}. Re-push to retry.`);let a=`/appmodulecomponents${(0,Ne.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${o.unique} and componenttype eq 1`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)throw new Se.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 reading them back returned HTTP ${s.status}. Re-push to retry.`);let l=(i=s.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(l))throw new Se.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 u=new Set(l.map(d=>d.objectid).filter(d=>typeof d=="string").map(d=>d.toLowerCase())),c=r.filter(d=>!u.has(d.metadataId.toLowerCase()));if(c.length>0)throw new Se.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${c.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${c.map(d=>`'${d.logicalName}' (expected objectid ${d.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function nW(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`,o;try{o=await oW(e,r.sitemapId,r.sitemapNameUnique)}catch(l){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${Oi(l)})`}}let a=o==="foreign",s=l=>l.kind==="deleted"?{outcome:"removed",foreignSitemap:a}:l.kind==="refused"?{outcome:"kept",foreignSitemap:a,reason:`its delete was refused (${Oi(l.error)})`}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${Oi(l.error)})`};try{if(o==="absent"||o==="foreign"){if(!r.serverRefusedSitemap)return{outcome:"kept",foreignSitemap:a,reason:"the sitemap write's outcome was never observed, so its row may still appear"};let l=await(0,he.resendAppSearchIndexRace)(()=>e.delete(n));return s(l.status===404?{kind:"deleted"}:a_(l,e.apiUrl(n)))}return e.supportsAtomicBatch?r.sitemapWriteToken?s(await s_(e,[{path:n},{path:i,etag:r.sitemapWriteToken}])):{outcome:"kept",reason:"the sitemap write returned no token of its own, and deleting the row without one could destroy another writer's change"}:{outcome:"kept",reason:"the HttpClient cannot send an atomic change set (no `postRaw`), and deleting the two rows one at a time could strand the sitemap"}}catch(l){return s({kind:"unknown",error:l})}}function iW(e,t,r){if(!(e instanceof Error))return e;let n=t.foreignSitemap?` Sitemap id '${r.sitemapId}' already belongs to ANOTHER app's sitemap, which was left untouched and must not be deleted: supply a sitemapId no other app uses, or omit it so one is minted.`:"";if(t.outcome==="removed")return e.message+=` The partial app this create wrote was removed.${n}`,e;let i=t.foreignSitemap?`appmodule '${r.appId}' (unique name '${r.uniqueName}')`:`appmodule '${r.appId}' (unique name '${r.uniqueName}') and, if it was written, sitemap '${r.sitemapId}'`,a=`a create with that unique name is refused \u2014 remove it in the maker portal, or, once you have confirmed the rows are this create's own, with ${t.foreignSitemap?`deleteRecord('appmodule', '${r.appId}')`:`deleteRecord('appmodule', '${r.appId}') and deleteRecord('sitemap', '${r.sitemapId}')`}.`;return e.message+=t.outcome==="kept"?` The partial app this create wrote was KEPT, because ${t.reason}: ${i}. While it exists, ${a}`:` Whether the partial app this create wrote was removed could not be confirmed, because ${t.reason}. Check for ${i}: while any of it exists, ${a}`,e.message+=n,e}async function oW(e,t,r){var n,i,o;let a=Fd(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);return l.length===0?"absent":String((o=(i=l[0])===null||i===void 0?void 0:i.sitemapnameunique)!==null&&o!==void 0?o:"")===r?"ours":"foreign"}async function aW(e,t){var r;let n;try{n=await e.get(xd("appmoduleid,uniquename,componentstate",`appmoduleid eq ${t}`))}catch(s){return{kind:"unsettled",why:`its unpublished read failed (${s.message})`}}if(n.status<200||n.status>=300)return{kind:"unsettled",why:`its unpublished read returned HTTP ${n.status}`};let i=(r=n.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(i)||i.length!==1)return{kind:"unsettled",why:`its unpublished read returned ${Array.isArray(i)?i.length:"no"} row(s), not exactly one`};let o=i[0],a=o?.uniquename;return!Md(o?.appmoduleid,t)||o?.componentstate!==1||typeof a!="string"||!a?{kind:"unsettled",why:"its unpublished row is not this app as a never-published draft"}:{kind:"draft",uniquename:a}}async function o_(e,t){var r;let n=(0,Ne.normalizeGuid)(t,"id"),i=b=>{throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${b} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`)},o=`/appmodules(${n})${j8}`,a;try{a=await e.get(o)}catch(b){return i(`reading the app failed (${b.message}).`)}let s,l=!1;if(a.status===404){let b=await aW(e,n);if(b.kind!=="draft")return i(`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; ${b.why}.`);s=b.uniquename,l=!0}else{if(a.status<200||a.status>=300)return i(`reading the app returned HTTP ${a.status}.`);s=(r=a.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 u=l?{draft:!0}:{appEtag:(0,he.readEtag)(a)},c=await t_(e,s);if(!c)return{uniquename:s,...u};let d=(0,Ne.normalizeGuid)(c,"sitemapId"),f=await $d(e,d),m=Fd(d,"sitemapid,sitemapnameunique,sitemapxml"),p;try{p=await e.get(m)}catch(b){return i(`reading sitemap '${d}' failed (${b.message}).`)}if(p.status<200||p.status>=300)return i(`reading sitemap '${d}' returned HTTP ${p.status}.`);let h=nu(p);if(!h)return i(`sitemap '${d}' was not returned by the unpublished-aware read.`);if(h.sitemapnameunique!==s)return i(`sitemap '${d}' now carries sitemapnameunique '${String(h.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);if(!Md(h.sitemapid,d))return i(`sitemap '${d}' was read back as a row carrying sitemapid '${String(h.sitemapid)}'.`);let g=h.sitemapxml;return typeof g!="string"?i(`sitemap '${d}' returned no sitemapxml.`):{sitemapId:d,uniquename:s,sitemapXml:g,...u,sitemapEtag:f}}async function sW(e,t,r){let n=(0,Ne.normalizeGuid)(t,"id"),i=await o_(e,n);await r?.(i.sitemapXml),await u_(e,n,i)}Qn.deleteAppResolvingOnce=sW;async function lW(e,t){let r=await s_(e,t);if(r.kind!=="deleted")throw r.error}function a_(e,t){try{return(0,he.ensureSuccess)(e,t),{kind:"deleted"}}catch(r){return l_(e.status)?{kind:"refused",error:r}:{kind:"unknown",error:r}}}function uW(e,t){var r;if(e.status!==400&&(e.status<200||e.status>=300))return!1;let n=(r=(0,e_.parseChangeSetParts)(e.body,t))===null||r===void 0?void 0:r.filter(i=>i.status<200||i.status>=300);return n!==void 0&&n.length>0&&n.every(i=>i.status===400&&(0,he.namesAppSearchIndexRace)(i.text))}async function s_(e,t){let r=`batch_${(0,Og.newId)()}`,n=`changeset_${(0,Og.newId)()}`,i=t.map((m,p)=>[`--${n}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${p+1}`,"",`DELETE ${e.apiUrl(m.path)} HTTP/1.1`,...m.etag?[`If-Match: ${m.etag}`]:[],""].join(`\r
-`)),o=[`--${r}`,`Content-Type: multipart/mixed;boundary=${n}`,"",...i,`--${n}--`,`--${r}--`,""].join(`\r
-`),a=e.apiUrl("/$batch"),s=i.map((m,p)=>String(p+1)),l;try{l=await(0,he.resendWhile)(m=>uW(m,s),()=>e.postBatch(o,r),he.DEADLOCK_BACKOFF_MS)}catch(m){return{kind:"unknown",error:m}}let u=a_(l,a);if(u.kind!=="deleted")return u;let c=`app '${t[0].path}'`;if(typeof l.body!="string"||l.body.length===0)return{kind:"unknown",error:new Se.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`)};let d=(0,e_.parseChangeSetStatuses)(l.body,s);if(d===void 0)return{kind:"unknown",error:new Se.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let f=d.find(m=>m<200||m>=300);return f!==void 0?{kind:"refused",error:new Se.ConnectionError(a,f,`atomic delete of ${c} was rolled back: the change set reported HTTP ${f}`)}:d.length!==i.length?{kind:"unknown",error:new Se.ConnectionError(a,l.status,`atomic delete of ${c} cannot be confirmed: the $batch response reported ${d.length} operation result(s), expected exactly ${i.length}`)}:{kind:"deleted"}}async function $d(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,he.readEtag)(r)}catch{return null}}async function JN(e,t){let r=`/appmodules(${t})?$select=appmoduleid`,n=await e.get(r);if(n.status!==404)return(0,he.ensureSuccess)(n,e.apiUrl(r)),(0,he.readEtag)(n)}function YN(e){return{sitemapxml:e.sitemapxml,...e.sitemapname!==void 0?{sitemapname:e.sitemapname}:{}}}async function Ig(e,t,r,n){if(!n)return null;let i=await $d(e,t);if(!i)return null;try{let o=await e.get(Fd(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=nu(o);return!a||!Md(a.sitemapid,t)||a.sitemapnameunique!==n||a.sitemapxml!==r.sitemapxml||r.sitemapname!==void 0&&a.sitemapname!==r.sitemapname?null:i}catch{return null}}function l_(e){return e>=400&&e<500&&e!==408&&e!==429}function QN(e,t,r){if(!e)throw new Se.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 u_(e,t,r){let n=`/appmodules(${t})`,i=r.draft?void 0:QN(r.appEtag,t,"app");if(!r.sitemapId){if(r.draft){(0,he.ensureSuccess)(await(0,he.resendAppSearchIndexRace)(()=>e.delete(n)),e.apiUrl(n));return}await cW(e,n,i);return}if(!e.supportsAtomicBatch)throw new Se.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 lW(e,[{path:n,etag:i},{path:`/sitemaps(${r.sitemapId})`,etag:QN(r.sitemapEtag,t,"sitemap")}])}async function cW(e,t,r){(0,he.ensureSuccess)(await(0,he.resendAppSearchIndexRace)(()=>e.delete(t,{headers:{"If-Match":r}})),e.apiUrl(t))}async function XN(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,V8.collectGenPageIds)(t))]}catch(i){throw new Se.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 (${Oi(i)}).`)}if(r.length===0)return;let n=await(0,G8.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new Se.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${n.map(i=>`'${i}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function dW(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")}function fW(e,t){var r;let n=[["name",e.appModuleName],["description",e.appModuleDescription],["aiappdescription",e.appModuleAiDescription]],i={};for(let[o,a]of n)a!==void 0&&(t!==void 0&&String((r=t[o])!==null&&r!==void 0?r:"")===String(a??"")||(i[o]=a));return i}async function ZN(e,t,r){var n;let i=(0,Ne.normalizeGuid)(t,"id"),o=r==="tokens-first",a=o?await JN(e,i):null,s=Rg(Pg,i),l=(0,he.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=(n=nu(l))!==null&&n!==void 0?n:{};if(!u.appmoduleid)throw new Se.SdkError("APP_NOT_FOUND",`App '${i}' was not found (checked the unpublished-aware projection, which includes drafts).`);let c=await t_(e,u.uniquename),d=c?(0,Ne.normalizeGuid)(c,"sitemapId"):void 0,f=null;if(d){o&&(f=await $d(e,d));let p=Fd(d,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),h=(0,he.ensureSuccess)(await e.get(p),e.apiUrl(p)),g=nu(h),b=w=>{throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap '${d}' was located by unique name, but ${w}, so the sitemap cannot be read. Persisting the app without it would misreport it as having no sitemap, or write an empty one over its navigation. Retry.`)};if(!g)return b("the by-id read returned no row");if(g.sitemapnameunique!==u.uniquename)throw new Se.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': sitemap '${d}' now carries sitemapnameunique '${String(g.sitemapnameunique)}', not '${String(u.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!Md(g.sitemapid,d))return b(`the by-id read returned a row carrying sitemapid '${String(g.sitemapid)}'`);if(typeof g.sitemapxml!="string")return b("the by-id read returned no sitemapxml");u.$sitemap=g,o||(f=await $d(e,d))}o||(a=await JN(e,i));let m=a??H8(u);return{raw:u,etag:f,...u.appmoduleid?{siblingEtags:{[(0,Ne.normalizeGuid)(u.appmoduleid,"appmoduleid")]:m}}:{}}}Qn.appApi={get(e,t){return ZN(e,t,"tokens-first")},readContentThenToken(e,t){return ZN(e,t,"content-first")},async list(e,t){let r=Rg(Pg);return(await(0,ms.collectPages)(e,r,"listArtifacts('app')")).map(i=>{var o,a;return{type:"app",id:(o=i.appmoduleid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",isDirty:!1}})},async create(e,t,r){let n=t;if(typeof n.appModuleName!="string"||n.appModuleName.trim()==="")throw new Se.ValidationError("app",n.appModuleId,[{pointer:"/name",rule:"app-name-required",message:"an app needs a name to be created, and its 'name' is missing or blank \u2014 set it (updateElement('app', id, '/name', \u2026), or addElement when the key was removed) and push again. Nothing was written."}]);await XN(e,n.sitemapxml);let i=await jN(e,n,n.appModuleId),o=n.iconWebResourceId?void 0:await J8(e),a=n.iconWebResourceId||o?.id;if(!a)throw new Se.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 s=null;o?.managed&&(s=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${o.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 l=n.appModuleUniqueName||K8(n.appModuleId),u={name:n.appModuleName,uniquename:l,clienttype:4,formfactor:1,navigationtype:0};n.appModuleDescription&&(u.description=n.appModuleDescription),n.appModuleAiDescription&&(u.aiappdescription=n.appModuleAiDescription),a&&(u.webresourceid=a);let c="/appmodules",d=(0,he.ensureSuccess)(await(0,he.resendDeadlockVictim)(()=>e.post(c,(0,he.withClientMintedId)(u,"appmoduleid",r))),e.apiUrl(c)),f=(0,he.resolveCreatedId)(d,"appmoduleid","app module",r),m=null,p=null,h=[];s&&h.push(s);let g={kind:"notRequested"},b=n.sitemapId?(0,Ne.normalizeGuid)(n.sitemapId,"sitemapId"):(0,Og.newId)(),w=!1,E=YN(n);try{let P="/sitemaps",L=(0,he.echoWrite)("sitemapid"),I=await e.post(`${P}${L.query}`,{sitemapid:b,sitemapnameunique:l,...E},L.options);w=l_(I.status);let D=(0,he.ensureSuccess)(I,e.apiUrl(P));p=(0,he.readEtag)(D),m=p??await Ig(e,b,E,l);let O=await WN(e,n,i);h.push(...O.warnings);let x=O.components;x.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:b}),await HN(e,f,x);let K=kd(e,f);await KN(e,f,O.tables,K),i&&await tW(e,f,i,K);let Re=await Y8(e,f);Re&&h.push(Re),n.appSettings&&Object.keys(n.appSettings).length>0&&h.push(...await(0,W8.applyAppSettings)(e,f,n.appSettings)),n.published!==!1&&(await(0,BN.publishAppModule)(e,f),g={kind:"submitted"})}catch(P){let L=await nW(e,f,{sitemapId:b,sitemapNameUnique:l,serverRefusedSitemap:w,sitemapWriteToken:p});throw(0,z8.failedAfterPrimaryWrite)(iW(P,L,{appId:f,sitemapId:b,uniqueName:l}))}let S=null;if(g.kind==="submitted")try{let P=await e.get(`/appmodules(${f})?$select=appmoduleid`);P.status>=200&&P.status<300&&(S=(0,he.readEtag)(P))}catch{}return{id:f,etag:m,serverIdentity:{sitemapId:b},siblingEtags:{[f]:S},publish:g,...h.length>0?{warnings:h}:{}}},async update(e,t,r,n,i,o){var a,s,l;let u=r,c=(0,Ne.normalizeGuid)(t,"id");if(await XN(e,u.sitemapxml),!u.sitemapId)throw new Se.ValidationError("app",c,[{pointer:"/sitemapId",rule:"app-sitemap-identity-missing",message:`missing sitemap identity \u2014 re-fetch the app before pushing edits: fetchArtifact('app', '${c}', { overwrite: true }) (it REPLACES the local copy \u2014 keep outstanding changes aside), push that refreshed copy UNTOUCHED, then re-apply your changes and push again. If the untouched push is refused with this same rule, the app has NO sitemap on the server \u2014 an earlier create committed its appmodule but not its sitemap \u2014 and it can be neither updated, published nor removed with deleteRemoteArtifact (an unpublished app reads back 404). Only for an app you have confirmed is your own abandoned partial create, with nothing else provisioning it: remove its appmodule row with deleteRecord('appmodule', '${c}'), clear the local copy with deleteArtifact('app', '${c}'), then author the app again and push.`}]);let d=(0,Ne.normalizeGuid)(u.sitemapId,"sitemapId");if(!(0,he.isVersionToken)(n))throw new Se.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${c}': ${n?`the concurrency token held for its sitemap row ('${n}') is not a version`:"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 f=await jN(e,u,c),m=await WN(e,u,f),p=`/appmodules(${c})`,h=(a=o?.[c])!==null&&a!==void 0?a:null,g,b;try{let ge=Rg(Pg,c),je=await e.get(ge);if(je.status>=200&&je.status<300){let de=nu(je);if(typeof de=="object"&&de!==null&&!Array.isArray(de)){g=de;let He=g.uniquename;b=typeof He=="string"&&He?He:void 0}}}catch{}let w=fW(u,g),E=h;if(Object.keys(w).length>0){if(!(0,he.isVersionToken)(h))throw new Se.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${c}': ${h?`the concurrency token held for its appmodule header ('${h}') is not a version`:"no concurrency token is held for its appmodule header"}, so its header edit could not be made conditional and would silently overwrite a concurrent edit. Nothing was modified. Re-fetch the app (fetchArtifact('app', '${c}', { overwrite: true })) and re-apply the change.`);let ge=(0,he.echoWrite)("appmoduleid",{"If-Match":h}),je=await e.patch(`${p}${ge.query}`,w,ge.options);if(dW(je))throw new Se.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${c}': 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,he.ensureSuccess)(je,e.apiUrl(p)),E=(0,he.readEtag)(je)}let S=YN(u),P=b||u.appModuleUniqueName||void 0,L=(0,he.echoWrite)("sitemapid",{"If-Match":n}),I=`/sitemaps(${d})`,D;try{D=(0,he.ensureSuccess)(await e.patch(`${I}${L.query}`,{...S},L.options),e.apiUrl(I))}catch(ge){throw(0,Se.withPartialTokens)(ge,{siblingEtags:{[c]:E}})}let O=[...m.warnings],x=kd(e,c);try{await HN(e,c,m.components),await KN(e,c,m.tables,x)}catch(ge){O.push(`App '${c}': one or more components were not pinned (${ge.message}). Navigation may reference content not included in the app; re-push to retry.`)}f&&O.push(...await rW(e,c,f,x));let K={kind:"notRequested"},Re=E,qt=(s=(0,he.readEtag)(D))!==null&&s!==void 0?s:await Ig(e,d,S,P);if(u.published===!0){try{await(0,BN.publishAppModule)(e,c),K={kind:"submitted"}}catch(ge){K={kind:"failed",error:ge},O.push(`App '${c}': saved, but publishing failed (${ge.message}). The app remains unpublished; re-push to retry.`)}if(K.kind==="submitted"){Re=null;try{let ge=await e.get(`/appmodules(${c})?$select=appmoduleid`);ge.status>=200&&ge.status<300&&(Re=(0,he.readEtag)(ge)),qt=(l=await Ig(e,d,S,P))!==null&&l!==void 0?l:qt}catch{}}}return{id:c,etag:qt,siblingEtags:{[c]:Re},publish:K,...O.length>0?{warnings:O}:{}}},async delete(e,t){let r=(0,Ne.normalizeGuid)(t,"id");await u_(e,r,await o_(e,r))}}});var $g=v(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.deleteAppCascade=hs.collectGenPageIds=void 0;var pW=Ud(),mW=Q(),xg=se(),hW=es();function c_(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),n=new hW.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml"),i=n?.documentElement;if(!i||t.length>0)throw new mW.InvalidArgumentError(`The app sitemap xml could not be parsed cleanly, so its generative-page children cannot be determined${t.length>0?` (${t[0]})`:""}`);let o=[],a=s=>{if(s.nodeName==="SubArea"){let u=s.getAttribute("GenPageId");u&&o.push((0,xg.normalizeGuid)(u,"GenPageId"))}let l=s.childNodes;for(let u=0;u<l.length;u+=1){let c=l[u];c.nodeType===1&&a(c)}};return a(i),o}hs.collectGenPageIds=c_;async function gW(e,t,r){let n=(0,xg.normalizeGuid)(t,"appModuleId");(0,xg.normalizeGuid)(r,"appModuleIdUnique");let i=[],o=[],a=[];await(0,pW.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&a.push(...c_(l))}),i.push({type:"app",id:n});let s=[...new Set(a)].map(l=>({type:"genPage",id:l}));return{success:o.length===0,deleted:i,failures:o,retained:s}}hs.deleteAppCascade=gW});var d_={};Hr(d_,{Guid:()=>U});var U,pt=k(()=>{"use strict";U=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 q,Yt=k(()=>{"use strict";ot();q=class e{static get EmptyString(){return""}static IsTrue(t){let r=!1;return r=t&&(this.IsStrictTrue(t)||this.IsYes(t)),r}static IsStrictTrue(t){let r=!1;return t&&(r=t.toLowerCase()==="true"),r}static IsYes(t){return t.toLowerCase()==="yes"||t.toLowerCase()==="y"}static get WhiteSpace(){return/ /g}static get EnglishAndNumericCharacters(){return/([a-z0-9A-Z]+)/g}static get ValidIdExpression(){return/([a-z0-9A-Z_]+)/g}static IsNullOrEmpty(t){return t==null||t==null||t==""}static Format(t,r){return e.IsNullOrEmpty(t)?t:t.replace(/\{\{|\}\}|\{(\d+)\}/g,function(n,i){return n=="{{"?"{":n=="}}"?"}":r[i]})}static EndsWithString(t,r){return t.indexOf(r,t.length-r.length)!==-1}static IsBlankString(t){return t.replace(/\s/g,"").length==0}static EscapeXml(t,r){let n=t;return this.IsNullOrEmpty(n)||(n=n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),r&&(n=n.replace(/"/g,"&quot;").replace(/'/g,"&apos;"))),n}static EscapeDomId(t){return t.replace(".","\\.")}static ToSnakeCase(t){let r=e.EmptyString;for(let n=0;n<t.length;n++)n!==0&&t[n]==t[n].toUpperCase()&&(r+="-"),r+=t[n].toLowerCase();return r}static GetSnakeCaseMarkup(t,r){let n="<"+this.ToSnakeCase(t);if(!R.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 R.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 f_={};Hr(f_,{ScriptUtilities:()=>R});var R,ot=k(()=>{"use strict";pt();Yt();R=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return q.IsNullOrEmpty(t.ToString())?!0:U.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:q.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 Bd,qd,ea,Vd,Fg,Gd,Mg=k(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(Bd||(Bd={}));qd=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},ea=class extends qd{key;oldValue;newValue;constructor(t,r,n,i){super(Bd.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)}},Vd=class extends qd{property;oldValue;newValue;constructor(t,r,n,i){super(Bd.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)}},Fg=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()})}},Gd=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 Fg(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 p_={};Hr(p_,{ChartGridMode:()=>an,ColumnLayoutWidths:()=>CW,ComponentCategory:()=>zd,ComponentType:()=>Ug,ControlLayoutTypes:()=>jg,DisplayConditionsInfo:()=>vW,ElementNames:()=>C,ElementProperties:()=>y,ElementType:()=>qg,EntityAttributeProperty:()=>Vg,EventType:()=>iu,FormActivationState:()=>zg,FormCanvasServiceScope:()=>LW,FormDesignerSideBarTab:()=>Bg,FormPresentation:()=>Gg,FormState:()=>Wd,FormType:()=>mt,HeaderDensityType:()=>mo,LookUpTable:()=>Xn,MORE_TAB_PREFIX:()=>AW,NavBarChildElementType:()=>Wg,PREVIEW_ID_HEADER_FLYOUT:()=>TW,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>IW,PREVIEW_ID_NAVIGATION_AREA:()=>NW,PREVIEW_ID_QUICKCREATE_ROOT:()=>PW,PREVIEW_ID_TAB:()=>OW,PREVIEW_ID_TAB_LIST:()=>DW,PREVIEW_ID_TAB_PANEL:()=>_W,PropertyModelKeys:()=>Jg,PropertyModelSectionKeys:()=>EW,RELATED_TAB_ID:()=>Yg,RELATED_TAB_PREFIX:()=>SW,SectionDefaultProperties:()=>wW,SectionLayoutTypes:()=>ze,TabContentType:()=>Hg,TabDefaultProperties:()=>ho,TabLayoutTypes:()=>We,TelemetryPropertyNames:()=>RW,UnboundControlPropertyKeys:()=>Kg,compositeAddressFields:()=>bW,compositeFieldNames:()=>Gr,compositeFields:()=>yW});var mt,Ug,Bg,C,y,qg,Gr,yW,bW,Vg,Xn,Wd,mo,Gg,vW,Wg,zg,We,wW,ho,ze,jg,Hg,CW,Kg,Jg,EW,iu,an,Yg,AW,SW,NW,_W,TW,DW,IW,OW,PW,RW,zd,LW,le=k(()=>{"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"})(mt||(mt={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(Ug||(Ug={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(Bg||(Bg={}));(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"})(C||(C={}));y={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"})(qg||(qg={}));Gr={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},yW=[Gr.fullname,Gr.yomifullname,Gr.address1_composite,Gr.address2_composite,Gr.address3_composite,Gr.billto,Gr.shipto],bW=[Gr.address1_composite,Gr.address2_composite,Gr.address3_composite,Gr.billto,Gr.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(Vg||(Vg={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(Xn||(Xn={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Wd||(Wd={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(mo||(mo={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Gg||(Gg={}));vW={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(Wg||(Wg={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(zg||(zg={}));(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"})(We||(We={}));wW={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},ho={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"})(ze||(ze={}));(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"})(jg||(jg={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(Hg||(Hg={}));CW={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"})(Kg||(Kg={}));(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"})(Jg||(Jg={}));EW={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"})(iu||(iu={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(an||(an={}));Yg="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",AW="more_tab_",SW="related_tab_",NW="preview_id_navigation_area",_W="tab-section",TW="headerFieldsFlyout",DW="tablist",IW="header_overflowButton",OW="tab",PW="quickCreateRoot",RW={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"})(zd||(zd={}));LW="CellCanvasServiceScope"});var m_={};Hr(m_,{Attribute:()=>jd,FormElementNode:()=>re});var jd,re,Dt=k(()=>{"use strict";ot();Yt();Mg();le();pt();jd=class{key;value;constructor(t,r){this.key=t,this.value=r}},re=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-${U.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(C.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new jd(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 ea(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 ea(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 ea(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 Vd(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 ea(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){R.IsNullOrUndefined(t)||(t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,0,t)}))}moveChild(t,r){let n=this.childrenNodes.indexOf(t);if(n<0)return!1;let i=Math.min(Math.max(0,n+r),this.childrenNodes.length-1);return n!==i&&this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(i,0,this.childrenNodes.splice(n,1)[0])}),!0}getChildren(t){let r=[];for(let n of this.childrenNodes)n.nodeName===t&&r.push(n);return r}getFirstChild(t){for(let r of this.childrenNodes)if(r.nodeName===t)return r;return null}getAllGrandChildren(t){let r=this.getChildren(t),n=null;return r.length===0?new Array:(n=r[0],n.childrenNodes)}deleteChild(t){if(R.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:q.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=R.IsNullOrUndefined(r)?this.childrenNodes.length:r,this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(t,r)})}deleteGrandChildren(t,r,n){this.getChildren(t)[0].deleteChildren(r,n)}addGrandChild(t,r){let n=this.getChildren(t),i=null;n.length===0?(i=new e(t,this),this.addChild(i)):i=n[0],i.addChild(r)}addGrandChildAtIndex(t,r,n){let i=this.getChildren(t),o=null;i.length===0?(o=new e(t,this),this.addChild(o)):o=i[0],o.insertChildAtIndex(r,n)}GetPropertyByParameter(t){return this.getProperty(t)}getSemanticParent(){switch(this.getNodeName()){case C.formCell:let t=this.getAncestor(C.formSection);return t||(t=this.getAncestor(C.formHeader),t)||(t=this.getAncestor(C.formFooter),t)?t:null;case C.formSection:return this.getAncestor(C.formTab);case C.formTab:return this.getAncestor(C.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(C.form);return t?t.changeTracker():null}}});var h_={};Hr(h_,{ControlClassId:()=>N,ControlNamePrefixes:()=>Hd,getControlDisplayNames:()=>kW});function kW(e){return{[N.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[N.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[N.ACIControl]:e("controls.controlNames.aci"),[N.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[N.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[N.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[N.ArticleContentControl]:e("controls.controlNames.articleContent"),[N.BooleanControl]:e("controls.controlNames.twoOption"),[N.ButtonControl]:e("controls.controlNames.button"),[N.CheckboxControl]:e("controls.controlNames.checkbox"),[N.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[N.ConnectionControl]:e("controls.controlNames.connection"),[N.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[N.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[N.DashboardControl]:e("controls.controlNames.dashboard"),[N.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[N.EditFilterControl]:e("controls.controlNames.editFilter"),[N.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[N.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[N.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[N.KBViewerControl]:e("controls.controlNames.kbViewer"),[N.LabelControl]:e("controls.controlNames.label"),[N.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[N.MapLinkControl]:e("controls.controlNames.mapLink"),[N.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[N.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[N.PowerBIControl]:e("controls.controlNames.powerBI"),[N.ProcessControl]:e("controls.controlNames.process"),[N.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[N.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[N.ReportControl]:e("controls.controlNames.report"),[N.StreamsControl]:e("controls.controlNames.streams"),[N.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[N.CurrencyControl]:e("controls.controlNames.currency"),[N.DateTimeControl]:e("controls.controlNames.dateAndTime"),[N.DecimalControl]:e("controls.controlNames.decimal"),[N.DurationControl]:e("controls.controlNames.duration"),[N.EmailAddressControl]:e("controls.controlNames.email"),[N.FileControl]:e("controls.controlNames.file"),[N.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[N.IframeControl]:e("controls.controlNames.iframe"),[N.ImageControl]:e("controls.controlNames.image"),[N.LookupControl]:e("controls.controlNames.lookup"),[N.MapsControl]:e("controls.controlNames.maps"),[N.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[N.ChoiceControl]:e("controls.controlNames.choice"),[N.QuickViewControl]:e("controls.controlNames.quickView"),[N.QuickFormControl]:e("controls.controlNames.quickForm"),[N.CustomControl]:e("controls.controlNames.customControl"),[N.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[N.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[N.SubgridControl]:e("controls.controlNames.subgrid"),[N.TextAreaControl]:e("controls.controlNames.textArea"),[N.TextboxControl]:e("controls.controlNames.textBox"),[N.TickerControl]:e("controls.controlNames.ticker"),[N.UrlControl]:e("controls.controlNames.url"),[N.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[N.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[N.IntegerControl]:e("controls.controlNames.integer"),[N.TimerControl]:e("controls.controlNames.timer"),[N.TimelineControl]:e("controls.controlNames.timeline"),[N.EmailBodyControl]:e("controls.controlNames.emailBody"),[N.PartyListControl]:e("controls.controlNames.partyList"),[N.TimezoneControl]:e("controls.controlNames.timezone"),[N.LanguageControl]:e("controls.controlNames.language"),[N.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[N.ChoicesControl]:e("controls.controlNames.choices"),[N.RegardingControl]:e("controls.controlNames.regarding"),[N.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[N.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[N.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[N.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[N.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[N.KBEditorControl]:e("controls.controlNames.KBEditor"),[N.LinkControl]:e("controls.controlNames.link")}}var N,Hd,ta=k(()=>{"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"})(N||(N={}));Hd={[N.WebResourceHTMLControl]:"WebResource",[N.WebResourceImageControl]:"WebResource",[N.IframeControl]:"IFRAME",[N.SearchWidgetControl]:"Search widget",[N.SubgridControl]:"Subgrid",[N.TimelineControl]:"Timeline",[N.QuickViewControl]:"QuickviewControl"}});var ra=v((Dle,y_)=>{var ou=new Proxy(function(){return ou},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:ou},apply:function(){return ou},construct:function(){return{}}}),g_=function(){return ou};Object.setPrototypeOf(g_,ou);y_.exports=g_});var sr,Pi,b_,v_,gs=k(()=>{"use strict";sr="cds-designer-models",Pi="FormCustomControl",b_="FormCell",v_="Form"});var na,Qg=k(()=>{"use strict";Bl();le();na=class e{static lockedFieldCount=new nr;static dependencyFieldCount=new nr;static getNecessaryLookUpTable(t){switch(t){case Xn.DependencyFieldTable:return e.dependencyFieldCount;case Xn.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case Xn.DependencyFieldTable:e.dependencyFieldCount=new nr;case Xn.LockedFieldTable:e.lockedFieldCount=new nr}}}});var Kd,w_=k(()=>{"use strict";pt();ot();le();Dt();Kd=class extends re{constructor(t){super(C.controlDescription,t)}get forControl(){let t=this.getProperty(y.ForControl);return R.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set forControl(t){this.setProperty(y.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(C.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!R.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!R.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)R.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}}});function Ri(){return Zn||(Zn=window._makerConfig,Zn&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(Zn={...Zn,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),Zn?.region==="prod"&&(Zn={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/"}}},...Zn}),Zn||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var Zn,Jd=k(()=>{"use strict";});function C_(e,t,r){if(!e)return Yd.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),Yd.add("")),!1;if(e){if(e=e.toLowerCase(),Yd.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}}),Yd.add(e),!1}return!0}function $W(e){return C_(e,Xg,"Location dictionary")?Xg[e.toLowerCase()]:"us"}function xW(){let e=Ri().location.toLowerCase();return C_(e,Xg,"Current location dictionary")?e:"us"}var Yd,Xg,qle,E_=k(()=>{"use strict";Jd();Yd=new Set,Xg={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"};qle=$W(xW())});var Y,Gle,A_=k(()=>{"use strict";Y={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"},Gle={[Y.USWest]:{geoName:"us",regionShortName:"wus"},[Y.USCentral]:{geoName:"us",regionShortName:"cus"},[Y.USEast]:{geoName:"us",regionShortName:"eus"},[Y.USEast2]:{geoName:"us",regionShortName:"eus2"},[Y.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[Y.USWest2]:{geoName:"us",regionShortName:"wus2"},[Y.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[Y.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[Y.UKSouth]:{geoName:"uk",regionShortName:"suk"},[Y.UKWest]:{geoName:"uk",regionShortName:"wuk"},[Y.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[Y.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[Y.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[Y.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[Y.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[Y.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[Y.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[Y.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[Y.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[Y.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[Y.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[Y.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[Y.AsiaEast]:{geoName:"as",regionShortName:"eas"},[Y.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[Y.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[Y.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[Y.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[Y.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[Y.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[Y.UAENorth]:{geoName:"ae",regionShortName:"nae"},[Y.UAECentral]:{geoName:"ae",regionShortName:"cae"},[Y.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[Y.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[Y.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[Y.NorwayEast]:{geoName:"no",regionShortName:"eno"},[Y.NorwayWest]:{geoName:"no",regionShortName:"wno"},[Y.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[Y.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[Y.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[Y.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[Y.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[Y.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[Y.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[Y.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[Y.GovernmentUSDodCentral]:{regionShortName:"udc"},[Y.GovernmentUSDodEast]:{regionShortName:"ude"},[Y.ChinaEast]:{regionShortName:"cne"},[Y.ChinaEast2]:{regionShortName:"cne2"},[Y.ChinaEast3]:{regionShortName:"cne3"},[Y.ChinaNorth]:{regionShortName:"cnn"},[Y.ChinaNorth2]:{regionShortName:"cnn2"},[Y.ChinaNorth3]:{regionShortName:"cnn3"},[Y.UssecEast]:{geoName:"us",regionShortName:"erx"},[Y.UssecWest]:{geoName:"us",regionShortName:"wrx"},[Y.UsnatEast]:{geoName:"us",regionShortName:"eex"},[Y.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var S_=k(()=>{"use strict";Jd();});var au=k(()=>{"use strict";Jd();E_();A_();S_();});function su(e,t){return N_?N_.isOverridden(e,t):{overridden:!1}}var N_,lu=k(()=>{"use strict";});var Zg=k(()=>{"use strict";au();lu();});function FW(e,t){let{region:r}=Ri();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=su(e.packageName,t);if(s.overridden)return typeof s.value=="string"?MW(s.value):s.value}let o=n.values,a=process.env.SETTINGS_FALLBACK_REGION?.[r];return o[r]!==void 0?o[r]:a&&o[a]!==void 0?o[a]:o.default}}function MW(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function UW(e){let t=e.packageName;if(Qd.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=>t0(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=>!Zd(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function uu(e){UW(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:FW(e,r)}}),Qd.set(e.packageName,e),Object.defineProperties({},t)}function e0(e,t){return Qd.has(e)?!!Qd.get(e).settings[t]:!1}var Qd,Xd=k(()=>{"use strict";au();lu();r0();cu();Qd=new Map});function __(e,t){let{region:r}=Ri();return()=>{let n=su(e.packageName,t);if(n.overridden)return n.value.toString()==="true";let i=e.features[t].enabledFor,o=process.env.SETTINGS_FALLBACK_REGION?.[r];return i[r]!==void 0?!!i[r]:o&&i[o]!==void 0?!!i[o]:!1}}function BW(e){let t=e.packageName;if(ef.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=>e0(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=>!Zd(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function n0(e){BW(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:__(e,i)}});let r={},n=new Set;return t.dangerouslySet={enumerable:!1,value:(i,o)=>{n.add(i),Object.defineProperty(r,i,{enumerable:!0,configurable:!0,value:o})}},t.dangerouslyReset={enumerable:!1,value:()=>{let i={};n.forEach(o=>{i[o.toString()]={enumerable:!0,configurable:!0,get:__(e,o.toString())}}),Object.defineProperties(r,i),n.clear()}},ef.set(e.packageName,e),Object.defineProperties(r,t)}function t0(e,t){return ef.has(e)?!!ef.get(e).features[t]:!1}var ef,r0=k(()=>{"use strict";au();cu();lu();Xd();ef=new Map});var D_=v((mue,T_)=>{"use strict";T_.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 P_=v(i0=>{"use strict";var qW=Object.prototype.hasOwnProperty,VW;function I_(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function O_(e){try{return encodeURIComponent(e)}catch{return null}}function GW(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=I_(n[1]),o=I_(n[2]);i===null||o===null||i in r||(r[i]=o)}return r}function WW(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(qW.call(e,i)){if(n=e[i],!n&&(n===null||n===VW||isNaN(n))&&(n=""),i=O_(i),n=O_(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}i0.stringify=WW;i0.parse=GW});var s0=v((gue,F_)=>{"use strict";var L_=D_(),tf=P_(),k_=/[\n\r\t]/g,zW=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,jW=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,HW=/^[a-zA-Z]:/,KW=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function a0(e){return(e||"").toString().replace(KW,"")}var o0=[["#","hash"],["?","query"],function(t,r){return ei(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]],R_={hash:1,query:1};function $_(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,o;if(e.protocol==="blob:")n=new ti(unescape(e.pathname),{});else if(i==="string"){n=new ti(e,{});for(o in R_)delete n[o]}else if(i==="object"){for(o in e)o in R_||(n[o]=e[o]);n.slashes===void 0&&(n.slashes=zW.test(e.href))}return n}function ei(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function x_(e,t){e=a0(e),e=e.replace(k_,""),t=t||{};var r=jW.exec(e),n=r[1]?r[1].toLowerCase():"",i=!!r[2],o=!!r[3],a=0,s;return i?o?(s=r[2]+r[3]+r[4],a=r[2].length+r[3].length):(s=r[2]+r[4],a=r[2].length):o?(s=r[3]+r[4],a=r[3].length):s=r[4],n==="file:"?a>=2&&(s=s.slice(2)):ei(n)?s=r[4]:n?i&&(s=s.slice(2)):a>=2&&ei(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||ei(n),slashesCount:a,rest:s}}function JW(e,t){if(e==="")return t;for(var r=(t||"/").split("/").slice(0,-1).concat(e.split("/")),n=r.length,i=r[n-1],o=!1,a=0;n--;)r[n]==="."?r.splice(n,1):r[n]===".."?(r.splice(n,1),a++):a&&(n===0&&(o=!0),r.splice(n,1),a--);return o&&r.unshift(""),(i==="."||i==="..")&&r.push(""),r.join("/")}function ti(e,t,r){if(e=a0(e),e=e.replace(k_,""),!(this instanceof ti))return new ti(e,t,r);var n,i,o,a,s,l,u=o0.slice(),c=typeof t,d=this,f=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=tf.parse),t=$_(t),i=x_(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||HW.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!ei(d.protocol)))&&(u[3]=[/(.*)/,"pathname"]);f<u.length;f++){if(a=u[f],typeof a=="function"){e=a(e,d);continue}o=a[0],l=a[1],o!==o?d[l]=e:typeof o=="string"?(s=o==="@"?e.lastIndexOf(o):e.indexOf(o),~s&&(typeof a[2]=="number"?(d[l]=e.slice(0,s),e=e.slice(s+a[2])):(d[l]=e.slice(s),e=e.slice(0,s)))):(s=o.exec(e))&&(d[l]=s[1],e=e.slice(0,s.index)),d[l]=d[l]||n&&a[3]&&t[l]||"",a[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=JW(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&ei(d.protocol)&&(d.pathname="/"+d.pathname),L_(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:"&&ei(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function YW(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||tf.parse)(t)),n[e]=t;break;case"port":n[e]=t,L_(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 o=t.indexOf(":");~o?(n.username=t.slice(0,o),n.username=encodeURIComponent(decodeURIComponent(n.username)),n.password=t.slice(o+1),n.password=encodeURIComponent(decodeURIComponent(n.password))):n.username=encodeURIComponent(decodeURIComponent(t))}for(var a=0;a<o0.length;a++){var s=o0[a];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:"&&ei(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function QW(e){(!e||typeof e!="function")&&(e=tf.stringify);var t,r=this,n=r.host,i=r.protocol;i&&i.charAt(i.length-1)!==":"&&(i+=":");var o=i+(r.protocol&&r.slashes||ei(r.protocol)?"//":"");return r.username?(o+=r.username,r.password&&(o+=":"+r.password),o+="@"):r.password?(o+=":"+r.password,o+="@"):r.protocol!=="file:"&&ei(r.protocol)&&!n&&r.pathname!=="/"&&(o+="@"),n[n.length-1]===":"&&(n+=":"),o+=n+r.pathname,t=typeof r.query=="object"?e(r.query):r.query,t&&(o+=t.charAt(0)!=="?"?"?"+t:t),r.hash&&(o+=r.hash),o}ti.prototype={set:YW,toString:QW};ti.extractProtocol=x_;ti.location=$_;ti.trimLeft=a0;ti.qs=tf;F_.exports=ti});var XW,M_=k(()=>{"use strict";XW=Ee(s0());});function l0(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 rf=k(()=>{"use strict";});var u0,c0,d0=k(()=>{"use strict";rf();u0=class{features=new Map;register(t,r){let n=l0(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()}},c0=new u0});var f0=k(()=>{"use strict";});function Zd(e){return ZW.has(e)}var ZW,cu=k(()=>{"use strict";Zg();r0();Xd();lu();Zg();M_();d0();rf();f0();ZW=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var e6,U_=k(()=>{"use strict";cu();e6=uu({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 G_,m0,ys,ia,p0,nf,bs,Li,Ue,B_,q_,V_,_n=k(()=>{"use strict";G_={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},m0={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"})(ys||(ys={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(ia||(ia={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(p0||(p0={}));nf=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"})(bs||(bs={}));Li=class{static StartTag="<"},Ue={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:ia.Left,labelPosition:bs.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"})(B_||(B_={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(q_||(q_={}));(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"})(V_||(V_={}))});var h0,W_=k(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(h0||(h0={}))});var H_,t6,z_,dce,fce,du,j_,pce,mce,K_=k(()=>{"use strict";H_=Ee(ra());ot();gs();U_();rs();_n();zo();le();t6=Ee(Yi());W_();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(z_||(z_={}));dce={Read:no.Read,Edit:no.Edit,Both:no.Both,Container:no.Container},fce={input:Wo.Input,bound:Wo.Bound,output:Wo.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(du||(du={}));(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"})(j_||(j_={}));pce=new Set([F.Currency,F.Decimal,F.FP,F.Multiple,F.SingleLineEmail,F.SingleLinePhone,F.SingleLineText,F.SingleLineTextArea,F.SingleLineURL,F.SingleLineTickerSymbol,F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.Enum,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.TwoOptions,F.Boolean,F.PowerBIReport,F.DateAndTimeDateAndTime,F.DateAndTimeDateOnly,F.OptionSet,F.MultiSelectOptionSet,F.CardForm]),mce={numbers:[F.WholeNone,F.FP,F.Decimal,F.Currency],text:[F.SingleLineText,F.SingleLineTextArea,F.Multiple],lookup:[F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding],dates:[F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime],allFields:[F.TwoOptions,F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime,F.FP,F.Decimal,F.WholeNone,F.WholeDuration,F.WholeTimeZone,F.WholeLanguage,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.Multiple,F.OptionSet,F.SingleLineText,F.SingleLineTextArea,F.SingleLineEmail,F.SingleLineURL,F.SingleLineTickerSymbol,F.SingleLinePhone]}});var Tn,of,J_=k(()=>{"use strict";Tn=Ee(ra());pt();ot();Yt();gs();zo();K_();rs();le();Dt();_n();of=class extends re{constructor(t){super(C.customControl,t)}customControlId;get id(){let t=this.getProperty(y.id);return R.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(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 o=i.getNodeName();t.get(o)?t.get(o).push(i):t.set(o,[i])}}}return t}getFormComponentValueByParameterName(t){let r=this.getParameters()?.get(jt.value);if(r?.length>0){let n=r[0],i=n?.getAllChildren()?.length>0?n.getAllChildren().find(a=>a.getNodeName()===t):null,o=i?.getAllChildren()?.length>0?i.getAllChildren()[0].getNodeName():"";return this.normalizePropertyValue(o)}}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===jt.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===jt.name)?.value,o={Name:i,Type:F.Grid,Columns:[]},l=this.getParameters().get(jt.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());o[c]=d}}return o}}getParameterIsStatic(t){let r=!1,n=this.getParameters().get(t)[0],i=n&&n.getAllProperties();if(i){for(let o of i)if(o.key===y.static&&o.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(y.Name)}get formFactor(){return this.getProperty(y.formFactor)}set formFactor(t){this.setProperty(y.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(Li.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,o=this.getParameters();for(let[a,s]of o)if(this.isDataSet(a))for(let l of o.get(a)){let u=l.getAllProperties(),c=this.getDatasetName(l),d=i.get(c),f=await this.parameterJSON(a,u,d,t);r.push({Name:c,Value:f})}else if(this.isGroups(s))r.push({Name:a,Value:{Type:Lh.GroupDefinition,Value:this.normalizePropertyValue(this.getParameterNodeChild(s[0].NodeName).NodeName)}}),i.get(a).groupSet?.forEach(u=>{u.groupConfigurableProperties.forEach(async c=>{let d=c.name;c.propertyType===du.dataset?o.get(jt.dataset)?.some(m=>this.getDatasetName(m)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:F.Grid}}):c.propertyType===du.property&&(o.has(d)||r.push({Name:d,Value:{Usage:c.usage}}))})});else{let l=s[0].getAllProperties(),u=i.get(a),c=await this.parameterJSON(a,l,u,t);if(c)r.push({Name:a,Value:c});else{(0,Tn.trackInfoTrace)(sr,{eventName:`${Pi}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/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,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/parametersToJSON`,eventData:{message:"parameters to json failed"}},n)}return r}async parameterJSON(t,r,n,i){if(this.isDataSet(t)){let o=n,a=r.find(s=>s.key===jt.name)?.value;if(o)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${a}`);(0,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let o=n,a=r&&r.find(l=>l.key===y.Type),s=o&&!o.ofTypeGroup.every(l=>!od.includes(l));if(this.isLookupType(a?.value)||this.isLookupType(o?.ofType)||s)if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=o.isPrimary;if(this.name===_i.FormComponent){let d=this.getFormComponentValueByParameterName(y.bindAttribute),f=await i.formModelService.loadLookupModel(d),m=f.lookupColumn,p=this.getLookupDataTypeFromAttributeMetadata(m);return{Name:t,Type:p,Usage:l,Static:u,Primary:c,EntityName:f.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(Rh.DefaultViewId),TargetEntityType:m.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(y.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(y.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(y.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(y.DependentAttributeType),AllowFilterOff:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.AllowFilterOff)),DisableQuickFind:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.DisableQuickFind)),EnableViewPicker:!q.IsStrictTrue(this.getFormComponentValueByParameterName(y.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,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/parameterJSON`,eventData:{message:"Missing custom control manifest lookup property info"}},l)}if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=this.getParameterValue(t),d=o.isPrimary;if(a){let m=a.value;return{Type:m,Static:u,Usage:l,Value:this.isNumberTypeProperty(o,m)&&Number(c)?Number(c):c,Primary:d}}if(o.ofType)return{Type:o.ofType,Static:u,Usage:l,Value:c,Primary:!0};if(o.ofTypeGroup)return{Static:u,Usage:l,Value:c,Primary:!0};let f=new Error(`No property type info for ${t}`);(0,Tn.trackErrorTrace)(sr,{eventName:`${Pi}/parameterJSON`,eventData:{message:"Missing property type info"}},f)}else{let l=new Error(`No property manifest info for ${t}`);(0,Tn.trackWarningTrace)(sr,{eventName:`${Pi}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case $.Customer:return F.LookupCustomer;case $.Owner:return F.LookupOwner;case $.PartyList:return F.LookupPartyList;default:return n===W.Regarding?F.LookupRegarding:F.LookupSimple}}isLookupType(t){return od.includes(t)}isNumberTypeProperty(t,r){return ad.includes(r)||t.ofTypeGroup.some(n=>ad.includes(n))}isDataSet(t){return jt.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var ee,g0=k(()=>{"use strict";ee=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 Y_={};Hr(Y_,{CustomControlUniqueId:()=>oa,DeprecatedControlClassIds:()=>G,FieldControlTypes:()=>at,mapFieldTypeToControl:()=>r6});function r6(e,t){switch(e){case $.TwoOptions:return N.BooleanControl;case $.Customer:case $.CustomerType:return N.LookupControl;case $.DateTime:return t===W.DateAndTime?N.DateTimeControl:N.DateTimeControl;case $.DecimalNumber:return N.DecimalControl;case $.FloatingPointNumber:return N.FloatingNumberControl;case $.WholeNumber:return t===W.Duration?N.DurationControl:t===W.Language?N.LanguageControl:t===W.TimeZone?N.TimezoneControl:N.IntegerControl;case $.CustomerType:case $.Lookup:case $.LookupType:return t===W.Regarding?N.RegardingControl:N.LookupControl;case $.MultipleLineofText:return t===W.Email?N.EmailBodyControl:N.TextAreaControl;case $.Currency:return N.CurrencyControl;case $.Owner:case $.OwnerType:return N.LookupControl;case $.PartyList:case $.PartyListType:return N.PartyListControl;case $.Status:case $.OptionSet:return N.ChoiceControl;case $.SingleLineofText:return t===W.Email?N.EmailAddressControl:t===W.Phone?N.PhoneNumberControl:t===W.Text?N.TextboxControl:t===W.TextArea?N.TextAreaControl:t===W.TickerSymbol?N.TickerControl:t===W.Url?N.UrlControl:t===W.PhoneticGuide?N.TextboxControl:N.TextboxControl;case $.MultiSelectOptionSet:return N.ChoicesControl;case $.Image:return N.ImageControl;case $.File:return N.FileControl;case $.State:return N.ChoiceControl;case $.Status:return N.ChoiceStatusControl;default:throw new Error(`Cannot get base control for ${e} field type`)}}var G,oa,at,fu=k(()=>{"use strict";pt();Bl();ot();Yt();rs();ta();g0();_n();G=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"}};oa=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},at=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new nr;static initializeFieldControls(){let t=new nr,r=e.getControlName($.SingleLineofText,W.Phone);t.add(r,new U(G.PhoneNumberControl));let n=e.getControlName($.SingleLineofText,W.TextArea);t.add(n,new U(G.TextAreaControl));let i=e.getControlName($.SingleLineofText,W.Text);t.add(i,new U(G.TextBoxControl));let o=e.getControlName($.SingleLineofText,W.Email);t.add(o,new U(G.EmailAddressControl));let a=e.getControlName($.SingleLineofText,W.Url);t.add(a,new U(G.UrlControl));let s=e.getControlName($.SingleLineofText,W.TickerSymbol);t.add(s,new U(G.TickerControl));let l=e.getControlName($.SingleLineofText,W.PhoneticGuide);t.add(l,new U(G.TextBoxControl));let u=e.getControlName($.WholeNumber,W.Duration);t.add(u,new U(G.DurationControl));let c=e.getControlName($.WholeNumber,W.Language);t.add(c,new U(G.LanguagePickerControl));let d=e.getControlName($.WholeNumber,W.TimeZone);t.add(d,new U(G.TimeZonePicklistControl));let f=e.getControlName($.WholeNumber,W.None);t.add(f,new U(G.IntegerControl));let m=e.getControlName($.DateTime,W.DateOnly);t.add(m,new U(G.DateTimeControl));let p=e.getControlName($.DateTime,W.DateAndTime);t.add(p,new U(G.DateTimeControl));let h=e.getControlName($.LookupType,W.None);t.add(h,new U(G.LookupControl));let g=e.getControlName($.CustomerType,W.None);t.add(g,new U(G.LookupControl));let b=e.getControlName($.FloatingPointNumber,W.None);t.add(b,new U(G.FloatControl));let w=e.getControlName($.DecimalNumber,W.None);t.add(w,new U(G.DecimalControl));let E=e.getControlName($.Currency,W.None);t.add(E,new U(G.MoneyControl));let S=e.getControlName($.MultipleLineofText,W.None);t.add(S,new U(G.TextAreaControl));let P=e.getControlName($.MultipleLineofText,W.Text);t.add(P,new U(G.TextAreaControl));let L=e.getControlName($.MultipleLineofText,W.TextArea);t.add(L,new U(G.TextAreaControl));let I=e.getControlName($.MultipleLineofText,W.Email);t.add(I,new U(G.EmailBodyControl));let D=e.getControlName($.OptionSet,W.None);t.add(D,new U(G.PicklistControl));let O=e.getControlName($.TwoOptions,W.None);t.add(O,new U(G.RadioControl));let x=e.getControlName($.Image,W.None);t.add(x,new U(G.WebResourceImageControl));let K=e.getControlName($.Image,W.None);t.add(K,new U(G.WebResourceHtmlControl));let Re=e.getControlName($.TwoOptions,"Radio");t.add(Re,new U(G.RadioControl));let qt=e.getControlName($.TwoOptions,"CheckBox");t.add(qt,new U(G.CheckBoxControl));let ge=e.getControlName($.TwoOptions,"List");t.add(ge,new U(G.PicklistControl));let je=e.getControlName($.State,W.None);t.add(je,new U(G.PicklistControl));let de=e.getControlName($.Status,W.None);t.add(de,new U(G.PicklistStatusControl));let He=e.getControlName($.OwnerType,W.None);t.add(He,new U(G.LookupControl));let bn=e.getControlName($.PartyListType,W.None);t.add(bn,new U(G.PartyListControl));let CU=e.getControlName($.LookupType,W.Regarding);t.add(CU,new U(G.RegardingControl));let EU=e.getControlName($.MultiSelectOptionSet,W.None);return t.add(EU,new U(G.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(!R.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=R.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===G.CustomControl}static initializeUnboundControls(){let t=new nr;return t.add(G.ACIControl,ee.ACIControl),t.add(G.IframeControl,ee.IframeControl),t.add(G.SearchWidgetControl,ee.SearchWidgetControl),t.add(G.MapsControl,ee.MapsControl),t.add(G.QuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.GridControl,ee.SubGridControl),t.add(G.WebResourceImageControl,ee.WebResourceImageControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.TimerControl,ee.TimerControl),t.add(G.TimeLineControl,ee.NotesControl),t.add(G.TimeLineControlUC,ee.NotesControl),t.add(G.SocialInsightControl,ee.SocialInsightControl),t.add(oa.RelationshipAssistant,ee.CustomControl),t}static initializeReferencePanelControls(){let t=new nr;return t.add(G.IframeControl,ee.IframeControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.WebResourceImageControl,ee.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new ts;return t.add(ys.IFRAME,!0),t.add(ys.SPACER,!0),t.add(ys.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!R.IsNullOrUndefined(t)&&!R.IsNullOrUndefined(t.Name)&&t.Name.indexOf(Ue.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=q.EmptyString;if(R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.guidString)?q.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===G.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!R.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case ee.IframeControl:case ee.ACIControl:case ee.SocialInsightControl:return 6;case ee.SubGridControl:case ee.CustomControl:return 4;case ee.WebResourceImageControl:return 15;case ee.WebResourceHtmlControl:return 15;case ee.MapsControl:return 8;case ee.SearchWidgetControl:return 10;case ee.NotesControl:case ee.TimeLineControl:return 15;case ee.TimerControl:return 2;default:}}static isLookUpControl(t){return!R.IsNullOrUndefined(t)&&t.ClassId.guidString===G.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!R.IsNullOrUndefined(t)&&(t.guidString===oa.RelationshipAssistant||t.guidString===oa.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!R.IsNullOrUndefined(t)&&t.guidString===oa.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(R.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!R.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var af,Q_=k(()=>{"use strict";af=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 aa,vs,X_,Z_,go,eT,tT,y0=k(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(aa||(aa={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(vs||(vs={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(X_||(X_={}));(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"})(Z_||(Z_={}));(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"})(go||(go={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(eT||(eT={}));(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"})(tT||(tT={}))});var ws,rT=k(()=>{"use strict";cu();ws=n0({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 nT(e){return{...e,extractConfig:t=>n6(t,Object.keys(e.fallback))}}function n6(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var b0=k(()=>{"use strict";});var v0=v((qce,oT)=>{var pu=new Proxy(function(){return pu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:pu},apply:function(){return pu},construct:function(){return{}}}),iT=function(){return pu};Object.setPrototypeOf(iT,pu);oT.exports=iT});var lT=v((Vce,sT)=>{var mu=new Proxy(function(){return mu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:mu},apply:function(){return mu},construct:function(){return{}}}),aT=function(){return mu};Object.setPrototypeOf(aT,mu);sT.exports=aT});var w0=v((Gce,cT)=>{var hu=new Proxy(function(){return hu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:hu},apply:function(){return hu},construct:function(){return{}}}),uT=function(){return hu};Object.setPrototypeOf(uT,hu);cT.exports=uT});var fT=v((Wce,dT)=>{function i6(){this.__data__=[],this.size=0}dT.exports=i6});var Cs=v((zce,pT)=>{function o6(e,t){return e===t||e!==e&&t!==t}pT.exports=o6});var gu=v((jce,mT)=>{var a6=Cs();function s6(e,t){for(var r=e.length;r--;)if(a6(e[r][0],t))return r;return-1}mT.exports=s6});var gT=v((Hce,hT)=>{var l6=gu(),u6=Array.prototype,c6=u6.splice;function d6(e){var t=this.__data__,r=l6(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():c6.call(t,r,1),--this.size,!0}hT.exports=d6});var bT=v((Kce,yT)=>{var f6=gu();function p6(e){var t=this.__data__,r=f6(t,e);return r<0?void 0:t[r][1]}yT.exports=p6});var wT=v((Jce,vT)=>{var m6=gu();function h6(e){return m6(this.__data__,e)>-1}vT.exports=h6});var ET=v((Yce,CT)=>{var g6=gu();function y6(e,t){var r=this.__data__,n=g6(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}CT.exports=y6});var yu=v((Qce,AT)=>{var b6=fT(),v6=gT(),w6=bT(),C6=wT(),E6=ET();function Es(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])}}Es.prototype.clear=b6;Es.prototype.delete=v6;Es.prototype.get=w6;Es.prototype.has=C6;Es.prototype.set=E6;AT.exports=Es});var NT=v((Xce,ST)=>{var A6=yu();function S6(){this.__data__=new A6,this.size=0}ST.exports=S6});var TT=v((Zce,_T)=>{function N6(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}_T.exports=N6});var IT=v((ede,DT)=>{function _6(e){return this.__data__.get(e)}DT.exports=_6});var PT=v((tde,OT)=>{function T6(e){return this.__data__.has(e)}OT.exports=T6});var C0=v((rde,RT)=>{var D6=typeof global=="object"&&global&&global.Object===Object&&global;RT.exports=D6});var Dn=v((nde,LT)=>{var I6=C0(),O6=typeof self=="object"&&self&&self.Object===Object&&self,P6=I6||O6||Function("return this")();LT.exports=P6});var bu=v((ide,kT)=>{var R6=Dn(),L6=R6.Symbol;kT.exports=L6});var MT=v((ode,FT)=>{var $T=bu(),xT=Object.prototype,k6=xT.hasOwnProperty,$6=xT.toString,vu=$T?$T.toStringTag:void 0;function x6(e){var t=k6.call(e,vu),r=e[vu];try{e[vu]=void 0;var n=!0}catch{}var i=$6.call(e);return n&&(t?e[vu]=r:delete e[vu]),i}FT.exports=x6});var BT=v((ade,UT)=>{var F6=Object.prototype,M6=F6.toString;function U6(e){return M6.call(e)}UT.exports=U6});var sa=v((sde,GT)=>{var qT=bu(),B6=MT(),q6=BT(),V6="[object Null]",G6="[object Undefined]",VT=qT?qT.toStringTag:void 0;function W6(e){return e==null?e===void 0?G6:V6:VT&&VT in Object(e)?B6(e):q6(e)}GT.exports=W6});var ki=v((lde,WT)=>{function z6(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}WT.exports=z6});var sf=v((ude,zT)=>{var j6=sa(),H6=ki(),K6="[object AsyncFunction]",J6="[object Function]",Y6="[object GeneratorFunction]",Q6="[object Proxy]";function X6(e){if(!H6(e))return!1;var t=j6(e);return t==J6||t==Y6||t==K6||t==Q6}zT.exports=X6});var HT=v((cde,jT)=>{var Z6=Dn(),ez=Z6["__core-js_shared__"];jT.exports=ez});var YT=v((dde,JT)=>{var E0=HT(),KT=(function(){var e=/[^.]+$/.exec(E0&&E0.keys&&E0.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function tz(e){return!!KT&&KT in e}JT.exports=tz});var A0=v((fde,QT)=>{var rz=Function.prototype,nz=rz.toString;function iz(e){if(e!=null){try{return nz.call(e)}catch{}try{return e+""}catch{}}return""}QT.exports=iz});var ZT=v((pde,XT)=>{var oz=sf(),az=YT(),sz=ki(),lz=A0(),uz=/[\\^$.*+?()[\]{}|]/g,cz=/^\[object .+?Constructor\]$/,dz=Function.prototype,fz=Object.prototype,pz=dz.toString,mz=fz.hasOwnProperty,hz=RegExp("^"+pz.call(mz).replace(uz,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function gz(e){if(!sz(e)||az(e))return!1;var t=oz(e)?hz:cz;return t.test(lz(e))}XT.exports=gz});var tD=v((mde,eD)=>{function yz(e,t){return e?.[t]}eD.exports=yz});var yo=v((hde,rD)=>{var bz=ZT(),vz=tD();function wz(e,t){var r=vz(e,t);return bz(r)?r:void 0}rD.exports=wz});var lf=v((gde,nD)=>{var Cz=yo(),Ez=Dn(),Az=Cz(Ez,"Map");nD.exports=Az});var wu=v((yde,iD)=>{var Sz=yo(),Nz=Sz(Object,"create");iD.exports=Nz});var sD=v((bde,aD)=>{var oD=wu();function _z(){this.__data__=oD?oD(null):{},this.size=0}aD.exports=_z});var uD=v((vde,lD)=>{function Tz(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}lD.exports=Tz});var dD=v((wde,cD)=>{var Dz=wu(),Iz="__lodash_hash_undefined__",Oz=Object.prototype,Pz=Oz.hasOwnProperty;function Rz(e){var t=this.__data__;if(Dz){var r=t[e];return r===Iz?void 0:r}return Pz.call(t,e)?t[e]:void 0}cD.exports=Rz});var pD=v((Cde,fD)=>{var Lz=wu(),kz=Object.prototype,$z=kz.hasOwnProperty;function xz(e){var t=this.__data__;return Lz?t[e]!==void 0:$z.call(t,e)}fD.exports=xz});var hD=v((Ede,mD)=>{var Fz=wu(),Mz="__lodash_hash_undefined__";function Uz(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Fz&&t===void 0?Mz:t,this}mD.exports=Uz});var yD=v((Ade,gD)=>{var Bz=sD(),qz=uD(),Vz=dD(),Gz=pD(),Wz=hD();function As(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])}}As.prototype.clear=Bz;As.prototype.delete=qz;As.prototype.get=Vz;As.prototype.has=Gz;As.prototype.set=Wz;gD.exports=As});var wD=v((Sde,vD)=>{var bD=yD(),zz=yu(),jz=lf();function Hz(){this.size=0,this.__data__={hash:new bD,map:new(jz||zz),string:new bD}}vD.exports=Hz});var ED=v((Nde,CD)=>{function Kz(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}CD.exports=Kz});var Cu=v((_de,AD)=>{var Jz=ED();function Yz(e,t){var r=e.__data__;return Jz(t)?r[typeof t=="string"?"string":"hash"]:r.map}AD.exports=Yz});var ND=v((Tde,SD)=>{var Qz=Cu();function Xz(e){var t=Qz(this,e).delete(e);return this.size-=t?1:0,t}SD.exports=Xz});var TD=v((Dde,_D)=>{var Zz=Cu();function ej(e){return Zz(this,e).get(e)}_D.exports=ej});var ID=v((Ide,DD)=>{var tj=Cu();function rj(e){return tj(this,e).has(e)}DD.exports=rj});var PD=v((Ode,OD)=>{var nj=Cu();function ij(e,t){var r=nj(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}OD.exports=ij});var uf=v((Pde,RD)=>{var oj=wD(),aj=ND(),sj=TD(),lj=ID(),uj=PD();function Ss(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])}}Ss.prototype.clear=oj;Ss.prototype.delete=aj;Ss.prototype.get=sj;Ss.prototype.has=lj;Ss.prototype.set=uj;RD.exports=Ss});var kD=v((Rde,LD)=>{var cj=yu(),dj=lf(),fj=uf(),pj=200;function mj(e,t){var r=this.__data__;if(r instanceof cj){var n=r.__data__;if(!dj||n.length<pj-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new fj(n)}return r.set(e,t),this.size=r.size,this}LD.exports=mj});var S0=v((Lde,$D)=>{var hj=yu(),gj=NT(),yj=TT(),bj=IT(),vj=PT(),wj=kD();function Ns(e){var t=this.__data__=new hj(e);this.size=t.size}Ns.prototype.clear=gj;Ns.prototype.delete=yj;Ns.prototype.get=bj;Ns.prototype.has=vj;Ns.prototype.set=wj;$D.exports=Ns});var FD=v((kde,xD)=>{var Cj="__lodash_hash_undefined__";function Ej(e){return this.__data__.set(e,Cj),this}xD.exports=Ej});var UD=v(($de,MD)=>{function Aj(e){return this.__data__.has(e)}MD.exports=Aj});var qD=v((xde,BD)=>{var Sj=uf(),Nj=FD(),_j=UD();function cf(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Sj;++t<r;)this.add(e[t])}cf.prototype.add=cf.prototype.push=Nj;cf.prototype.has=_j;BD.exports=cf});var GD=v((Fde,VD)=>{function Tj(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}VD.exports=Tj});var zD=v((Mde,WD)=>{function Dj(e,t){return e.has(t)}WD.exports=Dj});var N0=v((Ude,jD)=>{var Ij=qD(),Oj=GD(),Pj=zD(),Rj=1,Lj=2;function kj(e,t,r,n,i,o){var a=r&Rj,s=e.length,l=t.length;if(s!=l&&!(a&&l>s))return!1;var u=o.get(e),c=o.get(t);if(u&&c)return u==t&&c==e;var d=-1,f=!0,m=r&Lj?new Ij:void 0;for(o.set(e,t),o.set(t,e);++d<s;){var p=e[d],h=t[d];if(n)var g=a?n(h,p,d,t,e,o):n(p,h,d,e,t,o);if(g!==void 0){if(g)continue;f=!1;break}if(m){if(!Oj(t,function(b,w){if(!Pj(m,w)&&(p===b||i(p,b,r,n,o)))return m.push(w)})){f=!1;break}}else if(!(p===h||i(p,h,r,n,o))){f=!1;break}}return o.delete(e),o.delete(t),f}jD.exports=kj});var _0=v((Bde,HD)=>{var $j=Dn(),xj=$j.Uint8Array;HD.exports=xj});var JD=v((qde,KD)=>{function Fj(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}KD.exports=Fj});var QD=v((Vde,YD)=>{function Mj(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}YD.exports=Mj});var rI=v((Gde,tI)=>{var XD=bu(),ZD=_0(),Uj=Cs(),Bj=N0(),qj=JD(),Vj=QD(),Gj=1,Wj=2,zj="[object Boolean]",jj="[object Date]",Hj="[object Error]",Kj="[object Map]",Jj="[object Number]",Yj="[object RegExp]",Qj="[object Set]",Xj="[object String]",Zj="[object Symbol]",e7="[object ArrayBuffer]",t7="[object DataView]",eI=XD?XD.prototype:void 0,T0=eI?eI.valueOf:void 0;function r7(e,t,r,n,i,o,a){switch(r){case t7:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case e7:return!(e.byteLength!=t.byteLength||!o(new ZD(e),new ZD(t)));case zj:case jj:case Jj:return Uj(+e,+t);case Hj:return e.name==t.name&&e.message==t.message;case Yj:case Xj:return e==t+"";case Kj:var s=qj;case Qj:var l=n&Gj;if(s||(s=Vj),e.size!=t.size&&!l)return!1;var u=a.get(e);if(u)return u==t;n|=Wj,a.set(e,t);var c=Bj(s(e),s(t),n,i,o,a);return a.delete(e),c;case Zj:if(T0)return T0.call(e)==T0.call(t)}return!1}tI.exports=r7});var iI=v((Wde,nI)=>{function n7(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}nI.exports=n7});var bo=v((zde,oI)=>{var i7=Array.isArray;oI.exports=i7});var sI=v((jde,aI)=>{var o7=iI(),a7=bo();function s7(e,t,r){var n=t(e);return a7(e)?n:o7(n,r(e))}aI.exports=s7});var uI=v((Hde,lI)=>{function l7(e,t){for(var r=-1,n=e==null?0:e.length,i=0,o=[];++r<n;){var a=e[r];t(a,r,e)&&(o[i++]=a)}return o}lI.exports=l7});var dI=v((Kde,cI)=>{function u7(){return[]}cI.exports=u7});var mI=v((Jde,pI)=>{var c7=uI(),d7=dI(),f7=Object.prototype,p7=f7.propertyIsEnumerable,fI=Object.getOwnPropertySymbols,m7=fI?function(e){return e==null?[]:(e=Object(e),c7(fI(e),function(t){return p7.call(e,t)}))}:d7;pI.exports=m7});var gI=v((Yde,hI)=>{function h7(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}hI.exports=h7});var vo=v((Qde,yI)=>{function g7(e){return e!=null&&typeof e=="object"}yI.exports=g7});var vI=v((Xde,bI)=>{var y7=sa(),b7=vo(),v7="[object Arguments]";function w7(e){return b7(e)&&y7(e)==v7}bI.exports=w7});var D0=v((Zde,EI)=>{var wI=vI(),C7=vo(),CI=Object.prototype,E7=CI.hasOwnProperty,A7=CI.propertyIsEnumerable,S7=wI((function(){return arguments})())?wI:function(e){return C7(e)&&E7.call(e,"callee")&&!A7.call(e,"callee")};EI.exports=S7});var SI=v((efe,AI)=>{function N7(){return!1}AI.exports=N7});var df=v((Eu,_s)=>{var _7=Dn(),T7=SI(),TI=typeof Eu=="object"&&Eu&&!Eu.nodeType&&Eu,NI=TI&&typeof _s=="object"&&_s&&!_s.nodeType&&_s,D7=NI&&NI.exports===TI,_I=D7?_7.Buffer:void 0,I7=_I?_I.isBuffer:void 0,O7=I7||T7;_s.exports=O7});var ff=v((tfe,DI)=>{var P7=9007199254740991,R7=/^(?:0|[1-9]\d*)$/;function L7(e,t){var r=typeof e;return t=t??P7,!!t&&(r=="number"||r!="symbol"&&R7.test(e))&&e>-1&&e%1==0&&e<t}DI.exports=L7});var I0=v((rfe,II)=>{var k7=9007199254740991;function $7(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=k7}II.exports=$7});var PI=v((nfe,OI)=>{var x7=sa(),F7=I0(),M7=vo(),U7="[object Arguments]",B7="[object Array]",q7="[object Boolean]",V7="[object Date]",G7="[object Error]",W7="[object Function]",z7="[object Map]",j7="[object Number]",H7="[object Object]",K7="[object RegExp]",J7="[object Set]",Y7="[object String]",Q7="[object WeakMap]",X7="[object ArrayBuffer]",Z7="[object DataView]",eH="[object Float32Array]",tH="[object Float64Array]",rH="[object Int8Array]",nH="[object Int16Array]",iH="[object Int32Array]",oH="[object Uint8Array]",aH="[object Uint8ClampedArray]",sH="[object Uint16Array]",lH="[object Uint32Array]",$e={};$e[eH]=$e[tH]=$e[rH]=$e[nH]=$e[iH]=$e[oH]=$e[aH]=$e[sH]=$e[lH]=!0;$e[U7]=$e[B7]=$e[X7]=$e[q7]=$e[Z7]=$e[V7]=$e[G7]=$e[W7]=$e[z7]=$e[j7]=$e[H7]=$e[K7]=$e[J7]=$e[Y7]=$e[Q7]=!1;function uH(e){return M7(e)&&F7(e.length)&&!!$e[x7(e)]}OI.exports=uH});var LI=v((ife,RI)=>{function cH(e){return function(t){return e(t)}}RI.exports=cH});var $I=v((Au,Ts)=>{var dH=C0(),kI=typeof Au=="object"&&Au&&!Au.nodeType&&Au,Su=kI&&typeof Ts=="object"&&Ts&&!Ts.nodeType&&Ts,fH=Su&&Su.exports===kI,O0=fH&&dH.process,pH=(function(){try{var e=Su&&Su.require&&Su.require("util").types;return e||O0&&O0.binding&&O0.binding("util")}catch{}})();Ts.exports=pH});var pf=v((ofe,MI)=>{var mH=PI(),hH=LI(),xI=$I(),FI=xI&&xI.isTypedArray,gH=FI?hH(FI):mH;MI.exports=gH});var P0=v((afe,UI)=>{var yH=gI(),bH=D0(),vH=bo(),wH=df(),CH=ff(),EH=pf(),AH=Object.prototype,SH=AH.hasOwnProperty;function NH(e,t){var r=vH(e),n=!r&&bH(e),i=!r&&!n&&wH(e),o=!r&&!n&&!i&&EH(e),a=r||n||i||o,s=a?yH(e.length,String):[],l=s.length;for(var u in e)(t||SH.call(e,u))&&!(a&&(u=="length"||i&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||CH(u,l)))&&s.push(u);return s}UI.exports=NH});var mf=v((sfe,BI)=>{var _H=Object.prototype;function TH(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||_H;return e===r}BI.exports=TH});var R0=v((lfe,qI)=>{function DH(e,t){return function(r){return e(t(r))}}qI.exports=DH});var GI=v((ufe,VI)=>{var IH=R0(),OH=IH(Object.keys,Object);VI.exports=OH});var zI=v((cfe,WI)=>{var PH=mf(),RH=GI(),LH=Object.prototype,kH=LH.hasOwnProperty;function $H(e){if(!PH(e))return RH(e);var t=[];for(var r in Object(e))kH.call(e,r)&&r!="constructor"&&t.push(r);return t}WI.exports=$H});var Nu=v((dfe,jI)=>{var xH=sf(),FH=I0();function MH(e){return e!=null&&FH(e.length)&&!xH(e)}jI.exports=MH});var KI=v((ffe,HI)=>{var UH=P0(),BH=zI(),qH=Nu();function VH(e){return qH(e)?UH(e):BH(e)}HI.exports=VH});var YI=v((pfe,JI)=>{var GH=sI(),WH=mI(),zH=KI();function jH(e){return GH(e,zH,WH)}JI.exports=jH});var ZI=v((mfe,XI)=>{var QI=YI(),HH=1,KH=Object.prototype,JH=KH.hasOwnProperty;function YH(e,t,r,n,i,o){var a=r&HH,s=QI(e),l=s.length,u=QI(t),c=u.length;if(l!=c&&!a)return!1;for(var d=l;d--;){var f=s[d];if(!(a?f in t:JH.call(t,f)))return!1}var m=o.get(e),p=o.get(t);if(m&&p)return m==t&&p==e;var h=!0;o.set(e,t),o.set(t,e);for(var g=a;++d<l;){f=s[d];var b=e[f],w=t[f];if(n)var E=a?n(w,b,f,t,e,o):n(b,w,f,e,t,o);if(!(E===void 0?b===w||i(b,w,r,n,o):E)){h=!1;break}g||(g=f=="constructor")}if(h&&!g){var S=e.constructor,P=t.constructor;S!=P&&"constructor"in e&&"constructor"in t&&!(typeof S=="function"&&S instanceof S&&typeof P=="function"&&P instanceof P)&&(h=!1)}return o.delete(e),o.delete(t),h}XI.exports=YH});var tO=v((hfe,eO)=>{var QH=yo(),XH=Dn(),ZH=QH(XH,"DataView");eO.exports=ZH});var nO=v((gfe,rO)=>{var eK=yo(),tK=Dn(),rK=eK(tK,"Promise");rO.exports=rK});var oO=v((yfe,iO)=>{var nK=yo(),iK=Dn(),oK=nK(iK,"Set");iO.exports=oK});var sO=v((bfe,aO)=>{var aK=yo(),sK=Dn(),lK=aK(sK,"WeakMap");aO.exports=lK});var hO=v((vfe,mO)=>{var L0=tO(),k0=lf(),$0=nO(),x0=oO(),F0=sO(),pO=sa(),Ds=A0(),lO="[object Map]",uK="[object Object]",uO="[object Promise]",cO="[object Set]",dO="[object WeakMap]",fO="[object DataView]",cK=Ds(L0),dK=Ds(k0),fK=Ds($0),pK=Ds(x0),mK=Ds(F0),la=pO;(L0&&la(new L0(new ArrayBuffer(1)))!=fO||k0&&la(new k0)!=lO||$0&&la($0.resolve())!=uO||x0&&la(new x0)!=cO||F0&&la(new F0)!=dO)&&(la=function(e){var t=pO(e),r=t==uK?e.constructor:void 0,n=r?Ds(r):"";if(n)switch(n){case cK:return fO;case dK:return lO;case fK:return uO;case pK:return cO;case mK:return dO}return t});mO.exports=la});var AO=v((wfe,EO)=>{var M0=S0(),hK=N0(),gK=rI(),yK=ZI(),gO=hO(),yO=bo(),bO=df(),bK=pf(),vK=1,vO="[object Arguments]",wO="[object Array]",hf="[object Object]",wK=Object.prototype,CO=wK.hasOwnProperty;function CK(e,t,r,n,i,o){var a=yO(e),s=yO(t),l=a?wO:gO(e),u=s?wO:gO(t);l=l==vO?hf:l,u=u==vO?hf:u;var c=l==hf,d=u==hf,f=l==u;if(f&&bO(e)){if(!bO(t))return!1;a=!0,c=!1}if(f&&!c)return o||(o=new M0),a||bK(e)?hK(e,t,r,n,i,o):gK(e,t,l,r,n,i,o);if(!(r&vK)){var m=c&&CO.call(e,"__wrapped__"),p=d&&CO.call(t,"__wrapped__");if(m||p){var h=m?e.value():e,g=p?t.value():t;return o||(o=new M0),i(h,g,r,n,o)}}return f?(o||(o=new M0),yK(e,t,r,n,i,o)):!1}EO.exports=CK});var TO=v((Cfe,_O)=>{var EK=AO(),SO=vo();function NO(e,t,r,n,i){return e===t?!0:e==null||t==null||!SO(e)&&!SO(t)?e!==e&&t!==t:EK(e,t,r,n,NO,i)}_O.exports=NO});var IO=v((Efe,DO)=>{var AK=TO();function SK(e,t){return AK(e,t)}DO.exports=SK});var U0=v((Afe,OO)=>{var NK=yo(),_K=(function(){try{var e=NK(Object,"defineProperty");return e({},"",{}),e}catch{}})();OO.exports=_K});var gf=v((Sfe,RO)=>{var PO=U0();function TK(e,t,r){t=="__proto__"&&PO?PO(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}RO.exports=TK});var B0=v((Nfe,LO)=>{var DK=gf(),IK=Cs();function OK(e,t,r){(r!==void 0&&!IK(e[t],r)||r===void 0&&!(t in e))&&DK(e,t,r)}LO.exports=OK});var $O=v((_fe,kO)=>{function PK(e){return function(t,r,n){for(var i=-1,o=Object(t),a=n(t),s=a.length;s--;){var l=a[e?s:++i];if(r(o[l],l,o)===!1)break}return t}}kO.exports=PK});var FO=v((Tfe,xO)=>{var RK=$O(),LK=RK();xO.exports=LK});var VO=v((_u,Is)=>{var kK=Dn(),qO=typeof _u=="object"&&_u&&!_u.nodeType&&_u,MO=qO&&typeof Is=="object"&&Is&&!Is.nodeType&&Is,$K=MO&&MO.exports===qO,UO=$K?kK.Buffer:void 0,BO=UO?UO.allocUnsafe:void 0;function xK(e,t){if(t)return e.slice();var r=e.length,n=BO?BO(r):new e.constructor(r);return e.copy(n),n}Is.exports=xK});var zO=v((Dfe,WO)=>{var GO=_0();function FK(e){var t=new e.constructor(e.byteLength);return new GO(t).set(new GO(e)),t}WO.exports=FK});var HO=v((Ife,jO)=>{var MK=zO();function UK(e,t){var r=t?MK(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}jO.exports=UK});var JO=v((Ofe,KO)=>{function BK(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}KO.exports=BK});var XO=v((Pfe,QO)=>{var qK=ki(),YO=Object.create,VK=(function(){function e(){}return function(t){if(!qK(t))return{};if(YO)return YO(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();QO.exports=VK});var q0=v((Rfe,ZO)=>{var GK=R0(),WK=GK(Object.getPrototypeOf,Object);ZO.exports=WK});var tP=v((Lfe,eP)=>{var zK=XO(),jK=q0(),HK=mf();function KK(e){return typeof e.constructor=="function"&&!HK(e)?zK(jK(e)):{}}eP.exports=KK});var nP=v((kfe,rP)=>{var JK=Nu(),YK=vo();function QK(e){return YK(e)&&JK(e)}rP.exports=QK});var aP=v(($fe,oP)=>{var XK=sa(),ZK=q0(),eJ=vo(),tJ="[object Object]",rJ=Function.prototype,nJ=Object.prototype,iP=rJ.toString,iJ=nJ.hasOwnProperty,oJ=iP.call(Object);function aJ(e){if(!eJ(e)||XK(e)!=tJ)return!1;var t=ZK(e);if(t===null)return!0;var r=iJ.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&iP.call(r)==oJ}oP.exports=aJ});var V0=v((xfe,sP)=>{function sJ(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}sP.exports=sJ});var G0=v((Ffe,lP)=>{var lJ=gf(),uJ=Cs(),cJ=Object.prototype,dJ=cJ.hasOwnProperty;function fJ(e,t,r){var n=e[t];(!(dJ.call(e,t)&&uJ(n,r))||r===void 0&&!(t in e))&&lJ(e,t,r)}lP.exports=fJ});var cP=v((Mfe,uP)=>{var pJ=G0(),mJ=gf();function hJ(e,t,r,n){var i=!r;r||(r={});for(var o=-1,a=t.length;++o<a;){var s=t[o],l=n?n(r[s],e[s],s,r,e):void 0;l===void 0&&(l=e[s]),i?mJ(r,s,l):pJ(r,s,l)}return r}uP.exports=hJ});var fP=v((Ufe,dP)=>{function gJ(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}dP.exports=gJ});var mP=v((Bfe,pP)=>{var yJ=ki(),bJ=mf(),vJ=fP(),wJ=Object.prototype,CJ=wJ.hasOwnProperty;function EJ(e){if(!yJ(e))return vJ(e);var t=bJ(e),r=[];for(var n in e)n=="constructor"&&(t||!CJ.call(e,n))||r.push(n);return r}pP.exports=EJ});var W0=v((qfe,hP)=>{var AJ=P0(),SJ=mP(),NJ=Nu();function _J(e){return NJ(e)?AJ(e,!0):SJ(e)}hP.exports=_J});var yP=v((Vfe,gP)=>{var TJ=cP(),DJ=W0();function IJ(e){return TJ(e,DJ(e))}gP.exports=IJ});var AP=v((Gfe,EP)=>{var bP=B0(),OJ=VO(),PJ=HO(),RJ=JO(),LJ=tP(),vP=D0(),wP=bo(),kJ=nP(),$J=df(),xJ=sf(),FJ=ki(),MJ=aP(),UJ=pf(),CP=V0(),BJ=yP();function qJ(e,t,r,n,i,o,a){var s=CP(e,r),l=CP(t,r),u=a.get(l);if(u){bP(e,r,u);return}var c=o?o(s,l,r+"",e,t,a):void 0,d=c===void 0;if(d){var f=wP(l),m=!f&&$J(l),p=!f&&!m&&UJ(l);c=l,f||m||p?wP(s)?c=s:kJ(s)?c=RJ(s):m?(d=!1,c=OJ(l,!0)):p?(d=!1,c=PJ(l,!0)):c=[]:MJ(l)||vP(l)?(c=s,vP(s)?c=BJ(s):(!FJ(s)||xJ(s))&&(c=LJ(l))):d=!1}d&&(a.set(l,c),i(c,l,n,o,a),a.delete(l)),bP(e,r,c)}EP.exports=qJ});var z0=v((Wfe,NP)=>{var VJ=S0(),GJ=B0(),WJ=FO(),zJ=AP(),jJ=ki(),HJ=W0(),KJ=V0();function SP(e,t,r,n,i){e!==t&&WJ(t,function(o,a){if(i||(i=new VJ),jJ(o))zJ(e,t,a,r,SP,n,i);else{var s=n?n(KJ(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),GJ(e,a,s)}},HJ)}NP.exports=SP});var j0=v((zfe,_P)=>{function JJ(e){return e}_P.exports=JJ});var DP=v((jfe,TP)=>{function YJ(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)}TP.exports=YJ});var PP=v((Hfe,OP)=>{var QJ=DP(),IP=Math.max;function XJ(e,t,r){return t=IP(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,o=IP(n.length-t,0),a=Array(o);++i<o;)a[i]=n[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=n[i];return s[t]=r(a),QJ(e,this,s)}}OP.exports=XJ});var LP=v((Kfe,RP)=>{function ZJ(e){return function(){return e}}RP.exports=ZJ});var xP=v((Jfe,$P)=>{var eY=LP(),kP=U0(),tY=j0(),rY=kP?function(e,t){return kP(e,"toString",{configurable:!0,enumerable:!1,value:eY(t),writable:!0})}:tY;$P.exports=rY});var MP=v((Yfe,FP)=>{var nY=800,iY=16,oY=Date.now;function aY(e){var t=0,r=0;return function(){var n=oY(),i=iY-(n-r);if(r=n,i>0){if(++t>=nY)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}FP.exports=aY});var BP=v((Qfe,UP)=>{var sY=xP(),lY=MP(),uY=lY(sY);UP.exports=uY});var VP=v((Xfe,qP)=>{var cY=j0(),dY=PP(),fY=BP();function pY(e,t){return fY(dY(e,t,cY),e+"")}qP.exports=pY});var WP=v((Zfe,GP)=>{var mY=Cs(),hY=Nu(),gY=ff(),yY=ki();function bY(e,t,r){if(!yY(r))return!1;var n=typeof t;return(n=="number"?hY(r)&&gY(t,r.length):n=="string"&&t in r)?mY(r[t],e):!1}GP.exports=bY});var H0=v((epe,zP)=>{var vY=VP(),wY=WP();function CY(e){return vY(function(t,r){var n=-1,i=r.length,o=i>1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(o=e.length>3&&typeof o=="function"?(i--,o):void 0,a&&wY(r[0],r[1],a)&&(o=i<3?void 0:o,i=1),t=Object(t);++n<i;){var s=r[n];s&&e(t,s,n,o)}return t})}zP.exports=CY});var HP=v((tpe,jP)=>{var EY=z0(),AY=H0(),SY=AY(function(e,t,r,n){EY(e,t,r,n)});jP.exports=SY});var sn,Tu=k(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(sn||(sn={}))});function JP(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${KP.EcsConfigType[i]}_${r}`;return{getData:i=>{let o=t.getItem(n(i));return Promise.resolve(o?JSON.parse(o):void 0)},putData:(i,o)=>(t.setItem(n(i),JSON.stringify(o)),Promise.resolve())}}var KP,NY,YP=k(()=>{"use strict";KP=Ee(w0()),NY=Ee(v0());});var K0,QP=k(()=>{"use strict";Xd();K0=uu({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 ZP,eR,tR,rR,J0,_Y,yf,XP,Y0=k(()=>{"use strict";ZP=Ee(v0()),eR=Ee(lT()),tR=Ee(w0()),rR=Ee(IO()),J0=Ee(HP());Tu();YP();QP();_Y=60*1e3,yf=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=sn.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"?K0.prodEcsEndpoint:K0.integrationEcsEndpoint}client=new eR.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=ZP.StorageHelper.transientWithGlobalFallback,updateIntervalInMinutes:i,overrideEcsInitParams:o})=>{this.client.telemetryEventAdded.subscribe(this.logger.logEvent),this.client.configUpdated.subscribe(this.handleConfigUpdated);let a=(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:[tR.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:JP(this.clientName,n,this.endpointType),...o}),this.client.requestUpdate(),this._status===sn.NotLoaded&&(this._status=sn.Initialized)}catch(s){this._status=sn.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*_Y)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,J0.default)({},t.fallback,n,t.override,XP)};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 o=this.getConfig(t);(0,rR.default)(o,n)||(n={...o},r(o))});return{unsubscribe:()=>i.unsubscribe()}};waitUntilLoaded=async t=>{if(t!==void 0){let r,n=new Promise((i,o)=>{r=window.setTimeout(()=>{o(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,J0.default)({},this.client.getConfig()?.config,this.clientConfigOverride,XP);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=sn.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})}},XP=(e,t)=>{if(Array.isArray(t))return t}});var iR=v((cpe,nR)=>{"use strict";var TY=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};nR.exports=TY});var Q0=v((dpe,aR)=>{var Du=new Proxy(function(){return Du},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Du},apply:function(){return Du},construct:function(){return{}}}),oR=function(){return Du};Object.setPrototypeOf(oR,Du);aR.exports=oR});var uR=v((fpe,lR)=>{var Iu=new Proxy(function(){return Iu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Iu},apply:function(){return Iu},construct:function(){return{}}}),sR=function(){return Iu};Object.setPrototypeOf(sR,Iu);lR.exports=sR});var gR=v((ppe,hR)=>{"use strict";var X0=uR(),DY={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},IY={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},OY={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},pR={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},Z0={};Z0[X0.ForwardRef]=OY;Z0[X0.Memo]=pR;function cR(e){return X0.isMemo(e)?pR:Z0[e.$$typeof]||DY}var PY=Object.defineProperty,RY=Object.getOwnPropertyNames,dR=Object.getOwnPropertySymbols,LY=Object.getOwnPropertyDescriptor,kY=Object.getPrototypeOf,fR=Object.prototype;function mR(e,t,r){if(typeof t!="string"){if(fR){var n=kY(t);n&&n!==fR&&mR(e,n,r)}var i=RY(t);dR&&(i=i.concat(dR(t)));for(var o=cR(e),a=cR(t),s=0;s<i.length;++s){var l=i[s];if(!IY[l]&&!(r&&r[l])&&!(a&&a[l])&&!(o&&o[l])){var u=LY(t,l);try{PY(e,l,u)}catch{}}}}return e}hR.exports=mR});function bR(e,t,r){let[n,i]=(0,Os.useState)(e.getConfig(t));return(0,Os.useEffect)(()=>{if(!r?.subscribe&&e.status===sn.ConfigsLoaded)return;let o=e.subscribe(t,a=>{i(a),r?.subscribe||o.unsubscribe()});return o?.unsubscribe},[]),n}function vR(e){return function(t,r){return bR(e,t,r)}}function wR(e,t,r,n){let i=o=>{let a=bR(e,t,n),s={...o,...a};return Os.default.createElement(r,{...s})};return(0,yR.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function CR(e,t,r,n){return t.reduce((i,o)=>wR(e,o,i,n),r)}function ER(e){return function(t,r,n){return wR(e,t,r,n)}}var yR,Os,ey=k(()=>{"use strict";yR=Ee(gR()),Os=Ee(Q0());Tu();});var SR=v((gpe,AR)=>{var $Y=z0(),xY=H0(),FY=xY(function(e,t,r){$Y(e,t,r)});AR.exports=FY});var bf=v((ype,NR)=>{var MY=sa(),UY=vo(),BY="[object Symbol]";function qY(e){return typeof e=="symbol"||UY(e)&&MY(e)==BY}NR.exports=qY});var TR=v((bpe,_R)=>{var VY=bo(),GY=bf(),WY=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,zY=/^\w*$/;function jY(e,t){if(VY(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||GY(e)?!0:zY.test(e)||!WY.test(e)||t!=null&&e in Object(t)}_R.exports=jY});var OR=v((vpe,IR)=>{var DR=uf(),HY="Expected a function";function ty(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(HY);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],o=r.cache;if(o.has(i))return o.get(i);var a=e.apply(this,n);return r.cache=o.set(i,a)||o,a};return r.cache=new(ty.Cache||DR),r}ty.Cache=DR;IR.exports=ty});var RR=v((wpe,PR)=>{var KY=OR(),JY=500;function YY(e){var t=KY(e,function(n){return r.size===JY&&r.clear(),n}),r=t.cache;return t}PR.exports=YY});var kR=v((Cpe,LR)=>{var QY=RR(),XY=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ZY=/\\(\\)?/g,eQ=QY(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(XY,function(r,n,i,o){t.push(i?o.replace(ZY,"$1"):n||r)}),t});LR.exports=eQ});var xR=v((Epe,$R)=>{function tQ(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}$R.exports=tQ});var VR=v((Ape,qR)=>{var FR=bu(),rQ=xR(),nQ=bo(),iQ=bf(),oQ=1/0,MR=FR?FR.prototype:void 0,UR=MR?MR.toString:void 0;function BR(e){if(typeof e=="string")return e;if(nQ(e))return rQ(e,BR)+"";if(iQ(e))return UR?UR.call(e):"";var t=e+"";return t=="0"&&1/e==-oQ?"-0":t}qR.exports=BR});var WR=v((Spe,GR)=>{var aQ=VR();function sQ(e){return e==null?"":aQ(e)}GR.exports=sQ});var jR=v((Npe,zR)=>{var lQ=bo(),uQ=TR(),cQ=kR(),dQ=WR();function fQ(e,t){return lQ(e)?e:uQ(e,t)?[e]:cQ(dQ(e))}zR.exports=fQ});var KR=v((_pe,HR)=>{var pQ=bf(),mQ=1/0;function hQ(e){if(typeof e=="string"||pQ(e))return e;var t=e+"";return t=="0"&&1/e==-mQ?"-0":t}HR.exports=hQ});var QR=v((Tpe,YR)=>{var gQ=G0(),yQ=jR(),bQ=ff(),JR=ki(),vQ=KR();function wQ(e,t,r,n){if(!JR(e))return e;t=yQ(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var l=vQ(t[i]),u=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(i!=a){var c=s[l];u=n?n(c,l,s):void 0,u===void 0&&(u=JR(c)?c:bQ(t[i+1])?[]:{})}gQ(s,l,u),s=s[l]}return e}YR.exports=wQ});var ZR=v((Dpe,XR)=>{var CQ=QR();function EQ(e,t,r){return e==null?e:CQ(e,t,r)}XR.exports=EQ});function n2(e){let{query:t}=(0,r2.default)(window.location.href,!0);return SQ(e,t),e}function SQ(e,t){let r=AQ+e.clientName,n=Object.keys(t).filter(o=>o.startsWith(r));if(!n)return;let i={};n.forEach(o=>{let a=t[o];if(a)try{let s=JSON.parse(a),l=r+i2,u={};if(o===r)u=s;else if(o.startsWith(l)){let c=o.substring(l.length);(0,t2.default)(u,c,s)}(0,e2.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var e2,t2,r2,i2,AQ,o2=k(()=>{"use strict";e2=Ee(SR()),t2=Ee(ZR()),r2=Ee(s0());i2=".",AQ="ecs"+i2});function wf(e,t,r){let n=n2(new yf(e,t,r));function i(o){(0,vf.useEffect)(()=>{n.init(o)},[])}return{featuresClient:n,createFeature:_Q(n),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>CR(n,o,a,s)}}function _Q(e){let t=vR(e),r=ER(e);return function(i){let o=nT(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===sn.ConfigsLoaded,c0.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>r(o,a,s),feature:o}}}var NQ,vf,ry=k(()=>{"use strict";NQ=Ee(iR()),vf=Ee(Q0());b0();Y0();Tu();ey();o2();d0();});var a2=k(()=>{"use strict";b0();Y0();ry();Tu();ey();rf();f0();});function Cf(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,Ps.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,Ps.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,Ps.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var Ps,ny=k(()=>{"use strict";Ps=Ee(ra());});var Kpe,Jpe,Ype,s2=k(()=>{"use strict";a2();ny();({featuresClient:Kpe,createFeature:Jpe,useFeaturesClientInitParams:Ype}=wf("PowerApps-Shell-Test",Cf("shell-features")))});var c2=v((Xpe,u2)=>{var Ou=new Proxy(function(){return Ou},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Ou},apply:function(){return Ou},construct:function(){return{}}}),l2=function(){return Ou};Object.setPrototypeOf(l2,Ou);u2.exports=l2});var TQ,DQ,d2=k(()=>{"use strict";au();TQ=Ee(c2()),DQ=Ee(ra());});var f2=k(()=>{"use strict";s2();ny();d2();});var sme,Rs,lme,p2=k(()=>{"use strict";f2();ry();({featuresClient:sme,createFeature:Rs,useFeaturesClientInitParams:lme}=wf("PowerApps-MakerPortal",Cf("powerapps-features")))});var m2,h2,fme,pme,mme,hme,iy=k(()=>{"use strict";rT();p2();({feature:m2}=Rs({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:ws.enableAutoInsertionOfCellInRow}})),{feature:h2}=Rs({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:ws.enableOneGridEvents}}),{feature:fme}=Rs({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:ws.disablePBIComponents}}),{feature:pme}=Rs({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:ws.enableAgentResponse}}),{feature:mme,useFeature:hme}=Rs({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:ws.enableDelayedLocalizationForCustomControls}})});var b2=v((yme,y2)=>{var Pu=new Proxy(function(){return Pu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Pu},apply:function(){return Pu},construct:function(){return{}}}),g2=function(){return Pu};Object.setPrototypeOf(g2,Pu);y2.exports=g2});var Qt,wo=k(()=>{"use strict";pt();ot();Yt();fu();le();Dt();Qt=class extends re{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(y.colspan);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){R.IsNullOrUndefined(t)||this.setProperty(y.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(y.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}set id(t){this.setProperty(y.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(y.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(y.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}get Name(){return this.getProperty(y.Name)}set Name(t){this.setProperty(y.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(y.languagecode)===r){i.setProperty(y.description,t);return}let n=new re(C.formLabel,null);n.setProperty(y.description,t),n.setProperty(y.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(y.languagecode)===t)return r.getProperty(y.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(y.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(y.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(y.availableforphone)}set availableforphone(t){R.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(y.availableforphone,String(t))}get visible(){return this.getProcessedValue(y.visible)}set visible(t){R.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(y.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(y.showlabel)}set showlabel(t){R.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return R.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(C.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(C.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.DefaultViewId):q.EmptyString}set defaultviewid(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.DependentAttributeName):q.EmptyString}set dependentattributename(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.DependentAttributeType):q.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(C.formControl);if(t)return t.getParam(y.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.FilterRelationshipName):q.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(C.formControl);return t?t.getParam(y.AvailableViewIds):q.EmptyString}set availableviewids(t){let r=this.getFirstChild(C.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(C.formControl);if(t&&t.ClassId){let r=at.getUniqueIdentifierForControl(t);return!R.IsNullOrUndefined(r)&&at.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(C.formControl);if(t){let n=at.getUniqueIdentifierForControl(t).guidString,i=n===G.GridControl||n===G.TimeLineControl||n===G.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===C.formSection||this.NodeName===C.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(C.formControl);if(t){let n=at.getUniqueIdentifierForControl(t).guidString,i=n===G.MapsControl||n===G.WebResourceHtmlControl||n===G.WebResourceImageControl||n===G.IframeControl||n===G.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(C.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(C.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var Ls,oy=k(()=>{"use strict";Yt();le();Dt();Ls=class extends re{constructor(t,r){super(C.dependency,t),q.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}setDefaultProperties(t){this.id=t}}});var v2,ks,ay=k(()=>{"use strict";ot();oy();le();Dt();wo();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(v2||(v2={}));ks=class extends Qt{constructor(t,r){super(C.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(y.Name,t)}get eventName(){return this.getProperty(y.Name)}set application(t){this.setProperty(y.application,t)}get application(){return this.getProperty(y.application)}set attribute(t){this.setProperty(y.EventAttribute,t)}get attribute(){return this.getProperty(y.EventAttribute)}set relationship(t){this.setProperty(y.Relationship,t)}get relationship(){return this.getProperty(y.Relationship)}set control(t){this.setProperty(y.Control,t)}get control(){return this.getProperty(y.Control)}set active(t){this.setProperty(y.EventActive,t)}get active(){return this.getProperty(y.EventActive)}getAllHandlers(){let t=this.getChildren(C.EventHandlers);return t&&t.length?t[0].getChildren(C.handler):[]}getAllDependencies(){let t=this.getChildren(C.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(C.formDependencies);if(R.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new re(C.formDependencies,this)),r=this.getFirstChild(C.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new Ls(r,n.toString()))}}}});var In,Ru=k(()=>{"use strict";pt();Bl();ot();ta();le();Dt();_n();In=class extends re{previewVersion;constructor(t){super(C.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(y.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t)}set ClassId(t){this.setProperty(y.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(y.datafieldname)}set dataFieldName(t){this.setProperty(y.datafieldname,t)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}get UniqueId(){let t=this.getProperty(y.uniqueid);return R.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set UniqueId(t){this.setProperty(y.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(y.isRequired)==="true"}set isRequired(t){R.IsNullOrUndefined(t)||this.setProperty(y.isRequired,String(t))}get disableMru(){return this.getParam(y.DisableMru)==="true"}set disableMru(t){R.IsNullOrUndefined(t)||this.setParameter(y.DisableMru,t)}get useMFDForCreate(){return this.getParam(y.UseMFDForCreate)==="true"}set useMFDForCreate(t){R.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(y.UseMFDForEdit)==="true"}set useMFDForEdit(t){R.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForEdit,t)}get disabled(){return this.getProperty(y.disabled)==="true"}set disabled(t){R.IsNullOrUndefined(t)||this.setProperty(y.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(y.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(y.indicationOfSubgrid,String(t))}getAllParameters(){let t=new nr,r=this.getFirstChild(y.parameters);return r&&r.getAllChildren().forEach(n=>{if(n){let i=n.getAllChildren(),o=i&&i.length>0&&i[0];o&&t.add(n.getNodeName(),o.getNodeName())}}),t}setParameter(t,r){let n=!1;r===null&&(n=!0);let i=(Li.StartTag+r).toString(),o=this.parametersNode;if(o){let a=o.findFirst(s=>s&&s.getNodeName()===t);if(a)if(n){this.deleteFirstGrandChildOfName(C.controlParameters,a);return}else{let s=a.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):a.addChild(new re(i,a))}else n||(a=new re(t,o),a.addChild(new re(i,a)),o.addChild(a))}else if(!n){o=new re("parameters",this);let a=new re(t,o);a.addChild(new re(i,a)),o.addChild(a),this.addChild(o)}}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 o=i.getNodeName();return o.charAt(0)===Li.StartTag?o.substring(1):o}}}return null}get parametersNode(){let t=this.getChildren(y.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new nr;switch(this.ClassId.guidString.toUpperCase()){case N.LookupControl:if(t&&t.getKeys())if(t.getKeys().forEach(a=>{n.add(a,this.getParam(a))}),t&&t.containsKey("DefaultViewId")){let a=this.getParam("DefaultViewId").replace("{","").replace("}","");n.upsert("DefaultViewId",a)}else{let a=this.getParent(),s=await r.formModelService.lookupControlService.populateDefaultView(this,a.getParentForm().entityName);s&&s.id&&n.upsert("DefaultViewId",s.id.replace("{","").replace("}",""))}break;default:t&&t.getKeys()&&t.getKeys().forEach(a=>{n.add(a,this.getParam(a))});break}let i=n.getInternalObject(),o=[];for(let a in i)i.hasOwnProperty(a)&&o.push({Name:a,Value:i[a]});return o}getIsUnbound(){return this.getProperty(y.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case N.BooleanControl:case N.CheckboxControl:return 0;case N.DateTimeControl:return 2;case N.DecimalControl:return 3;case N.FloatingNumberControl:return 4;case N.IntegerControl:case N.DurationControl:case N.LanguageControl:case N.TimezoneControl:return 5;case N.LookupControl:return 6;case N.CurrencyControl:return 8;case N.PartyListControl:return 10;case N.ChoiceControl:case N.RelationshipRoleChoiceControl:return 11;case N.ChoiceStatusControl:return 13;case N.TextAreaControl:case N.TextboxControl:case N.LabelControl:case N.EmailAddressControl:case N.UrlControl:case N.TickerControl:case N.ButtonControl:case N.PhoneNumberControl:return 14;case N.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===mt.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 $s,sy=k(()=>{"use strict";Yt();zo();Ru();le();Dt();$s=class extends In{constructor(t){super(t)}get targetEntityType(){return this.getParam(y.targetEntityType)||q.EmptyString}set targetEntityType(t){this.setParameter(y.targetEntityType,t)}get viewId(){return q.StripBraces(this.getParam(y.viewId))||q.EmptyString}set viewId(t){this.setParameter(y.viewId,q.AddBraces(t))}get viewIds(){return this.getParam(y.viewIds)||q.EmptyString}set viewIds(t){this.setParameter(y.viewIds,t)}get relationshipName(){return this.getParam(y.RelationshipName)||q.EmptyString}set relationshipName(t){this.setParameter(y.RelationshipName,t)}get isUserView(){return q.IsStrictTrue(this.getParam(y.isUserView))}set isUserView(t){this.setParameter(y.isUserView,t.toString())}get enableViewPicker(){return q.IsStrictTrue(this.getParam(y.enableViewPicker))}set enableViewPicker(t){this.setParameter(y.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(y.autoExpand)===y.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(y.autoExpand,t?y.Auto:y.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(y.recordsPerPage)?Number(this.getParam(y.recordsPerPage)):Number(y.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(y.recordsPerPage,String(t))}get enableQuickFind(){return q.IsStrictTrue(this.getParam(y.enableQuickFind))}set enableQuickFind(t){this.setParameter(y.enableQuickFind,t)}get teamTemplateId(){return q.StripBraces(this.getParam(y.teamTemplateId))||q.EmptyString}set teamTemplateId(t){this.setParameter(y.teamTemplateId,q.AddBraces(t))}get chartId(){return this.getParam(y.visualizationId)||q.EmptyString}set chartId(t){this.setParameter(y.visualizationId,t)}get enableChartPicker(){return q.IsStrictTrue(this.getParam(y.enableChartPicker))}set enableChartPicker(t){this.setParameter(y.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(y.chartGridMode)){case an.Chart:return an.Chart;case an.Grid:return an.Grid;default:return an.All}}set chartGridMode(t){this.setParameter(y.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=an.Chart:this.chartGridMode=this.enableChartPicker?an.All:an.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case y.viewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.viewId));break;case y.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case y.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case y.RelationshipName:let i=n.getAllChildren(),o="<"+r.relationshipName;i.length?n.getAllChildren()[0].setNodeName(o):n.addChild(new re(o,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 o=n[i].getParameters().get(jt.dataset)?n[i].getParameters().get(jt.dataset)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var xs,ly=k(()=>{"use strict";Yt();zo();Ru();le();xs=class extends In{constructor(t){super(t)}get defaultViewId(){return q.StripBraces(this.getParam(y.DefaultViewId))||q.EmptyString}set defaultViewId(t){this.setParameter(y.DefaultViewId,q.AddBraces(t))}get autoResolve(){return q.IsStrictTrue(this.getParam(y.AutoResolve))}set autoResolve(t){this.setParameter(y.AutoResolve,t)}get disableQuickFind(){return q.IsStrictTrue(this.getParam(y.DisableQuickFind))}set disableQuickFind(t){this.setParameter(y.DisableQuickFind,t)}get disableViewPicker(){return q.IsStrictTrue(this.getParam(y.DisableViewPicker))}set disableViewPicker(t){this.setParameter(y.DisableViewPicker,t)}get allowFilterOff(){return q.IsStrictTrue(this.getParam(y.AllowFilterOff))}set allowFilterOff(t){this.setParameter(y.AllowFilterOff,t)}get disableMru(){return q.IsStrictTrue(this.getParam(y.DisableMru))}set disableMru(t){this.setParameter(y.DisableMru,t)}get dependentAttributeName(){return this.getParam(y.DependentAttributeName)||q.EmptyString}set dependentAttributeName(t){this.setParameter(y.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(y.DependentAttributeType)||q.EmptyString}set dependentAttributeType(t){this.setParameter(y.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(y.FilterRelationshipName)||q.EmptyString}set filterRelationshipName(t){this.setParameter(y.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(y.AvailableViewIds)||q.EmptyString}set availableViewIds(t){this.setParameter(y.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.datafieldname:case y.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case y.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.defaultViewId));break;case y.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case y.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case y.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case y.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case y.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case y.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case y.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case y.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case y.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 o=n[i].getParameters().get(jt.value)?n[i].getParameters().get(jt.value)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var w2,uy,_r,Lu=k(()=>{"use strict";w2=Ee(b2());wo();le();ot();pt();ay();Ru();fu();g0();Qg();_n();ta();gs();sy();ly();cy();rs();uy="_",_r=class e extends Qt{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(C.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,R.IsNullOrUndefined(this.getProperty(y.id))&&(this.id=new U(U.NewGuid()))}addControl(t,r,n,i,o,a,s){n instanceof In?this.addChild(n):n instanceof U&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,o,a,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!R.IsNullOrUndefined(this.control))return R.IsNullOrUndefined(this.control.dataFieldName)?R.IsNullOrUndefined(this.control.id)?!0:!na.dependencyFieldCount.containsKey(this.control.id):!na.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new ks(this,iu.onLoad))}get dependencies(){let t=this.getChildren(C.formEvents);for(let r of t){let n=r.getChildren(C.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let o;if(i&&Hd[i])o=Hd[i].replace(/ /g,uy)+uy;else{o="Control_";let u=new Error("Control class id does not exist or is undefined");(0,w2.trackErrorTrace)(sr,{eventName:`${b_}/getNextAvailableControlName`},u)}let a="new_",s=this.getHighestIndexById(t,i)+1,l=`${o}${a}${s}`;for(;n.has(l);)s++,l=`${o}${a}${s}`;return l}getUnboundControlProperties(t){e.prototype.setProperty.call(t,y.isUnbound,"true"),e.prototype.setProperty.call(t,y.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,o,a,s){let l;o===ln.Grid?(l=new $s(this),l.indicationOfSubgrid=!0):o===ln.Lookup?l=new xs(this):l=new In(this);let u=n.guidString,c=a||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,y.id,c),l.ClassId=n,!R.IsNullOrUndefined(s)&&(l.UniqueId=s),!a&&r)this.getUnboundControlProperties(l);else{let d=at.getUniqueIdentifierForControl(l);R.IsNullOrUndefined(d)||(at.getControlDataTypeByControlOrUniqueId(d)===ee.QuickFormCollectionControl||!at.isUnboundFormControlByIdentifier(d)?o!==ln.Grid&&a&&u!==N.IframeControl&&u!==N.SubgridControl&&u!==N.ReferencePanelSubgridControl&&(l.dataFieldName=a,e.prototype.setProperty.call(l,y.disabled,"false")):(this.rowspan=at.GetRowSpan(l),(at.getControlDataTypeByControlOrUniqueId(d)===ee.NotesControl||at.getControlDataTypeByControlOrUniqueId(d)===ee.TimeLineControl)&&(e.prototype.setProperty.call(l,y.disabled,"false"),l.id=ee.NotesControl)),(at.getUnboundControlNameFromIdentifier(n)===ee.SubGridControl||at.getUnboundControlNameFromIdentifier(n)===ee.NotesControl||at.getUnboundControlNameFromIdentifier(n)===ee.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(R.IsNullOrUndefined(t))return;let n=t.getAllChildren();for(let i of n){let o=i.getAllChildren();for(let a of o){let s=a.GetPropertyByParameter(y.id);a.getNodeName()===C.dependency&&s?r.push(s):this.buildDependencyList(a,r)}}}get control(){return this.getFirstChild(C.formControl)}set rowspan(t){this.setProperty(y.rowspan,String(t))}get rowspan(){let t=this.getProperty(y.rowspan);return R.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(y.auto,String(t))}get autoexpand(){return this.getProperty(y.auto)==="true"}set colspan(t){let r=Number(m0.ONE_COLUMN),n=Number(m0.FOUR_COLUMN);R.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(y.colspan,String(t))}get colspan(){let t=this.getProperty(y.colspan);return R.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(C.formRow)}getParentSection(){return this.getAncestor(C.formSection)}getParentTab(){return this.getAncestor(C.formTab)}getParentForm(){return this.getAncestor(C.form)}isInHeader(){let t=this.getAncestor(C.formHeader);return!R.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(C.formFooter);return!R.IsNullOrUndefined(t)}isEmpty(){return R.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(C.formHeader):this.isInFooter()?this.getAncestor(C.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(y.userspacer);return R.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(y.userspacer,"true")}ClearUserSpacer(){this.setProperty(y.userspacer,"false")}get columns(){let t=this.getProperty(y.columnName);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case ze.TWO_COLUMN:r="11";break;case ze.THREE_COLUMN:r="111";break;case ze.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(!R.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();R.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 o=i.isDuplicateCell(this,n),a=this.getRequiredLevel(t);if((a===io.ApplicationRequired||a===io.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?io.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??io.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()===C.formCell){let i=n;i.control&&i!==this&&r.add(n.control.id)}return!1}),r}getHighestIndexById(t,r){let n=t.findAll(o=>o.getNodeName()===C.formCell&&o.control&&o.control.ClassId.guidString===r),i=0;return n.forEach(o=>{i=Math.max(this.parseControlNameIndex(o.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)===uy&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var Fs,dy=k(()=>{"use strict";Yt();le();Dt();Fs=class extends re{isInternal;constructor(t,r,n,i){super(C.library,t),this.isInternal=!!i,q.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(y.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(y.libraryUniqueId,t)}get name(){return this.getProperty(y.libraryName)}set name(t){this.setProperty(y.libraryName,t)}get displayName(){return this.getProperty(y.displayName)}set displayName(t){this.setProperty(y.displayName,t)}get description(){return this.getProperty(y.description)}set description(t){this.setProperty(y.description,t)}}});var ua,fy=k(()=>{"use strict";ot();Lu();le();Dt();ua=class extends re{isRowAddedOnDragOver;constructor(t){super(C.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 R.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return R.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(C.formSection)}insertPaddingCellAtIndex(t){let r=new _r(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(C.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 IQ(e){switch(e){case ia.Left:return aa.Left;case ia.Right:return aa.Right;case ia.Center:return aa.Center;default:return aa.Left}}function OQ(e){switch(e){case bs.Left:return vs.Left;case bs.Top:return vs.Top;default:return vs.Left}}function C2(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var PQ,ri,ku=k(()=>{"use strict";y0();pt();ot();Yt();iy();Lu();le();_n();wo();fy();PQ=115,ri=class e extends Qt{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=ze.ONE_COLUMN;break;case 11:t=ze.TWO_COLUMN;break;case 111:t=ze.THREE_COLUMN;break;case 1111:t=ze.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=Ue.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+Ue.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(y.Name,r)}initializeDefaultProperties(t,r,n){if(n===ze.REFERENCE_PANEL){this.addProperty(y.rowheight,"25");let i=`${Ue.referencePanelNamePrefix}${U.NewGuid()}${Ue.namePrefix}`;this.addProperty(y.Name,i)}else this.setUniqueName();if(this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,Ue.IsUserDefined),this.addProperty(y.locklevel,Ue.LockLevel),this.addProperty(y.showlabel,Ue.ShowLabel),this.addProperty(y.showbar,Ue.ShowBar),this.addProperty(y.layout,Ue.Layout),this.addProperty(y.Fieldlabelalignment,Ue.labelAlignment),this.addProperty(y.Fieldlabelposition,Ue.labelPosition),R.IsNullOrUndefined(n))this.addProperty(y.columnName,Ue.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(y.columnName,i)}this.addProperty(y.LabelWidth,Ue.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case ze.TWO_COLUMN:r="11";break;case ze.THREE_COLUMN:r="111";break;case ze.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 R.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(q.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new ua(null);if(this.addGrandChild(C.formRows,r),m2.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new _r(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===ze.REFERENCE_PANEL&&(n=ze.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(C.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(C.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(C.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(C.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(C.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(C.formRows);return t.length===0?[]:t[0].getChildren(C.formRow)}get columns(){let t=this.getProperty(y.columnName),r=R.IsNullOrUndefined(t)?NaN:parseInt(t,10);if(isNaN(r)){let n=1;for(let i of this.rows)n=Math.max(n,i.cells.length);return C2(n)}return r}set columns(t){R.IsNullOrUndefined(t)||this.setProperty(y.columnName,String(t))}get rowHeight(){let t=this.getProperty(y.rowheight);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(y.rowheight,String(t))}set autoexpand(t){this.setProperty(y.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(y.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(y.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(y.IsUserDefined,"1"):this.setProperty(y.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(C.formColumn)}getParentTab(){return this.getAncestor(C.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(y.showlabel)==="true"}set showlabel(t){R.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}get fieldLabelAlignment(){let t=Ue.labelAlignment,r=this.getProperty(y.Fieldlabelalignment);return R.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){R.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(y.Fieldlabelposition);return R.IsNullOrUndefined(t)?Ue.labelPosition:t}set fieldLabelPosition(t){R.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(y.showbar)==="true"}set showbar(t){R.IsNullOrUndefined(t)||this.setProperty(y.showbar,String(t))}get labelwidth(){let t=+this.getProperty(y.LabelWidth);return t===0?PQ:t}set labelwidth(t){R.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(y.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:IQ(this.fieldLabelAlignment),Position:OQ(this.fieldLabelPosition)},Columns:C2(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()===C.formSection){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!R.IsNullOrUndefined(this)&&!R.IsNullOrUndefined(this.Name)&&this.Name.indexOf(Ue.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===C.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===C.formFooter||this.NodeName===C.formHeader}}});var Co,Ef=k(()=>{"use strict";le();Dt();ku();Co=class e extends re{constructor(t){super(C.formColumn,t)}initializeDefaultProperties(t){this.addProperty(y.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(C.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new ri(C.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(C.formSections,t,r)}initialize(t,r,n,i=ze.ONE_COLUMN){this.initializeDefaultProperties(t);let o=e.createAndInitNewSection(r,n,i);this.addSectionAtIndex(o,this.sections.length),o.setUniqueName()}get parentTab(){return this.getAncestor(C.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(C.formSection)}get width(){return this.getProperty(y.width)}set width(t){this.setProperty(y.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(C.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(y.Name),Id:this.getProperty(y.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(y.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var Af,E2=k(()=>{"use strict";pt();le();_n();ku();Af=class extends ri{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(y.Name,n),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.columnName,Ue.columns),this.setDisplayName(r,t)}}});var Sf,A2=k(()=>{"use strict";Ef();le();E2();Sf=class extends Co{addAndIntializeNavBarSection(t,r,n,i){let o=new Af(C.formSection,null);return o.initializeNavArea(t,r,i),this.addGrandChildAtIndex(C.formSections,o,n),o}}});var $i,Nf=k(()=>{"use strict";pt();ot();Yt();Ef();le();Dt();wo();$i=class extends Qt{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(C.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(C.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=We.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=We.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=We.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=We.TWO_COLUMN_WIDER_RIGHT;break}t=We.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=We.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=We.THREE_COLUMN_WIDER_MID;break}t=We.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(y.Name,ho.namePrefix+t.toString()),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,ho.IsUserDefined),this.addProperty(y.locklevel,ho.LockLevel),this.addProperty(y.showlabel,ho.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=ze.ONE_COLUMN,o=!0,a){let s=this.getChildren(C.formColumns)[0],l=[];switch(t){case We.ONE_COLUMN:l.push(100);break;case We.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case We.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case We.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case We.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case We.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new Co(s);c.initialize(u,r,n,i),this.addGrandChild(C.formColumns,c)}}initialize(t,r,n,i,o,a=ze.ONE_COLUMN,s=!0,l){this.addChild(new re(C.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,o,a,s,l)}get columns(){let t=this.getChildren(C.formColumns);return t.length!==1?[]:t[0].getChildren(C.formColumn)}get expanded(){return this.getProcessedValue(y.expanded)}set expanded(t){R.IsNullOrUndefined(t)||this.setProperty(y.expanded,String(t))}get groupName(){return this.getProperty(y.groupName)}get contentType(){return this.getProperty(y.contentType)}set contentType(t){this.setProperty(y.contentType,t)}insertNewColumnAtIndex(t,r,n,i,o){t.initialize(n,i,o),this.addGrandChildAtIndex(C.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(C.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(C.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()===C.formTab){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var ca,py=k(()=>{"use strict";pt();le();Dt();_n();A2();Nf();ca=class extends $i{constructor(t,r,n){super(t,We.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new U(U.NewGuid())}initializeDefaultProps(){this.addChild(new re(C.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(C.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 o of i.cells)if(o.NavId===t)return o;return null}initializeFiveColumns(){for(let t=0;t<nf.FIVE_COLUMN;t++){let r=new Sf(this.getChildren(C.formColumns)[0]);r.initializeDefaultProperties(G_.FiveEqColumn),this.addGrandChild(C.formColumns,r)}}}});function LQ(e){switch(e){case mt.Main:return go.Main;case mt.QuickCreate:return go.QuickCreate;case mt.QuickViewForm:return go.Quick;case mt.Dialog:return go.Dialog;default:return go.None}}function kQ(e,t){if(t===mt.Main){if(e)switch(e.toLowerCase()){case"low":return mo.Low;case"highreadonlyvalues":return mo.HighReadOnlyValues;default:return mo.HighWithControls}return mo.Low}}var Tf,RQ,_f,S2=k(()=>{"use strict";Q_();Tf=Ee(ra());y0();ot();Yt();gs();iy();le();zo();Mg();ta();Lu();le();wo();dy();py();Nf();RQ="1920";_f=class e extends Qt{_formUniqueName;isHeaderDefaulted;consistencyStrong=!1;_formId;_rawFormXml;_entityName;_entityDisplayName;_status;_formName;_langCode;_description;_formType;_formPresentation;parameters=[];_formactivationstate;_changeTracker;_metadataChangeEvent;_etag;constructor(t,r,n,i,o,a,s,l,u){super(C.form,null),this._formUniqueName=o,this._formId=t,this._entityName=r,this._status=n,this._formName=i,this._description=l,this._formType=a,this._formPresentation=s,this._formactivationstate=u,this._changeTracker=new Gd,this._metadataChangeEvent=new af}get FormLibraries(){let t=this.getFirstChild(C.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(o=>o instanceof _r).forEach(o=>{let a=o.events;a&&(t=t.concat(a))})}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 _r){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()===C.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let o=i.GetPropertyByParameter(n).replace("$webresource:",""),a=new Fs(void 0,void 0,"",!0);return a.name=o,a.displayName=o,a})),r}getDependentFields(){let t=this.getAllEvents(),r=new Set;return t.forEach(n=>{try{n.getAllDependencies().forEach(o=>{r.add(o.id)})}catch(i){throw(0,Tf.trackErrorTrace)(v_,{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 q.IsNullOrEmpty(this.getProperty(y.ShowImage))?!0:this.getProperty(y.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(y.ShowImage,String(t)):this.setProperty(y.ShowImage,"false")}get ShowNavigation(){return q.IsNullOrEmpty(this.getProperty(y.ShowNavigationbar))?!0:this.getProperty(y.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(y.ShowNavigationbar,String(t)):this.setProperty(y.ShowNavigationbar,"false")}get MaxWidth(){return q.IsNullOrEmpty(this.getProperty(y.MaxWidth))?RQ:this.getProperty(y.MaxWidth)}set MaxWidth(t){this.setProperty(y.MaxWidth,t)}get headerDensityType(){return this.getProperty(y.HeaderDensityType)}set headerDensityType(t){t&&this.formType===mt.Main?this.setProperty(y.HeaderDensityType,t):this.formType!==mt.Main&&this.headerDensityType&&this.removeProperty(y.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===mt.Main||this.formType===mt.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(C.formHeader);return t.length!==1?null:t[0]}set header(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(C.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(C.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return R.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(C.formFooter);return t.length!==1?null:t[0]}set footer(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new $i(null,t),o=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,o,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(C.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,o){let a=new $i(null,We.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);a.initialize(We.ONE_COLUMN,s,this.LanguageCode,r,n,o,!1),this.addGrandChildAtIndex(C.formTabs,a,i);let l=a.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===ho.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(C.formTabs);return t.length!==1?[]:t[0].getChildren(C.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof ca)return t}return null}get NavigationNode(){let t=this.getChildren(C.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(C.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(C.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(C.formTabs);if(!R.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(C.formFooter).length>0}get displayCondition(){let t=this.getChildren(C.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(C.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(C.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(C.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);R.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(C.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 _r))return!1;let o=!0;return r==="Tab"?o=i.getParentTab()!==t.getParentTab():r==="Section"?o=i.getParentSection()!==t.getParentSection():o=i!==t,i instanceof _r&&i.control&&t.control&&o&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==N.CustomControl?!1:this.cellHasCustomControlWithName(t,_i.EditableGridControl)||h2.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,_i.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===N.CustomControl&&this.cellHasCustomControlWithName(t,_i.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()===C.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 o of r)if(!(o instanceof ca)){let a=o.toJSON(t);n.push(a)}for(let o of n)i.push(await o)}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,Tf.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===mt.Main?{HeaderDensity:kQ(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:LQ(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 Df,my,N2=k(()=>{"use strict";pt();ot();le();Dt();wo();Df=class extends Qt{constructor(t){super(C.formDisplayConditions,t)}get Order(){let t=this.getProperty(y.Order);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(y.Order,t.toString())}get FallbackForm(){return this.getProperty(y.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(y.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(C.formEveryOne)&&this.getChildren(C.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new my(this))}},my=class extends re{constructor(t){super(C.formEveryOne,t)}}});var If,_2=k(()=>{"use strict";le();Dt();If=class extends re{constructor(t,r){super(C.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(y.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(y.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(y.functionName)}set FunctionName(t){this.setProperty(y.functionName,t)}get LibraryName(){return this.getProperty(y.libraryNameEventHandler)}set LibraryName(t){this.setProperty(y.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(y.enabledForField)}set Enabled(t){this.setProperty(y.enabledForField,t)}get PassExecutionContext(){return this.getProperty(y.passExecutionContext)}set PassExecutionContext(t){this.setProperty(y.passExecutionContext,t)}get Parameters(){return this.getProperty(y.parameters)}set Parameters(t){this.setProperty(y.parameters,t)}}});var Ms,hy=k(()=>{"use strict";le();ku();Ms=class extends ri{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(C.formCell);for(let o of i)r.push(o)}}return r}get occupiedCells(){return this.cells.filter(t=>!t.isEmpty())}get maxColumns(){return super.getColumnCountValue()}}});var $u,T2=k(()=>{"use strict";le();hy();$u=class extends Ms{_customFooter;constructor(t,r){super(C.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 xu,D2=k(()=>{"use strict";le();hy();xu=class extends Ms{_customHeader;constructor(t,r){super(C.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(y.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(y.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(y.showBody)}set showBody(t){t!=null&&this.setProperty(y.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(y.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(y.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 Tr,da=k(()=>{"use strict";pt();Yt();le();wo();Tr=class e extends Qt{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(y.LCID)===t)return r.getProperty(y.text);return null}getAllTitles(){let t=this.getChildren(C.Titles);return t.length===0?[]:t[0].getChildren(C.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(y.LCID)===r){i.setProperty(y.text,t);return}let n=new e(C.Title,null);n.setProperty(y.text,t),n.setProperty(y.LCID,String(r)),this.addGrandChild(C.Titles,n)}get Sequence(){return+this.getProperty(y.Sequence)}set Sequence(t){this.setProperty(y.Sequence,t.toString())}get Area(){return this.getProperty(y.Area)}set Area(t){this.setProperty(y.Area,t)}set Id(t){this.setProperty(y.Id,t)}get Id(){return this.getProperty(y.Id)}get id(){return new U(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(y.icon)}set Icon(t){t=t||q.EmptyString,this.setProperty(y.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var Fu,I2=k(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(Fu||(Fu={}))});var Of,O2=k(()=>{"use strict";ot();le();da();I2();Of=class extends Tr{constructor(t){super(C.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 R.IsNullOrUndefined(r)?Fu.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):Fu.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 xe,$Q,P2,a0e,Us,gy=k(()=>{"use strict";pt();le();da();(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"})(xe||(xe={}));$Q=new Map([[xe.Info,"Info"],[xe.Sales,"Sales"],[xe.Service,"Service"],[xe.Marketing,"Marketing"],[xe.ProcessCenter,"ProcessCenter"]]),P2=new Map([["Info",xe.Info],["Sales",xe.Sales],["Service",xe.Service],["Marketing",xe.Marketing],["ProcessCenter",xe.ProcessCenter]]),a0e=new Map([[xe.Info,9e3],[xe.Sales,9200],[xe.Service,9400],[xe.Marketing,9600],[xe.ProcessCenter,9800],[xe.InternetMarketing,1e4],[xe.Async,10200]]),Us=class extends Tr{constructor(t,r){super(C.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=$Q.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(C.formNavigation)}get AreaId(){return this.getProperty(y.Id)}set AreaId(t){this.setProperty(y.Id,t)}get id(){return new U(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 Bs,yy=k(()=>{"use strict";le();da();Bs=class extends Tr{constructor(t,r){super(C.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(C.formNavBarArea)}get ParentNavigation(){return this.getAncestor(C.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var Pf,R2=k(()=>{"use strict";ot();le();da();Pf=class extends Tr{RelationshipNameUCIRuntime;constructor(t){super(C.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(y.RelationshipName)}set RelationshipName(t){this.setProperty(y.RelationshipName,t)}set Show(t){this.setProperty(y.Show,String(t))}get Show(){let t=this.getProperty(y.Show);return R.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(y.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 Rf,L2=k(()=>{"use strict";le();da();Rf=class extends Tr{constructor(t){super(C.formNavBarItem,t)}get Url(){return this.getProperty(y.url)}set Url(t){this.setProperty(y.url,t)}}});var Lf,k2=k(()=>{"use strict";pt();le();gy();yy();da();Lf=class extends Tr{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(C.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[xe.Info,xe.Sales,xe.Service,xe.Marketing,xe.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let o=new Set(i.map(a=>P2.get(a.AreaId)));n=n.filter(a=>!o.has(a))}}else{let i=new Bs(C.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let o=new Us(C.formNavBarArea,this.navBarAreas);o.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(o)}),!0):!1}get navBar(){return this.getFirstChild(C.formNavBar)}get id(){return new U(Yg,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(C.formNavBarAreas,r),this.addGrandChildAtIndex(C.formNavBarAreas,r,t))}async getNavBarAreasJSON(t){let r=[],n=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let o of this.navBarAreas.AllNavBarAreaItems)n.push(o.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 $2={};Hr($2,{ControlType:()=>ln,DeserializationService:()=>wy,DeserializationServiceScope:()=>vy,DeserializedFormElementNode:()=>Dr});var by,Dr,vy,ln,wy,cy=k(()=>{"use strict";by=Ee(ra());pt();ot();Yt();gs();Qg();ta();w_();J_();fu();S2();Lu();Ef();Ru();oy();le();le();N2();Dt();_n();ay();_2();T2();sy();ly();D2();dy();fy();ku();Nf();O2();gy();yy();R2();L2();k2();Dr=class extends re{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},vy="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(ln||(ln={}));wy=class{lcid;constructor(t){this.lcid=t}deSerializeFormXml(t,r,n,i,o,a,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,by.trackErrorTrace)(sr,{eventName:vy,eventData:{error:m}}),new Error(m)}let f=this.createFormModel(d.item(0),r,n,i,o,a,s,l,u,c);return R.IsNullOrUndefined(f.displayCondition)&&s!==mt.Dialog&&this.appendDefaultDisplayCondition(f),f}upsertFieldCount(t,r){let n=na.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(!R.IsNullOrUndefined(t)){let n=R.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,o,a,s,l,u,c){let d=new _f(r,n,i,o,a,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===mt.Main&&(this.insertHeaderFooterElementProperties(C.formHeader,d,d.header),this.insertHeaderFooterElementProperties(C.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(R.IsNullOrUndefined(n)){let i=t===C.formHeader?new xu(r,!0):new $u(r,!0);Dr.prototype.insertProperty.call(i,y.id,"{"+U.NewGuid()+"}"),Dr.prototype.insertProperty.call(i,y.Fieldlabelposition,"Top"),Dr.prototype.insertProperty.call(i,y.columnName,Ue.MarginalControlColumns),Dr.prototype.insertProperty.call(i,y.LabelWidth,Ue.LabelWidth),Dr.prototype.insertProperty.call(i,y.Fieldlabelalignment,"Left");let o=null,a=new ua(o);for(let s=0;s<i.maxColumns;s++){let l=new _r(a);Dr.prototype.insertProperty.call(l,y.id,"{"+U.NewGuid()+"}"),l.setDisplayName(q.EmptyString,this.lcid),Dr.prototype.insertProperty.call(l,y.showlabel,"false"),a.addCell(l)}i.appendRow(a),t===C.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 Dr(`<${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,by.trackErrorTrace)(sr,{eventName:vy,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(Dr.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===C.formCell&&i.name===y.auto&&i.value==="true"&&t.setAutoExpandDetailsForTab())}}populateElementChildren(t,r){for(let n=0;n<r.length;n++){let i=r.item(n),o=this.deSerializeFormXmlNode(i,t);o&&Dr.prototype.insertChild.call(t,o)}}createModelNode(t,r){switch(t.nodeName){case C.form:throw new Error("Form node shouldn't be created using this method");case C.formTab:return new $i(r);case C.formColumn:return new Co(r);case C.formHeader:return new xu(r,!1);case C.formFooter:return new $u(r,!1);case C.formSection:return new ri(C.formSection,r);case C.formRow:return new ua(r);case C.formCell:return new _r(r);case C.formControl:let n=t.attributes,i=t.childNodes.length>0?t.childNodes[0].childNodes:null,o;for(let s=0;s<n.length;s++){let l=n.item(s);if(l.name===y.indicationOfSubgrid&&l.value==="true"||l.name===y.classid&&(l.value?.toLocaleUpperCase()===`{${N.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${N.ReferencePanelSubgridControl}}`))o=ln.Grid;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.LookupControl}}`)o=ln.Lookup;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===y.DefaultViewId&&(o=ln.Lookup)}return o===ln.Grid?new $s(r):o===ln.Lookup?new xs(r):new In(r);case C.formEvent:return new ks(r,q.EmptyString);case C.dependency:return this.populateDependencyTable(t),new Ls(r,q.EmptyString);case C.Handler:let a=[];return new If(a,r);case C.formNavigation:return new Lf(t.nodeName,r);case C.formNavBarArea:return new Us(t.nodeName,r);case C.formNavBarAreas:return new Bs(t.nodeName,r);case C.formNavBar:return new Of(r);case C.formNavBarByRelationshipItem:return new Pf(r);case C.formNavBarItem:return new Rf(r);case C.formDisplayConditions:return new Df(r);case C.library:return new Fs(r,q.EmptyString,q.EmptyString);case C.controlDescription:return new Kd(r);case C.customControl:return this.populateCustomControlConfigurationId(t),new of(r);default:return new Dr(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===y.id&&this.upsertFieldCount(i.value,Xn.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===y.id){let o=new U(i.value.substr(1,i.value.length-2));for(let a=0;a<t.parentNode.attributes.length;a++){let s=t.parentNode.attributes.item(a);if(s.name===y.ForControl){let l=s.value.substr(1,i.value.length-2);at.CustomControlIdMap.upsert(l,o);break}}break}}}}});var x2={};Hr(x2,{SerializationService:()=>Cy,SerializationServiceScope:()=>xQ,SerializedFormElementNode:()=>qs});var xQ,qs,Cy,F2=k(()=>{"use strict";Yt();Dt();_n();py();xQ="SerializationService",qs=class extends re{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},Cy=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=qs.prototype.fetchNodeName.call(t);if(r.charAt(0)===Li.StartTag)return q.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return q.EmptyString;let n=qs.prototype.enumerateProperties.call(t),i=qs.prototype.enumerateChildren.call(t);if(!(t instanceof ca)){let o=`<${r}`;if(n.length!==0&&(o+=` ${this.getPropertiesString(n)}`),i.length===0)o+=" />";else{let a=q.EmptyString;for(let s of i)a+=this.serializeFormXmlNode(s);o+=`>${a}</${r}>`}return o}return q.EmptyString}getPropertiesString(t){let r=q.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${q.EscapeXml(n.value,!0)}"`}),r}}});var Ny=v(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.completeRecordAsStored=Vs.completeLabelsAsStored=void 0;var Ey=uo(),FQ="E7A81278-8635-4D9E-8D4D-59480B391C5B",MQ=new Set(["tab","section","cell"]);function On(e){let t=[];for(let r=e.firstChild;r;r=r.nextSibling)r.nodeType===1&&t.push(r);return t}function Eo(e,t){return On(e).find(r=>r.tagName===t)}function U2(e,t){return e.length===t.length&&e.every((r,n)=>r.tagName===t[n].tagName)}function Ay(e){let t=Eo(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===FQ:!1}function Sy(e,t){var r,n;let i=((r=Eo(e,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"";return i!==""&&i===(((n=Eo(t,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"")}function UQ(e,t){if(Eo(e,"labels"))return;let r=On(e),n=On(t),i=n[0];if(!i||i.tagName!=="labels"||n.length!==r.length+1||!U2(r,n.slice(1)))return;let o=On(i);if(!(o.length===0||o.some(s=>s.tagName!=="label"||!s.hasAttribute("description")||!s.hasAttribute("languagecode"))||!(e.tagName==="cell"&&Ay(e)&&Sy(e,t))&&o.some(s=>s.getAttribute("description")!=="")))return i}function BQ(e,t){let r=qQ(e.ownerDocument,t),n=On(e)[0];n?e.insertBefore(r,n):e.appendChild(r)}function qQ(e,t){let r=e.createElement("labels");for(let n of On(t))r.appendChild(B2(e,n));return r}function B2(e,t){let r=e.createElement("label");for(let n=0;n<t.attributes.length;n+=1){let{name:i,value:o}=t.attributes[n];(i==="description"||i==="languagecode")&&r.setAttribute(i,o)}return r}function M2(e,t){let r=Eo(e,"labels");return r?On(r).find(n=>n.tagName==="label"&&n.getAttribute("languagecode")===String(t)):void 0}function VQ(e,t,r){if(e.tagName!=="cell"||!Ay(e)||!Sy(e,t))return!1;let n=M2(e,r),i=M2(t,r),o=i?.getAttribute("description")||"";return!n||!n.hasAttribute("description")||(n.getAttribute("description")||"")!==""||o===""?!1:(n.setAttribute("description",o),!0)}function GQ(e,t){if(e.tagName!=="cell"||!Ay(e)||!Sy(e,t))return;let r=Eo(e,"labels"),n=Eo(t,"labels");if(!r||!n)return;let i=On(r),o=On(n),a=f=>f.tagName==="label"&&f.hasAttribute("description")&&f.hasAttribute("languagecode");if(o.length<=i.length||!i.every(a)||!o.every(a))return;let s=new Map(i.map(f=>[f.getAttribute("languagecode")||"",f]));if(s.size!==i.length)return;let l=new Set,u=0,c=[],d=[];for(let f of o){let m=f.getAttribute("languagecode")||"";if(l.has(m))return;l.add(m);let p=s.get(m);if(!p){d.push(f);continue}if((p.getAttribute("description")||"")!==(f.getAttribute("description")||""))return;u+=1,c.push(...d.map(h=>({label:h,before:p}))),d=[]}return c.push(...d.map(f=>({label:f}))),u===i.length?c:void 0}function q2(e,t,r,n){if(e.tagName!==t.tagName)return;if(MQ.has(e.tagName)){let a=UQ(e,t);a&&(BQ(e,a),n.changed=!0),VQ(e,t,r)&&(n.changed=!0);let s=GQ(e,t),l=Eo(e,"labels");if(s&&l){for(let{label:u,before:c}of s){let d=B2(e.ownerDocument,u);c?l.insertBefore(d,c):l.appendChild(d)}n.changed=!0}}let i=On(e),o=On(t);U2(i,o)&&i.forEach((a,s)=>q2(a,o[s],r,n))}function V2(e,t,r){if(e===t)return e;let n,i;try{n=(0,Ey.parseXmlRoot)(e,""),i=(0,Ey.parseXmlRoot)(t,"")}catch{return e}let o={changed:!1};return q2(n,i,r,o),o.changed?(0,Ey.serializeNode)(n):e}Vs.completeLabelsAsStored=V2;function WQ(e,t,r){let n=e?.formxml,i=t?.formxml;if(typeof n!="string"||typeof i!="string")return e;let o=V2(n,i,r);return o===n?e:{...e,formxml:o}}Vs.completeRecordAsStored=WQ});var lL=v(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.pcfReadIssues=ue.pcfBindingIssues=ue.commitPcfState=ue.mayCommitPcfState=ue.reconcilePcfDescriptions=ue.customControlNeeds=ue.mintPcfIdentity=ue.planPcfBinding=ue.projectPcfBindings=ue.supportsPcfFormType=ue.storedBindingOf=ue.hasCustomControl=ue.sameAsStored=ue.readPcfDescription=ue.newPcfDescription=ue.editorText=ue.nativeClassFor=ue.pcfEntryLayout=void 0;var zQ=(fu(),Fr(Y_)),jQ=Q(),G2=dt(),V=wd(),HQ=Uh(),Ce=en(),Mi=["web","phone","tablet"],Mu={web:"2",phone:"0",tablet:"1"},K2=new Map([["2","web"],["0","phone"],["1","tablet"]]),KQ=["phone","web","tablet"];function $f(e){let t=new Set(e),r=KQ.filter(n=>!t.has(n));return{defaults:r.length===0?[null]:r,named:Mi.filter(n=>t.has(n))}}ue.pcfEntryLayout=$f;function lr(e){return Array.isArray(e)?e:[]}function st(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Uu(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ty(e){return{n:`<${e}`,a:[],c:[]}}function J2(e){return typeof e?.n=="string"&&e.n.startsWith("<")}function W2(e){let t=lr(e.c);return t.length===1&&J2(t[0])&&(0,V.rawText)(e)!==""?(0,V.rawText)(e):void 0}function cn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Y2(e){return`{${e.replace(/^\{|\}$/g,"").toUpperCase()}}`}function Dy(e){try{let t=(0,zQ.mapFieldTypeToControl)(e.attributeTypeName,e.format);return t?Y2(String(t)):void 0}catch{return}}ue.nativeClassFor=Dy;var Iy=new Map([["Whole.None",{digits:0,min:-2147483648,max:2147483647}],["Whole.Duration",{digits:0,min:0,max:2147483647}],["Decimal",{digits:7,min:-922337203685477,max:922337203685477}],["FP",{digits:5,min:-1e11,max:1e11}],["Currency",{digits:4,min:-1e11,max:1e11}]]),Q2=new Set(["TwoOptions","Boolean"]),X2=new Set(["SingleLine.Text","SingleLine.TextArea","SingleLine.Email","SingleLine.Phone","SingleLine.URL","SingleLine.Ticker","Multiple"]),JQ=new Map([...[...X2].map(e=>[e,100]),["SingleLine.TextArea",2e3],["Multiple",1048576]]),YQ=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function Z2(e){return YQ.test(e)&&e!=="__proto__"}function Oy(e){return e!==void 0&&(e==="Enum"||Iy.has(e)||Q2.has(e)||X2.has(e))}function eL(e){return typeof e=="number"?e:e!==""&&!Number.isNaN(Number(e))?Number(e):void 0}function Bu(e,t){let r=e!==void 0?Iy.get(e):void 0;if(r&&typeof t!="boolean"){let n=eL(t);if(n!==void 0)return n.toFixed(r.digits)}return typeof t=="boolean"?t?"true":"false":String(t)}ue.editorText=Bu;function QQ(e,t,r){var n;let i=[];for(let o of e.properties){let a=o.name,s;if(o.isPrimary?s=t:o.usage==="input"&&Uu(r,a)?s=Bu(o.defaultType,r[a]):s=(n=o.defaultValue)!==null&&n!==void 0?n:"",s==="")continue;let l=[];o.defaultType&&l.push(["type",o.defaultType]),!o.isPrimary&&(o.defaultType==="Enum"||o.usage==="input")&&l.push(["static","true"]),i.push({n:a,a:l,c:[Ty(s)]})}return i}function tL(e,t,r,n,i){var o,a;let s=(o=n.formFactors)!==null&&o!==void 0?o:Mi.filter(d=>Py(i).has(d)),l=$f(s),u=QQ(i,t,(a=n.parameters)!==null&&a!==void 0?a:{}),c=d=>JSON.parse(JSON.stringify(d));return{n:"controlDescription",a:[["forControl",e]],c:[...l.defaults.map(d=>({n:"customControl",a:d===null?[["id",r]]:[["id",r],["formFactor",Mu[d]]],c:[{n:"parameters",a:[],c:[{n:"datafieldname",a:[],c:[Ty(t)]}]}]})),...l.named.map(d=>({n:"customControl",a:[["name",n.name],["formFactor",Mu[d]]],c:[{n:"parameters",a:[],c:c(u)}]}))]}}ue.newPcfDescription=tL;function Py(e){return new Set(Mi.filter(t=>e.availableOn[t]))}function kf(e){var t;let r=lr(e.c);if(r.length!==1||((t=r[0])===null||t===void 0?void 0:t.n)!=="parameters"||lr(r[0].a).length>0)return;let n=lr(r[0].c);return n.every(i=>st(i)&&!J2(i))?n:void 0}function fa(e){let t=lr(e?.c);if(t.length===0||!t.every(p=>st(p)&&p.n==="customControl"))return;let r=t.findIndex(p=>(0,V.rawAttr)(p,"name")!==void 0);if(r<=0)return;let n=t.slice(r),i=(0,V.rawAttr)(n[0],"name"),o=[];for(let p of n){let h=lr(p.a),g=h.length===2?K2.get(h[1][1]):void 0;if(!g||h[0][0]!=="name"||h[0][1]!==i||h[1][0]!=="formFactor"||o.includes(g))return;o.push(g)}let a=$f(o);if(!cn(a.named,o)||i==="")return;let s=kf(n[0]);if(!s||!n.every(p=>cn(kf(p),s)))return;let l=t.slice(0,r);if(l.length!==a.defaults.length)return;let u=(0,V.rawAttr)(l[0],"id"),c;for(let p=0;p<l.length;p+=1){let h=a.defaults[p],g=h===null?[["id",u??""]]:[["id",u??""],["formFactor",Mu[h]]],b=kf(l[p]),w=b?.length===1&&b[0].n==="datafieldname"&&lr(b[0].a).length===0?W2(b[0]):void 0;if(!u||!cn(lr(l[p].a),g)||w===void 0||c!==void 0&&w!==c)return;c=w}let d={},f={},m;for(let p of s){let h=lr(p.a),g=W2(p),b=h.map(w=>w[0]);if(g===void 0||!Z2(p.n)||Uu(d,p.n)||p.n===m)return;if((0,V.rawAttr)(p,"static")===void 0){if(m!==void 0||g!==c||!(b.length===0||cn(b,["type"])))return;m=p.n;continue}if((0,V.rawAttr)(p,"static")!=="true"||!(cn(b,["static"])||cn(b,["type","static"])))return;d[p.n]=g,f[p.n]=(0,V.rawAttr)(p,"type")}if(!(m===void 0||c===void 0||u===void 0))return{binding:{name:i,...Object.keys(d).length>0?{parameters:d}:{},...o.length===Mi.length?{}:{formFactors:o}},fieldName:c,nativeClass:u,parameterTypes:f,boundProperty:m}}ue.readPcfDescription=fa;function rL(e,t,r){return e===t?!0:typeof e!="string"&&(t===String(e)||t===Bu(r,e))}function nL(e){let t=e.formFactors;return t===void 0?[...Mi]:Array.isArray(t)?Mi.filter(r=>t.includes(r)):[]}function _y(e,t){var r,n,i;if(e.name!==t.binding.name||!cn(nL(e),(r=t.binding.formFactors)!==null&&r!==void 0?r:Mi))return!1;let o=(n=e.parameters)!==null&&n!==void 0?n:{},a=(i=t.binding.parameters)!==null&&i!==void 0?i:{},s=Object.keys(o);return s.length!==Object.keys(a).length?!1:s.every(l=>Uu(a,l)&&rL(o[l],a[l],t.parameterTypes[l]))}ue.sameAsStored=_y;function ht(e){return st(e)&&e.customControl!==void 0}ue.hasCustomControl=ht;function Fi(e,t){var r;return t?lr((r=(0,V.descriptionsRegion)(e))===null||r===void 0?void 0:r.node.c).filter(n=>n?.n==="controlDescription"&&(0,V.normGuid)((0,V.rawAttr)(n,"forControl"))===t):[]}function Ry(e,t){let r=Fi(e.bag,(0,V.controlUniqueId)(t));return r.length===1?fa(r[0]):void 0}ue.storedBindingOf=Ry;function Ly(e){let t=(0,V.effectiveFormType)(e);return t==="Main"||t==="QuickCreate"}ue.supportsPcfFormType=Ly;function XQ(e){if(!Ly(e))return;let t=(0,V.controlUniqueIds)(e);for(let{cell:r}of(0,V.typedCellSites)(e)){let n=r.control;if(!st(n)||!n.fieldName||!xi(n.classId)||t.get((0,V.controlUniqueId)(n))!==1)continue;let i=Ry(e,n);i&&i.fieldName===n.fieldName&&(n.customControl=JSON.parse(JSON.stringify(i.binding)))}}ue.projectPcfBindings=XQ;function xi(e){return typeof e=="string"&&e.replace(/^\{|\}$/g,"").toUpperCase()===V.CUSTOM_CONTROL_CLASS_ID}var un=(e,t)=>({kind:"refused",rule:e,message:t});function ZQ(e){let t=e.replace(/^\{|\}$/g,"");return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)&&!xi(e)}function z2(e,t,r){var n,i;let o=fa(r);if(!o)return un("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");if(o.fieldName!==e.fieldName)return un("pcf-binding-rebind",`the binding is filed for "${o.fieldName}": remove it, push, then bind the new column`);if(t.name!==o.binding.name)return un("pcf-binding-control-swap",`the binding uses "${o.binding.name}": to use another control, remove customControl, push, then add it`);let a=st(t.parameters)?t.parameters:{},s=(n=o.binding.parameters)!==null&&n!==void 0?n:{},l=Object.keys(a).sort();if(!cn(l,Object.keys(s).sort()))return un("pcf-binding-edit-parameter-set",`an edit changes parameter values only \u2014 the binding stores exactly ${Object.keys(s).sort().map(g=>`"${g}"`).join(", ")||"none"}: to add or remove one, remove the binding, push, then add it`);let u=l.filter(g=>!rL(a[g],s[g],o.parameterTypes[g])),c=u.find(g=>Bu(o.parameterTypes[g],a[g]).trim()==="");if(c!==void 0)return un("pcf-binding-edit-parameter-set",`"${c}" cannot be cleared in place \u2014 an empty value is not written, which removes the parameter: remove the binding, push, then add it`);let d=nL(t),f=(i=o.binding.formFactors)!==null&&i!==void 0?i:[...Mi],m=d.filter(g=>!f.includes(g)),p=f.filter(g=>!d.includes(g));if(u.length===0&&m.length===0&&p.length===0)return{kind:"unchanged"};let h=u.find(g=>!Oy(o.parameterTypes[g]));if(h!==void 0){let g=o.parameterTypes[h];return un("pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which the property editor does not write: remove the binding, push, then add it`)}return(m.length>0||p.length>0)&&!ZQ(o.nativeClass)?un("pcf-binding-edit-fallback",`the factors the control leaves fall back to "${o.nativeClass}", which is not a native control class: remove the binding, push, then add it`):{kind:"edit",description:r,stored:o,changed:u,factors:d,added:m,removed:p}}function eX(e,t){return t&&(0,V.typedCellSites)(e).find(({cell:n})=>ht(n.control)&&(0,V.controlUniqueId)(n.control)===t)?{descriptions:Fi(e.bag,t)}:void 0}function iL(e,t){let r=new Map,n=tX(e),i=new Set,o=new Map,a=u=>{let c=o.get(u);return c||(c={before:[],now:[]},o.set(u,c)),c},s=(u,c)=>({cell:iX(u),uid:(0,V.controlUniqueId)(c),bound:ht(c)});for(let{cell:u}of(0,V.typedCellSites)(e)){let c=u.control;st(c)&&typeof c.id=="string"&&c.id&&a(c.id).now.push({...s(u,c),control:c})}for(let{cell:u}of(0,V.typedCellSites)(t)){let c=u.control;if(!st(c))continue;let d=s(u,c);d.bound&&d.uid&&i.add(d.uid),typeof c.id=="string"&&c.id&&a(c.id).before.push(d)}let l=(u,c)=>{let d=u.filter(f=>f.cell===c);return d.length===1?d[0]:void 0};for(let[u,{before:c,now:d}]of o){let f=c.filter(D=>D.bound&&D.uid!==""&&!n.has(D.uid));if(f.length===0||d.length===0)continue;let m=[...c],p=D=>{let O=m.findIndex(D);return O<0?void 0:m.splice(O,1)[0]},g=d.filter(D=>!D.bound||D.uid===""?!0:p(O=>O.bound&&O.uid===D.uid)!==void 0?!1:!i.has(D.uid)).filter(D=>{let O=D.cell?l(c,D.cell):void 0;return!O||!l(d,D.cell)||!m.includes(O)?!0:(m.splice(m.indexOf(O),1),f.includes(O)&&D.uid!==O.uid&&j2(D.control)&&r.set(D.control,H2(O.uid)),!1)}),b=[],w=(D,O)=>{let x=D.uid===""?void 0:p(K=>K.uid===D.uid&&(!O||K.bound===D.bound));return x&&f.includes(x)&&b.push(x),x!==void 0},S=g.filter(D=>!w(D,!0)).filter(D=>!w(D,!1)&&j2(D.control)),P=f.filter(D=>m.includes(D));if(S.length===0||P.length===0&&b.length===0)continue;let L=[...P,...b],I=P.length===1&&S.length===1&&m.length===1?H2(P[0].uid):`the controls with id "${u}" cannot all be matched to those last synced \u2014 their cells do not tell them apart \u2014 and ${L.map(D=>`{${D.uid}}`).join(", ")} no longer ${L.length===1?"names":"name"} a control: which control held ${L.length===1?"that binding":"those bindings"} is ambiguous. Re-fetch the form; to drop a bound control, remove its customControl and push before removing the control`;for(let D of S)r.set(D.control,I)}return r}function tX(e){let t=(0,V.controlUniqueIds)(e),r=new Map;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=st(i.control)?(0,V.controlUniqueId)(i.control):"";o&&!r.has(o)&&r.set(o,i.control)}let n=new Set;for(let[i,o]of t){let a=r.get(i);(a===void 0||ht(a)||o>1)&&n.add(i)}return n}function j2(e){return ht(e)||e.genPage===void 0&&xi((0,V.effectiveClassId)(e))}function rX(e,t){let r=o=>(0,V.typedCellSites)(o).flatMap(({cell:a,pointer:s})=>{let l=a.control;if(!st(l)||ht(l)||l.genPage!==void 0||!xi((0,V.effectiveClassId)(l)))return[];let u=(0,V.controlUniqueId)(l);return u===""||Fi(o.bag,u).length===0?[{control:l,pointer:`${s}/control`}]:[]}),n=o=>`${String(o.id)}\0${(0,V.controlUniqueId)(o)}`,i=r(t).map(({control:o})=>n(o));return r(e).filter(({control:o})=>{let a=i.indexOf(n(o));return a<0?!0:(i.splice(a,1),!1)})}var nX="this control would keep the custom-control class with no binding (its customControl and uniqueid are gone): remove the binding from an unchanged copy \u2014 keep its uniqueid, and the native control comes back \u2014 or set classId to the column's native control";function H2(e){return`this control's uniqueid changed since it was last synced (it was {${e}}), and a binding is linked to its description by it: restore it (re-fetch the form), or remove the binding, push, then add the new one`}function iX(e){let t=typeof e.id=="string"?e.id.trim():"";return(0,V.normGuid)(t)||t.toLowerCase()}function qu(e,t,r,n){let i=t.customControl,o=(0,V.controlUniqueId)(t),a=Fi(e.bag,o),s=r?iL(e,r).get(t):void 0;if(s!==void 0)return un("pcf-binding-unique-id",s);let l=r?eX(r,o):void 0;if(l){let c=l.descriptions,d=c.length===1?fa(c[0]):void 0;if(d&&d.fieldName!==t.fieldName)return un("pcf-binding-rebind",`the binding is filed for "${d.fieldName}": remove it, push, then bind the new column`);if(c.length===1&&a.length===1&&cn(c[0],a[0]))return z2(t,i,a[0]);let f=a.length===1?fa(a[0]):void 0;return d&&f&&f.fieldName===t.fieldName&&_y(i,d)&&_y(i,f)?{kind:"unchanged"}:un("pcf-binding-edit-changed-description","the binding\u2019s description changed since it was last synced (edited in the bag, re-keyed or deleted): re-fetch the form before changing the binding")}if(a.length===0)return{kind:"new"};if(a.length>1)return un("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");let u=z2(t,i,a[0]);return n&&(u.kind==="edit"||u.kind==="unchanged")?u.kind==="unchanged"?u:un("pcf-binding-edit","this binding\u2019s description was never synced from the server (no baseline): changing it in place is not supported \u2014 remove customControl, push, then add the new one"):u}ue.planPcfBinding=qu;function oL(e){return e.kind==="edit"&&(e.changed.length>0||e.added.length>0)}function oX(e){let t=n=>ht(n.control)&&(!n.control.id||!n.id||(0,V.authoredUniqueId)(n.control)===void 0);if(!(0,V.typedCellSites)(e).some(({cell:n})=>t(n)))return e;let r=JSON.parse(JSON.stringify(e));for(let{cell:n}of(0,V.typedCellSites)(r)){if(!t(n))continue;let i=n.control;i.id||(i.id=(0,G2.newId)()),n.id||(n.id=(0,G2.newId)()),(0,V.authoredUniqueId)(i)===void 0&&(0,V.setUniqueId)(i)}return r}ue.mintPcfIdentity=oX;function aX(e,t){let r=new Set,n=new Set;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=i.control;if(!ht(o)||!st(o.customControl))continue;let a=o.customControl.name;if(typeof a!="string"||a===""||typeof o.fieldName!="string"||!o.fieldName)continue;let s=qu(e,o,t,!0);s.kind==="new"?(r.add(a),n.add(o.fieldName)):oL(s)&&r.add(a)}return{controls:[...r],columns:[...n],...n.size>0&&(0,V.effectiveFormType)(e)==="QuickCreate"?{requireCreateEligibility:!0}:{}}}ue.customControlNeeds=aX;function sX(e,t,r){var n,i,o,a,s,l;let u=e.bag,c=new Map;for(let{cell:f,pointer:m}of(0,V.typedCellSites)(e)){let p=f.control;if(!ht(p)||!st(p.customControl))continue;let h=(0,V.controlUniqueId)(p);h&&Fi(u,h).length>0&&c.set(p,{plan:qu(e,p,t,!0),pointer:`${m}/control/customControl`})}let d=(0,V.descriptionsRegion)(u);if(d&&t){let f=(0,V.controlUniqueIds)(e),m=new Set,p=new Map;for(let{cell:h}of(0,V.typedCellSites)(e)){let g=st(h.control)?(0,V.controlUniqueId)(h.control):"";g&&!p.has(g)&&p.set(g,h.control)}for(let{cell:h}of(0,V.typedCellSites)(t)){let g=h.control;if(!ht(g))continue;let b=(0,V.controlUniqueId)(g),w=Fi(t.bag,b),E=Fi(u,b);if(w.length!==1||E.length!==1||!cn(w[0],E[0])||!fa(E[0]))continue;let S=p.get(b);if(S&&!ht(S)){if(((n=f.get(b))!==null&&n!==void 0?n:0)>1)continue;let P=(o=(i=fa(E[0]))===null||i===void 0?void 0:i.nativeClass)!==null&&o!==void 0?o:"";S.classId=P.replace(/^\{|\}$/g,"").toUpperCase(),lX(S,"uniqueid"),m.add(b)}else!S&&!f.has(b)&&m.add(b)}m.size>0&&(d.node.c=lr(d.node.c).filter(h=>!(h?.n==="controlDescription"&&m.has((0,V.normGuid)((0,V.rawAttr)(h,"forControl"))))))}for(let{cell:f}of(0,V.typedCellSites)(e)){let m=f.control;if(!ht(m)||!st(m.customControl))continue;xi(m.classId)||(m.classId=V.CUSTOM_CONTROL_CLASS_ID);let p=(0,V.controlUniqueId)(m);if(!p){if((0,V.authoredUniqueId)(m)!==void 0)continue;p=(0,V.setUniqueId)(m)}let h=c.get(m);if(h){if(h.plan.kind==="refused")throw new jQ.ValidationError("form",e.id,[(0,Ce.issue)(h.pointer,h.plan.rule,h.plan.message)]);h.plan.kind==="edit"&&uX(h.plan,m.customControl);continue}let g=r?.control(m.customControl.name),b=r?.column(e.entityLogicalName,m.fieldName),w=b?.kind==="found"?Dy(b.value):void 0;if(g?.kind!=="found"||!w)continue;d||(d={i:(0,V.embedAppendIndex)(u),node:{n:"controlDescriptions",a:[],c:[]}},u.c.push(d));let E=((l=(s=lr((a=m.bag)===null||a===void 0?void 0:a.a).find(P=>P[0]==="uniqueid"))===null||s===void 0?void 0:s[1])!==null&&l!==void 0?l:"").trim(),S=E.startsWith("{")?E:`{${p}}`;d.node.c.push(tL(S,m.fieldName,w,m.customControl,g.value))}}ue.reconcilePcfDescriptions=sX;function lX(e,t){st(e.bag)&&(e.bag.a=lr(e.bag.a).filter(r=>r[0]!==t))}function uX(e,t){var r,n;let i=lr(e.description.c),o=i.findIndex(g=>(0,V.rawAttr)(g,"name")!==void 0),a=i.slice(0,o),s=i.slice(o),l=(r=t.parameters)!==null&&r!==void 0?r:{};for(let g of s)for(let b of(n=kf(g))!==null&&n!==void 0?n:[])e.changed.includes(b.n)&&(b.c=[Ty(Bu(e.stored.parameterTypes[b.n],l[b.n]))]);if(e.added.length===0&&e.removed.length===0)return;let u=g=>JSON.parse(JSON.stringify(g)),c=g=>{var b;let w=(0,V.rawAttr)(g,"formFactor");return w===void 0?null:(b=K2.get(w))!==null&&b!==void 0?b:null},d=(0,V.rawAttr)(a[0],"id"),f=(0,V.rawAttr)(s[0],"name"),m=$f(e.factors),p=m.defaults.map(g=>{let b=a.find(E=>c(E)===g);if(b)return b;let w=u(a[0]);return w.a=g===null?[["id",d]]:[["id",d],["formFactor",Mu[g]]],w}),h=m.named.map(g=>{let b=s.find(E=>c(E)===g);if(b)return b;let w=u(s[0]);return w.a=[["name",f],["formFactor",Mu[g]]],w});e.description.c=[...p,...h]}function cX(e){return(0,V.typedCellSites)(e).some(({cell:t})=>ht(t.control))}ue.mayCommitPcfState=cX;function dX(e,t){var r;let n=JSON.parse(JSON.stringify(e)),i=!1;for(let{cell:o}of(0,V.typedCellSites)(n)){let a=o.control;if(!ht(a))continue;let s=Ry(n,a);if(!s||s.fieldName!==a.fieldName)continue;let l=t(V.CUSTOM_CONTROL_CLASS_ID),u=lr((r=a.bag)===null||r===void 0?void 0:r.a).find(c=>c[0]==="classid");(!xi(a.classId)||a.type!==l||u!==void 0&&!xi(u[1])||!cn(a.customControl,s.binding))&&(xi(a.classId)||(a.classId=V.CUSTOM_CONTROL_CLASS_ID),a.type=l,u&&!xi(u[1])&&(u[1]=Y2(V.CUSTOM_CONTROL_CLASS_ID)),a.customControl=JSON.parse(JSON.stringify(s.binding)),i=!0)}return i?n:e}ue.commitPcfState=dX;var fX=new Set(["name","parameters","formFactors"]);function pX(e,t,r){let n=[],i=(0,V.controlUniqueIds)(e);for(let{cell:o,pointer:a}of(0,V.typedCellSites)(e)){let s=o.control;ht(s)&&hX(e,s,`${a}/control`,i,n,t,r?.atPush===!0)}return t&&gX(e,t,n),n}ue.pcfBindingIssues=pX;function mX(e,t,r){let n=r.length;if(!st(e))return r.push((0,Ce.issue)(t,"pcf-binding-shape","customControl must be an object")),!1;for(let i of Object.keys(e))fX.has(i)||r.push((0,Ce.issue)(`${t}/${i}`,"pcf-binding-unknown-key",`customControl has no "${i}"`));if((typeof e.name!="string"||e.name.trim()==="")&&r.push((0,Ce.issue)(`${t}/name`,"pcf-binding-shape","name must be the control's non-empty customcontrols name")),e.parameters!==void 0)if(!st(e.parameters))r.push((0,Ce.issue)(`${t}/parameters`,"pcf-binding-shape","parameters must be an object"));else for(let[i,o]of Object.entries(e.parameters))typeof o=="string"||typeof o=="boolean"||typeof o=="number"&&Number.isFinite(o)||r.push((0,Ce.issue)(`${t}/parameters/${i}`,"pcf-binding-shape","a parameter must be a string, a finite number or a boolean"));if(e.formFactors!==void 0){let i=e.formFactors;Array.isArray(i)&&i.length>0&&i.every(a=>typeof a=="string"&&Mi.includes(a))&&new Set(i).size===i.length||r.push((0,Ce.issue)(`${t}/formFactors`,"pcf-binding-shape","formFactors must be distinct 'web', 'phone' and 'tablet', at least one"))}return r.length===n}function hX(e,t,r,n,i,o,a){var s;let l=`${r}/customControl`,u=mX(t.customControl,l,i);t.fieldName||i.push((0,Ce.issue)(l,"pcf-binding-unbound","a PCF binding needs a control bound to a column (fieldName)")),t.genPage!==void 0&&i.push((0,Ce.issue)(l,"pcf-binding-with-genpage","a control cannot embed a page and bind a PCF control")),Ly(e)||i.push((0,Ce.issue)(l,"pcf-binding-form-type","PCF bindings are supported on Main and Quick Create forms only (not Quick View or Card)")),t.classId!==void 0&&typeof t.classId!="string"&&i.push((0,Ce.issue)(`${r}/classId`,"pcf-binding-class-id","classId must be a string"));let c=(0,V.authoredUniqueId)(t),d=(0,V.controlUniqueId)(t);if(c!==void 0&&!d?i.push((0,Ce.issue)(`${r}/bag`,"pcf-binding-unique-id","the control's uniqueid must be a GUID")):d&&((s=n.get(d))!==null&&s!==void 0?s:0)>1&&i.push((0,Ce.issue)(`${r}/bag`,"pcf-binding-unique-id","another control carries the same uniqueid")),!u)return;let f=qu(e,t,o,a);f.kind==="refused"&&i.push((0,Ce.issue)(l,f.rule,f.message))}function gX(e,t,r){var n;let i=new Map,o=iL(e,t);for(let{cell:l,pointer:u}of(0,V.typedCellSites)(e)){let c=st(l.control)?(0,V.controlUniqueId)(l.control):"";if(c&&!i.has(c)&&i.set(c,{control:l.control,pointer:`${u}/control`}),st(l.control)&&!ht(l.control)){let d=o.get(l.control);d!==void 0&&r.push((0,Ce.issue)(`${u}/control`,"pcf-binding-unique-id",d))}}let a=(0,V.controlUniqueIds)(e);for(let{cell:l}of(0,V.typedCellSites)(t)){if(!ht(l.control))continue;let u=(0,V.controlUniqueId)(l.control),c=i.get(u);!c||ht(c.control)||(((n=a.get(u))!==null&&n!==void 0?n:0)>1?r.push((0,Ce.issue)(c.pointer,"pcf-binding-unique-id","another control carries this binding\u2019s uniqueid; removing the binding would delete its description too")):cn(Fi(t.bag,u),Fi(e.bag,u))?c.control.fieldName!==l.control.fieldName&&r.push((0,Ce.issue)(c.pointer,"pcf-binding-rebind","remove the binding, push, then bind the new column")):r.push((0,Ce.issue)(c.pointer,"pcf-binding-removed-changed","the binding changed since it was last pushed; remove it from an unchanged copy (re-fetch)")))}let s=new Set(r.map(l=>l.pointer));for(let{pointer:l}of rX(e,t))s.has(l)||r.push((0,Ce.issue)(l,"pcf-binding-unique-id",nX))}var yX=new Set(["Form.Card"]),bX="MscrmControls.ModelForm.ModelFormControl";function aL(e,t){var r;if(e.hasDataset||e.hasGroups)return"it has a data-set or groups";if(!e.isBound)return"its first property is not bound to a column";let n=e.properties;if(n.filter(s=>s.usage==="bound").length!==1)return"it has more than one bound property";let i=n.map(s=>s.name);if(i.some(s=>!s)||new Set(i).size!==i.length)return"a property has no name, or two share one";let o=i.find(s=>!Z2(s));if(o!==void 0)return`the property name "${o}" cannot be written as an element`;if(t===bX||n.some(s=>s.defaultType!==void 0&&yX.has(s.defaultType)))return"a property needs a special encoding";if(n.some(s=>s.usage==="output"&&s.defaultValue!==null&&s.defaultValue!==""))return"an output property has a default";let a=n.find(s=>s.usage==="input"&&!Oy(s.defaultType));return a?`input "${a.name}" has a type the property editor does not write as text (${(r=a.defaultType)!==null&&r!==void 0?r:"none"})`:void 0}function vX(e){return e.ofType!==null?[e.ofType]:e.ofTypeGroup}function sL(e,t,r=e.defaultType){if(r==="Enum")return e.enumValues.some(o=>o.value===String(t))?void 0:`must be one of ${e.enumValues.map(o=>`"${o.value}"`).join(", ")}`;let n=r!==void 0?Iy.get(r):void 0;if(n){let o=typeof t=="boolean"?void 0:eL(t);return o===void 0||o<n.min||o>n.max?`must be a number from ${n.min.toFixed(n.digits)} through ${n.max.toFixed(n.digits)}`:void 0}if(r!==void 0&&Q2.has(r))return t===!0||t===!1||t==="true"||t==="false"?void 0:"must be true or false";let i=r!==void 0?JQ.get(r):void 0;return i!==void 0&&String(t).length>i?`must be at most ${i} characters`:e.required&&String(t)===""?"is required":void 0}function wX(e,t,r){var n,i,o,a;let s={issues:[]},l=s.issues;for(let{cell:u,pointer:c}of(0,V.typedCellSites)(e)){let d=u.control;if(!ht(d)||!d.fieldName)continue;let f=d.customControl;if(!st(f)||typeof f.name!="string")continue;let m=`${c}/control/customControl`,p=qu(e,d,r,!0);if(p.kind==="edit"){oL(p)&&AX(p,f,m,t,s);continue}if(p.kind!=="new")continue;let h=t?.control(f.name),g=t?.column((n=e.entityLogicalName)!==null&&n!==void 0?n:"",d.fieldName);if(!h||h.kind==="unavailable"){(i=s.unavailable)!==null&&i!==void 0||(s.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${f.name}" could not be read`,...h?.kind==="unavailable"?{cause:h.error}:{}});continue}if(h.kind!=="found"){l.push((0,Ce.issue)(`${m}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${f.name}" (${h.kind})`));continue}if(!g||g.kind==="unavailable"){(o=s.unavailable)!==null&&o!==void 0||(s.unavailable={code:"PCF_COLUMN_UNAVAILABLE",message:`the column "${d.fieldName}" could not be read`,...g?.kind==="unavailable"?{cause:g.error}:{}});continue}let b=aL(h.value,f.name);if(b){l.push((0,Ce.issue)(`${m}/name`,"pcf-binding-unsupported-control",`"${f.name}" is not supported: ${b}`));continue}let w=h.value.properties.find(x=>x.isPrimary),E=g.kind==="found"?g.value:void 0,S=E?(a=(0,HQ.manifestTypesForColumn)(E.attributeTypeName,E.format,E.formatName))!==null&&a!==void 0?a:[]:[];E!==void 0&&!E.isPrimaryId&&E.isValidForForm&&Dy(E)!==void 0&&vX(w).some(x=>S.includes(x))?(0,V.effectiveFormType)(e)==="QuickCreate"&&E?.isValidForCreate!==!0&&l.push((0,Ce.issue)(m,"pcf-binding-quick-create-column",`"${d.fieldName}" cannot be set when a record is created, so a Quick Create form cannot bind it`)):l.push((0,Ce.issue)(m,"pcf-binding-incompatible-column",`"${f.name}" cannot be bound to "${d.fieldName}"`));let L=new Map(h.value.properties.filter(x=>x.usage==="input").map(x=>[x.name,x])),I=st(f.parameters)?f.parameters:{};for(let[x,K]of Object.entries(I)){let Re=L.get(x);if(!Re){l.push((0,Ce.issue)(`${m}/parameters/${x}`,"pcf-binding-unknown-parameter",`"${f.name}" has no input "${x}"`));continue}let qt=sL(Re,K);qt&&l.push((0,Ce.issue)(`${m}/parameters/${x}`,"pcf-binding-parameter-value",`"${x}" ${qt}`))}for(let x of L.values())x.required&&!Uu(I,x.name)&&!x.defaultValue&&l.push((0,Ce.issue)(`${m}/parameters`,"pcf-binding-missing-parameter",`"${x.name}" is required`));let D=Py(h.value),O=Array.isArray(f.formFactors)?f.formFactors:void 0;(O?O.some(x=>!D.has(x)):D.size===0)&&l.push((0,Ce.issue)(`${m}/formFactors`,"pcf-binding-form-factor",`"${f.name}" is available on ${D.size===0?"no form factor":[...D].join(", ")}`))}return s}ue.pcfReadIssues=wX;function CX(e,t){return t===void 0||!Oy(t)?!1:e.ofType!==null?e.ofType===t:e.ofTypeGroup.includes(t)}function EX(e,t,r){var n,i;let o=aL(e,t);if(o)return`it is no longer supported (${o})`;let a=e.properties.find(d=>d.isPrimary);if(a?.name!==r.boundProperty)return`its bound property is now "${(n=a?.name)!==null&&n!==void 0?n:"none"}", not "${r.boundProperty}"`;let s=(i=r.binding.parameters)!==null&&i!==void 0?i:{},l=new Set(e.properties.filter(d=>d.usage==="input").map(d=>d.name)),u=Object.keys(s).find(d=>!l.has(d));if(u!==void 0)return`"${u}" is no longer one of its inputs`;let c=e.properties.find(d=>d.usage==="input"&&d.required&&!d.defaultValue&&!Uu(s,d.name));return c?`it now requires "${c.name}", which the binding does not store`:void 0}function AX(e,t,r,n,i){var o,a,s;let l=i.issues,u=n?.control(t.name);if(!u||u.kind==="unavailable"){(o=i.unavailable)!==null&&o!==void 0||(i.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${t.name}" could not be read`,...u?.kind==="unavailable"?{cause:u.error}:{}});return}if(u.kind!=="found"){l.push((0,Ce.issue)(`${r}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${t.name}" (${u.kind})`));return}let c=EX(u.value,t.name,e.stored);if(c){l.push((0,Ce.issue)(r,"pcf-binding-edit-manifest-changed",`"${t.name}" changed since this binding was written: ${c} \u2014 remove the binding, push, then add it`));return}let d=new Map(u.value.properties.filter(h=>h.usage==="input").map(h=>[h.name,h])),f=l.length;for(let h of Object.keys((a=e.stored.binding.parameters)!==null&&a!==void 0?a:{})){let g=e.stored.parameterTypes[h];CX(d.get(h),g)||l.push((0,Ce.issue)(`${r}/parameters/${h}`,"pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which "${t.name}" does not take for it now: remove the binding, push, then add it`))}if(l.length>f)return;let m=(s=t.parameters)!==null&&s!==void 0?s:{};for(let h of e.changed){let g=sL(d.get(h),m[h],e.stored.parameterTypes[h]);g&&l.push((0,Ce.issue)(`${r}/parameters/${h}`,"pcf-binding-parameter-value",`"${h}" ${g}`))}let p=Py(u.value);e.added.some(h=>!p.has(h))&&l.push((0,Ce.issue)(`${r}/formFactors`,"pcf-binding-form-factor",`"${t.name}" is available on ${p.size===0?"no form factor":[...p].join(", ")}`))}});var SL=v(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.classIdForAttributeType=Or.QUICK_VIEW_CLASS_ID=Or.NOTES_CLASS_ID=Or.SUBGRID_CLASS_ID=Or.formRegistration=Or.FormAdapter=void 0;var Ui=(pt(),Fr(d_)),uL=(ot(),Fr(f_)),SX=(Dt(),Fr(m_)),gt=(le(),Fr(p_)),tt=(ta(),Fr(h_)),NX=(cy(),Fr($2)),_X=(F2(),Fr(x2)),yt=so(),cL=Jr(),Ir=en(),TX=vg(),Ws=dt(),DX=Ny(),Xt=wd(),ni=lL(),Gs=Q(),Uy=se(),ky=lo(),gL=Ho(),IX={[gt.FormType.Main]:"Main",[gt.FormType.QuickCreate]:"QuickCreate",[gt.FormType.QuickViewForm]:"QuickView",[gt.FormType.Card]:"Card"},xf={Main:gt.FormType.Main,QuickCreate:gt.FormType.QuickCreate,QuickView:gt.FormType.QuickViewForm,Card:gt.FormType.Card},OX=new Map(Object.entries(tt.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function By(e){var t;return e&&(t=OX.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function Vu(e){return e.getAllProperties().map(t=>[t.key,t.value])}function pa(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function yL(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function qy(e,t){var r,n;let i=yL(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(r=o.find(s=>pa(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return a&&(n=pa(a).get("description"))!==null&&n!==void 0?n:""}function PX(e){let t=yL(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 o=n.getAllChildren()[0],a=o?o.getNodeName():"";a.charAt(0)==="<"&&(a=a.substring(1)),r[i]=a}return r}function bL(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function $y(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function Gu(e){return String(e??"").replace(/[{}]/g,"")}function xy(e){return`{${Gu(e)}}`}function Fy(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function Mf(e,t,r){let n=e.getAllChildren(),i=n.findIndex(u=>u.getNodeName()===t),o=[];if(n.forEach((u,c)=>{c!==i&&o.push({i:c,node:(0,yt.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:Vu(e),c:o}};let a=n[i],s=[],l=[];return a.getAllChildren().forEach((u,c)=>{u.getNodeName()===r?s.push(u):l.push({i:c,node:(0,yt.rawFromNode)(u)})}),{modeled:s,bag:{a:Vu(e),c:o,w:{n:a.getNodeName(),a:Vu(a),c:l}}}}function vL(e,t,r){let n=[],i=[];return e.getAllChildren().forEach((o,a)=>{o.getNodeName()===t&&(!r||n.length===0)?n.push(o):i.push({i:a,node:(0,yt.rawFromNode)(o)})}),{modeled:n,bag:{a:Vu(e),c:i}}}function dL(e,t){let{modeled:r,bag:n}=Mf(e,"tabs","tab");return{tabs:r.map(i=>RX(i,t)),bag:n}}function RX(e,t){var r,n;let i=pa(e),{modeled:o,bag:a}=Mf(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:qy(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:o.map(s=>LX(s,t)),bag:a}}function LX(e,t){let r=pa(e),{modeled:n,bag:i}=Mf(e,"sections","section");return{width:r.get("width"),sections:n.map(o=>kX(o,t)),bag:i}}function kX(e,t){var r,n,i;let o=pa(e),{modeled:a,bag:s}=Mf(e,"rows","row");return{id:(r=o.get("id"))!==null&&r!==void 0?r:"",name:(n=o.get("name"))!==null&&n!==void 0?n:"",label:qy(e,t),visible:o.has("visible")?o.get("visible")==="true":!0,showLabel:o.get("showlabel")==="true",columns:bL((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(l=>$X(l,t)),bag:s}}function $X(e,t){let{modeled:r,bag:n}=vL(e,"cell",!1);return{cells:r.map(i=>xX(i,t)),bag:n}}function xX(e,t){var r;let n=pa(e),{modeled:i,bag:o}=vL(e,"control",!0),a=qy(e,t),s=n.get("showlabel")==="true",l=i[0]?FX(i[0],a,s):null;return{id:(r=n.get("id"))!==null&&r!==void 0?r:"",visible:n.has("visible")?n.get("visible")==="true":!0,colspan:Fy(n.get("colspan"),1),rowspan:Fy(n.get("rowspan"),1),control:l,bag:o}}function FX(e,t,r){var n,i;let o=pa(e),a=Gu((n=o.get("classid"))!==null&&n!==void 0?n:""),s=o.get("datafieldname");return{id:(i=o.get("id"))!==null&&i!==void 0?i:"",classId:a,fieldName:s||null,type:By(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:r,parameters:PX(e),bag:{a:Vu(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,yt.rawFromNode)(l)}))}}}function No(e){return e.a.length===0&&e.c.length===0&&!e.w}function wL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function ma(e,t){var r;let n=new Set(e.a.map(a=>a[0])),i=No(e),o=[];for(let a of t)if(n.has(a.key)){let s=(r=wL(e,a.key))!==null&&r!==void 0?r:"";a.matches(s)||o.push([a.key,a.render()])}else i?o.push([a.key,a.render()]):a.matches(a.absentDefault)||o.push([a.key,a.render()]);return(0,yt.mergeAttrs)(e.a,o)}var Ao=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),So=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),fL=(e,t,r=1)=>({key:e,matches:n=>Fy(n,r)===t,render:()=>String(t),absentDefault:String(r)});function Vy(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function My(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>{var r;return{n:(0,Uy.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${(r=e[t])!==null&&r!==void 0?r:""}`,a:[],c:[]}]}})}}function MX(e,t){var r,n;let i=e.c.find(a=>a.n==="label"&&a.a.some(s=>s[0]==="languagecode"&&s[1]===String(t))),o=i??e.c.find(a=>a.n==="label");return(n=(r=o?.a.find(a=>a[0]==="description"))===null||r===void 0?void 0:r[1])!==null&&n!==void 0?n:""}function UX(e,t,r){let n=!1,i=e.c.map(o=>o.n!=="label"||!o.a.some(s=>s[0]==="languagecode"&&s[1]===String(r))?o:(n=!0,{...o,a:o.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 Gy(e,t,r){let n=e.c.findIndex(o=>o.node.n==="labels");if(n<0){if(!t||No(e))return e;let a=e.c.some(s=>s.i===0)?e.c.map(s=>({...s,i:s.i+1})):e.c;return{...e,c:[{i:0,node:Vy(t,r)},...a]}}if(MX(e.c[n].node,r)===t)return e;let i=UX(e.c[n].node,t,r);return{...e,c:e.c.map((o,a)=>a===n?{...o,node:i}:o)}}function BX(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],o=i?i.n:"";o.charAt(0)==="<"&&(o=o.substring(1)),t[n]=o}return t}function qX(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function VX(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function GX(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||No(e))return e;let i=e.c.reduce((o,a)=>a.i>o?a.i:o,-1);return{...e,c:[...e.c,{i:i+1,node:My(t)}]}}if(qX(BX(e.c[r].node),t))return e;let n=My(t);return{...e,c:e.c.map((i,o)=>o===r?{...i,node:n}:i)}}function Uf(e,t,r,n){if(e.w){let a={n:e.w.n,a:e.w.a.map(s=>[s[0],s[1]]),c:(0,yt.spliceChildren)(e.w.c,r)};return(0,yt.spliceChildren)(e.c,[a])}let i=n(),o={n:t,a:[],c:r};return e.c.length===0?[...i,o]:(0,yt.spliceChildren)(e.c,[...i,o])}function WX(e,t){let r=e.tabs.map(n=>zX(n,t));return{n:"form",a:ma(e.bag,[]),c:e.tabs.length===0&&No(e.bag)?[]:Uf(e.bag,"tabs",r,()=>[])}}function CL(e,t,r){return t&&!e.c.some(n=>n.node.n==="labels")?[Vy(t,r)]:[]}function zX(e,t){let r=[Ao("id",e.id),Ao("name",e.name),So("expanded",e.expanded),So("visible",e.visible,!0)],n=e.columns.map(o=>jX(o,t)),i=Gy(e.bag,e.label,t);return{n:"tab",a:ma(i,r),c:Uf(i,"columns",n,()=>CL(i,e.label,t))}}function jX(e,t){let r=e.width!==void 0?[Ao("width",e.width)]:[],n=e.sections.map(i=>HX(i,t));return{n:"column",a:ma(e.bag,r),c:Uf(e.bag,"sections",n,()=>[])}}function HX(e,t){let r=[Ao("id",e.id),Ao("name",e.name),So("showlabel",e.showLabel),So("visible",e.visible,!0),{key:"columns",matches:o=>bL(o)===e.columns,render:()=>$y(e.columns),absentDefault:$y(1)}],n=e.rows.map(o=>KX(o,t)),i=Gy(e.bag,e.label,t);return{n:"section",a:ma(i,r),c:Uf(i,"rows",n,()=>CL(i,e.label,t))}}function KX(e,t){let r=e.cells.map(n=>JX(n,t));return{n:"row",a:ma(e.bag,[]),c:No(e.bag)?r:(0,yt.assembleChildren)(e.bag,r)}}function JX(e,t){let r=e.control?e.control.showLabel:wL(e.bag,"showlabel")==="true",n=[Ao("id",e.id),So("showlabel",r),So("visible",e.visible,!0),fL("colspan",e.colspan),fL("rowspan",e.rowspan)],i=e.control?[YX(e.control)]:[],o;if(No(e.bag))o=[...e.control&&e.control.label?[Vy(e.control.label,t)]:[],...i];else{let a=e.control?Gy(e.bag,e.control.label,t):e.bag;o=(0,yt.assembleChildren)(a,i)}return{n:"cell",a:ma(e.bag,n),c:o}}function YX(e){let t=[Ao("id",e.id),{key:"classid",matches:i=>Gu(i)===e.classId,render:()=>xy(e.classId||String(tt.ControlClassId.TextboxControl)),absentDefault:""}];e.fieldName!==null&&t.push(Ao("datafieldname",e.fieldName)),t.push(So("disabled",e.isReadOnly)),t.push(So("isrequired",e.isRequired));let r=e.fieldName===null?VX(e.bag,"datafieldname"):e.bag,n;return No(r)?n=Object.keys(e.parameters).length>0?[My(e.parameters)]:[]:n=(0,yt.assembleChildren)(GX(r,e.parameters),[]),{n:"control",a:ma(r,t),c:n}}var QX={make:(e,t)=>new SX.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function pL(e,t,r,n){(0,ky.installDomShim)();let i=ZX(e,r);(0,Xt.reconcileEmbedDescriptions)(i,n),(0,ni.reconcilePcfDescriptions)(i,n,r?.pcf);let o=(0,yt.rebuildRaw)(WX(i,t),QX,null);return new _X.SerializationService(t).serializeFormXmlNode(o)}function XX(e){return JSON.parse(JSON.stringify(e))}function ZX(e,t){let r=XX(e);r.bag||(r.bag=(0,yt.emptyBag)()),r.tabs||(r.tabs=[]),sZ(r.bag),t&&eZ(r,t);for(let n of r.tabs)tZ(n);return r}function eZ(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";Wy(e,i=>{let o=i.fieldName,a=i;if(!o||a.label!==void 0&&a.classId!==void 0)return;let s=t.resolveField(n,o);s&&(a.label===void 0&&s.displayName&&(a.label=s.displayName),a.classId===void 0&&s.attributeType&&(a.classId=AL(s.attributeType)))})}function mL(e){let t=[];return Wy(e,r=>t.push(r)),t}function Wy(e,t){var r,n,i,o,a;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(o=u.rows)!==null&&o!==void 0?o:[])for(let d of(a=c.cells)!==null&&a!==void 0?a:[])d.control&&t(d.control)}function tZ(e){e.id||(e.id=Ui.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)rZ(t);e.bag||(e.bag=(0,yt.emptyBag)())}function rZ(e){e.sections||(e.sections=[]);for(let t of e.sections)nZ(t);e.bag||(e.bag=(0,yt.emptyBag)()),e.width===void 0&&No(e.bag)&&(e.width="100%")}function nZ(e){e.id||(e.id=Ui.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)iZ(t);e.bag||(e.bag=(0,yt.emptyBag)())}function iZ(e){e.cells||(e.cells=[]);for(let t of e.cells)oZ(t);e.bag||(e.bag=(0,yt.emptyBag)())}function oZ(e){(0,Xt.hasGenPage)(e.control)&&(0,Xt.applyEmbedCellDefaults)(e),e.id||(e.id=Ui.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&&aZ(e.control),e.bag||(e.bag=(0,yt.emptyBag)())}function aZ(e){var t;(0,Xt.hasGenPage)(e)&&(0,Xt.applyEmbedControlDefaults)(e),e.id||(e.id=Ui.Guid.NewGuid()),(e.classId===void 0||e.classId===null)&&(e.classId=String(tt.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":By(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,Uy.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,yt.emptyBag)())}function sZ(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 o of i.c)o.n==="Handler"&&!hL(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",xy(Ui.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!hL(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",xy(Ui.Guid.NewGuid())])}}var Ff=class{constructor(t=gL.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,o;let{tabs:a,bag:s}=dL(t,this.lcid),l={id:t.formId?t.formId.guidString:"",name:(n=t.formName)!==null&&n!==void 0?n:"",entityLogicalName:(i=t.entityName)!==null&&i!==void 0?i:"",formType:(o=IX[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:a,bag:s};return(0,Xt.projectGenPageEmbeds)(l),(0,ni.projectPcfBindings)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:pL(t,this.lcid),formid:t.id||(0,Ws.newId)(),objecttypecode:t.entityLogicalName,type:xf[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:gt.FormPresentation.AirForm,formactivationstate:t.status==="Active"?gt.FormActivationState.Active:gt.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,o,a,s,l;let u=t,c=(r=u.formxml)!==null&&r!==void 0?r:"",d={formxml:c,formid:(n=u.formid)!==null&&n!==void 0?n:(0,Ws.newId)(),objecttypecode:(i=u.objecttypecode)!==null&&i!==void 0?i:"",type:u.type,name:(o=u.name)!==null&&o!==void 0?o:"",uniquename:(a=u.uniquename)!==null&&a!==void 0?a:"",description:(s=u.description)!==null&&s!==void 0?s:"",formpresentation:u.formpresentation,formactivationstate:u.formactivationstate};(0,ky.installDomShim)();let f=uL.ScriptUtilities.ParseXml(c),m=lZ(f),p=this.deserializeDocument(d,f);return uZ(this.toArtifact(p,(l=u.description)!==null&&l!==void 0?l:void 0),m)}toApiPayload(t,r,n){let i=(0,Xt.genPageEmbedIssues)(t);if(i.length>0)throw new Gs.ValidationError("form",t.id,i);let o=(0,ni.pcfBindingIssues)(t,r,{atPush:!0});if(o.length>0)throw new Gs.ValidationError("form",t.id,o);let a=(0,ni.pcfReadIssues)(t,n?.pcf,r);if(a.unavailable)throw(0,Gs.attachCause)(new Gs.SdkError(a.unavailable.code,a.unavailable.message),a.unavailable.cause);if(a.issues.length>0)throw new Gs.ValidationError("form",t.id,a.issues);return{formxml:pL(t,this.lcid,n,r),name:t.name,type:xf[t.formType],objecttypecode:t.entityLogicalName,...t.description!==void 0?{description:t.description}:{}}}metadataNeeds(t){let r=t.entityLogicalName;if(!r)return[];let n=new Map;return Wy(t,i=>{var o;let a=i.fieldName,s=i;if(!a||s.label!==void 0&&s.classId!==void 0)return;let l=(o=n.get(a))!==null&&o!==void 0?o:{entityLogicalName:r,fieldName:a};s.label===void 0&&(l.needsLabel=!0),n.set(a,l)}),[...n.values()]}customControlNeeds(t,r){var n;return{entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",...(0,ni.customControlNeeds)(t,r)}}createDefault(t){var r,n,i,o,a,s,l,u,c,d,f,m;let p=[...(0,Xt.genPageEmbedIssues)(t),...(0,ni.pcfBindingIssues)(t)];if(p.length>0)throw new Gs.ValidationError("form",t.id||"(new)",p);let h=t.tabs&&t.tabs.length>0?void 0:vZ(this.lcid),g=h!==void 0?h:t.tabs.map(E=>cZ(E,this.lcid)).join(""),b=this.deserialize({formxml:`<form><tabs>${g}</tabs></form>`,formid:t.id||(0,Ws.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:xf[(n=t.formType)!==null&&n!==void 0?n:"Main"],name:(i=t.name)!==null&&i!==void 0?i:"New Form",uniquename:(o=t.name)!==null&&o!==void 0?o:"New Form",description:(a=t.description)!==null&&a!==void 0?a:"",formpresentation:gt.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?gt.FormActivationState.Active:gt.FormActivationState.InActive});(l=b.displayCondition)===null||l===void 0||l.removeProperty(gt.ElementProperties.Order);let w=this.toArtifact(b,t.description);if(t.tabs&&t.tabs.length>0){let E=mL(t);mL(w).forEach((S,P)=>{E[P]&&E[P].label===void 0&&delete S.label,E[P]&&E[P].genPage!==void 0&&(S.genPage=JSON.parse(JSON.stringify(E[P].genPage))),E[P]&&E[P].customControl!==void 0&&(S.customControl=JSON.parse(JSON.stringify(E[P].customControl)))})}return{id:(u=t.id)!==null&&u!==void 0?u:w.id,name:(c=t.name)!==null&&c!==void 0?c:"New Form",entityLogicalName:(d=t.entityLogicalName)!==null&&d!==void 0?d:"",formType:(f=t.formType)!==null&&f!==void 0?f:"Main",status:(m=t.status)!==null&&m!==void 0?m:"Active",...t.description!==void 0?{description:t.description}:{},tabs:w.tabs,bag:w.bag}}assignMissingIds(t){return(0,Ws.assignMissingIds)(t)}completeAsStored(t,r){return(0,DX.completeRecordAsStored)(t,r,this.lcid)}normalize(t){return(0,ni.mintPcfIdentity)((0,Xt.mintEmbedIdentity)(t))}committed(t,r){var n,i,o,a,s,l;let u=r?.formxml;if(typeof u!="string"||!((0,Xt.mayCommitEmbedState)(t)||(0,ni.mayCommitPcfState)(t)))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,Ws.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:xf[(i=t.formType)!==null&&i!==void 0?i:"Main"],name:(o=t.name)!==null&&o!==void 0?o:"",uniquename:(a=t.name)!==null&&a!==void 0?a:"",description:(s=t.description)!==null&&s!==void 0?s:"",formpresentation:gt.FormPresentation.AirForm,formactivationstate:gt.FormActivationState.Active}),{bag:d}=dL(c,this.lcid),f=(0,ni.commitPcfState)((0,Xt.commitEmbedState)(t,(l=(0,Xt.descriptionsRegion)(d))===null||l===void 0?void 0:l.node),By);return{artifact:f,baseline:f}}validate(t){return DZ(t)}deserialize(t){return(0,ky.installDomShim)(),this.deserializeDocument(t,uL.ScriptUtilities.ParseXml(t.formxml))}deserializeDocument(t,r){let n=new NX.DeserializationService(this.lcid).deSerializeFormXml(r,new Ui.Guid(t.formid),t.objecttypecode,gt.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===gt.FormActivationState.InActive?"Inactive":"Active"}};Or.FormAdapter=Ff;var EL=["header","footer","DisplayConditions"];function lZ(e){var t;let r=e?.getElementsByTagName("form")[0],n=new Set;for(let i=(t=r?.firstChild)!==null&&t!==void 0?t:null;i;i=i.nextSibling)i.nodeType===1&&EL.includes(i.nodeName)&&n.add(i.nodeName);return n}function uZ(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=EL.filter(o=>!t.has(o)),i=e.bag.c.filter(o=>{var a;return n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>o.i);return i.length>0&&(e.bag.c=e.bag.c.filter(o=>{var a;return!n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>({...o,i:o.i-i.filter(a=>a<o.i).length}))),e}function Pn(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function zy(e,t){return e?`<labels><label description="${Pn(e)}" languagecode="${t}" /></labels>`:""}function jy(e){return e&&e.length>0?Gu(e):(0,Ws.newId)()}function cZ(e,t){var r,n,i,o;let a=(r=e.columns)!==null&&r!==void 0?r:[],s=(a.length>0?a:[bZ()]).map(l=>dZ(l,t)).join("");return`<tab id="{${Pn(jy(e.id))}}" name="${Pn((n=e.name)!==null&&n!==void 0?n:"")}" expanded="${(i=e.expanded)!==null&&i!==void 0?i:!0}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}">${zy(e.label,t)}<columns>${s}</columns></tab>`}function dZ(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(o=>fZ(o,t)).join("");return`<column width="${Pn((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function fZ(e,t){var r,n,i,o,a;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>pZ(l,t)).join("");return`<section id="{${Pn(jy(e.id))}}" name="${Pn((n=e.name)!==null&&n!==void 0?n:"")}" showlabel="${(i=e.showLabel)!==null&&i!==void 0?i:!1}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}" columns="${$y((a=e.columns)!==null&&a!==void 0?a:1)}">${zy(e.label,t)}<rows>${s}</rows></section>`}function pZ(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>mZ(n,t)).join("")}</row>`}function mZ(e,t){var r,n,i,o,a;let s=hZ(e),l=s.control,u=l?zy((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?gZ(l):"";return`<cell id="{${Pn(jy(s.id))}}" showlabel="${l?(n=l.showLabel)!==null&&n!==void 0?n:!0:!1}" visible="${(i=s.visible)!==null&&i!==void 0?i:!0}" colspan="${(o=s.colspan)!==null&&o!==void 0?o:1}" rowspan="${(a=s.rowspan)!==null&&a!==void 0?a:1}">${u}${c}</cell>`}function hZ(e){if(!(0,Xt.hasGenPage)(e.control))return e;let t={...e.control};(0,Xt.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,Xt.applyEmbedCellDefaults)(r),r}function gZ(e){var t,r,n;let i=e.fieldName?` datafieldname="${Pn(e.fieldName)}"`:"",o=yZ(e.parameters),a=e.classId?Gu(e.classId):String(tt.ControlClassId.TextboxControl);return`<control id="${Pn((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Pn(a)}}"${i} disabled="${(r=e.isReadOnly)!==null&&r!==void 0?r:!1}" isrequired="${(n=e.isRequired)!==null&&n!==void 0?n:!1}">${o}</control>`}function yZ(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,Uy.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Pn(e[n])}</${n}>`).join("")}</parameters>`)}function bZ(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function vZ(e){return`<tab id="{${Ui.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${Ui.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 wZ(e=gL.DEFAULT_LCID){return{adapter:new Ff(e),api:TX.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,cL.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,cL.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}Or.formRegistration=wZ;var CZ=new Set(["id","name","label","expanded","visible","columns","bag"]),EZ=new Set(["id","width","sections","bag"]),AZ=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),SZ=new Set(["id","cells","bag"]),NZ=new Set(["id","visible","colspan","rowspan","control","bag"]),_Z=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","customControl","bag"]),TZ={elsewhere:{isReadOnly:"control",isRequired:"control",fieldName:"control",classId:"control",label:"control",showLabel:"control",parameters:"control"},unsupported:{createOnly:"FormXml has no create-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled.",updateOnly:"FormXml has no update-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled."}};function DZ(e){let t=[];return(0,Ir.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let o=`/tabs/${i}`;(0,Ir.rejectUnknownKeys)(n,CZ,o,"tab",t),(0,Ir.childObjects)(n,"columns",o,"column",t).forEach(({node:s,index:l})=>{let u=`${o}/columns/${l}`;(0,Ir.rejectUnknownKeys)(s,EZ,u,"column",t),(0,Ir.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:f})=>{let m=`${u}/sections/${f}`;(0,Ir.rejectUnknownKeys)(d,AZ,m,"section",t),(0,Ir.childObjects)(d,"rows",m,"row",t).forEach(({node:h,index:g})=>{let b=`${m}/rows/${g}`;(0,Ir.rejectUnknownKeys)(h,SZ,b,"row",t),(0,Ir.childObjects)(h,"cells",b,"cell",t).forEach(({node:E,index:S})=>{let P=`${b}/cells/${S}`;(0,Ir.rejectUnknownKeys)(E,NZ,P,"cell",t,TZ);let L=E.control;L!=null&&!(0,Ir.isJsonObject)(L)?t.push((0,Ir.issue)(`${P}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof L}`)):(0,Ir.isJsonObject)(L)&&(0,Ir.rejectUnknownKeys)(L,_Z,`${P}/control`,"control",t)})})})})}),t.push(...(0,Xt.genPageEmbedIssues)(e)),t.push(...(0,ni.pcfBindingIssues)(e)),t}Or.SUBGRID_CLASS_ID=tt.ControlClassId.SubgridControl;Or.NOTES_CLASS_ID=tt.ControlClassId.TimelineControl;Or.QUICK_VIEW_CLASS_ID=tt.ControlClassId.QuickViewControl;var IZ={Lookup:String(tt.ControlClassId.LookupControl),Customer:String(tt.ControlClassId.LookupControl),Owner:String(tt.ControlClassId.LookupControl),PartyList:String(tt.ControlClassId.PartyListControl),Boolean:String(tt.ControlClassId.BooleanControl),DateTime:String(tt.ControlClassId.DateTimeControl),Decimal:String(tt.ControlClassId.DecimalControl),Double:String(tt.ControlClassId.FloatingNumberControl),Money:String(tt.ControlClassId.CurrencyControl),Integer:String(tt.ControlClassId.IntegerControl),BigInt:String(tt.ControlClassId.IntegerControl),Memo:String(tt.ControlClassId.TextAreaControl),String:String(tt.ControlClassId.TextboxControl)},OZ="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function AL(e){return e==="Picklist"||e==="State"||e==="Status"?OZ:e&&IZ[e]||String(tt.ControlClassId.TextboxControl)}Or.classIdForAttributeType=AL;function hL(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var Hy=v(zs=>{"use strict";Object.defineProperty(zs,"__esModule",{value:!0});zs.viewApi=zs.findDefaultViews=void 0;var DL=Lt(),ur=ye(),Rn=se(),PZ=es(),NL="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",RZ="savedqueryid,name,returnedtypecode,querytype,isdefault",LZ=60*1e3;function Bf(e){return(e.localName||e.nodeName).toLowerCase()}function Wu(e,t){let r;for(let n=0;n<e.attributes.length;n+=1){let i=e.attributes[n];i.nodeName.toLowerCase()===t&&(r=r===void 0?i.value:null)}return r}function kZ(e){if(!e)return;let t=!0,r=()=>{t=!1},n=new PZ.DOMParser({errorHandler:{warning:r,error:r,fatalError:r}}).parseFromString(e,"text/xml").documentElement;return t&&n&&Bf(n)==="fetch"?n:void 0}function $Z(e){for(let t=e.parentNode;t;t=t.parentNode)if(Bf(t)==="link-entity")return!0;return!1}function _L(e,t){var r,n,i;if(((r=e.canbedeleted)===null||r===void 0?void 0:r.Value)!==!1)return!1;let o=kZ(e.fetchxml);if(!o)return!1;let a=Array.from(o.getElementsByTagName("*")),s=a.filter(u=>Bf(u)==="condition"),l=s.length===1?s[0]:void 0;return l!==void 0&&a.filter(u=>Bf(u)==="link-entity").every(u=>{var c;return((c=Wu(u,"link-type"))===null||c===void 0?void 0:c.toLowerCase())==="outer"})&&!$Z(l)&&Wu(l,"entityname")===void 0&&((n=Wu(l,"attribute"))===null||n===void 0?void 0:n.toLowerCase())==="statecode"&&((i=Wu(l,"operator"))===null||i===void 0?void 0:i.toLowerCase())==="eq"&&Wu(l,"value")===String(t)}function xZ(e,t){let r=String(e??"").trim().toLowerCase().split(/\s+/).filter(i=>i!==""),n=String(t??"").trim().toLowerCase().split(/\s+/).filter(i=>i!=="");return r.length===n.length&&r.filter((i,o)=>i!==n[o]).length===1}function FZ(e){var t,r;let n=e.filter(a=>_L(a,0)),i=e.filter(a=>_L(a,1)),o=[];for(let a of n)for(let s of i)Math.abs(Date.parse(String((t=s.createdon)!==null&&t!==void 0?t:""))-Date.parse(String((r=a.createdon)!==null&&r!==void 0?r:"")))<=LZ&&xZ(a.name,s.name)&&o.push({active:a,inactive:s});return o.length===1?o[0]:void 0}async function MZ(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,Rn.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,Rn.odataQuery)([["$select","savedqueryid,name,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,DL.collectPages)(e,a,`findDefaultViews('${t}')`),l=FZ(s),u=new Set(l?[l.active,l.inactive]:[]);return s.filter(c=>c.savedqueryid&&!i.has(c.savedqueryid)&&u.has(c)).map(c=>{var d;return{id:String(c.savedqueryid),name:String((d=c.name)!==null&&d!==void 0?d:"")}})}zs.findDefaultViews=MZ;async function UZ(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,Rn.odataPathLiteral)(t)}')${(0,Rn.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status>=200&&i.status<300){let o=(r=i.body)===null||r===void 0?void 0:r.ObjectTypeCode;return typeof o=="number"?o:void 0}}async function TL(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await UZ(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}zs.viewApi={async get(e,t){let r=(0,Rn.normalizeGuid)(t,"id"),n=await(0,ur.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Rn.odataQuery)([["$select",NL]]);return{raw:(0,ur.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,Rn.normalizeGuid)(t,"id"),n=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Rn.odataQuery)([["$select",NL]]),i=(0,ur.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,ur.readRowEtag)(e,"savedqueries","savedqueryid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueries${(0,Rn.odataQuery)([["$select",RZ],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,Rn.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,DL.collectPages)(e,r,"listArtifacts('view')")).map(i=>{var o,a;return{type:"view",id:(o=i.savedqueryid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.returnedtypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,ur.echoWrite)("savedqueryid"),o=`/savedqueries${i.query}`,a=await TL(e,n.layoutxml,n.returnedtypecode),s=Object.freeze((0,ur.withClientMintedId)({name:n.name,description:n.description,fetchxml:n.fetchxml,layoutxml:a,returnedtypecode:n.returnedtypecode,querytype:n.querytype,isdefault:n.isdefault},"savedqueryid",r)),l=(0,ur.ensureSuccess)(await(0,ur.resendDeadlockVictim)(()=>e.post(o,{...s},i.options)),e.apiUrl(o));return{id:(0,ur.resolveCreatedId)(l,"savedqueryid","view",r),etag:(0,ur.readEtag)(l)}},async update(e,t,r,n){let i=r,o=(0,Rn.normalizeGuid)(t,"id"),a=(0,ur.echoWrite)("savedqueryid",{"If-Match":(0,ur.requireEtag)(n,"view",o)}),s=`/savedqueries(${o})${a.query}`,l=await TL(e,i.layoutxml,i.returnedtypecode),u=(0,ur.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,fetchxml:i.fetchxml,layoutxml:l},a.options),e.apiUrl(s));return{id:o,etag:(0,ur.readEtag)(u)}},delete(e,t){return(0,ur.deleteRecord)(e,"savedqueries",t)}}});var WL=v(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.viewRegistration=js.ViewAdapter=void 0;var $L=Q(),Wr=en(),Ky=so(),ha=uo(),IL=Jr(),BZ=Hy(),Jy=lo(),qZ=dt(),xL=100,Vf=class{toArtifact(t){var r,n,i,o,a,s,l,u;(0,Jy.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",f=(0,ha.parseXmlRoot)(c,"<fetch/>"),m=(0,ha.parseXmlRoot)(d,"<grid/>"),p=ML(f);return{id:(i=t.savedqueryid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.returnedtypecode)!==null&&s!==void 0?s:GZ(f),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:FL(m,f),filters:BL(f),sort:UL(f),...p.length>0?{linkEntities:p}:{},fetchBag:c?(0,ha.projectElementBag)(f):void 0,layoutBag:d?(0,ha.projectElementBag)(m):void 0}}fromArtifact(t){(0,Jy.installDomShim)();let{fetchxml:r,layoutxml:n}=OL(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,o,a;(0,Jy.installDomShim)();let{fetchxml:s,layoutxml:l}=OL(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:(o=t.queryType)!==null&&o!==void 0?o:0,isdefault:(a=t.isDefault)!==null&&a!==void 0?a:!1}}createDefault(t){var r,n,i,o,a,s,l,u;let c=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,qZ.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New View",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:c,queryType:(a=t.queryType)!==null&&a!==void 0?a:0,isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,columns:t.columns&&t.columns.length>0?t.columns:[{name:`${c}id`,width:300,order:0}],filters:(l=t.filters)!==null&&l!==void 0?l:{type:"and",conditions:[],groups:[]},sort:(u=t.sort)!==null&&u!==void 0?u:[],...t.linkEntities&&t.linkEntities.length>0?{linkEntities:t.linkEntities}:{}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;(0,Wr.childObjects)(n,"columns","","column",r),(0,Wr.childObjects)(n,"sort","","sort",r),(0,Wr.childObjects)(n,"linkEntities","","linkEntity",r),VZ(n.linkEntities,r);let i=n.filters;return i!=null&&((0,Wr.isJsonObject)(i)?Yy(i,"/filters",r):r.push((0,Wr.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};js.ViewAdapter=Vf;function VZ(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,Wr.isJsonObject)(r))return;for(let o of["name","from","to"]){let a=r[o];(typeof a!="string"||a.trim()==="")&&t.push((0,Wr.issue)(`/linkEntities/${n}/${o}`,"linkentity-needs-keys",`a join needs a non-empty '${o}' \u2014 'from'/'to' are what DEFINE the relationship, and a link without them is unresolvable. Got ${JSON.stringify(a)}.`))}let i=r.filters;i!=null&&((0,Wr.isJsonObject)(i)?Yy(i,`/linkEntities/${n}/filters`,t):t.push((0,Wr.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function Yy(e,t,r){(0,Wr.childObjects)(e,"conditions",t,"condition",r),(0,Wr.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:o})=>Yy(i,`${t}/groups/${o}`,r))}function GZ(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function FL(e,t){var r;let n=Gf(t),i=e.getElementsByTagName("cell"),o=[],a=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)?xL:c,order:a},f=n.get(u);f&&(d.relatedEntity=f.linkKey,f.attributeName&&f.attributeName!==u&&(d.sourceAttribute=f.attributeName)),a+=1,o.push(d)}return o}function Gf(e){let t=new Map,r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("name")||"",c=l.getAttribute("alias")||u;c&&t.set(c,{linkKey:i.getAttribute("alias")||o,linkName:o,attributeName:u,link:i})}}return t}function ML(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of Ft(t,"link-entity")){let i=n.getAttribute("name"),o=n.getAttribute("from"),a=n.getAttribute("to");if(!i||!o||!a)continue;let s=n.getAttribute("alias"),l=n.getAttribute("link-type"),u=Ft(n,"filter").find(c=>!Wf(c));r.push({name:i,from:o,to:a,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:Qy(u)}:{}})}return r}function UL(e){var t;let r=e.getElementsByTagName("entity")[0];if(!r)return[];let n=[],i=r.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a.nodeType===1&&a.tagName==="order"){let s=a.getAttribute("attribute");s&&n.push({attribute:s,descending:((t=a.getAttribute("descending"))!==null&&t!==void 0?t:"").toLowerCase()==="true",entityname:a.getAttribute("entityname")||""})}}return n}function BL(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=Ft(t,"filter").filter(i=>!Wf(i)).map(Qy);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function Wf(e){if(e.getAttribute("isquickfindfields")==="1"||qL(e))return!0;if(Ft(e,"filter").length>0)return!1;let t=Ft(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||Ft(r,"value").length>0||zZ(r))}function qL(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&(n.tagName==="filter"?qL(n):n.tagName!=="condition"))return!0}return!1}var WZ=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function zZ(e){var t;let r=e.attributes;for(let n=0;n<r.length;n+=1){let i=(t=r[n])===null||t===void 0?void 0:t.name;if(i&&!WZ.has(i))return!0}return!1}function Qy(e){var t,r;let n=((t=e.getAttribute("type"))!==null&&t!==void 0?t:"and").toLowerCase()==="or"?"or":"and",i=[],o=[],a=e.childNodes;for(let s=0;s<a.length;s+=1){let l=a[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:""};l.hasAttribute("value")&&(c.value=l.getAttribute("value")||"");let d=l.getAttribute("entityname")||"";d&&(c.entityname=d),i.push(c)}else l.tagName==="filter"&&o.push(Qy(l))}return{type:n,conditions:i,groups:o}}function Ft(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}var Xy=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function jZ(e,t){let r=Gf(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=r.get(i.name);if(o){let a=Xy(i),s=n.get(a);s?s.push(o.link):n.set(a,[o.link])}}return n}function HZ(e,t,r,n){if(!n||n.size===0)return;let i=new Set,o=t.getElementsByTagName("link-entity");for(let s=0;s<o.length;s+=1)i.add(o[s]);let a=r.filter(s=>{if(!s.relatedEntity)return!1;let l=n.get(Xy(s));return!!l&&l.some(u=>!i.has(u))});if(a.length!==0)throw new $L.ValidationError("view",e.id,a.map(s=>(0,Wr.issue)(`/columns/${r.indexOf(s)}`,"view-column-orphaned-by-join-removal",`column '${s.name}' came from a join this push REMOVED. Another join matching '${s.relatedEntity}' still exists, but nothing can say whether it is the one the column belonged to \u2014 re-attaching it there would silently change the data the column shows. Remove the column too, keep the join it came from, or point the column at the join you want by setting relatedEntity to that join's alias.`)))}function OL(e){var t,r;let n=KZ(e.columns),i=(t=e.sort)!==null&&t!==void 0?t:[],o=(r=e.filters)!==null&&r!==void 0?r:{type:"and",conditions:[],groups:[]};if(!PL(e.fetchBag)||!PL(e.layoutBag))return{fetchxml:see({...e,columns:n,sort:i,filters:o}),layoutxml:lee({...e,columns:n},`${e.entityLogicalName}id`)};let a=new DOMParser().parseFromString("<root/>","text/xml"),s=RL(e.fetchBag,"fetch",a),l=RL(e.layoutBag,"grid",a),u=FL(l,s),c=!qf(n,u),d=!qf(i,UL(s)),f=!qf(o,BL(s)),m=e.linkEntities,p=m!==void 0&&!qf(m,ML(s)),h=p?jZ(s,u):void 0;return p&&iee(a,s,m),p&&(aee(e,s,n,h),HZ(e,s,n,h)),c?(LL(a,s,n,u),ZZ(a,l,n)):p&&LL(a,s,n,u),d&&ree(a,s,i),f&&nee(a,s,o),{fetchxml:(0,ha.serializeNode)(s),layoutxml:(0,ha.serializeNode)(l)}}function KZ(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:xL,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function PL(e){return!!e&&(e.c.length>0||e.a.length>0)}function RL(e,t,r){let n={n:t,a:(0,Ky.mergeAttrs)(e.a,[]),c:(0,Ky.spliceChildren)(e.c,[])};return(0,Ky.rebuildRaw)(n,(0,ha.domEngine)(r),null)}function LL(e,t,r,n){var i,o,a;let s=t.getElementsByTagName("entity")[0];if(!s)return;let l=p=>{var h,g;return`${(h=p.relatedEntity)!==null&&h!==void 0?h:""}:${p.name}:${(g=p.sourceAttribute)!==null&&g!==void 0?g:p.name}`},u=new Set(r.map(l)),c=new Set(r.map(p=>p.name)),d=Gf(t);for(let p of n)u.has(l(p))||(YZ(s,p),p.relatedEntity&&c.has(p.name)&&JZ((i=d.get(p.name))===null||i===void 0?void 0:i.link,p.name));let f=Gf(t),m=new Set(Ft(s,"attribute").map(p=>p.getAttribute("name")).filter(p=>!!p));for(let p of[...r].sort((h,g)=>h.order-g.order))if(p.relatedEntity){let h=f.get(p.name);if(h&&h.attributeName===((o=p.sourceAttribute)!==null&&o!==void 0?o:p.name)&&(h.linkKey===p.relatedEntity||h.linkName===p.relatedEntity||!GL(s,p.relatedEntity)))continue;let g=QZ(e,s,p.relatedEntity),b=e.createElement("attribute");VL(b,p),g.appendChild(b),f.set(p.name,{linkKey:p.relatedEntity,linkName:g.getAttribute("name")||p.relatedEntity,attributeName:(a=p.sourceAttribute)!==null&&a!==void 0?a:p.name,link:g})}else{if(m.has(p.name))continue;let h=e.createElement("attribute");h.setAttribute("name",p.name),XZ(s,h),m.add(p.name)}}function VL(e,t){if(t.sourceAttribute&&t.sourceAttribute!==t.name){e.setAttribute("name",t.sourceAttribute),e.setAttribute("alias",t.name);return}e.setAttribute("name",t.name)}function JZ(e,t){if(e){for(let r of Ft(e,"attribute"))if((r.getAttribute("alias")||r.getAttribute("name"))===t){e.removeChild(r);return}}}function YZ(e,t){if(t.relatedEntity){for(let r of Ft(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of Ft(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of Ft(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function GL(e,t,r=!1){let n=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of Ft(e,"link-entity"))if(n(o))return o;if(r)return;let i=e.getElementsByTagName("link-entity");for(let o=0;o<i.length;o+=1)if(n(i[o]))return i[o]}function QZ(e,t,r){let n=GL(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function XZ(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 ZZ(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),o=eee(n);if(tee(o,i)){for(let s=0;s<i.length;s+=1){let l=String(i[s].width);o[s].getAttribute("width")!==l&&o[s].setAttribute("width",l)}return}let a=new Map;for(let s of o){let l=s.getAttribute("name");l&&a.set(l,s),n.removeChild(s)}for(let s of i){let l=a.get(s.name);l||(l=e.createElement("cell"),l.setAttribute("name",s.name)),l.setAttribute("width",String(s.width)),n.appendChild(l)}}function eee(e){return Ft(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function tee(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 ree(e,t,r){let n=t.getElementsByTagName("entity")[0];if(!n)return;let i=(m,p)=>`${m.toLowerCase()}\0${p.toLowerCase()}`,o=new Map,a=new Map,s=(m,p,h)=>{let g=m.get(p);g?g.push(h):m.set(p,[h])},l=null;for(let m of Ft(n,"order")){let p=m.getAttribute("attribute")||"";p&&(l||(l=e.createTextNode(""),n.insertBefore(l,m)),s(o,i(m.getAttribute("entityname")||"",p),m),s(a,p.toLowerCase(),m),n.removeChild(m))}let u=new Set,c=(m,p)=>{let h=m.get(p);for(;h&&h.length>0;){let g=h.shift();if(!u.has(g))return u.add(g),g}},d=m=>{var p;let h=a.get(m.toLowerCase());if(!h)return;let g=h.filter(w=>!u.has(w)),b=(p=g.find(w=>!w.getAttribute("entityname")))!==null&&p!==void 0?p:g[0];return b&&u.add(b),b},f=r.map(m=>{let p=String(m.attribute);return m.entityname===void 0?{expression:m,element:void 0}:{expression:m,element:c(o,i(m.entityname,p))}});for(let m of f)m.expression.entityname===void 0&&(m.element=d(String(m.expression.attribute)));for(let{expression:m,element:p}of f){let h=p??e.createElement("order");h.setAttribute("attribute",m.attribute),h.setAttribute("descending",String(m.descending)),m.entityname?h.setAttribute("entityname",m.entityname):m.entityname===""&&h.removeAttribute("entityname"),n.insertBefore(h,l)}l&&n.removeChild(l)}function nee(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Ft(n,"filter"))Wf(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(zu(e,r))}}function qf(e,t){return JSON.stringify(e)===JSON.stringify(t)}function iee(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=Ft(i,"link-entity").filter(p=>p.getAttribute("name")&&p.getAttribute("from")&&p.getAttribute("to")),a=(p,h)=>p.getAttribute(h)||"",s=new Array(r.length),l=new Set,u=p=>{r.forEach((h,g)=>{if(s[g])return;let b=o.filter(S=>!l.has(S)&&p(S,h));if(b.length!==1)return;let w=b[0];r.some((S,P)=>P!==g&&!s[P]&&p(w,S))||(s[g]=w,l.add(w))})};u((p,h)=>!!h.alias&&a(p,"name")===h.name&&a(p,"alias")===h.alias),u((p,h)=>a(p,"name")===h.name&&a(p,"from")===h.from&&a(p,"to")===h.to),u((p,h)=>a(p,"name")===h.name&&a(p,"from")===h.from),u((p,h)=>a(p,"name")===h.name&&a(p,"to")===h.to),u((p,h)=>a(p,"name")===h.name);let c=r.map((p,h)=>h).filter(p=>!s[p]),d=o.filter(p=>!l.has(p)),f=new Map;for(let p of d){let h=f.get(a(p,"name"));h?h.push(p):f.set(a(p,"name"),[p])}let m=new Map;for(let p of c){let h=m.get(r[p].name);h?h.push(p):m.set(r[p].name,[p])}for(let[p,h]of m){let g=(n=f.get(p))!==null&&n!==void 0?n:[];g.length===h.length&&h.forEach((b,w)=>{s[b]=g[w],l.add(g[w])})}r.forEach((p,h)=>{let g=s[h];if(g){kL(e,g,p);return}let b=e.createElement("link-entity");kL(e,b,p),i.appendChild(b)});for(let p of o)l.has(p)||i.removeChild(p)}var oee=new Set(["inner","outer"]);function aee(e,t,r,n){if(!t.getElementsByTagName("entity")[0])return;let o=new Set,a=t.getElementsByTagName("link-entity");for(let c=0;c<a.length;c+=1){let d=a[c],f=d.getAttribute("name"),m=d.getAttribute("alias");f&&o.add(f),m&&o.add(m)}let s=new Set;for(let c=0;c<a.length;c+=1)s.add(a[c]);let l=c=>{let d=n?.get(Xy(c));return!!d&&d.every(f=>s.has(f))},u=r.filter(c=>c.relatedEntity&&!o.has(c.relatedEntity)&&!l(c));if(u.length!==0)throw new $L.ValidationError("view",e.id,u.map(c=>{var d;let f=((d=e.linkEntities)!==null&&d!==void 0?d:[]).some(m=>m.name===c.relatedEntity||m.alias===c.relatedEntity);return(0,Wr.issue)(`/columns/${r.indexOf(c)}`,"view-column-dangling-link",`column '${c.name}' has relatedEntity '${c.relatedEntity}', but no matching join remains in linkEntities. `+(f?"Remove the column too, or keep the join.":"That join is NESTED (a join off a join), which the typed layer does not model, so it cannot be re-declared in linkEntities \u2014 it only survives while the join above it does. Remove the column, or restore the parent join this push replaced."))}))}function kL(e,t,r){t.setAttribute("name",r.name),t.setAttribute("from",r.from),t.setAttribute("to",r.to),r.alias?t.setAttribute("alias",r.alias):t.removeAttribute("alias"),r.linkType?t.setAttribute("link-type",r.linkType):oee.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=Ft(t,"filter").find(o=>!Wf(o)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?zu(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function see(e){var t;let r=new DOMParser().parseFromString("<fetch/>","text/xml"),n=r.documentElement;n.setAttribute("version","1.0"),n.setAttribute("mapping","logical");let i=r.createElement("entity");i.setAttribute("name",e.entityLogicalName),n.appendChild(i);let o=new Map;for(let a of(t=e.linkEntities)!==null&&t!==void 0?t:[]){let s=r.createElement("link-entity");s.setAttribute("name",a.name),s.setAttribute("from",a.from),s.setAttribute("to",a.to),a.alias&&s.setAttribute("alias",a.alias),a.linkType&&s.setAttribute("link-type",a.linkType),a.filters&&(a.filters.conditions.length>0||a.filters.groups.length>0)&&s.appendChild(zu(r,a.filters)),i.appendChild(s);for(let l of[a.alias||a.name,a.name])o.has(l)||o.set(l,s)}for(let a of[...e.columns].sort((s,l)=>s.order-l.order)){let s=r.createElement("attribute");if(a.relatedEntity){VL(s,a);let l=o.get(a.relatedEntity);l||(l=r.createElement("link-entity"),l.setAttribute("name",a.relatedEntity),i.appendChild(l),o.set(a.relatedEntity,l)),l.appendChild(s)}else s.setAttribute("name",a.name),i.appendChild(s)}for(let a of e.sort){let s=r.createElement("order");s.setAttribute("attribute",a.attribute),s.setAttribute("descending",String(a.descending)),a.entityname&&s.setAttribute("entityname",a.entityname),i.appendChild(s)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&i.appendChild(zu(r,e.filters)),new XMLSerializer().serializeToString(r)}function zu(e,t){let r=e.createElement("filter");r.setAttribute("type",t.type);for(let n of t.conditions){let i=e.createElement("condition");i.setAttribute("attribute",n.attribute),i.setAttribute("operator",n.operator),n.entityname&&i.setAttribute("entityname",n.entityname),n.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(zu(e,n));return r}function lee(e,t){var r;let n=new DOMParser().parseFromString("<grid/>","text/xml"),i=n.documentElement,o=[...e.columns].sort((s,l)=>s.order-l.order);i.setAttribute("name","resultset"),i.setAttribute("jump",((r=o[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 a=n.createElement("row");a.setAttribute("name","result"),a.setAttribute("id",t||`${e.entityLogicalName}id`),i.appendChild(a);for(let s of o){let l=n.createElement("cell");l.setAttribute("name",s.name),l.setAttribute("width",String(s.width)),a.appendChild(l)}return new XMLSerializer().serializeToString(n)}function uee(){return{adapter:new Vf,api:BZ.viewApi,publish:(e,t,r)=>(0,IL.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,IL.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}js.viewRegistration=uee});function zf(e,t){return e==="SetFieldValue"&&t!==void 0&&cee.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var cee,Zy=k(()=>{"use strict";cee=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function zL(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function eb(e){return e==="AllForms"||zL(e)?1:2}function tb(e){return zL(e)?e:null}function jL(e,t){return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:e.name,description:e.description,workflowid:t,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:Hs.WorkflowCategory.BusinessRule,type:Hs.WorkflowTypeCode.Definition,mode:1,scope:Hs.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:eb(e.scope),processtriggerformid:tb(e.scope)}}var Hs,HL=k(()=>{"use strict";Hs=Ee(Yi());});function KL(e,t=0){return(Mt[e[t+0]]+Mt[e[t+1]]+Mt[e[t+2]]+Mt[e[t+3]]+"-"+Mt[e[t+4]]+Mt[e[t+5]]+"-"+Mt[e[t+6]]+Mt[e[t+7]]+"-"+Mt[e[t+8]]+Mt[e[t+9]]+"-"+Mt[e[t+10]]+Mt[e[t+11]]+Mt[e[t+12]]+Mt[e[t+13]]+Mt[e[t+14]]+Mt[e[t+15]]).toLowerCase()}var Mt,JL=k(()=>{Mt=[];for(let e=0;e<256;++e)Mt.push((e+256).toString(16).slice(1))});function rb(){return jf>Hf.length-16&&((0,YL.randomFillSync)(Hf),jf=0),Hf.slice(jf,jf+=16)}var YL,Hf,jf,QL=k(()=>{YL=require("crypto"),Hf=new Uint8Array(256),jf=Hf.length});var XL,nb,ZL=k(()=>{XL=require("crypto"),nb={randomUUID:XL.randomUUID}});function dee(e,t,r){if(nb.randomUUID&&!t&&!e)return nb.randomUUID();e=e||{};let n=e.random??e.rng?.()??rb();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 KL(n)}var cr,ek=k(()=>{ZL();QL();JL();cr=dee});var ib=k(()=>{ek()});var tk=k(()=>{"use strict";});function rk(e){return e!=null&&fee.has(e)}function Kf(e){if(e==null)return!1;let t=e.trim();if(!/^[+-]?\d+$/.test(t))return!1;let r=Number(t);return Number.isInteger(r)&&r>=-2147483648&&r<=2147483647}var fee,ob=k(()=>{"use strict";fee=new Set(["Picklist","State","Status"])});var Jf=v(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.WorkflowConditionOperator=dn.WorkflowAttributeType=dn.SystemStep=dn.FieldRequiredLevelTypes=dn.AttributeDateTimeBehavior=void 0;dn.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};dn.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};dn.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};dn.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"};dn.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 Yf(e){return e!=null&&ik.includes(e)}function ab(e){return e===oe.WorkflowAttributeType.Integer}function sb(e,t){return t===oe.WorkflowConditionOperator.Equal||t===oe.WorkflowConditionOperator.NotEqual?e:pee.includes(t)?ik.includes(e)||e===oe.WorkflowAttributeType.DateTime?e:oe.WorkflowAttributeType.String:t===oe.WorkflowConditionOperator.On||t===oe.WorkflowConditionOperator.NotOn?e===oe.WorkflowAttributeType.DateTime?e:oe.WorkflowAttributeType.String:oe.WorkflowAttributeType.String}function ok(e){let t=e.leftWorkflowType??e.valueWorkflowType??oe.WorkflowAttributeType.String,r=ju[e.operator]??oe.WorkflowConditionOperator.Equal;return sb(t,r)}function ak(e,t){let r=e.trim(),i=(r.startsWith("+")||r.startsWith("-")?r.slice(1):r).split(".");if(i.length>2)return!1;let[o,a=""]=i;return o.length===0&&a.length===0||!nk.test(o)||!nk.test(a)||o.length>1&&o.startsWith("0")||o.length>mee?!1:t!==oe.WorkflowAttributeType.Integer||i.length===1}var oe,ju,ik,pee,nk,mee,lb=k(()=>{"use strict";oe=Ee(Jf());ju={Equals:oe.WorkflowConditionOperator.Equal,DoesNotEqual:oe.WorkflowConditionOperator.NotEqual,IsGreaterThan:oe.WorkflowConditionOperator.GreaterThan,IsLessThan:oe.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:oe.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:oe.WorkflowConditionOperator.LessThanOrEqual,Contains:oe.WorkflowConditionOperator.Contains,DoesNotContain:oe.WorkflowConditionOperator.DoesNotContain,BeginsWith:oe.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:oe.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:oe.WorkflowConditionOperator.EndsWith,DoesNotEndWith:oe.WorkflowConditionOperator.DoesNotEndWith,On:oe.WorkflowConditionOperator.On,NotOn:oe.WorkflowConditionOperator.NotOn,ContainsData:oe.WorkflowConditionOperator.NotNull,DoesNotContainData:oe.WorkflowConditionOperator.IsNull},ik=[oe.WorkflowAttributeType.Decimal,oe.WorkflowAttributeType.Float,oe.WorkflowAttributeType.Integer,oe.WorkflowAttributeType.Money],pee=[oe.WorkflowConditionOperator.GreaterThan,oe.WorkflowConditionOperator.GreaterThanOrEqual,oe.WorkflowConditionOperator.LessThan,oe.WorkflowConditionOperator.LessThanOrEqual];nk=/^\d*$/,mee=28});var sk=k(()=>{"use strict";});function Ln(e){return!hee.has(e)}function ub(e){return e==="Equals"||e==="DoesNotEqual"}function Qf(e){return uk.has(e)?gee:Cee.has(e)?yee:ck.has(e)?bee:Aee.has(e)?wee:vee}function dk(e){return Qf(e)[0]}function fk(e,t){return Qf(t).includes(e)}function lk(e){return uk.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":ck.has(e)?"date":Eee.has(e)?"boolean":"other"}function Xf(e,t){let r=lk(e),n=lk(t);return r==="other"||n==="other"?e===t:r===n}var hee,gee,yee,bee,vee,wee,uk,Cee,ck,Eee,Aee,Zf=k(()=>{"use strict";sk();hee=new Set(["ContainsData","DoesNotContainData"]);gee=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],yee=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],bee=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],vee=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],wee=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],uk=new Set(["String","Memo","EntityName"]),Cee=new Set(["Integer","BigInt","Money","Decimal","Double"]),ck=new Set(["DateTime"]),Eee=new Set(["Boolean"]),Aee=new Set(["Lookup","Owner","Customer"])});function gk(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 Ak(e){return e&&e!==Fe.WorkflowAttributeType.String?e:void 0}function _ee(e){return{__class:Ek,parameterName:"primaryEntity",entityName:e}}function pk(e){return{__class:db,type:cb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:yk,parameters:[e]}}function mk(e,t,r=Fe.WorkflowAttributeType.String){return{__class:vk,type:r,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,entity:_ee(t),attributeName:e}}function Tee(e,t=Fe.WorkflowAttributeType.String){return{__class:wk,type:t,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function Dee(e){return{__class:Ck,type:cb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function Sk(e,t){let r=See[e.operator],n=pk(mk(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=Dee(e.right.value??"0"):e.right.kind==="field"?i=mk(e.right.field??"",t,e.right.workflowType):i=Tee(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=pk(i);return{__class:db,type:cb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:bk,parameters:[r,n,o]}}function Nk(e){return typeof e=="object"&&e.__class===db}function Iee(e){return typeof e=="object"&&e.__class===Ck}function ep(e){return Nk(e)&&e.method===yk&&e.parameters.length>0?ep(e.parameters[0]):e}function hk(e){if(typeof e!="object"||e.__class!==vk)return null;let t=e.entity;if(t&&t.__class&&t.__class!==Ek)return null;let r=e.attributeName;return r?{field:r,workflowType:Ak(e.type)}:null}function _k(e){if(!e)return null;let t=ep(e);if(!Nk(t)||t.method!==bk||t.parameters.length!==3)return null;let r=t.parameters[0],n=Nee[String(r)];if(!n)return null;let i=hk(ep(t.parameters[1]));if(!i)return null;let o=ep(t.parameters[2]);if(Iee(o))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=hk(o);if(a)return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"field",field:a.field,workflowType:a.workflowType}};if(typeof o=="object"&&o.__class===wk){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:Ak(o.type)}}}return null}function pb(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=fb&&r<=Ks}function ga(e){if(!e||!e.leftField)return"incomplete";if(e.right.kind==="field")return e.right.field&&e.right.field.trim()?null:"incomplete";let t=e.right.value;return!t||!t.trim()?"incomplete":e.dateArithmetic&&!pb(t)?"invalidDayCount":null}function Js(e){return ga(e)===null}var Fe,yk,bk,cb,vk,wk,db,Ck,Ek,See,Nee,fb,Ks,Hu=k(()=>{"use strict";Fe=Ee(Jf());Zf();yk="0",bk="3",cb="0",vk="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",wk="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",db="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",Ck="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",Ek="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";See={"+":0,"-":1,"*":2,"/":3},Nee={0:"+",1:"-",2:"*",3:"/"};fb=0,Ks=2147483647});function Pee(e){return e.startsWith("__")&&!Oee.has(e)}function Ree(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{Pee(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function Bk(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function ba(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function tp(e){return Bk(e)||ba(e)}function Lee(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function Ku(){return{list:[]}}function mb(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:cr(),languageCode:r,description:t}]}}function gb(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function op(e,t,r,n=z.AttributeDateTimeBehavior.None){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:n,typeSet:!1,entity:gb(t),attributeName:e}}function ya(e,t,r=z.AttributeDateTimeBehavior.None){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:r,typeSet:!1,primitiveValue:e}}function xee(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?Gk:Vk:qk}function Wk(e){return e.bpfField==="StageCategory"?z.WorkflowAttributeType.BpfStageCategory:z.WorkflowAttributeType.BpfProcess}function Fee(e,t){let r=Wk(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${Dk}_${Tk}`,entityName:Tk,relatedAttributeName:Dk},attributeName:$ee}:op(kee,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,method:vb,parameters:[xee(e),n]}}function zk(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==vb)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===Vk?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===Gk?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===qk?{bpfField:"ProcessName"}:null}function rp(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===vb){let r=(t.parameters??[])[0];if(typeof r=="string"&&Mee.has(r.replace(/^"+|"+$/g,"")))return!0}return ba(e)?rp(e.operand):Bk(e)?rp(e.left)||(e.right??[]).some(rp):!1}function jk(e){if(e?.__class!=="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.entity;return t==null||t.__class==="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions"}function Uee(e){if(e?.__class!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.primitiveValue;return t===!0||typeof t=="string"&&t.toLowerCase()==="true"}function Ik(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return jk(e);case"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions":return e.primitiveValue!=null||e.type!==void 0;case"LookupExpression:#Microsoft.Crm.Workflow.Expressions":case"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions":return!0;default:return!1}}function Bee(e){let t=bb[e.conditionOperatoroperator];if(!t)return!1;let r=t==="ContainsData"||t==="DoesNotContainData";if(ba(e))return r&&Ok(e.operand,!0);let n=e.right??[];return n.length!==(r?0:1)?!1:Ok(e.left,r,n[0])}function Ok(e,t,r){return zk(e)||jk(e)?t||Ik(r):!1}function yb(e){if(!e||!tp(e))return!1;let t=e.conditionOperatoroperator;if(!ba(e)&&(t===z.WorkflowConditionOperator.LogicalAnd||t===z.WorkflowConditionOperator.LogicalOr)){let r=e.right??[];return r.length>0&&yb(e.left)&&r.every(yb)}return Bee(e)}function Pk(e){return!e||Uee(e)?!1:rp(e)||!yb(e)}function Hk(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:ya(e.id.replace(/[{}]/g,""),z.WorkflowAttributeType.UniqueIdentifier)}}function Vee(e){return e===z.WorkflowAttributeType.DateTime?z.AttributeDateTimeBehavior.DateOnly:z.AttributeDateTimeBehavior.None}function Gee(e,t){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let r=e.leftDateTimeBehavior;return r!==void 0&&r!==z.AttributeDateTimeBehavior.None?r:Vee(t)}function Wee(e,t,r){if(t!==z.WorkflowAttributeType.DateTime)return z.AttributeDateTimeBehavior.None;let n=e.valueFieldDateTimeBehavior;return n!==void 0&&n!==z.AttributeDateTimeBehavior.None?n:r}function jee(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return"1";if(t==="false"||t==="0")return"0"}function ete(e){let t=Zee.exec(e);if(t)return`${t[1]}T${t[2]}`;let r=Xee.exec(e);if(!r)return;let[,n,i,o,a,s,l]=r,u=Qee.indexOf(i.toLowerCase());if(u<0)return;let c=String(u+1).padStart(2,"0");return`${o}-${c}-${n}T${a}:${s}:${l}`}function tte(e){let t=ete(e.trim());return t!==void 0&&Kk(t)?t:e}function Kk(e){let t=e.trim(),r=t.indexOf("T")>=0?"T":" ",n=t.indexOf(r),i=n>=0?t.slice(0,n):t,o=n>=0?t.slice(n+1):"";if(!Hee.test(i)||o.length>0&&!Kee.test(o)&&!Jee.test(o)&&!Yee.test(o))return!1;let[a,s,l]=i.split("-"),u=new Date(`${a}-${s}-${l}T00:00:00Z`);return!Number.isNaN(u.getTime())&&u.getUTCFullYear()===Number(a)&&u.getUTCMonth()+1===Number(s)&&u.getUTCDate()===Number(l)}function rte(e,t){let r={value:e,type:z.WorkflowAttributeType.String};if(t===z.WorkflowAttributeType.String||zee.includes(t)||e.trim().length===0)return r;if(t===z.WorkflowAttributeType.Boolean){let n=jee(e);return n==null?r:{value:n,type:t}}return qee.includes(t)?Kf(e)?{value:e.trim(),type:t}:r:Yf(t)?{value:e.trim(),type:t}:t===z.WorkflowAttributeType.DateTime&&Kk(e)?{value:e.trim(),type:t}:r}function Rk(e){return e==="ContainsData"||e==="DoesNotContainData"}function Lk(e){return nte.has(e)}function kk(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function $k(e,t){let r=e.leftWorkflowType??e.valueWorkflowType??z.WorkflowAttributeType.String,n=ju[e.operator]??z.WorkflowConditionOperator.Equal,i=Gee(e,r),o=sb(r,n);if(e.source==="BusinessProcess"){let l=Fee(e,t);if(Rk(e.operator))return kk(l,n);let u=Wk(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:l,right:[ya(e.value??"",u)]}}let a=op(e.field,t,r,i);if(Rk(e.operator))return kk(a,n);let s;if(e.valueType==="Field"&&e.valueField){let l=Lk(o)&&Lk(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:o;s=[op(e.valueField,t,l,Wee(e,l,i))]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[Hk(e.lookupValue)]}else if(e.valueType==="Clear")s=[ya(null,z.WorkflowAttributeType.String,i)];else if(e.valueType==="Expression")s=[ip(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)];else{let l=rte(e.value??"",o);s=[ya(l.value,l.type,i)]}return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:a,right:s}}function ite(){return ya(!0,z.WorkflowAttributeType.Boolean)}function ote(e,t,r){if(e.length===0)return null;let n=$k(e[0],r);for(let i=1;i<e.length;i++){let o=e[i].connector??t;n={__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:z.WorkflowAttributeType.Boolean,behavior:z.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?z.WorkflowConditionOperator.LogicalAnd:z.WorkflowConditionOperator.LogicalOr,left:n,right:[$k(e[i],r)]}}return n}function np(e){if(!e)return{valueType:"Value",value:""};if(e.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return{valueType:"Field",valueField:e.attributeName,valueFieldWorkflowType:e.type};if(e.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"){if(e.primitiveValue==null)return{valueType:"Clear",valueWorkflowType:e.type};let t=String(e.primitiveValue);if(e.type===z.WorkflowAttributeType.Boolean){let r=t.trim().toLowerCase();if(r==="1"||r==="true")return{valueType:"Value",value:"true",valueWorkflowType:e.type};if(r==="0"||r==="false")return{valueType:"Value",value:"false",valueWorkflowType:e.type}}return e.type===z.WorkflowAttributeType.DateTime?{valueType:"Value",value:tte(t),valueWorkflowType:e.type}:{valueType:"Value",value:t,valueWorkflowType:e.type}}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=_k(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function ate(e){let t=bb[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=ba(e)?e.operand:e.left,i=ba(e)?[]:e.right??[],o=zk(n);if(o){let g=i[0];return{id:cr(),field:"",fieldDisplayName:"",source:"BusinessProcess",bpfField:o.bpfField,...o.stageType?{stageType:o.stageType}:{},operator:t,valueType:"Value",value:g?.primitiveValue!=null&&!r?String(g.primitiveValue):""}}let a=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",s=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?n.attributeName:"",l=a?n.type:void 0,u=r?{valueType:"Value"}:np(i[0]),c=l,d=a&&n.type===z.WorkflowAttributeType.DateTime&&n.behavior!==z.AttributeDateTimeBehavior.None?n.behavior:void 0,f=u.valueWorkflowType??l,m=r?void 0:i[0],h=m?.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"&&m.type===z.WorkflowAttributeType.DateTime&&m.behavior!==z.AttributeDateTimeBehavior.None?m.behavior:void 0;return{id:cr(),field:s,fieldDisplayName:s,operator:t,...u,...f?{valueWorkflowType:f}:{},...c?{leftWorkflowType:c}:{},...d!==void 0?{leftDateTimeBehavior:d}:{},...h!==void 0?{valueFieldDateTimeBehavior:h}:{}}}function xk(e){if(!e||!tp(e))return{clauses:[],logic:"AND"};let t=[],r=(o,a)=>{let s=o.conditionOperatoroperator;if(ba(o)||s!==z.WorkflowConditionOperator.LogicalAnd&&s!==z.WorkflowConditionOperator.LogicalOr){t.push({...ate(o),...a?{connector:a}:{}});return}let l=s===z.WorkflowConditionOperator.LogicalAnd?"AND":"OR";tp(o.left)&&r(o.left,a),(o.right??[]).filter(tp).forEach(u=>r(u,l))};r(e,void 0);let i=t.slice(1).map(o=>o.connector??"AND")[0]??"AND";return{clauses:t,logic:i}}function ip(e,t,r,n,i,o,a,s){if(e==="Field"&&r)return op(r,n,z.WorkflowAttributeType.String);if(e==="Expression"){if(i)return Sk(i,n);if(o!=null)return o}return e==="Lookup"&&a?Hk(a):e==="Clear"?ya(null,s??z.WorkflowAttributeType.String):ya(t??"",z.WorkflowAttributeType.String)}function hb(e,t){return{propertyName:e,propertyValueExpr:t}}function Ys(e){return`Step_${e.value++}`}function fn(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 Fk(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):fn(t,r)}function ste(e){return e===Uk.StateCode.Activated?"Active":"Draft"}function lte(e){let t={},r=e;typeof r.ismanaged=="boolean"&&(t.isManaged=r.ismanaged);let n=r.iscustomizable;return typeof n=="boolean"?t.isCustomizable=n:n!==null&&typeof n=="object"&&typeof n.Value=="boolean"&&(t.isCustomizable=n.Value),t}function ute(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function Jk(e,t=1033){return new Qs({languageCode:t}).serialize(e)}function Yk(e){return new Qs().deserialize(e)}var Uk,z,Oee,bb,vb,qk,Vk,Gk,kee,$ee,Tk,Dk,Mee,qee,zee,Hee,Kee,Jee,Yee,Qee,Xee,Zee,nte,wb,Qs,Cb=k(()=>{"use strict";ib();Uk=Ee(Yi());tk();ob();lb();Hu();z=Ee(Jf());Oee=new Set(["__class"]);bb={};for(let e of Object.keys(ju))bb[ju[e]]=e;vb="23",qk="BpfProcess",Vk="ActiveStageCategory",Gk="SelectedStageCategory",kee="processid",$ee="stagecategory",Tk="processstage",Dk="stageid";Mee=new Set(["ActiveStage","SelectedStage","Stage"]);qee=[z.WorkflowAttributeType.Picklist,z.WorkflowAttributeType.State,z.WorkflowAttributeType.Status];zee=[z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Customer,z.WorkflowAttributeType.Owner];Hee=/^\d{4}-\d{2}-\d{2}$/,Kee=/^\d{2}:\d{2}$/,Jee=/^\d{2}:\d{2}:\d{2}$/,Yee=/^\d{2}:\d{2}:\d{2}\.\d{1,7}$/,Qee=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],Xee=/^[A-Za-z]{3}, (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/,Zee=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2}\.\d{1,7}|\d{2}:\d{2}:\d{2}|\d{2}:\d{2})Z$/;nte=new Set([z.WorkflowAttributeType.Lookup,z.WorkflowAttributeType.Owner,z.WorkflowAttributeType.Customer]);wb={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"};Qs=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>wb[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)]:[],o={...r?.reservedProperties??{},__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:r?.id??t.ruleId??cr(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:Ku(),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(o)}makeApplyActionStep(t){return{__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",id:fn("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??Ys(this.stepCounter),stepLabels:{list:[]},specification:hb(t.field,ip(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:gb(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),o=t??"",a=n?.stepLabels,s=mb(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:Fk(n?.id,"ActionStep",this.idCounter),name:n?.name??Ys(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??cr(),uniqueName:n?.uniqueName??`id_${cr().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=gb(this.entityName),n=t.stepName??Ys(this.stepCounter),i=t.stepLabels??Ku(),o={name:n,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:fn("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:hb(t.field,ip(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:fn("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:hb(t.field,ip(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:fn("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...o,id:fn("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{...o,id:fn("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=mb(t.stepLabels,s,this.languageCode);return{...o,id:fn("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=mb(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:fn("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: ${a}`)}}serializeConditionNode(t){let r=t.stepName??Ys(this.stepCounter),n=fn("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??ote(o.clauses,o.logic,this.entityName),l=a?o.branchName??Ys(this.stepCounter):Ys(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?Fk(o.branchId,"ConditionBranchStep",this.idCounter):fn("ConditionBranchStep",this.idCounter),name:l,description:o.displayName,stepLabels:Ku(),conditionExpression:s??(a?ite():void 0),steps:{list:o.trueBranch.map(f=>this.serializeBranchItem(f))}};i.push(c);let d=o.falseBranch;if(d.length===1&&d[0].kind==="condition"){o=d[0],a=!1;continue}d.length>0&&i.push(this.makeTerminalElseBranch(d)),o=void 0}return{__class:"ConditionStep:#Microsoft.Crm.Workflow.ObjectModel",id:n,name:r,description:"",stepLabels:Ku(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:fn("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:Ku(),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 o=JSON.parse(t.wfomJson);i={id:o.id==="WorkflowStep0"||!o.id?t.workflowid??cr():o.id,name:o.name,description:o.description,nextStepIndex:o.nextStepIndex,category:o.category==="0"||o.category===0?"2":o.category,businessProcessType:o.businessProcessType,mode:o.mode,title:o.title||t.name||"",primaryEntityName:o.primaryEntityName==="1"||!o.primaryEntityName?t.primaryentity??"":o.primaryEntityName,workflowEntityId:o.workflowEntityId==="00000000-0000-0000-0000-000000000000"||!o.workflowEntityId?t.workflowid??"":o.workflowEntityId,formId:o.formId,variables:o.variables,inputs:o.inputs,reservedProperties:Ree(o)};let s=(o.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:ute(r,i?.formId),status:ste(t.statecode),rootCondition:n,wfomRoot:i,...lte(t)}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(Lee);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...o]=t,{clauses:a,logic:s}=xk(i?.conditionExpression),l=this.deserializeBranch(i?.steps?.list??[]),u=this.deserializeElseChain(o,r),c=i?.description||i?.name||r.description||r.name||this.label("condition");return{kind:"condition",id:(n?r.id:i?.id)??cr(),displayName:c,clauses:a,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,...Pk(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=xk(n.conditionExpression);return i.length===0&&!Pk(n.conditionExpression)?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},o=n.stepLabels?.list,a=o&&o.length>0?o[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||cr(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...np(u?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=np(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=np(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:o,acceptanceText:a}=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:a,applyActions:i,recommendationActionStepMeta:o}}return{kind:"action",id:t.id,type:"ShowErrorMessage",displayName:t.description||this.label("showErrorMessage"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,errorMessage:n||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:r,meta:n,acceptanceText:i}=this.parseRecommendationApplyActions({list:[t]});return{kind:"action",id:t.id,type:"Recommendation",displayName:t.name||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.actionControl?.controlId??"",recommendationTitle:t.name||"",messageText:t.description||"",acceptanceText:i,applyActions:r,recommendationActionStepMeta:n}}default:return null}}}});var Qk=k(()=>{"use strict";});function mte(e){return typeof e=="object"&&e!==null?e:null}function Xs(e){let t=mte(e);if(!t)return!1;if(t.__class===fte){let r=t;return String(r.method)===pte?!0:Array.isArray(r.parameters)&&r.parameters.some(Xs)}if(t.__class===dte)return Xs(t.operand);if(t.__class===cte){let r=t;return Xs(r.left)||Array.isArray(r.right)&&r.right.some(Xs)}return!1}var cte,dte,fte,pte,Xk=k(()=>{"use strict";Qk();cte="BinaryExpression:#Microsoft.Crm.Workflow.Expressions",dte="UnaryExpression:#Microsoft.Crm.Workflow.Expressions",fte="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",pte="23"});function Nb(e){return hte.has(e.type)}function Eb(e,t,r,n,i,o,a){let s=i.get(r);!s||!t1.has(s.attributeType)||n!=="Value"||a?.operator&&!ub(a.operator)||o.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:a?.target,itemId:a?.itemId,messageKey:"Validation.InvalidValueTypeForField",messageParams:{label:t}})}function gte(e,t){let r=t.get(e.field);return!!r&&t1.has(r.attributeType)&&ub(e.operator)}function Ab(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function Sb(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${Ks}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:Ks}}}function Zk(e,t,r,n,i,o,a,s){if(i!=="Clear")return;let l=o.get(n);zf(r,l)||a.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 sp(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if(Nb(t))return!0}else if(sp(t))return!0;return!1}function _b(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=_b(r,t);if(n)return n}}return null}function yte(e){if(!e||typeof e!="object")return!1;let{__class:t,primitiveValue:r}=e;return t!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?!1:r===!0||typeof r=="string"&&r.toLowerCase()==="true"}function bte(e){return e.clauses.length===0&&(e.rawConditionExpression===void 0||yte(e.rawConditionExpression))}function wte(e){return!!e.clauses?.some(t=>t.source==="BusinessProcess")||Xs(e.rawConditionExpression)}function Zs(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=Zs(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=Zs(n,t);if(i)return i}}return null}function Tb(e,t){return{...e,trueBranch:e1(e.trueBranch,t),falseBranch:e1(e.falseBranch,t)}}function e1(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?Tb(r,t):r)}function _o(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?_o(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?_o(n,t,r):n)}}function ap(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?ap(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?ap(n,t,r):n)}}function r1(e,t,r,n){return _o(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function Db(e){return e.length===1&&e[0].kind==="condition"}function Ete(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(Db(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function Ate(e){return!!e&&Ete(e)<Cte}function Ste(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let o=[];if(Db(n.falseBranch)){let a=r(n.falseBranch[0],i);if(a)return a}else o.push(...n.falseBranch.filter(a=>a.kind==="condition"));o.push(...n.trueBranch.filter(a=>a.kind==="condition"));for(let a of o){let s=r(a,a);if(s)return s}};return r(e,e)}function n1(e,t,r){let n=Ste(e,t);return!n||!Ate(n)?e:_o(e,t,i=>i1(i,r))}function i1(e,t){if(Db(e.falseBranch))return{...e,falseBranch:[i1(e.falseBranch[0],t)]};let r=Ib(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function o1(e,t){let r=Zs(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 _o(e,r.node.id,o=>({...o,falseBranch:i}))}function a1(e,t,r){let n=Zs(e,t);if(!n)return e;let i=o=>{let a=[...o],s=a[n.index+r];return s?(a[n.index+r]=a[n.index],a[n.index]=s,a):o};return _o(e,n.node.id,o=>({...o,trueBranch:n.branch==="true"?i(o.trueBranch):o.trueBranch,falseBranch:n.branch==="false"?i(o.falseBranch):o.falseBranch}))}function Ib(e){return{kind:"condition",id:cr(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function s1(e,t){let r={kind:"action",id:cr(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:cr(),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 l1(e){if(!e)return[];let t=[];return u1(e,t),[...new Set(t)]}function u1(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?u1(r,t):"field"in r&&r.field&&t.push(r.field)})}function c1(e,t=[],r){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition.",target:"node"}];let n=[],i=new Map(t.map(o=>[o.logicalName,o]));return f1(e,n,i,!0),r==="Entity"&&d1(e,n),sp(e)||n.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),n}function d1(e,t){wte(e)&&t.push({nodeId:e.id,kind:"BPF_IN_ENTITY_SCOPE",message:"Process based conditions are not allowed in Entity scope.",target:"node",messageKey:"Validation.ProcessConditionNotAllowedInEntityScope"}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"&&d1(r,t)})}function f1(e,t,r,n=!1){let i=n&&bte(e),o=!!e.rawConditionExpression;e.clauses.length===0&&!n&&!o&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition.",target:"node",messageKey:"Validation.AddClause"}),i&&e.falseBranch.length>0&&t.push({nodeId:e.id,kind:"UNREACHABLE_ELSE",message:"Add a condition to the IF clause, or delete the ELSE clause it can never reach.",target:"node",messageKey:"Validation.UnreachableElse"}),e.clauses.forEach(a=>{if(o)return;if(a.source==="BusinessProcess"){a.bpfField?a.value||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id}):t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a business process field for this clause.",target:"clauseField",itemId:a.id,messageKey:"Validation.SelectBusinessProcessField"});return}let s=a.valueType==="Expression"&&!a.rawExpression?ga(a.expression):null;if(!a.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause.",target:"clauseField",itemId:a.id});else if(Ln(a.operator)&&a.valueType==="Value"&&!a.value&&!gte(a,r))t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id});else if(Ln(a.operator)&&a.valueType==="Value"&&a.value){let u=r.get(a.field);u?.maxLength&&a.value.length>u.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${u.maxLength} characters.`,target:"clauseValue",itemId:a.id,messageParams:{maxLength:u.maxLength}})}else Ln(a.operator)&&a.valueType==="Expression"&&!a.rawExpression&&!Js(a.expression)?t.push(s==="invalidDayCount"?Sb(e.id,"clauseValue",a.id):{nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.CompleteClauseFormula"}):Ln(a.operator)&&a.valueType==="Field"&&!a.valueField&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a field to compare to for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseCompareField"});Ln(a.operator)&&a.valueType==="Value"&&a.value&&rk(r.get(a.field)?.attributeType)&&!Kf(a.value)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_OPTION_VALUE",message:"Please enter a whole number option value for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.InvalidClauseOptionValue"});let l=ok(a);Ln(a.operator)&&a.valueType==="Value"&&a.value&&Yf(l)&&!ak(a.value,l)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_NUMERIC_VALUE",message:ab(l)?"Please enter a whole number for this clause.":"Please enter a valid number for this clause.",target:"clauseValue",itemId:a.id,messageKey:ab(l)?"Validation.InvalidClauseWholeNumberValue":"Validation.InvalidClauseNumericValue"}),Ln(a.operator)&&a.valueType==="Lookup"&&(Ab(a.lookupValue)||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseLookupValue"})),Ln(a.operator)&&Eb(e.id,"Condition",a.field,a.valueType,r,t,{operator:a.operator,target:"clauseValue",itemId:a.id})}),i&&e.trueBranch.forEach(a=>{a.kind==="action"&&vte.has(a.type)&&t.push({nodeId:a.id,kind:"ACTION_REQUIRES_CONDITION",message:"Set field value, Show error message, and Recommendation actions require a condition. Add a condition to the IF clause, or use a different action.",target:"node",messageKey:"Validation.ActionRequiresCondition",messageParams:{actionType:a.type}})}),[...e.trueBranch,...e.falseBranch].forEach(a=>{if(a.kind==="condition")f1(a,t,r);else{if(!("field"in a)||!a.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:`${a.type}: a target field is required.`,target:"actionField",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&(a.valueType??"Value")==="Value"&&!a.value?.trim())t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please provide a value.`,target:"actionValue",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Value"&&a.value){let s=r.get(a.field);s?.maxLength&&a.value.length>s.maxLength&&t.push({nodeId:a.id,kind:"ACTION_VALUE_TOO_LONG",message:`${a.type}: value exceeds the field's maximum length of ${s.maxLength} characters.`,target:"actionValue",messageParams:{actionType:a.type,maxLength:s.maxLength}})}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Field"){if(!a.valueField)t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please select a field to copy from.`,target:"actionValue",messageKey:"Validation.SelectActionSourceField",messageParams:{actionType:a.type}});else if(r.size>0){let s=r.get(a.field),l=r.get(a.valueField);s&&l&&!Xf(s.attributeType,l.attributeType)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: the source field's type is not compatible with the target field.`,target:"actionValue",messageKey:"Validation.IncompatibleActionSourceField",messageParams:{actionType:a.type}})}}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Expression"){let s=a.rawExpression?null:ga(a.expression);!a.rawExpression&&!Js(a.expression)&&t.push(s==="invalidDayCount"?Sb(a.id,"actionValue"):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the formula.`,target:"actionValue",messageKey:"Validation.CompleteActionFormula",messageParams:{actionType:a.type}})}else(a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Lookup"&&!Ab(a.lookupValue)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the lookup record.`,target:"actionValue",messageKey:"Validation.EmptyActionLookupValue",messageParams:{actionType:a.type}});if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.field&&(Eb(a.id,a.type,a.field,a.valueType,r,t,{target:"actionValue"}),Zk(a.id,a.type,a.type,a.field,a.valueType,r,t,{target:"actionValue"})),a.type==="ShowErrorMessage"&&!a.errorMessage?.trim()&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_MESSAGE",message:"Show error message: please enter an error message.",target:"actionMessage"}),a.type==="Recommendation"){let s=a.applyActions??[];a.recommendationTitle?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_TITLE",message:"Recommendation: please enter a recommendation title.",target:"recommendationTitle"}),a.messageText?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_MESSAGE",message:"Recommendation: please enter a recommendation message.",target:"recommendationMessage"}),s.length===0&&t.push({nodeId:a.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply.",target:"node"}),s.forEach(l=>{if(!l.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply.",target:"applyActionField",itemId:l.id,messageKey:"Validation.RecommendationApplyField"});else if(l.valueType==="Field")l.valueField||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplySourceField"});else if(l.valueType==="Expression"){let u=l.rawExpression?null:ga(l.expression);!l.rawExpression&&!Js(l.expression)&&t.push(u==="invalidDayCount"?Sb(a.id,"applyActionValue",l.id):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyFormula"})}else l.valueType==="Lookup"?Ab(l.lookupValue)||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyLookupValue"}):l.valueType==="Clear"||l.value?.trim()||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyValue"});l.field&&(Eb(a.id,"Recommendation",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}),Zk(a.id,"Recommendation","SetFieldValue",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}))})}}})}var hte,t1,vte,Cte,Ob=k(()=>{"use strict";ib();Zy();Zf();Hu();Xk();lb();ob();hte=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);t1=new Set(["Lookup","Customer","Owner"]);vte=new Set(["SetFieldValue","ShowErrorMessage","Recommendation"]);Cte=10});var p1={};Hr(p1,{DAY_COUNT_MAX:()=>Ks,DAY_COUNT_MIN:()=>fb,DEFAULT_DESERIALIZE_LABELS:()=>wb,WorkflowJsonMapper:()=>Qs,addElseIfInTree:()=>n1,appendToBranch:()=>r1,areFieldKindsCompatible:()=>Xf,attributeTypeToWorkflowType:()=>gk,buildWorkflowEntity:()=>jL,collectUsedFields:()=>l1,createEmptyAction:()=>s1,createEmptyCondition:()=>Ib,deserializeWorkflowJson:()=>Yk,findNode:()=>_b,findParent:()=>Zs,getDefaultOperatorForFieldType:()=>dk,getExpressionModelIssue:()=>ga,getOperatorsForFieldType:()=>Qf,hasAnyTriggerGeneratingAction:()=>sp,isDayCountValid:()=>pb,isExpressionModelComplete:()=>Js,isOperatorCompatible:()=>fk,isTriggerGeneratingAction:()=>Nb,moveBranchItemInTree:()=>a1,operatorNeedsValue:()=>Ln,processTriggerFormIdFromScope:()=>tb,processTriggerScopeFromScope:()=>eb,removeElseIfInTree:()=>o1,removeNodeFromTree:()=>Tb,serializeToWorkflowJson:()=>Jk,supportsClearForActionType:()=>zf,updateActionInTree:()=>ap,updateConditionInTree:()=>_o,validateBusinessRule:()=>c1});var m1=k(()=>{"use strict";Zy();HL();Cb();Cb();Ob();Ob();Zf();Hu();Hu();});var Pb=v(lp=>{"use strict";Object.defineProperty(lp,"__esModule",{value:!0});lp.cloneJson=void 0;function Nte(e){return JSON.parse(JSON.stringify(e))}lp.cloneJson=Nte});var _1=v(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});To.BUSINESS_RULE_NULL_GUID=To.businessRuleRegistration=To.BusinessRuleAdapter=void 0;var h1=dt(),Ju=(m1(),Fr(p1)),g1=Jr(),y1=Q(),_te=Pb(),ii=en(),Tte=Im(),Dte=dt(),Ite=Ho(),Ote=new Set(["ShowErrorMessage","Recommendation"]);function C1(e){var t,r;return e?[...(t=e.trueBranch)!==null&&t!==void 0?t:[],...(r=e.falseBranch)!==null&&r!==void 0?r:[]].some(n=>Array.isArray(n.trueBranch)||Array.isArray(n.falseBranch)?C1(n):Ote.has(String(n.type))):!1}function Pte(e){return E1((0,_te.cloneJson)(e))}function E1(e){var t,r;let n=i=>(i??[]).map(o=>Rte(o)?E1(o):o);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 Rte(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 Lte(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new y1.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 y1.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 kte="00000000-0000-0000-0000-000000000000";To.BUSINESS_RULE_NULL_GUID=kte;var $te=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),xte=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],Fte=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],Mte=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function kn(e,t){return e===void 0?t:{...e,...t}}var va=["kind","id","type","displayName","field","stepName","stepLabels"],b1=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],Ute={Recommendation:[...va,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...va,"lock"],ShowErrorMessage:[...va,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...va,...b1],SetDefaultValue:[...va,...b1],SetBusinessRequired:[...va,"required"],SetVisibility:[...va,"visible"]};function ne(e,t){return t===void 0?{}:{[e]:t}}function A1(e){var t;return e==null?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function Rb(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",A1(e.lookupValue)),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function S1(e,t){let r=new Set(t),n={};for(let[i,o]of Object.entries(e))r.has(i)||o!==void 0&&(n[i]=o);return Object.keys(n).length>0?n:void 0}var Bte=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function qte(e){return kn(e.bag,{id:e.id,field:e.field,...Rb(e),...ne("stepName",e.stepName),...ne("displayName",e.displayName)})}function Vte(e){let t=S1(e,Bte);return{id:e.id,field:e.field,valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",e.lookupValue),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression),...ne("stepName",e.stepName),...ne("displayName",e.displayName),...ne("bag",t)}}function v1(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",e.lookupValue),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function w1(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var Gte=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),Wte=new Set,zte="INVALID_CLEAR_FOR_FIELD";function jte(e){let t=n=>{var i;return(0,ii.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,ii.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 o of["clauses","trueBranch","falseBranch"])Array.isArray(i[o])&&(i[o]=i[o].map(r));return i};return r(e)}var up=class{toArtifact(t){let r=this.residualBag(t,xte),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 kn(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},o=(0,Ju.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return C1(t.rootCondition)}toApiPayload(t,r,n){var i,o;let a=this.fromArtifact(t);a.wfomRoot&&(a.wfomRoot={...a.wfomRoot,name:t.name,title:t.name,primaryEntityName:t.entityLogicalName||a.wfomRoot.primaryEntityName},a.entityLogicalName=a.wfomRoot.primaryEntityName);let s=(0,Ju.serializeToWorkflowJson)(a,(i=n?.baseLanguageCode)!==null&&i!==void 0?i:Ite.DEFAULT_LCID),l=(o=a.ruleId)!==null&&o!==void 0?o:(0,h1.newId)();return{Entity:this.buildWorkflowEntity(a,l),WfomJson:s,status:t.status}}createDefault(t){var r,n,i,o,a,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:(o=t.entityLogicalName)!==null&&o!==void 0?o:"",scope:(a=t.scope)!==null&&a!==void 0?a:"Entity",status:(s=t.status)!==null&&s!==void 0?s:"Draft",rootCondition:t.rootCondition===void 0?(0,Ju.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(Pte(Lte(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,h1.newId)()),u}assignMissingIds(t){return(0,Dte.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,ii.isJsonObject)(n)?(N1(n,"/rootCondition",r),r):(r.push((0,ii.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(a){return[(0,ii.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=n.rootCondition===null?null:jte(n.rootCondition),o;return r.length===0?o=Gte:r.some(a=>a.requiredLevel!==void 0)?o=Wte:o=new Set([zte]),(0,Ju.validateBusinessRule)(i,r).filter(a=>!o.has(a.kind)).map(a=>(0,ii.issue)(`/rootCondition (${a.nodeId})`,`business-rule-${a.kind}`,a.message))}issuesBlockingPush(t,r=[],n){return this.semanticIssues(t,r)}columnsCheckedAtPush(t){let r;try{r=this.fromArtifact(t)}catch{return[]}let n=new Set,i=a=>{a&&n.add(a)},o=a=>{var s;for(let l of a.clauses)i(l.field),i(l.valueField);for(let l of[...a.trueBranch,...a.falseBranch]){if(l.kind==="condition"){o(l);continue}if(i(l.field),l.type==="SetFieldValue"||l.type==="SetDefaultValue")i(l.valueField);else if(l.type==="Recommendation")for(let u of(s=l.applyActions)!==null&&s!==void 0?s:[])i(u.field),i(u.valueField)}};return r.rootCondition&&o(r.rootCondition),[...n]}residualBag(t,r){return S1(t,r)}buildWorkflowEntity(t,r){return(0,Ju.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,Fte),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,Mte),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,Ute[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...ne("stepName",t.stepName),...ne("stepLabels",t.stepLabels),...ne("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(Vte),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",...v1(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...v1(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return w1(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return kn(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 kn(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,...ne("value",t.value),...ne("valueField",t.valueField),...ne("lookupValue",A1(t.lookupValue)),...ne("expression",t.expression),...ne("rawExpression",t.rawExpression),...ne("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!$te.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);Kte(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...ne("stepName",t.stepName),...ne("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return kn(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(qte),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return kn(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return kn(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return kn(t.bag,{...r,type:"SetFieldValue",...Rb(t)});case"SetDefaultValue":return kn(t.bag,{...r,type:"SetDefaultValue",...Rb(t)});case"SetBusinessRequired":return kn(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return kn(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return w1(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};To.BusinessRuleAdapter=up;function N1(e,t,r){(0,ii.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,ii.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,ii.childObjects)(e,n,t,"branchItem",r).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?N1(o,`${t}/${n}/${a}`,r):Hte(o,`${t}/${n}/${a}`,r)})}function Hte(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,ii.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function Kte(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function Jte(){return{adapter:new up,api:Tte.businessRuleApi,publish:(e,t,r)=>(0,g1.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,g1.boundEntityPublishScope)(t)}}To.businessRuleRegistration=Jte});var W1=v(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.appRegistration=Do.AppAdapter=Do.HEADER_NAV_BOOLEAN_RULE=void 0;var Bi=en(),It=so(),Qu=uo(),Yte=Jr(),x1=Ud(),Lb=Od(),kb=lo(),Qte=dt(),Xte=se(),F1=Ho(),M1=Q(),U1=Rd();Object.defineProperty(Do,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return U1.HEADER_NAV_BOOLEAN_RULE}});var pp="7.0.0.0",T1=`<SiteMap IntroducedVersion="${pp}"></SiteMap>`,D1="/_imgs/imagestrips/transparent_spacer.gif",I1="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",B1=["Entity","Url","DefaultDashboard","Page","GenPageId"],Yu="sitemapId",O1="sitemapName",Zte="sitemapNameUnique",P1="aiDescription",R1="[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}",ere=new RegExp(`^(?:\\{${R1}\\}|${R1})$`);function L1(e,t){if(!ere.test(e.trim()))throw new M1.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function k1(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new M1.ValidationError("app",t,[q1(e)]);return e}function q1(e){return(0,Bi.issue)("/headerAndNavigationRefresh",U1.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function tre(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,Xte.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}}function rre(e){var t,r,n,i;let o=[];for(let a of(r=(t=e.siteMap)===null||t===void 0?void 0:t.areas)!==null&&r!==void 0?r:[])for(let s of(n=a.groups)!==null&&n!==void 0?n:[])for(let l of(i=s.subAreas)!==null&&i!==void 0?i:[])l.type==="Entity"&&l.entity&&o.push(l.entity);return o}var mp=class{constructor(t=F1.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=cp(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,It.emptyBag)()}}fromArtifact(t){(0,kb.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,It.rebuildRaw)(i,(0,Qu.domEngine)(n),null)}fromApiResponse(t){var r,n,i,o,a,s,l,u,c,d,f;(0,kb.installDomShim)();let m=t??{},p=(r=m.$sitemap)!==null&&r!==void 0?r:m,h=(0,Qu.parseXmlRoot)((n=p.sitemapxml)!==null&&n!==void 0?n:T1,T1),g=this.toArtifact(h);return g.id=(i=m.appmoduleid)!==null&&i!==void 0?i:"",g.name=(o=m.name)!==null&&o!==void 0?o:"",g.uniqueName=(a=m.uniquename)!==null&&a!==void 0?a:"",g.description=(s=m.description)!==null&&s!==void 0?s:"",m.aiappdescription&&(g.aiDescription=m.aiappdescription),g.bag={a:[[Yu,(u=(l=p.sitemapid)!==null&&l!==void 0?l:m._sitemapid_value)!==null&&u!==void 0?u:""],[O1,(c=p.sitemapname)!==null&&c!==void 0?c:""],[Zte,(d=p.sitemapnameunique)!==null&&d!==void 0?d:""],[P1,(f=m.aiappdescription)!==null&&f!==void 0?f:""]],c:[]},g}toApiPayload(t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b;(0,kb.installDomShim)();let w=(0,Qu.serializeNode)(this.fromArtifact(t)),E=[],S=[];for(let L of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let I of(o=L.groups)!==null&&o!==void 0?o:[])for(let D of(a=I.subAreas)!==null&&a!==void 0?a:[])D.type==="Entity"&&D.entity?E.push(D.entity):D.type==="DashBoard"&&D.dashboardId&&S.push(D.dashboardId);let P=(s=t.bag)!==null&&s!==void 0?s:(0,It.emptyBag)();return{sitemapId:xb(P,Yu)||(t.sitemapId?L1(t.sitemapId,t.id):""),sitemapxml:w,sitemapname:xb(P,O1)||t.name,appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:xb(P,P1))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[Lb.HEADER_AND_NAVIGATION_REFRESH]:k1(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?Lb.APP_SETTING_ON:Lb.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:E,components:{forms:(c=(u=t.components)===null||u===void 0?void 0:u.forms)!==null&&c!==void 0?c:[],views:(f=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&f!==void 0?f:[],charts:(p=(m=t.components)===null||m===void 0?void 0:m.charts)!==null&&p!==void 0?p:[],dashboards:[...(g=(h=t.components)===null||h===void 0?void 0:h.dashboards)!==null&&g!==void 0?g:[],...S],...((b=t.components)===null||b===void 0?void 0:b.mainFormsByTable)!==void 0?{mainFormsByTable:t.components.mainFormsByTable}:{}}}}createDefault(t){var r,n,i,o,a,s;let l=!((r=t.siteMap)===null||r===void 0)&&r.areas&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}],u=(n=t.id)!==null&&n!==void 0?n:(0,Qte.newId)();return{id:u,name:(i=t.name)!==null&&i!==void 0?i:"New App",uniqueName:(o=t.uniqueName)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",...t.aiDescription?{aiDescription:t.aiDescription}:{},siteMap:{areas:l},...t.sitemapId?{sitemapId:L1(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:k1(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(Mb):Array.isArray(r.areas)?r.areas.forEach(Mb):Array.isArray(r.groups)?Mb(r):Array.isArray(r.subAreas)?G1(r):"type"in r&&hp(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,Bi.issue)("/published","published-must-be-boolean",`published must be a boolean, got ${typeof n}`));let i=t.siteMap,o=t.headerAndNavigationRefresh;if(o!==void 0&&typeof o!="boolean"&&r.push(q1(o)),i==null)return r;if(!(0,Bi.isJsonObject)(i))return r.push((0,Bi.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let a=(0,Bi.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return a.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,Bi.childObjects)(l,"groups",c,"group",r).forEach(({node:f,index:m})=>{let p=`${c}/groups/${m}`;(0,Bi.childObjects)(f,"subAreas",p,"subArea",r).forEach(({node:g,index:b})=>{let w=`${p}/subAreas/${b}`;(0,Bi.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],w,"subarea-type-invalid",r);let E=tre(g);if(!E)return;let S=s.get(E);if(S===void 0){s.set(E,w);return}r.push((0,Bi.issue)(w,"subarea-duplicate-target",`the sitemap already navigates to this target at ${S}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}issuesBlockingPush(t){var r;return(0,x1.mainFormSetShapeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsByTable,rre(t))}applyServerIdentity(t,r){let n=r[Yu];if(!n)return;t.bag||(t.bag=(0,It.emptyBag)());let i=t.bag.a.find(o=>o[0]===Yu);i?i[1]=n:t.bag.a.push([Yu,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=cp(t,"Group"),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:$b(t,this.lcid),groups:i.map(l=>this.groupToJson(l)),bag:n},a=t.getAttribute("Icon");a&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}groupToJson(t){var r;let{bag:n,modeledEls:i}=cp(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:$b(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:n}}subAreaToJson(t){var r;let{bag:n}=cp(t,null),i=nre(t),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:$b(t,this.lcid),bag:n};if(i==="Entity"){let l=t.getAttribute("Entity");l&&(o.entity=l)}else if(i==="DashBoard"){let l=t.getAttribute("DefaultDashboard");l&&(o.dashboardId=l);let u=t.getAttribute("Url");u&&(o.dashboardUrl=u)}else if(i==="CustomPage"){let l=t.getAttribute("Page");l&&(o.page=l)}else if(i==="GenPage"){let l=t.getAttribute("GenPageId");l&&(o.genPageId=l)}else{let l=t.getAttribute("Url");l&&(o.url=l)}let a=t.getAttribute("Icon");a&&a!==D1&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}rootToRaw(t){var r,n,i,o;let a=(n=(r=t.siteMap)===null||r===void 0?void 0:r.bag)!==null&&n!==void 0?n:(0,It.emptyBag)(),l=dp(a)?[["IntroducedVersion",pp]]:[],u=((o=(i=t.siteMap)===null||i===void 0?void 0:i.areas)!==null&&o!==void 0?o:[]).map(c=>this.areaToRaw(c));return{n:"SiteMap",a:(0,It.mergeAttrs)(a.a,l),c:(0,It.spliceChildren)(a.c,u)}}areaToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,It.emptyBag)(),o=dp(i),a=[],s=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",pp]),t.icon!==void 0?a.push(["Icon",t.icon]):fp(i.a,"Icon")&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):fp(i.a,"VectorIcon")&&s.push("VectorIcon");let l=((n=t.groups)!==null&&n!==void 0?n:[]).map(c=>this.groupToRaw(c)),u=Fb((0,It.spliceChildren)(i.c,l),t.title,o,this.lcid);return{n:"Area",a:(0,It.mergeAttrs)(i.a,a,s),c:u}}groupToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,It.emptyBag)(),o=dp(i),a=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",pp],["IsProfile","false"]);let s=((n=t.subAreas)!==null&&n!==void 0?n:[]).map(u=>this.subAreaToRaw(u)),l=Fb((0,It.spliceChildren)(i.c,s),t.title,o,this.lcid);return{n:"Group",a:(0,It.mergeAttrs)(i.a,a),c:l}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,It.emptyBag)(),i=dp(n),o=ore(n.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]);let l=!i&&!n.a.some(([c])=>B1.includes(c));sre(a,t,l),i?(a.push(["ResourceId","SitemapDesigner.NewSubArea"],["Client","All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web"],["Sku","All,OnPremise,Live,SPLA"],["AvailableOffline","true"],["PassParams","false"]),t.icon&&a.push(["Icon",t.icon])):t.icon!==void 0?a.push(["Icon",t.icon]):fp(o,"Icon",D1)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):fp(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",I1]):s.push("VectorIcon"):t.type==="GenPage"&&!ire(o,"VectorIcon")&&a.push(["VectorIcon",I1]);let u=Fb((0,It.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,It.mergeAttrs)(o,a,s),c:u}}};Do.AppAdapter=mp;function cp(e,t){let r=(0,Qu.nodeLikeFromDom)(e).getAllProperties().map(s=>[s.key,s.value]),n=[],i=[],o=e.childNodes,a=0;for(let s=0;s<o.length;s+=1){let l=o[s];l.nodeType!==1&&l.nodeType!==3||(l.nodeType===1&&t!==null&&l.tagName===t?i.push(l):n.push({i:a,node:(0,It.rawFromNode)((0,Qu.nodeLikeFromDom)(l))}),a+=1)}return{bag:{a:r,c:n},modeledEls:i}}function $1(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}function $b(e,t){var r;let n=$1(e,"Titles")[0];if(!n)return"";let o=$1(n,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(r=o.getAttribute("Title"))!==null&&r!==void 0?r:""}function nre(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function dp(e){return e.a.length===0&&e.c.length===0}function ire(e,t){return e.some(([r])=>r===t)}function fp(e,t,r){let n=e.find(([o])=>o===t),i=n?.[1];return!!i&&i!==r}function xb(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function ore(e,t){let r=are(t);return e.filter(([n])=>!B1.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function are(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 sre(e,t,r){var n,i,o,a,s;switch(t.type){case"Entity":e.push(["Entity",(n=t.entity)!==null&&n!==void 0?n:""]);break;case"URL":(t.url!==void 0||!r)&&e.push(["Url",(i=t.url)!==null&&i!==void 0?i:""]);break;case"DashBoard":e.push(["DefaultDashboard",(o=t.dashboardId)!==null&&o!==void 0?o:""]),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",(s=t.genPageId)!==null&&s!==void 0?s:""]);break;default:break}}function Fb(e,t,r,n){if(!t)return e;let i=e.findIndex(o=>o.n==="Titles");if(i>=0){let o=e.slice();return o[i]=lre(e[i],t,n),o}return r?[ure(t,n),...e]:e}function lre(e,t,r){let n=!1,i=e.c.map(o=>!n&&o.n==="Title"&&cre(o,"LCID")===String(r)?(n=!0,{n:o.n,a:(0,It.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return n||i.unshift(V1(t,r)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function ure(e,t){return{n:"Titles",a:[],c:[V1(e,t)]}}function V1(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function cre(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function dre(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function hp(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${dre(8)}`)}function Mb(e){var t;hp(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])G1(r)}function G1(e){var t;hp(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])hp(r,"subarea")}function fre(e=F1.DEFAULT_LCID){return{adapter:new mp(e),api:x1.appApi,languageSensitive:!0,publish:(t,r)=>(0,Yte.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]}),rebaselineAfterPublish:"bracket"}}Do.appRegistration=fre});var z1={};Hr(z1,{ActionType:()=>Bb,AppActionOrigin:()=>Kb,AppActionVisibilityType:()=>Hb,ButtonType:()=>Vb,CannotUpdateAppActionColumns:()=>pre,Context:()=>Wb,IconType:()=>qb,Location:()=>Gb,OnClickEventType:()=>jb,Scope:()=>zb,VisibilityType:()=>Ub});var Ub,Bb,qb,Vb,Gb,Wb,zb,jb,Hb,Kb,pre,j1=k(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(Ub||(Ub={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(Bb||(Bb={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(qb||(qb={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(Vb||(Vb={}));(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"})(Gb||(Gb={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(Wb||(Wb={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(zb||(zb={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(jb||(jb={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(Hb||(Hb={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(Kb||(Kb={}));pre=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var Z1=v(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.assertOneWritePerRow=Ot.commandApi=Ot.COMMAND_DUPLICATE_ROW_CODE=Ot.COMMAND_ROW_NOT_IN_BAR_CODE=Ot.COMMAND_TABLE_MISMATCH_CODE=void 0;var Jb=Lt(),Pr=ye(),qi=Q(),Rr=se();Ot.COMMAND_TABLE_MISMATCH_CODE="COMMAND_TABLE_MISMATCH";Ot.COMMAND_ROW_NOT_IN_BAR_CODE="COMMAND_ROW_NOT_IN_BAR";Ot.COMMAND_DUPLICATE_ROW_CODE="COMMAND_DUPLICATE_ROW";var mre="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function Yb(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Rr.odataPathLiteral)(t)}')${(0,Rr.odataQuery)([["$select","MetadataId"]])}`,i=(0,Pr.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,o=i?.MetadataId;return o?(0,Rr.normalizeGuid)(o,"entityMetadataId"):""}function Qb(e,t){return t?`_contextentity_value eq ${t}`:`contextvalue eq '${(0,Rr.odataLiteral)(e)}'`}function Xu(e){return`Nothing was written. Re-fetch the command with fetchArtifact('command', '${e}', { overwrite: true }) \u2014 this discards local edits \u2014 and re-apply the change.`}function H1(e,t){let r=e.entityLogicalName;if(t===void 0)return r;if(typeof r!="string"||r.toLowerCase()!==t.toLowerCase())throw new qi.SdkError(Ot.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': its JSON names table '${String(r)}'. A command's id is its table, so the push would write another table's command bar. Nothing was written. Fix its entityLogicalName, or push it under that table's id.`);return t}async function K1(e,t,r){let n=await Yb(e,t);if(r){let i=(0,Rr.normalizeGuid)(r,"entityMetadataId");if(i!==n)throw new qi.SdkError(Ot.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': it was fetched for table id ${i}, but table '${t}' is ${n||"not resolvable"} on the server \u2014 the table was re-created, or the local copy edited. `+Xu(t))}return n}Ot.commandApi={async get(e,t){let r=t,n=await Yb(e,r),i=Qb(r,n),o=`/appactions${(0,Rr.odataQuery)([["$expand",mre],["$filter",i]])}`,a,s=await(0,Jb.collectPages)(e,o,"fetchArtifact('command')",c=>{a=c}),l={entityLogicalName:r,entityMetadataId:n,appActions:s},u={};for(let c of s){let d=typeof c.appactionid=="string"?c.appactionid:void 0;if(d){let f=c["@odata.etag"];u[(0,Rr.normalizeGuid)(d,"appactionid")]=typeof f=="string"?f:null}}return{raw:l,etag:a?(0,Pr.readEtag)(a):null,memberEtags:u}},async list(e,t){let r=t?.entityLogicalName;return r?[{type:"command",id:r,name:`${r} commands`,entityLogicalName:r,isDirty:!1}]:[]},async create(e,t,r){let n=t,i=H1(n,r),o=await K1(e,i,n.entityMetadataId);return J1(e,i,{...n,entityMetadataId:o},!1)},async update(e,t,r,n,i){let o=r,a=H1(o,t),s=await K1(e,a,o.entityMetadataId);return J1(e,a,{...o,entityMetadataId:s},!0,i)},async delete(e,t){let r=await Yb(e,t),n=`/appactions${(0,Rr.odataQuery)([["$select","appactionid"],["$filter",Qb(t,r)]])}`,i=await(0,Jb.collectPages)(e,n,"deleteArtifact('command')");for(let o of i)o.appactionid&&await(0,Pr.deleteRecord)(e,"appactions",o.appactionid)}};async function J1(e,t,r,n,i){let o=r.entityMetadataId?(0,Rr.normalizeGuid)(r.entityMetadataId,"entityMetadataId"):"",a=await gre(e,t,r,o,n,i),s={};try{await bre(e,a,o,s)}catch(l){throw(0,qi.withPartialTokens)(l,{memberEtags:s})}return{id:r.entityLogicalName,etag:null,memberEtags:s}}function Xb(e){return e.replace(/[{}]/g,"").toLowerCase()}function X1(e,t){var r;let n=new Map,i=[...t.rows.map(o=>[o.appactionid,"written"]),...((r=t.deletedRowIds)!==null&&r!==void 0?r:[]).map(o=>[o,"deleted"])];for(let[o,a]of i){let s=Xb(o),l=n.get(s);if(l===void 0){n.set(s,a);continue}throw new qi.SdkError(Ot.COMMAND_DUPLICATE_ROW_CODE,l===a?`Refusing to push command '${e}': app action '${s}' appears twice in it \u2014 two of its controls or groups carry that id, as one copied together with its id or bag does \u2014 so one would silently replace or remove the other. Nothing was written. Remove the id and the bag from the copy, so it is created as a new one, and push again.`:`Refusing to push command '${e}': app action '${s}' would be both written and deleted \u2014 one of its controls or groups spells that id differently (case or braces) than the copy last fetched or pushed \u2014 so the delete would remove what the write saved. Nothing was written. Spell the id as it was, and push again.`)}}Ot.assertOneWritePerRow=X1;var hre={entities:/^\/entities\(([^()]+)\)$/,appactions:/^\/appactions\(([^()]+)\)$/};function Y1(e,t){let r=hre[t].exec(e);return r?Xb(r[1]):void 0}async function gre(e,t,r,n,i,o){var a,s;X1(t,r);let l=vre(r.rows),u=new Set(l.map(f=>Xb(f.appactionid))),c={writes:[],deletes:[]};for(let f of l){let m=f.body["[email protected]"];if(m!==void 0&&!(typeof m=="string"&&n!==""&&Y1(m,"entities")===n))throw new qi.SdkError(Ot.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' binds to ${typeof m=="string"?`'${m}'`:String(m)}, not to table '${t}' (${n?`/entities(${n})`:"whose id is not resolvable"}). `+Xu(t));let p=f.body["[email protected]"];if(typeof p=="string"){let h=Y1(p,"appactions");if(h===void 0||!u.has(h))throw new qi.SdkError(Ot.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' would be placed under '${p}', which is not a row of this command. `+Xu(t))}if(i&&f.exists){let h=(0,Rr.normalizeGuid)(f.appactionid,"id"),g=(a=o?.[h])!==null&&a!==void 0?a:f.etag;if(!(0,Pr.isVersionToken)(g))throw Q1(t,h,"update",g);c.writes.push({kind:"patch",row:f,id:h,token:g})}else{if(m===void 0&&!n)throw new qi.SdkError("COMMAND_CONTEXT_ENTITY_UNRESOLVED",`Cannot create app action '${f.appactionid}' for entity '${r.entityLogicalName}': the entity MetadataId could not be resolved, so the required ContextEntity bind cannot be set. A row written without it is created but is permanently unreadable \u2014 commandApi.get filters on _contextentity_value. Verify the entity logical name exists and is readable, then retry.`);c.writes.push({kind:"post",row:f})}}for(let f of(s=r.deletedRowIds)!==null&&s!==void 0?s:[]){let m=(0,Rr.normalizeGuid)(f,"id"),p=o?.[m];if(!(0,Pr.isVersionToken)(p))throw Q1(t,m,"delete",p);c.deletes.push({id:m,token:p})}let d=[...c.writes.flatMap(f=>f.kind==="patch"?[{id:f.id,verb:"update"}]:[]),...c.deletes.map(f=>({id:f.id,verb:"delete"}))];if(d.length>0){let f=await yre(e,t,n),m=d.find(p=>!f.has(p.id));if(m)throw new qi.SdkError(Ot.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': it would ${m.verb} app action '${m.id}', which is not in table '${t}''s command bar on the server \u2014 a row of another table, or one deleted since the fetch. `+Xu(t))}return c}function Q1(e,t,r,n){return new qi.SdkError(Pr.UPDATE_NO_ETAG_CODE,`Refusing to push command '${e}': ${typeof n=="string"&&n!==""?`the token held for app action '${t}' ('${n}') is not a version`:`no token is held for app action '${t}'`}, so its ${r} could not be made conditional and would overwrite or remove a concurrent edit. `+Xu(e))}async function yre(e,t,r){let n=`/appactions${(0,Rr.odataQuery)([["$select","appactionid"],["$filter",Qb(t,r)]])}`,i=await(0,Jb.collectPages)(e,n,"pushArtifact('command') bar membership"),o=new Set;for(let a of i)typeof a.appactionid=="string"&&o.add((0,Rr.normalizeGuid)(a.appactionid,"appactionid"));return o}async function bre(e,t,r,n){for(let i of t.writes)if(i.kind==="patch"){let o=(0,Pr.echoWrite)("appactionid",{"If-Match":i.token}),a=`/appactions(${i.id})${o.query}`,s=(0,Pr.ensureSuccess)(await e.patch(a,i.row.body,o.options),e.apiUrl(a));n[i.id]=(0,Pr.readEtag)(s)}else{let o=(0,Pr.echoWrite)("appactionid"),a=`/appactions${o.query}`,s={...i.row.body};s["[email protected]"]===void 0&&(s["[email protected]"]=`/entities(${r})`);let l=(0,Pr.ensureSuccess)(await e.post(a,s,o.options),e.apiUrl(a)),u=(0,Pr.readCreatedId)(l,"appactionid");u&&(n[(0,Rr.normalizeGuid)(u,"appactionid")]=(0,Pr.readEtag)(l))}for(let{id:i,token:o}of[...t.deletes].reverse())await(0,Pr.deleteRecord)(e,"appactions",i,o),delete n[i]}function vre(e){let t=new Map(e.map(o=>[o.appactionid,o])),r=new Set,n=[],i=o=>{if(r.has(o.appactionid))return;let a=o.body["[email protected]"];if(typeof a=="string"){let s=/\(([^)]+)\)/.exec(a),l=s?t.get(s[1]):void 0;l&&i(l)}r.add(o.appactionid),n.push(o)};return e.forEach(i),n}});var h$=v(el=>{"use strict";Object.defineProperty(el,"__esModule",{value:!0});el.commandRegistration=el.CommandAdapter=void 0;var lt=(j1(),Fr(z1)),e$=Jr(),bt=en(),n$=Z1(),i$=dt(),tl=se(),o$=Q(),tv="$ClientSvg:",rv=".svg",wre=2,Cre=1,Ere=1,a$="entityMetadataId",Are=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"]),gp=class{toArtifact(t){var r,n,i,o,a,s,l;let u=(r=t.appActions)!==null&&r!==void 0?r:[],c=(n=t.entityLogicalName)!==null&&n!==void 0?n:"",d=u.find(h=>typeof h.appactionid!="string"||h.appactionid==="");if(d)throw new o$.InvalidArgumentError(`Cannot read the command bar of '${c}': app action row '${String((i=d.name)!==null&&i!==void 0?i:"")}' has no appactionid (its primary key), so it cannot be placed in the bar or written back.`);let f=new Map;for(let h of u){let g=typeof h._parentappactionid_value=="string"&&h._parentappactionid_value?h._parentappactionid_value:"",b=(o=f.get(g))!==null&&o!==void 0?o:[];b.push(h),f.set(g,b)}let m=new Map;for(let h of(a=f.get(""))!==null&&a!==void 0?a:[]){let g=Dre(h.location),b=(s=m.get(g))!==null&&s!==void 0?s:[];b.push(h),m.set(g,b)}let p=[];for(let[h,g]of m)p.push({location:h,groups:Nre(g,f,c$(h),c)});return{id:c,entityLogicalName:c,commandBars:Tre(p),bag:{a:[[a$,(l=t.entityMetadataId)!==null&&l!==void 0?l:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:iv(t),appActions:Zb(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?Zb(r).map(l=>l.appactionid):[]),i=Zb(t,new Set([...n].map(l=>l.toLowerCase()))),o=new Set(i.map(l=>l.appactionid)),a=i.map(l=>{let u=l.exists||n.has(l.appactionid);return{appactionid:l.appactionid,exists:u,etag:l.etag,body:u?qre(l.row):m$(l.row)}}),s=[...n].filter(l=>!o.has(l));return(0,n$.assertOneWritePerRow)(t.entityLogicalName,{rows:a,deletedRowIds:s}),{entityLogicalName:t.entityLogicalName,entityMetadataId:iv(t),rows:a,...s.length>0?{deletedRowIds:s}:{}}}createDefault(t){var r,n,i,o;let a=(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:a,entityLogicalName:a,commandBars:(o=t.commandBars)!==null&&o!==void 0?o:[]}}assignMissingIds(t){return(0,i$.assignMissingIds)(t)}normalize(t){let r=Rre(t),n=!1,i=(Array.isArray(t.commandBars)?t.commandBars:[]).map(o=>{let a=(0,bt.isJsonObject)(o)&&Array.isArray(o.groups)?o.groups:void 0;if(!a)return o;let s=!1,l=a.map(u=>{let c=(0,bt.isJsonObject)(u)&&Array.isArray(u.controls)?u.controls:void 0;if(!c)return u;let d=c.map(f=>f$(f,r));return d.every((f,m)=>f===c[m])?u:(s=!0,{...u,controls:d})});return s?(n=!0,{...o,groups:l}):o});return n?{...t,commandBars:i}:t}validate(t){let r=[];return(0,bt.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,bt.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",r),(0,bt.childObjects)(i,"groups",a,"group",r).forEach(({node:l,index:u})=>{let c=`${a}/groups/${u}`;vp(l.bag)||((0,bt.optionalGuidId)(l,"id",c,"group-id-invalid",r),typeof l.title=="string"&&l.title.length>0&&r.push({pointer:`${c}/title`,rule:"group-toplevel-title-unsupported",message:"a new top-level command group cannot have a title: Dataverse rejects a Group row with no parent (0x80040265). Leave the title empty to hold the commands without creating a group row, or nest them under a FlyoutAnchor control, which supplies the parent a group needs."})),s$((0,bt.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};el.CommandAdapter=gp;function vp(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function s$(e,t,r){e.forEach(({node:n,index:i})=>{let o=`${t}/${i}`;vp(n.bag)||(0,bt.optionalGuidId)(n,"id",o,"control-id-invalid",r),(0,bt.optionalEnum)(n,"type",["Button","FlyoutAnchor","SplitButton"],o,"control-type-invalid",r);let a=n.location;a!==void 0&&(typeof a!="number"||!Number.isInteger(a)||a<0||a>6)&&r.push((0,bt.issue)(`${o}/location`,"control-location-invalid",`location must be an integer 0-6 when present, got ${JSON.stringify(a)}`)),n.action!==void 0&&n.action!==null&&((0,bt.isJsonObject)(n.action)?(0,bt.optionalEnum)(n.action,"type",["javascript"],`${o}/action`,"action-type-invalid",r):r.push((0,bt.issue)(`${o}/action`,"control-action-must-be-object",`a control action must be a JSON object when present, got ${typeof n.action}`)));let s=(0,bt.childObjects)(n,"children",o,"control",r);s.length>0&&s$(s,`${o}/children`,r)})}function nv(e){return{a:Object.entries(e)}}function Sre(e){return Object.fromEntries(e.a)}function Zu(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function iv(e){let t=Zu(e.bag,a$);return typeof t=="string"?t:""}function Nre(e,t,r,n){var i,o;let a=[],s=[];for(let l of bp(e))l.type===lt.ButtonType.Group?a.push({id:u$(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:bp((o=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(u=>yp(u,t,r,n)),bag:nv(l)}):s.push(yp(l,t,r,n));return s.length>0&&a.unshift({id:Bre(n,r),title:"",controls:s}),a}function ov(e){let t=e.bag?Zu(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function yp(e,t,r,n){var i,o,a,s,l;let u=u$(e.name,n),c={id:u,type:Ire(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:nv(e)},d=l$(e);d&&(c.icon=d);let f=_re(e);f&&(c.action=f),typeof e.hidden=="boolean"&&(c.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(c.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(c.location=e.location);let m=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(m&&m.length>0){let p=[],h=[];for(let g of bp(m))if(g.type===lt.ButtonType.Group){let b=(o=g.appactionid)!==null&&o!==void 0?o:"",w=nv(g);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(a=g.appactionid)!==null&&a!==void 0?a:void 0,c.flyoutGroupBag=w);let E=[];for(let S of bp((l=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let P=yp(S,t,r,n);p.push(P),E.push(ov(P))}h.push({id:b,bag:w,childIds:E})}else p.push(yp(g,t,r,n));c.children=p,h.length>1&&(c.flyoutGroups=h)}return c}function l$(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(tv)?e.fonticon.slice(tv.length)+rv:e.fonticon}function _re(e){var t;let r=e.onclickeventjavascriptfunctionname;if(typeof r!="string"||!r)return;let n=e.OnClickEventJavaScriptWebResourceId,i=e._onclickeventjavascriptwebresourceid_value,o={type:"javascript",webResourceId:(t=typeof i=="string"?i:n?.webresourceid)!==null&&t!==void 0?t:"",functionName:r};n?.name&&(o.libraryName=n.name);let a=e.onclickeventjavascriptparameters;return typeof a=="string"&&a&&(o.parameters=a),o}function t$(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function bp(e){return[...e].sort((t,r)=>t$(t)-t$(r))}function Tre(e){let t={MainTab:0,ContextualTab:1,HomeTab:2};return[...e].sort((r,n)=>{var i,o;return((i=t[r.location])!==null&&i!==void 0?i:9)-((o=t[n.location])!==null&&o!==void 0?o:9)})}function u$(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 Dre(e){switch(e){case lt.Location.Form:case lt.Location.QuickForm:return"MainTab";case lt.Location.HomePageGrid:case lt.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function c$(e){switch(e){case"MainTab":return lt.Location.Form;case"HomeTab":return lt.Location.HomePageGrid;default:return lt.Location.SubGridStandard}}function Ire(e){switch(e){case lt.ButtonType.Dropdown:return"FlyoutAnchor";case lt.ButtonType.Split:return"SplitButton";default:return"Button"}}function Ore(e){switch(e){case"FlyoutAnchor":return lt.ButtonType.Dropdown;case"SplitButton":return lt.ButtonType.Split;default:return lt.ButtonType.Standard}}function Pre(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function d$(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 Zb(e,t=new Set){var r,n,i,o;let a=[],s=iv(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=c$(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(m=>{var p;return(p=m.controls)!==null&&p!==void 0?p:[]}),d=c.length>0&&c.every(m=>!d$(m,t)),f=0;for(let m of(i=l.groups)!==null&&i!==void 0?i:[]){let p;if(Pre(m)){let h=kre(m,u,void 0,e,s);a.push(h),p=h.appactionid}for(let h of(o=m.controls)!==null&&o!==void 0?o:[])p$(h,u,p,e,s,a,d?f:void 0,t),f+=1}}return a}function f$(e,t){if(!(0,bt.isJsonObject)(e))return e;let r=e.children,n=r,i=!1;Array.isArray(r)&&(n=r.map(s=>f$(s,t)),i=n.some((s,l)=>s!==r[l]));let o=!vp(e.bag)&&(typeof e.id!="string"||e.id.trim()==="");if(!o&&!i)return e;let a;if(o){do a=(0,i$.newId)();while(t.has(a));t.add(a)}return{...e,...a!==void 0?{id:a}:{},...i?{children:n}:{}}}function Rre(e){let t=new Set,r=(o,...a)=>{if((0,bt.isJsonObject)(o))for(let s of[...a.map(l=>o[l]),vp(o.bag)?Zu(o.bag,"appactionid"):void 0])typeof s=="string"&&s.trim()!==""&&t.add(s.toLowerCase())},n=o=>{(0,bt.isJsonObject)(o)&&(r(o,"id","flyoutGroupId"),r({bag:o.flyoutGroupBag}),(Array.isArray(o.flyoutGroups)?o.flyoutGroups:[]).forEach(a=>r(a,"id")),(Array.isArray(o.children)?o.children:[]).forEach(n))},i=e.commandBars;return(Array.isArray(i)?i:[]).forEach(o=>{let a=(0,bt.isJsonObject)(o)?o.groups:void 0;(Array.isArray(a)?a:[]).forEach(s=>{r(s,"id");let l=(0,bt.isJsonObject)(s)?s.controls:void 0;(Array.isArray(l)?l:[]).forEach(n)})}),t}function p$(e,t,r,n,i,o,a,s=new Set){var l;let u=Lre(e,t,r,n,i,a);o.push(u);let c=(l=e.children)!==null&&l!==void 0?l:[];if(c.length===0&&!(e.flyoutGroups&&e.flyoutGroups.length>0))return;let d=c.every(h=>!d$(h,s)),f=(h,g,b)=>{p$(h,t,g,n,i,o,d?b:void 0,s)},m=e.flyoutGroups;if(m&&m.length>0){let h=new Map(c.map(S=>[ov(S),S])),g=new Set,b=0,w;for(let[S,P]of m.entries()){let L=P.id||(S===0?ev(u.appactionid):sv("flyout-group",`${u.appactionid}#${S}`)),I=r$(L,t,u.appactionid,n,i,P.bag);o.push(I);let D=I.appactionid;w===void 0&&(w=D);for(let O of P.childIds){let x=h.get(O);!x||g.has(O)||(g.add(O),f(x,D,b),b+=1)}}let E=w??ev(u.appactionid);for(let S of c){let P=ov(S);g.has(P)||(g.add(P),f(S,E,b),b+=1)}return}let p=e.flyoutGroupId||ev(u.appactionid);o.push(r$(p,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,g]of c.entries())f(g,p,h)}function Lre(e,t,r,n,i,o){let a=av(e,t,r,n,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let l=l$(s);return e.location!==void 0&&(s.location=e.location),s.type=Ore(e.type),s.buttonlabeltext=e.label,xre(s,e.icon,l),Mre(s,e.action),Fre(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function kre(e,t,r,n,i){let o=av(e,t,r,n,i);return o.row.type=lt.ButtonType.Group,o.row.grouptitle=e.title,o}function r$(e,t,r,n,i,o){let a=av({id:e,bag:o},t,r,n,i),s=a.row;return s["[email protected]"]=`/appactions(${(0,tl.normalizeGuid)(r,"Command flyout group id")})`,s.type=lt.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),a}function av(e,t,r,n,i){let o,a,s,l;if(e.bag&&e.bag.a.length>0){o=Sre(e.bag),a=!0;let u=Zu(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=Zu(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else{if(typeof e.id!="string"||e.id.trim()==="")throw new o$.InvalidArgumentError(`Cannot serialize command '${n.entityLogicalName}': a new control has no id. Its primary key is minted once, before the first push, by normalize() \u2014 serialize the normalized artifact.`);l=e.id,o=$re(l,t,n,i),a=!1,s=null}return r?o["[email protected]"]=`/appactions(${(0,tl.normalizeGuid)(r,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==lt.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:l,exists:a,etag:s,row:o}}function $re(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:lt.Context.Entity,contextvalue:r.entityLogicalName,scope:lt.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,tl.normalizeGuid)(n,"Command context entity metadata id")})`),i}function xre(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,tl.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(rv)?tv+t.slice(0,t.length-rv.length):t,e.IconWebResourceId=null}function Fre(e){let t=(n,i)=>{let o=e[n];if(typeof o!="string"||o.length===0||e[`${i}@odata.bind`]!==void 0)return;let a=(0,tl.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===Cre&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===Ere)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function Mre(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=wre,t.webResourceId){let r=(0,tl.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 Ure(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 sv(e,t){let r="";for(let n=0;n<4;n+=1)r+=Ure(`${n}:${e}:${t}`).toString(16).padStart(8,"0");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function ev(e){return sv("flyout-group",e)}function Bre(e,t){return sv("loose-group",`${e}|${t}`)}function m$(e){let t={...e};for(let r of Are)delete t[r];return t}function qre(e){let t=m$(e);for(let r of lt.CannotUpdateAppActionColumns)delete t[r];return t}function Vre(){return{adapter:new gp,api:n$.commandApi,publish:(e,t,r)=>(0,e$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,e$.boundEntityPublishScope)(t)}}el.commandRegistration=Vre});var y$=v(wp=>{"use strict";Object.defineProperty(wp,"__esModule",{value:!0});wp.chartApi=void 0;var Gre=Lt(),Lr=ye(),wa=se(),g$="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",Wre="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";wp.chartApi={async get(e,t){let r=(0,wa.normalizeGuid)(t,"id"),n=await(0,Lr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,wa.odataQuery)([["$select",g$]]);return{raw:(0,Lr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,wa.normalizeGuid)(t,"id"),n=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,wa.odataQuery)([["$select",g$]]),i=(0,Lr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,Lr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueryvisualizations${(0,wa.odataQuery)([["$select",Wre],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,wa.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,Gre.collectPages)(e,r,"listArtifacts('chart')")).map(i=>{var o,a;return{type:"chart",id:(o=i.savedqueryvisualizationid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.primaryentitytypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Lr.echoWrite)("savedqueryvisualizationid"),o=`/savedqueryvisualizations${i.query}`,a=(0,Lr.ensureSuccess)(await e.post(o,(0,Lr.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(o));return{id:(0,Lr.resolveCreatedId)(a,"savedqueryvisualizationid","chart",r),etag:(0,Lr.readEtag)(a)}},async update(e,t,r,n){let i=r,o=(0,wa.normalizeGuid)(t,"id"),a=(0,Lr.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,Lr.requireEtag)(n,"chart",o)}),s=`/savedqueryvisualizations(${o})${a.query}`,l=(0,Lr.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,datadescription:i.datadescription,presentationdescription:i.presentationdescription},a.options),e.apiUrl(s));return{id:o,etag:(0,Lr.readEtag)(l)}},delete(e,t){return(0,Lr.deleteRecord)(e,"savedqueryvisualizations",t)}}});var k$=v(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});nl.chartRegistration=nl.ChartAdapter=void 0;var lv=so(),b$=en(),oi=uo(),v$=Jr(),zre=y$(),uv=lo(),jre=dt(),Hre=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],Kre=new Map(Hre.map(e=>[e.toLowerCase(),e]));function S$(e){var t;return e&&(t=Kre.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function Jre(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function Yre(e){var t,r;let n=e.entityLogicalName,i=e.series.map((h,g)=>({alias:`agg_${g}`,series:h})),o=e.categories.map((h,g)=>({alias:`grp_${g}`,category:h})),a=h=>`<attribute alias="${h.alias}" name="${rl(h.series.attribute)}" aggregate="${rl(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${rl(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${rl(h.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(h,g)=>{if(!h){l.push(g);return}let b=u.get(h);b?b.push(g):u.set(h,[g])};i.forEach(h=>c(h.series.relatedEntity,a(h))),o.forEach(h=>c(h.category.relatedEntity,s(h)));let d=[...u.entries()].map(([h,g])=>`<link-entity name="${rl(h)}">${g.join("")}</link-entity>`).join(""),f=l.join("")+d,m=i.map(h=>`<measurecollection><measure alias="${h.alias}" /></measurecollection>`).join(""),p=(r=(t=o[0])===null||t===void 0?void 0:t.alias)!==null&&r!==void 0?r:"";return`<datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="${rl(n)}">${f}</entity></fetch></fetchcollection><categorycollection><category alias="${p}">${m}</category></categorycollection></datadefinition>`}var Cp=class{toArtifact(t){var r,n,i,o,a,s,l;(0,uv.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,oi.parseXmlRoot)(u,"<datadefinition/>"),f=(0,oi.parseXmlRoot)(c,"<Chart/>");return{id:(i=t.savedqueryvisualizationid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.primaryentitytypecode)!==null&&s!==void 0?s:"",chartType:Ep(f),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:T$(d),categories:D$(d),presentation:N$(f),dataBag:u?(0,oi.projectElementBag)(d):void 0,presentationBag:c?(0,oi.projectElementBag)(f):void 0,rowBag:Qre(t.charttype,t.type)}}fromArtifact(t){(0,uv.installDomShim)();let{datadescription:r,presentationdescription:n}=Xre(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:w$(t.rowBag,"charttype"),type:w$(t.rowBag,"type"),isdefault:t.isDefault}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,o,a,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:(o=u.presentationdescription)!==null&&o!==void 0?o:"",primaryentitytypecode:(a=u.primaryentitytypecode)!==null&&a!==void 0?a:"",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,o,a,s,l;(0,uv.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,jre.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New Chart",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:u,chartType:(a=t.chartType)!==null&&a!==void 0?a:"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,b$.childObjects)(n,"series","","series",r),(0,b$.childObjects)(n,"categories","","category",r),r}};nl.ChartAdapter=Cp;function Qre(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 w$(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 Ep(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return S$(t[r].getAttribute("ChartType"));return"Column"}function N$(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],o=((t=i?.textContent)!==null&&t!==void 0?t:"").trim();return o&&(r.title=o),r}function Ap(e){return e.getElementsByTagName("fetch")[0]}function _$(e){let t=new Map;if(!e)return t;let r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("alias")||l.getAttribute("name");u&&t.set(u,o)}}return t}function T$(e){let t=Ap(e);if(!t)return[];let r=_$(t),n=t.getElementsByTagName("attribute"),i=[];for(let o=0;o<n.length;o+=1){let a=n[o],s=a.getAttribute("aggregate");if(!s)continue;let l=a.getAttribute("name");if(!l)continue;let u={attribute:l,aggregate:s},c=a.getAttribute("charttype");c&&(u.seriesType=S$(c));let d=a.getAttribute("alias");d&&(u.alias=d);let f=d||l,m=r.get(f);m&&(u.relatedEntity=m),i.push(u)}return i}function D$(e){var t;let r=Ap(e);if(!r)return[];let n=_$(r),i=r.getElementsByTagName("attribute"),o=[];for(let a=0;a<i.length;a+=1){let s=i[a];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 f=d||l,m=n.get(f);m&&(u.relatedEntity=m),o.push(u)}return o}function Xre(e){var t,r;let n=(t=e.series)!==null&&t!==void 0?t:[],i=(r=e.categories)!==null&&r!==void 0?r:[];if(!C$(e.dataBag)||!C$(e.presentationBag)){let c=Yre({...e,series:n,categories:i});return{datadescription:c,presentationdescription:yne(e,c)}}let o=new DOMParser().parseFromString("<root/>","text/xml"),a=E$(e.dataBag,"datadefinition",o),s=E$(e.presentationBag,"Chart",o),l=e.chartType||Ep(s),u=T$(a);if(!cv(n,u)){let c=dv(a);Zre(o,a,n);let d=dv(a),f=d.length>0?d:n.map(()=>"");I$(o,s,f,c,l)}return cv(i,D$(a))||ene(o,a,i),e.chartType&&e.chartType!==Ep(s)&&R$(s,e.chartType),e.presentation&&!cv(e.presentation,N$(s))&&L$(s,e.presentation),{datadescription:(0,oi.serializeNode)(a),presentationdescription:(0,oi.serializeNode)(s)}}function C$(e){return!!e&&(e.c.length>0||e.a.length>0)}function I$(e,t,r,n,i){let o,a=t.childNodes;for(let d=0;d<a.length;d+=1)if(a[d].nodeType===1&&a[d].tagName==="Series"){o=a[d];break}o||(o=e.createElement("Series"),t.insertBefore(o,t.firstChild));let s=[],l=o.childNodes;for(let d=0;d<l.length;d+=1)l[d].nodeType===1&&l[d].tagName==="Series"&&s.push(l[d]);let u=new Map;n.forEach((d,f)=>{let m=s[f];if(!m)return;let p=u.get(d);p?p.push(m):u.set(d,[m])});let c=r.map(d=>{let f=u.get(d),m=f&&f.length>0?f.shift():void 0;if(m)return m;let p=e.createElement("Series");p.setAttribute("ChartType",i);let h=s.length>0?s[0].getAttribute("ChartArea"):null;return h&&p.setAttribute("ChartArea",h),p});for(let d of s)o.removeChild(d);for(let d of c)o.appendChild(d)}function dv(e){let t=[],r=e.getElementsByTagName("measure");for(let n=0;n<r.length;n+=1)t.push(r[n].getAttribute("alias")||"");return t}function E$(e,t,r){let n={n:t,a:(0,lv.mergeAttrs)(e.a,[]),c:(0,lv.spliceChildren)(e.c,[])};return(0,lv.rebuildRaw)(n,(0,oi.domEngine)(r),null)}function Zre(e,t,r){let n=Ap(t),i=n?.getElementsByTagName("entity")[0];!n||!i||O$(e,t,i,sne(n),r,une,{aliasPrefix:"aggregate_column",addRef:nne,removeRef:ane})}function ene(e,t,r){let n=Ap(t),i=n?.getElementsByTagName("entity")[0];!n||!i||O$(e,t,i,lne(n),r,cne,{aliasPrefix:"groupby_column",addRef:ine,removeRef:one})}function O$(e,t,r,n,i,o,a){let s=new Map;for(let m of n){let p=m.getAttribute("alias");p&&s.set(p,m)}let l=new Set,u=[],c=(m,p)=>{var h;let g=dne(r,m),b=p.relatedEntity;(g??void 0)!==(b??void 0)&&((h=m.parentNode)===null||h===void 0||h.removeChild(m),A$(e,r,m,b))};for(let m of i){let p=m.alias?s.get(m.alias):void 0;p&&!l.has(p)?(o(p,m),c(p,m),l.add(p)):u.push(m)}let d=n.filter(m=>!l.has(m)),f=0;for(let m of u)if(f<d.length){let p=d[f];o(p,m),c(p,m),l.add(p),f+=1}else{let p=e.createElement("attribute"),h=m.alias||rne(t,a.aliasPrefix);p.setAttribute("alias",h),o(p,m),A$(e,r,p,m.relatedEntity),a.addRef(e,t,h)}for(let m of n)if(!l.has(m)){let p=m.getAttribute("alias");p&&a.removeRef(t,p),pne(m)}}function tne(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 o=n[i].getAttribute("alias");o&&t.add(o)}}return t}function rne(e,t){let r=tne(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function P$(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function nne(e,t,r){let n=P$(e,t),i=n.getElementsByTagName("category")[0];i||(i=e.createElement("category"),n.appendChild(i));let o=e.createElement("measurecollection"),a=e.createElement("measure");a.setAttribute("alias",r),o.appendChild(a),i.appendChild(o)}function ine(e,t,r){let n=P$(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function one(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 ane(e,t){var r;let n=e.getElementsByTagName("measure"),i=[];for(let o=0;o<n.length;o+=1)n[o].getAttribute("alias")===t&&i.push(n[o]);for(let o of i){let a=o.parentNode;a?.removeChild(o),a&&a.tagName==="measurecollection"&&!hne(a)&&((r=a.parentNode)===null||r===void 0||r.removeChild(a))}}function sne(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 lne(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 une(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function cne(e,t){e.setAttribute("name",t.attribute),e.setAttribute("groupby","true"),t.dateGrouping?e.setAttribute("dategrouping",t.dateGrouping):e.hasAttribute("dategrouping")&&e.removeAttribute("dategrouping")}function dne(e,t){let r=t.parentNode;for(;r&&r!==e;){let n=r;if(n.nodeType===1&&n.tagName==="link-entity")return n.getAttribute("name")||void 0;r=n.parentNode}}function A$(e,t,r,n){n?fne(e,t,n).appendChild(r):t.appendChild(r)}function fne(e,t,r){let n=t.getElementsByTagName("link-entity");for(let o=0;o<n.length;o+=1)if(n[o].getAttribute("name")===r)return n[o];let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function pne(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!mne(t))){let r=t.parentNode;r&&r.removeChild(t)}}function mne(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 hne(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function R$(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(!gne(r[i])){r[i].setAttribute("ChartType",t);return}}}function gne(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 L$(e,t){var r;let n=e.ownerDocument;if(t.palette!==void 0&&e.setAttribute("Palette",t.palette),t.showLegend!==void 0){let i=e.getElementsByTagName("Legend").length>0;if(t.showLegend&&!i){let o=e.getElementsByTagName("Legends")[0];o||(o=n.createElement("Legends"),e.appendChild(o));let a=n.createElement("Legend");a.setAttribute("Name","Default"),o.appendChild(a)}else if(!t.showLegend)for(let o of["Legends","Legend"]){let a=[],s=e.getElementsByTagName(o);for(let l=0;l<s.length;l+=1)a.push(s[l]);for(let l of a)(r=l.parentNode)===null||r===void 0||r.removeChild(l)}}if(t.title!==void 0){let i=e.getElementsByTagName("Title")[0];i&&(i.textContent=t.title)}}function yne(e,t){let r=(0,oi.parseXmlRoot)(Jre(),"<Chart/>"),n=e.chartType||Ep(r);R$(r,n),e.presentation&&L$(r,e.presentation);let i=dv((0,oi.parseXmlRoot)(t,"<datadefinition/>"));return i.length>0&&I$(r.ownerDocument,r,i,i.slice(0,1),n),(0,oi.serializeNode)(r)}function cv(e,t){return JSON.stringify(e)===JSON.stringify(t)}function rl(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function bne(){return{adapter:new Cp,api:zre.chartApi,publish:(e,t,r)=>(0,v$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,v$.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}nl.chartRegistration=bne});var M$=v(Ca=>{"use strict";Object.defineProperty(Ca,"__esModule",{value:!0});Ca.dashboardApi=Ca.dashboardEntity=void 0;var vne=Lt(),Io=ye(),il=se(),wne=mg(),$$=Xl();function x$(e){return e&&e.toLowerCase()!=="none"?e:void 0}Ca.dashboardEntity=x$;var F$="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",Cne={select:F$,required:["name","type","objecttypecode","istabletenabled"]},Ene="formid,name,type,objecttypecode",Ane=0,Sne=10;Ca.dashboardApi={async get(e,t){let r=(0,il.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,il.odataQuery)([["$select",F$]]),i=(0,Io.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,$$.assertSystemFormRecordKind)(i.body,r,"dashboard","fetch"),{raw:i.body,etag:(0,Io.readEtag)(i)}},async list(e,t){let r=[`(type eq ${Ane} or type eq ${Sne})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,il.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,il.odataQuery)([["$select",Ene],["$filter",r.join(" and ")]])}`;return(await(0,vne.collectPages)(e,n,"listArtifacts('dashboard')")).map(o=>{var a,s;let l=x$(o.objecttypecode);return{type:"dashboard",id:(a=o.formid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",...l?{entityLogicalName:l}:{},isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Io.echoWrite)("formid"),o=`/systemforms${i.query}`,a={name:n.name,description:n.description,formxml:n.formxml,istabletenabled:n.istabletenabled,type:n.type};n.objecttypecode&&(a.objecttypecode=n.objecttypecode);let s=(0,Io.ensureSuccess)(await e.post(o,(0,Io.withClientMintedId)(a,"formid",r),i.options),e.apiUrl(o));return{id:(0,Io.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Io.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,wne.patchSystemForm)(e,(0,il.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,Cne)},readContentThenToken(e,t){return Ca.dashboardApi.get(e,t)},async delete(e,t){let r=(0,il.normalizeGuid)(t,"id");return await(0,$$.assertSystemFormKind)(e,r,"dashboard"),(0,Io.deleteRecord)(e,"systemforms",r)}}});var Q$=v(ai=>{"use strict";Object.defineProperty(ai,"__esModule",{value:!0});ai.dashboardRegistration=ai.TILE_CLASS_ID=ai.DashboardAdapter=void 0;var tc=so(),pn=uo(),fv=Jr(),ec=en(),W$=M$(),pv=lo(),Ea=dt(),z$=se(),j$=Ho(),Nne=Ny(),U$="0",mv="10",_ne=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"]]),Tne="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",Np=class{constructor(t=j$.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,o,a;(0,pv.installDomShim)();let s=(r=t.formxml)!==null&&r!==void 0?r:"",l=(0,pn.parseXmlRoot)(s,"<form/>");return{id:(n=t.formid)!==null&&n!==void 0?n:"",name:(i=t.name)!==null&&i!==void 0?i:"",description:(o=t.description)!==null&&o!==void 0?o:"",dashboardType:Dne(t.type),entityLogicalName:(a=(0,W$.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:Ine(l),components:B$(l,this.lcid),bag:(0,pn.projectElementBag)(l)}}fromArtifact(t){var r;return(0,pv.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?mv:U$,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:q$(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}completeAsStored(t,r){return(0,Nne.completeRecordAsStored)(t,r,this.lcid)}toApiPayload(t){return{name:t.name,description:t.description,formxml:q$(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?mv:U$,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,o,a,s,l,u;(0,pv.installDomShim)();let c=(0,pn.parseXmlRoot)(Vne(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,Ea.newId)(),name:(n=t.name)!==null&&n!==void 0?n:"New Dashboard",description:(i=t.description)!==null&&i!==void 0?i:"",dashboardType:(o=t.dashboardType)!==null&&o!==void 0?o:"Standard",entityLogicalName:(a=t.entityLogicalName)!==null&&a!==void 0?a: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:B$(c,this.lcid),bag:(0,pn.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,Ea.newId)())}return t}validate(t){let r=[],n=(0,ec.childObjects)(t,"components","","component",r),i=new Set;return n.forEach(({node:o,index:a})=>{let s=`/components/${a}`;for(let l of["position","parameters"]){let u=o[l];u!==void 0&&!(0,ec.isJsonObject)(u)&&r.push((0,ec.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,ec.isJsonObject)(o.position)){let l=rc(o.position);i.has(l)?r.push((0,ec.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};ai.DashboardAdapter=Np;function Dne(e){return String(e??"")===mv?"Interactive":"Standard"}function Ine(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),r=parseInt(t??"",10);return Number.isNaN(r)?0:r}function ae(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName.toLowerCase()===t&&r.push(o)}return r}function B$(e,t){let r=[];return ae(e,"tabs").flatMap(i=>ae(i,"tab")).forEach((i,o)=>{ae(i,"columns").flatMap(s=>ae(s,"column")).forEach((s,l)=>{ae(s,"sections").flatMap(c=>ae(c,"section")).forEach((c,d)=>{One(c,{tabIndex:o,columnIndex:l,sectionIndex:d},r,t)})})}),r}function One(e,t,r,n){ae(e,"rows").flatMap(o=>ae(o,"row")).forEach((o,a)=>{ae(o,"cell").forEach((s,l)=>{let u=Pne(s,{...t,rowIndex:a,cellIndex:l},n);u&&r.push(u)})})}function Pne(e,t,r){var n,i;let o=J$((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(o.toLowerCase().startsWith("spacer"))return null;let a=ae(e,"control")[0];if(!a)return null;let s=(i=a.getAttribute("classid"))!==null&&i!==void 0?i:"",l=kne(a),u=$ne(s,l,a),c=Rne(a);return{id:a.getAttribute("id")||o,type:u,name:K$(e,r),classId:s,position:t,colspan:_p(e,"colspan",1),rowspan:_p(e,"rowspan",1),parameters:l,bag:(0,pn.projectElementBag)(e),...c?{icProperties:c}:{}}}function H$(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 Rne(e){let t=H$(e);return t?(0,pn.serializeNode)(t):void 0}function Lne(e,t,r){let n=H$(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,o=(0,tc.rebuildRaw)((0,tc.rawFromNode)((0,pn.nodeLikeFromDom)(i)),(0,pn.domEngine)(e),null);n&&(0,pn.serializeNode)(n)===(0,pn.serializeNode)(o)||(n?t.replaceChild(o,n):t.appendChild(o))}function K$(e,t){var r,n;let i=ae(e,"labels")[0];if(!i)return"";let o=ae(i,"label"),a=(r=o.find(s=>s.getAttribute("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return(n=a?.getAttribute("description"))!==null&&n!==void 0?n:""}function kne(e){var t;let r={},n=ae(e,"parameters")[0];if(!n)return r;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];a.nodeType===1&&(r[a.tagName]=((t=a.textContent)!==null&&t!==void 0?t:"").trim())}return r}function $ne(e,t,r){var n;let i=_ne.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"?((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===Tne?"assistant":t.ChartGridMode!==void 0||r.getAttribute("indicationOfSubgrid")==="true"?t.ChartGridMode==="Chart"?"chart":"list":"unknown":i:"unknown"}function _p(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 J$(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function xne(e,t){let r={n:"form",a:(0,tc.mergeAttrs)(e.bag.a,[]),c:(0,tc.spliceChildren)(e.bag.c,[])};return(0,tc.rebuildRaw)(r,(0,pn.domEngine)(t),null)}function q$(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=xne(e,r);return Une(r,n,e.components,t),Fne(r,n,e.components,t),(0,pn.serializeNode)(n)}function Fne(e,t,r,n){let i=Y$(t);for(let o of r)i.has(rc(o.position))||Mne(e,t,o,n)}function Mne(e,t,r,n){var i,o,a,s;let l=(o=(i=r.position)===null||i===void 0?void 0:i.sectionIndex)!==null&&o!==void 0?o:0,u=Gne(t,e,l);for(let x of ae(u,"row"))ae(x,"cell").some(K=>ae(K,"control").length>0)||u.removeChild(x);let c=r.classId||ai.TILE_CLASS_ID[r.type]||ai.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,f=r.bag&&V$(r.bag,"id")?String(V$(r.bag,"id")):Sp((0,Ea.newId)()),m=r.id?Sp(r.id):Sp((0,Ea.newId)()),p=u.parentNode,h=Math.max(1,parseInt(p&&p.getAttribute&&p.getAttribute("columns")||"1",10)||1),g=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),h),b=ae(u,"row"),w=b[b.length-1],E=w?ae(w,"cell").reduce((x,K)=>x+_p(K,"colspan",1),0):0;(!w||E+g>h)&&(w=e.createElement("row"),u.appendChild(w));let S=e.createElement("cell");S.setAttribute("id",f),S.setAttribute("colspan",String(g)),S.setAttribute("rowspan",String(d)),S.setAttribute("showlabel","true");let P=e.createElement("labels"),L=e.createElement("label");L.setAttribute("description",(a=r.name)!==null&&a!==void 0?a:""),L.setAttribute("languagecode",String(n)),P.appendChild(L),S.appendChild(P);let I=e.createElement("control");I.setAttribute("id",m),I.setAttribute("classid",Sp(c));let D=e.createElement("parameters"),O=(s=r.parameters)!==null&&s!==void 0?s:{};for(let x of Object.keys(O)){let K=(0,z$.createSafeXmlElement)(e,x,"dashboard tile parameter");K.textContent=O[x],D.appendChild(K)}I.appendChild(D),S.appendChild(I),w.appendChild(S)}function V$(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Une(e,t,r,n){var i;let o=Y$(t),a=new Set(r.map(s=>rc(s.position)));for(let s of r){let l=o.get(rc(s.position));if(!l)continue;let u=ae(l,"control")[0];u&&(Bne(e,l,s.name,n),qne(e,u,s.parameters),G$(l,"colspan",s.colspan),G$(l,"rowspan",s.rowspan),s.icProperties!==void 0&&Lne(e,u,s.icProperties))}for(let[s,l]of o)a.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function Y$(e){let t=new Map;return ae(e,"tabs").flatMap(n=>ae(n,"tab")).forEach((n,i)=>{ae(n,"columns").flatMap(a=>ae(a,"column")).forEach((a,s)=>{ae(a,"sections").flatMap(u=>ae(u,"section")).forEach((u,c)=>{ae(u,"rows").flatMap(f=>ae(f,"row")).forEach((f,m)=>{ae(f,"cell").forEach((p,h)=>{var g;J$((g=p.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||ae(p,"control")[0]&&t.set(rc({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:m,cellIndex:h}),p)})})})})}),t}function rc(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function Bne(e,t,r,n){if(r===K$(t,n))return;let i=ae(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let o=ae(i,"label").find(a=>a.getAttribute("languagecode")===String(n));o||(o=e.createElement("label"),o.setAttribute("languagecode",String(n)),i.appendChild(o)),o.setAttribute("description",r)}function qne(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let o=ae(t,"parameters")[0];o||(o=e.createElement("parameters"),t.appendChild(o));let a=new Map,s=o.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];u.nodeType===1&&a.set(u.tagName,u)}for(let l of i){let u=r[l],c=a.get(l);if(c)((n=c.textContent)!==null&&n!==void 0?n:"")!==u&&(c.textContent=u);else{let d=(0,z$.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,o.appendChild(d)}}}function G$(e,t,r){_p(e,t,1)!==r&&e.setAttribute(t,String(r))}function Vne(e=2){let t=`{${(0,Ea.newId)()}}`,r=`{${(0,Ea.newId)()}}`,n=`{${(0,Ea.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>`}ai.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 Sp(e){return`{${e.replace(/[{}]/g,"")}}`}function Gne(e,t,r){var n;let i=ae(e,"tabs").flatMap(u=>ae(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let o=ae(i,"columns").flatMap(u=>ae(u,"column"))[0];if(!o)throw new Error("addDashboardTile: dashboard formxml has no <column>");let a=ae(o,"sections").flatMap(u=>ae(u,"section")),s=(n=a[r])!==null&&n!==void 0?n:a[0];if(!s)throw new Error("addDashboardTile: dashboard formxml has no <section>");let l=ae(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function Wne(e=j$.DEFAULT_LCID){return{adapter:new Np(e),api:W$.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,fv.publishBoundEntity)(t,n):(0,fv.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,fv.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}ai.dashboardRegistration=Wne});var gv=v(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.readEveryInOrder=kr.readInOrder=kr.plainRead=kr.resolveReadConcurrency=kr.MAX_READ_CONCURRENCY=void 0;var X$=Q();kr.MAX_READ_CONCURRENCY=8;function zne(e){if(e===void 0)return 1;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>kr.MAX_READ_CONCURRENCY)throw new X$.InvalidArgumentError(`readConcurrency must be a whole number from 1 to ${kr.MAX_READ_CONCURRENCY} (got ${typeof e=="string"?`'${e}'`:String(e)})`);return e}kr.resolveReadConcurrency=zne;var jne=e=>({ok:!0,value:e}),hv=e=>({ok:!1,error:e});function Hne(e){let t=(async()=>e())().then(jne,hv);return{outcome:t,finish:async r=>{await r()},discard:async()=>{await t}}}kr.plainRead=Hne;async function Z$(e,t,r,n,i){if(!Number.isInteger(t)||t<1)throw new X$.InvalidArgumentError(`a read window holds a whole number of reads, at least 1 (got ${String(t)})`);let o=new Map,a=0,s=Promise.resolve(),l=!1,u=0,c,d=async f=>{if(l)return{refusal:new Error("The read was not started: an earlier read had already failed.")};try{let m=await r(e[f],f),p=m.outcome.catch(hv);return i==="stop"&&p.then(h=>{l=l||!h.ok}),{read:m,outcome:p}}catch(m){return l=l||i==="stop",{refusal:m}}};try{for(let f=0;f<e.length;f+=1){for(;a<e.length&&a<f+t;){let g=a;a+=1;let b=s.then(()=>d(g));o.set(g,b),s=b}let m=await o.get(f),p="read"in m?await m.outcome:hv(m.refusal);if(!p.ok&&i==="stop"){c={error:p.error};break}u=f+1,o.delete(f);let h=()=>n(p,e[f],f);"read"in m?await m.read.finish(h):await h()}}finally{l=!0;for(let f=u;f<a;f+=1){let m=await o.get(f);"read"in m&&await m.read.discard().catch(()=>{})}}if(c)throw c.error}function Kne(e,t,r,n){return Z$(e,t,r,(i,o,a)=>n(i.value,o,a),"stop")}kr.readInOrder=Kne;function Jne(e,t,r,n){return Z$(e,t,r,n,"continue")}kr.readEveryInOrder=Jne});var gx=v(Dp=>{"use strict";Object.defineProperty(Dp,"__esModule",{value:!0});Dp.genPageApi=void 0;var Tp=Lt(),dx=Wl(),Be=ye(),ve=se(),$n=Dd(),Ye=Q(),fx=dt(),ex=gv();function Yne(e){if(ArrayBuffer.isView(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(Object.prototype.toString.call(e)==="[object ArrayBuffer]")return new Uint8Array(e);let t=globalThis;if(t.Buffer&&t.Buffer.isBuffer(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}}var si="uxagentprojects",Sa="uxagentprojectfiles",oc="agentconversationmessages",ac="uxagentprojectid",Ut="uxagentprojectfileid",Na="agentconversationmessageid",nc=`${ac},name`,Qne=`${Ut},filename,filetype`,px=2e8,mx=200000001,_a={"MSCRM.IncludeUnpublished":"true"},yv={};function Aa(e,t){return{"MSCRM.VersioningChangeset":e,..._a,...t}}async function wv(e,t,r,n){var i;let o=`/${t}(${r})`+(0,ve.odataQuery)([["$select",n]]),a=(0,Be.ensureSuccess)(await e.get(o,{headers:{..._a}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,Be.readEtag)(a)}}async function sc(e,t,r=_a){let n=`/${Sa}(${t})/filecontent/$value`,i=await e.get(n,{headers:{...r}});if(i.status===404)return{status:"unavailable",reason:"missing"};(0,Be.ensureSuccess)(i,e.apiUrl(n));let o=i.body,a=Yne(o);if(a)return{status:"available",data:(0,$n.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,$n.utf8ToBase64)(o)};throw new Ye.SdkError("GENPAGE_CONTENT_UNREADABLE",`Read the content of file '${t}' but the injected HttpClient returned a body this SDK cannot encode (${typeof o}). Return the response as a string, Uint8Array, Buffer, or ArrayBuffer; a byte-returning transport is required to round-trip non-UTF8 assets.`)}function hx(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function Xne(e,t,r,n,i,o){if(!e.supportsBinaryPatch)throw new Ye.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 a=`/${Sa}(${t})/filecontent`,s=(0,$n.base64ToBytes)(n);(0,ve.assertNoControlChars)(r,"generative-page file name"),(0,Be.ensureSuccess)(await e.patchRaw(a,s,{headers:Aa(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":hx(r),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function ic(e,t,r=_a){let n=`/${Sa}`+(0,ve.odataQuery)([["$select",Qne],["$filter",`_${ac}_value eq ${t}`]]);return(await(0,Tp.collectPages)(e,n,"fetchArtifact('genPage')",void 0,{headers:{...r}})).map(o=>({row:o,etag:typeof o["@odata.etag"]=="string"?o["@odata.etag"]:null}))}async function bv(e,t){let r=`/${oc}`+(0,ve.odataQuery)([["$select",`${Na},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,Tp.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{..._a}})}async function tx(e,t){var r,n,i;let{row:o,etag:a}=await wv(e,si,t,nc),s=new Map;for(let{row:l,etag:u}of await ic(e,t))s.set((0,ve.normalizeGuid)(String((r=l[Ut])!==null&&r!==void 0?r:""),Ut),{filename:String((n=l.filename)!==null&&n!==void 0?n:""),filetype:Number(l.filetype),etag:u});return{name:String((i=o.name)!==null&&i!==void 0?i:""),etag:a,rows:s}}function rx(e,t,r){var n,i,o,a,s;let l=[];r||l.push({kind:"createProject",name:t.name});let u=new Set;for(let c of(n=t.files)!==null&&n!==void 0?n:[]){let d=(0,ve.normalizeGuid)(c.id,"file id");u.add(d);let f=r?.rows.get(d);if(c.content.status==="retain"){if(!r)throw new Ye.SdkError("GENPAGE_RETAIN_ON_CREATE",`Refusing to create generative page '${e}': file '${c.name}' asks to keep content the page does not have yet. This is an SDK defect \u2014 the page's rows were not written.`);if(!f)throw new Ye.SdkError("GENPAGE_RETAINED_ROW_MISSING",`Refusing to write generative page '${e}': file '${c.name}' was to be kept unchanged but is not on the server. Re-fetch the page and retry.`);continue}f&&c.unchanged||(f?(f.filename!==c.name||f.filetype!==c.fileType)&&l.push({kind:"renameRow",file:c}):l.push({kind:"createRow",file:c}),c.content.status==="available"&&l.push({kind:"content",file:c,data:c.content.data,existing:f!==void 0}))}for(let c of(i=r?.rows.keys())!==null&&i!==void 0?i:[])u.has(c)||l.push({kind:"deleteRow",fileId:c});(!r||l.length>0||r.name!==t.name||((a=(o=t.messages)===null||o===void 0?void 0:o.length)!==null&&a!==void 0?a:0)>0)&&l.push({kind:"patchProject",name:t.name});for(let c of(s=t.messages)!==null&&s!==void 0?s:[])l.push({kind:"message",turn:c});return l}function Cv(e){let t=(0,$n.base64ToUtf8)(e);return(0,$n.utf8ToBase64)(t)===(0,$n.bytesToBase64)((0,$n.base64ToBytes)(e))?t:void 0}function Zne(e,t,r,n){var i,o,a,s,l,u,c,d;let f=t.sender==="user"?{changeSet:n,dataSources:(o=(i=r.messageContext)===null||i===void 0?void 0:i.dataSources)!==null&&o!==void 0?o:[],model:(s=(a=r.messageContext)===null||a===void 0?void 0:a.model)!==null&&s!==void 0?s:"",enabledTools:(u=(l=r.messageContext)===null||l===void 0?void 0:l.enabledTools)!==null&&u!==void 0?u:[],configurableTools:(d=(c=r.messageContext)===null||c===void 0?void 0:c.configurableTools)!==null&&d!==void 0?d:[]}:{changeSet:n};return{...t.id?{[Na]:(0,ve.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${si}(${e})`,message:t.message,messagecontext:JSON.stringify(f),messagesender:t.sender==="user"?px:mx}}async function eie(e,t,r){var n,i,o,a;let s=((n=r.messages)!==null&&n!==void 0?n:[]).map(f=>f.id).filter(f=>typeof f=="string"&&f!=="").map(f=>(0,ve.normalizeGuid)(f,"message id"));if(s.length===0)return r;let l=`/${oc}`+(0,ve.odataQuery)([["$select",`${Na},message,messagesender,_regardingobjectid_value`],["$filter",s.map(f=>`${Na} eq ${f}`).join(" or ")]]),u=await(0,Tp.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{..._a}});if(u.length===0)return r;let c=new Map(u.map(f=>{var m;return[String((m=f[Na])!==null&&m!==void 0?m:"").toLowerCase(),f]})),d=[];for(let f of(i=r.messages)!==null&&i!==void 0?i:[]){let m=f.id?c.get((0,ve.normalizeGuid)(f.id,"message id")):void 0;if(!m){d.push(f);continue}if(!(String((o=m.message)!==null&&o!==void 0?o:"")===f.message&&Number(m.messagesender)===(f.sender==="user"?px:mx)&&String((a=m._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new Ye.SdkError("GENPAGE_TURN_CONFLICT",`Refusing to push generative page '${t}': its pending turn's identity is already recorded \u2014 as a DIFFERENT ${f.sender} message. An earlier push of this turn did commit (its response was lost), and the turn was changed since. Nothing was written, and the turn is still pending. To record it as a new turn, remove '/newTurn/id' (a new identity is minted on the next push); to keep only what was recorded, remove '/newTurn'.`)}return{...r,messages:d}}function vv(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${si}`,body:(0,Be.withClientMintedId)({name:t.name},ac,e),headers:Aa(n)};case"createRow":return{method:"POST",path:`/${Sa}`,body:(0,Be.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${ac}@odata.bind`]:`/${si}(${e})`},Ut,(0,ve.normalizeGuid)(t.file.id,"file id")),headers:Aa(n)};case"renameRow":return{method:"PATCH",path:`/${Sa}(${(0,ve.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Aa(n,{"If-Match":"*"})};case"content":{let i=Cv(t.data);if(i===void 0)throw new Ye.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,ve.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${Sa}(${(0,ve.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Aa(n,{"x-ms-file-name":hx(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${Sa}(${t.fileId})`,headers:Aa(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${si}(${e})`,body:{name:t.name},headers:Aa(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${oc}`,body:Zne(e,t.turn,r,n)};default:{let i=t;throw new Ye.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function nx(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||Cv(r.data)!==void 0)}async function ix(e,t,r,n,i){await(0,dx.postChangeSet)(e,r.map(o=>vv(t,o,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function ox(e,t,r,n,i){var o;let a=[];for(let s of r){if(s.kind==="message"){a.push(s);continue}if(s.kind==="content"){await Xne(e,(0,ve.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=vv(t,s,n,i),u={headers:(o=l.headers)!==null&&o!==void 0?o:{}},c=l.method==="POST"?await e.post(l.path,l.body,u):l.method==="PATCH"?await e.patch(l.path,l.body,u):await e.delete(l.path,u);(0,Be.ensureSuccess)(c,e.apiUrl(l.path))}if(a.length===0)return{warnings:[],turnRecorded:!0};try{let s=a.map(l=>vv(t,l,n,i));if(e.supportsAtomicBatch)await(0,dx.postChangeSet)(e,s,`the conversation turn of generative page '${t}'`);else for(let l of s)(0,Be.ensureSuccess)(await e.post(l.path,l.body),e.apiUrl(l.path));return{warnings:[],turnRecorded:!0}}catch(s){return{warnings:[`Generative page '${t}' was saved, but its conversation turn could not be recorded (${s instanceof Error?s.message:String(s)}). The turn is kept: the next push of the page records it.`],turnRecorded:!1}}}async function ax(e,t,r,n,i,o,a){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...a,u]});try{let u=await tx(e,t),c=new Map;for(let E of r)(E.kind==="createRow"||E.kind==="renameRow"||E.kind==="content")&&c.set((0,ve.normalizeGuid)(E.file.id,"file id"),E.file);let d=[];u.name!==n.name&&d.push(`the page is named '${u.name}', not '${n.name}'`);for(let[E,S]of c){let P=u.rows.get(E);P&&(P.filename!==S.name||P.filetype!==S.fileType)&&d.push(`file '${S.name}' is stored as '${P.filename}' (type ${P.filetype})`)}for(let E of r){if(E.kind!=="content")continue;let S=await sc(e,(0,ve.normalizeGuid)(E.file.id,"file id")),P=(0,$n.bytesToBase64)((0,$n.base64ToBytes)(E.data));(S.status!=="available"||S.data!==P)&&d.push(S.status==="available"?`file '${E.file.name}' holds ${(0,$n.base64ToBytes)(S.data).byteLength} byte(s) that differ from the ${(0,$n.base64ToBytes)(P).byteLength} written`:`file '${E.file.name}' holds no content`)}let f=new Set(r.filter(E=>E.kind==="content").map(E=>(0,ve.normalizeGuid)(E.file.id,"file id")));for(let[E,S]of c)!f.has(E)&&(await sc(e,E)).status==="available"&&d.push(`file '${S.name}' holds content this push did not write`);if(d.length>0)return l(`Generative page '${t}' was written, but reading it back does not match what was sent: ${d.join("; ")}. The local baseline is now unusable: re-fetch the page to see what the server holds \u2014 the next push will refuse rather than overwrite blind.`);let m=await tx(e,t),p=[...m.rows.keys()],h=m.etag!==u.etag||m.rows.size!==u.rows.size||p.some(E=>{var S,P;return((S=u.rows.get(E))===null||S===void 0?void 0:S.etag)!==((P=m.rows.get(E))===null||P===void 0?void 0:P.etag)}),g=p.length!==i.size||p.some(E=>!i.has(E)),b={},w=[];for(let[E,S]of m.rows){let P=c.has(E)||!o?S.etag:(s=o.get(E))!==null&&s!==void 0?s:null;b[E]=P,P!==S.etag&&w.push(S.filename)}return h||g||!m.etag||Object.values(b).some(E=>!E)?l(`Generative page '${t}' was written, but its files changed on the server while the write was in progress, so the new concurrency tokens cannot be trusted. The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`):tie({id:t,etag:m.etag,memberEtags:b},[...a,...w.map(E=>`Generative page '${t}' was written, but its file '${E}' changed on the server while this push ran \u2014 another writer edited it. This push did not touch that file, so the next one refuses until you re-fetch the page and see their change.`)])}catch(u){return l(`The generative page was written, but reading it back failed (${u instanceof Error?u.message:String(u)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`)}}async function sx(e,t,r,n=e.readConcurrency){var i;let o=(0,ve.normalizeGuid)(t,"id"),{row:a,etag:s}=await wv(e,si,o,nc),l=await ic(e,o),u={},c=[];if(n>1)await(0,ex.readInOrder)(l,n,({row:f})=>{var m;let p=(0,ve.normalizeGuid)(String((m=f[Ut])!==null&&m!==void 0?m:""),Ut);return(0,ex.plainRead)(async()=>({fileId:p,content:await sc(e,p)}))},({fileId:f,content:m},{row:p,etag:h})=>{u[f]=h,c.push({...p,content:m})});else for(let{row:f,etag:m}of l){let p=(0,ve.normalizeGuid)(String((i=f[Ut])!==null&&i!==void 0?i:""),Ut);u[p]=m;let h=await sc(e,p);c.push({...f,content:h})}return{raw:r?{project:a,files:c,conversation:await bv(e,o)}:{project:a,files:c},etag:s,memberEtags:u}}Dp.genPageApi={get(e,t,r){return sx(e,t,!0,r?.fileConcurrency)},getForRebaseline(e,t){return sx(e,t,!1)},async getPublished(e,t){var r,n;let i=(0,ve.normalizeGuid)(t,"id"),o=`/${si}(${i})`+(0,ve.odataQuery)([["$select",nc]]),a=await e.get(o);if(a.status===404)return null;(0,Be.ensureSuccess)(a,e.apiUrl(o));let s=(r=a.body)!==null&&r!==void 0?r:{},l={},u=[],c=await ic(e,i,yv);for(let{row:g,etag:b}of c){let w=(0,ve.normalizeGuid)(String((n=g[Ut])!==null&&n!==void 0?n:""),Ut);l[w]=b,u.push({...g,content:await sc(e,w,yv)})}let d=g=>g.map(({row:b,etag:w})=>`${String(b[Ut])}@${String(w)}`).sort().join("|"),f=()=>new Ye.SdkError("GENPAGE_PUBLISHED_READ_MOVED",`The published projection of generative page '${i}' changed while it was being read, so what was read is not one published state. PublishXml is asynchronous \u2014 re-read shortly.`),m=await e.get(o);if(m.status===404)throw f();(0,Be.ensureSuccess)(m,e.apiUrl(o));let p=await ic(e,i,yv);if([(0,Be.readEtag)(a),(0,Be.readEtag)(m),...[...c,...p].map(g=>g.etag)].some(g=>!g))throw new Ye.SdkError("GENPAGE_PUBLISHED_READ_UNVERSIONED",`The published projection of generative page '${i}' answered without a version token for the page or one of its rows, so what was read cannot be proven to be one published state.`);if((0,Be.readEtag)(m)!==(0,Be.readEtag)(a)||d(p)!==d(c))throw f();return{raw:{project:s,files:u,conversation:[]},etag:(0,Be.readEtag)(a),memberEtags:l}},async list(e,t){let r=`/${si}`+(0,ve.odataQuery)([["$select",nc]]);return(await(0,Tp.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{..._a}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[ac])!==null&&o!==void 0?o:""),name:String((a=i.name)!==null&&a!==void 0?a:""),isDirty:!1}})},async create(e,t,r){var n;let i=t,o=r?(0,ve.normalizeGuid)(r,"id"):(0,fx.newId)(),a=rx(o,i,void 0);cx(e,a),ux(e,o,i);let s=lx(),l=[],u=!0;nx(e,a)?await ix(e,o,a,i,s):{warnings:l,turnRecorded:u}=await ox(e,o,a,i,s);let c=new Set(((n=i.files)!==null&&n!==void 0?n:[]).map(f=>(0,ve.normalizeGuid)(f.id,"file id"))),d=await ax(e,o,a,i,c,void 0,l);return u?d:{...d,intentPending:!0}},async update(e,t,r,n,i){var o,a;let s=r,l=(0,ve.normalizeGuid)(t,"id");if(!Array.isArray(s.files))throw new Ye.SdkError("GENPAGE_FILES_REQUIRED",`Refusing to update generative page '${l}': its payload has no files list. A page's files are its complete set of rows \u2014 a row the list omits is deleted \u2014 so an omitted list would delete every row of the page. Nothing was written.`);let u=await eie(e,l,s);ux(e,l,u);let c=await ic(e,l),{row:d,etag:f}=await wv(e,si,l,nc);if(n&&f&&n!==f)throw new Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Generative page '${l}' changed on the server after it was fetched (baseline ${n}, server ${f}) \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||!f)throw new Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify generative page '${l}' before writing: ${n?"the server did not return the page's current token":"no baseline token was recorded"}. This entity accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let m=new Map(c.map(({row:I})=>{var D,O;return[(0,ve.normalizeGuid)(String((D=I[Ut])!==null&&D!==void 0?D:""),Ut),{filename:String((O=I.filename)!==null&&O!==void 0?O:""),filetype:Number(I.filetype)}]})),p=new Set(m.keys()),h=new Set(((o=u.files)!==null&&o!==void 0?o:[]).map(I=>(0,ve.normalizeGuid)(I.id,"file id")));if(!i)throw new Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${l}' before writing: no child baseline was recorded. These rows accept no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let g=new Set(Object.keys(i).map(I=>I.toLowerCase()));for(let I of h)if(!p.has(I)&&g.has(I))throw new Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${I}' existed when this page was fetched but is gone from the server now \u2014 another writer deleted it. Refusing to recreate it, because a blind re-create would undo that delete. Re-fetch the page and re-apply the edit.`);for(let I of p)if(!g.has(I))throw new Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${I}' is on the server but absent from this page's baseline \u2014 another writer added it after the page was fetched, so its contents cannot be verified. Refusing to write over or delete it. Re-fetch the page so the addition is part of your baseline.`);let b=new Map(c.map(({row:I,etag:D})=>{var O;return[(0,ve.normalizeGuid)(String((O=I[Ut])!==null&&O!==void 0?O:""),Ut),D]}));for(let[I,D]of Object.entries(i)){let O=I.toLowerCase();if(!p.has(O))continue;let x=b.get(O);if(!D||!x)throw new Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${O}' before writing: ${D?"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(D!==x)throw new Ye.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${O}' changed on the server after this page was fetched (baseline ${D}, server ${x}) \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 w=rx(l,u,{rows:m,name:String((a=d.name)!==null&&a!==void 0?a:"")});if(cx(e,w),w.length===0)return{id:l,etag:f,memberEtags:Object.fromEntries(c.map(({row:I,etag:D})=>{var O;return[(0,ve.normalizeGuid)(String((O=I[Ut])!==null&&O!==void 0?O:""),Ut),D]}))};let E=lx(),S=[],P=!0;nx(e,w)?await ix(e,l,w,u,E):{warnings:S,turnRecorded:P}=await ox(e,l,w,u,E);let L=await ax(e,l,w,u,h,b,S);return P?L:{...L,intentPending:!0}},async delete(e,t){var r;let n=(0,ve.normalizeGuid)(t,"id"),i=await bv(e,n);await(0,Be.deleteRecord)(e,si,n);let o=new Set(i.map(l=>{var u;return String((u=l[Na])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),a=!1;try{for(let l of await bv(e,n)){let u=String((r=l[Na])!==null&&r!==void 0?r:"");u!==""&&o.add(u)}}catch{a=!0}let s=[];for(let l of o)try{await(0,Be.deleteRecord)(e,oc,l)}catch(u){u instanceof Ye.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||a)throw new Ye.SdkError("GENPAGE_HISTORY_NOT_DELETED",`Generative page '${n}' was deleted, but its conversation history was not fully removed`+(s.length>0?` \u2014 ${s.length} of ${o.size} message(s) could not be (${s.join(", ")})`:"")+(a?" \u2014 and re-reading it after the delete failed, so a late turn may remain":"")+`. They no longer belong to any page; delete them as ${oc} rows regarding '${n}'.`)}};function lx(){return`uxagentproject_${(0,fx.newId)()}`}function tie(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function ux(e,t,r){var n,i;if(((i=(n=r.messages)===null||n===void 0?void 0:n.length)!==null&&i!==void 0?i:0)>1&&!e.supportsAtomicBatch)throw new Ye.SdkError("GENPAGE_TURN_NOT_ATOMIC",`Refusing to write generative page '${t}': its new turn has a prompt AND a reply, which must be recorded together, and the injected HttpClient does not implement postRaw() \u2014 one request at a time, a failure between the two would leave half a turn. Implement postRaw(), or record the prompt alone (omit newTurn.agentMessage). Nothing was written.`)}function cx(e,t){let r=t.filter(i=>i.kind==="content");if(r.length>0&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new Ye.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient implements neither patchRaw() nor postRaw(). A Dataverse File column is not writable through a JSON body, so proceeding would create the page and its rows and then fail, leaving a page whose source never uploaded.");if(r.some(i=>Cv(i.data)===void 0)&&!e.supportsBinaryPatch)throw new Ye.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: a file's content is not UTF-8 text, which only the binary channel can carry, and the injected HttpClient does not implement patchRaw().")}});var Lx=v(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});al.genPageRegistration=al.GenPageAdapter=void 0;var rie=gx(),nie=Jr(),Ie=en(),Lp=dt(),kp=Dd(),iie=se(),Ta=Q(),Tx=Tg(),Ev=Km(),Oo=2e8,Dx=200000001,Gi={source:{name:"src/pages/page.tsx",fileType:Oo},output:{name:"src/pages/page.compiled",fileType:Dx},config:{name:"config.json",fileType:Oo},prompt:{name:"firstPrompt.json",fileType:Oo}},Ix=Object.keys(Gi),oie=["dataSources","model","connectorBindings","actionBindings"],aie=["userMessage","agentMessage"],yx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,sie={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},lie="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function Ox(e,t,r){let n=(0,iie.normalizeGuid)(e,r).replace(/-/g,""),i=[];for(let a=0;a<32;a+=1)i.push(parseInt(n[a],16)^parseInt(t[a],16));i[12]=4,i[16]=i[16]&3|8;let o=i.map(a=>a.toString(16)).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function Ip(e,t){return Ox(e,sie[t],"id")}function uie(e,t){let r=Ox(e,lie,"newTurn.id"),n=parseInt(r.slice(24),16)%2**47+(t==="agent"?1:0);return`${r.slice(0,24)}${n.toString(16).padStart(12,"0")}`}function bx(e){return typeof e=="string"&&e.trim()!==""?e:(0,Lp.newId)()}function Vi(e){return(0,Ie.isJsonObject)(e)?e:{}}function ol(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function Op(e){return JSON.parse(JSON.stringify(e))}function cie(e){let t=Vi(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function uc(e){if(!e||e.status!=="available")return;let t=(0,kp.base64ToUtf8)(e.data);return(0,kp.utf8ToBase64)(t)===e.data?t:void 0}function Px(e,t,r){var n,i,o,a;return e.source!==void 0&&t!==void 0&&t?.source===e.source&&ol((n=t?.dataSources)!==null&&n!==void 0?n:[],(i=e.dataSources)!==null&&i!==void 0?i:[])&&((a=(o=e.bag)===null||o===void 0?void 0:o.rows)!==null&&a!==void 0?a:{}).output!==void 0&&(0,Tx.isLoadableGenPageOutput)(r)}function die(e,t){var r;try{return Px(e,t,uc((r=e.bag)===null||r===void 0?void 0:r.output))}catch{return!1}}function Pp(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,Ie.isJsonObject)(t)?t:void 0}catch{return}}function vx(e,t){if(t===Oo&&e.includes("page.tsx"))return"source";if(t===Dx&&e.includes(".compiled"))return"output";if(t===Oo&&e===Gi.config.name)return"config";if(t===Oo&&e===Gi.prompt.name)return"prompt"}function wx(e){let t=e.toLowerCase();return Ix.some(r=>Gi[r].name.toLowerCase()===t)}function Av(e){return Object.fromEntries(e)}function Rx(e,t,r,n){let i=[],o=new Set,a=new Set(t),s=l=>{if(o.has(l))return;let u=a.has(l)?e[l]:r&&Object.prototype.hasOwnProperty.call(r,l)?r[l]:void 0;u!==void 0&&(o.add(l),i.push([l,u]))};return(n??[]).forEach(s),t.forEach(s),Object.keys(r??{}).forEach(s),Av(i)}function Cx(e){var t,r,n;return Rx({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},oie,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function Ex(e){var t,r;return Rx({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},aie,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function Ax(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="dataSources"){if(!Array.isArray(o)||!o.every(a=>typeof a=="string"))return!1;e.dataSources=o}else if(i==="model"){if(typeof o!="string")return!1;e.model=o}else i==="connectorBindings"?e.connectorBindings=o:i==="actionBindings"?e.actionBindings=o:n.push([i,o]);return t.configKeys=Object.keys(r),n.length>0&&(t.config=Av(n)),!0}function Sx(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="userMessage"||i==="agentMessage"){if(typeof o!="string")return!1;i==="userMessage"?e.firstPrompt=o:e.firstAgentMessage=o}else n.push([i,o]);return t.promptKeys=Object.keys(r),n.length>0&&(t.prompt=Av(n)),!0}function cc(e){var t,r;return e.source!==void 0||Object.keys((r=(t=e.bag)===null||t===void 0?void 0:t.rows)!==null&&r!==void 0?r:{}).length>0}var fie=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function Nx(e){return cc(e)?[]:fie.filter(t=>e[t]!==void 0).map(t=>(0,Ie.issue)(`/${t}`,"genpage-raw-structured-field",`${t} cannot be applied: this page is in raw-file mode \u2014 it has no source and no managed rows, so a push writes its files[] exactly as they are, and ${t} nowhere. Set source to make the page managed (the SDK then writes config.json and firstPrompt.json from the typed fields; a file in files[] holding one of those names must be removed first), or change the file that stores the value in files[] directly.`))}function _x(){return(0,Ie.issue)("/source","genpage-source-required","the page's source cannot be removed: its source row still exists, and a page without one cannot run. Set a new source, or delete the page with deleteRemoteArtifact.")}function Rp(e){return{status:"available",data:(0,kp.utf8ToBase64)(e)}}function lc(e,t){var r,n;return{id:String((r=e.uxagentprojectid)!==null&&r!==void 0?r:""),name:String((n=e.name)!==null&&n!==void 0?n:""),files:t}}var $p=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=Vi(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(g=>{var b,w,E;let S=Vi(g);return{id:String((b=S.uxagentprojectfileid)!==null&&b!==void 0?b:""),name:String((w=S.filename)!==null&&w!==void 0?w:""),fileType:Number((E=S.filetype)!==null&&E!==void 0?E:Oo),content:cie(S.content)}}),o=Array.isArray(r?.conversation)?r.conversation.map(g=>{var b,w;let E=Vi(g);return{sender:Number(E.messagesender)===200000001?"agent":"user",message:String((b=E.message)!==null&&b!==void 0?b:""),createdOn:String((w=E.createdon)!==null&&w!==void 0?w:"")}}):void 0,a=g=>o?{...g,conversation:o}:g,s=new Map,l=[],u=!0;for(let g of i){let b=vx(g.name,g.fileType);b?((s.has(b)||g.name!==Gi[b].name)&&(u=!1),s.set(b,g)):(wx(g.name)&&(u=!1),l.push(g))}if(!u||s.size===0)return a(lc(n,i));let c=lc(n,l),d={rows:{}};for(let[g,b]of s)d.rows[g]=b.id;let f=s.get("source");if(f){let g=uc(f.content);if(g===void 0)return a(lc(n,i));c.source=g}let m=s.get("output");m&&(d.output=m.content);let p=s.get("config");if(p){let g=Pp(uc(p.content));if(!g||!Ax(c,d,g))return a(lc(n,i))}let h=s.get("prompt");if(h){let g=Pp(uc(h.content));if(!g||!Sx(c,d,g))return a(lc(n,i))}return c.bag=d,a(c)}async toApiPayload(t,r,n){var i,o,a,s,l,u,c,d,f,m,p,h,g;if(r&&!ol((i=t.conversation)!==null&&i!==void 0?i:[],(o=r.conversation)!==null&&o!==void 0?o:[]))throw new Ta.ValidationError("genPage",t.id,[(0,Ie.issue)("/conversation","genpage-conversation-read-only","conversation is the page's recorded history and cannot be edited. Record a new turn with newTurn; revert the edit to conversation before pushing.")]);let b=Nx(t);if(b.length>0)throw new Ta.ValidationError("genPage",t.id,b);let w=[],E=r===void 0,S=E&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(cc(S)){let I=(s=(a=S.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},D=ge=>{var je;return(je=I[ge])!==null&&je!==void 0?je:Ip(S.id,ge)},O=(ge,je,de)=>{w.push({id:D(ge),name:Gi[ge].name,fileType:Gi[ge].fileType,content:je,unchanged:de})};if(S.source!==void 0){O("source",Rp(S.source),!E&&r?.source===S.source&&I.source!==void 0);let ge=uc((l=S.bag)===null||l===void 0?void 0:l.output);Px(S,r,ge)?O("output",{status:"retain"},!0):O("output",Rp(await this.compile(S,S.source,n)),!1)}else{if(I.source!==void 0)throw new Ta.ValidationError("genPage",S.id,[_x()]);if(I.output!==void 0){if(!E&&!ol((u=r?.dataSources)!==null&&u!==void 0?u:[],(c=S.dataSources)!==null&&c!==void 0?c:[]))throw new Ta.ValidationError("genPage",S.id,[(0,Ie.issue)("/dataSources","genpage-source-required","the page has no source row, so its output cannot be recompiled for new data sources; set a source to change them.")]);O("output",{status:"retain"},!0)}}let x=Cx(S),K=!E&&r!==void 0&&ol(Cx(r),x);(E||I.config!==void 0||!K)&&O("config",Rp(JSON.stringify(x)),K&&I.config!==void 0);let Re=Ex(S),qt=!E&&r!==void 0&&ol(Ex(r),Re);(I.prompt!==void 0||Object.keys(Re).length>0&&!qt)&&O("prompt",Rp(JSON.stringify(Re)),qt&&I.prompt!==void 0)}for(let I of(d=S.files)!==null&&d!==void 0?d:[]){let D=(f=r?.files)===null||f===void 0?void 0:f.find(O=>O.id===I.id);w.push({id:I.id,name:I.name,fileType:I.fileType,content:I.content,unchanged:D!==void 0&&ol(D,I)})}let P=[];if(S.newTurn){let I=S.newTurn.id,D=O=>I?{id:uie(I,O)}:{};P.push({...D("user"),sender:"user",message:S.newTurn.prompt}),S.newTurn.agentMessage&&P.push({...D("agent"),sender:"agent",message:S.newTurn.agentMessage})}let L=(p=(m=S.bag)===null||m===void 0?void 0:m.config)!==null&&p!==void 0?p:{};return{name:S.name,files:w,...P.length>0?{messages:P,messageContext:{dataSources:(h=S.dataSources)!==null&&h!==void 0?h:[],model:(g=S.model)!==null&&g!==void 0?g:"",enabledTools:Array.isArray(L.enabledTools)?L.enabledTools:[],configurableTools:Array.isArray(L.configurableTools)?L.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:Op(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,o,a,s,l;if(!cc(t)&&!t.newTurn)return t;let u=Op(t);if(delete u.newTurn,!cc(t))return u;let c={...(n=u.bag)!==null&&n!==void 0?n:{},rows:{...(o=(i=u.bag)===null||i===void 0?void 0:i.rows)!==null&&o!==void 0?o:{}}};for(let d of(a=r.files)!==null&&a!==void 0?a:[]){let f=Ix.find(p=>Gi[p].name===d.name&&Gi[p].fileType===d.fileType);if(!f||u.files.some(p=>p.id===d.id)||(c.rows[f]=d.id,d.content.status!=="available"))continue;let m=(0,kp.base64ToUtf8)(d.content.data);f==="output"?c.output={status:"available",data:d.content.data}:f==="config"?(delete c.config,delete u.dataSources,delete u.model,delete u.connectorBindings,delete u.actionBindings,Ax(u,c,(s=Pp(m))!==null&&s!==void 0?s:{})):f==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,Sx(u,c,(l=Pp(m))!==null&&l!==void 0?l:{}))}return u.bag=c,u}baselineContent(t){var r;let n={...t};return delete n.conversation,delete n.newTurn,n.files=[...(r=t.files)!==null&&r!==void 0?r:[]].sort((i,o)=>i.id<o.id?-1:i.id>o.id?1:0),n}normalize(t){let r=t.newTurn;return!(0,Ie.isJsonObject)(r)||typeof r.id=="string"&&yx.test(r.id)?t:{...t,newTurn:{...r,id:(0,Lp.newId)()}}}async compile(t,r,n){var i;let o=(i=t.dataSources)!==null&&i!==void 0?i:[],a=[],s=[];if(o.forEach((f,m)=>{var p;let h=(p=n?.resolveEntity)===null||p===void 0?void 0:p.call(n,f);h&&h.columnDetailComplete===!0?a.push(h):s.push((0,Ie.issue)(`/dataSources/${m}`,h?"genpage-data-source-incomplete":"genpage-data-source-unresolved",h?`the column metadata of data source '${f}' could not be read completely (a choice or lookup read failed, or returned options with no label), so the page cannot be compiled with its enums. Retry the push.`:`the metadata of data source '${f}' could not be read, so the page cannot be compiled with its enums. Check the table's logical name and that it exists in this environment.`))}),s.length>0)throw new Ta.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new Ta.ValidationError("genPage",t.id,[(0,Ie.issue)("/source","genpage-compiler-unavailable","no TypeScript compiler is available to compile the page")]);let l=await n.loadTypeScript(),u=a.length>0?(0,Ev.buildGenPageRuntimeTypes)(a):void 0,c=a.length>0?(0,Ev.buildGenPageLegacyEnums)(a):void 0,d=(0,Tx.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new Ta.ValidationError("genPage",t.id,d.diagnostics.map(pie));return d.code}metadataNeeds(t,r){if(t.source===void 0||!Array.isArray(t.dataSources))return[];let n=die(t,r)?{fetchRequired:!1}:{};return t.dataSources.filter(i=>typeof i=="string"&&i!=="").map(i=>({entityLogicalName:i,fieldName:"",needsColumnDetail:!0,...n}))}createDefault(t){var r,n;let i=bx(t.id),o={id:i,name:(r=t.name)!==null&&r!==void 0?r:"New page",files:((n=t.files)!==null&&n!==void 0?n:[]).map(a=>{var s,l,u;return{id:bx(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=a.fileType)!==null&&l!==void 0?l:Oo,content:(u=a.content)!==null&&u!==void 0?u:{status:"available",data:""}}})};t.source!==void 0&&(o.source=t.source),t.dataSources!==void 0&&(o.dataSources=[...t.dataSources]);for(let a of["model","firstPrompt","firstAgentMessage"])t[a]!==void 0&&(o[a]=t[a]);return t.newTurn!==void 0&&(o.newTurn={...t.newTurn}),t.connectorBindings!==void 0&&(o.connectorBindings=Op(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=Op(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:Ip(i,"source"),output:Ip(i,"output"),config:Ip(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,Lp.newId)()};if(!(0,Ie.isJsonObject)(t))return t;let r=t;return(Object.keys(r).length===0||"id"in r||"content"in r||"fileType"in r||Array.isArray(r.files))&&(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Lp.newId)()),r}validate(t){let r=[],n=t;for(let s of["source","model","firstPrompt","firstAgentMessage"])n[s]!==void 0&&typeof n[s]!="string"&&r.push((0,Ie.issue)(`/${s}`,"genpage-field-type",`${s} must be a string, got ${typeof n[s]}`));if(n.source===void 0&&Vi(Vi(n.bag).rows).source!==void 0&&r.push(_x()),r.push(...Nx(t)),n.newTurn!==void 0){let s=Vi(n.newTurn);(!(0,Ie.isJsonObject)(n.newTurn)||typeof s.prompt!="string"||s.prompt.trim()==="")&&r.push((0,Ie.issue)("/newTurn/prompt","genpage-turn-prompt","newTurn needs a non-empty prompt")),s.agentMessage!==void 0&&typeof s.agentMessage!="string"&&r.push((0,Ie.issue)("/newTurn/agentMessage","genpage-field-type","newTurn.agentMessage must be a string")),s.id!==void 0&&(typeof s.id!="string"||!yx.test(s.id))&&r.push((0,Ie.issue)("/newTurn/id","genpage-turn-id","newTurn.id is the turn's identity, which the SDK mints \u2014 remove it, or keep the GUID it minted"))}if(n.dataSources!==void 0)if(!Array.isArray(n.dataSources))r.push((0,Ie.issue)("/dataSources","genpage-data-sources-array","dataSources must be an array of table logical names"));else{let s=new Set;n.dataSources.forEach((l,u)=>{typeof l!="string"||!Ev.TABLE_LOGICAL_NAME.test(l)?r.push((0,Ie.issue)(`/dataSources/${u}`,"genpage-data-source-name",`a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(l)}'`)):s.has(l)?r.push((0,Ie.issue)(`/dataSources/${u}`,"genpage-data-source-duplicate",`data source '${l}' is listed twice`)):s.add(l)})}n.conversation!==void 0&&!Array.isArray(n.conversation)&&r.push((0,Ie.issue)("/conversation","genpage-conversation-array","conversation must be an array"));let i=n.files;if(i!==void 0&&!Array.isArray(i))return r.push((0,Ie.issue)("/files","files-must-be-array",`files must be an array, got ${typeof i}`)),r;let o=cc(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=Vi(s),d=typeof c.id=="string"?c.id.trim().toLowerCase():"";if(d==="")r.push((0,Ie.issue)(u,"file-id-required","a generative-page file needs an id"));else{let g=a.get(d);g!==void 0?r.push((0,Ie.issue)(u,"file-id-duplicate",`two files share the id '${c.id}' (also at /files/${g}); a file's id is its identity, so a duplicate makes an edit ambiguous`)):a.set(d,l)}let f=typeof c.name=="string"?c.name:"",m=f.split("/");f===""||/[\u0000-\u001F\u007F]/.test(f)||f.includes("\\")||m.some(g=>g===""||g==="."||g==="..")?r.push((0,Ie.issue)(u+"/name","file-name-invalid",`a file name must be a relative path of non-empty '/'-separated segments (no '.', '..', backslash or control character \u2014 its last segment is sent as an HTTP header); got '${f}'`)):o&&(wx(f)||vx(f,Number(c.fileType))!==void 0)&&r.push((0,Ie.issue)(u+"/name","file-name-reserved",`'${f}' would be read by the maker portal as one of the page's managed rows (its source, output, config or first prompt), which the SDK writes from source and the configuration fields; it cannot also be a file in files[]`));let p=c.content;if(p===void 0){r.push((0,Ie.issue)(u+"/content","file-content-required","content is required: omitting it is indistinguishable from an empty file, and the two have opposite effects on the next push"));return}let h=Vi(p);h.status==="available"?typeof h.data!="string"&&r.push((0,Ie.issue)(u+"/content/data","file-content-data-invalid","available content needs base64 `data`")):h.status!=="unavailable"&&r.push((0,Ie.issue)(u+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(h.status)}`))}),r}};al.GenPageAdapter=$p;function pie(e){let t=`line ${e.line}, column ${e.column}`;return e.rule==="genpage-source-syntax"?(0,Ie.issue)("/source",e.rule,`${t}: ${e.message} (TS${e.code}) \u2014 the page cannot run, so it was not pushed`):(0,Ie.issue)("/source",e.rule,`${t}: ${e.message}`)}function mie(){return{adapter:new $p,api:rie.genPageApi,publish:(e,t)=>(0,nie.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}al.genPageRegistration=mie});var $x=v(Fp=>{"use strict";Object.defineProperty(Fp,"__esModule",{value:!0});Fp.reconcileBpfSecurityRoles=void 0;var kx=Lt(),Nv=Q(),xp=ye(),dc=se(),hie="Global",Sv={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function gie(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,dc.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,i=(0,xp.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.Privileges;if(!Array.isArray(o))throw new Nv.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of business process flow table '${t}' returned no 'Privileges' array (got ${(0,kx.describeMalformedValue)(o)}), so which access it can grant is unknown.`);let a=o,s={},l=new Set;return Object.keys(Sv).forEach(u=>{let c=a.find(d=>d.PrivilegeType===Sv[u]);if(c){let d=(0,dc.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function yie(e,t){var r;let n=`/RetrieveRolePrivilegesRole(RoleId=${t})`,i=(0,xp.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.RolePrivileges;if(!Array.isArray(o))throw new Nv.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of role '${t}' returned no 'RolePrivileges' array (got ${(0,kx.describeMalformedValue)(o)}), so what it holds is unknown.`);return new Set(o.map(a=>(0,dc.normalizeGuid)(a.PrivilegeId,"PrivilegeId")))}async function bie(e,t,r){if(r.length===0)return;let n={Privileges:r.map(o=>({Depth:hie,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,xp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function vie(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,xp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function wie(e,t,r){var n,i,o;if(!r||r.length===0)return;let a=await gie(e,t.toLowerCase());for(let s of r){let l=(0,dc.normalizeGuid)(s.roleId,"roleId"),u=((n=s.access)!==null&&n!==void 0?n:[]).find(c=>!a.byAccess[c]);if(u!==void 0)throw new Nv.InvalidArgumentError(`Cannot grant '${u}' access to role '${l}' on business process flow table '${t.toLowerCase()}': its metadata lists no '${(i=Sv[u])!==null&&i!==void 0?i:u}' privilege. No security role was changed.`)}for(let s of r){let l=(0,dc.normalizeGuid)(s.roleId,"roleId"),u=new Set(((o=s.access)!==null&&o!==void 0?o:[]).map(p=>a.byAccess[p]).filter(p=>!!p)),c=await yie(e,l),d=new Set([...c].filter(p=>a.all.has(p))),f=[...u].filter(p=>!d.has(p)),m=[...d].filter(p=>!u.has(p));await bie(e,l,f);for(let p of m)await vie(e,l,p)}}Fp.reconcileBpfSecurityRoles=wie});var Kx=v(Up=>{"use strict";Object.defineProperty(Up,"__esModule",{value:!0});Up.bpfApi=void 0;var dr=Yi(),xx=Wl(),Cie=Lt(),Qe=Q(),ut=ye(),mn=se(),Eie=$x(),Aie=_m(),fc=Dm(),Sie={"Content-Type":"application/json",Accept:"application/json"},Tv={...Sie,Prefer:"return=representation"},Nie=`category eq ${dr.WorkflowCategory.BusinessProcessFlow} and type eq ${dr.WorkflowTypeCode.Definition} and businessprocesstype eq ${dr.BusinessProcessType.BusinessFlow}`,_ie="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",Tie="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",Die=["xaml","name","description","processorder"];async function _v(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,Eie.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Iv(e,t,r){let n={statecode:dr.StateCode.Activated,statuscode:dr.StatusCode.Activated},i=`/workflows(${t})`,{response:o,resent:a}=await Hx(e,i,n,r,null);try{return(0,ut.ensureSuccess)(o,e.apiUrl(i))}catch(s){throw a?zx(s):s}}var Wx=new WeakSet;function zx(e){return typeof e=="object"&&e!==null&&Wx.add(e),e}function jx(e){return typeof e=="object"&&e!==null&&Wx.has(e)}function Fx(e){return e instanceof Qe.ConnectionError&&(e.statusCode===0||ut.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}async function Hx(e,t,r,n,i){let o=n??i,a=0;try{return{response:await(0,ut.resendWhile)(ut.isConcurrencyLockRefusal,()=>{a+=1;let l=a===1?n:o,u={...Tv};return l&&(u["If-Match"]=l),e.patch(t,r,{headers:u})},o?ut.LOCK_BACKOFF_MS:[]),resent:a>1}}catch(s){throw a>1?zx(s):s}}async function Mx(e,t,r){return(0,ut.readEtag)(await Iv(e,t,r))}function Ux(e,t){return new Qe.SdkError("BPF_WRITE_NOT_ECHOED",`The ${t} of business process flow '${e}' was applied, but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next step could not be conditioned on a token this push produced and was NOT sent. `+Mp(e))}async function pc(e,t){var r;let n=`/workflows(${t})${(0,mn.odataQuery)([["$select","statecode"]])}`,i=(0,ut.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.statecode,a=Number(o);if(o==null||o===""||!Number.isFinite(a))throw new Qe.SdkError("BPF_STATE_UNREADABLE",`Reading the state of business process flow '${t}' answered HTTP ${i.status} without a usable statecode, so whether it is Active cannot be decided.`);return a}async function Dv(e,t,r,n,i=null){if((n??await pc(e,t))!==dr.StateCode.Activated)return{deactivated:!1,etag:null};let o={statecode:dr.StateCode.Draft,statuscode:dr.StatusCode.Draft},a=`/workflows(${t})`,s,l;try{({response:s,resent:l}=await Hx(e,a,o,r,i))}catch(c){return await Bx(e,t,c,jx(c))}if(ut.AMBIGUOUS_WRITE_STATUSES.has(s.status))return await Bx(e,t,new Qe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' answered HTTP ${s.status} from an intermediary, so whether it committed is unknown.`),l);let u=(0,ut.ensureSuccess)(s,e.apiUrl(a));return{deactivated:!0,etag:(0,ut.readEtag)(u)}}async function Bx(e,t,r,n){let i;try{i=await pc(e,t)}catch{i=void 0}if(i===dr.StateCode.Draft&&!n)return{deactivated:!0,etag:null,uncertainCause:r};if(i===dr.StateCode.Activated)throw r;let o=new Qe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",i===dr.StateCode.Draft?`Deactivating business process flow '${t}' waited for the platform's concurrency lock, and its last attempt ended without a definitive answer. The process now reads Draft, but whether this deactivate or another writer's change put it there is unknown \u2014 the row may even have been replaced at the same id \u2014 so nothing more was sent: no edit, no re-activation, no delete. It MAY be left DISABLED: read it before retrying. Original failure: ${r instanceof Error?r.message:String(r)}`:`Deactivating business process flow '${t}' did not complete, and its state could not be re-read \u2014 it MAY be left DISABLED and needs reconciling. Original failure: ${r instanceof Error?r.message:String(r)}`);throw(0,Qe.attachCause)(o,r),o}async function Iie(e,t){let r=(0,mn.normalizeGuid)(t,"workflowid");try{return await Iv(e,r,null),"restored"}catch{return Ov(e,r)}}async function Oie(e,t,r){let n=(0,mn.normalizeGuid)(t,"workflowid");try{return await Iv(e,n,r),"restored"}catch(i){return i instanceof Qe.SdkError&&i.code===ut.VERSION_CONFLICT_CODE?"changed":Ov(e,n)}}async function Ov(e,t){try{let r=await pc(e,t);return r===dr.StateCode.Activated?"restored":r===dr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}async function qx(e,t,r,n){return r?{outcome:await Oie(e,t,r),attempted:!0}:n?{outcome:await Ov(e,(0,mn.normalizeGuid)(t,"workflowid")),attempted:!1}:{outcome:await Iie(e,t),attempted:!0}}function Pie(e,t){let r=new Qe.SdkError(fc.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting business process flow '${e}' failed${(0,fc.failedAfterResend)(t)?" after it was re-sent":""}, and re-activating the process this delete had deactivated was refused (HTTP 412): the row at that id is no longer the version this delete deactivated \u2014 it was edited, or deleted and re-created at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read the row before deleting it again. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function Vx(e,t,r,n,i=!0){let o=`Original failure: ${n instanceof Error?n.message:String(n)}`,a="it was NOT re-activated: it waited for the platform's concurrency lock, and no write of this operation proves the row is still its own, so a re-activation could have enabled another writer's edit",s;return r==="changed"?s=new Qe.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",`Business process flow '${e}' was deactivated ${t}, and re-activating it was refused (HTTP 412): the row is no longer the version this operation last wrote \u2014 another writer changed it, or replaced it at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read it before retrying. ${o}`):r==="disabled"?s=new Qe.SdkError("BPF_LEFT_DEACTIVATED",i?`Business process flow '${e}' was deactivated ${t}, and it could NOT be reactivated \u2014 it is left DISABLED. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a} \u2014 it is left DISABLED. ${o}`):s=new Qe.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",i?`Business process flow '${e}' was deactivated ${t}, and whether it was reactivated could not be confirmed \u2014 it MAY be left DISABLED and needs checking. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a}; its state could not be read \u2014 it MAY be left DISABLED and needs checking. ${o}`),(0,Qe.attachCause)(s,n),s}async function Rie(e,t){try{return await pc(e,t),"survived"}catch(r){return r instanceof Qe.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function Lie(e,t,r){if(r)try{let{deactivated:n,etag:i}=await Dv(e,t,r),o=n?i:r;if(o)return await(0,fc.deleteWorkflowResending)(e,t,{bindingToken:o,kindName:"business process flow",resendDeadlockVictim:!0,ifMatchOnFirst:!0}),"removed"}catch{}return Rie(e,t)}function Mp(e){return`Adopt the server's copy with fetchArtifact('bpf', '${e}', { overwrite: true }) \u2014 it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push.`}function Gx(e,t){return new Qe.SdkError("BPF_CREATE_NO_TOKEN",`Created business process flow '${e}' but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next push would have nothing to condition on. ${t} It was NOT rolled back: deleting it without a token could remove an edit made since. ${Mp(e)}`)}function kie(e,t){let r=new Qe.SdkError("BPF_CREATE_NOT_ROLLED_BACK",`Creating business process flow '${e}' failed part-way, and the rollback could NOT remove it \u2014 it still EXISTS, possibly Active and half-configured. (The rollback deletes only on a token this create produced, so a row somebody has since edited is left in place on purpose; a delete the platform refused or failed leaves it too.) ${Mp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function $ie(e,t){let r=new Qe.SdkError("BPF_CREATE_ROLLBACK_OUTCOME_UNKNOWN",`Creating business process flow '${e}' failed part-way, and whether its rollback removed the process could not be confirmed \u2014 it MAY still exist, possibly Active and half-configured. ${Mp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function xie(e,t){let r=new Qe.SdkError("BPF_CREATE_REMOVED_AFTER_CONFLICT",`Creating business process flow '${e}' was interrupted: another writer changed it right after it was created, so this push's next step was refused rather than overwrite or activate their edit \u2014 and the process has since been removed. Nothing is left behind and there is nothing to fetch. If the removal was deliberate, stop here; otherwise push again to re-create it at the same id. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function Pv(e){let t={};for(let r of Die)e[r]!==void 0&&(t[r]=e[r]);return t}var Fie=["name,processorder","description,name,processorder"];function Mie(e){let{xaml:t,...r}=Pv(e);return typeof t=="string"&&Fie.includes(Object.keys(r).sort().join(","))}async function Uie(e,t,r,n){let{xaml:i,...o}=Pv(r),[,a]=await(0,xx.sendChangeSet)(e,[{method:"PATCH",path:`/workflows(${t})`,body:o,etag:n},{method:"PATCH",path:`/workflows(${t})${(0,mn.odataQuery)([["$select","workflowid"]])}`,body:{xaml:i},headers:{Prefer:"return=representation"}}],`business process flow '${t}'`);return(0,ut.readEtag)((0,xx.partResponse)(a))}Up.bpfApi={async get(e,t){let n=`/workflows(${(0,mn.normalizeGuid)(t,"id")})${(0,mn.odataQuery)([["$select",Tie]])}`,i=(0,ut.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,ut.readEtag)(i)}},async list(e,t){let r=[Nie];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,mn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,mn.odataQuery)([["$select",_ie],["$filter",r.join(" and ")]])}`;return(await(0,Cie.collectPages)(e,n,"listArtifacts('bpf')")).map(o=>{var a,s;return{type:"bpf",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){let r=t,n=(0,mn.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",o=(0,ut.ensureSuccess)(await e.post(i,r.record,{headers:Tv}),e.apiUrl(i)),a=(0,ut.readEtag)(o);if(!a)throw Gx(n,r.status==="Active"?"The process EXISTS as Draft and was NOT activated \u2014 an activation that cannot be conditioned on our own write could activate somebody else's edit.":"The process EXISTS as Draft.");let s=a;try{r.status==="Active"&&(s=await Mx(e,n,a)),await _v(e,r)}catch(l){let u=await Lie(e,n,s);throw u==="survived"?kie(n,l):u==="unknown"?$ie(n,l):l instanceof Qe.SdkError&&l.code===ut.VERSION_CONFLICT_CODE?xie(n,l):l}if(!s)throw Gx(n,"The process EXISTS and IS Active, but its activation returned no token.");return{id:n,etag:s}},async update(e,t,r,n){let i=r,o=(0,mn.normalizeGuid)(t,"id"),a=(0,ut.requireEtag)(n,"bpf",o),s=await pc(e,o);if(s===dr.StateCode.Activated&&i.status==="Active"&&e.supportsAtomicBatch&&Mie(i.record)){let m=await Uie(e,o,i.record,a);return await _v(e,i),{id:o,etag:m}}let{deactivated:l,etag:u,uncertainCause:c}=await Dv(e,o,a,s),d=u,f=!1;try{if(c!==void 0)throw c;let m=a;if(l){if(!u)throw Ux(o,"deactivation");m=u}let p=`/workflows(${o})`,h;try{h=(0,ut.ensureSuccess)(await e.patch(p,Pv(i.record),{headers:{...Tv,"If-Match":m}}),e.apiUrl(p))}catch(b){throw Fx(b)&&(d=null),b}let g=(0,ut.readEtag)(h);if(d=g,i.status==="Active"){if(!g)throw Ux(o,"definition write");try{g=await Mx(e,o,g)}catch(b){throw Fx(b)&&(d=null),b}f=!0}return await _v(e,i),{id:o,etag:g}}catch(m){if(l&&!f){let{outcome:p,attempted:h}=await qx(e,o,d,jx(m));if(p!=="restored")throw Vx(o,"to apply an edit, the edit failed",p,m,h)}throw m}},async delete(e,t){let r=(0,mn.normalizeGuid)(t,"id"),n=await(0,Aie.assertWorkflowKind)(e,r,dr.WorkflowCategory.BusinessProcessFlow),{deactivated:i,etag:o}=await Dv(e,r,null,void 0,n);try{await(0,fc.deleteWorkflowResending)(e,r,{bindingToken:i?o:n,kindName:"business process flow",deactivated:i,resendDeadlockVictim:!0})}catch(a){if(i&&!(0,fc.isWorkflowDeleteUnsettled)(a)){let{outcome:s,attempted:l}=await qx(e,r,o,!1);if(s==="changed")throw Pie(r,a);if(s!=="restored")throw Vx(r,"so it could be deleted, the delete failed",s,a,l)}throw a}}}});var PF=v(ll=>{"use strict";Object.defineProperty(ll,"__esModule",{value:!0});ll.bpfRegistration=ll.BpfAdapter=void 0;var Bp=Yi(),Bie=Kx(),Rv=so(),Da=uo(),sF=lo(),zr=en(),$r=dt(),xn=Q(),qie=100,Lv='<?xml version="1.0" encoding="utf-16"?>',Jx=1033,lF="mxswa:Workflow",Vie="mxswa:ActivityReference.Properties",Gie="mcwo:StepLabel",Wie="mcwb:Control",Yx="mcwb:Control.ControlDisplayName",uF="mcwb:Control.DataFieldName",cF="DataFieldName",Qx="ControlDisplayName",dF="Literal",Vp="x:Null",Xx="x:String",kv="x:Key",$v="DisplayName",Wp="Activities",zie="StepLabels",fF="StageId",pF="StageCategory",mF="NextStageId",hF="ProcessStepId",qp="IsProcessRequired",gF="EntityComposite",yF="StageComposite",bF="StepComposite";function mc(e){return(0,zr.isJsonObject)(e)?e:{}}function ui(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 Ia(e,t){var r;return(r=ui(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function di(e){return Ia(e,Vie)}function fr(e,t){var r;return(r=ui(e).find(n=>n.getAttribute(kv)===t))!==null&&r!==void 0?r:null}function sl(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function ci(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function vF(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function hc(e){var t;let r=(t=e.getAttribute($v))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function wF(e,t){var r;let n=(r=e.getAttribute($v))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute($v,i>=0?n.slice(0,i+2)+t:t)}function CF(e,t){let r=fr(e,zie),n=Ia(r,Gie);n&&n.setAttribute("Description",t)}function jie(e){let t=fr(e,pF);if(!t||t.tagName===Vp)return;let r=ci(t).trim();return r===""?void 0:Number(r)}function Hie(e){let t=fr(e,mF);if(!t||t.tagName===Vp)return;let r=ci(t).trim();return r===""?void 0:r}function EF(e){let t=AF(e);if(!t)return;let r=NF(t,cF,uF);return r===""?void 0:r}function xv(e,t){let r=ui(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of ui(n))r.push(i)}return null}function AF(e){let t=fr(di(e),Wp);return t?xv(t,Wie):null}function SF(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 NF(e,t,r){var n;return SF(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":Xie(e,r)}function Zx(e,t,r,n){if(SF(e,t)){e.setAttribute(t,n);return}if(Ia(e,r)){Kie(e,r,n);return}throw new xn.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function Kie(e,t,r){let n=Ia(e,t),i=n?xv(n,dF):null;if(!i)throw new xn.InvalidArgumentError(`BPF step control's <${t}> wrapper holds no <Literal> to bind a column`);i.setAttribute("Value",r)}function _F(e){return hc(e)}function zp(e){let t=Ia(e,lF),r=[];for(let n of ui(t).filter(i=>sl(i,gF))){let i=fr(di(n),Wp);for(let o of ui(i).filter(a=>sl(a,yF)))r.push({el:o,entity:_F(n)})}return r}function Fv(e){let t=fr(di(e),Wp);return ui(t).filter(r=>sl(r,bF))}function Jie(e){let t=di(e),r=ci(fr(t,qp)).trim().toLowerCase(),n=EF(e),i={id:ci(fr(t,hF)),name:hc(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function Yie(e,t){let r=di(e),n=jie(r),i=Hie(r),o={id:ci(fr(r,fF)),name:hc(e),entityLogicalName:t,steps:Fv(e).map(Jie)};return n!==void 0&&(o.category=n),i!==void 0&&(o.nextStageId=i),o}function Qie(e){return zp(e).map(({el:t,entity:r})=>Yie(t,r))}function li(e){return new xn.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 Xie(e,t){var r;let n=Ia(e,t),i=n?xv(n,dF):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function Mv(e,t){var r;let n=e.createElement(t.tagName),i=t.attributes;for(let a=0;a<i.length;a+=1)n.setAttribute(i[a].name,i[a].value);let o=t.childNodes;for(let a=0;a<o.length;a+=1){let s=o[a];s.nodeType===1?n.appendChild(Mv(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function TF(e){return fr(di(e),Wp)}function Zie(e,t,r){var n;let i=t.entityLogicalName&&t.entityLogicalName.trim()!==""?t.entityLogicalName:r,o=!((n=t.steps[0])===null||n===void 0)&&n.id&&t.steps[0].id.trim()!==""?t.steps[0].id:(0,$r.newId)(),{body:a}=jp(Uv(i,(0,$r.newId)(),t.id,o));return Mv(e,zp((0,Da.parseXmlRoot)(a,"<Activity/>"))[0].el)}function eoe(e,t){let{body:r}=jp(Uv("account",(0,$r.newId)(),(0,$r.newId)(),t.id));return Mv(e,Fv(zp((0,Da.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function DF(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function IF(e,t,r,n){let i=fr(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw li(`setting '${r}' on a stage whose xaml does not expose that slot`);return}let o=i.parentNode;if(n===void 0||n===""){if(i.tagName!==Vp&&ci(i).trim()!==""){let s=t.createElement(Vp);s.setAttribute(kv,r),o.replaceChild(s,i)}return}if(i.tagName===Xx){ci(i).trim()!==n&&vF(i,t,n);return}let a=t.createElement(Xx);a.setAttribute(kv,r),a.appendChild(t.createTextNode(n)),o.replaceChild(a,i)}function toe(e,t,r){IF(e,t,pF,r===void 0?void 0:String(r))}function roe(e,t,r){IF(e,t,mF,r)}function OF(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 eF(e){return ci(fr(di(e),fF))}function tF(e){return ci(fr(di(e),hF))}function rF(e,t,r){var n,i,o,a;let s=di(e);r.name!==hc(e)&&(wF(e,r.name),CF(s,r.name));let l=ci(fr(s,qp)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=fr(s,qp);if(!u)throw li(`setting '${qp}' on a step whose xaml does not expose that slot`);vF(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((o=EF(e))!==null&&o!==void 0?o:"")){let u=AF(e);if(!u)throw new xn.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=r.fieldName)!==null&&a!==void 0?a:"";Zx(u,cF,uF,c),c!==""&&NF(u,Qx,Yx)===""&&Zx(u,Qx,Yx,c)}}function nF(e,t,r,n){var i;let o=di(e);if(!o)throw new xn.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==hc(e)&&(wF(e,r.name),CF(o,r.name)),toe(o,t,r.category),roe(o,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw li("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw li("stage actions or conditional branching");let a=TF(e);if(!a)throw new xn.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new xn.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=Fv(e);if(OF(l,s.map(d=>d.id),tF)){l.forEach((d,f)=>rF(d,t,s[f]));return}let u=new Map(l.map(d=>[tF(d),d]));if(ui(a).some(d=>!sl(d,bF)))throw li("adding, removing or reordering steps on a stage that also contains branching or actions");let c=s.map(d=>{var f;return(f=u.get(d.id))!==null&&f!==void 0?f:eoe(t,d)});DF(a,c),c.forEach((d,f)=>rF(d,t,s[f]))}function noe(e,t,r){let n=Ia(e,lF);if(!n)throw new xn.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw li("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new xn.InvalidArgumentError("a BPF must have at least one stage");let i=zp(e),o=i.map(f=>f.el);if(OF(o,r.stages.map(f=>f.id),eF)){i.forEach(({el:f,entity:m},p)=>{let h=r.stages[p];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==m)throw li(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${m}')`);nF(f,t,h,h.nextStageId)});return}let a=ui(n).filter(f=>sl(f,gF));if(a.length!==1)throw li("adding, removing or reordering stages on a multi-table process");let s=a[0],l=_F(s),u=TF(s);if(!u)throw new xn.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(ui(u).some(f=>!sl(f,yF)))throw li("adding, removing or reordering stages on a process whose primary composite holds non-stage activities (multi-table nesting or advanced constructs)");for(let f of r.stages)if(f.entityLogicalName&&f.entityLogicalName.trim()!==""&&f.entityLogicalName!==l)throw li(`a stage on a different table ('${f.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(o.map(f=>[eF(f),f])),d=r.stages.map(f=>{var m;return(m=c.get(f.id))!==null&&m!==void 0?m:Zie(t,f,l)});DF(u,d),d.forEach((f,m)=>{let p=m<d.length-1?r.stages[m+1].id:void 0;nF(f,t,r.stages[m],p)})}function jp(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function ioe(e){var t,r,n,i,o,a;(0,sF.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let f=new DOMParser().parseFromString("<root/>","text/xml"),m={n:"Activity",a:(0,Rv.mergeAttrs)(s.a,[]),c:(0,Rv.spliceChildren)(s.c,[])};return{root:(0,Rv.rebuildRaw)(m,(0,Da.domEngine)(f),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Lv,eol:(o=(i=e.bag)===null||i===void 0?void 0:i.xamlEol)!==null&&o!==void 0?o:"lf"}}let l=e.stages[0],u=(a=l?.steps)===null||a===void 0?void 0:a[0],c=Uv(e.entityLogicalName,(0,$r.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,$r.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,$r.newId)()),{body:d}=jp(c);return{root:(0,Da.parseXmlRoot)(d,"<Activity/>"),prolog:Lv,eol:"lf"}}function ooe(e){let{root:t,prolog:r,eol:n}=ioe(e);noe(t,t.ownerDocument,e);let i=(0,Da.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r
-`)),r+i}function aoe(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Gp=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,sF.installDomShim)();let i=t,o=typeof i.xaml=="string"?i.xaml:"",a={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&&(a.uniqueName=String(i.uniquename)),i.description!=null&&i.description!==""&&(a.description=String(i.description)),i.processorder!=null&&i.processorder!==""&&(a.order=Number(i.processorder)),o.trim()!==""){let{prolog:s,body:l}=jp(o),u=(0,Da.parseXmlRoot)(l,"<Activity/>");a.stages=Qie(u),a.bag={xaml:(0,Da.projectElementBag)(u),xamlProlog:s,xamlEol:/\r\n/.test(o)?"crlf":"lf"}}return a}toApiPayload(t){var r;let n={workflowid:t.id&&t.id.trim()!==""?t.id:(0,$r.newId)(),name:t.name,uniquename:aoe(t),primaryentity:t.entityLogicalName,xaml:ooe(t),category:Bp.WorkflowCategory.BusinessProcessFlow,type:Bp.WorkflowTypeCode.Definition,businessprocesstype:Bp.BusinessProcessType.BusinessFlow,scope:Bp.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:qie};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 xn.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 o=t.stages&&t.stages.length>0?t.stages.map(oF):[oF({id:(0,$r.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,$r.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:o};return t.uniqueName&&(a.uniqueName=t.uniqueName),t.description!==void 0&&(a.description=t.description),t.order!==void 0&&(a.order=t.order),t.globalActions!==void 0&&(a.globalActions=t.globalActions),t.securityRoles!==void 0&&(a.securityRoles=t.securityRoles),a}assignMissingIds(t){let r=mc(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,$r.newId)());for(let n of["stages","steps","actions","globalActions"]){let i=r[n];Array.isArray(i)&&i.forEach(o=>this.assignMissingIds(o))}return r}validate(t){let r=[],n=t.stages;if(n!==void 0&&!Array.isArray(n))return r.push((0,zr.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,zr.issue)("/stages","too-many-stages",`a BPF allows at most 30 stages, got ${i.length}`));let o=new Set,a=new Map;i.forEach((l,u)=>{let c=`/stages/${u}`,d=mc(l),f=typeof d.id=="string"?d.id.trim():"";f===""?r.push((0,zr.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(f.toLowerCase())?r.push((0,zr.issue)(`${c}/id`,"stage-id-duplicate",`two stages share the id '${d.id}' (also at /stages/${a.get(f.toLowerCase())})`)):a.set(f.toLowerCase(),u),typeof d.entityLogicalName=="string"&&d.entityLogicalName!==""&&o.add(d.entityLogicalName);let m=Array.isArray(d.steps)?d.steps:[];m.length===0&&r.push((0,zr.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),m.length>30&&r.push((0,zr.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${m.length}`));let p=new Map;m.forEach((h,g)=>{let b=`${c}/steps/${g}`,w=typeof mc(h).id=="string"?h.id.trim():"";w===""?r.push((0,zr.issue)(`${b}/id`,"step-id-required","a step needs an id")):p.has(w.toLowerCase())?r.push((0,zr.issue)(`${b}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):p.set(w.toLowerCase(),g)}),d.branch&&!iF(i,d.branch.nextStageId)&&r.push((0,zr.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${d.branch.nextStageId}' does not match any stage id`)),typeof d.nextStageId=="string"&&d.nextStageId!==""&&!iF(i,d.nextStageId)&&r.push((0,zr.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${d.nextStageId}' does not match any stage id`))}),o.size>5&&r.push((0,zr.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=soe(i);return s>=0&&r.push((0,zr.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};ll.BpfAdapter=Gp;function soe(e){let t=new Map(e.map(r=>[mc(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 iF(e,t){return e.some(r=>mc(r).id===t)}function oF(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(aF):[aF({id:(0,$r.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,$r.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 aF(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,$r.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 Uv(e,t,r,n){return`${Lv}<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="${Jx}" /></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="${Jx}" /></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 loe(){return{adapter:new Gp,api:Bie.bpfApi,languageSensitive:!0}}ll.bpfRegistration=loe});var RF=v(Hp=>{"use strict";Object.defineProperty(Hp,"__esModule",{value:!0});Hp.buildRegistrations=void 0;var uoe=SL(),coe=WL(),doe=_1(),foe=W1(),poe=h$(),moe=k$(),hoe=Q$(),goe=Lx(),yoe=PF();function boe(e){let t=new Map;return t.set("form",(0,uoe.formRegistration)(e)),t.set("view",(0,coe.viewRegistration)()),t.set("businessRule",(0,doe.businessRuleRegistration)()),t.set("app",(0,foe.appRegistration)(e)),t.set("command",(0,poe.commandRegistration)()),t.set("chart",(0,moe.chartRegistration)()),t.set("dashboard",(0,hoe.dashboardRegistration)(e)),t.set("genPage",(0,goe.genPageRegistration)()),t.set("bpf",(0,yoe.bpfRegistration)()),t}Hp.buildRegistrations=boe});var jF=v(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE=Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE=Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE=Te.removeRowSummary=Te.configureRowSummary=Te.buildGptDynamicPrompt=Te.setAppAiFeatures=Te.getAiReadiness=Te.saveSettingValue=Te.retrieveSetting=Te.AI_GATE=void 0;var Wi=Lt(),hn=ye(),qe=se(),LF=dt(),Ve=Q();Te.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var UF={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},voe=new Set(Object.entries(Te.AI_GATE).filter(([e,t])=>UF[e]===t).map(([e])=>e)),woe={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function Bv(e){return woe[e]}var Kp=1e6;function Coe(e,t){let r=Bv(t),n=()=>{throw new Ve.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${Kp} (e.g. 0, 1, 2); got '${String(e)}'.`)},i=o=>r?o?r.enabled:r.disabled:o?"1":"0";if(typeof e=="boolean")return i(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>Kp?n():String(e);if(typeof e=="string"){let o=e.trim(),a=o.toLowerCase();if(a==="true")return i(!0);if(a==="false")return i(!1);if(/^[0-9]+$/.test(o)){let s=o.replace(/^0+(?=[0-9])/,"");return s.length>String(Kp).length||Number(s)>Kp?n():s}}return n()}function Eoe(e,t){let r=Bv(t);return r?e===r.enabled:e!=="0"}async function Aoe(e,t){var r,n;let i=`/appmodules${(0,qe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,o=await e.get(i);if(o.status<200||o.status>=300)return;let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ve.ConnectionError(e.apiUrl(i),o.status,`the app lookup for '${t}' returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,Wi.describeMalformedValue)(a)}`);return(n=a[0])===null||n===void 0?void 0:n.appmoduleid}async function Soe(e,t){var r,n;let i=`/appmodules${(0,qe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,o;try{o=await e.get(i)}catch(l){throw new Ve.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(o.status<200||o.status>=300)throw new Ve.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned HTTP ${o.status}. Retry, or omit appModuleId to verify by name.`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ve.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a malformed body.`);if(a.length===0)return;let s=(n=a[0])===null||n===void 0?void 0:n.appmoduleid;if(!s)throw new Ve.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var kF=new WeakMap;async function Noe(e,t){var r,n;let i=kF.get(e);if(i||(i=new Map,kF.set(e,i)),i.has(t))return i.get(t);let o=`/settingdefinitions${(0,qe.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,a=await e.get(o);if(a.status<200||a.status>=300)return;let s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))throw new Ve.ConnectionError(e.apiUrl(o),a.status,`the setting definition lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,Wi.describeMalformedValue)(s)}`);let l=(n=s[0])===null||n===void 0?void 0:n.settingdefinitionid;return l&&i.set(t,l),l}async function _oe(e,t,r){var n,i;let o=await Noe(e,r);if(!t||!o)return;let a=`/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()${(0,qe.odataQuery)([["$select","value,componentstate"],["$filter",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${o}`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)return;let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new Ve.ConnectionError(e.apiUrl(a),s.status,`the app-scope override read returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,Wi.describeMalformedValue)(l)}`);let u=l;if(u.length===0)return{exists:!1};let c=(i=u.find(d=>d?.componentstate===1))!==null&&i!==void 0?i:u[0];return{exists:!0,value:c.value,pendingPublish:c.componentstate===1}}var Toe=4,Doe=500,$F=20,xF=3e4;function Ioe(e){if(e===void 0)return Toe;if(!Number.isFinite(e))throw new Ve.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${$F}; got ${e}.`);return Math.min($F,Math.max(1,Math.floor(e)))}function Ooe(e){if(e===void 0)return Doe;if(!Number.isFinite(e))throw new Ve.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${xF}; got ${e}.`);return Math.min(xF,Math.max(0,Math.floor(e)))}async function Poe(e,t,r,n,i,o,a){let s,l,u,c=!1;for(let d=0;d<o;d+=1){d>0&&await new Promise(m=>setTimeout(m,a*d));let f;try{let m=await t();m?(f=await _oe(e,m,n),f===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){f=void 0,u=m.message}c=f!==void 0,l=f?.exists;try{s=(await Jp(e,n,{appUniqueName:r})).value}catch{}if(f?.exists&&f.value===i)return{result:"proven",effectiveValue:f.value,appOverrideExists:!0,...f.pendingPublish?{pendingPublish:!0}:{}}}return c?{result:"absent",effectiveValue:s,appOverrideExists:l}:{result:"unverifiable",effectiveValue:s,appOverrideExists:void 0,reason:u}}function BF(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?Bv(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function Jp(e,t,r={}){var n;let i=[`SettingName='${(0,qe.odataPathLiteral)(t)}'`];r.appUniqueName&&i.push(`AppUniqueName='${(0,qe.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${i.join(",")})`,a=(0,hn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.SettingDetail;if(s===null||typeof s!="object"||Array.isArray(s)||!("Value"in s))throw new Ve.ConnectionError(e.apiUrl(o),a.status,`RetrieveSetting for '${t}' returned a malformed answer \u2014 expected a SettingDetail with a Value`);let{Value:l,DataType:u}=s;return{value:l,dataType:u}}Te.retrieveSetting=Jp;async function qF(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,hn.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Te.saveSettingValue=qF;async function Roe(e,t={}){let r={};for(let[n,i]of Object.entries(Te.AI_GATE)){let{value:o,dataType:a}=await Jp(e,i,t);r[n]={enabled:BF(o,a,n),setting:i,value:o}}return r}Te.getAiReadiness=Roe;async function Loe(e,t,r,n={}){var i;if(!t||!t.trim())throw new Ve.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let o=Ioe(n.verifyAttempts),a=Ooe(n.verifyDelayMs),s=[];for(let[p,h]of Object.entries(r)){if(h===void 0)continue;let g=UF[p];g&&s.push({feature:p,setting:g,requestedValue:Coe(h,p)})}let l=[],u=n.appModuleId?(0,qe.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(u){let p=await Soe(e,t);if(p&&(0,qe.normalizeGuid)(p,"appModuleId")!==u)throw new Ve.InvalidArgumentError(`setAppAiFeatures: appModuleId '${u}' does not belong to app '${t}' (which resolves to '${p}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let c,d=async()=>u||(c||(c=await Aoe(e,t)),c),f=new Map,m=async p=>{if(voe.has(p))return;let h=Te.AI_GATE[p];if(h){if(!f.has(h))try{let{value:g,dataType:b}=await Jp(e,h);f.set(h,{enabled:BF(g,b,p),setting:h,value:g})}catch{f.set(h,void 0)}return f.get(h)}};for(let{feature:p,setting:h,requestedValue:g}of s)try{await qF(e,h,g,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let b=await Poe(e,d,t,h,g,o,a),w={feature:p,setting:h,requestedValue:g,effectiveValue:b.effectiveValue,appOverrideExists:b.appOverrideExists};if(b.result==="proven")l.push({...w,status:"applied",...b.pendingPublish?{pendingPublish:!0}:{}});else if(b.result==="absent"){let E=Eoe(g,p)?await m(p):void 0;E&&!E.enabled?l.push({...w,status:"skipped",reason:`the write was issued and no app-scope override holding '${g}' was observed for '${h}' after ${o} attempt(s); the org readiness gate '${E.setting}' reads '${E.value}', so an environment admin must enable it before this app can turn the feature on`}):l.push({...w,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${g}' was observed for '${h}' after ${o} attempt(s) \u2014 ${b.effectiveValue===void 0?"the value in effect for this app could not be read":`it reads '${b.effectiveValue}' for this app`} (Dataverse can accept an app-scope write without storing it)`})}else l.push({...w,status:"unverified",reason:`the write was issued but could not be confirmed: ${(i=b.reason)!==null&&i!==void 0?i:"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(b){l.push({feature:p,setting:h,requestedValue:g,status:"failed",reason:b.message})}return{applied:l.filter(p=>p.status==="applied").map(p=>p.feature),skipped:l.filter(p=>p.status==="skipped").map(p=>p.feature),notPersisted:l.filter(p=>p.status==="notPersisted").map(p=>p.feature),unverified:l.filter(p=>p.status==="unverified").map(p=>p.feature),failed:l.filter(p=>p.status==="failed").map(p=>p.feature),outcomes:l}}Te.setAppAiFeatures=Loe;var VF="GptPowerPrompt",koe='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function GF(e){var t,r,n,i;let o=e.entityLogicalName,a=[{type:"literal",text:e.instruction.replace(/\s*$/,"")+" "}];return e.columns.forEach((s,l)=>{a.push({type:"data",id:`${o}.${s.logical}`,text:s.display}),l<e.columns.length-1&&a.push({type:"literal",text:", "})}),{version:"GptDynamicPrompt-2",prompt:a,definitions:{inputs:[{id:"RecordId",text:"RecordId",type:"text"},{id:"LanguageCode",text:"LanguageCode",type:"text"}],formulas:[],data:[{id:o,displayName:o,type:"dataverseTable",filters:[{filterType:"equal",attribute:e.primaryKey,valueType:"inputVariable",value:"RecordId"}]}],output:{formats:[(t=e.outputFormat)!==null&&t!==void 0?t:"text"]}},modelParameters:{modelType:"default",gptParameters:{temperature:(r=e.temperature)!==null&&r!==void 0?r:0}},settings:{recordRetrievalLimit:(n=e.recordRetrievalLimit)!==null&&n!==void 0?n:30,shouldPreserveRecordLinks:null,runtime:null,enableReasoning:(i=e.enableReasoning)!==null&&i!==void 0?i:!0},code:"",signature:""}}Te.buildGptDynamicPrompt=GF;async function $oe(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,qe.odataPathLiteral)(t)}')${(0,qe.odataQuery)([["$select","MetadataId"]])}`,i=(0,hn.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.MetadataId;if(typeof o!="string"||o==="")throw new Ve.ConnectionError(e.apiUrl(n),i.status,`the table metadata read for '${t}' returned a malformed answer \u2014 expected a MetadataId but got ${o===""?"an empty string":(0,Wi.describeMalformedValue)(o)}`);return o}function qv(e,t,r,n){if(e.length===0)return;let i=e[0];if(typeof i!="object"||i===null||Array.isArray(i))throw new Ve.ConnectionError(t,r,`${n} returned a malformed row \u2014 expected an object but got ${Array.isArray(i)?"an array":(0,Wi.describeMalformedValue)(i)}`);return i}async function WF(e){var t;let r=`/msdyn_aitemplates${(0,qe.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${VF}'`],["$top",1]])}`,n=(0,hn.ensureSuccess)(await e.get(r),e.apiUrl(r)),i=(t=n.body)===null||t===void 0?void 0:t.value;if(!Array.isArray(i))throw new Ve.ConnectionError(e.apiUrl(r),n.status,`the row-summary template lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,Wi.describeMalformedValue)(i)}`);let o=qv(i,e.apiUrl(r),n.status,"the row-summary template lookup");if(!o)return;let a=o.msdyn_aitemplateid;if(typeof a=="string"&&a!=="")try{return(0,qe.normalizeGuid)(a,"msdyn_aitemplateid")}catch{}throw new Ve.ConnectionError(e.apiUrl(r),n.status,`the row-summary template lookup returned a malformed row \u2014 expected a GUID 'msdyn_aitemplateid' but got ${a===""?"an empty string":typeof a=="string"?"a string that is not a GUID":(0,Wi.describeMalformedValue)(a)}`)}function zF(e){return`${e} row summary`}async function xoe(e,t,r){var n;let i=`/msdyn_aimodels(${t})${(0,qe.odataQuery)([["$select","msdyn_name,_msdyn_templateid_value"]])}`,o=await e.get(i);if(o.status===404)return!1;let a=(n=(0,hn.ensureSuccess)(o,e.apiUrl(i)).body)!==null&&n!==void 0?n:{},s=await WF(e);return typeof a.msdyn_name=="string"&&a.msdyn_name.toLowerCase()===zF(r).toLowerCase()&&typeof a._msdyn_templateid_value=="string"&&s!==void 0&&a._msdyn_templateid_value.toLowerCase()===s.toLowerCase()}async function Foe(e,t,r={}){var n;let i=`ais_RowSummary_${t.entityLogicalName}`,o=`/aiskillconfigs${(0,qe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(i)}'`],["$top",1]])}`,a=(0,hn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new Ve.ConnectionError(e.apiUrl(o),a.status,`the existing row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,Wi.describeMalformedValue)(s)}`);let l=qv(s,e.apiUrl(o),a.status,"the existing row-summary skill lookup");if(l)return{modelId:l._aimodel_value,aiSkillConfigId:l.aiskillconfigid};let u=await $oe(e,t.entityLogicalName),c=await WF(e);if(c===void 0)throw new Ve.SdkError(Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE,`Cannot configure the row summary of '${t.entityLogicalName}': this org has no AI template '${VF}' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written.`);let d=(0,LF.newId)(),f=(0,LF.newId)(),m=JSON.stringify(GF(t)),p={ModelId:d,RunConfigurationId:f,ModelName:zF(t.entityLogicalName),TemplateId:c,CustomConfiguration:m,Source:koe,RunConfiguration:""};(0,hn.ensureSuccess)(await e.post("/AIModelPublish",p),e.apiUrl("/AIModelPublish"));try{let h={uniquename:i,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${u})`,"[email protected]":`/msdyn_aimodels(${d})`,aiskill:"RowSummary"},g=(0,hn.ensureSuccess)(await e.post("/aiskillconfigs",h),e.apiUrl("/aiskillconfigs")),b=(0,hn.requireCreatedId)(g,"aiskillconfigid","row-summary skill");return{modelId:d,aiSkillConfigId:b}}catch(h){try{await e.delete(`/msdyn_aimodels(${d})`)}catch{}throw h}}Te.configureRowSummary=Foe;async function Moe(e,t){var r;let n=`ais_RowSummary_${t.entityLogicalName}`,i=`/aiskillconfigs${(0,qe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(n)}'`],["$top",1]])}`,o=(0,hn.ensureSuccess)(await e.get(i),e.apiUrl(i)),a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ve.ConnectionError(e.apiUrl(i),o.status,`the row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,Wi.describeMalformedValue)(a)}`);let s=qv(a,e.apiUrl(i),o.status,"the row-summary skill lookup");if(!s)return{removed:!1};let l=(0,qe.normalizeGuid)(s.aiskillconfigid,"aiskillconfigid"),u=s._aimodel_value?(0,qe.normalizeGuid)(s._aimodel_value,"_aimodel_value"):void 0,c=u?await xoe(e,u,t.entityLogicalName):!1,d=t.entityLogicalName,f=`/aiskillconfigs(${l})`,m=await FF(e,f,`${f}${(0,qe.odataQuery)([["$select","aiskillconfigid"]])}`);if(m.kind==="failed")throw m.stillThere===void 0&&u&&c?(0,Ve.attachCause)(new Ve.SdkError(Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE,`Removing the row summary of '${d}' could not be confirmed: deleting its skill row failed (${MF(m.failure)}) and the row could not be read back. If it is gone, its AI model '${u}' is left behind, unreferenced. Retry removeRowSummary: while the skill row exists it removes both; once it is gone, delete that model.`),m.failure):m.failure;if(u&&c){let p=`/msdyn_aimodels(${u})`,h=await FF(e,p,`${p}${(0,qe.odataQuery)([["$select","msdyn_aimodelid"]])}`,Boe);if(h.kind==="failed")throw(0,Ve.attachCause)(new Ve.SdkError(Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE,`The row summary of '${d}' was removed, but its AI model '${u}' ${h.stillThere?"was not deleted":"could not be confirmed deleted"} (${MF(h.failure)}). The model is no longer used by the row summary; delete it before configuring a row summary for '${d}' again, which needs its name.`),h.failure)}return{removed:!0}}Te.removeRowSummary=Moe;Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE="ROW_SUMMARY_MODEL_NOT_DELETED";Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE="ROW_SUMMARY_REMOVAL_UNCONFIRMED";Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE="ROW_SUMMARY_TEMPLATE_NOT_FOUND";var Uoe="0x8004f01f";function Boe(e){var t,r;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return e.status===400&&typeof n=="string"&&n.toLowerCase()===Uoe}function qoe(e){if(e.status!==400&&e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/chosen as the deadlock victim|\bSql Number:\s*1205\b/i.test(t)}async function FF(e,t,r,n=()=>!1){let i;try{let o=await(0,hn.resendWhile)(qoe,()=>e.delete(t));if(o.status>=200&&o.status<300||o.status===404)return{kind:"gone"};if(n(o))return{kind:"kept"};try{(0,hn.ensureSuccess)(o,e.apiUrl(t))}catch(a){i=a}}catch(o){i=o}try{let o=await e.get(r);return o.status===404?{kind:"gone"}:{kind:"failed",failure:i,stillThere:o.status>=200&&o.status<300?!0:void 0}}catch{return{kind:"failed",failure:i,stillThere:void 0}}}function MF(e){return e instanceof Error?e.message:String(e)}});var JF=v(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});ul.findArtifact=ul.resolveArtifact=void 0;var Bt=se(),zi=Td(),Voe=Ud(),Goe=Lt(),Woe=ye(),HF=Q();async function KF(e,t,r){let n="/uxagentprojects"+(0,Bt.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,Bt.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,Goe.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function zoe(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p;switch(t){case"app":{let h=(0,Voe.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,Bt.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),b=(i=(0,Woe.ensureSuccess)(await e.get(h),e.apiUrl(h)).body)===null||i===void 0?void 0:i.value,w=b&&b[0];return w?[{id:String(w.appmoduleid),name:String(w.name),appModuleIdUnique:String(w.appmoduleidunique)}]:[]}case"dashboard":return(await(0,zi.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,Bt.odataLiteral)((o=r.name)!==null&&o!==void 0?o:"")}' and type eq 0`,top:10})||[]).map(g=>({id:String(g.formid),name:String(g.name)}));case"command":{if(!r.entity)return[];let h=await(0,zi.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,Bt.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?[{id:r.entity,entity:r.entity}]:[]}case"form":return(await(0,zi.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,Bt.odataLiteral)((a=r.name)!==null&&a!==void 0?a:"")}' and objecttypecode eq '${(0,Bt.odataLiteral)((s=r.entity)!==null&&s!==void 0?s:"")}'`,top:10})||[]).map(g=>({id:String(g.formid),name:String(g.name)}));case"chart":return(await(0,zi.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,Bt.odataLiteral)((l=r.name)!==null&&l!==void 0?l:"")}' and primaryentitytypecode eq '${(0,Bt.odataLiteral)((u=r.entity)!==null&&u!==void 0?u:"")}'`,top:10})||[]).map(g=>({id:String(g.savedqueryvisualizationid),name:String(g.name)}));case"view":return(await(0,zi.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,Bt.odataLiteral)((c=r.name)!==null&&c!==void 0?c:"")}' and returnedtypecode eq '${(0,Bt.odataLiteral)((d=r.entity)!==null&&d!==void 0?d:"")}'`,top:10})||[]).map(g=>({id:String(g.savedqueryid),name:String(g.name)}));case"webResource":return(await(0,zi.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,Bt.odataLiteral)((f=r.name)!==null&&f!==void 0?f:"")}'`,top:1})||[]).map(g=>({id:String(g.webresourceid),name:String(g.name)}));case"solution":return(await(0,zi.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,Bt.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(g=>({id:String(g.solutionid),name:String(g.uniquename)}));case"genPage":return KF(e,(p=r.name)!==null&&p!==void 0?p:"");default:return[]}}ul.resolveArtifact=zoe;async function joe(e,t,r){var n,i,o,a,s,l;let u=(0,Bt.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),c=(0,Bt.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){if(!r.entity)return null;let h=await(0,zi.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,Bt.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?r.entity:null}if(t==="genPage"){let h=await KF(e,(o=r.name)!==null&&o!==void 0?o:"",2);if(h.length>1)throw new HF.AmbiguousArtifactError(t,(a=r.name)!==null&&a!==void 0?a:"",h.length);return h.length===1?h[0].id:null}let d=Hoe(t,u,c,r),f=t!=="app",m=await(0,zi.queryRecords)(e,d.set,{select:[d.idField],filter:d.filter,top:f?2:1});if(f&&m&&m.length>1)throw new HF.AmbiguousArtifactError(t,(l=(s=r.name)!==null&&s!==void 0?s:r.uniqueName)!==null&&l!==void 0?l:"",m.length);let p=m&&m[0]&&m[0][d.idField];return p!=null?String(p):null}ul.findArtifact=joe;function Hoe(e,t,r,n){var i;switch(e){case"view":return{set:"savedquery",idField:"savedqueryid",filter:`returnedtypecode eq '${r}' and name eq '${t}'`};case"chart":return{set:"savedqueryvisualization",idField:"savedqueryvisualizationid",filter:`primaryentitytypecode eq '${r}' and name eq '${t}'`};case"form":return{set:"systemform",idField:"formid",filter:`objecttypecode eq '${r}' and name eq '${t}'`};case"app":return{set:"appmodule",idField:"appmoduleid",filter:`uniquename eq '${(0,Bt.odataLiteral)((i=n.uniqueName)!==null&&i!==void 0?i:"")}'`};case"dashboard":return{set:"systemform",idField:"formid",filter:`name eq '${t}' and type eq 0`};default:throw new Error(`Unsupported findable kind: ${e}`)}}});var QF=v(Qp=>{"use strict";Object.defineProperty(Qp,"__esModule",{value:!0});Qp.seedRecordGraph=void 0;var YF=Td(),Koe=cd(),Yp=se(),Joe=Q();async function Yoe(e,t,r={}){var n,i,o,a,s;let l=(n=r.createdIds)!==null&&n!==void 0?n:{},u=(i=r.entitySetFor)!==null&&i!==void 0?i:(f=>(0,Koe.resolveEntitySetName)(e,f)),c={},d=f=>{var m;return(m=c[f])!==null&&m!==void 0?m:l[f]};for(let f of t){let m=f.entityLogical.toLowerCase(),p=(o=f.matchOn)===null||o===void 0?void 0:o.toLowerCase(),h=[];for(let L of f.records){let I={...L.body};for(let D of(a=L.binds)!==null&&a!==void 0?a:[]){let O=D.parentEntity.toLowerCase(),x=(s=d(O))===null||s===void 0?void 0:s[D.parentIndex];if(!x)throw new Joe.InvalidArgumentError(`Cannot resolve bind '${D.navProperty}' on a '${m}' record: parent '${D.parentEntity}'[${D.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let K=(0,Yp.assertODataName)(await u(O),`entity set for parent '${D.parentEntity}'`),Re=(0,Yp.normalizeGuid)(x,`parent id for bind '${D.navProperty}'`);I[`${D.navProperty}@odata.bind`]=`/${K}(${Re})`}h.push(I)}let g=p?h.map(L=>{let I=L[p];return I!=null&&I!==""?String(I):null}):h.map(()=>null),b=new Map;if(p){let L=(0,Yp.assertODataName)(p,"RecordGraph matchOn key"),I=[...new Set(g.filter(D=>D!==null))];if(I.length){let D=I.map(x=>`${L} eq '${(0,Yp.odataLiteral)(x)}'`).join(" or "),O=await(0,YF.queryRecords)(e,m,{select:[L,`${m}id`],filter:D,top:5e3});for(let x of O??[]){let K=x[L];K!=null&&b.set(String(K).toLowerCase(),String(x[`${m}id`]))}}}let w=[],E=new Map,S=h.map((L,I)=>{let D=g[I];if(D&&b.has(D.toLowerCase()))return null;if(D){let O=D.toLowerCase(),x=E.get(O);if(x!==void 0)return x;let K=w.push(L)-1;return E.set(O,K),K}return w.push(L)-1}),P=w.length?await(0,YF.createRecordsBulk)(e,m,w):[];c[m]=h.map((L,I)=>{let D=g[I];return D&&b.has(D.toLowerCase())?b.get(D.toLowerCase()):P[S[I]]})}return{createdIds:c}}Qp.seedRecordGraph=Yoe});var sM=v(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.getEntityPrivileges=Zt.addEntityPrivilegesToRole=Zt.deleteSecurityRole=Zt.createPersonaRole=Zt.createSecurityRole=Zt.SDK_ROLE_MARKER=void 0;var Fn=ye(),Pt=se(),jr=Q(),Xp={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},Gv={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},XF={user:1,businessUnit:2,parentChild:3,organization:4},Vv={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};Zt.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function Qoe(e){return Object.prototype.hasOwnProperty.call(Xp,e)?Xp[e]:void 0}function Xoe(e){return Object.prototype.hasOwnProperty.call(Gv,e)}var ZF=new WeakMap,eM=new WeakMap;async function nM(e,t){var r,n;(0,Pt.assertODataName)(t,"entity logical name");let i=ZF.get(e);i||(i=new Map,ZF.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,Pt.odataPathLiteral)(t)}')${(0,Pt.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,Fn.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[];if(l.length===0)throw new jr.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function Zoe(e){var t,r,n;let i=eM.get(e);if(i)return i;let o=`/businessunits${(0,Pt.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,Fn.ensureSuccess)(await e.get(o),e.apiUrl(o)).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 jr.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,Pt.normalizeGuid)(l,"businessUnitId");return eM.set(e,u),u}async function iM(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new jr.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let o=(r=i.scope)!==null&&r!==void 0?r:"user";if(!Xoe(o))throw new jr.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await nM(e,i.entity);for(let s of i.access){let l=Qoe(s);if(!l)throw new jr.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=a.find(p=>p.PrivilegeType===l);if(!u)throw new jr.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=Vv[o];if(u[c]===!1)throw new jr.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,Pt.normalizeGuid)(u.PrivilegeId,"PrivilegeId"),f=n.get(d);if(!f){n.set(d,{privilegeName:u.Name,privilegeType:l,scope:o,entities:new Set([i.entity])});continue}if(f.scope===o){f.entities.add(i.entity);continue}if(!(f.entities.size===1&&f.entities.has(i.entity))){let p=[...f.entities].sort().join(", ");throw new jr.InvalidArgumentError(`Entities '${p}' 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.`)}f.scope=XF[o]>XF[f.scope]?o:f.scope}}return[...n.entries()].map(([i,o])=>({entity:[...o.entities].sort().join(", "),privilegeId:i,privilegeName:o.privilegeName,privilegeType:o.privilegeType,scope:o.scope}))}async function eae(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(a=>({Depth:Gv[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,Fn.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function tM(e,t,r,n,i){var o,a;let s=`/${t}(${r})/${n}${(0,Pt.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((a=(o=(0,Fn.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||o===void 0?void 0:o.value)!==null&&a!==void 0?a:[]).length>0}async function tae(e,t,r){var n,i;let o=[],a=[],s={"@odata.id":e.apiUrl(`/roles(${t})`)};for(let l of(n=r?.teams)!==null&&n!==void 0?n:[]){let u=(0,Pt.normalizeGuid)(l,"teamId");if(!await tM(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,Fn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}for(let l of(i=r?.users)!==null&&i!==void 0?i:[]){let u=(0,Pt.normalizeGuid)(l,"userId");if(!await tM(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,Fn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}return{teams:o,users:a}}async function rM(e,t,r){var n,i;let o=`/roles${(0,Pt.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Pt.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,Fn.ensureSuccess)(await e.get(o),e.apiUrl(o)).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 f;return d.ismanaged!==!0&&((f=d.description)!==null&&f!==void 0?f:"")===Zt.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new jr.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 jr.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,Pt.normalizeGuid)(c,"roleId"):void 0}function rae(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,Pt.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,Pt.normalizeGuid)(n,"userId"))}}function oM(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function aM(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new jr.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,Pt.normalizeGuid)(t.businessUnitId,"businessUnitId"):await Zoe(e),a=await iM(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=rae(t.assignTo),l=await rM(e,i,o),u=l!==void 0;if(!l){let d="/roles",f={name:i,description:Zt.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let m=(0,Fn.ensureSuccess)(await e.post(d,f),e.apiUrl(d));l=(0,Pt.normalizeGuid)((0,Fn.requireCreatedId)(m,"roleid","role"),"roleId")}catch(m){let p;try{p=await rM(e,i,o)}catch{p=void 0}if(!p)throw m;l=p}}await eae(e,l,a,u);let c=await tae(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:oM(a),assignedTeams:c.teams,assignedUsers:c.users}}Zt.createSecurityRole=aM;async function nae(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new jr.InvalidArgumentError("createPersonaRole: a non-empty persona name is required.");let o=[...t.jobs.flatMap(a=>{var s;return(s=a.privileges)!==null&&s!==void 0?s:[]}),...(n=t.additionalPrivileges)!==null&&n!==void 0?n:[]];return aM(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}Zt.createPersonaRole=nae;async function iae(e,t){let n=`/roles(${(0,Pt.normalizeGuid)(t,"roleId")})`;(0,Fn.ensureSuccess)(await e.delete(n),e.apiUrl(n))}Zt.deleteSecurityRole=iae;async function oae(e,t,r){let n=(0,Pt.normalizeGuid)(t,"roleId");if(r.length===0)throw new jr.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await iM(e,r),o={Privileges:i.map(s=>({Depth:Gv[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,Fn.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),oM(i)}Zt.addEntityPrivilegesToRole=oae;var aae=new Map(Object.keys(Xp).map(e=>[Xp[e],e]));async function sae(e,t){return(await nM(e,t)).map(n=>{let i=Object.keys(Vv).filter(a=>n[Vv[a]]!==!1),o=aae.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...o?{access:o}:{},scopes:i}})}Zt.getEntityPrivileges=sae});var SM=v(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.createMakerSdk=mr.MakerSdk=mr.PUSH_NOT_ATTEMPTED_CODE=mr.ALREADY_EXISTS_CODE=void 0;var lM=Im(),uM=Jr(),Z=Q(),gn=$a(),lae=DC(),wM=$C(),cl=qC(),uae=Pm(),cae=lE(),dl=dE(),dae=NE(),fae=PE(),pae=lA(),cM=iS(),Rt=cd(),Wv=vg(),dM=hN(),Zp=Xl(),ji=Td(),em=AN(),fl=Od(),mae=Rd(),er=wg(),hae=Tg(),gae=$g(),fM=Dg(),yae=RF(),tm=dt(),bae=Ho(),fi=Pb(),yn=xm(),zv=gv(),vae=3e5,pr=ye(),Oa=se(),pl=jF(),pM=JF(),wae=QF(),Cae=Hy(),gc=sM(),CM=Symbol("cds-maker-sdk.committedWrite");function Eae(e){return typeof e=="object"&&e!==null&&(e[CM]=!0),e}function Aae(e){return typeof e=="object"&&e!==null&&e[CM]===!0}var Sae={fileConcurrency:1},jv="SOLUTION_COMPONENT_UNCLASSIFIED",Nae=2,_ae=4,Tae="This table is in the solution with ALL its subcomponents. Those are members the solution does not list one by one, so fetchSolution did not enumerate or fetch them: none of its forms, views, charts or dashboards were fetched here. To fetch them, read the table's logical name from its metadata (EntityDefinitions(<componentId>), $select=LogicalName), list each kind with fetchArtifactList \u2014 'form' with formTypes Main, QuickView, QuickCreate and Card; 'view'; 'chart'; 'dashboard' \u2014 passing { entityLogicalName }, and fetch each listed id with fetchArtifact: listing returns ids and names only.";function mM(e){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"unsupported",...e.includesAllSubcomponents?{detail:Tae}:{}}}function hM(e,t){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"failed",error:Po(t)}}function gM(e,t,r){let n=r;return{type:e,id:t.objectId,name:typeof n.name=="string"?n.name:t.objectId,entityLogicalName:typeof n.entityLogicalName=="string"?n.entityLogicalName:void 0,lastFetched:(0,pr.nowIso)(),isDirty:!1}}var Dae=new Set(["entity","appmodule","dashboard","uxagentproject"]);function Iae(e){var t;let r={entity:[],appmodule:[],dashboard:[],uxagentproject:[]},n=new Set,i=(s,l)=>{let u=`${s}\0${l.toLowerCase()}`;n.has(u)||(n.add(u),r[s].push(l))};for(let{scope:s}of e)if(s?.envelope==="entity")s.entityLogicalName&&i("entity",s.entityLogicalName);else if(s&&s.envelope!=="webresource")for(let l of(t=s.targetIds)!==null&&t!==void 0?t:[])i(s.envelope,l);let o=(s,l,u)=>u.length>0?`<${s}>${u.map(c=>`<${l}>${(0,Oa.xmlText)(c)}</${l}>`).join("")}</${s}>`:"",a=o("entities","entity",r.entity)+o("appmodules","appmodule",r.appmodule)+o("dashboards","dashboard",r.dashboard)+o("uxagentprojects","uxagentproject",r.uxagentproject);return a?`<importexportxml>${a}</importexportxml>`:void 0}function Oae(e){let t=e.workspaceStorage;if(t==null)throw new Error("createMakerSdk requires a workspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'; a host with no filesystem implements WorkspaceStorage directly.");return new wM.WorkspaceManager(Rae,e.instanceUrl,(0,uae.assertStorageContract)(t))}mr.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var Pae="this build answers a replayed create with HTTP 404, and the unpublished read of an existing row is not authoritative after another writer's save on it, so the row cannot be proven to be what this create wrote";mr.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var Rae="<injected workspaceStorage>",rm=class{constructor(t){var r,n;if(this.artifactLocks=new Map,this.observedGenerations=new Map,this.baselineObserved=new Map,this.generationHighWater=new Map,this.entityMetadataLoads=new Map,this.entityMetadataLoadEpochs=new WeakMap,this.schemaWrites=new Map,this.undroppedMetadata=new Set,this.metadataPublications=new Set,t.createRecovery!==void 0&&t.createRecovery!=="adoptExact")throw new Z.InvalidArgumentError(`createRecovery must be 'adoptExact' or omitted (got '${String(t.createRecovery)}').`);this.createRecovery=t.createRecovery,this.readConcurrency=(0,zv.resolveReadConcurrency)(t.readConcurrency),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:bae.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:vae,this.compiler={load:(0,hae.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=Oae(t),this.versions=new cl.VersionManager(this.workspace),this.dataverse=new cae.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName,this.readConcurrency),this.connectivity=new pae.ConnectivityRouter(this.dataverse,t.instanceUrl,{powerAppsServiceClient:t.powerAppsServiceClient,powerPlatformApiClient:t.powerPlatformApiClient,connectorRuntimeClient:t.connectorRuntimeClient}),this.registrations=(0,yae.buildRegistrations)(this.languageCode)}async initWorkspace(){await this.workspace.init()}async getManifest(){return this.workspace.getManifest()}async cleanWorkspace(){await this.workspace.clean()}withArtifactLock(t,r,n){var i;let o=this.artifactKey(t,r),s=((i=this.artifactLocks.get(o))!==null&&i!==void 0?i:Promise.resolve()).then(n,n),l=s.then(()=>{},()=>{});return this.artifactLocks.set(o,l),l.then(()=>{this.artifactLocks.get(o)===l&&this.artifactLocks.delete(o)}),s}async fetchArtifact(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.fetchArtifactUnlocked(t,r,n);return await this.acknowledgeRefresh(t,r),i})}async fetchArtifactUnlocked(t,r,n){let i=this.requireRegistration(t,"fetchArtifact"),o=await i.api.get(this.dataverse,r);return this.applyFetchedArtifactUnlocked(t,r,i,o,n)}async applyFetchedArtifactUnlocked(t,r,n,i,o){var a,s,l;let{raw:u,etag:c,memberEtags:d,siblingEtags:f}=i,m=n.adapter.fromApiResponse(u);if(!o?.overwrite&&await this.versions.isDirty(t,r)){let h=(s=(a=await this.versions.getMeta(t,r))===null||a===void 0?void 0:a.etag)!==null&&s!==void 0?s:null;if(h&&c&&h!==c)throw new Z.LocalEditsWouldBeLostError(t,r,h,c);let g=await this.workspace.readArtifact(t,r);if(g){let b=await this.versions.getMeta(t,r);if(b&&!b.etag&&c){if(!(0,yn.deepEqual)(b.snapshot,m))throw new Z.LocalEditsWouldBeLostError(t,r,h,c);await this.versions.storeMeta(t,r,{...b,etag:c,fetchedAt:(0,pr.nowIso)()},b)}return(0,fi.cloneJson)(g)}}await this.workspace.writeArtifact(t,r,m);let p=await this.versions.getMeta(t,r);return await this.versions.storeMeta(t,r,{etag:c,languageCode:this.languageCode,projectionVersion:cl.PROJECTION_VERSION,fetchedAt:(0,pr.nowIso)(),snapshot:(0,fi.cloneJson)(m),...d?{memberEtags:d}:{},...f?{siblingEtags:f}:{},...p?.refreshGeneration?{refreshGeneration:p.refreshGeneration,observedGeneration:(l=p.observedGeneration)!==null&&l!==void 0?l:0}:{}},p),(0,fi.cloneJson)(m)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){await this.workspace.ensureReady();let r=await(0,er.fetchSolutionComponents)(this.dataverse,t),n=[],i=[];if(this.readConcurrency>1)await this.fetchComponentsOverlapped(r,n,i);else for(let o of r)try{let a=await this.resolveComponentType(o);if(!a){i.push(mM(o));continue}let s=await this.fetchArtifact(a,o.objectId);n.push(gM(a,o,s))}catch(a){i.push(hM(o,a))}return await this.workspace.updateManifest({lastSyncAt:(0,pr.nowIso)()}),{summaries:n,skipped:i}}async fetchComponentsOverlapped(t,r,n){await(0,zv.readEveryInOrder)(t,this.readConcurrency,i=>this.beginComponentRead(i),async(i,o)=>{try{if(!i.ok)throw i.error;let a=i.value;if(a.kind==="unsupported"){n.push(mM(o));return}let s=await this.applyFetchedArtifactUnlocked(a.type,o.objectId,a.reg,a.fetched);await this.acknowledgeRefresh(a.type,o.objectId),r.push(gM(a.type,o,s))}catch(a){n.push(hM(o,a))}})}async beginComponentRead(t){let r=await this.resolveComponentType(t);return r?this.lockedRead(r,t.objectId,async()=>{let n=this.requireRegistration(r,"fetchArtifact"),i=await n.api.get(this.dataverse,t.objectId,Sae);return{kind:"artifact",type:r,reg:n,fetched:i}}):(0,zv.plainRead)(async()=>({kind:"unsupported"}))}lockedRead(t,r,n){let i,o=new Promise(u=>{i=u}),a,s=new Promise(u=>{a=u}),l=this.withArtifactLock(t,r,async()=>{try{i({ok:!0,value:await n()})}catch(c){i({ok:!1,error:c})}let u=await s;await u?.()});return{outcome:o,finish:u=>(a(u),l),discard:async()=>{a(void 0),await l}}}async fetchEntityMetadata(t){let r=t.toLowerCase(),n=this.schemaEpoch(r),i=await(0,dl.fetchEntityMetadataFromApi)(this.dataverse,t);if(this.schemaEpoch(r)!==n)return i;let o=this.workspace.writeEntityMetadata(t,i),a={key:r,settled:o.then(()=>{},()=>{})};this.metadataPublications.add(a);try{await o}finally{this.metadataPublications.delete(a)}return this.schemaEpoch(r)===n&&this.undroppedMetadata.delete(r),i}schemaEpoch(t){var r,n;return`${(r=this.schemaWrites.get("*"))!==null&&r!==void 0?r:0}:${(n=this.schemaWrites.get(t.toLowerCase()))!==null&&n!==void 0?n:0}`}async schemaWrite(t,r){try{return await r()}finally{await this.forgetEntityMetadata(t)}}async forgetEntityMetadata(t){let r=i=>{var o;this.schemaWrites.set(i,((o=this.schemaWrites.get(i))!==null&&o!==void 0?o:0)+1)};if(t===void 0){r("*"),await this.publicationsSettled(void 0),await this.dropCachedMetadata(void 0);return}let n=[...new Set(t.filter(i=>typeof i=="string"&&i!=="").map(i=>i.toLowerCase()))];n.forEach(r),await this.publicationsSettled(n);for(let i of n)await this.dropCachedMetadata(i)}async publicationsSettled(t){let r=t===void 0?void 0:new Set(t);await Promise.all([...this.metadataPublications].filter(n=>r===void 0||r.has(n.key)).map(n=>n.settled))}async dropCachedMetadata(t){try{await this.workspace.dropEntityMetadata(t)}catch(r){r instanceof Z.WorkspaceNotInitializedError||r instanceof Z.WorkspaceOrgMismatchError||this.undroppedMetadata.add(t??"*");return}t===void 0?this.undroppedMetadata.clear():this.undroppedMetadata.delete(t)}async readCachedEntityMetadata(t){let r=t.toLowerCase();return this.undroppedMetadata.has("*")&&await this.dropCachedMetadata(void 0),this.undroppedMetadata.has(r)&&await this.dropCachedMetadata(r),this.undroppedMetadata.has("*")||this.undroppedMetadata.has(r)?null:this.workspace.readEntityMetadata(t)}loadMissedEntityMetadata(t){let r=this.schemaEpoch(t),n=this.entityMetadataLoads.get(t);if(n&&this.entityMetadataLoadEpochs.get(n)===r)return n;let i=this.fetchEntityMetadata(t).then(()=>{});this.entityMetadataLoads.set(t,i),this.entityMetadataLoadEpochs.set(i,r);let o=()=>{this.entityMetadataLoads.get(t)===i&&this.entityMetadataLoads.delete(t)};return i.then(o,o),i}generateGenPageRuntimeTypes(t,r){return(0,dae.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,dl.findTables)(this.dataverse,t,r)}getEnvironmentLanguages(){return(0,fae.getEnvironmentLanguages)(this.dataverse)}listConnections(){return this.connectivity.listConnections()}listConnectorOperations(t){return this.connectivity.listConnectorOperations(t)}getConnectorOperationSchema(t,r){return this.connectivity.getConnectorOperationSchema(t,r)}listConnectorTables(t,r,n){return this.connectivity.listConnectorTables(t,r,n)}getConnectorTableSchema(t,r,n,i){return this.connectivity.getConnectorTableSchema(t,r,n,i)}findColumns(t,r,n){return(0,dl.findColumns)(this.dataverse,t,r,n)}createTable(t){return this.schemaWrite([t.schemaName],()=>(0,Rt.createTable)(this.dataverse,t))}createColumn(t,r){return this.schemaWrite([t],()=>(0,Rt.createColumn)(this.dataverse,t,r))}createColumns(t,r){return this.schemaWrite([t],()=>(0,Rt.createColumns)(this.dataverse,t,r))}updateColumn(t,r,n){return this.schemaWrite([t],()=>(0,Rt.updateColumn)(this.dataverse,t,r,n))}deleteColumn(t,r){return this.schemaWrite([t],()=>(0,Rt.deleteColumn)(this.dataverse,t,r))}setFormSecurityRoles(t,r){return(0,Wv.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,Wv.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,Rt.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,Rt.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return this.schemaWrite([t,"account","contact"],()=>(0,Rt.createCustomerColumn)(this.dataverse,t,r))}insertStatusValue(t,r){return this.schemaWrite([t],()=>(0,Rt.insertStatusValue)(this.dataverse,t,r))}updateTable(t,r){return this.schemaWrite([t],()=>(0,Rt.updateTable)(this.dataverse,t,r))}async setEntityIcon(t,r){if(await this.schemaWrite([t],()=>(0,Rt.updateTable)(this.dataverse,t,{iconVectorName:r.vector,iconSmallName:r.small,iconMediumName:r.medium,iconLargeName:r.large})),r.publish!==!1){let n=`<importexportxml><entities><entity>${(0,Oa.xmlText)(t)}</entity></entities></importexportxml>`;(0,pr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,Rt.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,Rt.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){let r=t.type==="ManyToMany"?[t.entity1,t.entity2]:[t.referencedEntity,t.referencingEntity];return this.schemaWrite(r,()=>(0,Rt.createRelationship)(this.dataverse,t))}deleteRelationship(t){return this.schemaWrite(void 0,()=>(0,Rt.deleteRelationship)(this.dataverse,t))}createGlobalOptionSet(t){return(0,Rt.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,Rt.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return this.schemaWrite(void 0,()=>(0,Rt.deleteTable)(this.dataverse,t))}createSecurityRole(t){return(0,gc.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,gc.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,gc.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,gc.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,gc.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,ji.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,ji.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,ji.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,ji.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,ji.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,ji.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,ji.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,wae.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,pM.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,pM.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){await this.workspace.ensureReady();let n=await(0,gae.deleteAppCascade)(this.dataverse,t,r),i=(0,Oa.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,ji.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,ji.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,em.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,em.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,em.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,em.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,fl.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,fl.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new Z.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:mae.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,fl.setAppSetting)(this.dataverse,t,fl.HEADER_AND_NAVIGATION_REFRESH,r?fl.APP_SETTING_ON:fl.APP_SETTING_OFF)}getSolution(t){return(0,er.getSolution)(this.dataverse,t)}createPublisher(t){return(0,er.createPublisher)(this.dataverse,t)}createSolution(t){return(0,er.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,er.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,er.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,er.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,er.exportSolution)(this.dataverse,t)}importSolution(t){return this.schemaWrite(void 0,()=>(0,er.importSolution)(this.dataverse,t))}getDeploymentSettingsTemplate(t){return(0,er.getDeploymentSettingsTemplate)(this.dataverse,t)}deleteSolution(t){return this.schemaWrite(void 0,()=>(0,er.deleteSolution)(this.dataverse,t))}async getArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let{artifact:n,meta:i}=await this.readWhole(t,r);return await this.acknowledgeRefresh(t,r,i),n})}async getArtifactUnlocked(t,r){return this.readRaw(t,r)}async readWhole(t,r){let{meta:n}=await this.revalidate(t,r);return{artifact:await this.readLocal(t,r),meta:n}}async acknowledgeRefresh(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=n===void 0?await this.versions.getMeta(t,r):n;this.baselineObserved.has(s)||this.baselineObserved.set(s,(i=l?.observedGeneration)!==null&&i!==void 0?i:0);let u=(o=l?.refreshGeneration)!==null&&o!==void 0?o:0;this.raiseGenerationHighWater(s,u),l&&u!==((a=l.observedGeneration)!==null&&a!==void 0?a:0)&&await this.versions.storeMeta(t,r,{...l,observedGeneration:u},l),this.observedGenerations.set(s,u)}raiseGenerationHighWater(t,r){var n;r>((n=this.generationHighWater.get(t))!==null&&n!==void 0?n:0)&&this.generationHighWater.set(t,r)}async observedAtInvocation(t,r,n){var i,o;if(n!==void 0)return n;let a=this.baselineObserved.get(this.artifactKey(t,r));return a!==void 0?a:(o=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.observedGeneration)!==null&&o!==void 0?o:0}artifactKey(t,r){return`${t}\0${(0,wM.canonicalArtifactId)(r)}`}nextRefreshGeneration(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=Math.max((i=n?.refreshGeneration)!==null&&i!==void 0?i:0,(o=n?.observedGeneration)!==null&&o!==void 0?o:0,(a=this.generationHighWater.get(s))!==null&&a!==void 0?a:0)+1;return this.raiseGenerationHighWater(s,l),l}async readRaw(t,r){return await this.revalidateIfStale(t,r),this.readLocal(t,r)}async readForMutation(t,r,n,i){var o,a;let s=await this.observedAtInvocation(t,r,i);if(((a=(o=await this.versions.getMeta(t,r))===null||o===void 0?void 0:o.refreshGeneration)!==null&&a!==void 0?a:0)>s)throw new Z.StaleArtifactError(t,r,n,"pushed");if(await this.revalidateIfStale(t,r)==="refreshed-changed")throw new Z.StaleArtifactError(t,r,n);return this.readLocal(t,r)}async readLocal(t,r){let n=await this.workspace.readArtifact(t,r);if(!n)throw new Z.ArtifactNotFoundError(t,r);return n}async revalidateIfStale(t,r){return(await this.revalidate(t,r)).outcome}async revalidate(t,r){let n=await this.versions.getMeta(t,r);if(!n)return{outcome:"skipped",meta:null};let i=n.fetchedAt?Date.parse(n.fetchedAt):NaN,o=Date.now()-i;if(!Number.isNaN(i)&&this.cacheStalenessMs>0&&o<=this.cacheStalenessMs)return{outcome:"fresh",meta:n};if(await this.versions.isDirty(t,r,n))return{outcome:"skipped",meta:n};let a=await this.workspace.readArtifact(t,r);await this.fetchArtifactUnlocked(t,r);let s=await this.workspace.readArtifact(t,r);return{outcome:(0,yn.deepEqual)(a,s)?"refreshed-unchanged":"refreshed-changed"}}async queryTree(t,r,n){return this.withArtifactLock(t,r,async()=>{let{artifact:i,meta:o}=await this.readWhole(t,r),a=gn.JsonPointer.resolve(i,n);if(a===void 0)throw new Z.PathNotFoundError(t,r,n);return n===""&&await this.acknowledgeRefresh(t,r,o),a})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,lae.findElements)(await this.getArtifactUnlocked(t,r),n))}async withDirtyFlags(t){let r=[];for(let n of t)r.push({...n,isDirty:await this.versions.isDirty(n.type,n.id)});return r}async listArtifacts(t,r){return this.withDirtyFlags(await this.workspace.listArtifacts(t,r))}async getEntityMetadata(t){let r=await this.readCachedEntityMetadata(t);if(!r)throw new Z.ArtifactNotFoundError("entityMetadata",t);return r}async getFieldMetadata(t,r){let i=(await this.getEntityMetadata(t)).attributes.find(o=>o.logicalName===r);if(!i)throw new Z.PathNotFoundError("entityMetadata",t,r);return i}async updateElement(t,r,n,i){let o=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let a=await this.readForMutation(t,r,n,o),s=gn.JsonPointer.resolve(a,n);if(s===void 0)throw new Z.PathNotFoundError(t,r,n);let l=Hi(s)&&Hi(i)?{...s,...i}:i;return gn.JsonPointer.set(a,n,(0,fi.cloneJson)(l)),this.assertStructurallyValid(t,r,a,n),await this.workspace.writeArtifact(t,r,a),this.getArtifactUnlocked(t,r)})}async addElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let s=await this.readForMutation(t,r,n,a),l=gn.JsonPointer.resolve(s,n);if(l===void 0)throw new Z.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!Hi(l)||!Hi(i))throw new Z.ValidationError(t,r,n,"parent must be an array, or an object with an object of properties to add");if(o?.position!==void 0)throw new Z.ValidationError(t,r,n,"position is not supported for an object parent");let d={};for(let f of Object.keys(i)){if(f==="id")throw new Z.ValidationError(t,r,n,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let m=(0,fi.cloneJson)(i[f]),p=(0,tm.isValueMapKey)(f)||(0,tm.pointerTouchesValueMap)(n);d[f]=p?m:Array.isArray(m)?m.map(h=>Hi(h)?this.assignMissingIds(t,h):h):Hi(m)?this.assignMissingIds(t,m):m}for(let f of Object.keys(d))gn.JsonPointer.set(s,gn.JsonPointer.append(n,f),d[f]);return this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)}let u=(0,tm.pointerTouchesValueMap)(n)?(0,fi.cloneJson)(i):this.assignMissingIds(t,(0,fi.cloneJson)(i)),c=xae(l,o?.position);return l.splice(c,0,u),this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)})}async moveElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{var s;let l=await this.readForMutation(t,r,n,a),u=gn.JsonPointer.resolve(l,n);if(u===void 0)throw new Z.PathNotFoundError(t,r,n);let c=gn.JsonPointer.resolve(l,i);if(c===void 0)throw new Z.PathNotFoundError(t,r,i);if(!Array.isArray(c))throw new Z.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new Z.ValidationError(t,r,i,"cannot move an element into its own subtree");gn.JsonPointer.remove(l,n);let d=(s=o?.index)!==null&&s!==void 0?s:c.length;c.splice(Math.max(0,Math.min(d,c.length)),0,u),vM(c);let f=gn.JsonPointer.resolve(l,bM(n));return Array.isArray(f)&&f!==c&&vM(f),this.assertStructurallyValid(t,r,l,i),await this.workspace.writeArtifact(t,r,l),this.getArtifactUnlocked(t,r)})}async removeElement(t,r,n){let i=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let o=await this.readForMutation(t,r,n,i);if(gn.JsonPointer.resolve(o,n)===void 0)throw new Z.PathNotFoundError(t,r,n);return gn.JsonPointer.remove(o,n),this.assertStructurallyValid(t,r,o,bM(n)),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)})}assertStructurallyValid(t,r,n,i){var o,a,s;let l=this.registrations.get(t),u=(s=(a=l==null?void 0:(o=l.adapter).validate)===null||a===void 0?void 0:a.call(o,n,i))!==null&&s!==void 0?s:[];if(u.length>0)throw new Z.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,pl.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,pl.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,pl.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,pl.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,pl.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,pl.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,Cae.findDefaultViews)(this.dataverse,t,{excludeViewIds:n.excludeViewIds}),o=n.publish===!1,a=[],s=[],l=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,uM.boundEntityPublishScope)({entityLogicalName:t}),artifacts:a.map(c=>({type:"view",id:c}))}]:[]}),u;try{for(let c of i){await this.fetchArtifact("view",c.id),await this.updateElement("view",c.id,"/columns",r),u=c.id;let d=await this.pushArtifact("view",c.id);u=void 0,s.push(d),d.saved&&a.push(c.id)}}catch(c){throw u&&Aae(c)&&a.push(u),o?(0,Z.withPartialEnrichment)(c,l()):c}if(o)return l();if(a.length){let c=await this.publishArtifact("view",a[0]);if(c.publish.kind==="failed")throw new Z.SdkError("ENRICH_DEFAULT_VIEWS_PUBLISH_FAILED",`enrichDefaultViews: ${a.length} view(s) on '${t}' were saved but the publish FAILED, so none of them is live (${c.publish.error.message}). Re-publish the entity to make them visible; the saves themselves are unaffected.`)}return{updated:a}}async createArtifact(t,r){let n=this.requireRegistration(t,"createArtifact"),i=n.adapter.assignMissingIds(n.adapter.createDefault(r)),o=i.id;if(!o)throw new Z.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,o,async()=>(await this.workspace.writeArtifact(t,o,i),(0,fi.cloneJson)(i)))}async deleteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.workspace.deleteArtifact(t,r)})}async deleteRemoteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let n=this.requireRegistration(t,"deleteRemoteArtifact");await this.workspace.ensureReady(),await n.api.delete(this.dataverse,r),await this.workspace.readArtifact(t,r)&&await this.workspace.deleteArtifact(t,r)})}async publishArtifact(t,r,n){let{result:i,siblings:o}=await this.withArtifactLock(t,r,()=>this.publishArtifactUnlocked(t,r,n));for(let a of o)await this.withArtifactLock(a.type,a.id,()=>this.adoptBracket(a));return i}async publishArtifacts(t,r){var n,i;let o=new Map;for(let p of t){let h=this.artifactKey(p.type,p.id);o.has(h)||o.set(h,{type:p.type,id:p.id})}let a=[];for(let[p,h]of o)a.push(await this.withArtifactLock(h.type,h.id,()=>this.preparePublish(p,h.type,h.id)));let s=new Set(o.keys()),l=[],u=new Set;for(let p of a){let h=((n=p.scope)===null||n===void 0?void 0:n.envelope)==="entity"?(i=p.scope.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;p.scope&&h&&!u.has(h)&&(u.add(h),l.push(p.scope))}let c=await this.captureSiblings(l,s),d=Iae(a),f;if(d)try{await(0,uM.publishXml)(this.dataverse,d)}catch(p){f=Po(p)}let m=new Map;for(let p of a)m.set(p.key,await this.withArtifactLock(p.type,p.id,()=>this.settlePublish(p,f,r)));for(let p of c)await this.withArtifactLock(p.type,p.id,()=>this.adoptBracket(p));return t.map(p=>({...m.get(this.artifactKey(p.type,p.id))}))}async preparePublish(t,r,n){var i;let o=await this.readRaw(r,n),a=this.registrations.get(r);if(!a?.publish)return{key:t,type:r,id:n,artifact:o,notApplicable:!0};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,n,o);if(!s||!Dae.has(s.envelope))throw new Z.InvalidArgumentError(`publishArtifacts: ${r} '${n}' publishes through ${s?`a '${s.envelope}'`:"no declared"} scope, which one PublishXml envelope cannot carry. Publish it with publishArtifact.`);let l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,r,n):void 0;return{key:t,type:r,id:n,artifact:o,reg:a,scope:s,...l?{own:l}:{}}}async settlePublish(t,r,n){let{type:i,id:o}=t;if(t.notApplicable||!t.reg)return{type:i,id:o,shipped:!1,publish:{kind:"notApplicable"}};let a=t.scope?{publishScope:t.scope}:{};if(t.reg.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(t.reg,i,o),t.own&&await this.adoptBracket(t.own),r)return{type:i,id:o,shipped:!1,publish:{kind:"failed",error:r},...a};if(!n?.verify)return{type:i,id:o,shipped:!1,publish:{kind:"submitted"},...a};let s=await this.workspace.readArtifact(i,o).catch(()=>null);if(!s||!(0,yn.deepEqual)(s,t.artifact))return{type:i,id:o,shipped:!1,publish:{kind:"unverifiable",reason:`the local ${i} was ${s?"edited":"deleted"} while the publish was in flight, so what shipped cannot be told from what is local now; verify it with publishArtifact`},...a};let l=await this.verifyPublished(i,o,t.artifact);return{type:i,id:o,shipped:l.kind==="verified",publish:l,...a}}async publishArtifactUnlocked(t,r,n){var i;let o=await this.readRaw(t,r),a=this.registrations.get(t);if(!a?.publish)return{result:{type:t,id:r,shipped:!1,publish:{kind:"notApplicable"}},siblings:[]};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,r,o),l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,t,r):void 0,u=s?await this.captureSiblings([s],new Set([this.artifactKey(t,r)])):[];try{await a.publish(this.dataverse,r,o)}catch(d){return{result:{type:t,id:r,shipped:!1,publish:{kind:"failed",error:Po(d)},...s?{publishScope:s}:{}},siblings:[]}}if(a.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(a,t,r),l&&await this.adoptBracket(l),!n?.verify)return{result:{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}},siblings:u};let c=await this.verifyPublished(t,r,o);return{result:{type:t,id:r,shipped:c.kind==="verified",publish:c,...s?{publishScope:s}:{}},siblings:u}}async captureBracket(t,r,n){try{let i=await this.versions.getMeta(r,n),o=i?.etag;if(!(0,pr.isVersionToken)(o)||!t.api.readContentThenToken)return;let{raw:a,etag:s,siblingEtags:l}=await t.api.readContentThenToken(this.dataverse,n),u=i?.siblingEtags;return s!==o||!kae(u,l)?void 0:{type:r,id:n,reg:t,heldEtag:o,...u?{heldSiblings:u}:{},content:this.bracketContent(t,a)}}catch{return}}async captureSiblings(t,r){var n,i,o;let a=new Map;for(let u of t){let c=u.envelope==="entity"?(n=u.entityLogicalName)===null||n===void 0?void 0:n.toLowerCase():void 0;c&&!a.has(c)&&a.set(c,[])}if(a.size===0)return[];let s;try{s=await this.workspace.listArtifacts()}catch{return[]}for(let u of s){let c=this.registrations.get(u.type);if(!(r.has(this.artifactKey(u.type,u.id))||c?.rebaselineAfterPublish!=="bracket"||!c.publishScope))try{let d=await this.workspace.readArtifact(u.type,u.id),f=d?c.publishScope(u.id,d):void 0,m=f?.envelope==="entity"?(i=f.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;m!==void 0&&((o=a.get(m))===null||o===void 0||o.push(u))}catch{continue}}let l=[];for(let u of a.values())for(let c of u){let d=this.registrations.get(c.type),f=d?await this.captureBracket(d,c.type,c.id):void 0;f&&l.push(f)}return l}async adoptBracket(t){var r;try{let n=await this.versions.getMeta(t.type,t.id);if(!n||n.etag!==t.heldEtag||!(0,yn.deepEqual)((r=n.siblingEtags)!==null&&r!==void 0?r:void 0,t.heldSiblings))return;let{raw:i,etag:o,siblingEtags:a}=await t.reg.api.get(this.dataverse,t.id);if(!(0,pr.isVersionToken)(o)||!EM(a,t.heldSiblings)||!AM(a)||!(o!==t.heldEtag||!(0,yn.deepEqual)(a??void 0,t.heldSiblings))||!(0,yn.deepEqual)(this.bracketContent(t.reg,i),t.content))return;await this.versions.storeMeta(t.type,t.id,{...n,etag:o,...t.heldSiblings?{siblingEtags:{...a}}:{},fetchedAt:(0,pr.nowIso)()},n)}catch{}}bracketContent(t,r){var n,i,o;let a=t.adapter.fromApiResponse(r);return(o=(i=(n=t.adapter).baselineContent)===null||i===void 0?void 0:i.call(n,a))!==null&&o!==void 0?o:a}adoptReadBack(t,r){try{return{artifact:t.adapter.fromApiResponse(r)}}catch(n){return{warning:`The write was saved, but the record read back after it could not be read into the local copy (${Po(n).message}). The SDK holds no version for it now, so the next push is refused: re-fetch before editing again.`}}}adoptedAsSent(t,r,n,i){try{let o={...n,...i},a=t.adapter.fromApiResponse(t.adapter.completeAsStored?t.adapter.completeAsStored(o,n):o);return(0,yn.deepEqual)(r,a)}catch{return!1}}async rebaselineAfterPublish(t,r,n){try{let i=await this.versions.getMeta(r,n);if(!i)return;let{raw:o,etag:a,memberEtags:s,siblingEtags:l}=t.api.getForRebaseline?await t.api.getForRebaseline(this.dataverse,n):await t.api.get(this.dataverse,n),u=t.adapter.fromApiResponse(o),c=d=>{var f,m,p;return(p=(m=(f=t.adapter).baselineContent)===null||m===void 0?void 0:m.call(f,d))!==null&&p!==void 0?p:d};if(!a||!(0,yn.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:a,fetchedAt:(0,pr.nowIso)(),...s?{memberEtags:s}:{},...l?{siblingEtags:l}:{}},i)}catch{}}async verifyPublished(t,r,n){var i;if(t!=="app"){let o=this.registrations.get(t);return o?.api.getPublished?this.verifyPublishedContent(o,t,r,n):{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`}}try{let o=`/appmodules(${(0,Oa.normalizeGuid)(r,"id")})${(0,Oa.odataQuery)([["$select","appmoduleid,name,description"]])}`,a=await this.dataverse.get(o);if(a.status>=200&&a.status<300){let s=(i=a.body)!==null&&i!==void 0?i:{},l=n;if(!l)return{kind:"unverifiable",reason:"there is no local copy of the app to compare the published projection with"};let u=["name","description"].filter(d=>l[d]!==void 0);if(u.length===0)return{kind:"unverifiable",reason:"the local copy of the app holds neither a name nor a description to compare the published projection with, and its presence alone proves nothing for a re-publish"};let c=u.filter(d=>{var f,m;return((f=l[d])!==null&&f!==void 0?f:"")!==((m=s[d])!==null&&m!==void 0?m:"")});return c.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${c.join(", ")} still differ). PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}:{kind:"verified"}}return{kind:"unverifiable",reason:`the published projection answered HTTP ${a.status}`}}catch(o){return{kind:"unverifiable",reason:Po(o).message}}}async verifyPublishedContent(t,r,n,i){var o,a,s;try{let l=f=>{var m,p,h;return(h=(p=(m=t.adapter).baselineContent)===null||p===void 0?void 0:p.call(m,f))!==null&&h!==void 0?h:f},u=l(i),c=(o=await this.versions.getMeta(r,n))===null||o===void 0?void 0:o.snapshot;if(c===void 0||!(0,yn.deepEqual)(u,l(c)))return{kind:"unverifiable",reason:`the local ${r} holds edits that were never pushed, so no publish could have shipped them \u2014 push, then publish again`};let d=await((s=(a=t.api).getPublished)===null||s===void 0?void 0:s.call(a,this.dataverse,n));return d?(0,yn.deepEqual)(u,l(t.adapter.fromApiResponse(d.raw)))?{kind:"verified"}:{kind:"unverifiable",reason:"the published projection does not show what was pushed. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists"}:{kind:"unverifiable",reason:`the ${r} is not in the published projection yet. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}}catch(l){return{kind:"unverifiable",reason:Po(l).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async prepareArtifactUnlocked(t,r,n){var i,o;let a=this.requireRegistration(t,"pushArtifact"),s=await this.workspace.readArtifactWithText(t,r);if(!s)throw new Z.ArtifactNotFoundError(t,r);let l=s.artifact,u=s.text,c=(o=(i=a.adapter).normalize)===null||o===void 0?void 0:o.call(i,l);c&&c!==l&&(await this.workspace.writeArtifact(t,r,c),l=c,u=void 0);let d=await this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,d,a),this.assertProjectionMatches(t,r,d);let f=await this.buildMetadataContext(a.adapter,l,d?.snapshot),m=await a.adapter.toApiPayload(l,d?.snapshot,f);return await this.assertSemanticallyComplete(a,t,r,l,d===null,d?.everActivated,n),{type:t,id:r,reg:a,json:l,...u!==void 0?{storedText:u}:{},meta:d,payload:m}}async assertSemanticallyComplete(t,r,n,i,o,a,s){let l=t.adapter.issuesBlockingPush;if(!l)return;let u=i.entityLogicalName,d=(u?await this.columnsForCheck(t,u,i,s):[]).map(m=>({logicalName:m.logicalName,displayName:m.displayName,attributeType:m.attributeType,isCustomAttribute:m.isCustomAttribute,...m.maxLength!==void 0?{maxLength:m.maxLength}:{},...m.options?{options:m.options.map(p=>({value:p.value,label:p.label}))}:{},...m.targets?{targets:m.targets}:{}})),f=l.call(t.adapter,i,d,{isCreate:o,everActivated:a});if(f.length>0)throw new Z.ValidationError(r,n,f)}columnsForCheck(t,r,n,i){var o,a,s;let l=(s=(a=(o=t.adapter).columnsCheckedAtPush)===null||a===void 0?void 0:a.call(o,n))!==null&&s!==void 0?s:[],u=async()=>{let f=await this.readCachedEntityMetadata(r);if(f)return f.attributes;try{return await(0,dl.readCheckColumns)(this.dataverse,r,l)}catch{return[]}};if(!i)return u();let c=[r,...[...new Set(l)].sort()].join("\0"),d=i.get(c);return d||(d=u(),i.set(c,d)),d}async pushArtifactUnlocked(t,r,n){return this.executePrepared(await this.prepareArtifactUnlocked(t,r,n))}async executePrepared(t){var r,n,i,o,a,s,l,u,c;let{type:d,id:f,reg:m,json:p,meta:h,payload:g}=t,b=!1;try{let w;if(h)w=await m.api.update(this.dataverse,f,g,h.etag,h.memberEtags,h.siblingEtags);else{let O=await this.createWithMintedId(m,d,f,g,p);if("adopted"in O)return await this.persistAdoption(d,f,p,O.adopted);w=O.written}b=!0;let E=f;h||(w.serverIdentity&&m.adapter.applyServerIdentity&&m.adapter.applyServerIdentity(p,w.serverIdentity),w.id&&w.id!==f&&(p.id=w.id,await this.workspace.deleteArtifact(d,f),E=w.id));let S=h&&w.readBack!==void 0?this.adoptReadBack(m,w.readBack):void 0,P=S?.artifact?{artifact:S.artifact,baseline:S.artifact}:m.adapter.committed?m.adapter.committed(p,g,{intentPending:w.intentPending===!0}):{artifact:p,baseline:p};await this.workspace.writeArtifact(d,E,P.artifact,h&&E===f?t.storedText:void 0);let L=S?.artifact!==void 0&&!(0,yn.deepEqual)(S.artifact,p),I=L?this.nextRefreshGeneration(d,E,h):(r=h?.refreshGeneration)!==null&&r!==void 0?r:0,D=[...(n=w.warnings)!==null&&n!==void 0?n:[],...S?.warning?[S.warning]:[],...S?.artifact!==void 0&&!this.adoptedAsSent(m,S.artifact,w.readBack,g)?[`Saved, but the server holds something other than what was pushed (another writer saved in between, or the platform rewrote something the SDK does not model \u2014 a label in a language the org does not provision, a hand-written fragment); the local ${d} now holds the server's version. Read it (getArtifact) before the next edit: a mutation whose pointer was derived from the earlier copy is refused (StaleArtifactError).`]:[]];return await this.versions.storeMeta(d,E,{etag:S&&!S.artifact?null:w.etag,...I>0?{refreshGeneration:I,observedGeneration:(i=h?.observedGeneration)!==null&&i!==void 0?i:0}:{},languageCode:this.languageCode,projectionVersion:cl.PROJECTION_VERSION,fetchedAt:(0,pr.nowIso)(),snapshot:(0,fi.cloneJson)(P.baseline),...w.memberEtags?{memberEtags:w.memberEtags}:{},...w.siblingEtags?{siblingEtags:w.siblingEtags}:{}},E===f?h:void 0),{type:d,id:E,saved:!0,shipped:!1,publish:(o=w.publish)!==null&&o!==void 0?o:{kind:"notRequested"},...w.publish&&w.publish.kind!=="notRequested"?(()=>{var O;let x=(O=m.publishScope)===null||O===void 0?void 0:O.call(m,E,p);return x?{publishScope:x}:{}})():{},...L?{refreshed:!0}:{},...D.length>0?{warnings:D}:{}}}catch(w){let E=(0,Z.readPartialTokens)(w);if(E&&h){let S={...(a=h.memberEtags)!==null&&a!==void 0?a:{},...(s=E.memberEtags)!==null&&s!==void 0?s:{}},P={...(l=h.siblingEtags)!==null&&l!==void 0?l:{},...(u=E.siblingEtags)!==null&&u!==void 0?u:{}};await this.versions.storeMeta(d,f,{...h,...Object.keys(S).length>0?{memberEtags:S}:{},...Object.keys(P).length>0?{siblingEtags:P}:{}},h)}if(w instanceof Z.SdkError&&w.code===mr.ALREADY_EXISTS_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===lM.WFOM_API_UNAVAILABLE_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===lM.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===pr.VERSION_CONFLICT_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,fM.isFailureAfterPrimaryWrite)(w)?w:new Z.VersionConflictError(d,f,(c=h?.etag)!==null&&c!==void 0?c:null,null,w.message)};throw b?Eae(w):w}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new Z.SdkError("ARTIFACT_LANGUAGE_MISMATCH",`Refusing to push ${t} '${r}': it was fetched with languageCode ${n.languageCode} but this SDK is configured with ${this.languageCode}. Pushing would rewrite labels read in one language as labels in another. Re-fetch with languageCode ${this.languageCode}, or create the SDK with languageCode ${n.languageCode}.`)}assertProjectionMatches(t,r,n){var i;if(n&&n.projectionVersion!==cl.PROJECTION_VERSION)throw new Z.SdkError("ARTIFACT_PROJECTION_STALE",`Refusing to push ${t} '${r}': its workspace copy was produced by projection version ${(i=n.projectionVersion)!==null&&i!==void 0?i:"unknown (pre-versioning)"}, but this SDK produces version ${cl.PROJECTION_VERSION}. The parsers changed in between, so an unedited part of this artifact can no longer be told apart from an edited one and pushing could overwrite server content the caller never touched. Re-fetch it with fetchArtifact('${t}', '${r}') and re-apply any local edits.`)}async createWithMintedId(t,r,n,i,o){try{return{written:await t.api.create(this.dataverse,i,n)}}catch(a){let s=r==="form"?(0,Wv.readPrimaryCreateRefusal)(a):void 0;if(s?.status===404&&await(0,dM.formExistsAtId)(()=>t.api.get(this.dataverse,n),s.sent.formid)){let u=`the platform answered the create with ${a.message} \u2014 this build refuses a replayed create that way \u2014 but a read of that id finds the record`;throw(0,Z.attachCause)(new Z.SdkError(mr.ALREADY_EXISTS_CODE,Hv(r,n,u)+(this.createRecovery==="adoptExact"?` ${yM(Pae)}`:"")),a)}if(!(a instanceof Z.SdkError)||a.code!==pr.VERSION_CONFLICT_CODE||(0,fM.isFailureAfterPrimaryWrite)(a))throw a;if(this.createRecovery==="adoptExact"&&s?.status===412){let l=await(0,dM.recoverFormCreate)({client:this.dataverse,read:()=>t.api.get(this.dataverse,n),sent:s.sent,authoredFormType:o.formType,project:u=>t.adapter.fromApiResponse(u)});if("adopted"in l)return{adopted:l.adopted};throw new Z.SdkError(mr.ALREADY_EXISTS_CODE,`${Hv(r,n)} ${yM(l.refused)}`)}throw new Z.SdkError(mr.ALREADY_EXISTS_CODE,Hv(r,n))}}async persistAdoption(t,r,n,i){let{artifact:o,etag:a}=i,s=!(0,yn.deepEqual)(o,n);return await this.versions.storeMeta(t,r,{etag:a,...s?{refreshGeneration:this.nextRefreshGeneration(t,r,null),observedGeneration:0}:{},languageCode:this.languageCode,projectionVersion:cl.PROJECTION_VERSION,fetchedAt:(0,pr.nowIso)(),snapshot:(0,fi.cloneJson)(o)},null),s&&await this.workspace.writeArtifact(t,r,o),{type:t,id:r,saved:!1,adoptedExisting:!0,shipped:!1,publish:{kind:"notRequested"},...s?{refreshed:!0}:{}}}async buildMetadataContext(t,r,n){var i,o,a,s;let l=(o=(i=t.metadataNeeds)===null||i===void 0?void 0:i.call(t,r,n))!==null&&o!==void 0?o:[],u=new Set(l.map(L=>L.entityLogicalName).filter(L=>!!L)),c=new Set(l.filter(L=>L.needsColumnDetail).map(L=>L.entityLogicalName)),d=new Set(l.filter(L=>L.needsColumnDetail||!L.fieldName).map(L=>L.entityLogicalName)),f=L=>l.filter(I=>I.entityLogicalName===L).every(I=>I.fetchRequired===!1),m=new Map,p=new Map;for(let L of u){let I=await this.readCachedEntityMetadata(L);if(I&&c.has(L)&&(I.columnDetailComplete!==!0||!(typeof I.columnDetailVersion=="number"&&I.columnDetailVersion>=dl.COLUMN_DETAIL_VERSION)||I.attributes.some(D=>typeof D.attributeTypeName!="string"))&&(I=null),!I&&!d.has(L)){if(!f(L)){let D=l.filter(O=>O.entityLogicalName===L).map(O=>O.fieldName);try{let O=await(0,dl.readColumnHints)(this.dataverse,L,D);p.set(L,new Map(O.map(x=>[x.logicalName,x])))}catch{}}continue}if(!I&&!f(L))try{await this.loadMissedEntityMetadata(L),I=await this.readCachedEntityMetadata(L)}catch{}I&&m.set(L,I)}let h=(L,I)=>{var D,O,x;return(O=(D=m.get(L))===null||D===void 0?void 0:D.attributes.find(K=>K.logicalName===I))!==null&&O!==void 0?O:(x=p.get(L))===null||x===void 0?void 0:x.get(I)},g=this.languageCode,w=l.some(L=>{if(!L.needsLabel||!L.fieldName)return!1;let I=h(L.entityLogicalName,L.fieldName);return I?.localizedDisplayName!==void 0&&!I.localizedDisplayName[g]})?await this.readBaseLanguage():void 0,E=!((a=t.needsBaseLanguage)===null||a===void 0)&&a.call(t,r)?await this.readBaseLanguage():void 0,S=(s=t.customControlNeeds)===null||s===void 0?void 0:s.call(t,r,n),P=S&&(S.controls.length>0||S.columns.length>0)?await this.readPcfNeeds(S):void 0;return{resolveField:(L,I)=>{let D=h(L,I);return D?{displayName:$ae(D,g,w),attributeType:D.attributeType}:void 0},resolveEntity:L=>m.get(L),loadTypeScript:()=>this.compiler.load(),...E!==void 0?{baseLanguageCode:E}:{},...P?{pcf:P}:{}}}async readPcfNeeds(t){let r=new Map;for(let i of t.controls)r.set(i,await(0,cM.readControlManifest)(this.dataverse,i));let n=new Map;for(let i of t.columns)n.set(i,await(0,cM.readPcfColumn)(this.dataverse,t.entityLogicalName,i,t.requireCreateEligibility?{requireCreateEligibility:!0}:void 0));return{control:i=>r.get(i),column:(i,o)=>i===t.entityLogicalName?n.get(o):void 0}}readBaseLanguage(){if(!this.baseLanguage){let t=(async()=>{var r,n,i;try{let o=await this.dataverse.get("/organizations?$select=languagecode");if(o.status<200||o.status>=300)return;let a=Number((i=(n=(r=o.body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.languagecode);return Number.isInteger(a)&&a>0?a:void 0}catch{return}})();this.baseLanguage=t,t.then(r=>{r===void 0&&this.baseLanguage===t&&(this.baseLanguage=void 0)})}return this.baseLanguage}async pushAll(){let t=await this.getDirtyArtifacts();await this.warmBatchMetadata(t);let r=new Map,n=new Map;for(let o=0;o<t.length;o+=1){let a=t[o];try{await this.withArtifactLock(a.type,a.id,()=>this.prepareArtifactUnlocked(a.type,a.id,r))}catch(s){n.set(o,{type:a.type,id:a.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Po(s)})}}if(n.size>0)return t.map((o,a)=>{var s;return(s=n.get(a))!==null&&s!==void 0?s:{type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new Z.SdkError(mr.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${n.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let i=[];for(let o of t)try{i.push(await this.withArtifactLock(o.type,o.id,()=>this.pushArtifactUnlocked(o.type,o.id,r)))}catch(a){i.push({type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Po(a)})}return i}async warmBatchMetadata(t){var r,n,i;let o=new Set;for(let a of t){let s=this.registrations.get(a.type);if(!s)continue;let l;try{l=await this.readLocal(a.type,a.id)}catch{continue}let u=l.entityLogicalName;u&&o.add(u);for(let c of(i=(n=(r=s.adapter).metadataNeeds)===null||n===void 0?void 0:n.call(r,l))!==null&&i!==void 0?i:[])c.entityLogicalName&&o.add(c.entityLogicalName)}for(let a of o)if(!await this.readCachedEntityMetadata(a))try{await this.loadMissedEntityMetadata(a)}catch{}}async getDirtyArtifacts(){return(await this.withDirtyFlags(await this.workspace.listArtifacts())).filter(r=>r.isDirty)}async diffArtifact(t,r){return this.versions.diff(t,r)}assignMissingIds(t,r){let n=this.registrations.get(t);return n?n.adapter.assignMissingIds(r):(0,tm.assignMissingIds)(r)}async resolveComponentType(t){if(t.genPage)return"genPage";switch(t.componentType){case er.SolutionComponentType.SavedQuery:return"view";case er.SolutionComponentType.SavedQueryVisualization:return"chart";case er.SolutionComponentType.AppModule:return"app";case er.SolutionComponentType.Workflow:return this.workflowArtifactType(t);case er.SolutionComponentType.SystemForm:return this.systemFormArtifactType(t.objectId);default:return}}async systemFormArtifactType(t){let r=await(0,Zp.readSystemFormType)(this.dataverse,t);if(Number.isNaN(r))throw new Z.SdkError(jv,`System form '${t}' answered without a readable type, so whether it is a form or a dashboard cannot be told.`);return(0,Zp.systemFormKindOf)(r)}async workflowArtifactType(t){let r=(0,Oa.normalizeGuid)(t.objectId,"workflowId"),n=`/workflows(${r})${(0,Oa.odataQuery)([["$select","category,businessprocesstype"]])}`,o=(0,pr.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)).body,a=(0,Zp.decodeCode)(o?.category);if(Number.isNaN(a))throw new Z.SdkError(jv,`Workflow '${r}' answered without a readable category, so its kind cannot be told.`);if(t.workflowCategory=a,a===Nae)return"businessRule";if(a===_ae){let s=(0,Zp.decodeCode)(o?.businessprocesstype);if(Number.isNaN(s))throw new Z.SdkError(jv,`Workflow '${r}' (category 4) answered without a readable businessprocesstype, so whether it is a business process flow or a task flow cannot be told.`);return s===0?"bpf":void 0}}requireRegistration(t,r){let n=this.registrations.get(t);if(!n)throw new Z.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};mr.MakerSdk=rm;function Lae(e){return new rm(e)}mr.createMakerSdk=Lae;function Po(e){return e instanceof Error?e:new Error(String(e))}function EM(e,t){let r=Object.keys(e??{}),n=Object.keys(t??{});return r.length===n.length&&r.every(i=>Object.prototype.hasOwnProperty.call(t??{},i))}function AM(e){return Object.values(e??{}).every(pr.isVersionToken)}function kae(e,t){return EM(e,t)&&AM(e)&&Object.keys(e??{}).every(r=>t?.[r]===e?.[r])}function yM(e){return`createRecovery 'adoptExact' did not adopt it: ${e}.`}function Hv(e,t,r){return`Cannot create ${e} '${t}': a record already exists at that id${r?` (${r})`:""}, so an earlier push of this artifact committed before its local version metadata was saved. No duplicate was created. Run fetchArtifact('${e}', '${t}', { overwrite: true }) to adopt the existing record's identity, etag and snapshot \u2014 the overwrite is required, because this local copy has never been pushed, so a plain fetch keeps it and adopts nothing; it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push again: a conditional update, provided the adopted record is complete. If the earlier push committed only PART of a multi-row artifact (e.g. an app's appmodule without its sitemap), that update refuses, naming what is missing and how to remove the partial record. This is not done automatically because the only recovery available here would be an UNCONDITIONAL overwrite, which would destroy any edit made to the record in the meantime.`}function $ae(e,t,r){let n=e.localizedDisplayName;return n?.[t]||(r===void 0?void 0:n?.[r])||e.displayName}function Hi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function bM(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function vM(e){e.length===0||!e.every(t=>Hi(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function xae(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=>Hi(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>Hi(n)&&n.id===t.after);return r<0?e.length:r+1}});var NM=v(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});nm.ARTIFACT_TYPES=void 0;nm.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var TM=v(_M=>{"use strict";Object.defineProperty(_M,"__esModule",{value:!0})});var IM=v(DM=>{"use strict";Object.defineProperty(DM,"__esModule",{value:!0})});var PM=v(OM=>{"use strict";Object.defineProperty(OM,"__esModule",{value:!0})});var LM=v(RM=>{"use strict";Object.defineProperty(RM,"__esModule",{value:!0})});var $M=v(kM=>{"use strict";Object.defineProperty(kM,"__esModule",{value:!0})});var FM=v(xM=>{"use strict";Object.defineProperty(xM,"__esModule",{value:!0})});var UM=v(MM=>{"use strict";Object.defineProperty(MM,"__esModule",{value:!0})});var qM=v(BM=>{"use strict";Object.defineProperty(BM,"__esModule",{value:!0})});var GM=v(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0})});var zM=v(WM=>{"use strict";Object.defineProperty(WM,"__esModule",{value:!0})});var HM=v(jM=>{"use strict";Object.defineProperty(jM,"__esModule",{value:!0})});var JM=v(KM=>{"use strict";Object.defineProperty(KM,"__esModule",{value:!0})});var QM=v(YM=>{"use strict";Object.defineProperty(YM,"__esModule",{value:!0})});var ZM=v(XM=>{"use strict";Object.defineProperty(XM,"__esModule",{value:!0})});var tU=v(eU=>{"use strict";Object.defineProperty(eU,"__esModule",{value:!0})});var nU=v(rU=>{"use strict";Object.defineProperty(rU,"__esModule",{value:!0})});var oU=v(iU=>{"use strict";Object.defineProperty(iU,"__esModule",{value:!0})});var sU=v(aU=>{"use strict";Object.defineProperty(aU,"__esModule",{value:!0})});var uU=v(lU=>{"use strict";Object.defineProperty(lU,"__esModule",{value:!0})});var dU=v(cU=>{"use strict";Object.defineProperty(cU,"__esModule",{value:!0})});var pU=v(fU=>{"use strict";Object.defineProperty(fU,"__esModule",{value:!0})});var hU=v(ce=>{"use strict";var Fae=ce&&ce.__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]})),Ge=ce&&ce.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Fae(t,e,r)};Object.defineProperty(ce,"__esModule",{value:!0});ce.projectConnectorOperationSchema=ce.projectConnectorOperations=ce.createMakerSdk=void 0;var Mae=SM();Object.defineProperty(ce,"createMakerSdk",{enumerable:!0,get:function(){return Mae.createMakerSdk}});Ge(NM(),ce);Ge(TM(),ce);Ge(IM(),ce);Ge(PM(),ce);Ge(LM(),ce);Ge($M(),ce);Ge(FM(),ce);Ge(UM(),ce);Ge(qM(),ce);Ge(GM(),ce);Ge(zM(),ce);Ge(HM(),ce);Ge(JM(),ce);Ge(QM(),ce);Ge(ZM(),ce);Ge(Rd(),ce);Ge(tU(),ce);Ge(nU(),ce);Ge(oU(),ce);Ge(sU(),ce);Ge(uU(),ce);Ge(dU(),ce);Ge(pU(),ce);Ge(Q(),ce);var mU=Al();Object.defineProperty(ce,"projectConnectorOperations",{enumerable:!0,get:function(){return mU.projectConnectorOperations}});Object.defineProperty(ce,"projectConnectorOperationSchema",{enumerable:!0,get:function(){return mU.projectConnectorOperationSchema}})});var Jv=v(pi=>{"use strict";var Uae=pi&&pi.__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]})),Bae=pi&&pi.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),bU=pi&&pi.__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)&&Uae(t,e,r);return Bae(t,e),t};Object.defineProperty(pi,"__esModule",{value:!0});pi.NodeFileSystemStorage=void 0;var vt=bU(require("fs")),tr=bU(require("path")),gU=Q(),yU=Rm();async function vU(e){let t;try{t=await vt.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await vt.promises.unlink(e)}catch{await vt.promises.rmdir(e)}return}if(!t.isDirectory()){await vt.promises.unlink(e);return}for(let r of await vt.promises.readdir(e))await vU(tr.join(e,r));await vt.promises.rmdir(e)}var Kv=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(tr.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!vt.existsSync(r);){n.unshift(tr.basename(r));let i=tr.dirname(r);if(i===r)return tr.resolve(t);r=i}return tr.resolve(vt.realpathSync(r),...n)}assertWithinRoot(t,r){let n=tr.resolve(this.root),i=tr.resolve(t);if(i!==n&&!i.startsWith(n+tr.sep))throw new gU.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(n),a=r?this.realPathThroughNearestAncestor(i):tr.resolve(this.realPathThroughNearestAncestor(tr.dirname(i)),tr.basename(i));if(a!==o&&!a.startsWith(o+tr.sep))throw new gU.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!vt.existsSync(r))return null;try{return await(0,yU.retryTransientIoAsync)(()=>vt.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=tr.dirname(n);await vt.promises.mkdir(i,{recursive:!0});let o=tr.join(i,`.${tr.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await vt.promises.writeFile(o,r,"utf8"),await(0,yU.retryTransientIoAsync)(()=>vt.promises.rename(o,n))}catch(a){try{vt.existsSync(o)&&await vt.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let r=this.pathFor(t);vt.existsSync(r)&&await vt.promises.unlink(r)}async deleteByPrefix(t){await vU(this.pathFor(t,!1))}async ensureContainer(t){await vt.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return vt.existsSync(this.pathFor(t))}};pi.NodeFileSystemStorage=Kv});var wU=v(xr=>{"use strict";var qae=xr&&xr.__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]})),Vae=xr&&xr.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),Gae=xr&&xr.__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)&&qae(t,e,r);return Vae(t,e),t};Object.defineProperty(xr,"__esModule",{value:!0});xr.loadNodeTypeScript=xr.createNodeWorkspaceStorage=xr.NodeFileSystemStorage=void 0;var Wae=Jv(),zae=Jv();Object.defineProperty(xr,"NodeFileSystemStorage",{enumerable:!0,get:function(){return zae.NodeFileSystemStorage}});function jae(e){return new Wae.NodeFileSystemStorage(e)}xr.createNodeWorkspaceStorage=jae;async function Hae(){return await Promise.resolve().then(()=>Gae(require("typescript")))}xr.loadNodeTypeScript=Hae});var Ki={};module.exports=Fr(Ki);Ji(Ki,Ee(hU()),module.exports);Ji(Ki,Ee(wU()),module.exports);
+`),diagnostics:c}}ke.compileGenPage=Y5});var xg=v(ys=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});ys.isFailureAfterPrimaryWrite=ys.failedAfterPrimaryWrite=void 0;var QN=Symbol.for("cds-maker-sdk.createFailedAfterPrimaryWrite");function Q5(e){return typeof e=="object"&&e!==null&&(e[QN]=!0),e}ys.failedAfterPrimaryWrite=Q5;function X5(e){return typeof e=="object"&&e!==null&&e[QN]===!0}ys.isFailureAfterPrimaryWrite=X5});var zd=v(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.appApi=Xn.deleteAppResolvingOnce=Xn.mainFormSetShapeIssues=Xn.unpublishedAppModulesQuery=void 0;var mo=Lt(),Z5=zg(),e8=bg(),XN=Qr(),t8=Fd(),r8=xg(),fe=ye(),Ce=le(),Mg=pt(),Ug=Kl(),de=Q(),n8=(0,Ce.odataQuery)([["$select","appmoduleid,name,uniquename,description,aiappdescription"]]),Bg="appmoduleid,name,uniquename,description,aiappdescription";function uu(e,t,r){return"/appmodules/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ce.odataQuery)([["$select",e],["$filter",t],["$top",r]])}Xn.unpublishedAppModulesQuery=uu;function qg(e,t){return uu(e,t?`appmoduleid eq ${t}`:void 0,t?1:void 0)}function Gd(e,t){return"/sitemaps/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()"+(0,Ce.odataQuery)([["$select",t],["$filter",`sitemapid eq ${e}`],["$top",1]])}function su(e){var t;let r=(t=e.body)===null||t===void 0?void 0:t.value;if(Array.isArray(r))return r[0]}function i8(e){let t=e?.["@odata.etag"];return typeof t=="string"?t:null}function Wd(e,t){if(typeof e!="string")return!1;try{return(0,Ce.normalizeGuid)(e,"sitemapid")===t}catch{return!1}}function na(e){let t=new Set,r=[];for(let n of e??[])n&&!t.has(n)&&(t.add(n),r.push(n));return r}function o8(e){return`cdsapp_${(e||"").replace(/[^a-zA-Z0-9]/g,"")||"app"}`}async function a8(e,t){var r,n;let i=u=>{throw new de.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 o=`/sitemaps${(0,Ce.odataQuery)([["$select","sitemapid"],["$filter",`sitemapnameunique eq '${(0,Ce.odataLiteral)(t)}'`],["$top",1]])}`,a;try{a=await e.get(o)}catch(u){return i(`failed (${u.message})`)}if(a.status<200||a.status>=300)return i(`returned HTTP ${a.status}`);let s=(r=a.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 s8(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,Ce.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 o=t(await e.get(r(`${n} and ismanaged eq false`)));if(o)return{id:o,managed:!1};let a=t(await e.get(r(n)));return a?{id:a,managed:!0}:void 0}var ZN="627090ff-40a3-4053-8790-584edc5be201";function Dr(e){return e instanceof Error?e.message:String(e)}async function l8(e,t){var r;try{let n=`/roles${(0,Ce.odataQuery)([["$select","roleid,_parentrootroleid_value"],["$filter",`_roletemplateid_value eq ${ZN}`]])}`,i=await(0,mo.collectPages)(e,n,"the System Administrator role"),o=i.find(l=>typeof l.roleid=="string"&&typeof l._parentrootroleid_value=="string"&&l.roleid.toLowerCase()===l._parentrootroleid_value.toLowerCase()),a=(r=o??i.find(l=>typeof l.roleid=="string"))===null||r===void 0?void 0:r.roleid;if(!a)return`App roles: no 'System Administrator' role (template ${ZN}) was found in this environment, so the SDK did not associate one with the app \u2014 it may not be visible or playable until a role is granted access to it.`;let s=`/appmodules(${t})/appmoduleroles_association/$ref`;return(0,fe.ensureSuccess)(await e.post(s,{"@odata.id":e.apiUrl(`/roles(${a})`)}),e.apiUrl(s)),null}catch(n){return`App roles: could not associate the 'System Administrator' role with the app (${Dr(n)}); it will not be visible or playable until a role is granted access to it.`}}async function u8(e,t,r=!0){let n=[];async function i(l,u,c){try{return(await(0,mo.collectPages)(e,l,`app assets (${c} for '${t}')`)).map(f=>String(f[u])).filter(f=>f&&f!=="undefined")}catch(d){return n.push(`App components: could not enumerate ${c} for table '${t}' (${Dr(d)}); they were NOT added to the app.`),[]}}let[o,a,s]=await Promise.all([r?i(`/systemforms${(0,Ce.odataQuery)([["$select","formid"],["$filter",`objecttypecode eq '${(0,Ce.odataLiteral)(t)}' and type eq 2 and formactivationstate eq 1`]])}`,"formid","forms"):Promise.resolve([]),i(`/savedqueries${(0,Ce.odataQuery)([["$select","savedqueryid"],["$filter",`returnedtypecode eq '${(0,Ce.odataLiteral)(t)}' and querytype eq 0 and statecode eq 0`]])}`,"savedqueryid","views"),i(`/savedqueryvisualizations${(0,Ce.odataQuery)([["$select","savedqueryvisualizationid"],["$filter",`primaryentitytypecode eq '${(0,Ce.odataLiteral)(t)}'`]])}`,"savedqueryvisualizationid","charts")]);return{forms:o,views:a,charts:s,warnings:n}}var e_=new WeakMap;async function c8(e,t){let r=e_.get(e);r||(r=new Map,e_.set(e,r));let n=r.get(t);if(n!==void 0)return n;let i=await d8(e,t);return i&&r.set(t,i),i}async function t_(e,t,r){let n=new Array(e.length),i=0;async function o(){for(let a=i;a<e.length;a=i)i=a+1,n[a]=await r(e[a])}return await Promise.all(Array.from({length:Math.min(t,e.length)},()=>o())),n}async function d8(e,t){let r=`/EntityDefinitions(LogicalName='${(0,Ce.odataPathLiteral)(t)}')${(0,Ce.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 r_(e,t,r){let n=[],i=na(t.entities),o=4,a=await t_(i,o,g=>c8(e,g)),s=i.filter((g,b)=>!a[b]);if(s.length>0)throw new de.SdkError("APP_ENTITY_COMPONENT_UNRESOLVED",`Refusing to build app components: table(s) ${s.map(g=>`'${g}'`).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 l=a.filter(g=>!!g);for(let g of l)n.push({"@odata.id":`${g.entitySetName}(${g.metadataId})`});for(let g of na(t.components.forms))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});for(let g of na(t.components.views))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:g});for(let g of na(t.components.charts))n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:g});for(let g of na(t.components.dashboards))n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:g});let u=new Set(t.components.forms),c=new Set(t.components.views),d=new Set(t.components.charts),f=new Map((r??[]).map(g=>[g.table,g])),m=await t_(i,o,g=>u8(e,g,!f.has(g.toLowerCase()))),p=m.flatMap(g=>g.warnings),h=new Set([...na(t.components.forms),...na(t.components.dashboards)].map(at));return m.forEach((g,b)=>{let w=f.get(i[b].toLowerCase());if(w)for(let C of w.allowed)h.has(C)||(h.add(C),u.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:C}));else for(let C of g.forms)u.has(C)||(u.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.systemform",formid:C}));for(let C of g.views)c.has(C)||(c.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedquery",savedqueryid:C}));for(let C of g.charts)d.has(C)||(d.add(C),n.push({"@odata.type":"Microsoft.Dynamics.CRM.savedqueryvisualization",savedqueryvisualizationid:C}))}),{components:n,tables:l,warnings:p}}function at(e){let t=String(e).trim();return(t.startsWith("{")&&t.endsWith("}")?t.slice(1,-1):t).toLowerCase()}var bs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Vg="/components/mainFormsByTable",n_=50;function f_(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function p_(e,t){if(e===void 0)return[];if(e===null||typeof e!="object"||Array.isArray(e))return[{pointer:Vg,rule:"app-main-form-set-shape",message:"must be an object mapping a table logical name to its Main form ids"}];let r=[],n=new Set(t.map(o=>o.toLowerCase())),i=new Set;for(let[o,a]of Object.entries(e)){let s=o.toLowerCase(),l=`${Vg}/${f_(o)}`;if(i.has(s)){r.push({pointer:l,rule:"app-main-form-set-shape",message:`table '${o}' is listed twice (logical names compare case-insensitively)`});continue}if(i.add(s),n.has(s)||r.push({pointer:l,rule:"app-main-form-set-table",message:`'${o}' is not a table this app's sitemap navigates to (Entity subareas: ${[...n].join(", ")||"none"})`}),!Array.isArray(a)){r.push({pointer:l,rule:"app-main-form-set-shape",message:"must be an array of Main form ids"});continue}if(a.length===0){r.push({pointer:l,rule:"app-main-form-set-empty",message:`an empty list is refused: an app with no Main form of '${o}' offers every form of the table`});continue}let u=new Set;a.forEach((c,d)=>{let f=`${l}/${d}`;typeof c!="string"||!bs.test(at(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`'${String(c)}' is not a form id`}):u.has(at(c))?r.push({pointer:f,rule:"app-main-form-set-shape",message:`form '${c}' is listed twice`}):u.add(at(c))})}return r}Xn.mainFormSetShapeIssues=p_;async function i_(e,t,r){let n=t.components.mainFormsByTable;if(n===void 0)return;let i=p_(n,t.entities);if(i.length>0)throw new de.ValidationError("app",r,i);if(Object.keys(n).length===0)return;let o=[],a=[];for(let[l,u]of Object.entries(n)){let c=l.toLowerCase(),d=await(0,mo.collectPages)(e,`/systemforms${(0,Ce.odataQuery)([["$select","formid,formactivationstate"],["$filter",`objecttypecode eq '${(0,Ce.odataLiteral)(c)}' and type eq 2`]])}`,`app Main-form allow-list ('${c}')`),f=new Set,m=new Set;for(let h of d)typeof h.formid=="string"&&(f.add(at(h.formid)),Number(h.formactivationstate)===1&&m.add(at(h.formid)));let p=u.map(at);p.forEach((h,g)=>{let b=`${Vg}/${f_(l)}/${g}`;f.has(h)?m.has(h)||o.push({pointer:b,rule:"app-main-form-set-inactive",message:`Main form '${u[g]}' of '${c}' is inactive, so no app can offer it`}):o.push({pointer:b,rule:"app-main-form-set-not-main-form",message:`'${u[g]}' is not a Main form of '${c}'`})}),a.push({table:c,allowed:p,catalog:f})}let s=[...t.components.forms.map((l,u)=>({id:l,pointer:`/components/forms/${u}`})),...t.components.dashboards.map((l,u)=>({id:l,pointer:`/components/dashboards/${u}`}))];for(let l of s){let u=at(l.id);for(let c of a)c.catalog.has(u)&&!c.allowed.includes(u)&&o.push({pointer:l.pointer,rule:"app-main-form-set-conflict",message:`'${l.id}' is a Main form of '${c.table}' outside its allow-list, and this pin (an explicit form or dashboard, or a sitemap DashBoard subarea) would add it. Remove the pin, or list the form.`})}if(o.length>0)throw new de.ValidationError("app",r,o);return a}async function Wg(e,t){var r,n;let i=u=>({kind:"inconclusive",reason:u}),o=await e.get(uu("appmoduleid,appmoduleidunique,componentstate",`appmoduleid eq ${t}`));if(o.status<200||o.status>=300)return i(`reading the app returned HTTP ${o.status}`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a)||a.length===0)return i("reading the app returned no row");let s=a.length===1?a:a.filter(u=>Number(u?.componentstate)===1),l=s.length===1?(n=s[0])===null||n===void 0?void 0:n.appmoduleidunique:"";return typeof l!="string"||!bs.test(at(l))?i(`no single current layer among ${a.length} app row(s)`):{kind:"read",unique:at(l)}}function qd(e,t){let r;return()=>r??(r=Wg(e,t))}var m_=62;function f8(e,t,r,n,i){let o=i.map(a=>`'${a}'`).join(", ");return t==="delete"?new de.SdkError("APP_SITEMAP_SHARED",`Refusing to delete app '${e}': its sitemap '${r.sitemapId}' is also the navigation of app ${o}. The delete removes an app's sitemap with it, and the platform does not stop that for a sitemap another app uses, so those apps would be left without navigation. Nothing was deleted. Remove the sitemap from the other app first, then retry.`):new de.SdkError("APP_SITEMAP_SHARED",`Refusing to ${t} app '${e}': it has no SiteMap component, and the sitemap named like it ('${n??""}', '${r.sitemapId}') is the navigation of app ${o}, so it is not this app's. Nothing was ${t==="fetch"?"saved":"modified"}.`)}async function lu(e,t,r,n,i=!1){var o;let a=c=>{throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to ${n} app '${t}': ${c}, so it cannot be determined which sitemap is this app's. Nothing was ${n==="fetch"?"saved":n==="delete"?"deleted":"modified"}. Retry.`)},s;try{s=await Wg(e,t)}catch(c){return a(`reading its current layer failed (${Dr(c)})`)}if(s.kind==="inconclusive")return a(`its current layer could not be read (${s.reason})`);let l;try{l=await(0,mo.collectPages)(e,`/appmodulecomponents${(0,Ce.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${s.unique} and componenttype eq ${m_}`]])}`,`app SiteMap component ('${t}')`)}catch(c){return a(`reading its SiteMap component failed (${Dr(c)})`)}let u;if(l.length>1)return a(`its current layer carries ${l.length} SiteMap components, where an app can hold one`);if(l.length===1){let c=(o=l[0])===null||o===void 0?void 0:o.objectid;if(typeof c!="string"||!bs.test(at(c)))return a(`its SiteMap component carries an object id that is not a GUID ('${String(c)}')`);u={sitemapId:at(c),by:"component"}}else{let c=await a8(e,r);if(!c)return;let d;try{d=(0,Ce.normalizeGuid)(c,"sitemapId")}catch{return a(`the sitemap lookup by unique name returned a sitemapid that is not a GUID ('${String(c)}')`)}u={sitemapId:d,by:"name"}}if(i||u.by==="name"){let c=await p8(e,u.sitemapId,t,a);if(c.length>0)throw f8(t,n,u,r,c)}return u}async function p8(e,t,r,n){var i;let o;try{o=await(0,mo.collectPages)(e,`/appmodulecomponents${(0,Ce.odataQuery)([["$select","_appmoduleidunique_value"],["$filter",`componenttype eq ${m_} and objectid eq ${t}`]])}`,`apps using sitemap '${t}'`)}catch(u){return n(`reading which apps use sitemap '${t}' failed (${Dr(u)})`)}let a=new Set;for(let u of o){let c=u?._appmoduleidunique_value;if(typeof c!="string"||!bs.test(at(c)))return n(`a SiteMap component naming sitemap '${t}' carries no app layer id`);a.add(at(c))}let s=at(r),l=[];for(let u of a){let c;try{c=await e.get(uu("appmoduleid",`appmoduleidunique eq ${u}`))}catch(f){return n(`resolving app layer '${u}' failed (${Dr(f)})`)}if(c.status<200||c.status>=300)return n(`resolving app layer '${u}' returned HTTP ${c.status}`);let d=(i=c.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(d))return n(`resolving app layer '${u}' returned a malformed body`);for(let f of d){let m=f?.appmoduleid;if(typeof m!="string"||!bs.test(at(m)))return n(`app layer '${u}' resolved to a row with no app id`);let p=at(m);if(p===s||l.includes(p))continue;let h;try{h=await Wg(e,p)}catch(g){return n(`reading the current layer of app '${p}' failed (${Dr(g)})`)}if(h.kind==="inconclusive")return n(`the current layer of app '${p}' could not be read (${h.reason})`);h.unique===u&&l.push(p)}}return l}async function h_(e,t,r,n=qd(e,t)){let i=m=>({kind:"inconclusive",reason:m}),o=await n();if(o.kind==="inconclusive")return o;let a=o.unique,s;try{let m=await(0,mo.collectPages)(e,`/appmodulecomponents${(0,Ce.odataQuery)([["$select","objectid"],["$filter",`_appmoduleidunique_value eq ${at(a)} and componenttype eq 60`]])}`,`app Main-form membership ('${t}')`);if(m.some(p=>typeof p.objectid!="string"))return i("a form component carries no object id");s=m.map(p=>at(String(p.objectid)))}catch(m){return i(`reading its form components failed (${Dr(m)})`)}let l=new Map,u=[];for(let m of new Set(s)){let p=r.find(h=>h.catalog.has(m));p?l.set(m,p.table):u.push(m)}if(u.some(m=>!bs.test(m)))return i("a form component carries an object id that is not a GUID");let c=new Set(r.map(m=>m.table)),d=new Set;for(let m=0;m<u.length;m+=n_){let p=u.slice(m,m+n_);try{let h=await(0,mo.collectPages)(e,`/systemforms${(0,Ce.odataQuery)([["$select","formid,type,objecttypecode"],["$filter",p.map(g=>`formid eq ${g}`).join(" or ")]])}`,`app Main-form membership ('${t}': classifying components)`);for(let g of h){if(typeof g.formid!="string"||typeof g.type!="number"||g.type===2&&(typeof g.objecttypecode!="string"||g.objecttypecode===""))continue;let b=at(g.formid);d.add(b);let w=g.type===2?String(g.objecttypecode).toLowerCase():"";c.has(w)&&l.set(b,w)}}catch(h){return i(`classifying its form components failed (${Dr(h)})`)}}let f=u.filter(m=>!d.has(m));return f.length>0?i(`form component(s) ${f.join(", ")} could not be classified`):{kind:"read",tables:r.map(m=>{let p=[...l].filter(([,h])=>h===m.table).map(([h])=>h);return{table:m.table,members:p,extras:p.filter(h=>!m.allowed.includes(h)),missing:m.allowed.filter(h=>!p.includes(h))}})}}async function m8(e,t,r,n){let i=await h_(e,t,r,n);if(i.kind==="inconclusive")throw new de.SdkError("APP_MAIN_FORM_SET_UNVERIFIED",`App '${t}': its Main-form allow-list was written but could not be verified \u2014 ${i.reason}.`);let o=i.tables.filter(a=>a.extras.length>0||a.missing.length>0);if(o.length>0)throw new de.SdkError("APP_MAIN_FORM_SET_NOT_APPLIED",`App '${t}': its Main forms do not match the allow-list after the write \u2014 ${o.map(a=>`'${a.table}': unexpected [${a.extras.join(", ")}], missing [${a.missing.join(", ")}]`).join("; ")}.`)}async function h8(e,t,r,n){let i;try{i=await h_(e,t,r,n)}catch(a){i={kind:"inconclusive",reason:Dr(a)}}if(i.kind==="inconclusive")return[`Main-form membership of app '${t}' could not be verified (${i.reason}).`];let o=[];for(let a of i.tables)a.extras.length>0&&o.push(`Main-form components outside the allow-list remain for table '${a.table}': [${a.extras.join(", ")}]. This option controls additions only; it does not remove existing components. Runtime form availability has not been verified.`),a.missing.length>0&&o.push(`Allow-listed Main forms are not in app '${t}' after the push for table '${a.table}': [${a.missing.join(", ")}]; re-push to retry.`);return o}async function o_(e,t,r){if(r.length===0)return;let n="/AddAppComponents";(0,fe.ensureSuccess)(await e.post(n,{AppId:t,Components:r}),e.apiUrl(n))}async function a_(e,t,r,n=qd(e,t)){var i;if(r.length===0)return;let o=await n();if(o.kind==="inconclusive")throw new de.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its components were written but could not be verified \u2014 ${o.reason}. Re-push to retry.`);let a=`/appmodulecomponents${(0,Ce.odataQuery)([["$select","objectid,componenttype"],["$filter",`_appmoduleidunique_value eq ${o.unique} and componenttype eq 1`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)throw new de.SdkError("APP_COMPONENTS_UNVERIFIED",`App '${t}': its table components were written but could not be verified \u2014 reading them back returned HTTP ${s.status}. Re-push to retry.`);let l=(i=s.body)===null||i===void 0?void 0:i.value;if(!Array.isArray(l))throw new de.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 u=new Set(l.map(d=>d.objectid).filter(d=>typeof d=="string").map(d=>d.toLowerCase())),c=r.filter(d=>!u.has(d.metadataId.toLowerCase()));if(c.length>0)throw new de.SdkError("APP_COMPONENTS_NOT_PERSISTED",`App '${t}': ${c.length} declared table(s) are NOT components of the app after AddAppComponents reported success \u2014 ${c.map(d=>`'${d.logicalName}' (expected objectid ${d.metadataId})`).join(", ")}. The app's navigation would reference content the app does not contain.`)}async function g8(e,t,r){let n=`/appmodules(${t})`,i=`/sitemaps(${r.sitemapId})`,o;try{o=await b8(e,r.sitemapId,r.sitemapNameUnique)}catch(l){return{outcome:"kept",reason:`whether its sitemap row exists could not be determined (${Dr(l)})`}}let a=o==="foreign",s=l=>l.kind==="deleted"?{outcome:"removed",foreignSitemap:a}:l.kind==="refused"?{outcome:"kept",foreignSitemap:a,reason:`its delete was refused (${Dr(l.error)})`,...l.lock?{lock:!0}:{}}:{outcome:"unconfirmed",foreignSitemap:a,reason:`its delete was sent but its outcome is unknown (${Dr(l.error)})`,...l.lock?{lock:!0}:{}};try{if(o==="absent"||o==="foreign"){if(!r.serverRefusedSitemap)return{outcome:"kept",foreignSitemap:a,reason:"the sitemap write's outcome was never observed, so its row may still appear"};let l=await(0,fe.resendAppSearchIndexRace)(()=>e.delete(n));if(l.status===404)return s({kind:"deleted"});let u=Gg(l,e.apiUrl(n));return s(u.kind!=="deleted"&&(0,fe.isConcurrencyLockRefusal)(l)?{...u,lock:!0}:u)}return e.supportsAtomicBatch?r.sitemapWriteToken?s(await y_(e,[{path:n},{path:i,etag:r.sitemapWriteToken}],{reportLock:!0})):{outcome:"kept",reason:"the sitemap write returned no token of its own, and deleting the row without one could destroy another writer's change"}:{outcome:"kept",reason:"the HttpClient cannot send an atomic change set (no `postRaw`), and deleting the two rows one at a time could strand the sitemap"}}catch(l){return s({kind:"unknown",error:l})}}function y8(e,t,r){if(!(e instanceof Error))return e;let n=t.foreignSitemap?` Sitemap id '${r.sitemapId}' already belongs to ANOTHER app's sitemap, which was left untouched and must not be deleted: supply a sitemapId no other app uses, or omit it so one is minted.`:"";if(t.outcome==="removed")return e.message+=` The partial app this create wrote was removed.${n}`,e;let i=t.foreignSitemap?`appmodule '${r.appId}' (unique name '${r.uniqueName}')`:`appmodule '${r.appId}' (unique name '${r.uniqueName}') and, if it was written, sitemap '${r.sitemapId}'`,a=`a create with that unique name is refused \u2014 remove it in the maker portal, or, once you have confirmed the rows are this create's own, with ${t.foreignSitemap?`deleteRecord('appmodule', '${r.appId}')`:`deleteRecord('appmodule', '${r.appId}') and deleteRecord('sitemap', '${r.sitemapId}')`}.`,s="Once the lock frees \u2014 another customization operation holds it \u2014 check that the rows exist and are this create's own before removing them.";return t.lock&&t.outcome==="kept"?e.message+=` The partial app this create wrote was KEPT \u2014 its rollback deleted nothing, because the environment's customization lock refused it (another customization operation was running): ${i}. ${s} While it exists, ${a}`:t.lock?e.message+=` Whether the partial app this create wrote was removed could not be confirmed, because the environment's customization lock refused or interrupted its rollback, so it may not have run. Check for ${i}. ${s} While any of it exists, ${a}`:e.message+=t.outcome==="kept"?` The partial app this create wrote was KEPT, because ${t.reason}: ${i}. While it exists, ${a}`:` Whether the partial app this create wrote was removed could not be confirmed, because ${t.reason}. Check for ${i}: while any of it exists, ${a}`,e.message+=n,e}async function b8(e,t,r){var n,i,o;let a=Gd(t,"sitemapid,sitemapnameunique"),s=await e.get(a);if(s.status<200||s.status>=300)throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned HTTP ${s.status}, so it cannot be determined whether the row exists.`);let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`The unpublished-aware read of sitemap '${t}' returned no readable result set, so it cannot be determined whether the row exists.`);return l.length===0?"absent":String((o=(i=l[0])===null||i===void 0?void 0:i.sitemapnameunique)!==null&&o!==void 0?o:"")===r?"ours":"foreign"}async function v8(e,t){var r;let n;try{n=await e.get(uu("appmoduleid,uniquename,componentstate",`appmoduleid eq ${t}`))}catch(s){return{kind:"unsettled",why:`its unpublished read failed (${s.message})`}}if(n.status<200||n.status>=300)return{kind:"unsettled",why:`its unpublished read returned HTTP ${n.status}`};let i=(r=n.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(i)||i.length!==1)return{kind:"unsettled",why:`its unpublished read returned ${Array.isArray(i)?i.length:"no"} row(s), not exactly one`};let o=i[0],a=o?.uniquename;return!Wd(o?.appmoduleid,t)||o?.componentstate!==1||typeof a!="string"||!a?{kind:"unsettled",why:"its unpublished row is not this app as a never-published draft"}:{kind:"draft",uniquename:a}}async function g_(e,t){var r;let n=(0,Ce.normalizeGuid)(t,"id"),i=w=>{throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to delete app '${n}': ${w} Deleting the app would destroy the only pointer to its sitemap, stranding that row and reserving its unique name forever. Retry.`)},o=`/appmodules(${n})${n8}`,a;try{a=await e.get(o)}catch(w){return i(`reading the app failed (${w.message}).`)}let s,l=!1;if(a.status===404){let w=await v8(e,n);if(w.kind!=="draft")return i(`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; ${w.why}.`);s=w.uniquename,l=!0}else{if(a.status<200||a.status>=300)return i(`reading the app returned HTTP ${a.status}.`);s=(r=a.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 u=l?{draft:!0}:{appEtag:(0,fe.readEtag)(a)},c=await lu(e,n,s,"delete");if(!c)return{uniquename:s,...u};let d=c.sitemapId,f=await Vd(e,d),m=Gd(d,"sitemapid,sitemapnameunique,sitemapxml"),p;try{p=await e.get(m)}catch(w){return i(`reading sitemap '${d}' failed (${w.message}).`)}if(p.status<200||p.status>=300)return i(`reading sitemap '${d}' returned HTTP ${p.status}.`);let h=su(p);if(!h)return i(`sitemap '${d}' was not returned by the unpublished-aware read.`);if(c.by==="name"&&h.sitemapnameunique!==s)return i(`sitemap '${d}' now carries sitemapnameunique '${String(h.sitemapnameunique)}', not '${s}', so it is no longer this app's sitemap.`);if(!Wd(h.sitemapid,d))return i(`sitemap '${d}' was read back as a row carrying sitemapid '${String(h.sitemapid)}'.`);let g=h.sitemapxml;if(typeof g!="string")return i(`sitemap '${d}' returned no sitemapxml.`);let b=await lu(e,n,s,"delete",!0);return b?.sitemapId!==d||b.by!==c.by?i(`its sitemap link changed while it was read (sitemap '${d}' by ${c.by}, then ${b?`'${b.sitemapId}' by ${b.by}`:"none"}).`):{sitemapId:d,uniquename:s,sitemapXml:g,...u,sitemapEtag:f}}async function w8(e,t,r){let n=(0,Ce.normalizeGuid)(t,"id"),i=await g_(e,n);await r?.(i.sitemapXml),await v_(e,n,i)}Xn.deleteAppResolvingOnce=w8;async function C8(e,t){let r=await y_(e,t);if(r.kind!=="deleted")throw r.error}function Gg(e,t){try{return(0,fe.ensureSuccess)(e,t),{kind:"deleted"}}catch(r){return b_(e.status)?{kind:"refused",error:r}:{kind:"unknown",error:r}}}function E8(e,t){var r;if(e.status!==400&&(e.status<200||e.status>=300))return!1;let n=(r=(0,Ug.parseChangeSetParts)(e.body,t))===null||r===void 0?void 0:r.filter(i=>i.status<200||i.status>=300);return n!==void 0&&n.length>0&&n.every(i=>i.status===400&&(0,fe.namesAppSearchIndexRace)(i.text))}async function y_(e,t,r={}){let n=`batch_${(0,Mg.newId)()}`,i=`changeset_${(0,Mg.newId)()}`,o=t.map((p,h)=>[`--${i}`,"Content-Type: application/http","Content-Transfer-Encoding: binary",`Content-ID: ${h+1}`,"",`DELETE ${e.apiUrl(p.path)} HTTP/1.1`,...p.etag?[`If-Match: ${p.etag}`]:[],""].join(`\r
+`)),a=[`--${n}`,`Content-Type: multipart/mixed;boundary=${i}`,"",...o,`--${i}--`,`--${n}--`,""].join(`\r
+`),s=e.apiUrl("/$batch"),l=o.map((p,h)=>String(h+1)),u;try{u=await(0,fe.resendWhile)(p=>E8(p,l),()=>e.postBatch(a,n),fe.DEADLOCK_BACKOFF_MS)}catch(p){return{kind:"unknown",error:p}}if(r.reportLock){if((0,Ug.isChangeSetLockRefusal)(u,l))return{kind:"refused",lock:!0,error:new de.ConnectionError(s,u.status,`atomic delete of app '${t[0].path}' was refused whole by the customization lock, so it deleted nothing`)};if((0,fe.isConcurrencyLockRefusal)(u)){let p=Gg(u,s);return p.kind==="deleted"?p:{...p,lock:!0}}}let c=Gg(u,s);if(c.kind!=="deleted")return c;let d=`app '${t[0].path}'`;if(typeof u.body!="string"||u.body.length===0)return{kind:"unknown",error:new de.ConnectionError(s,u.status,`atomic delete of ${d} cannot be confirmed: the $batch response had no readable body, so the change set's outcome is unknown`)};let f=(0,Ug.parseChangeSetStatuses)(u.body,l);if(f===void 0)return{kind:"unknown",error:new de.ConnectionError(s,u.status,`atomic delete of ${d} cannot be confirmed: the $batch response could not be parsed as a change set, so the outcome is unknown`)};let m=f.find(p=>p<200||p>=300);return m!==void 0?{kind:"refused",error:new de.ConnectionError(s,m,`atomic delete of ${d} was rolled back: the change set reported HTTP ${m}`)}:f.length!==o.length?{kind:"unknown",error:new de.ConnectionError(s,u.status,`atomic delete of ${d} cannot be confirmed: the $batch response reported ${f.length} operation result(s), expected exactly ${o.length}`)}:{kind:"deleted"}}async function Vd(e,t){try{let r=await e.get(`/sitemaps(${t})?$select=sitemapid`);return r.status<200||r.status>=300?null:(0,fe.readEtag)(r)}catch{return null}}async function s_(e,t){let r=`/appmodules(${t})?$select=appmoduleid`,n=await e.get(r);if(n.status!==404)return(0,fe.ensureSuccess)(n,e.apiUrl(r)),(0,fe.readEtag)(n)}function l_(e){return{sitemapxml:e.sitemapxml,...e.sitemapname!==void 0?{sitemapname:e.sitemapname}:{}}}async function Fg(e,t,r,n){if(!n)return null;let i=await Vd(e,t);if(!i)return null;try{let o=await e.get(Gd(t,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"));if(o.status<200||o.status>=300)return null;let a=su(o);return!a||!Wd(a.sitemapid,t)||a.sitemapnameunique!==n||a.sitemapxml!==r.sitemapxml||r.sitemapname!==void 0&&a.sitemapname!==r.sitemapname?null:i}catch{return null}}function b_(e){return e>=400&&e<500&&e!==408&&e!==429}function u_(e,t,r){if(!e)throw new de.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 v_(e,t,r){let n=`/appmodules(${t})`,i=r.draft?void 0:u_(r.appEtag,t,"app");if(!r.sitemapId){if(r.draft){(0,fe.ensureSuccess)(await(0,fe.resendAppSearchIndexRace)(()=>e.delete(n)),e.apiUrl(n));return}await A8(e,n,i);return}if(!e.supportsAtomicBatch)throw new de.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 C8(e,[{path:n,etag:i},{path:`/sitemaps(${r.sitemapId})`,etag:u_(r.sitemapEtag,t,"sitemap")}])}async function A8(e,t,r){(0,fe.ensureSuccess)(await(0,fe.resendAppSearchIndexRace)(()=>e.delete(t,{headers:{"If-Match":r}})),e.apiUrl(t))}async function c_(e,t){if(!/GenPageId/i.test(t))return;let r;try{r=[...new Set((0,Z5.collectGenPageIds)(t))]}catch(i){throw new de.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 (${Dr(i)}).`)}if(r.length===0)return;let n=await(0,e8.findMissingGenPages)(e,r,"sitemap generative-page preflight");if(n.length>0)throw new de.SdkError("SITEMAP_TARGET_NOT_FOUND",`Refusing to push the app: its sitemap navigates to generative page(s) ${n.map(i=>`'${i}'`).join(", ")} that do not exist in this environment. Push the page before the app that links to it.`)}function S8(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")}function N8(e,t){var r;let n=[["name",e.appModuleName],["description",e.appModuleDescription],["aiappdescription",e.appModuleAiDescription]],i={};for(let[o,a]of n)a!==void 0&&(t!==void 0&&String((r=t[o])!==null&&r!==void 0?r:"")===String(a??"")||(i[o]=a));return i}async function d_(e,t,r){var n;let i=(0,Ce.normalizeGuid)(t,"id"),o=r==="tokens-first",a=o?await s_(e,i):null,s=qg(Bg,i),l=(0,fe.ensureSuccess)(await e.get(s),e.apiUrl(s)),u=(n=su(l))!==null&&n!==void 0?n:{};if(!u.appmoduleid)throw new de.SdkError("APP_NOT_FOUND",`App '${i}' was not found (checked the unpublished-aware projection, which includes drafts).`);let c=await lu(e,i,u.uniquename,"fetch"),d=c?.sitemapId,f=null;if(c&&d){o&&(f=await Vd(e,d));let p=Gd(d,"sitemapid,sitemapname,sitemapnameunique,sitemapxml"),h=(0,fe.ensureSuccess)(await e.get(p),e.apiUrl(p)),g=su(h),b=C=>{throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap '${d}' was located by its ${c.by==="component"?"SiteMap component":"unique name"}, but ${C}, so the sitemap cannot be read. Persisting the app without it would misreport it as having no sitemap, or write an empty one over its navigation. Retry.`)};if(!g)return b("the by-id read returned no row");if(c.by==="name"&&g.sitemapnameunique!==u.uniquename)throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': sitemap '${d}' now carries sitemapnameunique '${String(g.sitemapnameunique)}', not '${String(u.uniquename)}', so it is no longer this app's sitemap. Retry.`);if(!Wd(g.sitemapid,d))return b(`the by-id read returned a row carrying sitemapid '${String(g.sitemapid)}'`);if(typeof g.sitemapxml!="string")return b("the by-id read returned no sitemapxml");let w=await lu(e,i,u.uniquename,"fetch");if(w?.sitemapId!==d||w.by!==c.by)throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to fetch app '${i}': its sitemap link changed while it was read (sitemap '${d}' by ${c.by}, then ${w?`'${w.sitemapId}' by ${w.by}`:"none"}). Nothing was saved. Retry.`);u.$sitemap=g,o||(f=await Vd(e,d))}o||(a=await s_(e,i));let m=a??i8(u);return{raw:u,etag:f,...u.appmoduleid?{siblingEtags:{[(0,Ce.normalizeGuid)(u.appmoduleid,"appmoduleid")]:m}}:{}}}Xn.appApi={get(e,t){return d_(e,t,"tokens-first")},readContentThenToken(e,t){return d_(e,t,"content-first")},async list(e,t){let r=qg(Bg);return(await(0,mo.collectPages)(e,r,"listArtifacts('app')")).map(i=>{var o,a;return{type:"app",id:(o=i.appmoduleid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",isDirty:!1}})},async create(e,t,r){let n=t;if(typeof n.appModuleName!="string"||n.appModuleName.trim()==="")throw new de.ValidationError("app",n.appModuleId,[{pointer:"/name",rule:"app-name-required",message:"an app needs a name to be created, and its 'name' is missing or blank \u2014 set it (updateElement('app', id, '/name', \u2026), or addElement when the key was removed) and push again. Nothing was written."}]);await c_(e,n.sitemapxml);let i=await i_(e,n,n.appModuleId),o=n.iconWebResourceId?void 0:await s8(e),a=n.iconWebResourceId||o?.id;if(!a)throw new de.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 s=null;o?.managed&&(s=`No unmanaged image web resource was available, so the app icon resolved to a MANAGED one (${o.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 l=n.appModuleUniqueName||o8(n.appModuleId),u={name:n.appModuleName,uniquename:l,clienttype:4,formfactor:1,navigationtype:0};n.appModuleDescription&&(u.description=n.appModuleDescription),n.appModuleAiDescription&&(u.aiappdescription=n.appModuleAiDescription),a&&(u.webresourceid=a);let c="/appmodules",d=(0,fe.ensureSuccess)(await(0,fe.resendDeadlockVictim)(()=>e.post(c,(0,fe.withClientMintedId)(u,"appmoduleid",r))),e.apiUrl(c)),f=(0,fe.resolveCreatedId)(d,"appmoduleid","app module",r),m=null,p=null,h=[];s&&h.push(s);let g={kind:"notRequested"},b=n.sitemapId?(0,Ce.normalizeGuid)(n.sitemapId,"sitemapId"):(0,Mg.newId)(),w=!1,C=l_(n);try{let O="/sitemaps",k=(0,fe.echoWrite)("sitemapid"),I=await e.post(`${O}${k.query}`,{sitemapid:b,sitemapnameunique:l,...C},k.options);w=b_(I.status);let D=(0,fe.ensureSuccess)(I,e.apiUrl(O));p=(0,fe.readEtag)(D),m=p??await Fg(e,b,C,l);let P=await r_(e,n,i);h.push(...P.warnings);let x=P.components;x.unshift({"@odata.type":"Microsoft.Dynamics.CRM.sitemap",sitemapid:b}),await o_(e,f,x);let K=qd(e,f);await a_(e,f,P.tables,K),i&&await m8(e,f,i,K);let Oe=await l8(e,f);Oe&&h.push(Oe),n.appSettings&&Object.keys(n.appSettings).length>0&&h.push(...await(0,t8.applyAppSettings)(e,f,n.appSettings)),n.published!==!1&&(await(0,XN.publishAppModule)(e,f),g={kind:"submitted"})}catch(O){let k=await g8(e,f,{sitemapId:b,sitemapNameUnique:l,serverRefusedSitemap:w,sitemapWriteToken:p});throw(0,r8.failedAfterPrimaryWrite)(y8(O,k,{appId:f,sitemapId:b,uniqueName:l}))}let S=null;if(g.kind==="submitted")try{let O=await e.get(`/appmodules(${f})?$select=appmoduleid`);O.status>=200&&O.status<300&&(S=(0,fe.readEtag)(O))}catch{}return{id:f,etag:m,serverIdentity:{sitemapId:b},siblingEtags:{[f]:S},publish:g,...h.length>0?{warnings:h}:{}}},async update(e,t,r,n,i,o){var a,s,l;let u=r,c=(0,Ce.normalizeGuid)(t,"id");if(await c_(e,u.sitemapxml),!u.sitemapId)throw new de.ValidationError("app",c,[{pointer:"/sitemapId",rule:"app-sitemap-identity-missing",message:`missing sitemap identity \u2014 re-fetch the app before pushing edits: fetchArtifact('app', '${c}', { overwrite: true }) (it REPLACES the local copy \u2014 keep outstanding changes aside), push that refreshed copy UNTOUCHED, then re-apply your changes and push again. If the untouched push is refused with this same rule, the app has NO sitemap on the server \u2014 an earlier create committed its appmodule but not its sitemap \u2014 and it can be neither updated, published nor removed with deleteRemoteArtifact (an unpublished app reads back 404). Only for an app you have confirmed is your own abandoned partial create, with nothing else provisioning it: remove its appmodule row with deleteRecord('appmodule', '${c}'), clear the local copy with deleteArtifact('app', '${c}'), then author the app again and push.`}]);let d=(0,Ce.normalizeGuid)(u.sitemapId,"sitemapId");if(!(0,fe.isVersionToken)(n))throw new de.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${c}': ${n?`the concurrency token held for its sitemap row ('${n}') is not a version`:"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 f=await i_(e,u,c),m=await r_(e,u,f),p=`/appmodules(${c})`,h=(a=o?.[c])!==null&&a!==void 0?a:null,g,b;try{let Ne=qg(Bg,c),se=await e.get(Ne);if(se.status>=200&&se.status<300){let We=su(se);if(typeof We=="object"&&We!==null&&!Array.isArray(We)){g=We;let ir=g.uniquename;b=typeof ir=="string"&&ir?ir:void 0}}}catch{}let w=N8(u,g),C=await lu(e,c,b||u.appModuleUniqueName,"push");if(C?.sitemapId!==d)throw new de.SdkError("APP_SITEMAP_UNRESOLVED",`Refusing to push app '${c}': ${C?`its sitemap is now '${C.sitemapId}'`:"it has no sitemap now"}, not '${d}', the one this copy holds \u2014 the app's sitemap is no longer the one this copy was fetched with. Nothing was modified. Re-fetch the app (fetchArtifact('app', '${c}', { overwrite: true })) and re-apply the change.`);let S=h;if(Object.keys(w).length>0){if(!(0,fe.isVersionToken)(h))throw new de.SdkError("APP_UPDATE_NO_ETAG",`Refusing to push app '${c}': ${h?`the concurrency token held for its appmodule header ('${h}') is not a version`:"no concurrency token is held for its appmodule header"}, so its header edit could not be made conditional and would silently overwrite a concurrent edit. Nothing was modified. Re-fetch the app (fetchArtifact('app', '${c}', { overwrite: true })) and re-apply the change.`);let Ne=(0,fe.echoWrite)("appmoduleid",{"If-Match":h}),se=await e.patch(`${p}${Ne.query}`,w,Ne.options);if(S8(se))throw new de.SdkError("APP_DRAFT_HEADER_NOT_WRITABLE",`Refusing to update app '${c}': its appmodule row is UNPUBLISHED, and Dataverse cannot resolve version numbers for a draft appmodule (HTTP 400). A draft header cannot be PATCHed at all \u2014 a plain retry fails too, as an upsert-create ("webresourceid cannot be NULL"). Publish the app first, then push the header edit. Nothing was modified by this call.`);(0,fe.ensureSuccess)(se,e.apiUrl(p)),S=(0,fe.readEtag)(se)}let O=l_(u),k=u.sitemapNameUnique||b||u.appModuleUniqueName||void 0,I=(0,fe.echoWrite)("sitemapid",{"If-Match":n}),D=`/sitemaps(${d})`,P;try{P=(0,fe.ensureSuccess)(await e.patch(`${D}${I.query}`,{...O},I.options),e.apiUrl(D))}catch(Ne){throw(0,de.withPartialTokens)(Ne,{siblingEtags:{[c]:S}})}let x=[...m.warnings],K=qd(e,c);try{await o_(e,c,m.components),await a_(e,c,m.tables,K)}catch(Ne){x.push(`App '${c}': one or more components were not pinned (${Ne.message}). Navigation may reference content not included in the app; re-push to retry.`)}f&&x.push(...await h8(e,c,f,K));let Oe={kind:"notRequested"},Vt=S,Xe=(s=(0,fe.readEtag)(P))!==null&&s!==void 0?s:await Fg(e,d,O,k);if(u.published===!0){try{await(0,XN.publishAppModule)(e,c),Oe={kind:"submitted"}}catch(Ne){Oe={kind:"failed",error:Ne},x.push(`App '${c}': saved, but publishing failed (${Ne.message}). The app remains unpublished; re-push to retry.`)}if(Oe.kind==="submitted"){Vt=null;try{let Ne=await e.get(`/appmodules(${c})?$select=appmoduleid`);Ne.status>=200&&Ne.status<300&&(Vt=(0,fe.readEtag)(Ne)),Xe=(l=await Fg(e,d,O,k))!==null&&l!==void 0?l:Xe}catch{}}}return{id:c,etag:Xe,siblingEtags:{[c]:Vt},publish:Oe,...x.length>0?{warnings:x}:{}}},async delete(e,t){let r=(0,Ce.normalizeGuid)(t,"id");await v_(e,r,await g_(e,r))}}});var zg=v(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});vs.deleteAppCascade=vs.collectGenPageIds=void 0;var _8=zd(),T8=Q(),jg=le(),D8=ns();function w_(e){let t=[],r=s=>l=>t.push(`${s}: ${l}`),n=new D8.DOMParser({errorHandler:{warning:r("warning"),error:r("error"),fatalError:r("fatalError")}}).parseFromString(e,"text/xml"),i=n?.documentElement;if(!i||t.length>0)throw new T8.InvalidArgumentError(`The app sitemap xml could not be parsed cleanly, so its generative-page children cannot be determined${t.length>0?` (${t[0]})`:""}`);let o=[],a=s=>{if(s.nodeName==="SubArea"){let u=s.getAttribute("GenPageId");u&&o.push((0,jg.normalizeGuid)(u,"GenPageId"))}let l=s.childNodes;for(let u=0;u<l.length;u+=1){let c=l[u];c.nodeType===1&&a(c)}};return a(i),o}vs.collectGenPageIds=w_;async function I8(e,t,r){let n=(0,jg.normalizeGuid)(t,"appModuleId");(0,jg.normalizeGuid)(r,"appModuleIdUnique");let i=[],o=[],a=[];await(0,_8.deleteAppResolvingOnce)(e,n,l=>{l!==void 0&&a.push(...w_(l))}),i.push({type:"app",id:n});let s=[...new Set(a)].map(l=>({type:"genPage",id:l}));return{success:o.length===0,deleted:i,failures:o,retained:s}}vs.deleteAppCascade=I8});var C_={};Jr(C_,{Guid:()=>U});var U,ht=L(()=>{"use strict";U=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 q,Xt=L(()=>{"use strict";st();q=class e{static get EmptyString(){return""}static IsTrue(t){let r=!1;return r=t&&(this.IsStrictTrue(t)||this.IsYes(t)),r}static IsStrictTrue(t){let r=!1;return t&&(r=t.toLowerCase()==="true"),r}static IsYes(t){return t.toLowerCase()==="yes"||t.toLowerCase()==="y"}static get WhiteSpace(){return/ /g}static get EnglishAndNumericCharacters(){return/([a-z0-9A-Z]+)/g}static get ValidIdExpression(){return/([a-z0-9A-Z_]+)/g}static IsNullOrEmpty(t){return t==null||t==null||t==""}static Format(t,r){return e.IsNullOrEmpty(t)?t:t.replace(/\{\{|\}\}|\{(\d+)\}/g,function(n,i){return n=="{{"?"{":n=="}}"?"}":r[i]})}static EndsWithString(t,r){return t.indexOf(r,t.length-r.length)!==-1}static IsBlankString(t){return t.replace(/\s/g,"").length==0}static EscapeXml(t,r){let n=t;return this.IsNullOrEmpty(n)||(n=n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),r&&(n=n.replace(/"/g,"&quot;").replace(/'/g,"&apos;"))),n}static EscapeDomId(t){return t.replace(".","\\.")}static ToSnakeCase(t){let r=e.EmptyString;for(let n=0;n<t.length;n++)n!==0&&t[n]==t[n].toUpperCase()&&(r+="-"),r+=t[n].toLowerCase();return r}static GetSnakeCaseMarkup(t,r){let n="<"+this.ToSnakeCase(t);if(!R.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 R.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 E_={};Jr(E_,{ScriptUtilities:()=>R});var R,st=L(()=>{"use strict";ht();Xt();R=class e{static IsNullOrUndefined(t){return t==null||t===void 0}static IsMacMachine(){return navigator.platform.indexOf("Mac")!==-1}static IsNullOrEmptyGuid(t){return q.IsNullOrEmpty(t.ToString())?!0:U.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:q.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 jd,Hd,ia,Kd,Hg,Jd,Kg=L(()=>{"use strict";(function(e){e[e.FormElementNodeChange=0]="FormElementNodeChange",e[e.FormElementAttributeChange=1]="FormElementAttributeChange"})(jd||(jd={}));Hd=class{type;targetNode;constructor(t,r){this.type=t,this.targetNode=r}},ia=class extends Hd{key;oldValue;newValue;constructor(t,r,n,i){super(jd.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)}},Kd=class extends Hd{property;oldValue;newValue;constructor(t,r,n,i){super(jd.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)}},Hg=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()})}},Jd=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 Hg(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 A_={};Jr(A_,{ChartGridMode:()=>ln,ColumnLayoutWidths:()=>L8,ComponentCategory:()=>Qd,ComponentType:()=>Jg,ControlLayoutTypes:()=>r0,DisplayConditionsInfo:()=>R8,ElementNames:()=>E,ElementProperties:()=>y,ElementType:()=>Qg,EntityAttributeProperty:()=>Xg,EventType:()=>cu,FormActivationState:()=>t0,FormCanvasServiceScope:()=>j8,FormDesignerSideBarTab:()=>Yg,FormPresentation:()=>Zg,FormState:()=>Yd,FormType:()=>gt,HeaderDensityType:()=>ho,LookUpTable:()=>Zn,MORE_TAB_PREFIX:()=>x8,NavBarChildElementType:()=>e0,PREVIEW_ID_HEADER_FLYOUT:()=>B8,PREVIEW_ID_HEADER_OVERFLOW_BUTTON:()=>V8,PREVIEW_ID_NAVIGATION_AREA:()=>M8,PREVIEW_ID_QUICKCREATE_ROOT:()=>W8,PREVIEW_ID_TAB:()=>G8,PREVIEW_ID_TAB_LIST:()=>q8,PREVIEW_ID_TAB_PANEL:()=>U8,PropertyModelKeys:()=>o0,PropertyModelSectionKeys:()=>$8,RELATED_TAB_ID:()=>a0,RELATED_TAB_PREFIX:()=>F8,SectionDefaultProperties:()=>k8,SectionLayoutTypes:()=>je,TabContentType:()=>n0,TabDefaultProperties:()=>go,TabLayoutTypes:()=>ze,TelemetryPropertyNames:()=>z8,UnboundControlPropertyKeys:()=>i0,compositeAddressFields:()=>P8,compositeFieldNames:()=>zr,compositeFields:()=>O8});var gt,Jg,Yg,E,y,Qg,zr,O8,P8,Xg,Zn,Yd,ho,Zg,R8,e0,t0,ze,k8,go,je,r0,n0,L8,i0,o0,$8,cu,ln,a0,x8,F8,M8,U8,B8,q8,V8,G8,W8,z8,Qd,j8,ue=L(()=>{"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"})(gt||(gt={}));(function(e){e[e.Form=0]="Form",e[e.Dialog=1]="Dialog"})(Jg||(Jg={}));(function(e){e[e.Components=0]="Components",e[e.Properties=1]="Properties",e[e.Relationship=2]="Relationship",e[e.BusinessRules=3]="BusinessRules"})(Yg||(Yg={}));(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"})(E||(E={}));y={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"})(Qg||(Qg={}));zr={fullname:"fullname",yomifullname:"yomifullname",address1_composite:"address1_composite",address2_composite:"address2_composite",address3_composite:"address3_composite",billto:"billto_composite",shipto:"shipto_composite"},O8=[zr.fullname,zr.yomifullname,zr.address1_composite,zr.address2_composite,zr.address3_composite,zr.billto,zr.shipto],P8=[zr.address1_composite,zr.address2_composite,zr.address3_composite,zr.billto,zr.shipto];(function(e){e[e.IsValidForForm=0]="IsValidForForm",e[e.IsValidForCreate=1]="IsValidForCreate"})(Xg||(Xg={}));(function(e){e[e.DependencyFieldTable=0]="DependencyFieldTable",e[e.LockedFieldTable=1]="LockedFieldTable"})(Zn||(Zn={}));(function(e){e[e.Published=0]="Published",e[e.Draft=1]="Draft",e[e.New=2]="New",e[e.SaveAs=3]="SaveAs"})(Yd||(Yd={}));(function(e){e.Low="Low",e.HighReadOnlyValues="HighReadOnlyValues",e.HighWithControls="HighWithControls"})(ho||(ho={}));(function(e){e[e.ClassicForm=0]="ClassicForm",e[e.AirForm=1]="AirForm",e[e.ConvertedICForm=2]="ConvertedICForm"})(Zg||(Zg={}));R8={TopOrderFormId:"topOrderFormId",NextDisplayOrder:"nextDisplayOrder"};(function(e){e[e.NavBarRelationShipItem=0]="NavBarRelationShipItem",e[e.NavBarItem=1]="NavBarItem"})(e0||(e0={}));(function(e){e[e.InActive=0]="InActive",e[e.Active=1]="Active"})(t0||(t0={}));(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"})(ze||(ze={}));k8={ShowLabel:"false",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_"},go={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"})(je||(je={}));(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"})(r0||(r0={}));(function(e){e.cardSections="cardSections",e.singleComponent="singleComponent",e.default="default",e.expandAvailableSpace="expandAvailableSpace"})(n0||(n0={}));L8={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"})(i0||(i0={}));(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"})(o0||(o0={}));$8={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"})(cu||(cu={}));(function(e){e.All="All",e.Chart="Chart",e.Grid="Grid"})(ln||(ln={}));a0="tab_related3b554255-7717-4d17-bb7f-9936fb1e75ca",x8="more_tab_",F8="related_tab_",M8="preview_id_navigation_area",U8="tab-section",B8="headerFieldsFlyout",q8="tablist",V8="header_overflowButton",G8="tab",W8="quickCreateRoot",z8={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"})(Qd||(Qd={}));j8="CellCanvasServiceScope"});var S_={};Jr(S_,{Attribute:()=>Xd,FormElementNode:()=>re});var Xd,re,It=L(()=>{"use strict";st();Xt();Kg();ue();ht();Xd=class{key;value;constructor(t,r){this.key=t,this.value=r}},re=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-${U.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(E.form);r&&r.raiseMetadataChange(t)}trackPropertyAddition(t,r){this.trackPropertyCollectionChange(()=>{this.properties.push(new Xd(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 ia(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 ia(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 ia(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 Kd(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 ia(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){R.IsNullOrUndefined(t)||(t.trackParentNodeChange(()=>{t.parentNode=this}),this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(r,0,t)}))}moveChild(t,r){let n=this.childrenNodes.indexOf(t);if(n<0)return!1;let i=Math.min(Math.max(0,n+r),this.childrenNodes.length-1);return n!==i&&this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(i,0,this.childrenNodes.splice(n,1)[0])}),!0}getChildren(t){let r=[];for(let n of this.childrenNodes)n.nodeName===t&&r.push(n);return r}getFirstChild(t){for(let r of this.childrenNodes)if(r.nodeName===t)return r;return null}getAllGrandChildren(t){let r=this.getChildren(t),n=null;return r.length===0?new Array:(n=r[0],n.childrenNodes)}deleteChild(t){if(R.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:q.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=R.IsNullOrUndefined(r)?this.childrenNodes.length:r,this.trackChildrenCollectionChange(()=>{this.childrenNodes.splice(t,r)})}deleteGrandChildren(t,r,n){this.getChildren(t)[0].deleteChildren(r,n)}addGrandChild(t,r){let n=this.getChildren(t),i=null;n.length===0?(i=new e(t,this),this.addChild(i)):i=n[0],i.addChild(r)}addGrandChildAtIndex(t,r,n){let i=this.getChildren(t),o=null;i.length===0?(o=new e(t,this),this.addChild(o)):o=i[0],o.insertChildAtIndex(r,n)}GetPropertyByParameter(t){return this.getProperty(t)}getSemanticParent(){switch(this.getNodeName()){case E.formCell:let t=this.getAncestor(E.formSection);return t||(t=this.getAncestor(E.formHeader),t)||(t=this.getAncestor(E.formFooter),t)?t:null;case E.formSection:return this.getAncestor(E.formTab);case E.formTab:return this.getAncestor(E.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(E.form);return t?t.changeTracker():null}}});var N_={};Jr(N_,{ControlClassId:()=>N,ControlNamePrefixes:()=>Zd,getControlDisplayNames:()=>H8});function H8(e){return{[N.AccessPrivilegeControl]:e("controls.controlNames.accessPrivilege"),[N.AccessTeamTablePickerControl]:e("controls.controlNames.accessTeamTablePicker"),[N.ACIControl]:e("controls.controlNames.aci"),[N.ActivitiesContainerControl]:e("controls.controlNames.activitiesContainer"),[N.ActivitiesWallControl]:e("controls.controlNames.activitiesWall"),[N.AppliedFiltersControl]:e("controls.controlNames.appliedFilters"),[N.ArticleContentControl]:e("controls.controlNames.articleContent"),[N.BooleanControl]:e("controls.controlNames.twoOption"),[N.ButtonControl]:e("controls.controlNames.button"),[N.CheckboxControl]:e("controls.controlNames.checkbox"),[N.CompositionLinkControl]:e("controls.controlNames.compositionLink"),[N.ConnectionControl]:e("controls.controlNames.connection"),[N.ConnectionRoleObjectTypeListControl]:e("controls.controlNames.connectionRoleObjectTypeList"),[N.CoverageChoiceControl]:e("controls.controlNames.coverageChoice"),[N.DashboardControl]:e("controls.controlNames.dashboard"),[N.DynamicPropertyListControl]:e("controls.controlNames.dynamicPropertyList"),[N.EditFilterControl]:e("controls.controlNames.editFilter"),[N.ErrorStatusControl]:e("controls.controlNames.errorStatus"),[N.GlobalFilterControl]:e("controls.controlNames.globalFilter"),[N.HiddenInputControl]:e("controls.controlNames.hiddenInput"),[N.KBViewerControl]:e("controls.controlNames.kbViewer"),[N.LabelControl]:e("controls.controlNames.label"),[N.MailMergeLanguagePickerControl]:e("controls.controlNames.mailMergeLanguagePicker"),[N.MapLinkControl]:e("controls.controlNames.mapLink"),[N.OrgInsightsControl]:e("controls.controlNames.orgInsights"),[N.ChoiceLookupControl]:e("controls.controlNames.choiceLookup"),[N.PowerBIControl]:e("controls.controlNames.powerBI"),[N.ProcessControl]:e("controls.controlNames.process"),[N.RelatedInformationControl]:e("controls.controlNames.relatedInformation"),[N.RelationshipRoleChoiceControl]:e("controls.controlNames.relationshipRoleChoice"),[N.ReportControl]:e("controls.controlNames.report"),[N.StreamsControl]:e("controls.controlNames.streams"),[N.WebResourceSilverlightControl]:e("controls.controlNames.webResourceSilverlight"),[N.CurrencyControl]:e("controls.controlNames.currency"),[N.DateTimeControl]:e("controls.controlNames.dateAndTime"),[N.DecimalControl]:e("controls.controlNames.decimal"),[N.DurationControl]:e("controls.controlNames.duration"),[N.EmailAddressControl]:e("controls.controlNames.email"),[N.FileControl]:e("controls.controlNames.file"),[N.FloatingNumberControl]:e("controls.controlNames.floatingNumber"),[N.IframeControl]:e("controls.controlNames.iframe"),[N.ImageControl]:e("controls.controlNames.image"),[N.LookupControl]:e("controls.controlNames.lookup"),[N.MapsControl]:e("controls.controlNames.maps"),[N.PhoneNumberControl]:e("controls.controlNames.phoneNumber"),[N.ChoiceControl]:e("controls.controlNames.choice"),[N.QuickViewControl]:e("controls.controlNames.quickView"),[N.QuickFormControl]:e("controls.controlNames.quickForm"),[N.CustomControl]:e("controls.controlNames.customControl"),[N.SearchWidgetControl]:e("controls.controlNames.searchWidget"),[N.SocialInsightsControl]:e("controls.controlNames.socialInsights"),[N.SubgridControl]:e("controls.controlNames.subgrid"),[N.TextAreaControl]:e("controls.controlNames.textArea"),[N.TextboxControl]:e("controls.controlNames.textBox"),[N.TickerControl]:e("controls.controlNames.ticker"),[N.UrlControl]:e("controls.controlNames.url"),[N.WebResourceHTMLControl]:e("controls.controlNames.webResourceHTML"),[N.WebResourceImageControl]:e("controls.controlNames.webResourceImage"),[N.IntegerControl]:e("controls.controlNames.integer"),[N.TimerControl]:e("controls.controlNames.timer"),[N.TimelineControl]:e("controls.controlNames.timeline"),[N.EmailBodyControl]:e("controls.controlNames.emailBody"),[N.PartyListControl]:e("controls.controlNames.partyList"),[N.TimezoneControl]:e("controls.controlNames.timezone"),[N.LanguageControl]:e("controls.controlNames.language"),[N.ChoiceStatusControl]:e("controls.controlNames.choiceStatus"),[N.ChoicesControl]:e("controls.controlNames.choices"),[N.RegardingControl]:e("controls.controlNames.regarding"),[N.EmailEngagementActionsControl]:e("controls.controlNames.emailEngagementActions"),[N.EmailRecipientActivityControl]:e("controls.controlNames.emailRecipientActivity"),[N.ReferencePanelSearchWidgetControl]:e("controls.controlNames.referencePanelSearchWidget"),[N.ReferencePanelQuickViewControl]:e("controls.controlNames.referencePanelQuickView"),[N.ReferencePanelSubgridControl]:e("controls.controlNames.referencePanelSubgrid"),[N.KBEditorControl]:e("controls.controlNames.KBEditor"),[N.LinkControl]:e("controls.controlNames.link")}}var N,Zd,oa=L(()=>{"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"})(N||(N={}));Zd={[N.WebResourceHTMLControl]:"WebResource",[N.WebResourceImageControl]:"WebResource",[N.IframeControl]:"IFRAME",[N.SearchWidgetControl]:"Search widget",[N.SubgridControl]:"Subgrid",[N.TimelineControl]:"Timeline",[N.QuickViewControl]:"QuickviewControl"}});var aa=v((Ble,T_)=>{var du=new Proxy(function(){return du},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:du},apply:function(){return du},construct:function(){return{}}}),__=function(){return du};Object.setPrototypeOf(__,du);T_.exports=__});var cr,Ri,D_,I_,ws=L(()=>{"use strict";cr="cds-designer-models",Ri="FormCustomControl",D_="FormCell",I_="Form"});var sa,s0=L(()=>{"use strict";Wl();ue();sa=class e{static lockedFieldCount=new ar;static dependencyFieldCount=new ar;static getNecessaryLookUpTable(t){switch(t){case Zn.DependencyFieldTable:return e.dependencyFieldCount;case Zn.LockedFieldTable:return e.lockedFieldCount}}static initCanvasLockedFieldLookUp(t){switch(t){case Zn.DependencyFieldTable:e.dependencyFieldCount=new ar;case Zn.LockedFieldTable:e.lockedFieldCount=new ar}}}});var ef,O_=L(()=>{"use strict";ht();st();ue();It();ef=class extends re{constructor(t){super(E.controlDescription,t)}get forControl(){let t=this.getProperty(y.ForControl);return R.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set forControl(t){this.setProperty(y.ForControl,`{${t.ToString()}}`)}get customControls(){return this.getChildren(E.customControl)}set customControls(t){this.deleteAllChildren();for(let r of t)this.addChild(r)}get DefaultControlClassId(){for(let t of this.customControls)if(!R.IsNullOrUndefined(t.id))return t.id;return null}get DefaultCustomControl(){for(let t of this.customControls)if(!R.IsNullOrUndefined(t.id))return t;return null}get DefaultCustomControls(){let t=[];for(let r of this.customControls)R.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}}});function ki(){return ei||(ei=window._makerConfig,ei&&window?.location?.search?.indexOf("useProductionConfig")>-1&&(ei={...ei,region:"prod",graphQLEndpoint:"https://graph.make.powerapps.com/"}),ei?.region==="prod"&&(ei={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/"}}},...ei}),ei||{aadClientId:"a8f7a65c-f5ba-4859-b2d6-df772c264e9d",location:"cus",region:"test",publicPath:"/",graphQLEndpoint:"https://graph.make.test.powerapps.com/"})}var ei,tf=L(()=>{"use strict";});function P_(e,t,r){if(!e)return rf.has(e)||(window._ppux?.log?.("PPUX/Geo/NonExistent",{eventType:"Trace",team:"Shell",severity:"Error",errorCode:"GeoIsEmpty"}),rf.add("")),!1;if(e){if(e=e.toLowerCase(),rf.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}}),rf.add(e),!1}return!0}function K8(e){return P_(e,l0,"Location dictionary")?l0[e.toLowerCase()]:"us"}function J8(){let e=ki().location.toLowerCase();return P_(e,l0,"Current location dictionary")?e:"us"}var rf,l0,Zle,R_=L(()=>{"use strict";tf();rf=new Set,l0={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"};Zle=K8(J8())});var Y,tue,k_=L(()=>{"use strict";Y={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"},tue={[Y.USWest]:{geoName:"us",regionShortName:"wus"},[Y.USCentral]:{geoName:"us",regionShortName:"cus"},[Y.USEast]:{geoName:"us",regionShortName:"eus"},[Y.USEast2]:{geoName:"us",regionShortName:"eus2"},[Y.USWestCentral]:{geoName:"us",regionShortName:"wcus"},[Y.USWest2]:{geoName:"us",regionShortName:"wus2"},[Y.USSouthCentral]:{geoName:"br",regionShortName:"scus"},[Y.BrazilSouth]:{geoName:"br",regionShortName:"sbr"},[Y.UKSouth]:{geoName:"uk",regionShortName:"suk"},[Y.UKWest]:{geoName:"uk",regionShortName:"wuk"},[Y.JapanEast]:{geoName:"jp",regionShortName:"ejp"},[Y.JapanWest]:{geoName:"jp",regionShortName:"wjp"},[Y.IndiaCentral]:{geoName:"in",regionShortName:"cin"},[Y.IndiaSouth]:{geoName:"in",regionShortName:"sin"},[Y.ItalyNorth]:{geoName:"it",regionShortName:"nit"},[Y.GermanyWestCentral]:{geoName:"de",regionShortName:"wcde"},[Y.GermanyNorth]:{geoName:"de",regionShortName:"nde"},[Y.EuropeNorth]:{geoName:"eu",regionShortName:"neu"},[Y.EuropeWest]:{geoName:"eu",regionShortName:"weu"},[Y.AustraliaEast]:{geoName:"au",regionShortName:"eau"},[Y.AustraliaSouthEast]:{geoName:"au",regionShortName:"seau"},[Y.AsiaSouthEast]:{geoName:"as",regionShortName:"seas"},[Y.AsiaEast]:{geoName:"as",regionShortName:"eas"},[Y.CanadaCentral]:{geoName:"ca",regionShortName:"cca"},[Y.CanadaEast]:{geoName:"ca",regionShortName:"eca"},[Y.SouthAfricaNorth]:{geoName:"za",regionShortName:"nza"},[Y.SouthAfricaWest]:{geoName:"za",regionShortName:"wza"},[Y.FranceCentral]:{geoName:"fr",regionShortName:"cfr"},[Y.FranceSouth]:{geoName:"fr",regionShortName:"sfr"},[Y.UAENorth]:{geoName:"ae",regionShortName:"nae"},[Y.UAECentral]:{geoName:"ae",regionShortName:"cae"},[Y.SwedenCentral]:{geoName:"se",regionShortName:"cse"},[Y.SwitzerlandNorth]:{geoName:"ch",regionShortName:"nch"},[Y.SwitzerlandWest]:{geoName:"ch",regionShortName:"wch"},[Y.NorwayEast]:{geoName:"no",regionShortName:"eno"},[Y.NorwayWest]:{geoName:"no",regionShortName:"wno"},[Y.KoreaCentral]:{geoName:"kr",regionShortName:"ckr"},[Y.KoreaSouth]:{geoName:"kr",regionShortName:"skr"},[Y.SingaporeSouthEast]:{geoName:"sg",regionShortName:"seas"},[Y.PolandCentral]:{geoName:"pl",regionShortName:"cpl"},[Y.QatarCentral]:{geoName:"qa",regionShortName:"cqa"},[Y.NewZealandNorth]:{geoName:"nz",regionShortName:"nnz"},[Y.GovernmentUSTexas]:{geoName:"us",regionShortName:"ugtx"},[Y.GovernmentUSVirginia]:{geoName:"us",regionShortName:"ugva"},[Y.GovernmentUSDodCentral]:{regionShortName:"udc"},[Y.GovernmentUSDodEast]:{regionShortName:"ude"},[Y.ChinaEast]:{regionShortName:"cne"},[Y.ChinaEast2]:{regionShortName:"cne2"},[Y.ChinaEast3]:{regionShortName:"cne3"},[Y.ChinaNorth]:{regionShortName:"cnn"},[Y.ChinaNorth2]:{regionShortName:"cnn2"},[Y.ChinaNorth3]:{regionShortName:"cnn3"},[Y.UssecEast]:{geoName:"us",regionShortName:"erx"},[Y.UssecWest]:{geoName:"us",regionShortName:"wrx"},[Y.UsnatEast]:{geoName:"us",regionShortName:"eex"},[Y.UsnatWest]:{geoName:"us",regionShortName:"wex"}}});var L_=L(()=>{"use strict";tf();});var fu=L(()=>{"use strict";tf();R_();k_();L_();});function pu(e,t){return $_?$_.isOverridden(e,t):{overridden:!1}}var $_,mu=L(()=>{"use strict";});var u0=L(()=>{"use strict";fu();mu();});function Y8(e,t){let{region:r}=ki();return()=>{let n=e.settings[t];if(n.allowOverrides){let s=pu(e.packageName,t);if(s.overridden)return typeof s.value=="string"?Q8(s.value):s.value}let o=n.values,a=process.env.SETTINGS_FALLBACK_REGION?.[r];return o[r]!==void 0?o[r]:a&&o[a]!==void 0?o[a]:o.default}}function Q8(e){return isNaN(Number(e))?e==="true"?!0:e==="false"?!1:e:Number(e)}function X8(e){let t=e.packageName;if(nf.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=>d0(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=>!af(i))){let i=`error parsing settings config for package ${t}, setting ${r} has invalid region`;throw console.error(i),new Error(i)}})}function hu(e){X8(e);let t={};return Object.keys(e.settings).forEach(r=>{t[r]={enumerable:!0,get:Y8(e,r)}}),nf.set(e.packageName,e),Object.defineProperties({},t)}function c0(e,t){return nf.has(e)?!!nf.get(e).settings[t]:!1}var nf,of=L(()=>{"use strict";fu();mu();f0();gu();nf=new Map});function x_(e,t){let{region:r}=ki();return()=>{let n=pu(e.packageName,t);if(n.overridden)return n.value.toString()==="true";let i=e.features[t].enabledFor,o=process.env.SETTINGS_FALLBACK_REGION?.[r];return i[r]!==void 0?!!i[r]:o&&i[o]!==void 0?!!i[o]:!1}}function Z8(e){let t=e.packageName;if(sf.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=>c0(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=>!af(i))){let i=`error parsing feature gates config for package ${t}, feature ${r} has invalid region`;throw console.error(i),new Error(i)}})}function p0(e){Z8(e);let t={};Object.keys(e.features).forEach(i=>{t[i]={enumerable:!0,configurable:!0,get:x_(e,i)}});let r={},n=new Set;return t.dangerouslySet={enumerable:!1,value:(i,o)=>{n.add(i),Object.defineProperty(r,i,{enumerable:!0,configurable:!0,value:o})}},t.dangerouslyReset={enumerable:!1,value:()=>{let i={};n.forEach(o=>{i[o.toString()]={enumerable:!0,configurable:!0,get:x_(e,o.toString())}}),Object.defineProperties(r,i),n.clear()}},sf.set(e.packageName,e),Object.defineProperties(r,t)}function d0(e,t){return sf.has(e)?!!sf.get(e).features[t]:!1}var sf,f0=L(()=>{"use strict";fu();gu();mu();of();sf=new Map});var M_=v((_ue,F_)=>{"use strict";F_.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 q_=v(m0=>{"use strict";var e6=Object.prototype.hasOwnProperty,t6;function U_(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch{return null}}function B_(e){try{return encodeURIComponent(e)}catch{return null}}function r6(e){for(var t=/([^=?#&]+)=?([^&]*)/g,r={},n;n=t.exec(e);){var i=U_(n[1]),o=U_(n[2]);i===null||o===null||i in r||(r[i]=o)}return r}function n6(e,t){t=t||"";var r=[],n,i;typeof t!="string"&&(t="?");for(i in e)if(e6.call(e,i)){if(n=e[i],!n&&(n===null||n===t6||isNaN(n))&&(n=""),i=B_(i),n=B_(n),i===null||n===null)continue;r.push(i+"="+n)}return r.length?t+r.join("&"):""}m0.stringify=n6;m0.parse=r6});var y0=v((Due,H_)=>{"use strict";var G_=M_(),lf=q_(),W_=/[\n\r\t]/g,i6=/^[A-Za-z][A-Za-z0-9+-.]*:\/\//,o6=/^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i,a6=/^[a-zA-Z]:/,s6=/^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;function g0(e){return(e||"").toString().replace(s6,"")}var h0=[["#","hash"],["?","query"],function(t,r){return ti(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]],V_={hash:1,query:1};function z_(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,o;if(e.protocol==="blob:")n=new ri(unescape(e.pathname),{});else if(i==="string"){n=new ri(e,{});for(o in V_)delete n[o]}else if(i==="object"){for(o in e)o in V_||(n[o]=e[o]);n.slashes===void 0&&(n.slashes=i6.test(e.href))}return n}function ti(e){return e==="file:"||e==="ftp:"||e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function j_(e,t){e=g0(e),e=e.replace(W_,""),t=t||{};var r=o6.exec(e),n=r[1]?r[1].toLowerCase():"",i=!!r[2],o=!!r[3],a=0,s;return i?o?(s=r[2]+r[3]+r[4],a=r[2].length+r[3].length):(s=r[2]+r[4],a=r[2].length):o?(s=r[3]+r[4],a=r[3].length):s=r[4],n==="file:"?a>=2&&(s=s.slice(2)):ti(n)?s=r[4]:n?i&&(s=s.slice(2)):a>=2&&ti(t.protocol)&&(s=r[4]),{protocol:n,slashes:i||ti(n),slashesCount:a,rest:s}}function l6(e,t){if(e==="")return t;for(var r=(t||"/").split("/").slice(0,-1).concat(e.split("/")),n=r.length,i=r[n-1],o=!1,a=0;n--;)r[n]==="."?r.splice(n,1):r[n]===".."?(r.splice(n,1),a++):a&&(n===0&&(o=!0),r.splice(n,1),a--);return o&&r.unshift(""),(i==="."||i==="..")&&r.push(""),r.join("/")}function ri(e,t,r){if(e=g0(e),e=e.replace(W_,""),!(this instanceof ri))return new ri(e,t,r);var n,i,o,a,s,l,u=h0.slice(),c=typeof t,d=this,f=0;for(c!=="object"&&c!=="string"&&(r=t,t=null),r&&typeof r!="function"&&(r=lf.parse),t=z_(t),i=j_(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||a6.test(e))||!i.slashes&&(i.protocol||i.slashesCount<2||!ti(d.protocol)))&&(u[3]=[/(.*)/,"pathname"]);f<u.length;f++){if(a=u[f],typeof a=="function"){e=a(e,d);continue}o=a[0],l=a[1],o!==o?d[l]=e:typeof o=="string"?(s=o==="@"?e.lastIndexOf(o):e.indexOf(o),~s&&(typeof a[2]=="number"?(d[l]=e.slice(0,s),e=e.slice(s+a[2])):(d[l]=e.slice(s),e=e.slice(0,s)))):(s=o.exec(e))&&(d[l]=s[1],e=e.slice(0,s.index)),d[l]=d[l]||n&&a[3]&&t[l]||"",a[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=l6(d.pathname,t.pathname)),d.pathname.charAt(0)!=="/"&&ti(d.protocol)&&(d.pathname="/"+d.pathname),G_(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:"&&ti(d.protocol)&&d.host?d.protocol+"//"+d.host:"null",d.href=d.toString()}function u6(e,t,r){var n=this;switch(e){case"query":typeof t=="string"&&t.length&&(t=(r||lf.parse)(t)),n[e]=t;break;case"port":n[e]=t,G_(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 o=t.indexOf(":");~o?(n.username=t.slice(0,o),n.username=encodeURIComponent(decodeURIComponent(n.username)),n.password=t.slice(o+1),n.password=encodeURIComponent(decodeURIComponent(n.password))):n.username=encodeURIComponent(decodeURIComponent(t))}for(var a=0;a<h0.length;a++){var s=h0[a];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:"&&ti(n.protocol)&&n.host?n.protocol+"//"+n.host:"null",n.href=n.toString(),n}function c6(e){(!e||typeof e!="function")&&(e=lf.stringify);var t,r=this,n=r.host,i=r.protocol;i&&i.charAt(i.length-1)!==":"&&(i+=":");var o=i+(r.protocol&&r.slashes||ti(r.protocol)?"//":"");return r.username?(o+=r.username,r.password&&(o+=":"+r.password),o+="@"):r.password?(o+=":"+r.password,o+="@"):r.protocol!=="file:"&&ti(r.protocol)&&!n&&r.pathname!=="/"&&(o+="@"),n[n.length-1]===":"&&(n+=":"),o+=n+r.pathname,t=typeof r.query=="object"?e(r.query):r.query,t&&(o+=t.charAt(0)!=="?"?"?"+t:t),r.hash&&(o+=r.hash),o}ri.prototype={set:u6,toString:c6};ri.extractProtocol=j_;ri.location=z_;ri.trimLeft=g0;ri.qs=lf;H_.exports=ri});var d6,K_=L(()=>{"use strict";d6=Ae(y0());});function b0(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 uf=L(()=>{"use strict";});var v0,w0,C0=L(()=>{"use strict";uf();v0=class{features=new Map;register(t,r){let n=b0(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()}},w0=new v0});var E0=L(()=>{"use strict";});function af(e){return f6.has(e)}var f6,gu=L(()=>{"use strict";u0();f0();of();mu();u0();K_();C0();uf();E0();f6=new Set(["tie","test","prod","preview","preprod","gov","high","dod","mooncake","ex","rx"])});var p6,J_=L(()=>{"use strict";gu();p6=hu({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 Z_,S0,Cs,la,A0,cf,Es,Li,Ue,Y_,Q_,X_,Tn=L(()=>{"use strict";Z_={ThreeEqColumn_FirstColumn:34,ThreeEqColumn_SecondColumn:33,ThreeEqColumn_ThirdColumn:33,FiveEqColumn:20},S0={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"})(Cs||(Cs={}));(function(e){e.Left="Left",e.Right="Right",e.Center="Center"})(la||(la={}));(function(e){e[e.Mobile=0]="Mobile",e[e.Tablet=1]="Tablet",e[e.Web=2]="Web"})(A0||(A0={}));cf=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"})(Es||(Es={}));Li=class{static StartTag="<"},Ue={ShowLabel:"true",LockLevel:"0",IsUserDefined:"0",LabelWidth:"115",columns:"1",ShowBar:"false",Layout:"varwidth",namePrefix:"_section_",labelAlignment:la.Left,labelPosition:Es.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"})(Y_||(Y_={}));(function(e){e.TabWithLockedFieldRemoval="TabWithLockedFieldRemoval",e.SectionWithLockedFieldRemoval="SectionWithLockedFieldRemoval",e.LockedSectionRemoval="LockedSectionRemoval",e.LockedFieldRemoval="LockedFieldRemoval",e.RequiredFieldRemoval="RequiredFieldRemoval",e.LastRemainingTab="LastRemainingTab",e.UnknownRemoval="UnknownRemoval"})(Q_||(Q_={}));(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"})(X_||(X_={}))});var N0,eT=L(()=>{"use strict";(function(e){e.DefaultValue="defaultValue",e.Loaded="loaded"})(N0||(N0={}))});var nT,m6,tT,Ace,Sce,yu,rT,Nce,_ce,iT=L(()=>{"use strict";nT=Ae(aa());st();ws();J_();os();Tn();Ho();ue();m6=Ae(Qi());eT();(function(e){e.Model="Model",e.Canvas="Canvas",e.CustomPages="CustomPages"})(tT||(tT={}));Ace={Read:io.Read,Edit:io.Edit,Both:io.Both,Container:io.Container},Sce={input:jo.Input,bound:jo.Bound,output:jo.Output};(function(e){e[e.dataset=0]="dataset",e[e.property=1]="property",e[e.groups=2]="groups",e[e.group=3]="group"})(yu||(yu={}));(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"})(rT||(rT={}));Nce=new Set([F.Currency,F.Decimal,F.FP,F.Multiple,F.SingleLineEmail,F.SingleLinePhone,F.SingleLineText,F.SingleLineTextArea,F.SingleLineURL,F.SingleLineTickerSymbol,F.WholeNone,F.WholeDuration,F.WholeLanguage,F.WholeTimeZone,F.Enum,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.TwoOptions,F.Boolean,F.PowerBIReport,F.DateAndTimeDateAndTime,F.DateAndTimeDateOnly,F.OptionSet,F.MultiSelectOptionSet,F.CardForm]),_ce={numbers:[F.WholeNone,F.FP,F.Decimal,F.Currency],text:[F.SingleLineText,F.SingleLineTextArea,F.Multiple],lookup:[F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding],dates:[F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime],allFields:[F.TwoOptions,F.DateAndTimeDateOnly,F.DateAndTimeDateAndTime,F.FP,F.Decimal,F.WholeNone,F.WholeDuration,F.WholeTimeZone,F.WholeLanguage,F.LookupSimple,F.LookupCustomer,F.LookupOwner,F.LookupPartyList,F.LookupRegarding,F.Multiple,F.OptionSet,F.SingleLineText,F.SingleLineTextArea,F.SingleLineEmail,F.SingleLineURL,F.SingleLineTickerSymbol,F.SingleLinePhone]}});var Dn,df,oT=L(()=>{"use strict";Dn=Ae(aa());ht();st();Xt();ws();Ho();iT();os();ue();It();Tn();df=class extends re{constructor(t){super(E.customControl,t)}customControlId;get id(){let t=this.getProperty(y.id);return R.IsNullOrUndefined(t)?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(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 o=i.getNodeName();t.get(o)?t.get(o).push(i):t.set(o,[i])}}}return t}getFormComponentValueByParameterName(t){let r=this.getParameters()?.get(Ht.value);if(r?.length>0){let n=r[0],i=n?.getAllChildren()?.length>0?n.getAllChildren().find(a=>a.getNodeName()===t):null,o=i?.getAllChildren()?.length>0?i.getAllChildren()[0].getNodeName():"";return this.normalizePropertyValue(o)}}getParameterValue(t){let r=this.getParameterNodeChild(t);return r&&this.normalizePropertyValue(r.getNodeName())}getParameterNodeChild(t){let r=this.getParameters().get(t);return r?.length>0&&r[0].getAllChildren()?.length>0?r[0].getAllChildren()[0]:null}getDatasetName(t){return t.getAllProperties().find(r=>r.key===Ht.name)?.value}getParameterChildrenValues(t,r,n){if(this.isDataSet(t)){let i=r.find(u=>u.key===Ht.name)?.value,o={Name:i,Type:F.Grid,Columns:[]},l=this.getParameters().get(Ht.dataset).find(u=>this.getDatasetName(u)===i).getAllChildren();for(let u of l){let c=u.getNodeName();if(u&&u.getAllChildren().length>0){let d=this.normalizePropertyValue(u.getAllChildren()[0].getNodeName());o[c]=d}}return o}}getParameterIsStatic(t){let r=!1,n=this.getParameters().get(t)[0],i=n&&n.getAllProperties();if(i){for(let o of i)if(o.key===y.static&&o.value==="true"){r=!0;break}}return r}get name(){return this.getProperty(y.Name)}get formFactor(){return this.getProperty(y.formFactor)}set formFactor(t){this.setProperty(y.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(Li.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,o=this.getParameters();for(let[a,s]of o)if(this.isDataSet(a))for(let l of o.get(a)){let u=l.getAllProperties(),c=this.getDatasetName(l),d=i.get(c),f=await this.parameterJSON(a,u,d,t);r.push({Name:c,Value:f})}else if(this.isGroups(s))r.push({Name:a,Value:{Type:qh.GroupDefinition,Value:this.normalizePropertyValue(this.getParameterNodeChild(s[0].NodeName).NodeName)}}),i.get(a).groupSet?.forEach(u=>{u.groupConfigurableProperties.forEach(async c=>{let d=c.name;c.propertyType===yu.dataset?o.get(Ht.dataset)?.some(m=>this.getDatasetName(m)===d)||r.push({Name:d,Value:{Name:d,Columns:[],Type:F.Grid}}):c.propertyType===yu.property&&(o.has(d)||r.push({Name:d,Value:{Usage:c.usage}}))})});else{let l=s[0].getAllProperties(),u=i.get(a),c=await this.parameterJSON(a,l,u,t);if(c)r.push({Name:a,Value:c});else{(0,Dn.trackInfoTrace)(cr,{eventName:`${Ri}/parametersToJSON`,eventData:{message:`Configuration metadata for custom control parameter ${a} is not available for custom control : ${this.name}.`}}),r=[];break}}}else(0,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/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,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/parametersToJSON`,eventData:{message:"Custom Control Manifest not found"}},new Error(`No custom control manifest found for ${this.name}`))}catch(n){(0,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/parametersToJSON`,eventData:{message:"parameters to json failed"}},n)}return r}async parameterJSON(t,r,n,i){if(this.isDataSet(t)){let o=n,a=r.find(s=>s.key===Ht.name)?.value;if(o)return this.getParameterChildrenValues(t,r);{let s=new Error(`No dataset manifest info for ${a}`);(0,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/parameterJSON`,eventData:{message:"Missing custom control manifest dataset info"}},s)}}else{let o=n,a=r&&r.find(l=>l.key===y.Type),s=o&&!o.ofTypeGroup.every(l=>!fd.includes(l));if(this.isLookupType(a?.value)||this.isLookupType(o?.ofType)||s)if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=o.isPrimary;if(this.name===Ti.FormComponent){let d=this.getFormComponentValueByParameterName(y.bindAttribute),f=await i.formModelService.loadLookupModel(d),m=f.lookupColumn,p=this.getLookupDataTypeFromAttributeMetadata(m);return{Name:t,Type:p,Usage:l,Static:u,Primary:c,EntityName:f.primaryTableName,Value:d,ViewId:this.getFormComponentValueByParameterName(Bh.DefaultViewId),TargetEntityType:m.targets[0],FilterRelationshipName:this.getFormComponentValueByParameterName(y.FilterRelationshipName),AvailableViewIds:this.getFormComponentValueByParameterName(y.AvailableViewIds),DependentAttributeName:this.getFormComponentValueByParameterName(y.DependentAttributeName),DependentAttributeType:this.getFormComponentValueByParameterName(y.DependentAttributeType),AllowFilterOff:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.AllowFilterOff)),DisableQuickFind:q.IsStrictTrue(this.getFormComponentValueByParameterName(y.DisableQuickFind)),EnableViewPicker:!q.IsStrictTrue(this.getFormComponentValueByParameterName(y.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,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/parameterJSON`,eventData:{message:"Missing custom control manifest lookup property info"}},l)}if(o){let l=o.usage,u=this.getParameterIsStatic(t),c=this.getParameterValue(t),d=o.isPrimary;if(a){let m=a.value;return{Type:m,Static:u,Usage:l,Value:this.isNumberTypeProperty(o,m)&&Number(c)?Number(c):c,Primary:d}}if(o.ofType)return{Type:o.ofType,Static:u,Usage:l,Value:c,Primary:!0};if(o.ofTypeGroup)return{Static:u,Usage:l,Value:c,Primary:!0};let f=new Error(`No property type info for ${t}`);(0,Dn.trackErrorTrace)(cr,{eventName:`${Ri}/parameterJSON`,eventData:{message:"Missing property type info"}},f)}else{let l=new Error(`No property manifest info for ${t}`);(0,Dn.trackWarningTrace)(cr,{eventName:`${Ri}/parameterJSON`,eventData:{message:"Missing custom control manifest property info"}},l)}}return null}getLookupDataTypeFromAttributeMetadata(t){let{attributeType:r,format:n}=t;switch(r){case $.Customer:return F.LookupCustomer;case $.Owner:return F.LookupOwner;case $.PartyList:return F.LookupPartyList;default:return n===W.Regarding?F.LookupRegarding:F.LookupSimple}}isLookupType(t){return fd.includes(t)}isNumberTypeProperty(t,r){return pd.includes(r)||t.ofTypeGroup.some(n=>pd.includes(n))}isDataSet(t){return Ht.dataset===t}isGroups(t){return!!t[0].getAllProperties().find(n=>n.key==="isGroup"&&n.value==="true")}}});var ee,_0=L(()=>{"use strict";ee=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 aT={};Jr(aT,{CustomControlUniqueId:()=>ua,DeprecatedControlClassIds:()=>G,FieldControlTypes:()=>lt,mapFieldTypeToControl:()=>h6});function h6(e,t){switch(e){case $.TwoOptions:return N.BooleanControl;case $.Customer:case $.CustomerType:return N.LookupControl;case $.DateTime:return t===W.DateAndTime?N.DateTimeControl:N.DateTimeControl;case $.DecimalNumber:return N.DecimalControl;case $.FloatingPointNumber:return N.FloatingNumberControl;case $.WholeNumber:return t===W.Duration?N.DurationControl:t===W.Language?N.LanguageControl:t===W.TimeZone?N.TimezoneControl:N.IntegerControl;case $.CustomerType:case $.Lookup:case $.LookupType:return t===W.Regarding?N.RegardingControl:N.LookupControl;case $.MultipleLineofText:return t===W.Email?N.EmailBodyControl:N.TextAreaControl;case $.Currency:return N.CurrencyControl;case $.Owner:case $.OwnerType:return N.LookupControl;case $.PartyList:case $.PartyListType:return N.PartyListControl;case $.Status:case $.OptionSet:return N.ChoiceControl;case $.SingleLineofText:return t===W.Email?N.EmailAddressControl:t===W.Phone?N.PhoneNumberControl:t===W.Text?N.TextboxControl:t===W.TextArea?N.TextAreaControl:t===W.TickerSymbol?N.TickerControl:t===W.Url?N.UrlControl:t===W.PhoneticGuide?N.TextboxControl:N.TextboxControl;case $.MultiSelectOptionSet:return N.ChoicesControl;case $.Image:return N.ImageControl;case $.File:return N.FileControl;case $.State:return N.ChoiceControl;case $.Status:return N.ChoiceStatusControl;default:throw new Error(`Cannot get base control for ${e} field type`)}}var G,ua,lt,bu=L(()=>{"use strict";ht();Wl();st();Xt();os();oa();_0();Tn();G=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"}};ua=class{static get RelationshipAssistant(){return"3ff9a528-dd50-4aca-8f10-2e5ed73513ad"}static get PredictiveLeadScoring(){return"6f503f2a-d033-4106-b62c-f8f2e5f01a57"}},lt=class e{static FieldControlIds=e.initializeFieldControls();static UnboundControlIds=e.initializeUnboundControls();static ControlsAllowedForReferencePanel=e.initializeReferencePanelControls();static ControlsAllowedForFooter=e.initializeFooterControls();static CustomControlIdMap=new ar;static initializeFieldControls(){let t=new ar,r=e.getControlName($.SingleLineofText,W.Phone);t.add(r,new U(G.PhoneNumberControl));let n=e.getControlName($.SingleLineofText,W.TextArea);t.add(n,new U(G.TextAreaControl));let i=e.getControlName($.SingleLineofText,W.Text);t.add(i,new U(G.TextBoxControl));let o=e.getControlName($.SingleLineofText,W.Email);t.add(o,new U(G.EmailAddressControl));let a=e.getControlName($.SingleLineofText,W.Url);t.add(a,new U(G.UrlControl));let s=e.getControlName($.SingleLineofText,W.TickerSymbol);t.add(s,new U(G.TickerControl));let l=e.getControlName($.SingleLineofText,W.PhoneticGuide);t.add(l,new U(G.TextBoxControl));let u=e.getControlName($.WholeNumber,W.Duration);t.add(u,new U(G.DurationControl));let c=e.getControlName($.WholeNumber,W.Language);t.add(c,new U(G.LanguagePickerControl));let d=e.getControlName($.WholeNumber,W.TimeZone);t.add(d,new U(G.TimeZonePicklistControl));let f=e.getControlName($.WholeNumber,W.None);t.add(f,new U(G.IntegerControl));let m=e.getControlName($.DateTime,W.DateOnly);t.add(m,new U(G.DateTimeControl));let p=e.getControlName($.DateTime,W.DateAndTime);t.add(p,new U(G.DateTimeControl));let h=e.getControlName($.LookupType,W.None);t.add(h,new U(G.LookupControl));let g=e.getControlName($.CustomerType,W.None);t.add(g,new U(G.LookupControl));let b=e.getControlName($.FloatingPointNumber,W.None);t.add(b,new U(G.FloatControl));let w=e.getControlName($.DecimalNumber,W.None);t.add(w,new U(G.DecimalControl));let C=e.getControlName($.Currency,W.None);t.add(C,new U(G.MoneyControl));let S=e.getControlName($.MultipleLineofText,W.None);t.add(S,new U(G.TextAreaControl));let O=e.getControlName($.MultipleLineofText,W.Text);t.add(O,new U(G.TextAreaControl));let k=e.getControlName($.MultipleLineofText,W.TextArea);t.add(k,new U(G.TextAreaControl));let I=e.getControlName($.MultipleLineofText,W.Email);t.add(I,new U(G.EmailBodyControl));let D=e.getControlName($.OptionSet,W.None);t.add(D,new U(G.PicklistControl));let P=e.getControlName($.TwoOptions,W.None);t.add(P,new U(G.RadioControl));let x=e.getControlName($.Image,W.None);t.add(x,new U(G.WebResourceImageControl));let K=e.getControlName($.Image,W.None);t.add(K,new U(G.WebResourceHtmlControl));let Oe=e.getControlName($.TwoOptions,"Radio");t.add(Oe,new U(G.RadioControl));let Vt=e.getControlName($.TwoOptions,"CheckBox");t.add(Vt,new U(G.CheckBoxControl));let Xe=e.getControlName($.TwoOptions,"List");t.add(Xe,new U(G.PicklistControl));let Ne=e.getControlName($.State,W.None);t.add(Ne,new U(G.PicklistControl));let se=e.getControlName($.Status,W.None);t.add(se,new U(G.PicklistStatusControl));let We=e.getControlName($.OwnerType,W.None);t.add(We,new U(G.LookupControl));let ir=e.getControlName($.PartyListType,W.None);t.add(ir,new U(G.PartyListControl));let PU=e.getControlName($.LookupType,W.Regarding);t.add(PU,new U(G.RegardingControl));let RU=e.getControlName($.MultiSelectOptionSet,W.None);return t.add(RU,new U(G.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(!R.IsNullOrEmptyGuid(t)){let r=e.getTypeAndFormatByControlOrUniqueId(t.guidString.toLowerCase());return r=R.IsNullOrUndefined(r)?e.getUnboundControlNameFromIdentifier(t):r.substring(0,r.indexOf("_")),r}return null}static isCustomControl(t){return R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId)||t.control.ClassId.guidString===G.CustomControl}static initializeUnboundControls(){let t=new ar;return t.add(G.ACIControl,ee.ACIControl),t.add(G.IframeControl,ee.IframeControl),t.add(G.SearchWidgetControl,ee.SearchWidgetControl),t.add(G.MapsControl,ee.MapsControl),t.add(G.QuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.GridControl,ee.SubGridControl),t.add(G.WebResourceImageControl,ee.WebResourceImageControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.TimerControl,ee.TimerControl),t.add(G.TimeLineControl,ee.NotesControl),t.add(G.TimeLineControlUC,ee.NotesControl),t.add(G.SocialInsightControl,ee.SocialInsightControl),t.add(ua.RelationshipAssistant,ee.CustomControl),t}static initializeReferencePanelControls(){let t=new ar;return t.add(G.IframeControl,ee.IframeControl),t.add(G.ReferencePanelSearchWidget,ee.SearchWidgetControl),t.add(G.ReferencePanelQuickFormCollectionControl,ee.QuickFormCollectionControl),t.add(G.ReferencePanelSubgridControl,ee.SubGridControl),t.add(G.WebResourceHtmlControl,ee.WebResourceHtmlControl),t.add(G.WebResourceImageControl,ee.WebResourceHtmlControl),t}static initializeFooterControls(){let t=new is;return t.add(Cs.IFRAME,!0),t.add(Cs.SPACER,!0),t.add(Cs.WEB_RESOURCE_HTML,!0),t}static isUnboundFormControl(t){if(R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId))return!1;let r=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.containsKey(r.guidString)}static isReferencePanelSection(t){return!R.IsNullOrUndefined(t)&&!R.IsNullOrUndefined(t.Name)&&t.Name.indexOf(Ue.referencePanelNamePrefix)===0}static isUnboundFormControlByIdentifier(t){return R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.guidString)?!1:e.UnboundControlIds.containsKey(t.guidString)}static getUnboundFormControlName(t){let r=q.EmptyString;if(R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.control)||R.IsNullOrUndefined(t.control.ClassId))return r;let n=e.getUniqueIdentifierForControl(t.control);return e.UnboundControlIds.getValue(n.guidString).toString()}static getUnboundControlNameFromIdentifier(t){return R.IsNullOrUndefined(t)||R.IsNullOrUndefined(t.guidString)?q.EmptyString:e.UnboundControlIds.getValue(t.guidString).toString()}static isSpacerControl(t){return t===G.SpacerControl}static GetRowSpan(t){let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!R.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}switch(e.UnboundControlIds.getValue(r.guidString)){case ee.IframeControl:case ee.ACIControl:case ee.SocialInsightControl:return 6;case ee.SubGridControl:case ee.CustomControl:return 4;case ee.WebResourceImageControl:return 15;case ee.WebResourceHtmlControl:return 15;case ee.MapsControl:return 8;case ee.SearchWidgetControl:return 10;case ee.NotesControl:case ee.TimeLineControl:return 15;case ee.TimerControl:return 2;default:}}static isLookUpControl(t){return!R.IsNullOrUndefined(t)&&t.ClassId.guidString===G.LookupControl}static isRelationshipAssistantOrLeadScoringControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistantOrLeadScoring(t.UniqueId)}static isRelationshipAssistantOrLeadScoring(t){return!R.IsNullOrUndefined(t)&&(t.guidString===ua.RelationshipAssistant||t.guidString===ua.PredictiveLeadScoring)}static isRelationshipAssistantControl(t){return!R.IsNullOrUndefined(t)&&e.isRelationshipAssistant(t.UniqueId)}static isRelationshipAssistant(t){return!R.IsNullOrUndefined(t)&&t.guidString===ua.RelationshipAssistant}static getUniqueIdentifierForControl(t){if(R.IsNullOrUndefined(t))return null;let r=t.ClassId;if(e.isRelationshipAssistantControl(t))r=t.UniqueId;else if(r.guidString===G.CustomControl&&!R.IsNullOrUndefined(t.UniqueId)){let n=t.UniqueId.ToString();e.CustomControlIdMap.containsKey(n)&&(r=e.CustomControlIdMap.getValue(n))}return r}}});var ff,sT=L(()=>{"use strict";ff=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 ca,As,lT,uT,yo,cT,dT,T0=L(()=>{"use strict";(function(e){e[e.Center=0]="Center",e[e.Left=1]="Left",e[e.Right=2]="Right"})(ca||(ca={}));(function(e){e[e.Left=0]="Left",e[e.Top=1]="Top"})(As||(As={}));(function(e){e[e.Top=0]="Top",e[e.Middle=1]="Middle"})(lT||(lT={}));(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"})(uT||(uT={}));(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"})(yo||(yo={}));(function(e){e[e.None=0]="None",e[e.SystemRequired=1]="SystemRequired",e[e.ApplicationRequired=2]="ApplicationRequired",e[e.Recommended=3]="Recommended"})(cT||(cT={}));(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"})(dT||(dT={}))});var Ss,fT=L(()=>{"use strict";gu();Ss=p0({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 pT(e){return{...e,extractConfig:t=>g6(t,Object.keys(e.fallback))}}function g6(e,t){let r={};for(let n of t)typeof e[n]<"u"&&(r[n]=e[n]);return r}var D0=L(()=>{"use strict";});var I0=v((Zce,hT)=>{var vu=new Proxy(function(){return vu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:vu},apply:function(){return vu},construct:function(){return{}}}),mT=function(){return vu};Object.setPrototypeOf(mT,vu);hT.exports=mT});var bT=v((ede,yT)=>{var wu=new Proxy(function(){return wu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:wu},apply:function(){return wu},construct:function(){return{}}}),gT=function(){return wu};Object.setPrototypeOf(gT,wu);yT.exports=gT});var O0=v((tde,wT)=>{var Cu=new Proxy(function(){return Cu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Cu},apply:function(){return Cu},construct:function(){return{}}}),vT=function(){return Cu};Object.setPrototypeOf(vT,Cu);wT.exports=vT});var ET=v((rde,CT)=>{function y6(){this.__data__=[],this.size=0}CT.exports=y6});var Ns=v((nde,AT)=>{function b6(e,t){return e===t||e!==e&&t!==t}AT.exports=b6});var Eu=v((ide,ST)=>{var v6=Ns();function w6(e,t){for(var r=e.length;r--;)if(v6(e[r][0],t))return r;return-1}ST.exports=w6});var _T=v((ode,NT)=>{var C6=Eu(),E6=Array.prototype,A6=E6.splice;function S6(e){var t=this.__data__,r=C6(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():A6.call(t,r,1),--this.size,!0}NT.exports=S6});var DT=v((ade,TT)=>{var N6=Eu();function _6(e){var t=this.__data__,r=N6(t,e);return r<0?void 0:t[r][1]}TT.exports=_6});var OT=v((sde,IT)=>{var T6=Eu();function D6(e){return T6(this.__data__,e)>-1}IT.exports=D6});var RT=v((lde,PT)=>{var I6=Eu();function O6(e,t){var r=this.__data__,n=I6(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}PT.exports=O6});var Au=v((ude,kT)=>{var P6=ET(),R6=_T(),k6=DT(),L6=OT(),$6=RT();function _s(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])}}_s.prototype.clear=P6;_s.prototype.delete=R6;_s.prototype.get=k6;_s.prototype.has=L6;_s.prototype.set=$6;kT.exports=_s});var $T=v((cde,LT)=>{var x6=Au();function F6(){this.__data__=new x6,this.size=0}LT.exports=F6});var FT=v((dde,xT)=>{function M6(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}xT.exports=M6});var UT=v((fde,MT)=>{function U6(e){return this.__data__.get(e)}MT.exports=U6});var qT=v((pde,BT)=>{function B6(e){return this.__data__.has(e)}BT.exports=B6});var P0=v((mde,VT)=>{var q6=typeof global=="object"&&global&&global.Object===Object&&global;VT.exports=q6});var In=v((hde,GT)=>{var V6=P0(),G6=typeof self=="object"&&self&&self.Object===Object&&self,W6=V6||G6||Function("return this")();GT.exports=W6});var Su=v((gde,WT)=>{var z6=In(),j6=z6.Symbol;WT.exports=j6});var KT=v((yde,HT)=>{var zT=Su(),jT=Object.prototype,H6=jT.hasOwnProperty,K6=jT.toString,Nu=zT?zT.toStringTag:void 0;function J6(e){var t=H6.call(e,Nu),r=e[Nu];try{e[Nu]=void 0;var n=!0}catch{}var i=K6.call(e);return n&&(t?e[Nu]=r:delete e[Nu]),i}HT.exports=J6});var YT=v((bde,JT)=>{var Y6=Object.prototype,Q6=Y6.toString;function X6(e){return Q6.call(e)}JT.exports=X6});var da=v((vde,ZT)=>{var QT=Su(),Z6=KT(),ez=YT(),tz="[object Null]",rz="[object Undefined]",XT=QT?QT.toStringTag:void 0;function nz(e){return e==null?e===void 0?rz:tz:XT&&XT in Object(e)?Z6(e):ez(e)}ZT.exports=nz});var $i=v((wde,eD)=>{function iz(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}eD.exports=iz});var pf=v((Cde,tD)=>{var oz=da(),az=$i(),sz="[object AsyncFunction]",lz="[object Function]",uz="[object GeneratorFunction]",cz="[object Proxy]";function dz(e){if(!az(e))return!1;var t=oz(e);return t==lz||t==uz||t==sz||t==cz}tD.exports=dz});var nD=v((Ede,rD)=>{var fz=In(),pz=fz["__core-js_shared__"];rD.exports=pz});var aD=v((Ade,oD)=>{var R0=nD(),iD=(function(){var e=/[^.]+$/.exec(R0&&R0.keys&&R0.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();function mz(e){return!!iD&&iD in e}oD.exports=mz});var k0=v((Sde,sD)=>{var hz=Function.prototype,gz=hz.toString;function yz(e){if(e!=null){try{return gz.call(e)}catch{}try{return e+""}catch{}}return""}sD.exports=yz});var uD=v((Nde,lD)=>{var bz=pf(),vz=aD(),wz=$i(),Cz=k0(),Ez=/[\\^$.*+?()[\]{}|]/g,Az=/^\[object .+?Constructor\]$/,Sz=Function.prototype,Nz=Object.prototype,_z=Sz.toString,Tz=Nz.hasOwnProperty,Dz=RegExp("^"+_z.call(Tz).replace(Ez,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Iz(e){if(!wz(e)||vz(e))return!1;var t=bz(e)?Dz:Az;return t.test(Cz(e))}lD.exports=Iz});var dD=v((_de,cD)=>{function Oz(e,t){return e?.[t]}cD.exports=Oz});var bo=v((Tde,fD)=>{var Pz=uD(),Rz=dD();function kz(e,t){var r=Rz(e,t);return Pz(r)?r:void 0}fD.exports=kz});var mf=v((Dde,pD)=>{var Lz=bo(),$z=In(),xz=Lz($z,"Map");pD.exports=xz});var _u=v((Ide,mD)=>{var Fz=bo(),Mz=Fz(Object,"create");mD.exports=Mz});var yD=v((Ode,gD)=>{var hD=_u();function Uz(){this.__data__=hD?hD(null):{},this.size=0}gD.exports=Uz});var vD=v((Pde,bD)=>{function Bz(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}bD.exports=Bz});var CD=v((Rde,wD)=>{var qz=_u(),Vz="__lodash_hash_undefined__",Gz=Object.prototype,Wz=Gz.hasOwnProperty;function zz(e){var t=this.__data__;if(qz){var r=t[e];return r===Vz?void 0:r}return Wz.call(t,e)?t[e]:void 0}wD.exports=zz});var AD=v((kde,ED)=>{var jz=_u(),Hz=Object.prototype,Kz=Hz.hasOwnProperty;function Jz(e){var t=this.__data__;return jz?t[e]!==void 0:Kz.call(t,e)}ED.exports=Jz});var ND=v((Lde,SD)=>{var Yz=_u(),Qz="__lodash_hash_undefined__";function Xz(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Yz&&t===void 0?Qz:t,this}SD.exports=Xz});var TD=v(($de,_D)=>{var Zz=yD(),ej=vD(),tj=CD(),rj=AD(),nj=ND();function Ts(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])}}Ts.prototype.clear=Zz;Ts.prototype.delete=ej;Ts.prototype.get=tj;Ts.prototype.has=rj;Ts.prototype.set=nj;_D.exports=Ts});var OD=v((xde,ID)=>{var DD=TD(),ij=Au(),oj=mf();function aj(){this.size=0,this.__data__={hash:new DD,map:new(oj||ij),string:new DD}}ID.exports=aj});var RD=v((Fde,PD)=>{function sj(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}PD.exports=sj});var Tu=v((Mde,kD)=>{var lj=RD();function uj(e,t){var r=e.__data__;return lj(t)?r[typeof t=="string"?"string":"hash"]:r.map}kD.exports=uj});var $D=v((Ude,LD)=>{var cj=Tu();function dj(e){var t=cj(this,e).delete(e);return this.size-=t?1:0,t}LD.exports=dj});var FD=v((Bde,xD)=>{var fj=Tu();function pj(e){return fj(this,e).get(e)}xD.exports=pj});var UD=v((qde,MD)=>{var mj=Tu();function hj(e){return mj(this,e).has(e)}MD.exports=hj});var qD=v((Vde,BD)=>{var gj=Tu();function yj(e,t){var r=gj(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}BD.exports=yj});var hf=v((Gde,VD)=>{var bj=OD(),vj=$D(),wj=FD(),Cj=UD(),Ej=qD();function Ds(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])}}Ds.prototype.clear=bj;Ds.prototype.delete=vj;Ds.prototype.get=wj;Ds.prototype.has=Cj;Ds.prototype.set=Ej;VD.exports=Ds});var WD=v((Wde,GD)=>{var Aj=Au(),Sj=mf(),Nj=hf(),_j=200;function Tj(e,t){var r=this.__data__;if(r instanceof Aj){var n=r.__data__;if(!Sj||n.length<_j-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new Nj(n)}return r.set(e,t),this.size=r.size,this}GD.exports=Tj});var L0=v((zde,zD)=>{var Dj=Au(),Ij=$T(),Oj=FT(),Pj=UT(),Rj=qT(),kj=WD();function Is(e){var t=this.__data__=new Dj(e);this.size=t.size}Is.prototype.clear=Ij;Is.prototype.delete=Oj;Is.prototype.get=Pj;Is.prototype.has=Rj;Is.prototype.set=kj;zD.exports=Is});var HD=v((jde,jD)=>{var Lj="__lodash_hash_undefined__";function $j(e){return this.__data__.set(e,Lj),this}jD.exports=$j});var JD=v((Hde,KD)=>{function xj(e){return this.__data__.has(e)}KD.exports=xj});var QD=v((Kde,YD)=>{var Fj=hf(),Mj=HD(),Uj=JD();function gf(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Fj;++t<r;)this.add(e[t])}gf.prototype.add=gf.prototype.push=Mj;gf.prototype.has=Uj;YD.exports=gf});var ZD=v((Jde,XD)=>{function Bj(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}XD.exports=Bj});var tI=v((Yde,eI)=>{function qj(e,t){return e.has(t)}eI.exports=qj});var $0=v((Qde,rI)=>{var Vj=QD(),Gj=ZD(),Wj=tI(),zj=1,jj=2;function Hj(e,t,r,n,i,o){var a=r&zj,s=e.length,l=t.length;if(s!=l&&!(a&&l>s))return!1;var u=o.get(e),c=o.get(t);if(u&&c)return u==t&&c==e;var d=-1,f=!0,m=r&jj?new Vj:void 0;for(o.set(e,t),o.set(t,e);++d<s;){var p=e[d],h=t[d];if(n)var g=a?n(h,p,d,t,e,o):n(p,h,d,e,t,o);if(g!==void 0){if(g)continue;f=!1;break}if(m){if(!Gj(t,function(b,w){if(!Wj(m,w)&&(p===b||i(p,b,r,n,o)))return m.push(w)})){f=!1;break}}else if(!(p===h||i(p,h,r,n,o))){f=!1;break}}return o.delete(e),o.delete(t),f}rI.exports=Hj});var x0=v((Xde,nI)=>{var Kj=In(),Jj=Kj.Uint8Array;nI.exports=Jj});var oI=v((Zde,iI)=>{function Yj(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}iI.exports=Yj});var sI=v((efe,aI)=>{function Qj(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}aI.exports=Qj});var fI=v((tfe,dI)=>{var lI=Su(),uI=x0(),Xj=Ns(),Zj=$0(),e7=oI(),t7=sI(),r7=1,n7=2,i7="[object Boolean]",o7="[object Date]",a7="[object Error]",s7="[object Map]",l7="[object Number]",u7="[object RegExp]",c7="[object Set]",d7="[object String]",f7="[object Symbol]",p7="[object ArrayBuffer]",m7="[object DataView]",cI=lI?lI.prototype:void 0,F0=cI?cI.valueOf:void 0;function h7(e,t,r,n,i,o,a){switch(r){case m7:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case p7:return!(e.byteLength!=t.byteLength||!o(new uI(e),new uI(t)));case i7:case o7:case l7:return Xj(+e,+t);case a7:return e.name==t.name&&e.message==t.message;case u7:case d7:return e==t+"";case s7:var s=e7;case c7:var l=n&r7;if(s||(s=t7),e.size!=t.size&&!l)return!1;var u=a.get(e);if(u)return u==t;n|=n7,a.set(e,t);var c=Zj(s(e),s(t),n,i,o,a);return a.delete(e),c;case f7:if(F0)return F0.call(e)==F0.call(t)}return!1}dI.exports=h7});var mI=v((rfe,pI)=>{function g7(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e}pI.exports=g7});var vo=v((nfe,hI)=>{var y7=Array.isArray;hI.exports=y7});var yI=v((ife,gI)=>{var b7=mI(),v7=vo();function w7(e,t,r){var n=t(e);return v7(e)?n:b7(n,r(e))}gI.exports=w7});var vI=v((ofe,bI)=>{function C7(e,t){for(var r=-1,n=e==null?0:e.length,i=0,o=[];++r<n;){var a=e[r];t(a,r,e)&&(o[i++]=a)}return o}bI.exports=C7});var CI=v((afe,wI)=>{function E7(){return[]}wI.exports=E7});var SI=v((sfe,AI)=>{var A7=vI(),S7=CI(),N7=Object.prototype,_7=N7.propertyIsEnumerable,EI=Object.getOwnPropertySymbols,T7=EI?function(e){return e==null?[]:(e=Object(e),A7(EI(e),function(t){return _7.call(e,t)}))}:S7;AI.exports=T7});var _I=v((lfe,NI)=>{function D7(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}NI.exports=D7});var wo=v((ufe,TI)=>{function I7(e){return e!=null&&typeof e=="object"}TI.exports=I7});var II=v((cfe,DI)=>{var O7=da(),P7=wo(),R7="[object Arguments]";function k7(e){return P7(e)&&O7(e)==R7}DI.exports=k7});var M0=v((dfe,RI)=>{var OI=II(),L7=wo(),PI=Object.prototype,$7=PI.hasOwnProperty,x7=PI.propertyIsEnumerable,F7=OI((function(){return arguments})())?OI:function(e){return L7(e)&&$7.call(e,"callee")&&!x7.call(e,"callee")};RI.exports=F7});var LI=v((ffe,kI)=>{function M7(){return!1}kI.exports=M7});var yf=v((Du,Os)=>{var U7=In(),B7=LI(),FI=typeof Du=="object"&&Du&&!Du.nodeType&&Du,$I=FI&&typeof Os=="object"&&Os&&!Os.nodeType&&Os,q7=$I&&$I.exports===FI,xI=q7?U7.Buffer:void 0,V7=xI?xI.isBuffer:void 0,G7=V7||B7;Os.exports=G7});var bf=v((pfe,MI)=>{var W7=9007199254740991,z7=/^(?:0|[1-9]\d*)$/;function j7(e,t){var r=typeof e;return t=t??W7,!!t&&(r=="number"||r!="symbol"&&z7.test(e))&&e>-1&&e%1==0&&e<t}MI.exports=j7});var U0=v((mfe,UI)=>{var H7=9007199254740991;function K7(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=H7}UI.exports=K7});var qI=v((hfe,BI)=>{var J7=da(),Y7=U0(),Q7=wo(),X7="[object Arguments]",Z7="[object Array]",eH="[object Boolean]",tH="[object Date]",rH="[object Error]",nH="[object Function]",iH="[object Map]",oH="[object Number]",aH="[object Object]",sH="[object RegExp]",lH="[object Set]",uH="[object String]",cH="[object WeakMap]",dH="[object ArrayBuffer]",fH="[object DataView]",pH="[object Float32Array]",mH="[object Float64Array]",hH="[object Int8Array]",gH="[object Int16Array]",yH="[object Int32Array]",bH="[object Uint8Array]",vH="[object Uint8ClampedArray]",wH="[object Uint16Array]",CH="[object Uint32Array]",$e={};$e[pH]=$e[mH]=$e[hH]=$e[gH]=$e[yH]=$e[bH]=$e[vH]=$e[wH]=$e[CH]=!0;$e[X7]=$e[Z7]=$e[dH]=$e[eH]=$e[fH]=$e[tH]=$e[rH]=$e[nH]=$e[iH]=$e[oH]=$e[aH]=$e[sH]=$e[lH]=$e[uH]=$e[cH]=!1;function EH(e){return Q7(e)&&Y7(e.length)&&!!$e[J7(e)]}BI.exports=EH});var GI=v((gfe,VI)=>{function AH(e){return function(t){return e(t)}}VI.exports=AH});var zI=v((Iu,Ps)=>{var SH=P0(),WI=typeof Iu=="object"&&Iu&&!Iu.nodeType&&Iu,Ou=WI&&typeof Ps=="object"&&Ps&&!Ps.nodeType&&Ps,NH=Ou&&Ou.exports===WI,B0=NH&&SH.process,_H=(function(){try{var e=Ou&&Ou.require&&Ou.require("util").types;return e||B0&&B0.binding&&B0.binding("util")}catch{}})();Ps.exports=_H});var vf=v((yfe,KI)=>{var TH=qI(),DH=GI(),jI=zI(),HI=jI&&jI.isTypedArray,IH=HI?DH(HI):TH;KI.exports=IH});var q0=v((bfe,JI)=>{var OH=_I(),PH=M0(),RH=vo(),kH=yf(),LH=bf(),$H=vf(),xH=Object.prototype,FH=xH.hasOwnProperty;function MH(e,t){var r=RH(e),n=!r&&PH(e),i=!r&&!n&&kH(e),o=!r&&!n&&!i&&$H(e),a=r||n||i||o,s=a?OH(e.length,String):[],l=s.length;for(var u in e)(t||FH.call(e,u))&&!(a&&(u=="length"||i&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||LH(u,l)))&&s.push(u);return s}JI.exports=MH});var wf=v((vfe,YI)=>{var UH=Object.prototype;function BH(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||UH;return e===r}YI.exports=BH});var V0=v((wfe,QI)=>{function qH(e,t){return function(r){return e(t(r))}}QI.exports=qH});var ZI=v((Cfe,XI)=>{var VH=V0(),GH=VH(Object.keys,Object);XI.exports=GH});var tO=v((Efe,eO)=>{var WH=wf(),zH=ZI(),jH=Object.prototype,HH=jH.hasOwnProperty;function KH(e){if(!WH(e))return zH(e);var t=[];for(var r in Object(e))HH.call(e,r)&&r!="constructor"&&t.push(r);return t}eO.exports=KH});var Pu=v((Afe,rO)=>{var JH=pf(),YH=U0();function QH(e){return e!=null&&YH(e.length)&&!JH(e)}rO.exports=QH});var iO=v((Sfe,nO)=>{var XH=q0(),ZH=tO(),eK=Pu();function tK(e){return eK(e)?XH(e):ZH(e)}nO.exports=tK});var aO=v((Nfe,oO)=>{var rK=yI(),nK=SI(),iK=iO();function oK(e){return rK(e,iK,nK)}oO.exports=oK});var uO=v((_fe,lO)=>{var sO=aO(),aK=1,sK=Object.prototype,lK=sK.hasOwnProperty;function uK(e,t,r,n,i,o){var a=r&aK,s=sO(e),l=s.length,u=sO(t),c=u.length;if(l!=c&&!a)return!1;for(var d=l;d--;){var f=s[d];if(!(a?f in t:lK.call(t,f)))return!1}var m=o.get(e),p=o.get(t);if(m&&p)return m==t&&p==e;var h=!0;o.set(e,t),o.set(t,e);for(var g=a;++d<l;){f=s[d];var b=e[f],w=t[f];if(n)var C=a?n(w,b,f,t,e,o):n(b,w,f,e,t,o);if(!(C===void 0?b===w||i(b,w,r,n,o):C)){h=!1;break}g||(g=f=="constructor")}if(h&&!g){var S=e.constructor,O=t.constructor;S!=O&&"constructor"in e&&"constructor"in t&&!(typeof S=="function"&&S instanceof S&&typeof O=="function"&&O instanceof O)&&(h=!1)}return o.delete(e),o.delete(t),h}lO.exports=uK});var dO=v((Tfe,cO)=>{var cK=bo(),dK=In(),fK=cK(dK,"DataView");cO.exports=fK});var pO=v((Dfe,fO)=>{var pK=bo(),mK=In(),hK=pK(mK,"Promise");fO.exports=hK});var hO=v((Ife,mO)=>{var gK=bo(),yK=In(),bK=gK(yK,"Set");mO.exports=bK});var yO=v((Ofe,gO)=>{var vK=bo(),wK=In(),CK=vK(wK,"WeakMap");gO.exports=CK});var NO=v((Pfe,SO)=>{var G0=dO(),W0=mf(),z0=pO(),j0=hO(),H0=yO(),AO=da(),Rs=k0(),bO="[object Map]",EK="[object Object]",vO="[object Promise]",wO="[object Set]",CO="[object WeakMap]",EO="[object DataView]",AK=Rs(G0),SK=Rs(W0),NK=Rs(z0),_K=Rs(j0),TK=Rs(H0),fa=AO;(G0&&fa(new G0(new ArrayBuffer(1)))!=EO||W0&&fa(new W0)!=bO||z0&&fa(z0.resolve())!=vO||j0&&fa(new j0)!=wO||H0&&fa(new H0)!=CO)&&(fa=function(e){var t=AO(e),r=t==EK?e.constructor:void 0,n=r?Rs(r):"";if(n)switch(n){case AK:return EO;case SK:return bO;case NK:return vO;case _K:return wO;case TK:return CO}return t});SO.exports=fa});var kO=v((Rfe,RO)=>{var K0=L0(),DK=$0(),IK=fI(),OK=uO(),_O=NO(),TO=vo(),DO=yf(),PK=vf(),RK=1,IO="[object Arguments]",OO="[object Array]",Cf="[object Object]",kK=Object.prototype,PO=kK.hasOwnProperty;function LK(e,t,r,n,i,o){var a=TO(e),s=TO(t),l=a?OO:_O(e),u=s?OO:_O(t);l=l==IO?Cf:l,u=u==IO?Cf:u;var c=l==Cf,d=u==Cf,f=l==u;if(f&&DO(e)){if(!DO(t))return!1;a=!0,c=!1}if(f&&!c)return o||(o=new K0),a||PK(e)?DK(e,t,r,n,i,o):IK(e,t,l,r,n,i,o);if(!(r&RK)){var m=c&&PO.call(e,"__wrapped__"),p=d&&PO.call(t,"__wrapped__");if(m||p){var h=m?e.value():e,g=p?t.value():t;return o||(o=new K0),i(h,g,r,n,o)}}return f?(o||(o=new K0),OK(e,t,r,n,i,o)):!1}RO.exports=LK});var FO=v((kfe,xO)=>{var $K=kO(),LO=wo();function $O(e,t,r,n,i){return e===t?!0:e==null||t==null||!LO(e)&&!LO(t)?e!==e&&t!==t:$K(e,t,r,n,$O,i)}xO.exports=$O});var UO=v((Lfe,MO)=>{var xK=FO();function FK(e,t){return xK(e,t)}MO.exports=FK});var J0=v(($fe,BO)=>{var MK=bo(),UK=(function(){try{var e=MK(Object,"defineProperty");return e({},"",{}),e}catch{}})();BO.exports=UK});var Ef=v((xfe,VO)=>{var qO=J0();function BK(e,t,r){t=="__proto__"&&qO?qO(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}VO.exports=BK});var Y0=v((Ffe,GO)=>{var qK=Ef(),VK=Ns();function GK(e,t,r){(r!==void 0&&!VK(e[t],r)||r===void 0&&!(t in e))&&qK(e,t,r)}GO.exports=GK});var zO=v((Mfe,WO)=>{function WK(e){return function(t,r,n){for(var i=-1,o=Object(t),a=n(t),s=a.length;s--;){var l=a[e?s:++i];if(r(o[l],l,o)===!1)break}return t}}WO.exports=WK});var HO=v((Ufe,jO)=>{var zK=zO(),jK=zK();jO.exports=jK});var XO=v((Ru,ks)=>{var HK=In(),QO=typeof Ru=="object"&&Ru&&!Ru.nodeType&&Ru,KO=QO&&typeof ks=="object"&&ks&&!ks.nodeType&&ks,KK=KO&&KO.exports===QO,JO=KK?HK.Buffer:void 0,YO=JO?JO.allocUnsafe:void 0;function JK(e,t){if(t)return e.slice();var r=e.length,n=YO?YO(r):new e.constructor(r);return e.copy(n),n}ks.exports=JK});var tP=v((Bfe,eP)=>{var ZO=x0();function YK(e){var t=new e.constructor(e.byteLength);return new ZO(t).set(new ZO(e)),t}eP.exports=YK});var nP=v((qfe,rP)=>{var QK=tP();function XK(e,t){var r=t?QK(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}rP.exports=XK});var oP=v((Vfe,iP)=>{function ZK(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}iP.exports=ZK});var lP=v((Gfe,sP)=>{var eJ=$i(),aP=Object.create,tJ=(function(){function e(){}return function(t){if(!eJ(t))return{};if(aP)return aP(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}})();sP.exports=tJ});var Q0=v((Wfe,uP)=>{var rJ=V0(),nJ=rJ(Object.getPrototypeOf,Object);uP.exports=nJ});var dP=v((zfe,cP)=>{var iJ=lP(),oJ=Q0(),aJ=wf();function sJ(e){return typeof e.constructor=="function"&&!aJ(e)?iJ(oJ(e)):{}}cP.exports=sJ});var pP=v((jfe,fP)=>{var lJ=Pu(),uJ=wo();function cJ(e){return uJ(e)&&lJ(e)}fP.exports=cJ});var gP=v((Hfe,hP)=>{var dJ=da(),fJ=Q0(),pJ=wo(),mJ="[object Object]",hJ=Function.prototype,gJ=Object.prototype,mP=hJ.toString,yJ=gJ.hasOwnProperty,bJ=mP.call(Object);function vJ(e){if(!pJ(e)||dJ(e)!=mJ)return!1;var t=fJ(e);if(t===null)return!0;var r=yJ.call(t,"constructor")&&t.constructor;return typeof r=="function"&&r instanceof r&&mP.call(r)==bJ}hP.exports=vJ});var X0=v((Kfe,yP)=>{function wJ(e,t){if(!(t==="constructor"&&typeof e[t]=="function")&&t!="__proto__")return e[t]}yP.exports=wJ});var Z0=v((Jfe,bP)=>{var CJ=Ef(),EJ=Ns(),AJ=Object.prototype,SJ=AJ.hasOwnProperty;function NJ(e,t,r){var n=e[t];(!(SJ.call(e,t)&&EJ(n,r))||r===void 0&&!(t in e))&&CJ(e,t,r)}bP.exports=NJ});var wP=v((Yfe,vP)=>{var _J=Z0(),TJ=Ef();function DJ(e,t,r,n){var i=!r;r||(r={});for(var o=-1,a=t.length;++o<a;){var s=t[o],l=n?n(r[s],e[s],s,r,e):void 0;l===void 0&&(l=e[s]),i?TJ(r,s,l):_J(r,s,l)}return r}vP.exports=DJ});var EP=v((Qfe,CP)=>{function IJ(e){var t=[];if(e!=null)for(var r in Object(e))t.push(r);return t}CP.exports=IJ});var SP=v((Xfe,AP)=>{var OJ=$i(),PJ=wf(),RJ=EP(),kJ=Object.prototype,LJ=kJ.hasOwnProperty;function $J(e){if(!OJ(e))return RJ(e);var t=PJ(e),r=[];for(var n in e)n=="constructor"&&(t||!LJ.call(e,n))||r.push(n);return r}AP.exports=$J});var ey=v((Zfe,NP)=>{var xJ=q0(),FJ=SP(),MJ=Pu();function UJ(e){return MJ(e)?xJ(e,!0):FJ(e)}NP.exports=UJ});var TP=v((epe,_P)=>{var BJ=wP(),qJ=ey();function VJ(e){return BJ(e,qJ(e))}_P.exports=VJ});var kP=v((tpe,RP)=>{var DP=Y0(),GJ=XO(),WJ=nP(),zJ=oP(),jJ=dP(),IP=M0(),OP=vo(),HJ=pP(),KJ=yf(),JJ=pf(),YJ=$i(),QJ=gP(),XJ=vf(),PP=X0(),ZJ=TP();function eY(e,t,r,n,i,o,a){var s=PP(e,r),l=PP(t,r),u=a.get(l);if(u){DP(e,r,u);return}var c=o?o(s,l,r+"",e,t,a):void 0,d=c===void 0;if(d){var f=OP(l),m=!f&&KJ(l),p=!f&&!m&&XJ(l);c=l,f||m||p?OP(s)?c=s:HJ(s)?c=zJ(s):m?(d=!1,c=GJ(l,!0)):p?(d=!1,c=WJ(l,!0)):c=[]:QJ(l)||IP(l)?(c=s,IP(s)?c=ZJ(s):(!YJ(s)||JJ(s))&&(c=jJ(l))):d=!1}d&&(a.set(l,c),i(c,l,n,o,a),a.delete(l)),DP(e,r,c)}RP.exports=eY});var ty=v((rpe,$P)=>{var tY=L0(),rY=Y0(),nY=HO(),iY=kP(),oY=$i(),aY=ey(),sY=X0();function LP(e,t,r,n,i){e!==t&&nY(t,function(o,a){if(i||(i=new tY),oY(o))iY(e,t,a,r,LP,n,i);else{var s=n?n(sY(e,a),o,a+"",e,t,i):void 0;s===void 0&&(s=o),rY(e,a,s)}},aY)}$P.exports=LP});var ry=v((npe,xP)=>{function lY(e){return e}xP.exports=lY});var MP=v((ipe,FP)=>{function uY(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)}FP.exports=uY});var qP=v((ope,BP)=>{var cY=MP(),UP=Math.max;function dY(e,t,r){return t=UP(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,o=UP(n.length-t,0),a=Array(o);++i<o;)a[i]=n[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=n[i];return s[t]=r(a),cY(e,this,s)}}BP.exports=dY});var GP=v((ape,VP)=>{function fY(e){return function(){return e}}VP.exports=fY});var jP=v((spe,zP)=>{var pY=GP(),WP=J0(),mY=ry(),hY=WP?function(e,t){return WP(e,"toString",{configurable:!0,enumerable:!1,value:pY(t),writable:!0})}:mY;zP.exports=hY});var KP=v((lpe,HP)=>{var gY=800,yY=16,bY=Date.now;function vY(e){var t=0,r=0;return function(){var n=bY(),i=yY-(n-r);if(r=n,i>0){if(++t>=gY)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}HP.exports=vY});var YP=v((upe,JP)=>{var wY=jP(),CY=KP(),EY=CY(wY);JP.exports=EY});var XP=v((cpe,QP)=>{var AY=ry(),SY=qP(),NY=YP();function _Y(e,t){return NY(SY(e,t,AY),e+"")}QP.exports=_Y});var eR=v((dpe,ZP)=>{var TY=Ns(),DY=Pu(),IY=bf(),OY=$i();function PY(e,t,r){if(!OY(r))return!1;var n=typeof t;return(n=="number"?DY(r)&&IY(t,r.length):n=="string"&&t in r)?TY(r[t],e):!1}ZP.exports=PY});var ny=v((fpe,tR)=>{var RY=XP(),kY=eR();function LY(e){return RY(function(t,r){var n=-1,i=r.length,o=i>1?r[i-1]:void 0,a=i>2?r[2]:void 0;for(o=e.length>3&&typeof o=="function"?(i--,o):void 0,a&&kY(r[0],r[1],a)&&(o=i<3?void 0:o,i=1),t=Object(t);++n<i;){var s=r[n];s&&e(t,s,n,o)}return t})}tR.exports=LY});var nR=v((ppe,rR)=>{var $Y=ty(),xY=ny(),FY=xY(function(e,t,r,n){$Y(e,t,r,n)});rR.exports=FY});var un,ku=L(()=>{"use strict";(function(e){e[e.NotLoaded=0]="NotLoaded",e[e.Initialized=1]="Initialized",e[e.ConfigsLoaded=2]="ConfigsLoaded",e[e.Error=3]="Error"})(un||(un={}))});function oR(e,t,r="PROD"){let n=i=>`ShellSettings_ECS_ClientCache_${e}_${iR.EcsConfigType[i]}_${r}`;return{getData:i=>{let o=t.getItem(n(i));return Promise.resolve(o?JSON.parse(o):void 0)},putData:(i,o)=>(t.setItem(n(i),JSON.stringify(o)),Promise.resolve())}}var iR,MY,aR=L(()=>{"use strict";iR=Ae(O0()),MY=Ae(I0());});var iy,sR=L(()=>{"use strict";of();iy=hu({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 uR,cR,dR,fR,oy,UY,Af,lR,ay=L(()=>{"use strict";uR=Ae(I0()),cR=Ae(bT()),dR=Ae(O0()),fR=Ae(UO()),oy=Ae(nR());ku();aR();sR();UY=60*1e3,Af=class{clientName;logger;ecsEndpoint;resolveLoadingPromise;loadingPromise=new Promise(t=>this.resolveLoadingPromise=t);_status=un.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"?iy.prodEcsEndpoint:iy.integrationEcsEndpoint}client=new cR.default;init=async({clientVersion:t,getFilters:r,cacheStorage:n=uR.StorageHelper.transientWithGlobalFallback,updateIntervalInMinutes:i,overrideEcsInitParams:o})=>{this.client.telemetryEventAdded.subscribe(this.logger.logEvent),this.client.configUpdated.subscribe(this.handleConfigUpdated);let a=(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:[dR.EcsConfigType.Default],hosts:[this.ecsEndpoint],initialAppActiveState:!0,getEcsParameters:a,databaseInterface:oR(this.clientName,n,this.endpointType),...o}),this.client.requestUpdate(),this._status===un.NotLoaded&&(this._status=un.Initialized)}catch(s){this._status=un.Error,this.resolveLoadingPromise(),this.logEvent("FeaturesClient/initializationFailed",{ecsClientName:this.clientName,error:s},"Error")}i&&window.setInterval(()=>this.client.requestUpdate(),i*UY)};getConfig=t=>{let r=this.getMergedClientConfigByTeamName(t.teamName),n=r?t.extractConfig(r):{};return(0,oy.default)({},t.fallback,n,t.override,lR)};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 o=this.getConfig(t);(0,fR.default)(o,n)||(n={...o},r(o))});return{unsubscribe:()=>i.unsubscribe()}};waitUntilLoaded=async t=>{if(t!==void 0){let r,n=new Promise((i,o)=>{r=window.setTimeout(()=>{o(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,oy.default)({},this.client.getConfig()?.config,this.clientConfigOverride,lR);getMergedClientConfigByTeamName=t=>this.getMergedClientConfig()?.[t];handleConfigUpdated=()=>{let t=this.client.getConfig();if(t===void 0)return;this.resolveLoadingPromise(),this._status=un.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})}},lR=(e,t)=>{if(Array.isArray(t))return t}});var mR=v((Epe,pR)=>{"use strict";var BY=()=>{let e={};return e.promise=new Promise((t,r)=>{e.resolve=t,e.reject=r}),e};pR.exports=BY});var sy=v((Ape,gR)=>{var Lu=new Proxy(function(){return Lu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Lu},apply:function(){return Lu},construct:function(){return{}}}),hR=function(){return Lu};Object.setPrototypeOf(hR,Lu);gR.exports=hR});var vR=v((Spe,bR)=>{var $u=new Proxy(function(){return $u},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:$u},apply:function(){return $u},construct:function(){return{}}}),yR=function(){return $u};Object.setPrototypeOf(yR,$u);bR.exports=yR});var _R=v((Npe,NR)=>{"use strict";var ly=vR(),qY={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},VY={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},GY={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0},AR={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},uy={};uy[ly.ForwardRef]=GY;uy[ly.Memo]=AR;function wR(e){return ly.isMemo(e)?AR:uy[e.$$typeof]||qY}var WY=Object.defineProperty,zY=Object.getOwnPropertyNames,CR=Object.getOwnPropertySymbols,jY=Object.getOwnPropertyDescriptor,HY=Object.getPrototypeOf,ER=Object.prototype;function SR(e,t,r){if(typeof t!="string"){if(ER){var n=HY(t);n&&n!==ER&&SR(e,n,r)}var i=zY(t);CR&&(i=i.concat(CR(t)));for(var o=wR(e),a=wR(t),s=0;s<i.length;++s){var l=i[s];if(!VY[l]&&!(r&&r[l])&&!(a&&a[l])&&!(o&&o[l])){var u=jY(t,l);try{WY(e,l,u)}catch{}}}}return e}NR.exports=SR});function DR(e,t,r){let[n,i]=(0,Ls.useState)(e.getConfig(t));return(0,Ls.useEffect)(()=>{if(!r?.subscribe&&e.status===un.ConfigsLoaded)return;let o=e.subscribe(t,a=>{i(a),r?.subscribe||o.unsubscribe()});return o?.unsubscribe},[]),n}function IR(e){return function(t,r){return DR(e,t,r)}}function OR(e,t,r,n){let i=o=>{let a=DR(e,t,n),s={...o,...a};return Ls.default.createElement(r,{...s})};return(0,TR.default)(i,r),i.displayName=`WithFeature(${r.name})`,i}function PR(e,t,r,n){return t.reduce((i,o)=>OR(e,o,i,n),r)}function RR(e){return function(t,r,n){return OR(e,t,r,n)}}var TR,Ls,cy=L(()=>{"use strict";TR=Ae(_R()),Ls=Ae(sy());ku();});var LR=v((Dpe,kR)=>{var KY=ty(),JY=ny(),YY=JY(function(e,t,r){KY(e,t,r)});kR.exports=YY});var Sf=v((Ipe,$R)=>{var QY=da(),XY=wo(),ZY="[object Symbol]";function eQ(e){return typeof e=="symbol"||XY(e)&&QY(e)==ZY}$R.exports=eQ});var FR=v((Ope,xR)=>{var tQ=vo(),rQ=Sf(),nQ=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,iQ=/^\w*$/;function oQ(e,t){if(tQ(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||rQ(e)?!0:iQ.test(e)||!nQ.test(e)||t!=null&&e in Object(t)}xR.exports=oQ});var BR=v((Ppe,UR)=>{var MR=hf(),aQ="Expected a function";function dy(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(aQ);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],o=r.cache;if(o.has(i))return o.get(i);var a=e.apply(this,n);return r.cache=o.set(i,a)||o,a};return r.cache=new(dy.Cache||MR),r}dy.Cache=MR;UR.exports=dy});var VR=v((Rpe,qR)=>{var sQ=BR(),lQ=500;function uQ(e){var t=sQ(e,function(n){return r.size===lQ&&r.clear(),n}),r=t.cache;return t}qR.exports=uQ});var WR=v((kpe,GR)=>{var cQ=VR(),dQ=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,fQ=/\\(\\)?/g,pQ=cQ(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(dQ,function(r,n,i,o){t.push(i?o.replace(fQ,"$1"):n||r)}),t});GR.exports=pQ});var jR=v((Lpe,zR)=>{function mQ(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}zR.exports=mQ});var XR=v(($pe,QR)=>{var HR=Su(),hQ=jR(),gQ=vo(),yQ=Sf(),bQ=1/0,KR=HR?HR.prototype:void 0,JR=KR?KR.toString:void 0;function YR(e){if(typeof e=="string")return e;if(gQ(e))return hQ(e,YR)+"";if(yQ(e))return JR?JR.call(e):"";var t=e+"";return t=="0"&&1/e==-bQ?"-0":t}QR.exports=YR});var e2=v((xpe,ZR)=>{var vQ=XR();function wQ(e){return e==null?"":vQ(e)}ZR.exports=wQ});var r2=v((Fpe,t2)=>{var CQ=vo(),EQ=FR(),AQ=WR(),SQ=e2();function NQ(e,t){return CQ(e)?e:EQ(e,t)?[e]:AQ(SQ(e))}t2.exports=NQ});var i2=v((Mpe,n2)=>{var _Q=Sf(),TQ=1/0;function DQ(e){if(typeof e=="string"||_Q(e))return e;var t=e+"";return t=="0"&&1/e==-TQ?"-0":t}n2.exports=DQ});var s2=v((Upe,a2)=>{var IQ=Z0(),OQ=r2(),PQ=bf(),o2=$i(),RQ=i2();function kQ(e,t,r,n){if(!o2(e))return e;t=OQ(t,e);for(var i=-1,o=t.length,a=o-1,s=e;s!=null&&++i<o;){var l=RQ(t[i]),u=r;if(l==="__proto__"||l==="constructor"||l==="prototype")return e;if(i!=a){var c=s[l];u=n?n(c,l,s):void 0,u===void 0&&(u=o2(c)?c:PQ(t[i+1])?[]:{})}IQ(s,l,u),s=s[l]}return e}a2.exports=kQ});var u2=v((Bpe,l2)=>{var LQ=s2();function $Q(e,t,r){return e==null?e:LQ(e,t,r)}l2.exports=$Q});function p2(e){let{query:t}=(0,f2.default)(window.location.href,!0);return FQ(e,t),e}function FQ(e,t){let r=xQ+e.clientName,n=Object.keys(t).filter(o=>o.startsWith(r));if(!n)return;let i={};n.forEach(o=>{let a=t[o];if(a)try{let s=JSON.parse(a),l=r+m2,u={};if(o===r)u=s;else if(o.startsWith(l)){let c=o.substring(l.length);(0,d2.default)(u,c,s)}(0,c2.default)(i,u)}catch{}}),Object.keys(i).length>0&&e.overrideClientConfig(i)}var c2,d2,f2,m2,xQ,h2=L(()=>{"use strict";c2=Ae(LR()),d2=Ae(u2()),f2=Ae(y0());m2=".",xQ="ecs"+m2});function _f(e,t,r){let n=p2(new Af(e,t,r));function i(o){(0,Nf.useEffect)(()=>{n.init(o)},[])}return{featuresClient:n,createFeature:UQ(n),useFeaturesClientInitParams:i,withFeatures:(o,a,s)=>PR(n,o,a,s)}}function UQ(e){let t=IR(e),r=RR(e);return function(i){let o=pT(i);return o.getConfig=()=>e.getConfig(o),o.isLoaded=()=>e.status===un.ConfigsLoaded,w0.register(o,e.clientName),{useFeature:a=>t(o,a),withFeature:(a,s)=>r(o,a,s),feature:o}}}var MQ,Nf,fy=L(()=>{"use strict";MQ=Ae(mR()),Nf=Ae(sy());D0();ay();ku();cy();h2();C0();});var g2=L(()=>{"use strict";D0();ay();fy();ku();cy();uf();E0();});function Tf(e){return{logEvent:(t,r,n)=>{switch(n){case"Error":(0,$s.trackErrorTrace)(e,{eventName:t,eventData:r});break;case"Warning":(0,$s.trackWarningTrace)(e,{eventName:t,eventData:r});break;default:(0,$s.trackInfoTrace)(e,{eventName:t,eventData:r});break}}}}var $s,py=L(()=>{"use strict";$s=Ae(aa());});var ame,sme,lme,y2=L(()=>{"use strict";g2();py();({featuresClient:ame,createFeature:sme,useFeaturesClientInitParams:lme}=_f("PowerApps-Shell-Test",Tf("shell-features")))});var w2=v((cme,v2)=>{var xu=new Proxy(function(){return xu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:xu},apply:function(){return xu},construct:function(){return{}}}),b2=function(){return xu};Object.setPrototypeOf(b2,xu);v2.exports=b2});var BQ,qQ,C2=L(()=>{"use strict";fu();BQ=Ae(w2()),qQ=Ae(aa());});var E2=L(()=>{"use strict";y2();py();C2();});var vme,xs,wme,A2=L(()=>{"use strict";E2();fy();({featuresClient:vme,createFeature:xs,useFeaturesClientInitParams:wme}=_f("PowerApps-MakerPortal",Tf("powerapps-features")))});var S2,N2,Sme,Nme,_me,Tme,my=L(()=>{"use strict";fT();A2();({feature:S2}=xs({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:Ss.enableAutoInsertionOfCellInRow}})),{feature:N2}=xs({teamName:"MakerPortal",owners:["aansu"],description:"Enable the one grid events for form designer",createdOn:"08/21/2024",fallback:{enableOneGridEventsForFormDesigner:Ss.enableOneGridEvents}}),{feature:Sme}=xs({teamName:"MakerPortal",owners:["adekulkarni"],description:"Disables PBI components and cleans them up from the form",createdOn:"01/03/2023",fallback:{enableFallbackFormTemplate:Ss.disablePBIComponents}}),{feature:Nme}=xs({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:Ss.enableAgentResponse}}),{feature:_me,useFeature:Tme}=xs({teamName:"MakerPortal",owners:["aansu"],description:"Enables delayed localization of custom control",createdOn:"06/08/2025",fallback:{enableDelayedLocalizationForCustomControls:Ss.enableDelayedLocalizationForCustomControls}})});var D2=v((Ime,T2)=>{var Fu=new Proxy(function(){return Fu},{get:function(e,t){return t==="__esModule"?!1:t===Symbol.toPrimitive?function(){return""}:Fu},apply:function(){return Fu},construct:function(){return{}}}),_2=function(){return Fu};Object.setPrototypeOf(_2,Fu);T2.exports=_2});var Zt,Co=L(()=>{"use strict";ht();st();Xt();bu();ue();It();Zt=class extends re{static HighestUsedIndexByClass=new Map;get colspan(){let t=this.getProperty(y.colspan);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set colspan(t){R.IsNullOrUndefined(t)||this.setProperty(y.colspan,String(t))}constructor(t,r){super(t,r)}get id(){let t=this.getProperty(y.id);return t==null?null:t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}set id(t){this.setProperty(y.id,`{${t.ToString()}}`)}set labelId(t){this.setProperty(y.labelId,`{${t.ToString()}}`)}get labelId(){let t=this.getProperty(y.labelId);return t&&t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"?new U(t.substr(1,t.length-2)):new U(t)}get Name(){return this.getProperty(y.Name)}set Name(t){this.setProperty(y.Name,t)}setDisplayName(t,r){for(let i of this.getAllLabels())if(+i.getProperty(y.languagecode)===r){i.setProperty(y.description,t);return}let n=new re(E.formLabel,null);n.setProperty(y.description,t),n.setProperty(y.languagecode,String(r)),this.addGrandChild("labels",n)}getDisplayName(t){for(let r of this.getAllLabels())if(+r.getProperty(y.languagecode)===t)return r.getProperty(y.description)}getAllLabels(){let t=this.getChildren("labels");return t.length!==1?[]:t[0].getChildren("label")}get isLocked(){return+this.getProperty(y.locklevel)==1}set isLocked(t){!this.IsUnboundControl&&this.setProperty(y.locklevel,t?"1":"0")}get availableforphone(){return this.getProcessedValue(y.availableforphone)}set availableforphone(t){R.IsNullOrUndefined(t)||!this.IsAllowedUBCForAvailableOnPhone()||this.setProperty(y.availableforphone,String(t))}get visible(){return this.getProcessedValue(y.visible)}set visible(t){R.IsNullOrUndefined(t)||!this.IsAllowedUBCForVisibleByDefault()||this.setProperty(y.visible,String(t))}isLockLevelSettable(){return!this.IsUnboundControl}get showlabel(){return this.getProcessedValue(y.showlabel)}set showlabel(t){R.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}isAvailableForPhoneSettable(){return this.IsAllowedUBCForAvailableOnPhone()}isVisibleSettable(){return this.IsAllowedUBCForVisibleByDefault()}getProcessedValue(t){let r=this.getProperty(t);return R.IsNullOrUndefined(r)||this.getProperty(t)==="true"}get readonly(){let t=this.getFirstChild(E.formControl);return t?t.disabled:!1}set readonly(t){let r=this.getFirstChild(E.formControl);r&&(r.disabled=t)}get allowfilteroff(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.AllowFilterOff)==="true"}set allowfilteroff(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AllowFilterOff,t)}get autoresolve(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.AutoResolve)==="true"}set autoresolve(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AutoResolve,t)}get defaultviewid(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.DefaultViewId):q.EmptyString}set defaultviewid(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DefaultViewId,t)}get dependentattributename(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.DependentAttributeName):q.EmptyString}set dependentattributename(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeName,t)}get dependentattributetype(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.DependentAttributeType):q.EmptyString}set dependentattributetype(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DependentAttributeType,t)}get disablequickfind(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.DisableQuickFind)==="true"}set disablequickfind(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableQuickFind,t)}get disableviewpicker(){let t=this.getFirstChild(E.formControl);if(t)return t.getParam(y.DisableViewPicker)==="true"}set disableviewpicker(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.DisableViewPicker,t)}get filterrelationshipname(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.FilterRelationshipName):q.EmptyString}set filterrelationshipname(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.FilterRelationshipName,t)}get availableviewids(){let t=this.getFirstChild(E.formControl);return t?t.getParam(y.AvailableViewIds):q.EmptyString}set availableviewids(t){let r=this.getFirstChild(E.formControl);r&&!this.IsUnboundControl&&r.setParameter(y.AvailableViewIds,t)}get IsUnboundControl(){let t=this.getFirstChild(E.formControl);if(t&&t.ClassId){let r=lt.getUniqueIdentifierForControl(t);return!R.IsNullOrUndefined(r)&&lt.isUnboundFormControlByIdentifier(r)}else return!1}IsAllowedUBCForAvailableOnPhone(){let t=this.getFirstChild(E.formControl);if(t){let n=lt.getUniqueIdentifierForControl(t).guidString,i=n===G.GridControl||n===G.TimeLineControl||n===G.TimeLineControlUC;return this.IsUnboundControl?i:!0}return this.NodeName===E.formSection||this.NodeName===E.formTab}IsAllowedUBCForVisibleByDefault(){let t=this.getFirstChild(E.formControl);if(t){let n=lt.getUniqueIdentifierForControl(t).guidString,i=n===G.MapsControl||n===G.WebResourceHtmlControl||n===G.WebResourceImageControl||n===G.IframeControl||n===G.SocialInsightControl;return this.IsUnboundControl?i:!0}else return!0}get events(){let t=this.getChildren(E.formEvents);return t.length===1?t[0].getAllChildren():[]}addEvent(t){this.addGrandChild(E.formEvents,t)}getUsedNodeNameSet(t){return null}getHighestIndexById(t,r){return null}}});var Fs,hy=L(()=>{"use strict";Xt();ue();It();Fs=class extends re{constructor(t,r){super(E.dependency,t),q.IsNullOrEmpty(r)||this.setDefaultProperties(r)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}setDefaultProperties(t){this.id=t}}});var I2,Ms,gy=L(()=>{"use strict";st();hy();ue();It();Co();(function(e){e[e.Form=0]="Form",e[e.Cell=1]="Cell",e[e.Tab=2]="Tab",e[e.Control=3]="Control"})(I2||(I2={}));Ms=class extends Zt{constructor(t,r){super(E.formEvent,t),r&&(this.eventName=r,this.application="false",this.active="false")}set eventName(t){this.setProperty(y.Name,t)}get eventName(){return this.getProperty(y.Name)}set application(t){this.setProperty(y.application,t)}get application(){return this.getProperty(y.application)}set attribute(t){this.setProperty(y.EventAttribute,t)}get attribute(){return this.getProperty(y.EventAttribute)}set relationship(t){this.setProperty(y.Relationship,t)}get relationship(){return this.getProperty(y.Relationship)}set control(t){this.setProperty(y.Control,t)}get control(){return this.getProperty(y.Control)}set active(t){this.setProperty(y.EventActive,t)}get active(){return this.getProperty(y.EventActive)}getAllHandlers(){let t=this.getChildren(E.EventHandlers);return t&&t.length?t[0].getChildren(E.handler):[]}getAllDependencies(){let t=this.getChildren(E.formDependencies);return t.length===0?[]:t[0].getAllChildren()}setDependencies(t){let r=this.getFirstChild(E.formDependencies);if(R.IsNullOrUndefined(r)){if(t.length===0)return;this.addChild(new re(E.formDependencies,this)),r=this.getFirstChild(E.formDependencies)}if(t.length===0)r.getParentNode().deleteChild(r);else{r.deleteAllChildren();for(let n of t)r.addChild(new Fs(r,n.toString()))}}}});var On,Mu=L(()=>{"use strict";ht();Wl();st();oa();ue();It();Tn();On=class extends re{previewVersion;constructor(t){super(E.formControl,t)}updatePreview(){this.previewVersion=Date.now()}get ClassId(){let t=this.getProperty(y.classid);return t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t)}set ClassId(t){this.setProperty(y.classid,`{${t.ToString()}}`)}get dataFieldName(){return this.getProperty(y.datafieldname)}set dataFieldName(t){this.setProperty(y.datafieldname,t)}set id(t){this.setProperty(y.id,t)}get id(){return this.getProperty(y.id)}get UniqueId(){let t=this.getProperty(y.uniqueid);return R.IsNullOrUndefined(t)?null:(t.charAt(0)==="{"&&t.charAt(t.length-1)==="}"&&(t=t.substr(1,t.length-2)),new U(t))}set UniqueId(t){this.setProperty(y.uniqueid,`{${t.ToString()}}`)}get isRequired(){return this.getProperty(y.isRequired)==="true"}set isRequired(t){R.IsNullOrUndefined(t)||this.setProperty(y.isRequired,String(t))}get disableMru(){return this.getParam(y.DisableMru)==="true"}set disableMru(t){R.IsNullOrUndefined(t)||this.setParameter(y.DisableMru,t)}get useMFDForCreate(){return this.getParam(y.UseMFDForCreate)==="true"}set useMFDForCreate(t){R.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForCreate,t)}get useMFDForEdit(){return this.getParam(y.UseMFDForEdit)==="true"}set useMFDForEdit(t){R.IsNullOrUndefined(t)||this.setParameter(y.UseMFDForEdit,t)}get disabled(){return this.getProperty(y.disabled)==="true"}set disabled(t){R.IsNullOrUndefined(t)||this.setProperty(y.disabled,String(t))}get indicationOfSubgrid(){return this.getProperty(y.indicationOfSubgrid)==="true"}set indicationOfSubgrid(t){this.setProperty(y.indicationOfSubgrid,String(t))}getAllParameters(){let t=new ar,r=this.getFirstChild(y.parameters);return r&&r.getAllChildren().forEach(n=>{if(n){let i=n.getAllChildren(),o=i&&i.length>0&&i[0];o&&t.add(n.getNodeName(),o.getNodeName())}}),t}setParameter(t,r){let n=!1;r===null&&(n=!0);let i=(Li.StartTag+r).toString(),o=this.parametersNode;if(o){let a=o.findFirst(s=>s&&s.getNodeName()===t);if(a)if(n){this.deleteFirstGrandChildOfName(E.controlParameters,a);return}else{let s=a.getAllChildren();s&&s.length>0&&s[0]?s[0].setNodeName(i):a.addChild(new re(i,a))}else n||(a=new re(t,o),a.addChild(new re(i,a)),o.addChild(a))}else if(!n){o=new re("parameters",this);let a=new re(t,o);a.addChild(new re(i,a)),o.addChild(a),this.addChild(o)}}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 o=i.getNodeName();return o.charAt(0)===Li.StartTag?o.substring(1):o}}}return null}get parametersNode(){let t=this.getChildren(y.parameters);return t.length===0?null:t[0]}async serializeParameters(t,r){let n=new ar;switch(this.ClassId.guidString.toUpperCase()){case N.LookupControl:if(t&&t.getKeys())if(t.getKeys().forEach(a=>{n.add(a,this.getParam(a))}),t&&t.containsKey("DefaultViewId")){let a=this.getParam("DefaultViewId").replace("{","").replace("}","");n.upsert("DefaultViewId",a)}else{let a=this.getParent(),s=await r.formModelService.lookupControlService.populateDefaultView(this,a.getParentForm().entityName);s&&s.id&&n.upsert("DefaultViewId",s.id.replace("{","").replace("}",""))}break;default:t&&t.getKeys()&&t.getKeys().forEach(a=>{n.add(a,this.getParam(a))});break}let i=n.getInternalObject(),o=[];for(let a in i)i.hasOwnProperty(a)&&o.push({Name:a,Value:i[a]});return o}getIsUnbound(){return this.getProperty(y.isUnbound)==="true"}getAttributeTypeFromClassId(t){if(t)switch(t.toUpperCase()){case N.BooleanControl:case N.CheckboxControl:return 0;case N.DateTimeControl:return 2;case N.DecimalControl:return 3;case N.FloatingNumberControl:return 4;case N.IntegerControl:case N.DurationControl:case N.LanguageControl:case N.TimezoneControl:return 5;case N.LookupControl:return 6;case N.CurrencyControl:return 8;case N.PartyListControl:return 10;case N.ChoiceControl:case N.RelationshipRoleChoiceControl:return 11;case N.ChoiceStatusControl:return 13;case N.TextAreaControl:case N.TextboxControl:case N.LabelControl:case N.EmailAddressControl:case N.UrlControl:case N.TickerControl:case N.ButtonControl:case N.PhoneNumberControl:return 14;case N.ChoicesControl:return 24;default:return}return 14}async toJSON(t){let r=this.getParent(),n=t&&t.formModelService&&t.formModelService.getFormType()===gt.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 Us,yy=L(()=>{"use strict";Xt();Ho();Mu();ue();It();Us=class extends On{constructor(t){super(t)}get targetEntityType(){return this.getParam(y.targetEntityType)||q.EmptyString}set targetEntityType(t){this.setParameter(y.targetEntityType,t)}get viewId(){return q.StripBraces(this.getParam(y.viewId))||q.EmptyString}set viewId(t){this.setParameter(y.viewId,q.AddBraces(t))}get viewIds(){return this.getParam(y.viewIds)||q.EmptyString}set viewIds(t){this.setParameter(y.viewIds,t)}get relationshipName(){return this.getParam(y.RelationshipName)||q.EmptyString}set relationshipName(t){this.setParameter(y.RelationshipName,t)}get isUserView(){return q.IsStrictTrue(this.getParam(y.isUserView))}set isUserView(t){this.setParameter(y.isUserView,t.toString())}get enableViewPicker(){return q.IsStrictTrue(this.getParam(y.enableViewPicker))}set enableViewPicker(t){this.setParameter(y.enableViewPicker,t)}get autoExpand(){return this.getParent().autoexpand&&this.getParam(y.autoExpand)===y.Auto}set autoExpand(t){let r=this.getParent();this.setParameter(y.autoExpand,t?y.Auto:y.Fixed),r.autoexpand=t}get recordsPerPage(){return this.getParam(y.recordsPerPage)?Number(this.getParam(y.recordsPerPage)):Number(y.RecordsPerPageRAControlDefault)}set recordsPerPage(t){this.setParameter(y.recordsPerPage,String(t))}get enableQuickFind(){return q.IsStrictTrue(this.getParam(y.enableQuickFind))}set enableQuickFind(t){this.setParameter(y.enableQuickFind,t)}get teamTemplateId(){return q.StripBraces(this.getParam(y.teamTemplateId))||q.EmptyString}set teamTemplateId(t){this.setParameter(y.teamTemplateId,q.AddBraces(t))}get chartId(){return this.getParam(y.visualizationId)||q.EmptyString}set chartId(t){this.setParameter(y.visualizationId,t)}get enableChartPicker(){return q.IsStrictTrue(this.getParam(y.enableChartPicker))}set enableChartPicker(t){this.setParameter(y.enableChartPicker,t)}get chartGridMode(){switch(this.getParam(y.chartGridMode)){case ln.Chart:return ln.Chart;case ln.Grid:return ln.Grid;default:return ln.All}}set chartGridMode(t){this.setParameter(y.chartGridMode,t)}updateChartGridMode(t){t?this.chartGridMode=ln.Chart:this.chartGridMode=this.enableChartPicker?ln.All:ln.Grid}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.targetEntityType:n.getAllChildren()[0].setNodeName("<"+r.targetEntityType);break;case y.viewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.viewId));break;case y.isUserView:n.getAllChildren()[0].setNodeName("<"+r.isUserView);break;case y.enableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.enableViewPicker);break;case y.RelationshipName:let i=n.getAllChildren(),o="<"+r.relationshipName;i.length?n.getAllChildren()[0].setNodeName(o):n.addChild(new re(o,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 o=n[i].getParameters().get(Ht.dataset)?n[i].getParameters().get(Ht.dataset)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var Bs,by=L(()=>{"use strict";Xt();Ho();Mu();ue();Bs=class extends On{constructor(t){super(t)}get defaultViewId(){return q.StripBraces(this.getParam(y.DefaultViewId))||q.EmptyString}set defaultViewId(t){this.setParameter(y.DefaultViewId,q.AddBraces(t))}get autoResolve(){return q.IsStrictTrue(this.getParam(y.AutoResolve))}set autoResolve(t){this.setParameter(y.AutoResolve,t)}get disableQuickFind(){return q.IsStrictTrue(this.getParam(y.DisableQuickFind))}set disableQuickFind(t){this.setParameter(y.DisableQuickFind,t)}get disableViewPicker(){return q.IsStrictTrue(this.getParam(y.DisableViewPicker))}set disableViewPicker(t){this.setParameter(y.DisableViewPicker,t)}get allowFilterOff(){return q.IsStrictTrue(this.getParam(y.AllowFilterOff))}set allowFilterOff(t){this.setParameter(y.AllowFilterOff,t)}get disableMru(){return q.IsStrictTrue(this.getParam(y.DisableMru))}set disableMru(t){this.setParameter(y.DisableMru,t)}get dependentAttributeName(){return this.getParam(y.DependentAttributeName)||q.EmptyString}set dependentAttributeName(t){this.setParameter(y.DependentAttributeName,t)}get dependentAttributeType(){return this.getParam(y.DependentAttributeType)||q.EmptyString}set dependentAttributeType(t){this.setParameter(y.DependentAttributeType,t)}get filterRelationshipName(){return this.getParam(y.FilterRelationshipName)||q.EmptyString}set filterRelationshipName(t){this.setParameter(y.FilterRelationshipName,t)}get availableViewIds(){return this.getParam(y.AvailableViewIds)||q.EmptyString}set availableViewIds(t){this.setParameter(y.AvailableViewIds,t)}updateDefaultProperties(t,r){for(let n of t)switch(n.getNodeName()){case y.datafieldname:case y.bindAttribute:n.getAllChildren()[0].setNodeName("<"+r.dataFieldName);break;case y.DefaultViewId:n.getAllChildren()[0].setNodeName("<"+q.AddBraces(r.defaultViewId));break;case y.AllowFilterOff:n.getAllChildren()[0].setNodeName("<"+r.allowFilterOff);break;case y.DisableQuickFind:n.getAllChildren()[0].setNodeName("<"+r.disableQuickFind);break;case y.DisableViewPicker:n.getAllChildren()[0].setNodeName("<"+r.disableViewPicker);break;case y.FilterRelationshipName:n.getAllChildren()[0].setNodeName("<"+r.filterRelationshipName);break;case y.DependentAttributeName:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeName);break;case y.DependentAttributeType:n.getAllChildren()[0].setNodeName("<"+r.dependentAttributeType);break;case y.AvailableViewIds:n.getAllChildren()[0].setNodeName("<"+r.availableViewIds);break;case y.DisableMru:n.getAllChildren()[0].setNodeName("<"+r.disableMru);break;case y.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 o=n[i].getParameters().get(Ht.value)?n[i].getParameters().get(Ht.value)[0]:null;if(o){let a=o.getAllChildren();this.updateDefaultProperties(a,this)}else{let a=n[i].getAllChildren()[0].getAllChildren();this.updateDefaultProperties(a,this)}}}}}});var O2,vy,Ir,Uu=L(()=>{"use strict";O2=Ae(D2());Co();ue();st();ht();gy();Mu();bu();_0();s0();Tn();oa();ws();yy();by();wy();os();vy="_",Ir=class e extends Zt{fieldPlaceholder;fieldRequiredLevel;isNewField;cellColType;dependentFields=[];constructor(t){super(E.formCell,t),this.isNewField=!1}get cellType(){return this.cellColType}set cellType(t){this.cellColType=t}setDefaultProperties(t){this.showlabel=t,this.isLocked=!1,R.IsNullOrUndefined(this.getProperty(y.id))&&(this.id=new U(U.NewGuid()))}addControl(t,r,n,i,o,a,s){n instanceof On?this.addChild(n):n instanceof U&&this.addChild(this.getControlWithControlSpecificProperties(t,r,n,i,o,a,s))}removeControl(){return this.deleteChild(this.control)>=0}get isIndependent(){if(!R.IsNullOrUndefined(this.control))return R.IsNullOrUndefined(this.control.dataFieldName)?R.IsNullOrUndefined(this.control.id)?!0:!sa.dependencyFieldCount.containsKey(this.control.id):!sa.dependencyFieldCount.containsKey(this.control.dataFieldName)}createOnLoadEvent(){this.addEvent(new Ms(this,cu.onLoad))}get dependencies(){let t=this.getChildren(E.formEvents);for(let r of t){let n=r.getChildren(E.formEvent);for(let i of n)this.buildDependencyList(i,this.dependentFields)}return this.dependentFields}getNextAvailableControlName(t,r,n,i){let o;if(i&&Zd[i])o=Zd[i].replace(/ /g,vy)+vy;else{o="Control_";let u=new Error("Control class id does not exist or is undefined");(0,O2.trackErrorTrace)(cr,{eventName:`${D_}/getNextAvailableControlName`},u)}let a="new_",s=this.getHighestIndexById(t,i)+1,l=`${o}${a}${s}`;for(;n.has(l);)s++,l=`${o}${a}${s}`;return l}getUnboundControlProperties(t){e.prototype.setProperty.call(t,y.isUnbound,"true"),e.prototype.setProperty.call(t,y.isRequired,"false")}getControlWithControlSpecificProperties(t,r,n,i,o,a,s){let l;o===cn.Grid?(l=new Us(this),l.indicationOfSubgrid=!0):o===cn.Lookup?l=new Bs(this):l=new On(this);let u=n.guidString,c=a||this.getNextAvailableControlName(t,i,this.getUsedNodeNameSet(t),u);if(e.prototype.setProperty.call(l,y.id,c),l.ClassId=n,!R.IsNullOrUndefined(s)&&(l.UniqueId=s),!a&&r)this.getUnboundControlProperties(l);else{let d=lt.getUniqueIdentifierForControl(l);R.IsNullOrUndefined(d)||(lt.getControlDataTypeByControlOrUniqueId(d)===ee.QuickFormCollectionControl||!lt.isUnboundFormControlByIdentifier(d)?o!==cn.Grid&&a&&u!==N.IframeControl&&u!==N.SubgridControl&&u!==N.ReferencePanelSubgridControl&&(l.dataFieldName=a,e.prototype.setProperty.call(l,y.disabled,"false")):(this.rowspan=lt.GetRowSpan(l),(lt.getControlDataTypeByControlOrUniqueId(d)===ee.NotesControl||lt.getControlDataTypeByControlOrUniqueId(d)===ee.TimeLineControl)&&(e.prototype.setProperty.call(l,y.disabled,"false"),l.id=ee.NotesControl)),(lt.getUnboundControlNameFromIdentifier(n)===ee.SubGridControl||lt.getUnboundControlNameFromIdentifier(n)===ee.NotesControl||lt.getUnboundControlNameFromIdentifier(n)===ee.TimeLineControl)&&(this.availableforphone=!0))}return l}buildDependencyList(t,r){if(R.IsNullOrUndefined(t))return;let n=t.getAllChildren();for(let i of n){let o=i.getAllChildren();for(let a of o){let s=a.GetPropertyByParameter(y.id);a.getNodeName()===E.dependency&&s?r.push(s):this.buildDependencyList(a,r)}}}get control(){return this.getFirstChild(E.formControl)}set rowspan(t){this.setProperty(y.rowspan,String(t))}get rowspan(){let t=this.getProperty(y.rowspan);return R.IsNullOrUndefined(t)?1:parseInt(t,10)}set autoexpand(t){this.setProperty(y.auto,String(t))}get autoexpand(){return this.getProperty(y.auto)==="true"}set colspan(t){let r=Number(S0.ONE_COLUMN),n=Number(S0.FOUR_COLUMN);R.IsNullOrUndefined(t)||t>n||t<r||this.setProperty(y.colspan,String(t))}get colspan(){let t=this.getProperty(y.colspan);return R.IsNullOrUndefined(t)?1:parseInt(t,10)}getParentRow(){return this.getAncestor(E.formRow)}getParentSection(){return this.getAncestor(E.formSection)}getParentTab(){return this.getAncestor(E.formTab)}getParentForm(){return this.getAncestor(E.form)}isInHeader(){let t=this.getAncestor(E.formHeader);return!R.IsNullOrUndefined(t)}isInFooter(){let t=this.getAncestor(E.formFooter);return!R.IsNullOrUndefined(t)}isEmpty(){return R.IsNullOrUndefined(this.control)&&!this.IsUserSpacer}getHeaderFooter(){return this.isInHeader()?this.getAncestor(E.formHeader):this.isInFooter()?this.getAncestor(E.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(y.userspacer);return R.IsNullOrUndefined(t)?!1:t==="true"}SetUserSpacer(){this.setProperty(y.userspacer,"true")}ClearUserSpacer(){this.setProperty(y.userspacer,"false")}get columns(){let t=this.getProperty(y.columnName);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}getColumnLayoutValue(t){let r;switch(t){case je.TWO_COLUMN:r="11";break;case je.THREE_COLUMN:r="111";break;case je.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(!R.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();R.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 o=i.isDuplicateCell(this,n),a=this.getRequiredLevel(t);if((a===oo.ApplicationRequired||a===oo.SystemRequired)&&!o||this.isCellLockedByExternal(t)&&!o)return!0}}return!1}getRequiredLevel(t){return!this.control?.dataFieldName||!this.control?.id||this.IsNewField||!this.control?.ClassId?oo.None:t.getEntityAttributeByName(this.control.dataFieldName)?.requiredLevel?.toString()??oo.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()===E.formCell){let i=n;i.control&&i!==this&&r.add(n.control.id)}return!1}),r}getHighestIndexById(t,r){let n=t.findAll(o=>o.getNodeName()===E.formCell&&o.control&&o.control.ClassId.guidString===r),i=0;return n.forEach(o=>{i=Math.max(this.parseControlNameIndex(o.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)===vy&&(r++,n=parseInt(t.substr(r,t.length-r),10)),n}}});var qs,Cy=L(()=>{"use strict";Xt();ue();It();qs=class extends re{isInternal;constructor(t,r,n,i){super(E.library,t),this.isInternal=!!i,q.IsNullOrEmpty(n)||(this.name=r,this.libraryUniqueId=n)}get libraryUniqueId(){let t=this.getProperty(y.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(y.libraryUniqueId,t)}get name(){return this.getProperty(y.libraryName)}set name(t){this.setProperty(y.libraryName,t)}get displayName(){return this.getProperty(y.displayName)}set displayName(t){this.setProperty(y.displayName,t)}get description(){return this.getProperty(y.description)}set description(t){this.setProperty(y.description,t)}}});var pa,Ey=L(()=>{"use strict";st();Uu();ue();It();pa=class extends re{isRowAddedOnDragOver;constructor(t){super(E.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 R.IsNullOrUndefined(t)?!1:this.deleteChild(t)>=0}insertCellAtIndex(t,r){return R.IsNullOrUndefined(t)?!1:(this.insertChildAtIndex(t,r),!0)}isEmpty(){return!this.cells||this.cells.every(t=>t.isEmpty())}getParentSection(){return this.getAncestor(E.formSection)}insertPaddingCellAtIndex(t){let r=new Ir(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(E.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 VQ(e){switch(e){case la.Left:return ca.Left;case la.Right:return ca.Right;case la.Center:return ca.Center;default:return ca.Left}}function GQ(e){switch(e){case Es.Left:return As.Left;case Es.Top:return As.Top;default:return As.Left}}function P2(e){switch(e){case 1:return 1;case 2:return 11;case 3:return 111;case 4:return 1111;default:return 1}}var WQ,ni,Bu=L(()=>{"use strict";T0();ht();st();Xt();my();Uu();ue();Tn();Co();Ey();WQ=115,ni=class e extends Zt{colSpan=1;constructor(t,r){super(t,r)}getSectionType(){let t;switch(this.columns){case 1:t=je.ONE_COLUMN;break;case 11:t=je.TWO_COLUMN;break;case 111:t=je.THREE_COLUMN;break;case 1111:t=je.FOUR_COLUMN;break;default:t=this.colSpan-1}return t}setUniqueName(){let t=this.getParentTab(),r=Ue.namePrefix;if(t){let n=t.Name,i=t.TotalSectionsCount+1;r=n+Ue.namePrefix+i.toString()}else r+=Math.floor(Math.random()*1e3);this.setProperty(y.Name,r)}initializeDefaultProperties(t,r,n){if(n===je.REFERENCE_PANEL){this.addProperty(y.rowheight,"25");let i=`${Ue.referencePanelNamePrefix}${U.NewGuid()}${Ue.namePrefix}`;this.addProperty(y.Name,i)}else this.setUniqueName();if(this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,Ue.IsUserDefined),this.addProperty(y.locklevel,Ue.LockLevel),this.addProperty(y.showlabel,Ue.ShowLabel),this.addProperty(y.showbar,Ue.ShowBar),this.addProperty(y.layout,Ue.Layout),this.addProperty(y.Fieldlabelalignment,Ue.labelAlignment),this.addProperty(y.Fieldlabelposition,Ue.labelPosition),R.IsNullOrUndefined(n))this.addProperty(y.columnName,Ue.columns);else{let i=this.getColumnLayoutValue(n);this.addProperty(y.columnName,i)}this.addProperty(y.LabelWidth,Ue.LabelWidth),this.setDisplayName(r,t)}getColumnLayoutValue(t){let r;switch(t){case je.TWO_COLUMN:r="11";break;case je.THREE_COLUMN:r="111";break;case je.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 R.IsNullOrUndefined(this.columns)?t=this.ColSpan:this.columns.toString().split(q.EmptyString).forEach(r=>{t+=parseInt(r,10)}),t}get ColSpan(){return this.colSpan}initializeRow(t){if(t>0&&t<5){let r=new pa(null);if(this.addGrandChild(E.formRows,r),S2.getConfig().enableAutoInsertionOfCellInRow)for(let n=0;n<t;n++){let i=new Ir(r);i.setDefaultProperties(!1),r.addCell(i)}}}initialize(t,r,n){this.initializeDefaultProperties(t,r,n),n===je.REFERENCE_PANEL&&(n=je.ONE_COLUMN),this.initializeRow(n+1)}setColSpan(t){this.colSpan=t}appendRow(t){this.addGrandChild(E.formRows,t)}insertRowAtIndex(t,r){this.addGrandChildAtIndex(E.formRows,t,r)}insertRowsAtIndex(t,r){if(t&&t.length>0)for(let n=0;n<t.length;n++)this.addGrandChildAtIndex(E.formRows,t[n],r+n)}indexOfRow(t){return this.rows.indexOf(t)}deleteRow(t){return this.deleteFirstGrandChildOfName(E.formRows,t)}deleteRows(t,r){this.deleteGrandChildren(E.formRows,t,r)}get rows(){return this.getRows()}getRows(){let t=this.getChildren(E.formRows);return t.length===0?[]:t[0].getChildren(E.formRow)}get columns(){let t=this.getProperty(y.columnName),r=R.IsNullOrUndefined(t)?NaN:parseInt(t,10);if(isNaN(r)){let n=1;for(let i of this.rows)n=Math.max(n,i.cells.length);return P2(n)}return r}set columns(t){R.IsNullOrUndefined(t)||this.setProperty(y.columnName,String(t))}get rowHeight(){let t=this.getProperty(y.rowheight);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set rowHeight(t){this.setProperty(y.rowheight,String(t))}set autoexpand(t){this.setProperty(y.autoExpand.toLowerCase(),String(t))}get autoexpand(){return this.getProperty(y.autoExpand.toLowerCase())==="true"}get isUserDefined(){return+this.getProperty(y.IsUserDefined)!=0}set isUserDefined(t){t?this.setProperty(y.IsUserDefined,"1"):this.setProperty(y.IsUserDefined,"0")}getParentColumn(){return this.getAncestor(E.formColumn)}getParentTab(){return this.getAncestor(E.formTab)}get hasMultiColumnRow(){return this.getColumnCountValue()>1}get showlabel(){return this.getProperty(y.showlabel)==="true"}set showlabel(t){R.IsNullOrUndefined(t)||this.setProperty(y.showlabel,String(t))}get fieldLabelAlignment(){let t=Ue.labelAlignment,r=this.getProperty(y.Fieldlabelalignment);return R.IsNullOrUndefined(r)?t:r}set fieldLabelAlignment(t){R.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelalignment,t)}get fieldLabelPosition(){let t=this.getProperty(y.Fieldlabelposition);return R.IsNullOrUndefined(t)?Ue.labelPosition:t}set fieldLabelPosition(t){R.IsNullOrUndefined(t)||this.setProperty(y.Fieldlabelposition,String(t))}get showbar(){return this.getProperty(y.showbar)==="true"}set showbar(t){R.IsNullOrUndefined(t)||this.setProperty(y.showbar,String(t))}get labelwidth(){let t=+this.getProperty(y.LabelWidth);return t===0?WQ:t}set labelwidth(t){R.IsNullOrUndefined(t)||t>283&&t<57||this.setProperty(y.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:VQ(this.fieldLabelAlignment),Position:GQ(this.fieldLabelPosition)},Columns:P2(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()===E.formSection){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}isReferencePanelSection(){return!R.IsNullOrUndefined(this)&&!R.IsNullOrUndefined(this.Name)&&this.Name.indexOf(Ue.referencePanelNamePrefix)===0}getAllMultiRowCells(){return this.findAll(t=>{if(t.getNodeName()===E.formCell){let r=t;return!r.isEmpty()&&r.rowspan>1}return!1})}isHeaderOrFooterSection(){return this.NodeName===E.formFooter||this.NodeName===E.formHeader}}});var Eo,Df=L(()=>{"use strict";ue();It();Bu();Eo=class e extends re{constructor(t){super(E.formColumn,t)}initializeDefaultProperties(t){this.addProperty(y.width,t.toString()+"%")}insertSectionAtIndex(t,r){this.addGrandChildAtIndex(E.formSections,t,r)}static createAndInitNewSection(t,r,n){let i=new ni(E.formSection,null);return i.initialize(t,r,n),i}addSectionAtIndex(t,r){this.addGrandChildAtIndex(E.formSections,t,r)}initialize(t,r,n,i=je.ONE_COLUMN){this.initializeDefaultProperties(t);let o=e.createAndInitNewSection(r,n,i);this.addSectionAtIndex(o,this.sections.length),o.setUniqueName()}get parentTab(){return this.getAncestor(E.formTab)}get sections(){let t=this.getChildren("sections");return t.length!==1?[]:t[0].getChildren(E.formSection)}get width(){return this.getProperty(y.width)}set width(t){this.setProperty(y.width,t)}deleteSection(t){return this.deleteFirstGrandChildOfName(E.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(y.Name),Id:this.getProperty(y.id),Label:null,ShowLabel:!1,Visible:!0,LabelId:null,PreviewId:this.getProperty(y.id),Sections:await this.getSectionsJSON(t),Width:this.width}}}});var If,R2=L(()=>{"use strict";ht();ue();Tn();Bu();If=class extends ni{initializeNavArea(t,r,n){this.initializeNavAreaProps(t,r,n)}get AreaName(){return this.Name}initializeNavAreaProps(t,r,n){this.addProperty(y.Name,n),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.columnName,Ue.columns),this.setDisplayName(r,t)}}});var Of,k2=L(()=>{"use strict";Df();ue();R2();Of=class extends Eo{addAndIntializeNavBarSection(t,r,n,i){let o=new If(E.formSection,null);return o.initializeNavArea(t,r,i),this.addGrandChildAtIndex(E.formSections,o,n),o}}});var xi,Pf=L(()=>{"use strict";ht();st();Xt();Df();ue();It();Co();xi=class extends Zt{tabContainsAutoExpandControl;autoExpandCell;constructor(t,r){super(E.formTab,t),this.tabContainsAutoExpandControl=!1}getParentForm(){return this.getAncestor(E.form)}getTabLayoutType(){let t;switch(this.columns.length){case 1:t=ze.ONE_COLUMN;break;case 2:if(parseInt(this.columns[0].width,10)===50&&parseInt(this.columns[1].width,10)===50){t=ze.TWO_COLUMN_EQUAL;break}if(parseInt(this.columns[0].width,10)===67&&parseInt(this.columns[1].width,10)===33){t=ze.TWO_COLUMN_WIDER_LEFT;break}if(parseInt(this.columns[0].width,10)===34&&parseInt(this.columns[1].width,10)===66){t=ze.TWO_COLUMN_WIDER_RIGHT;break}t=ze.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=ze.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=ze.THREE_COLUMN_WIDER_MID;break}t=ze.THREE_COLUMN_CUSTOM_LAYOUT;break;default:}return t}initializeProperties(t,r,n){this.addProperty(y.Name,go.namePrefix+t.toString()),this.addProperty(y.id,new U(U.NewGuid()).guidString),this.addProperty(y.IsUserDefined,go.IsUserDefined),this.addProperty(y.locklevel,go.LockLevel),this.addProperty(y.showlabel,go.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=je.ONE_COLUMN,o=!0,a){let s=this.getChildren(E.formColumns)[0],l=[];switch(t){case ze.ONE_COLUMN:l.push(100);break;case ze.TWO_COLUMN_EQUAL:l.push(50),l.push(50);break;case ze.TWO_COLUMN_WIDER_LEFT:l.push(67),l.push(33);break;case ze.TWO_COLUMN_WIDER_RIGHT:l.push(34),l.push(66);break;case ze.THREE_COLUMN_EQUAL:l.push(34),l.push(33),l.push(33);break;case ze.THREE_COLUMN_WIDER_MID:l.push(28),l.push(44),l.push(28);break;default:}for(let u of l){let c=new Eo(s);c.initialize(u,r,n,i),this.addGrandChild(E.formColumns,c)}}initialize(t,r,n,i,o,a=je.ONE_COLUMN,s=!0,l){this.addChild(new re(E.formColumns,this)),this.initializeProperties(r,n,i),this.initializeColumns(t,n,o,a,s,l)}get columns(){let t=this.getChildren(E.formColumns);return t.length!==1?[]:t[0].getChildren(E.formColumn)}get expanded(){return this.getProcessedValue(y.expanded)}set expanded(t){R.IsNullOrUndefined(t)||this.setProperty(y.expanded,String(t))}get groupName(){return this.getProperty(y.groupName)}get contentType(){return this.getProperty(y.contentType)}set contentType(t){this.setProperty(y.contentType,t)}insertNewColumnAtIndex(t,r,n,i,o){t.initialize(n,i,o),this.addGrandChildAtIndex(E.formColumns,t,r)}insertColumnAtIndex(t,r){this.addGrandChildAtIndex(E.formColumns,t,r)}deleteColumn(t){return this.deleteFirstGrandChildOfName(E.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()===E.formTab){let i=n;i.Name&&!q.GuidStringEquals(i.id.guidString,this.id.guidString)&&r.add(n.Name)}return!1}),r}}});var ma,Ay=L(()=>{"use strict";ht();ue();It();Tn();k2();Pf();ma=class extends xi{constructor(t,r,n){super(t,ze.THREE_COLUMN_EQUAL),this.setDisplayName(r,n),this.id=new U(U.NewGuid())}initializeDefaultProps(){this.addChild(new re(E.formColumns,this)),this.initializeFiveColumns()}get columns(){let t=this.getChildren("columns");return t.length!==1?[]:t[0].getChildren(E.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 o of i.cells)if(o.NavId===t)return o;return null}initializeFiveColumns(){for(let t=0;t<cf.FIVE_COLUMN;t++){let r=new Of(this.getChildren(E.formColumns)[0]);r.initializeDefaultProperties(Z_.FiveEqColumn),this.addGrandChild(E.formColumns,r)}}}});function jQ(e){switch(e){case gt.Main:return yo.Main;case gt.QuickCreate:return yo.QuickCreate;case gt.QuickViewForm:return yo.Quick;case gt.Dialog:return yo.Dialog;default:return yo.None}}function HQ(e,t){if(t===gt.Main){if(e)switch(e.toLowerCase()){case"low":return ho.Low;case"highreadonlyvalues":return ho.HighReadOnlyValues;default:return ho.HighWithControls}return ho.Low}}var kf,zQ,Rf,L2=L(()=>{"use strict";sT();kf=Ae(aa());T0();st();Xt();ws();my();ue();Ho();Kg();oa();Uu();ue();Co();Cy();Ay();Pf();zQ="1920";Rf=class e extends Zt{_formUniqueName;isHeaderDefaulted;consistencyStrong=!1;_formId;_rawFormXml;_entityName;_entityDisplayName;_status;_formName;_langCode;_description;_formType;_formPresentation;parameters=[];_formactivationstate;_changeTracker;_metadataChangeEvent;_etag;constructor(t,r,n,i,o,a,s,l,u){super(E.form,null),this._formUniqueName=o,this._formId=t,this._entityName=r,this._status=n,this._formName=i,this._description=l,this._formType=a,this._formPresentation=s,this._formactivationstate=u,this._changeTracker=new Jd,this._metadataChangeEvent=new ff}get FormLibraries(){let t=this.getFirstChild(E.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(o=>o instanceof Ir).forEach(o=>{let a=o.events;a&&(t=t.concat(a))})}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 Ir){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()===E.internalLibraries),r=[],n="src";return t.length>0&&(r=t.map(i=>{let o=i.GetPropertyByParameter(n).replace("$webresource:",""),a=new qs(void 0,void 0,"",!0);return a.name=o,a.displayName=o,a})),r}getDependentFields(){let t=this.getAllEvents(),r=new Set;return t.forEach(n=>{try{n.getAllDependencies().forEach(o=>{r.add(o.id)})}catch(i){throw(0,kf.trackErrorTrace)(I_,{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 q.IsNullOrEmpty(this.getProperty(y.ShowImage))?!0:this.getProperty(y.ShowImage)!=="false"}set ShowImagecheck(t){t?this.setProperty(y.ShowImage,String(t)):this.setProperty(y.ShowImage,"false")}get ShowNavigation(){return q.IsNullOrEmpty(this.getProperty(y.ShowNavigationbar))?!0:this.getProperty(y.ShowNavigationbar)!=="false"}set ShowNavigation(t){t?this.setProperty(y.ShowNavigationbar,String(t)):this.setProperty(y.ShowNavigationbar,"false")}get MaxWidth(){return q.IsNullOrEmpty(this.getProperty(y.MaxWidth))?zQ:this.getProperty(y.MaxWidth)}set MaxWidth(t){this.setProperty(y.MaxWidth,t)}get headerDensityType(){return this.getProperty(y.HeaderDensityType)}set headerDensityType(t){t&&this.formType===gt.Main?this.setProperty(y.HeaderDensityType,t):this.formType!==gt.Main&&this.headerDensityType&&this.removeProperty(y.HeaderDensityType)}IsMainOrQuickCreateForm(){return this.formType===gt.Main||this.formType===gt.QuickCreate}get FormPresentation(){return this._formPresentation}get LanguageCode(){return this._langCode}set LanguageCode(t){this._langCode=t}get header(){let t=this.getChildren(E.formHeader);return t.length!==1?null:t[0]}set header(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.header),this.addChild(t))}getAllDependencies(){return this.getChildren(E.quickFormDependencies).length===0?[]:this.ConvertModelToArray(this.getChildren(E.quickFormDependencies)[0].getAllChildren())}ConvertModelToArray(t){let r=[];return R.IsNullOrUndefined(t)||t.forEach(n=>{r.push(n.id)}),r}get footer(){let t=this.getChildren(E.formFooter);return t.length!==1?null:t[0]}set footer(t){R.IsNullOrUndefined(t)||(this.deleteChild(this.footer),this.addChild(t))}createAndInitNewTab(t,r,n){let i=new xi(null,t),o=this.getNextTabCounter(this.tabs.length+1);return i.initialize(t,o,this.LanguageCode,r,n),i}addTabAtIndex(t,r){this.addGrandChildAtIndex(E.formTabs,t,r)}createAndInitNewTabWithMarginalControl(t,r,n,i,o){let a=new xi(null,ze.ONE_COLUMN),s=this.getNextTabCounter(this.tabs.length+1);a.initialize(ze.ONE_COLUMN,s,this.LanguageCode,r,n,o,!1),this.addGrandChildAtIndex(E.formTabs,a,i);let l=a.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===go.namePrefix+t.toString())return this.getNextTabCounter(t+1);return t}get allTabs(){let t=this.getChildren(E.formTabs);return t.length!==1?[]:t[0].getChildren(E.formTab)}get CanvasNavigationTab(){if(this.tabs.length>0){let t=this.tabs[this.tabs.length-1];if(t instanceof ma)return t}return null}get NavigationNode(){let t=this.getChildren(E.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(E.formTabs,t)}insertTabAtIndex(t,r){this.addGrandChildAtIndex(E.formTabs,t,r)}insertRelatedTab(t){let r=this.getAllGrandChildren(E.formTabs);if(!R.IsNullOrUndefined(r)){let n=r.length;this.insertTabAtIndex(t,n)}}get isfooterPresent(){return this.getChildren(E.formFooter).length>0}get displayCondition(){let t=this.getChildren(E.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(E.formTabs).indexOf(t)}get ControlDescriptions(){return this.getAllGrandChildren(E.controlDescriptions)}addControlDescriptionNode(t){this.addGrandChild(E.controlDescriptions,t)}deleteControlDescByForControlId(t){let r=this.getControlDescriptionByForControl(t);R.IsNullOrUndefined(r)||this.deleteFirstGrandChildOfName(E.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 Ir))return!1;let o=!0;return r==="Tab"?o=i.getParentTab()!==t.getParentTab():r==="Section"?o=i.getParentSection()!==t.getParentSection():o=i!==t,i instanceof Ir&&i.control&&t.control&&o&&i.control.dataFieldName===t.control.dataFieldName})}isCellEditableGridControl(t){return!t?.control?.indicationOfSubgrid||t.control.ClassId.guidString.toUpperCase()!==N.CustomControl?!1:this.cellHasCustomControlWithName(t,Ti.EditableGridControl)||N2.getConfig()?.enableOneGridEventsForFormDesigner&&this.cellHasCustomControlWithName(t,Ti.PowerAppsOneGrid)}isCellCanvasAppControl(t){return t?.control?.ClassId.guidString.toUpperCase()===N.CustomControl&&this.cellHasCustomControlWithName(t,Ti.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()===E.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 o of r)if(!(o instanceof ma)){let a=o.toJSON(t);n.push(a)}for(let o of n)i.push(await o)}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,kf.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===gt.Main?{HeaderDensity:HQ(this.headerDensityType,this.formType)}:{},InlineEditGridRow:[],InlineQuickForms:[],QuickFormEntities:[],EventHandlers:[],LinkControlSections:[],FormType:jQ(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 Lf,Sy,$2=L(()=>{"use strict";ht();st();ue();It();Co();Lf=class extends Zt{constructor(t){super(E.formDisplayConditions,t)}get Order(){let t=this.getProperty(y.Order);return R.IsNullOrUndefined(t)?null:parseInt(t,10)}set Order(t){this.setProperty(y.Order,t.toString())}get FallbackForm(){return this.getProperty(y.FallbackForm)==="true"}set FallbackForm(t){this.setProperty(y.FallbackForm,t.toString())}addRoles(t){this.deleteAllChildren();for(let r=0;r<t.length;r++)this.addChild(t[r])}isRoleEveryone(){return!!(this.getChildren(E.formEveryOne)&&this.getChildren(E.formEveryOne)[0])}setRoleEveryone(){this.deleteAllChildren(),this.addChild(new Sy(this))}},Sy=class extends re{constructor(t){super(E.formEveryOne,t)}}});var $f,x2=L(()=>{"use strict";ue();It();$f=class extends re{constructor(t,r){super(E.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(y.HandlerUniqueId)}set HandlerUniqueID(t){this.setProperty(y.HandlerUniqueId,t)}get FunctionName(){return this.getProperty(y.functionName)}set FunctionName(t){this.setProperty(y.functionName,t)}get LibraryName(){return this.getProperty(y.libraryNameEventHandler)}set LibraryName(t){this.setProperty(y.libraryNameEventHandler,t)}get Enabled(){return this.getProperty(y.enabledForField)}set Enabled(t){this.setProperty(y.enabledForField,t)}get PassExecutionContext(){return this.getProperty(y.passExecutionContext)}set PassExecutionContext(t){this.setProperty(y.passExecutionContext,t)}get Parameters(){return this.getProperty(y.parameters)}set Parameters(t){this.setProperty(y.parameters,t)}}});var Vs,Ny=L(()=>{"use strict";ue();Bu();Vs=class extends ni{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(E.formCell);for(let o of i)r.push(o)}}return r}get occupiedCells(){return this.cells.filter(t=>!t.isEmpty())}get maxColumns(){return super.getColumnCountValue()}}});var qu,F2=L(()=>{"use strict";ue();Ny();qu=class extends Vs{_customFooter;constructor(t,r){super(E.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 Vu,M2=L(()=>{"use strict";ue();Ny();Vu=class extends Vs{_customHeader;constructor(t,r){super(E.formHeader,t),this._customHeader=r}get customHeader(){return this._customHeader}set customHeader(t){this._customHeader=t}get showCommandBar(){return this.getProcessedValue(y.showCommandBar)}set showCommandBar(t){t!=null&&this.setProperty(y.showCommandBar,String(t))}get showBody(){return this.getProcessedValue(y.showBody)}set showBody(t){t!=null&&this.setProperty(y.showBody,String(t))}get showTabNavigator(){return this.getProcessedValue(y.showTabNavigator)}set showTabNavigator(t){t!=null&&this.setProperty(y.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 Or,ha=L(()=>{"use strict";ht();Xt();ue();Co();Or=class e extends Zt{constructor(t,r){super(t,r)}getTitle(t){for(let r of this.getAllTitles())if(+r.getProperty(y.LCID)===t)return r.getProperty(y.text);return null}getAllTitles(){let t=this.getChildren(E.Titles);return t.length===0?[]:t[0].getChildren(E.Title)}setTitle(t,r){for(let i of this.getAllTitles())if(+i.getProperty(y.LCID)===r){i.setProperty(y.text,t);return}let n=new e(E.Title,null);n.setProperty(y.text,t),n.setProperty(y.LCID,String(r)),this.addGrandChild(E.Titles,n)}get Sequence(){return+this.getProperty(y.Sequence)}set Sequence(t){this.setProperty(y.Sequence,t.toString())}get Area(){return this.getProperty(y.Area)}set Area(t){this.setProperty(y.Area,t)}set Id(t){this.setProperty(y.Id,t)}get Id(){return this.getProperty(y.Id)}get id(){return new U(this.Id??"",!0)}set id(t){this.Id=t.guidString}get Show(){return!0}get Icon(){return this.getProperty(y.icon)}set Icon(t){t=t||q.EmptyString,this.setProperty(y.icon,t)}updateCommonProperties(t,r){this.Area=t.Area,this.Sequence=t.Sequence,this.setTitle(t.getDisplayName(r),r)}}});var Gu,U2=L(()=>{"use strict";(function(e){e[e.NavLinkNotAvailable=-1]="NavLinkNotAvailable",e[e.NavLinkIdConflict=-2]="NavLinkIdConflict",e[e.NavBarNotAvailable=-3]="NavBarNotAvailable"})(Gu||(Gu={}))});var xf,B2=L(()=>{"use strict";st();ue();ha();U2();xf=class extends Or{constructor(t){super(E.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 R.IsNullOrUndefined(r)?Gu.NavLinkNotAvailable:r.length===1?this.deleteChild(r[0]):Gu.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 xe,KQ,q2,b0e,Gs,_y=L(()=>{"use strict";ht();ue();ha();(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"})(xe||(xe={}));KQ=new Map([[xe.Info,"Info"],[xe.Sales,"Sales"],[xe.Service,"Service"],[xe.Marketing,"Marketing"],[xe.ProcessCenter,"ProcessCenter"]]),q2=new Map([["Info",xe.Info],["Sales",xe.Sales],["Service",xe.Service],["Marketing",xe.Marketing],["ProcessCenter",xe.ProcessCenter]]),b0e=new Map([[xe.Info,9e3],[xe.Sales,9200],[xe.Service,9400],[xe.Marketing,9600],[xe.ProcessCenter,9800],[xe.InternetMarketing,1e4],[xe.Async,10200]]),Gs=class extends Or{constructor(t,r){super(E.formNavBarArea,r)}setDefaultPropertiesByType(t,r,n){this.AreaId=KQ.get(t);let i=n?.(`navBarArea.title.${this.AreaId}`)??this.AreaId;this.setTitle(i,r)}get ParentNavigation(){return this.getAncestor(E.formNavigation)}get AreaId(){return this.getProperty(y.Id)}set AreaId(t){this.setProperty(y.Id,t)}get id(){return new U(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 Ws,Ty=L(()=>{"use strict";ue();ha();Ws=class extends Or{constructor(t,r){super(E.formNavBarAreas,r)}get AllNavBarAreaItems(){return this.getChildren(E.formNavBarArea)}get ParentNavigation(){return this.getAncestor(E.formNavigation)}addNavBarArea(t){this.addChild(t)}}});var Ff,V2=L(()=>{"use strict";st();ue();ha();Ff=class extends Or{RelationshipNameUCIRuntime;constructor(t){super(E.formNavBarByRelationshipItem,t)}get RelationshipName(){return this.getProperty(y.RelationshipName)}set RelationshipName(t){this.setProperty(y.RelationshipName,t)}set Show(t){this.setProperty(y.Show,String(t))}get Show(){let t=this.getProperty(y.Show);return R.IsNullOrUndefined(t)||t==="true"}get TitleResourceId(){return this.getProperty(y.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 Mf,G2=L(()=>{"use strict";ue();ha();Mf=class extends Or{constructor(t){super(E.formNavBarItem,t)}get Url(){return this.getProperty(y.url)}set Url(t){this.setProperty(y.url,t)}}});var Uf,W2=L(()=>{"use strict";ht();ue();_y();Ty();ha();Uf=class extends Or{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(E.formNavBarAreas)}setDefaultNavBarAreas(t,r){let n=[xe.Info,xe.Sales,xe.Service,xe.Marketing,xe.ProcessCenter];if(this.navBarAreas){let i=this.navBarAreas?.AllNavBarAreaItems;if(i&&i.length>0){let o=new Set(i.map(a=>q2.get(a.AreaId)));n=n.filter(a=>!o.has(a))}}else{let i=new Ws(E.formNavBarAreas,this);i.isTransient=!0,this.addChild(i)}return n.length>0?(n.forEach(i=>{let o=new Gs(E.formNavBarArea,this.navBarAreas);o.setDefaultPropertiesByType(i,t,r),this.navBarAreas.addNavBarArea(o)}),!0):!1}get navBar(){return this.getFirstChild(E.formNavBar)}get id(){return new U(a0,!0)}replaceNavAreaToGivenIndex(t,r){this.navBarAreas?.AllNavBarAreaItems.indexOf(r)!==-1&&(this.deleteFirstGrandChildOfName(E.formNavBarAreas,r),this.addGrandChildAtIndex(E.formNavBarAreas,r,t))}async getNavBarAreasJSON(t){let r=[],n=[];if(this.navBarAreas?.AllNavBarAreaItems){for(let o of this.navBarAreas.AllNavBarAreaItems)n.push(o.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 z2={};Jr(z2,{ControlType:()=>cn,DeserializationService:()=>Oy,DeserializationServiceScope:()=>Iy,DeserializedFormElementNode:()=>Pr});var Dy,Pr,Iy,cn,Oy,wy=L(()=>{"use strict";Dy=Ae(aa());ht();st();Xt();ws();s0();oa();O_();oT();bu();L2();Uu();Df();Mu();hy();ue();ue();$2();It();Tn();gy();x2();F2();yy();by();M2();Cy();Ey();Bu();Pf();B2();_y();Ty();V2();G2();W2();Pr=class extends re{constructor(t,r){super(t,r)}insertProperty(t,r){this.addProperty(t,r)}insertChild(t){this.addChild(t)}},Iy="DeserializationService";(function(e){e.Grid="Grid",e.Lookup="Lookup",e.Base="Base"})(cn||(cn={}));Oy=class{lcid;constructor(t){this.lcid=t}deSerializeFormXml(t,r,n,i,o,a,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,Dy.trackErrorTrace)(cr,{eventName:Iy,eventData:{error:m}}),new Error(m)}let f=this.createFormModel(d.item(0),r,n,i,o,a,s,l,u,c);return R.IsNullOrUndefined(f.displayCondition)&&s!==gt.Dialog&&this.appendDefaultDisplayCondition(f),f}upsertFieldCount(t,r){let n=sa.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(!R.IsNullOrUndefined(t)){let n=R.ParseXml(r);n!==null&&this.populateElementChildren(t,n.childNodes)}}createFormModel(t,r,n,i,o,a,s,l,u,c){let d=new Rf(r,n,i,o,a,s,l,u,c);return this.populateElementProperties(d,t.attributes),this.populateElementChildren(d,t.childNodes),s===gt.Main&&(this.insertHeaderFooterElementProperties(E.formHeader,d,d.header),this.insertHeaderFooterElementProperties(E.formFooter,d,d.footer)),d}insertHeaderFooterElementProperties(t,r,n){if(R.IsNullOrUndefined(n)){let i=t===E.formHeader?new Vu(r,!0):new qu(r,!0);Pr.prototype.insertProperty.call(i,y.id,"{"+U.NewGuid()+"}"),Pr.prototype.insertProperty.call(i,y.Fieldlabelposition,"Top"),Pr.prototype.insertProperty.call(i,y.columnName,Ue.MarginalControlColumns),Pr.prototype.insertProperty.call(i,y.LabelWidth,Ue.LabelWidth),Pr.prototype.insertProperty.call(i,y.Fieldlabelalignment,"Left");let o=null,a=new pa(o);for(let s=0;s<i.maxColumns;s++){let l=new Ir(a);Pr.prototype.insertProperty.call(l,y.id,"{"+U.NewGuid()+"}"),l.setDisplayName(q.EmptyString,this.lcid),Pr.prototype.insertProperty.call(l,y.showlabel,"false"),a.addCell(l)}i.appendRow(a),t===E.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 Pr(`<${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,Dy.trackErrorTrace)(cr,{eventName:Iy,eventData:{error:n}}),new Error(n)}for(let n=0;n<r.length;n++){let i=r.item(n);i&&(Pr.prototype.insertProperty.call(t,i.name,i.value),t.getNodeName()===E.formCell&&i.name===y.auto&&i.value==="true"&&t.setAutoExpandDetailsForTab())}}populateElementChildren(t,r){for(let n=0;n<r.length;n++){let i=r.item(n),o=this.deSerializeFormXmlNode(i,t);o&&Pr.prototype.insertChild.call(t,o)}}createModelNode(t,r){switch(t.nodeName){case E.form:throw new Error("Form node shouldn't be created using this method");case E.formTab:return new xi(r);case E.formColumn:return new Eo(r);case E.formHeader:return new Vu(r,!1);case E.formFooter:return new qu(r,!1);case E.formSection:return new ni(E.formSection,r);case E.formRow:return new pa(r);case E.formCell:return new Ir(r);case E.formControl:let n=t.attributes,i=t.childNodes.length>0?t.childNodes[0].childNodes:null,o;for(let s=0;s<n.length;s++){let l=n.item(s);if(l.name===y.indicationOfSubgrid&&l.value==="true"||l.name===y.classid&&(l.value?.toLocaleUpperCase()===`{${N.SubgridControl}}`||l.value?.toLocaleUpperCase()===`{${N.ReferencePanelSubgridControl}}`))o=cn.Grid;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.LookupControl}}`)o=cn.Lookup;else if(l.name===y.classid&&l.value?.toLocaleUpperCase()===`{${N.CustomControl}}`)for(let u=0;u<i?.length;u++)i[u].nodeName===y.DefaultViewId&&(o=cn.Lookup)}return o===cn.Grid?new Us(r):o===cn.Lookup?new Bs(r):new On(r);case E.formEvent:return new Ms(r,q.EmptyString);case E.dependency:return this.populateDependencyTable(t),new Fs(r,q.EmptyString);case E.Handler:let a=[];return new $f(a,r);case E.formNavigation:return new Uf(t.nodeName,r);case E.formNavBarArea:return new Gs(t.nodeName,r);case E.formNavBarAreas:return new Ws(t.nodeName,r);case E.formNavBar:return new xf(r);case E.formNavBarByRelationshipItem:return new Ff(r);case E.formNavBarItem:return new Mf(r);case E.formDisplayConditions:return new Lf(r);case E.library:return new qs(r,q.EmptyString,q.EmptyString);case E.controlDescription:return new ef(r);case E.customControl:return this.populateCustomControlConfigurationId(t),new df(r);default:return new Pr(t.nodeName,r)}}populateDependencyTable(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);i.name===y.id&&this.upsertFieldCount(i.value,Zn.DependencyFieldTable)}}populateCustomControlConfigurationId(t){let r=t.attributes;for(let n=0;n<r.length;n++){let i=r.item(n);if(i.name===y.id){let o=new U(i.value.substr(1,i.value.length-2));for(let a=0;a<t.parentNode.attributes.length;a++){let s=t.parentNode.attributes.item(a);if(s.name===y.ForControl){let l=s.value.substr(1,i.value.length-2);lt.CustomControlIdMap.upsert(l,o);break}}break}}}}});var j2={};Jr(j2,{SerializationService:()=>Py,SerializationServiceScope:()=>JQ,SerializedFormElementNode:()=>zs});var JQ,zs,Py,H2=L(()=>{"use strict";Xt();It();Tn();Ay();JQ="SerializationService",zs=class extends re{fetchNodeName(){return this.getNodeName()}enumerateProperties(){return this.getAllProperties()}enumerateChildren(){return this.getAllChildren()}},Py=class{langCode;constructor(t){this.langCode=t}serializeFormXmlNode(t){let r=zs.prototype.fetchNodeName.call(t);if(r.charAt(0)===Li.StartTag)return q.EscapeXml(r.substr(1),!1);if(t.isTransient&&!t.isDirty())return q.EmptyString;let n=zs.prototype.enumerateProperties.call(t),i=zs.prototype.enumerateChildren.call(t);if(!(t instanceof ma)){let o=`<${r}`;if(n.length!==0&&(o+=` ${this.getPropertiesString(n)}`),i.length===0)o+=" />";else{let a=q.EmptyString;for(let s of i)a+=this.serializeFormXmlNode(s);o+=`>${a}</${r}>`}return o}return q.EmptyString}getPropertiesString(t){let r=q.EmptyString;return t.forEach((n,i)=>{i!==0&&(r+=" "),r+=`${n.key}="${q.EscapeXml(n.value,!0)}"`}),r}}});var $y=v(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.completeRecordAsStored=js.completeLabelsAsStored=void 0;var Ry=uo(),YQ="E7A81278-8635-4D9E-8D4D-59480B391C5B",QQ=new Set(["tab","section","cell"]);function Pn(e){let t=[];for(let r=e.firstChild;r;r=r.nextSibling)r.nodeType===1&&t.push(r);return t}function Ao(e,t){return Pn(e).find(r=>r.tagName===t)}function J2(e,t){return e.length===t.length&&e.every((r,n)=>r.tagName===t[n].tagName)}function ky(e){let t=Ao(e,"control");return t?(t.getAttribute("datafieldname")||"")!==""?!0:(t.getAttribute("classid")||"").replace(/[{}]/g,"").toUpperCase()===YQ:!1}function Ly(e,t){var r,n;let i=((r=Ao(e,"control"))===null||r===void 0?void 0:r.getAttribute("id"))||"";return i!==""&&i===(((n=Ao(t,"control"))===null||n===void 0?void 0:n.getAttribute("id"))||"")}function XQ(e,t){if(Ao(e,"labels"))return;let r=Pn(e),n=Pn(t),i=n[0];if(!i||i.tagName!=="labels"||n.length!==r.length+1||!J2(r,n.slice(1)))return;let o=Pn(i);if(!(o.length===0||o.some(s=>s.tagName!=="label"||!s.hasAttribute("description")||!s.hasAttribute("languagecode"))||!(e.tagName==="cell"&&ky(e)&&Ly(e,t))&&o.some(s=>s.getAttribute("description")!=="")))return i}function ZQ(e,t){let r=eX(e.ownerDocument,t),n=Pn(e)[0];n?e.insertBefore(r,n):e.appendChild(r)}function eX(e,t){let r=e.createElement("labels");for(let n of Pn(t))r.appendChild(Y2(e,n));return r}function Y2(e,t){let r=e.createElement("label");for(let n=0;n<t.attributes.length;n+=1){let{name:i,value:o}=t.attributes[n];(i==="description"||i==="languagecode")&&r.setAttribute(i,o)}return r}function K2(e,t){let r=Ao(e,"labels");return r?Pn(r).find(n=>n.tagName==="label"&&n.getAttribute("languagecode")===String(t)):void 0}function tX(e,t,r){if(e.tagName!=="cell"||!ky(e)||!Ly(e,t))return!1;let n=K2(e,r),i=K2(t,r),o=i?.getAttribute("description")||"";return!n||!n.hasAttribute("description")||(n.getAttribute("description")||"")!==""||o===""?!1:(n.setAttribute("description",o),!0)}function rX(e,t){if(e.tagName!=="cell"||!ky(e)||!Ly(e,t))return;let r=Ao(e,"labels"),n=Ao(t,"labels");if(!r||!n)return;let i=Pn(r),o=Pn(n),a=f=>f.tagName==="label"&&f.hasAttribute("description")&&f.hasAttribute("languagecode");if(o.length<=i.length||!i.every(a)||!o.every(a))return;let s=new Map(i.map(f=>[f.getAttribute("languagecode")||"",f]));if(s.size!==i.length)return;let l=new Set,u=0,c=[],d=[];for(let f of o){let m=f.getAttribute("languagecode")||"";if(l.has(m))return;l.add(m);let p=s.get(m);if(!p){d.push(f);continue}if((p.getAttribute("description")||"")!==(f.getAttribute("description")||""))return;u+=1,c.push(...d.map(h=>({label:h,before:p}))),d=[]}return c.push(...d.map(f=>({label:f}))),u===i.length?c:void 0}function Q2(e,t,r,n){if(e.tagName!==t.tagName)return;if(QQ.has(e.tagName)){let a=XQ(e,t);a&&(ZQ(e,a),n.changed=!0),tX(e,t,r)&&(n.changed=!0);let s=rX(e,t),l=Ao(e,"labels");if(s&&l){for(let{label:u,before:c}of s){let d=Y2(e.ownerDocument,u);c?l.insertBefore(d,c):l.appendChild(d)}n.changed=!0}}let i=Pn(e),o=Pn(t);J2(i,o)&&i.forEach((a,s)=>Q2(a,o[s],r,n))}function X2(e,t,r){if(e===t)return e;let n,i;try{n=(0,Ry.parseXmlRoot)(e,""),i=(0,Ry.parseXmlRoot)(t,"")}catch{return e}let o={changed:!1};return Q2(n,i,r,o),o.changed?(0,Ry.serializeNode)(n):e}js.completeLabelsAsStored=X2;function nX(e,t,r){let n=e?.formxml,i=t?.formxml;if(typeof n!="string"||typeof i!="string")return e;let o=X2(n,i,r);return o===n?e:{...e,formxml:o}}js.completeRecordAsStored=nX});var bk=v(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.pcfReadIssues=ce.pcfBindingIssues=ce.commitPcfState=ce.mayCommitPcfState=ce.reconcilePcfDescriptions=ce.customControlNeeds=ce.mintPcfIdentity=ce.planPcfBinding=ce.projectPcfBindings=ce.supportsPcfFormType=ce.storedBindingOf=ce.hasCustomControl=ce.sameAsStored=ce.readPcfDescription=ce.newPcfDescription=ce.editorText=ce.nativeClassFor=ce.pcfEntryLayout=void 0;var iX=(bu(),Br(aT)),oX=Q(),Z2=pt(),V=Dd(),aX=Hh(),Ee=rn(),Ui=["web","phone","tablet"],Wu={web:"2",phone:"0",tablet:"1"},ik=new Map([["2","web"],["0","phone"],["1","tablet"]]),sX=["phone","web","tablet"];function qf(e){let t=new Set(e),r=sX.filter(n=>!t.has(n));return{defaults:r.length===0?[null]:r,named:Ui.filter(n=>t.has(n))}}ce.pcfEntryLayout=qf;function dr(e){return Array.isArray(e)?e:[]}function ut(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function zu(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Fy(e){return{n:`<${e}`,a:[],c:[]}}function ok(e){return typeof e?.n=="string"&&e.n.startsWith("<")}function ek(e){let t=dr(e.c);return t.length===1&&ok(t[0])&&(0,V.rawText)(e)!==""?(0,V.rawText)(e):void 0}function fn(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ak(e){return`{${e.replace(/^\{|\}$/g,"").toUpperCase()}}`}function My(e){try{let t=(0,iX.mapFieldTypeToControl)(e.attributeTypeName,e.format);return t?ak(String(t)):void 0}catch{return}}ce.nativeClassFor=My;var Uy=new Map([["Whole.None",{digits:0,min:-2147483648,max:2147483647}],["Whole.Duration",{digits:0,min:0,max:2147483647}],["Decimal",{digits:7,min:-922337203685477,max:922337203685477}],["FP",{digits:5,min:-1e11,max:1e11}],["Currency",{digits:4,min:-1e11,max:1e11}]]),sk=new Set(["TwoOptions","Boolean"]),lk=new Set(["SingleLine.Text","SingleLine.TextArea","SingleLine.Email","SingleLine.Phone","SingleLine.URL","SingleLine.Ticker","Multiple"]),lX=new Map([...[...lk].map(e=>[e,100]),["SingleLine.TextArea",2e3],["Multiple",1048576]]),uX=/^[A-Za-z_][A-Za-z0-9_.-]*$/;function uk(e){return uX.test(e)&&e!=="__proto__"}function By(e){return e!==void 0&&(e==="Enum"||Uy.has(e)||sk.has(e)||lk.has(e))}function ck(e){return typeof e=="number"?e:e!==""&&!Number.isNaN(Number(e))?Number(e):void 0}function ju(e,t){let r=e!==void 0?Uy.get(e):void 0;if(r&&typeof t!="boolean"){let n=ck(t);if(n!==void 0)return n.toFixed(r.digits)}return typeof t=="boolean"?t?"true":"false":String(t)}ce.editorText=ju;function cX(e,t,r){var n;let i=[];for(let o of e.properties){let a=o.name,s;if(o.isPrimary?s=t:o.usage==="input"&&zu(r,a)?s=ju(o.defaultType,r[a]):s=(n=o.defaultValue)!==null&&n!==void 0?n:"",s==="")continue;let l=[];o.defaultType&&l.push(["type",o.defaultType]),!o.isPrimary&&(o.defaultType==="Enum"||o.usage==="input")&&l.push(["static","true"]),i.push({n:a,a:l,c:[Fy(s)]})}return i}function dk(e,t,r,n,i){var o,a;let s=(o=n.formFactors)!==null&&o!==void 0?o:Ui.filter(d=>qy(i).has(d)),l=qf(s),u=cX(i,t,(a=n.parameters)!==null&&a!==void 0?a:{}),c=d=>JSON.parse(JSON.stringify(d));return{n:"controlDescription",a:[["forControl",e]],c:[...l.defaults.map(d=>({n:"customControl",a:d===null?[["id",r]]:[["id",r],["formFactor",Wu[d]]],c:[{n:"parameters",a:[],c:[{n:"datafieldname",a:[],c:[Fy(t)]}]}]})),...l.named.map(d=>({n:"customControl",a:[["name",n.name],["formFactor",Wu[d]]],c:[{n:"parameters",a:[],c:c(u)}]}))]}}ce.newPcfDescription=dk;function qy(e){return new Set(Ui.filter(t=>e.availableOn[t]))}function Bf(e){var t;let r=dr(e.c);if(r.length!==1||((t=r[0])===null||t===void 0?void 0:t.n)!=="parameters"||dr(r[0].a).length>0)return;let n=dr(r[0].c);return n.every(i=>ut(i)&&!ok(i))?n:void 0}function ga(e){let t=dr(e?.c);if(t.length===0||!t.every(p=>ut(p)&&p.n==="customControl"))return;let r=t.findIndex(p=>(0,V.rawAttr)(p,"name")!==void 0);if(r<=0)return;let n=t.slice(r),i=(0,V.rawAttr)(n[0],"name"),o=[];for(let p of n){let h=dr(p.a),g=h.length===2?ik.get(h[1][1]):void 0;if(!g||h[0][0]!=="name"||h[0][1]!==i||h[1][0]!=="formFactor"||o.includes(g))return;o.push(g)}let a=qf(o);if(!fn(a.named,o)||i==="")return;let s=Bf(n[0]);if(!s||!n.every(p=>fn(Bf(p),s)))return;let l=t.slice(0,r);if(l.length!==a.defaults.length)return;let u=(0,V.rawAttr)(l[0],"id"),c;for(let p=0;p<l.length;p+=1){let h=a.defaults[p],g=h===null?[["id",u??""]]:[["id",u??""],["formFactor",Wu[h]]],b=Bf(l[p]),w=b?.length===1&&b[0].n==="datafieldname"&&dr(b[0].a).length===0?ek(b[0]):void 0;if(!u||!fn(dr(l[p].a),g)||w===void 0||c!==void 0&&w!==c)return;c=w}let d={},f={},m;for(let p of s){let h=dr(p.a),g=ek(p),b=h.map(w=>w[0]);if(g===void 0||!uk(p.n)||zu(d,p.n)||p.n===m)return;if((0,V.rawAttr)(p,"static")===void 0){if(m!==void 0||g!==c||!(b.length===0||fn(b,["type"])))return;m=p.n;continue}if((0,V.rawAttr)(p,"static")!=="true"||!(fn(b,["static"])||fn(b,["type","static"])))return;d[p.n]=g,f[p.n]=(0,V.rawAttr)(p,"type")}if(!(m===void 0||c===void 0||u===void 0))return{binding:{name:i,...Object.keys(d).length>0?{parameters:d}:{},...o.length===Ui.length?{}:{formFactors:o}},fieldName:c,nativeClass:u,parameterTypes:f,boundProperty:m}}ce.readPcfDescription=ga;function fk(e,t,r){return e===t?!0:typeof e!="string"&&(t===String(e)||t===ju(r,e))}function pk(e){let t=e.formFactors;return t===void 0?[...Ui]:Array.isArray(t)?Ui.filter(r=>t.includes(r)):[]}function xy(e,t){var r,n,i;if(e.name!==t.binding.name||!fn(pk(e),(r=t.binding.formFactors)!==null&&r!==void 0?r:Ui))return!1;let o=(n=e.parameters)!==null&&n!==void 0?n:{},a=(i=t.binding.parameters)!==null&&i!==void 0?i:{},s=Object.keys(o);return s.length!==Object.keys(a).length?!1:s.every(l=>zu(a,l)&&fk(o[l],a[l],t.parameterTypes[l]))}ce.sameAsStored=xy;function yt(e){return ut(e)&&e.customControl!==void 0}ce.hasCustomControl=yt;function Mi(e,t){var r;return t?dr((r=(0,V.descriptionsRegion)(e))===null||r===void 0?void 0:r.node.c).filter(n=>n?.n==="controlDescription"&&(0,V.normGuid)((0,V.rawAttr)(n,"forControl"))===t):[]}function Vy(e,t){let r=Mi(e.bag,(0,V.controlUniqueId)(t));return r.length===1?ga(r[0]):void 0}ce.storedBindingOf=Vy;function Gy(e){let t=(0,V.effectiveFormType)(e);return t==="Main"||t==="QuickCreate"}ce.supportsPcfFormType=Gy;function dX(e){if(!Gy(e))return;let t=(0,V.controlUniqueIds)(e);for(let{cell:r}of(0,V.typedCellSites)(e)){let n=r.control;if(!ut(n)||!n.fieldName||!Fi(n.classId)||t.get((0,V.controlUniqueId)(n))!==1)continue;let i=Vy(e,n);i&&i.fieldName===n.fieldName&&(n.customControl=JSON.parse(JSON.stringify(i.binding)))}}ce.projectPcfBindings=dX;function Fi(e){return typeof e=="string"&&e.replace(/^\{|\}$/g,"").toUpperCase()===V.CUSTOM_CONTROL_CLASS_ID}var dn=(e,t)=>({kind:"refused",rule:e,message:t});function fX(e){let t=e.replace(/^\{|\}$/g,"");return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)&&!Fi(e)}function tk(e,t,r){var n,i;let o=ga(r);if(!o)return dn("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");if(o.fieldName!==e.fieldName)return dn("pcf-binding-rebind",`the binding is filed for "${o.fieldName}": remove it, push, then bind the new column`);if(t.name!==o.binding.name)return dn("pcf-binding-control-swap",`the binding uses "${o.binding.name}": to use another control, remove customControl, push, then add it`);let a=ut(t.parameters)?t.parameters:{},s=(n=o.binding.parameters)!==null&&n!==void 0?n:{},l=Object.keys(a).sort();if(!fn(l,Object.keys(s).sort()))return dn("pcf-binding-edit-parameter-set",`an edit changes parameter values only \u2014 the binding stores exactly ${Object.keys(s).sort().map(g=>`"${g}"`).join(", ")||"none"}: to add or remove one, remove the binding, push, then add it`);let u=l.filter(g=>!fk(a[g],s[g],o.parameterTypes[g])),c=u.find(g=>ju(o.parameterTypes[g],a[g]).trim()==="");if(c!==void 0)return dn("pcf-binding-edit-parameter-set",`"${c}" cannot be cleared in place \u2014 an empty value is not written, which removes the parameter: remove the binding, push, then add it`);let d=pk(t),f=(i=o.binding.formFactors)!==null&&i!==void 0?i:[...Ui],m=d.filter(g=>!f.includes(g)),p=f.filter(g=>!d.includes(g));if(u.length===0&&m.length===0&&p.length===0)return{kind:"unchanged"};let h=u.find(g=>!By(o.parameterTypes[g]));if(h!==void 0){let g=o.parameterTypes[h];return dn("pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which the property editor does not write: remove the binding, push, then add it`)}return(m.length>0||p.length>0)&&!fX(o.nativeClass)?dn("pcf-binding-edit-fallback",`the factors the control leaves fall back to "${o.nativeClass}", which is not a native control class: remove the binding, push, then add it`):{kind:"edit",description:r,stored:o,changed:u,factors:d,added:m,removed:p}}function pX(e,t){return t&&(0,V.typedCellSites)(e).find(({cell:n})=>yt(n.control)&&(0,V.controlUniqueId)(n.control)===t)?{descriptions:Mi(e.bag,t)}:void 0}function mk(e,t){let r=new Map,n=mX(e),i=new Set,o=new Map,a=u=>{let c=o.get(u);return c||(c={before:[],now:[]},o.set(u,c)),c},s=(u,c)=>({cell:yX(u),uid:(0,V.controlUniqueId)(c),bound:yt(c)});for(let{cell:u}of(0,V.typedCellSites)(e)){let c=u.control;ut(c)&&typeof c.id=="string"&&c.id&&a(c.id).now.push({...s(u,c),control:c})}for(let{cell:u}of(0,V.typedCellSites)(t)){let c=u.control;if(!ut(c))continue;let d=s(u,c);d.bound&&d.uid&&i.add(d.uid),typeof c.id=="string"&&c.id&&a(c.id).before.push(d)}let l=(u,c)=>{let d=u.filter(f=>f.cell===c);return d.length===1?d[0]:void 0};for(let[u,{before:c,now:d}]of o){let f=c.filter(D=>D.bound&&D.uid!==""&&!n.has(D.uid));if(f.length===0||d.length===0)continue;let m=[...c],p=D=>{let P=m.findIndex(D);return P<0?void 0:m.splice(P,1)[0]},g=d.filter(D=>!D.bound||D.uid===""?!0:p(P=>P.bound&&P.uid===D.uid)!==void 0?!1:!i.has(D.uid)).filter(D=>{let P=D.cell?l(c,D.cell):void 0;return!P||!l(d,D.cell)||!m.includes(P)?!0:(m.splice(m.indexOf(P),1),f.includes(P)&&D.uid!==P.uid&&rk(D.control)&&r.set(D.control,nk(P.uid)),!1)}),b=[],w=(D,P)=>{let x=D.uid===""?void 0:p(K=>K.uid===D.uid&&(!P||K.bound===D.bound));return x&&f.includes(x)&&b.push(x),x!==void 0},S=g.filter(D=>!w(D,!0)).filter(D=>!w(D,!1)&&rk(D.control)),O=f.filter(D=>m.includes(D));if(S.length===0||O.length===0&&b.length===0)continue;let k=[...O,...b],I=O.length===1&&S.length===1&&m.length===1?nk(O[0].uid):`the controls with id "${u}" cannot all be matched to those last synced \u2014 their cells do not tell them apart \u2014 and ${k.map(D=>`{${D.uid}}`).join(", ")} no longer ${k.length===1?"names":"name"} a control: which control held ${k.length===1?"that binding":"those bindings"} is ambiguous. Re-fetch the form; to drop a bound control, remove its customControl and push before removing the control`;for(let D of S)r.set(D.control,I)}return r}function mX(e){let t=(0,V.controlUniqueIds)(e),r=new Map;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=ut(i.control)?(0,V.controlUniqueId)(i.control):"";o&&!r.has(o)&&r.set(o,i.control)}let n=new Set;for(let[i,o]of t){let a=r.get(i);(a===void 0||yt(a)||o>1)&&n.add(i)}return n}function rk(e){return yt(e)||e.genPage===void 0&&Fi((0,V.effectiveClassId)(e))}function hX(e,t){let r=o=>(0,V.typedCellSites)(o).flatMap(({cell:a,pointer:s})=>{let l=a.control;if(!ut(l)||yt(l)||l.genPage!==void 0||!Fi((0,V.effectiveClassId)(l)))return[];let u=(0,V.controlUniqueId)(l);return u===""||Mi(o.bag,u).length===0?[{control:l,pointer:`${s}/control`}]:[]}),n=o=>`${String(o.id)}\0${(0,V.controlUniqueId)(o)}`,i=r(t).map(({control:o})=>n(o));return r(e).filter(({control:o})=>{let a=i.indexOf(n(o));return a<0?!0:(i.splice(a,1),!1)})}var gX="this control would keep the custom-control class with no binding (its customControl and uniqueid are gone): remove the binding from an unchanged copy \u2014 keep its uniqueid, and the native control comes back \u2014 or set classId to the column's native control";function nk(e){return`this control's uniqueid changed since it was last synced (it was {${e}}), and a binding is linked to its description by it: restore it (re-fetch the form), or remove the binding, push, then add the new one`}function yX(e){let t=typeof e.id=="string"?e.id.trim():"";return(0,V.normGuid)(t)||t.toLowerCase()}function Hu(e,t,r,n){let i=t.customControl,o=(0,V.controlUniqueId)(t),a=Mi(e.bag,o),s=r?mk(e,r).get(t):void 0;if(s!==void 0)return dn("pcf-binding-unique-id",s);let l=r?pX(r,o):void 0;if(l){let c=l.descriptions,d=c.length===1?ga(c[0]):void 0;if(d&&d.fieldName!==t.fieldName)return dn("pcf-binding-rebind",`the binding is filed for "${d.fieldName}": remove it, push, then bind the new column`);if(c.length===1&&a.length===1&&fn(c[0],a[0]))return tk(t,i,a[0]);let f=a.length===1?ga(a[0]):void 0;return d&&f&&f.fieldName===t.fieldName&&xy(i,d)&&xy(i,f)?{kind:"unchanged"}:dn("pcf-binding-edit-changed-description","the binding\u2019s description changed since it was last synced (edited in the bag, re-keyed or deleted): re-fetch the form before changing the binding")}if(a.length===0)return{kind:"new"};if(a.length>1)return dn("pcf-binding-other-control","the control already has a description the SDK cannot read as a binding; adding would replace it");let u=tk(t,i,a[0]);return n&&(u.kind==="edit"||u.kind==="unchanged")?u.kind==="unchanged"?u:dn("pcf-binding-edit","this binding\u2019s description was never synced from the server (no baseline): changing it in place is not supported \u2014 remove customControl, push, then add the new one"):u}ce.planPcfBinding=Hu;function hk(e){return e.kind==="edit"&&(e.changed.length>0||e.added.length>0)}function bX(e){let t=n=>yt(n.control)&&(!n.control.id||!n.id||(0,V.authoredUniqueId)(n.control)===void 0);if(!(0,V.typedCellSites)(e).some(({cell:n})=>t(n)))return e;let r=JSON.parse(JSON.stringify(e));for(let{cell:n}of(0,V.typedCellSites)(r)){if(!t(n))continue;let i=n.control;i.id||(i.id=(0,Z2.newId)()),n.id||(n.id=(0,Z2.newId)()),(0,V.authoredUniqueId)(i)===void 0&&(0,V.setUniqueId)(i)}return r}ce.mintPcfIdentity=bX;function vX(e,t){let r=new Set,n=new Set;for(let{cell:i}of(0,V.typedCellSites)(e)){let o=i.control;if(!yt(o)||!ut(o.customControl))continue;let a=o.customControl.name;if(typeof a!="string"||a===""||typeof o.fieldName!="string"||!o.fieldName)continue;let s=Hu(e,o,t,!0);s.kind==="new"?(r.add(a),n.add(o.fieldName)):hk(s)&&r.add(a)}return{controls:[...r],columns:[...n],...n.size>0&&(0,V.effectiveFormType)(e)==="QuickCreate"?{requireCreateEligibility:!0}:{}}}ce.customControlNeeds=vX;function wX(e,t,r){var n,i,o,a,s,l;let u=e.bag,c=new Map;for(let{cell:f,pointer:m}of(0,V.typedCellSites)(e)){let p=f.control;if(!yt(p)||!ut(p.customControl))continue;let h=(0,V.controlUniqueId)(p);h&&Mi(u,h).length>0&&c.set(p,{plan:Hu(e,p,t,!0),pointer:`${m}/control/customControl`})}let d=(0,V.descriptionsRegion)(u);if(d&&t){let f=(0,V.controlUniqueIds)(e),m=new Set,p=new Map;for(let{cell:h}of(0,V.typedCellSites)(e)){let g=ut(h.control)?(0,V.controlUniqueId)(h.control):"";g&&!p.has(g)&&p.set(g,h.control)}for(let{cell:h}of(0,V.typedCellSites)(t)){let g=h.control;if(!yt(g))continue;let b=(0,V.controlUniqueId)(g),w=Mi(t.bag,b),C=Mi(u,b);if(w.length!==1||C.length!==1||!fn(w[0],C[0])||!ga(C[0]))continue;let S=p.get(b);if(S&&!yt(S)){if(((n=f.get(b))!==null&&n!==void 0?n:0)>1)continue;let O=(o=(i=ga(C[0]))===null||i===void 0?void 0:i.nativeClass)!==null&&o!==void 0?o:"";S.classId=O.replace(/^\{|\}$/g,"").toUpperCase(),CX(S,"uniqueid"),m.add(b)}else!S&&!f.has(b)&&m.add(b)}m.size>0&&(d.node.c=dr(d.node.c).filter(h=>!(h?.n==="controlDescription"&&m.has((0,V.normGuid)((0,V.rawAttr)(h,"forControl"))))))}for(let{cell:f}of(0,V.typedCellSites)(e)){let m=f.control;if(!yt(m)||!ut(m.customControl))continue;Fi(m.classId)||(m.classId=V.CUSTOM_CONTROL_CLASS_ID);let p=(0,V.controlUniqueId)(m);if(!p){if((0,V.authoredUniqueId)(m)!==void 0)continue;p=(0,V.setUniqueId)(m)}let h=c.get(m);if(h){if(h.plan.kind==="refused")throw new oX.ValidationError("form",e.id,[(0,Ee.issue)(h.pointer,h.plan.rule,h.plan.message)]);h.plan.kind==="edit"&&EX(h.plan,m.customControl);continue}let g=r?.control(m.customControl.name),b=r?.column(e.entityLogicalName,m.fieldName),w=b?.kind==="found"?My(b.value):void 0;if(g?.kind!=="found"||!w)continue;d||(d={i:(0,V.embedAppendIndex)(u),node:{n:"controlDescriptions",a:[],c:[]}},u.c.push(d));let C=((l=(s=dr((a=m.bag)===null||a===void 0?void 0:a.a).find(O=>O[0]==="uniqueid"))===null||s===void 0?void 0:s[1])!==null&&l!==void 0?l:"").trim(),S=C.startsWith("{")?C:`{${p}}`;d.node.c.push(dk(S,m.fieldName,w,m.customControl,g.value))}}ce.reconcilePcfDescriptions=wX;function CX(e,t){ut(e.bag)&&(e.bag.a=dr(e.bag.a).filter(r=>r[0]!==t))}function EX(e,t){var r,n;let i=dr(e.description.c),o=i.findIndex(g=>(0,V.rawAttr)(g,"name")!==void 0),a=i.slice(0,o),s=i.slice(o),l=(r=t.parameters)!==null&&r!==void 0?r:{};for(let g of s)for(let b of(n=Bf(g))!==null&&n!==void 0?n:[])e.changed.includes(b.n)&&(b.c=[Fy(ju(e.stored.parameterTypes[b.n],l[b.n]))]);if(e.added.length===0&&e.removed.length===0)return;let u=g=>JSON.parse(JSON.stringify(g)),c=g=>{var b;let w=(0,V.rawAttr)(g,"formFactor");return w===void 0?null:(b=ik.get(w))!==null&&b!==void 0?b:null},d=(0,V.rawAttr)(a[0],"id"),f=(0,V.rawAttr)(s[0],"name"),m=qf(e.factors),p=m.defaults.map(g=>{let b=a.find(C=>c(C)===g);if(b)return b;let w=u(a[0]);return w.a=g===null?[["id",d]]:[["id",d],["formFactor",Wu[g]]],w}),h=m.named.map(g=>{let b=s.find(C=>c(C)===g);if(b)return b;let w=u(s[0]);return w.a=[["name",f],["formFactor",Wu[g]]],w});e.description.c=[...p,...h]}function AX(e){return(0,V.typedCellSites)(e).some(({cell:t})=>yt(t.control))}ce.mayCommitPcfState=AX;function SX(e,t){var r;let n=JSON.parse(JSON.stringify(e)),i=!1;for(let{cell:o}of(0,V.typedCellSites)(n)){let a=o.control;if(!yt(a))continue;let s=Vy(n,a);if(!s||s.fieldName!==a.fieldName)continue;let l=t(V.CUSTOM_CONTROL_CLASS_ID),u=dr((r=a.bag)===null||r===void 0?void 0:r.a).find(c=>c[0]==="classid");(!Fi(a.classId)||a.type!==l||u!==void 0&&!Fi(u[1])||!fn(a.customControl,s.binding))&&(Fi(a.classId)||(a.classId=V.CUSTOM_CONTROL_CLASS_ID),a.type=l,u&&!Fi(u[1])&&(u[1]=ak(V.CUSTOM_CONTROL_CLASS_ID)),a.customControl=JSON.parse(JSON.stringify(s.binding)),i=!0)}return i?n:e}ce.commitPcfState=SX;var NX=new Set(["name","parameters","formFactors"]);function _X(e,t,r){let n=[],i=(0,V.controlUniqueIds)(e);for(let{cell:o,pointer:a}of(0,V.typedCellSites)(e)){let s=o.control;yt(s)&&DX(e,s,`${a}/control`,i,n,t,r?.atPush===!0)}return t&&IX(e,t,n),n}ce.pcfBindingIssues=_X;function TX(e,t,r){let n=r.length;if(!ut(e))return r.push((0,Ee.issue)(t,"pcf-binding-shape","customControl must be an object")),!1;for(let i of Object.keys(e))NX.has(i)||r.push((0,Ee.issue)(`${t}/${i}`,"pcf-binding-unknown-key",`customControl has no "${i}"`));if((typeof e.name!="string"||e.name.trim()==="")&&r.push((0,Ee.issue)(`${t}/name`,"pcf-binding-shape","name must be the control's non-empty customcontrols name")),e.parameters!==void 0)if(!ut(e.parameters))r.push((0,Ee.issue)(`${t}/parameters`,"pcf-binding-shape","parameters must be an object"));else for(let[i,o]of Object.entries(e.parameters))typeof o=="string"||typeof o=="boolean"||typeof o=="number"&&Number.isFinite(o)||r.push((0,Ee.issue)(`${t}/parameters/${i}`,"pcf-binding-shape","a parameter must be a string, a finite number or a boolean"));if(e.formFactors!==void 0){let i=e.formFactors;Array.isArray(i)&&i.length>0&&i.every(a=>typeof a=="string"&&Ui.includes(a))&&new Set(i).size===i.length||r.push((0,Ee.issue)(`${t}/formFactors`,"pcf-binding-shape","formFactors must be distinct 'web', 'phone' and 'tablet', at least one"))}return r.length===n}function DX(e,t,r,n,i,o,a){var s;let l=`${r}/customControl`,u=TX(t.customControl,l,i);t.fieldName||i.push((0,Ee.issue)(l,"pcf-binding-unbound","a PCF binding needs a control bound to a column (fieldName)")),t.genPage!==void 0&&i.push((0,Ee.issue)(l,"pcf-binding-with-genpage","a control cannot embed a page and bind a PCF control")),Gy(e)||i.push((0,Ee.issue)(l,"pcf-binding-form-type","PCF bindings are supported on Main and Quick Create forms only (not Quick View or Card)")),t.classId!==void 0&&typeof t.classId!="string"&&i.push((0,Ee.issue)(`${r}/classId`,"pcf-binding-class-id","classId must be a string"));let c=(0,V.authoredUniqueId)(t),d=(0,V.controlUniqueId)(t);if(c!==void 0&&!d?i.push((0,Ee.issue)(`${r}/bag`,"pcf-binding-unique-id","the control's uniqueid must be a GUID")):d&&((s=n.get(d))!==null&&s!==void 0?s:0)>1&&i.push((0,Ee.issue)(`${r}/bag`,"pcf-binding-unique-id","another control carries the same uniqueid")),!u)return;let f=Hu(e,t,o,a);f.kind==="refused"&&i.push((0,Ee.issue)(l,f.rule,f.message))}function IX(e,t,r){var n;let i=new Map,o=mk(e,t);for(let{cell:l,pointer:u}of(0,V.typedCellSites)(e)){let c=ut(l.control)?(0,V.controlUniqueId)(l.control):"";if(c&&!i.has(c)&&i.set(c,{control:l.control,pointer:`${u}/control`}),ut(l.control)&&!yt(l.control)){let d=o.get(l.control);d!==void 0&&r.push((0,Ee.issue)(`${u}/control`,"pcf-binding-unique-id",d))}}let a=(0,V.controlUniqueIds)(e);for(let{cell:l}of(0,V.typedCellSites)(t)){if(!yt(l.control))continue;let u=(0,V.controlUniqueId)(l.control),c=i.get(u);!c||yt(c.control)||(((n=a.get(u))!==null&&n!==void 0?n:0)>1?r.push((0,Ee.issue)(c.pointer,"pcf-binding-unique-id","another control carries this binding\u2019s uniqueid; removing the binding would delete its description too")):fn(Mi(t.bag,u),Mi(e.bag,u))?c.control.fieldName!==l.control.fieldName&&r.push((0,Ee.issue)(c.pointer,"pcf-binding-rebind","remove the binding, push, then bind the new column")):r.push((0,Ee.issue)(c.pointer,"pcf-binding-removed-changed","the binding changed since it was last pushed; remove it from an unchanged copy (re-fetch)")))}let s=new Set(r.map(l=>l.pointer));for(let{pointer:l}of hX(e,t))s.has(l)||r.push((0,Ee.issue)(l,"pcf-binding-unique-id",gX))}var OX=new Set(["Form.Card"]),PX="MscrmControls.ModelForm.ModelFormControl";function gk(e,t){var r;if(e.hasDataset||e.hasGroups)return"it has a data-set or groups";if(!e.isBound)return"its first property is not bound to a column";let n=e.properties;if(n.filter(s=>s.usage==="bound").length!==1)return"it has more than one bound property";let i=n.map(s=>s.name);if(i.some(s=>!s)||new Set(i).size!==i.length)return"a property has no name, or two share one";let o=i.find(s=>!uk(s));if(o!==void 0)return`the property name "${o}" cannot be written as an element`;if(t===PX||n.some(s=>s.defaultType!==void 0&&OX.has(s.defaultType)))return"a property needs a special encoding";if(n.some(s=>s.usage==="output"&&s.defaultValue!==null&&s.defaultValue!==""))return"an output property has a default";let a=n.find(s=>s.usage==="input"&&!By(s.defaultType));return a?`input "${a.name}" has a type the property editor does not write as text (${(r=a.defaultType)!==null&&r!==void 0?r:"none"})`:void 0}function RX(e){return e.ofType!==null?[e.ofType]:e.ofTypeGroup}function yk(e,t,r=e.defaultType){if(r==="Enum")return e.enumValues.some(o=>o.value===String(t))?void 0:`must be one of ${e.enumValues.map(o=>`"${o.value}"`).join(", ")}`;let n=r!==void 0?Uy.get(r):void 0;if(n){let o=typeof t=="boolean"?void 0:ck(t);return o===void 0||o<n.min||o>n.max?`must be a number from ${n.min.toFixed(n.digits)} through ${n.max.toFixed(n.digits)}`:void 0}if(r!==void 0&&sk.has(r))return t===!0||t===!1||t==="true"||t==="false"?void 0:"must be true or false";let i=r!==void 0?lX.get(r):void 0;return i!==void 0&&String(t).length>i?`must be at most ${i} characters`:e.required&&String(t)===""?"is required":void 0}function kX(e,t,r){var n,i,o,a;let s={issues:[]},l=s.issues;for(let{cell:u,pointer:c}of(0,V.typedCellSites)(e)){let d=u.control;if(!yt(d)||!d.fieldName)continue;let f=d.customControl;if(!ut(f)||typeof f.name!="string")continue;let m=`${c}/control/customControl`,p=Hu(e,d,r,!0);if(p.kind==="edit"){hk(p)&&xX(p,f,m,t,s);continue}if(p.kind!=="new")continue;let h=t?.control(f.name),g=t?.column((n=e.entityLogicalName)!==null&&n!==void 0?n:"",d.fieldName);if(!h||h.kind==="unavailable"){(i=s.unavailable)!==null&&i!==void 0||(s.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${f.name}" could not be read`,...h?.kind==="unavailable"?{cause:h.error}:{}});continue}if(h.kind!=="found"){l.push((0,Ee.issue)(`${m}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${f.name}" (${h.kind})`));continue}if(!g||g.kind==="unavailable"){(o=s.unavailable)!==null&&o!==void 0||(s.unavailable={code:"PCF_COLUMN_UNAVAILABLE",message:`the column "${d.fieldName}" could not be read`,...g?.kind==="unavailable"?{cause:g.error}:{}});continue}let b=gk(h.value,f.name);if(b){l.push((0,Ee.issue)(`${m}/name`,"pcf-binding-unsupported-control",`"${f.name}" is not supported: ${b}`));continue}let w=h.value.properties.find(x=>x.isPrimary),C=g.kind==="found"?g.value:void 0,S=C?(a=(0,aX.manifestTypesForColumn)(C.attributeTypeName,C.format,C.formatName))!==null&&a!==void 0?a:[]:[];C!==void 0&&!C.isPrimaryId&&C.isValidForForm&&My(C)!==void 0&&RX(w).some(x=>S.includes(x))?(0,V.effectiveFormType)(e)==="QuickCreate"&&C?.isValidForCreate!==!0&&l.push((0,Ee.issue)(m,"pcf-binding-quick-create-column",`"${d.fieldName}" cannot be set when a record is created, so a Quick Create form cannot bind it`)):l.push((0,Ee.issue)(m,"pcf-binding-incompatible-column",`"${f.name}" cannot be bound to "${d.fieldName}"`));let k=new Map(h.value.properties.filter(x=>x.usage==="input").map(x=>[x.name,x])),I=ut(f.parameters)?f.parameters:{};for(let[x,K]of Object.entries(I)){let Oe=k.get(x);if(!Oe){l.push((0,Ee.issue)(`${m}/parameters/${x}`,"pcf-binding-unknown-parameter",`"${f.name}" has no input "${x}"`));continue}let Vt=yk(Oe,K);Vt&&l.push((0,Ee.issue)(`${m}/parameters/${x}`,"pcf-binding-parameter-value",`"${x}" ${Vt}`))}for(let x of k.values())x.required&&!zu(I,x.name)&&!x.defaultValue&&l.push((0,Ee.issue)(`${m}/parameters`,"pcf-binding-missing-parameter",`"${x.name}" is required`));let D=qy(h.value),P=Array.isArray(f.formFactors)?f.formFactors:void 0;(P?P.some(x=>!D.has(x)):D.size===0)&&l.push((0,Ee.issue)(`${m}/formFactors`,"pcf-binding-form-factor",`"${f.name}" is available on ${D.size===0?"no form factor":[...D].join(", ")}`))}return s}ce.pcfReadIssues=kX;function LX(e,t){return t===void 0||!By(t)?!1:e.ofType!==null?e.ofType===t:e.ofTypeGroup.includes(t)}function $X(e,t,r){var n,i;let o=gk(e,t);if(o)return`it is no longer supported (${o})`;let a=e.properties.find(d=>d.isPrimary);if(a?.name!==r.boundProperty)return`its bound property is now "${(n=a?.name)!==null&&n!==void 0?n:"none"}", not "${r.boundProperty}"`;let s=(i=r.binding.parameters)!==null&&i!==void 0?i:{},l=new Set(e.properties.filter(d=>d.usage==="input").map(d=>d.name)),u=Object.keys(s).find(d=>!l.has(d));if(u!==void 0)return`"${u}" is no longer one of its inputs`;let c=e.properties.find(d=>d.usage==="input"&&d.required&&!d.defaultValue&&!zu(s,d.name));return c?`it now requires "${c.name}", which the binding does not store`:void 0}function xX(e,t,r,n,i){var o,a,s;let l=i.issues,u=n?.control(t.name);if(!u||u.kind==="unavailable"){(o=i.unavailable)!==null&&o!==void 0||(i.unavailable={code:"PCF_MANIFEST_UNAVAILABLE",message:`the manifest of "${t.name}" could not be read`,...u?.kind==="unavailable"?{cause:u.error}:{}});return}if(u.kind!=="found"){l.push((0,Ee.issue)(`${r}/name`,"PCF_CONTROL_NOT_FOUND",`no single installed control is named "${t.name}" (${u.kind})`));return}let c=$X(u.value,t.name,e.stored);if(c){l.push((0,Ee.issue)(r,"pcf-binding-edit-manifest-changed",`"${t.name}" changed since this binding was written: ${c} \u2014 remove the binding, push, then add it`));return}let d=new Map(u.value.properties.filter(h=>h.usage==="input").map(h=>[h.name,h])),f=l.length;for(let h of Object.keys((a=e.stored.binding.parameters)!==null&&a!==void 0?a:{})){let g=e.stored.parameterTypes[h];LX(d.get(h),g)||l.push((0,Ee.issue)(`${r}/parameters/${h}`,"pcf-binding-edit-stored-type",`"${h}" is stored ${g===void 0?"with no type":`as type "${g}"`}, which "${t.name}" does not take for it now: remove the binding, push, then add it`))}if(l.length>f)return;let m=(s=t.parameters)!==null&&s!==void 0?s:{};for(let h of e.changed){let g=yk(d.get(h),m[h],e.stored.parameterTypes[h]);g&&l.push((0,Ee.issue)(`${r}/parameters/${h}`,"pcf-binding-parameter-value",`"${h}" ${g}`))}let p=qy(u.value);e.added.some(h=>!p.has(h))&&l.push((0,Ee.issue)(`${r}/formFactors`,"pcf-binding-form-factor",`"${t.name}" is available on ${p.size===0?"no form factor":[...p].join(", ")}`))}});var Lk=v(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.classIdForAttributeType=kr.QUICK_VIEW_CLASS_ID=kr.NOTES_CLASS_ID=kr.SUBGRID_CLASS_ID=kr.formRegistration=kr.FormAdapter=void 0;var Bi=(ht(),Br(C_)),vk=(st(),Br(E_)),FX=(It(),Br(S_)),bt=(ue(),Br(A_)),rt=(oa(),Br(N_)),MX=(wy(),Br(z2)),UX=(H2(),Br(j2)),vt=so(),wk=Qr(),Rr=rn(),BX=_g(),Ks=pt(),qX=$y(),er=Dd(),ii=bk(),Hs=Q(),Jy=le(),Wy=lo(),_k=Jo(),VX={[bt.FormType.Main]:"Main",[bt.FormType.QuickCreate]:"QuickCreate",[bt.FormType.QuickViewForm]:"QuickView",[bt.FormType.Card]:"Card"},Vf={Main:bt.FormType.Main,QuickCreate:bt.FormType.QuickCreate,QuickView:bt.FormType.QuickViewForm,Card:bt.FormType.Card},GX=new Map(Object.entries(rt.ControlClassId).map(([e,t])=>[String(t).toUpperCase(),e]));function Yy(e){var t;return e&&(t=GX.get(e.toUpperCase()))!==null&&t!==void 0?t:"Unknown"}function Ku(e){return e.getAllProperties().map(t=>[t.key,t.value])}function ya(e){let t=new Map;for(let r of e.getAllProperties())t.has(r.key)||t.set(r.key,r.value);return t}function Tk(e,t){return e.getAllChildren().find(r=>r.getNodeName()===t)}function Qy(e,t){var r,n;let i=Tk(e,"labels");if(!i)return"";let o=i.getAllChildren().filter(s=>s.getNodeName()==="label"),a=(r=o.find(s=>ya(s).get("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return a&&(n=ya(a).get("description"))!==null&&n!==void 0?n:""}function WX(e){let t=Tk(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 o=n.getAllChildren()[0],a=o?o.getNodeName():"";a.charAt(0)==="<"&&(a=a.substring(1)),r[i]=a}return r}function Dk(e){return/^1+$/.test(e)&&e.length>=1&&e.length<=4?e.length:1}function zy(e){let t=Math.min(Math.max(Math.trunc(e),1),4);return"1".repeat(t)}function Ju(e){return String(e??"").replace(/[{}]/g,"")}function jy(e){return`{${Ju(e)}}`}function Hy(e,t){if(e===void 0||e==="")return t;let r=Number(e);return Number.isNaN(r)?t:r}function Wf(e,t,r){let n=e.getAllChildren(),i=n.findIndex(u=>u.getNodeName()===t),o=[];if(n.forEach((u,c)=>{c!==i&&o.push({i:c,node:(0,vt.rawFromNode)(u)})}),i<0)return{modeled:[],bag:{a:Ku(e),c:o}};let a=n[i],s=[],l=[];return a.getAllChildren().forEach((u,c)=>{u.getNodeName()===r?s.push(u):l.push({i:c,node:(0,vt.rawFromNode)(u)})}),{modeled:s,bag:{a:Ku(e),c:o,w:{n:a.getNodeName(),a:Ku(a),c:l}}}}function Ik(e,t,r){let n=[],i=[];return e.getAllChildren().forEach((o,a)=>{o.getNodeName()===t&&(!r||n.length===0)?n.push(o):i.push({i:a,node:(0,vt.rawFromNode)(o)})}),{modeled:n,bag:{a:Ku(e),c:i}}}function Ck(e,t){let{modeled:r,bag:n}=Wf(e,"tabs","tab");return{tabs:r.map(i=>zX(i,t)),bag:n}}function zX(e,t){var r,n;let i=ya(e),{modeled:o,bag:a}=Wf(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:Qy(e,t),expanded:i.get("expanded")==="true",visible:i.has("visible")?i.get("visible")==="true":!0,columns:o.map(s=>jX(s,t)),bag:a}}function jX(e,t){let r=ya(e),{modeled:n,bag:i}=Wf(e,"sections","section");return{width:r.get("width"),sections:n.map(o=>HX(o,t)),bag:i}}function HX(e,t){var r,n,i;let o=ya(e),{modeled:a,bag:s}=Wf(e,"rows","row");return{id:(r=o.get("id"))!==null&&r!==void 0?r:"",name:(n=o.get("name"))!==null&&n!==void 0?n:"",label:Qy(e,t),visible:o.has("visible")?o.get("visible")==="true":!0,showLabel:o.get("showlabel")==="true",columns:Dk((i=o.get("columns"))!==null&&i!==void 0?i:"1"),rows:a.map(l=>KX(l,t)),bag:s}}function KX(e,t){let{modeled:r,bag:n}=Ik(e,"cell",!1);return{cells:r.map(i=>JX(i,t)),bag:n}}function JX(e,t){var r;let n=ya(e),{modeled:i,bag:o}=Ik(e,"control",!0),a=Qy(e,t),s=n.get("showlabel")==="true",l=i[0]?YX(i[0],a,s):null;return{id:(r=n.get("id"))!==null&&r!==void 0?r:"",visible:n.has("visible")?n.get("visible")==="true":!0,colspan:Hy(n.get("colspan"),1),rowspan:Hy(n.get("rowspan"),1),control:l,bag:o}}function YX(e,t,r){var n,i;let o=ya(e),a=Ju((n=o.get("classid"))!==null&&n!==void 0?n:""),s=o.get("datafieldname");return{id:(i=o.get("id"))!==null&&i!==void 0?i:"",classId:a,fieldName:s||null,type:Yy(a),isRequired:o.get("isrequired")==="true",isReadOnly:o.get("disabled")==="true",label:t,showLabel:r,parameters:WX(e),bag:{a:Ku(e),c:e.getAllChildren().map((l,u)=>({i:u,node:(0,vt.rawFromNode)(l)}))}}}function _o(e){return e.a.length===0&&e.c.length===0&&!e.w}function Ok(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function ba(e,t){var r;let n=new Set(e.a.map(a=>a[0])),i=_o(e),o=[];for(let a of t)if(n.has(a.key)){let s=(r=Ok(e,a.key))!==null&&r!==void 0?r:"";a.matches(s)||o.push([a.key,a.render()])}else i?o.push([a.key,a.render()]):a.matches(a.absentDefault)||o.push([a.key,a.render()]);return(0,vt.mergeAttrs)(e.a,o)}var So=(e,t)=>({key:e,matches:r=>r===t,render:()=>t,absentDefault:""}),No=(e,t,r=!1)=>({key:e,matches:n=>n==="true"===t,render:()=>String(t),absentDefault:String(r)}),Ek=(e,t,r=1)=>({key:e,matches:n=>Hy(n,r)===t,render:()=>String(t),absentDefault:String(r)});function Xy(e,t){return{n:"labels",a:[],c:[{n:"label",a:[["description",e],["languagecode",String(t)]],c:[]}]}}function Ky(e){return{n:"parameters",a:[],c:Object.keys(e).map(t=>{var r;return{n:(0,Jy.assertXmlName)(t,"Form control parameter name"),a:[],c:[{n:`<${(r=e[t])!==null&&r!==void 0?r:""}`,a:[],c:[]}]}})}}function QX(e,t){var r,n;let i=e.c.find(a=>a.n==="label"&&a.a.some(s=>s[0]==="languagecode"&&s[1]===String(t))),o=i??e.c.find(a=>a.n==="label");return(n=(r=o?.a.find(a=>a[0]==="description"))===null||r===void 0?void 0:r[1])!==null&&n!==void 0?n:""}function XX(e,t,r){let n=!1,i=e.c.map(o=>o.n!=="label"||!o.a.some(s=>s[0]==="languagecode"&&s[1]===String(r))?o:(n=!0,{...o,a:o.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 Zy(e,t,r){let n=e.c.findIndex(o=>o.node.n==="labels");if(n<0){if(!t||_o(e))return e;let a=e.c.some(s=>s.i===0)?e.c.map(s=>({...s,i:s.i+1})):e.c;return{...e,c:[{i:0,node:Xy(t,r)},...a]}}if(QX(e.c[n].node,r)===t)return e;let i=XX(e.c[n].node,t,r);return{...e,c:e.c.map((o,a)=>a===n?{...o,node:i}:o)}}function ZX(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],o=i?i.n:"";o.charAt(0)==="<"&&(o=o.substring(1)),t[n]=o}return t}function eZ(e,t){let r=Object.keys(e),n=Object.keys(t);return r.length===n.length&&r.every(i=>e[i]===t[i])}function tZ(e,t){return e.a.some(r=>r[0]===t)?{...e,a:e.a.filter(r=>r[0]!==t)}:e}function rZ(e,t){let r=e.c.findIndex(i=>i.node.n==="parameters");if(r<0){if(Object.keys(t).length===0||_o(e))return e;let i=e.c.reduce((o,a)=>a.i>o?a.i:o,-1);return{...e,c:[...e.c,{i:i+1,node:Ky(t)}]}}if(eZ(ZX(e.c[r].node),t))return e;let n=Ky(t);return{...e,c:e.c.map((i,o)=>o===r?{...i,node:n}:i)}}function zf(e,t,r,n){if(e.w){let a={n:e.w.n,a:e.w.a.map(s=>[s[0],s[1]]),c:(0,vt.spliceChildren)(e.w.c,r)};return(0,vt.spliceChildren)(e.c,[a])}let i=n(),o={n:t,a:[],c:r};return e.c.length===0?[...i,o]:(0,vt.spliceChildren)(e.c,[...i,o])}function nZ(e,t){let r=e.tabs.map(n=>iZ(n,t));return{n:"form",a:ba(e.bag,[]),c:e.tabs.length===0&&_o(e.bag)?[]:zf(e.bag,"tabs",r,()=>[])}}function Pk(e,t,r){return t&&!e.c.some(n=>n.node.n==="labels")?[Xy(t,r)]:[]}function iZ(e,t){let r=[So("id",e.id),So("name",e.name),No("expanded",e.expanded),No("visible",e.visible,!0)],n=e.columns.map(o=>oZ(o,t)),i=Zy(e.bag,e.label,t);return{n:"tab",a:ba(i,r),c:zf(i,"columns",n,()=>Pk(i,e.label,t))}}function oZ(e,t){let r=e.width!==void 0?[So("width",e.width)]:[],n=e.sections.map(i=>aZ(i,t));return{n:"column",a:ba(e.bag,r),c:zf(e.bag,"sections",n,()=>[])}}function aZ(e,t){let r=[So("id",e.id),So("name",e.name),No("showlabel",e.showLabel),No("visible",e.visible,!0),{key:"columns",matches:o=>Dk(o)===e.columns,render:()=>zy(e.columns),absentDefault:zy(1)}],n=e.rows.map(o=>sZ(o,t)),i=Zy(e.bag,e.label,t);return{n:"section",a:ba(i,r),c:zf(i,"rows",n,()=>Pk(i,e.label,t))}}function sZ(e,t){let r=e.cells.map(n=>lZ(n,t));return{n:"row",a:ba(e.bag,[]),c:_o(e.bag)?r:(0,vt.assembleChildren)(e.bag,r)}}function lZ(e,t){let r=e.control?e.control.showLabel:Ok(e.bag,"showlabel")==="true",n=[So("id",e.id),No("showlabel",r),No("visible",e.visible,!0),Ek("colspan",e.colspan),Ek("rowspan",e.rowspan)],i=e.control?[uZ(e.control)]:[],o;if(_o(e.bag))o=[...e.control&&e.control.label?[Xy(e.control.label,t)]:[],...i];else{let a=e.control?Zy(e.bag,e.control.label,t):e.bag;o=(0,vt.assembleChildren)(a,i)}return{n:"cell",a:ba(e.bag,n),c:o}}function uZ(e){let t=[So("id",e.id),{key:"classid",matches:i=>Ju(i)===e.classId,render:()=>jy(e.classId||String(rt.ControlClassId.TextboxControl)),absentDefault:""}];e.fieldName!==null&&t.push(So("datafieldname",e.fieldName)),t.push(No("disabled",e.isReadOnly)),t.push(No("isrequired",e.isRequired));let r=e.fieldName===null?tZ(e.bag,"datafieldname"):e.bag,n;return _o(r)?n=Object.keys(e.parameters).length>0?[Ky(e.parameters)]:[]:n=(0,vt.assembleChildren)(rZ(r,e.parameters),[]),{n:"control",a:ba(r,t),c:n}}var cZ={make:(e,t)=>new FX.FormElementNode(e,t),setProp:(e,t,r)=>e.setProperty(t,r),addChild:(e,t)=>e.addChild(t)};function Ak(e,t,r,n){(0,Wy.installDomShim)();let i=fZ(e,r);(0,er.reconcileEmbedDescriptions)(i,n),(0,ii.reconcilePcfDescriptions)(i,n,r?.pcf);let o=(0,vt.rebuildRaw)(nZ(i,t),cZ,null);return new UX.SerializationService(t).serializeFormXmlNode(o)}function dZ(e){return JSON.parse(JSON.stringify(e))}function fZ(e,t){let r=dZ(e);r.bag||(r.bag=(0,vt.emptyBag)()),r.tabs||(r.tabs=[]),wZ(r.bag),t&&pZ(r,t);for(let n of r.tabs)mZ(n);return r}function pZ(e,t){var r;let n=(r=e.entityLogicalName)!==null&&r!==void 0?r:"";eb(e,i=>{let o=i.fieldName,a=i;if(!o||a.label!==void 0&&a.classId!==void 0)return;let s=t.resolveField(n,o);s&&(a.label===void 0&&s.displayName&&(a.label=s.displayName),a.classId===void 0&&s.attributeType&&(a.classId=kk(s.attributeType)))})}function Sk(e){let t=[];return eb(e,r=>t.push(r)),t}function eb(e,t){var r,n,i,o,a;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(o=u.rows)!==null&&o!==void 0?o:[])for(let d of(a=c.cells)!==null&&a!==void 0?a:[])d.control&&t(d.control)}function mZ(e){e.id||(e.id=Bi.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)hZ(t);e.bag||(e.bag=(0,vt.emptyBag)())}function hZ(e){e.sections||(e.sections=[]);for(let t of e.sections)gZ(t);e.bag||(e.bag=(0,vt.emptyBag)()),e.width===void 0&&_o(e.bag)&&(e.width="100%")}function gZ(e){e.id||(e.id=Bi.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)yZ(t);e.bag||(e.bag=(0,vt.emptyBag)())}function yZ(e){e.cells||(e.cells=[]);for(let t of e.cells)bZ(t);e.bag||(e.bag=(0,vt.emptyBag)())}function bZ(e){(0,er.hasGenPage)(e.control)&&(0,er.applyEmbedCellDefaults)(e),e.id||(e.id=Bi.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&&vZ(e.control),e.bag||(e.bag=(0,vt.emptyBag)())}function vZ(e){var t;(0,er.hasGenPage)(e)&&(0,er.applyEmbedControlDefaults)(e),e.id||(e.id=Bi.Guid.NewGuid()),(e.classId===void 0||e.classId===null)&&(e.classId=String(rt.ControlClassId.TextboxControl)),e.fieldName===void 0&&(e.fieldName=null),e.type===void 0&&(e.type=e.fieldName?"Field":Yy(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,Jy.assertXmlName)(r,"Form control parameter name");e.bag||(e.bag=(0,vt.emptyBag)())}function wZ(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 o of i.c)o.n==="Handler"&&!Nk(o,"handlerUniqueId")&&o.a.push(["handlerUniqueId",jy(Bi.Guid.NewGuid())])}}else if(r.n==="formLibraries")for(let n of r.c)n.n==="Library"&&!Nk(n,"libraryUniqueId")&&n.a.push(["libraryUniqueId",jy(Bi.Guid.NewGuid())])}}var Gf=class{constructor(t=_k.DEFAULT_LCID){this.lcid=t}toArtifact(t,r){var n,i,o;let{tabs:a,bag:s}=Ck(t,this.lcid),l={id:t.formId?t.formId.guidString:"",name:(n=t.formName)!==null&&n!==void 0?n:"",entityLogicalName:(i=t.entityName)!==null&&i!==void 0?i:"",formType:(o=VX[t.formType])!==null&&o!==void 0?o:"Main",status:this.readActivationStatus(t),...r!==void 0&&r!==""?{description:r}:{},tabs:a,bag:s};return(0,er.projectGenPageEmbeds)(l),(0,ii.projectPcfBindings)(l),l}fromArtifact(t){var r;return this.deserialize({formxml:Ak(t,this.lcid),formid:t.id||(0,Ks.newId)(),objecttypecode:t.entityLogicalName,type:Vf[t.formType],name:t.name,uniquename:t.name,description:(r=t.description)!==null&&r!==void 0?r:"",formpresentation:bt.FormPresentation.AirForm,formactivationstate:t.status==="Active"?bt.FormActivationState.Active:bt.FormActivationState.InActive})}fromApiResponse(t){var r,n,i,o,a,s,l;let u=t,c=(r=u.formxml)!==null&&r!==void 0?r:"",d={formxml:c,formid:(n=u.formid)!==null&&n!==void 0?n:(0,Ks.newId)(),objecttypecode:(i=u.objecttypecode)!==null&&i!==void 0?i:"",type:u.type,name:(o=u.name)!==null&&o!==void 0?o:"",uniquename:(a=u.uniquename)!==null&&a!==void 0?a:"",description:(s=u.description)!==null&&s!==void 0?s:"",formpresentation:u.formpresentation,formactivationstate:u.formactivationstate};(0,Wy.installDomShim)();let f=vk.ScriptUtilities.ParseXml(c),m=CZ(f),p=this.deserializeDocument(d,f);return EZ(this.toArtifact(p,(l=u.description)!==null&&l!==void 0?l:void 0),m)}toApiPayload(t,r,n){let i=(0,er.genPageEmbedIssues)(t);if(i.length>0)throw new Hs.ValidationError("form",t.id,i);let o=(0,ii.pcfBindingIssues)(t,r,{atPush:!0});if(o.length>0)throw new Hs.ValidationError("form",t.id,o);let a=(0,ii.pcfReadIssues)(t,n?.pcf,r);if(a.unavailable)throw(0,Hs.attachCause)(new Hs.SdkError(a.unavailable.code,a.unavailable.message),a.unavailable.cause);if(a.issues.length>0)throw new Hs.ValidationError("form",t.id,a.issues);return{formxml:Ak(t,this.lcid,n,r),name:t.name,type:Vf[t.formType],objecttypecode:t.entityLogicalName,...t.description!==void 0?{description:t.description}:{}}}metadataNeeds(t){let r=t.entityLogicalName;if(!r)return[];let n=new Map;return eb(t,i=>{var o;let a=i.fieldName,s=i;if(!a||s.label!==void 0&&s.classId!==void 0)return;let l=(o=n.get(a))!==null&&o!==void 0?o:{entityLogicalName:r,fieldName:a};s.label===void 0&&(l.needsLabel=!0),n.set(a,l)}),[...n.values()]}customControlNeeds(t,r){var n;return{entityLogicalName:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",...(0,ii.customControlNeeds)(t,r)}}createDefault(t){var r,n,i,o,a,s,l,u,c,d,f,m;let p=[...(0,er.genPageEmbedIssues)(t),...(0,ii.pcfBindingIssues)(t)];if(p.length>0)throw new Hs.ValidationError("form",t.id||"(new)",p);let h=t.tabs&&t.tabs.length>0?void 0:RZ(this.lcid),g=h!==void 0?h:t.tabs.map(C=>AZ(C,this.lcid)).join(""),b=this.deserialize({formxml:`<form><tabs>${g}</tabs></form>`,formid:t.id||(0,Ks.newId)(),objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",type:Vf[(n=t.formType)!==null&&n!==void 0?n:"Main"],name:(i=t.name)!==null&&i!==void 0?i:"New Form",uniquename:(o=t.name)!==null&&o!==void 0?o:"New Form",description:(a=t.description)!==null&&a!==void 0?a:"",formpresentation:bt.FormPresentation.AirForm,formactivationstate:((s=t.status)!==null&&s!==void 0?s:"Active")==="Active"?bt.FormActivationState.Active:bt.FormActivationState.InActive});(l=b.displayCondition)===null||l===void 0||l.removeProperty(bt.ElementProperties.Order);let w=this.toArtifact(b,t.description);if(t.tabs&&t.tabs.length>0){let C=Sk(t);Sk(w).forEach((S,O)=>{C[O]&&C[O].label===void 0&&delete S.label,C[O]&&C[O].genPage!==void 0&&(S.genPage=JSON.parse(JSON.stringify(C[O].genPage))),C[O]&&C[O].customControl!==void 0&&(S.customControl=JSON.parse(JSON.stringify(C[O].customControl)))})}return{id:(u=t.id)!==null&&u!==void 0?u:w.id,name:(c=t.name)!==null&&c!==void 0?c:"New Form",entityLogicalName:(d=t.entityLogicalName)!==null&&d!==void 0?d:"",formType:(f=t.formType)!==null&&f!==void 0?f:"Main",status:(m=t.status)!==null&&m!==void 0?m:"Active",...t.description!==void 0?{description:t.description}:{},tabs:w.tabs,bag:w.bag}}assignMissingIds(t){return(0,Ks.assignMissingIds)(t)}completeAsStored(t,r){return(0,qX.completeRecordAsStored)(t,r,this.lcid)}normalize(t){return(0,ii.mintPcfIdentity)((0,er.mintEmbedIdentity)(t))}committed(t,r){var n,i,o,a,s,l;let u=r?.formxml;if(typeof u!="string"||!((0,er.mayCommitEmbedState)(t)||(0,ii.mayCommitPcfState)(t)))return{artifact:t,baseline:t};let c=this.deserialize({formxml:u,formid:t.id||(0,Ks.newId)(),objecttypecode:(n=t.entityLogicalName)!==null&&n!==void 0?n:"",type:Vf[(i=t.formType)!==null&&i!==void 0?i:"Main"],name:(o=t.name)!==null&&o!==void 0?o:"",uniquename:(a=t.name)!==null&&a!==void 0?a:"",description:(s=t.description)!==null&&s!==void 0?s:"",formpresentation:bt.FormPresentation.AirForm,formactivationstate:bt.FormActivationState.Active}),{bag:d}=Ck(c,this.lcid),f=(0,ii.commitPcfState)((0,er.commitEmbedState)(t,(l=(0,er.descriptionsRegion)(d))===null||l===void 0?void 0:l.node),Yy);return{artifact:f,baseline:f}}validate(t){return qZ(t)}deserialize(t){return(0,Wy.installDomShim)(),this.deserializeDocument(t,vk.ScriptUtilities.ParseXml(t.formxml))}deserializeDocument(t,r){let n=new MX.DeserializationService(this.lcid).deSerializeFormXml(r,new Bi.Guid(t.formid),t.objecttypecode,bt.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===bt.FormActivationState.InActive?"Inactive":"Active"}};kr.FormAdapter=Gf;var Rk=["header","footer","DisplayConditions"];function CZ(e){var t;let r=e?.getElementsByTagName("form")[0],n=new Set;for(let i=(t=r?.firstChild)!==null&&t!==void 0?t:null;i;i=i.nextSibling)i.nodeType===1&&Rk.includes(i.nodeName)&&n.add(i.nodeName);return n}function EZ(e,t){var r;if(!(!((r=e.bag)===null||r===void 0)&&r.c))return e;let n=Rk.filter(o=>!t.has(o)),i=e.bag.c.filter(o=>{var a;return n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>o.i);return i.length>0&&(e.bag.c=e.bag.c.filter(o=>{var a;return!n.includes((a=o?.node)===null||a===void 0?void 0:a.n)}).map(o=>({...o,i:o.i-i.filter(a=>a<o.i).length}))),e}function Rn(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function tb(e,t){return e?`<labels><label description="${Rn(e)}" languagecode="${t}" /></labels>`:""}function rb(e){return e&&e.length>0?Ju(e):(0,Ks.newId)()}function AZ(e,t){var r,n,i,o;let a=(r=e.columns)!==null&&r!==void 0?r:[],s=(a.length>0?a:[PZ()]).map(l=>SZ(l,t)).join("");return`<tab id="{${Rn(rb(e.id))}}" name="${Rn((n=e.name)!==null&&n!==void 0?n:"")}" expanded="${(i=e.expanded)!==null&&i!==void 0?i:!0}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}">${tb(e.label,t)}<columns>${s}</columns></tab>`}function SZ(e,t){var r,n;let i=((r=e.sections)!==null&&r!==void 0?r:[]).map(o=>NZ(o,t)).join("");return`<column width="${Rn((n=e.width)!==null&&n!==void 0?n:"100%")}"><sections>${i}</sections></column>`}function NZ(e,t){var r,n,i,o,a;let s=((r=e.rows)!==null&&r!==void 0?r:[]).map(l=>_Z(l,t)).join("");return`<section id="{${Rn(rb(e.id))}}" name="${Rn((n=e.name)!==null&&n!==void 0?n:"")}" showlabel="${(i=e.showLabel)!==null&&i!==void 0?i:!1}" visible="${(o=e.visible)!==null&&o!==void 0?o:!0}" columns="${zy((a=e.columns)!==null&&a!==void 0?a:1)}">${tb(e.label,t)}<rows>${s}</rows></section>`}function _Z(e,t){var r;return`<row>${((r=e.cells)!==null&&r!==void 0?r:[]).map(n=>TZ(n,t)).join("")}</row>`}function TZ(e,t){var r,n,i,o,a;let s=DZ(e),l=s.control,u=l?tb((r=l.label)!==null&&r!==void 0?r:"",t):"",c=l?IZ(l):"";return`<cell id="{${Rn(rb(s.id))}}" showlabel="${l?(n=l.showLabel)!==null&&n!==void 0?n:!0:!1}" visible="${(i=s.visible)!==null&&i!==void 0?i:!0}" colspan="${(o=s.colspan)!==null&&o!==void 0?o:1}" rowspan="${(a=s.rowspan)!==null&&a!==void 0?a:1}">${u}${c}</cell>`}function DZ(e){if(!(0,er.hasGenPage)(e.control))return e;let t={...e.control};(0,er.applyEmbedControlDefaults)(t);let r={...e,control:t};return(0,er.applyEmbedCellDefaults)(r),r}function IZ(e){var t,r,n;let i=e.fieldName?` datafieldname="${Rn(e.fieldName)}"`:"",o=OZ(e.parameters),a=e.classId?Ju(e.classId):String(rt.ControlClassId.TextboxControl);return`<control id="${Rn((t=e.id)!==null&&t!==void 0?t:"")}" classid="{${Rn(a)}}"${i} disabled="${(r=e.isReadOnly)!==null&&r!==void 0?r:!1}" isrequired="${(n=e.isRequired)!==null&&n!==void 0?n:!1}">${o}</control>`}function OZ(e){let t=Object.keys(e??{});return t.length===0?"":(t.forEach(n=>(0,Jy.assertXmlName)(n,"Form control parameter name")),`<parameters>${t.map(n=>`<${n}>${Rn(e[n])}</${n}>`).join("")}</parameters>`)}function PZ(){return{width:"100%",sections:[],bag:{a:[],c:[]}}}function RZ(e){return`<tab id="{${Bi.Guid.NewGuid()}}" name="tab_general" expanded="true" visible="true"><labels><label description="General" languagecode="${e}" /></labels><columns><column width="100%"><sections><section id="{${Bi.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 kZ(e=_k.DEFAULT_LCID){return{adapter:new Gf(e),api:BX.formApi,languageSensitive:!0,publish:(t,r,n)=>(0,wk.publishBoundEntity)(t,n),publishScope:(t,r)=>(0,wk.boundEntityPublishScope)(r),rebaselineAfterPublish:"bracket"}}kr.formRegistration=kZ;var LZ=new Set(["id","name","label","expanded","visible","columns","bag"]),$Z=new Set(["id","width","sections","bag"]),xZ=new Set(["id","name","label","visible","showLabel","columns","rows","bag"]),FZ=new Set(["id","cells","bag"]),MZ=new Set(["id","visible","colspan","rowspan","control","bag"]),UZ=new Set(["id","classId","fieldName","type","isRequired","isReadOnly","label","showLabel","parameters","genPage","customControl","bag"]),BZ={elsewhere:{isReadOnly:"control",isRequired:"control",fieldName:"control",classId:"control",label:"control",showLabel:"control",parameters:"control"},unsupported:{createOnly:"FormXml has no create-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled.",updateOnly:"FormXml has no update-only concept; gate the field with a business rule instead. Raise it with the SDK owners if you need it modeled."}};function qZ(e){let t=[];return(0,Rr.childObjects)(e,"tabs","","tab",t).forEach(({node:n,index:i})=>{let o=`/tabs/${i}`;(0,Rr.rejectUnknownKeys)(n,LZ,o,"tab",t),(0,Rr.childObjects)(n,"columns",o,"column",t).forEach(({node:s,index:l})=>{let u=`${o}/columns/${l}`;(0,Rr.rejectUnknownKeys)(s,$Z,u,"column",t),(0,Rr.childObjects)(s,"sections",u,"section",t).forEach(({node:d,index:f})=>{let m=`${u}/sections/${f}`;(0,Rr.rejectUnknownKeys)(d,xZ,m,"section",t),(0,Rr.childObjects)(d,"rows",m,"row",t).forEach(({node:h,index:g})=>{let b=`${m}/rows/${g}`;(0,Rr.rejectUnknownKeys)(h,FZ,b,"row",t),(0,Rr.childObjects)(h,"cells",b,"cell",t).forEach(({node:C,index:S})=>{let O=`${b}/cells/${S}`;(0,Rr.rejectUnknownKeys)(C,MZ,O,"cell",t,BZ);let k=C.control;k!=null&&!(0,Rr.isJsonObject)(k)?t.push((0,Rr.issue)(`${O}/control`,"control-must-be-object-or-null",`a cell control must be a JSON object or null, got ${typeof k}`)):(0,Rr.isJsonObject)(k)&&(0,Rr.rejectUnknownKeys)(k,UZ,`${O}/control`,"control",t)})})})})}),t.push(...(0,er.genPageEmbedIssues)(e)),t.push(...(0,ii.pcfBindingIssues)(e)),t}kr.SUBGRID_CLASS_ID=rt.ControlClassId.SubgridControl;kr.NOTES_CLASS_ID=rt.ControlClassId.TimelineControl;kr.QUICK_VIEW_CLASS_ID=rt.ControlClassId.QuickViewControl;var VZ={Lookup:String(rt.ControlClassId.LookupControl),Customer:String(rt.ControlClassId.LookupControl),Owner:String(rt.ControlClassId.LookupControl),PartyList:String(rt.ControlClassId.PartyListControl),Boolean:String(rt.ControlClassId.BooleanControl),DateTime:String(rt.ControlClassId.DateTimeControl),Decimal:String(rt.ControlClassId.DecimalControl),Double:String(rt.ControlClassId.FloatingNumberControl),Money:String(rt.ControlClassId.CurrencyControl),Integer:String(rt.ControlClassId.IntegerControl),BigInt:String(rt.ControlClassId.IntegerControl),Memo:String(rt.ControlClassId.TextAreaControl),String:String(rt.ControlClassId.TextboxControl)},GZ="3EF39988-22BB-4F0B-BBBE-64B5A3748AEE";function kk(e){return e==="Picklist"||e==="State"||e==="Status"?GZ:e&&VZ[e]||String(rt.ControlClassId.TextboxControl)}kr.classIdForAttributeType=kk;function Nk(e,t){let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}});var nb=v(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.viewApi=Js.findDefaultViews=void 0;var Mk=Lt(),fr=ye(),kn=le(),WZ=ns(),$k="savedqueryid,name,description,fetchxml,layoutxml,querytype,returnedtypecode,isdefault",zZ="savedqueryid,name,returnedtypecode,querytype,isdefault",jZ=60*1e3;function jf(e){return(e.localName||e.nodeName).toLowerCase()}function Yu(e,t){let r;for(let n=0;n<e.attributes.length;n+=1){let i=e.attributes[n];i.nodeName.toLowerCase()===t&&(r=r===void 0?i.value:null)}return r}function HZ(e){if(!e)return;let t=!0,r=()=>{t=!1},n=new WZ.DOMParser({errorHandler:{warning:r,error:r,fatalError:r}}).parseFromString(e,"text/xml").documentElement;return t&&n&&jf(n)==="fetch"?n:void 0}function KZ(e){for(let t=e.parentNode;t;t=t.parentNode)if(jf(t)==="link-entity")return!0;return!1}function xk(e,t){var r,n,i;if(((r=e.canbedeleted)===null||r===void 0?void 0:r.Value)!==!1)return!1;let o=HZ(e.fetchxml);if(!o)return!1;let a=Array.from(o.getElementsByTagName("*")),s=a.filter(u=>jf(u)==="condition"),l=s.length===1?s[0]:void 0;return l!==void 0&&a.filter(u=>jf(u)==="link-entity").every(u=>{var c;return((c=Yu(u,"link-type"))===null||c===void 0?void 0:c.toLowerCase())==="outer"})&&!KZ(l)&&Yu(l,"entityname")===void 0&&((n=Yu(l,"attribute"))===null||n===void 0?void 0:n.toLowerCase())==="statecode"&&((i=Yu(l,"operator"))===null||i===void 0?void 0:i.toLowerCase())==="eq"&&Yu(l,"value")===String(t)}function JZ(e,t){let r=String(e??"").trim().toLowerCase().split(/\s+/).filter(i=>i!==""),n=String(t??"").trim().toLowerCase().split(/\s+/).filter(i=>i!=="");return r.length===n.length&&r.filter((i,o)=>i!==n[o]).length===1}function YZ(e){var t,r;let n=e.filter(a=>xk(a,0)),i=e.filter(a=>xk(a,1)),o=[];for(let a of n)for(let s of i)Math.abs(Date.parse(String((t=s.createdon)!==null&&t!==void 0?t:""))-Date.parse(String((r=a.createdon)!==null&&r!==void 0?r:"")))<=jZ&&JZ(a.name,s.name)&&o.push({active:a,inactive:s});return o.length===1?o[0]:void 0}async function QZ(e,t,r={}){var n;let i=new Set(((n=r.excludeViewIds)!==null&&n!==void 0?n:[]).filter(Boolean)),o=`returnedtypecode eq '${(0,kn.odataLiteral)(t)}' and querytype eq 0`,a=`/savedqueries${(0,kn.odataQuery)([["$select","savedqueryid,name,canbedeleted,fetchxml,createdon"],["$filter",o]])}`,s=await(0,Mk.collectPages)(e,a,`findDefaultViews('${t}')`),l=YZ(s),u=new Set(l?[l.active,l.inactive]:[]);return s.filter(c=>c.savedqueryid&&!i.has(c.savedqueryid)&&u.has(c)).map(c=>{var d;return{id:String(c.savedqueryid),name:String((d=c.name)!==null&&d!==void 0?d:"")}})}Js.findDefaultViews=QZ;async function XZ(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,kn.odataPathLiteral)(t)}')${(0,kn.odataQuery)([["$select","ObjectTypeCode"]])}`,i=await e.get(n);if(i.status>=200&&i.status<300){let o=(r=i.body)===null||r===void 0?void 0:r.ObjectTypeCode;return typeof o=="number"?o:void 0}}async function Fk(e,t,r){if(!r||!/<grid\b/.test(t)||/<grid[^>]*\bobject=/.test(t))return t;let n=await XZ(e,r);return n===void 0?t:t.replace(/<grid\b/,`<grid object="${n}"`)}Js.viewApi={async get(e,t){let r=(0,kn.normalizeGuid)(t,"id"),n=await(0,fr.readRowEtag)(e,"savedqueries","savedqueryid",r),i=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,kn.odataQuery)([["$select",$k]]);return{raw:(0,fr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,kn.normalizeGuid)(t,"id"),n=`/savedqueries(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,kn.odataQuery)([["$select",$k]]),i=(0,fr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,fr.readRowEtag)(e,"savedqueries","savedqueryid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueries${(0,kn.odataQuery)([["$select",zZ],["$filter",t?.entityLogicalName?`returnedtypecode eq '${(0,kn.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,Mk.collectPages)(e,r,"listArtifacts('view')")).map(i=>{var o,a;return{type:"view",id:(o=i.savedqueryid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.returnedtypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,fr.echoWrite)("savedqueryid"),o=`/savedqueries${i.query}`,a=await Fk(e,n.layoutxml,n.returnedtypecode),s=Object.freeze((0,fr.withClientMintedId)({name:n.name,description:n.description,fetchxml:n.fetchxml,layoutxml:a,returnedtypecode:n.returnedtypecode,querytype:n.querytype,isdefault:n.isdefault},"savedqueryid",r)),l=(0,fr.ensureSuccess)(await(0,fr.resendDeadlockVictim)(()=>e.post(o,{...s},i.options)),e.apiUrl(o));return{id:(0,fr.resolveCreatedId)(l,"savedqueryid","view",r),etag:(0,fr.readEtag)(l)}},async update(e,t,r,n){let i=r,o=(0,kn.normalizeGuid)(t,"id"),a=(0,fr.echoWrite)("savedqueryid",{"If-Match":(0,fr.requireEtag)(n,"view",o)}),s=`/savedqueries(${o})${a.query}`,l=await Fk(e,i.layoutxml,i.returnedtypecode),u=(0,fr.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,fetchxml:i.fetchxml,layoutxml:l},a.options),e.apiUrl(s));return{id:o,etag:(0,fr.readEtag)(u)}},delete(e,t){return(0,fr.deleteRecord)(e,"savedqueries",t)}}});var eL=v(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});Ys.viewRegistration=Ys.ViewAdapter=void 0;var zk=Q(),jr=rn(),ib=so(),va=uo(),Uk=Qr(),ZZ=nb(),ob=lo(),eee=pt(),jk=100,Kf=class{toArtifact(t){var r,n,i,o,a,s,l,u;(0,ob.installDomShim)();let c=(r=t.fetchxml)!==null&&r!==void 0?r:"",d=(n=t.layoutxml)!==null&&n!==void 0?n:"",f=(0,va.parseXmlRoot)(c,"<fetch/>"),m=(0,va.parseXmlRoot)(d,"<grid/>"),p=Kk(f);return{id:(i=t.savedqueryid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.returnedtypecode)!==null&&s!==void 0?s:ree(f),queryType:(l=t.querytype)!==null&&l!==void 0?l:0,isDefault:(u=t.isdefault)!==null&&u!==void 0?u:!1,columns:Hk(m,f),filters:Yk(f),sort:Jk(f),...p.length>0?{linkEntities:p}:{},fetchBag:c?(0,va.projectElementBag)(f):void 0,layoutBag:d?(0,va.projectElementBag)(m):void 0}}fromArtifact(t){(0,ob.installDomShim)();let{fetchxml:r,layoutxml:n}=Bk(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,o,a;(0,ob.installDomShim)();let{fetchxml:s,layoutxml:l}=Bk(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:(o=t.queryType)!==null&&o!==void 0?o:0,isdefault:(a=t.isDefault)!==null&&a!==void 0?a:!1}}createDefault(t){var r,n,i,o,a,s,l,u;let c=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,eee.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New View",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:c,queryType:(a=t.queryType)!==null&&a!==void 0?a:0,isDefault:(s=t.isDefault)!==null&&s!==void 0?s:!1,columns:t.columns&&t.columns.length>0?t.columns:[{name:`${c}id`,width:300,order:0}],filters:(l=t.filters)!==null&&l!==void 0?l:{type:"and",conditions:[],groups:[]},sort:(u=t.sort)!==null&&u!==void 0?u:[],...t.linkEntities&&t.linkEntities.length>0?{linkEntities:t.linkEntities}:{}}}assignMissingIds(t){return t}validate(t){let r=[],n=t;(0,jr.childObjects)(n,"columns","","column",r),(0,jr.childObjects)(n,"sort","","sort",r),(0,jr.childObjects)(n,"linkEntities","","linkEntity",r),tee(n.linkEntities,r);let i=n.filters;return i!=null&&((0,jr.isJsonObject)(i)?ab(i,"/filters",r):r.push((0,jr.issue)("/filters","filters-must-be-object",`filters must be a JSON object, got ${typeof i}`))),r}};Ys.ViewAdapter=Kf;function tee(e,t){Array.isArray(e)&&e.forEach((r,n)=>{if(!(0,jr.isJsonObject)(r))return;for(let o of["name","from","to"]){let a=r[o];(typeof a!="string"||a.trim()==="")&&t.push((0,jr.issue)(`/linkEntities/${n}/${o}`,"linkentity-needs-keys",`a join needs a non-empty '${o}' \u2014 'from'/'to' are what DEFINE the relationship, and a link without them is unresolvable. Got ${JSON.stringify(a)}.`))}let i=r.filters;i!=null&&((0,jr.isJsonObject)(i)?ab(i,`/linkEntities/${n}/filters`,t):t.push((0,jr.issue)(`/linkEntities/${n}/filters`,"filters-must-be-object",`filters must be a JSON object, got ${typeof i}`)))})}function ab(e,t,r){(0,jr.childObjects)(e,"conditions",t,"condition",r),(0,jr.childObjects)(e,"groups",t,"filterGroup",r).forEach(({node:i,index:o})=>ab(i,`${t}/groups/${o}`,r))}function ree(e){var t;let r=e.getElementsByTagName("entity")[0];return(t=r?.getAttribute("name"))!==null&&t!==void 0?t:""}function Hk(e,t){var r;let n=Jf(t),i=e.getElementsByTagName("cell"),o=[],a=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)?jk:c,order:a},f=n.get(u);f&&(d.relatedEntity=f.linkKey,f.attributeName&&f.attributeName!==u&&(d.sourceAttribute=f.attributeName)),a+=1,o.push(d)}return o}function Jf(e){let t=new Map,r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("name")||"",c=l.getAttribute("alias")||u;c&&t.set(c,{linkKey:i.getAttribute("alias")||o,linkName:o,attributeName:u,link:i})}}return t}function Kk(e){let t=e.getElementsByTagName("entity")[0];if(!t)return[];let r=[];for(let n of Mt(t,"link-entity")){let i=n.getAttribute("name"),o=n.getAttribute("from"),a=n.getAttribute("to");if(!i||!o||!a)continue;let s=n.getAttribute("alias"),l=n.getAttribute("link-type"),u=Mt(n,"filter").find(c=>!Yf(c));r.push({name:i,from:o,to:a,...s?{alias:s}:{},...l==="inner"||l==="outer"?{linkType:l}:{},...u?{filters:sb(u)}:{}})}return r}function Jk(e){var t;let r=e.getElementsByTagName("entity")[0];if(!r)return[];let n=[],i=r.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];if(a.nodeType===1&&a.tagName==="order"){let s=a.getAttribute("attribute");s&&n.push({attribute:s,descending:((t=a.getAttribute("descending"))!==null&&t!==void 0?t:"").toLowerCase()==="true",entityname:a.getAttribute("entityname")||""})}}return n}function Yk(e){let t=e.getElementsByTagName("entity")[0],r={type:"and",conditions:[],groups:[]};if(!t)return r;let n=Mt(t,"filter").filter(i=>!Yf(i)).map(sb);return n.length===0?r:n.length===1?n[0]:{type:"and",conditions:[],groups:n}}function Yf(e){if(e.getAttribute("isquickfindfields")==="1"||Qk(e))return!0;if(Mt(e,"filter").length>0)return!1;let t=Mt(e,"condition");return t.length===0?!1:t.some(r=>r.getAttribute("isquickfindfields")==="1"||Mt(r,"value").length>0||iee(r))}function Qk(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1){let n=t[r];if(n.nodeType===1&&(n.tagName==="filter"?Qk(n):n.tagName!=="condition"))return!0}return!1}var nee=new Set(["attribute","operator","value","entityname","uiname","uitype"]);function iee(e){var t;let r=e.attributes;for(let n=0;n<r.length;n+=1){let i=(t=r[n])===null||t===void 0?void 0:t.name;if(i&&!nee.has(i))return!0}return!1}function sb(e){var t,r;let n=((t=e.getAttribute("type"))!==null&&t!==void 0?t:"and").toLowerCase()==="or"?"or":"and",i=[],o=[],a=e.childNodes;for(let s=0;s<a.length;s+=1){let l=a[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:""};l.hasAttribute("value")&&(c.value=l.getAttribute("value")||"");let d=l.getAttribute("entityname")||"";d&&(c.entityname=d),i.push(c)}else l.tagName==="filter"&&o.push(sb(l))}return{type:n,conditions:i,groups:o}}function Mt(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}var lb=e=>{var t,r;return`${(t=e.relatedEntity)!==null&&t!==void 0?t:""}::${(r=e.sourceAttribute)!==null&&r!==void 0?r:e.name}`};function oee(e,t){let r=Jf(e),n=new Map;for(let i of t){if(!i.relatedEntity)continue;let o=r.get(i.name);if(o){let a=lb(i),s=n.get(a);s?s.push(o.link):n.set(a,[o.link])}}return n}function aee(e,t,r,n){if(!n||n.size===0)return;let i=new Set,o=t.getElementsByTagName("link-entity");for(let s=0;s<o.length;s+=1)i.add(o[s]);let a=r.filter(s=>{if(!s.relatedEntity)return!1;let l=n.get(lb(s));return!!l&&l.some(u=>!i.has(u))});if(a.length!==0)throw new zk.ValidationError("view",e.id,a.map(s=>(0,jr.issue)(`/columns/${r.indexOf(s)}`,"view-column-orphaned-by-join-removal",`column '${s.name}' came from a join this push REMOVED. Another join matching '${s.relatedEntity}' still exists, but nothing can say whether it is the one the column belonged to \u2014 re-attaching it there would silently change the data the column shows. Remove the column too, keep the join it came from, or point the column at the join you want by setting relatedEntity to that join's alias.`)))}function Bk(e){var t,r;let n=see(e.columns),i=(t=e.sort)!==null&&t!==void 0?t:[],o=(r=e.filters)!==null&&r!==void 0?r:{type:"and",conditions:[],groups:[]};if(!qk(e.fetchBag)||!qk(e.layoutBag))return{fetchxml:wee({...e,columns:n,sort:i,filters:o}),layoutxml:Cee({...e,columns:n},`${e.entityLogicalName}id`)};let a=new DOMParser().parseFromString("<root/>","text/xml"),s=Vk(e.fetchBag,"fetch",a),l=Vk(e.layoutBag,"grid",a),u=Hk(l,s),c=!Hf(n,u),d=!Hf(i,Jk(s)),f=!Hf(o,Yk(s)),m=e.linkEntities,p=m!==void 0&&!Hf(m,Kk(s)),h=p?oee(s,u):void 0;return p&&yee(a,s,m),p&&(vee(e,s,n,h),aee(e,s,n,h)),c?(Gk(a,s,n,u),fee(a,l,n)):p&&Gk(a,s,n,u),d&&hee(a,s,i),f&&gee(a,s,o),{fetchxml:(0,va.serializeNode)(s),layoutxml:(0,va.serializeNode)(l)}}function see(e){return(e??[]).map((t,r)=>{var n,i;return{name:String(t.name).toLowerCase(),width:(n=t.width)!==null&&n!==void 0?n:jk,order:(i=t.order)!==null&&i!==void 0?i:r,...t.relatedEntity?{relatedEntity:t.relatedEntity}:{},...t.sourceAttribute?{sourceAttribute:String(t.sourceAttribute).toLowerCase()}:{}}})}function qk(e){return!!e&&(e.c.length>0||e.a.length>0)}function Vk(e,t,r){let n={n:t,a:(0,ib.mergeAttrs)(e.a,[]),c:(0,ib.spliceChildren)(e.c,[])};return(0,ib.rebuildRaw)(n,(0,va.domEngine)(r),null)}function Gk(e,t,r,n){var i,o,a;let s=t.getElementsByTagName("entity")[0];if(!s)return;let l=p=>{var h,g;return`${(h=p.relatedEntity)!==null&&h!==void 0?h:""}:${p.name}:${(g=p.sourceAttribute)!==null&&g!==void 0?g:p.name}`},u=new Set(r.map(l)),c=new Set(r.map(p=>p.name)),d=Jf(t);for(let p of n)u.has(l(p))||(uee(s,p),p.relatedEntity&&c.has(p.name)&&lee((i=d.get(p.name))===null||i===void 0?void 0:i.link,p.name));let f=Jf(t),m=new Set(Mt(s,"attribute").map(p=>p.getAttribute("name")).filter(p=>!!p));for(let p of[...r].sort((h,g)=>h.order-g.order))if(p.relatedEntity){let h=f.get(p.name);if(h&&h.attributeName===((o=p.sourceAttribute)!==null&&o!==void 0?o:p.name)&&(h.linkKey===p.relatedEntity||h.linkName===p.relatedEntity||!Zk(s,p.relatedEntity)))continue;let g=cee(e,s,p.relatedEntity),b=e.createElement("attribute");Xk(b,p),g.appendChild(b),f.set(p.name,{linkKey:p.relatedEntity,linkName:g.getAttribute("name")||p.relatedEntity,attributeName:(a=p.sourceAttribute)!==null&&a!==void 0?a:p.name,link:g})}else{if(m.has(p.name))continue;let h=e.createElement("attribute");h.setAttribute("name",p.name),dee(s,h),m.add(p.name)}}function Xk(e,t){if(t.sourceAttribute&&t.sourceAttribute!==t.name){e.setAttribute("name",t.sourceAttribute),e.setAttribute("alias",t.name);return}e.setAttribute("name",t.name)}function lee(e,t){if(e){for(let r of Mt(e,"attribute"))if((r.getAttribute("alias")||r.getAttribute("name"))===t){e.removeChild(r);return}}}function uee(e,t){if(t.relatedEntity){for(let r of Mt(e,"link-entity"))if(!(r.getAttribute("alias")!==t.relatedEntity&&r.getAttribute("name")!==t.relatedEntity)){for(let n of Mt(r,"attribute"))if((n.getAttribute("alias")||n.getAttribute("name"))===t.name){r.removeChild(n);return}}return}for(let r of Mt(e,"attribute"))if(r.getAttribute("name")===t.name){e.removeChild(r);return}}function Zk(e,t,r=!1){let n=o=>o.getAttribute("alias")===t||o.getAttribute("name")===t;for(let o of Mt(e,"link-entity"))if(n(o))return o;if(r)return;let i=e.getElementsByTagName("link-entity");for(let o=0;o<i.length;o+=1)if(n(i[o]))return i[o]}function cee(e,t,r){let n=Zk(t,r);if(n)return n;let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function dee(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 fee(e,t,r){let n=t.getElementsByTagName("row")[0];if(!n)return;let i=[...r].sort((s,l)=>s.order-l.order),o=pee(n);if(mee(o,i)){for(let s=0;s<i.length;s+=1){let l=String(i[s].width);o[s].getAttribute("width")!==l&&o[s].setAttribute("width",l)}return}let a=new Map;for(let s of o){let l=s.getAttribute("name");l&&a.set(l,s),n.removeChild(s)}for(let s of i){let l=a.get(s.name);l||(l=e.createElement("cell"),l.setAttribute("name",s.name)),l.setAttribute("width",String(s.width)),n.appendChild(l)}}function pee(e){return Mt(e,"cell").filter(t=>!!t.getAttribute("name")&&t.getAttribute("ishidden")!=="1")}function mee(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 hee(e,t,r){let n=t.getElementsByTagName("entity")[0];if(!n)return;let i=(m,p)=>`${m.toLowerCase()}\0${p.toLowerCase()}`,o=new Map,a=new Map,s=(m,p,h)=>{let g=m.get(p);g?g.push(h):m.set(p,[h])},l=null;for(let m of Mt(n,"order")){let p=m.getAttribute("attribute")||"";p&&(l||(l=e.createTextNode(""),n.insertBefore(l,m)),s(o,i(m.getAttribute("entityname")||"",p),m),s(a,p.toLowerCase(),m),n.removeChild(m))}let u=new Set,c=(m,p)=>{let h=m.get(p);for(;h&&h.length>0;){let g=h.shift();if(!u.has(g))return u.add(g),g}},d=m=>{var p;let h=a.get(m.toLowerCase());if(!h)return;let g=h.filter(w=>!u.has(w)),b=(p=g.find(w=>!w.getAttribute("entityname")))!==null&&p!==void 0?p:g[0];return b&&u.add(b),b},f=r.map(m=>{let p=String(m.attribute);return m.entityname===void 0?{expression:m,element:void 0}:{expression:m,element:c(o,i(m.entityname,p))}});for(let m of f)m.expression.entityname===void 0&&(m.element=d(String(m.expression.attribute)));for(let{expression:m,element:p}of f){let h=p??e.createElement("order");h.setAttribute("attribute",m.attribute),h.setAttribute("descending",String(m.descending)),m.entityname?h.setAttribute("entityname",m.entityname):m.entityname===""&&h.removeAttribute("entityname"),n.insertBefore(h,l)}l&&n.removeChild(l)}function gee(e,t,r){let n=t.getElementsByTagName("entity")[0];if(n){for(let i of Mt(n,"filter"))Yf(i)||n.removeChild(i);(r.conditions.length>0||r.groups.length>0)&&n.appendChild(Qu(e,r))}}function Hf(e,t){return JSON.stringify(e)===JSON.stringify(t)}function yee(e,t,r){var n;let i=t.getElementsByTagName("entity")[0];if(!i)return;let o=Mt(i,"link-entity").filter(p=>p.getAttribute("name")&&p.getAttribute("from")&&p.getAttribute("to")),a=(p,h)=>p.getAttribute(h)||"",s=new Array(r.length),l=new Set,u=p=>{r.forEach((h,g)=>{if(s[g])return;let b=o.filter(S=>!l.has(S)&&p(S,h));if(b.length!==1)return;let w=b[0];r.some((S,O)=>O!==g&&!s[O]&&p(w,S))||(s[g]=w,l.add(w))})};u((p,h)=>!!h.alias&&a(p,"name")===h.name&&a(p,"alias")===h.alias),u((p,h)=>a(p,"name")===h.name&&a(p,"from")===h.from&&a(p,"to")===h.to),u((p,h)=>a(p,"name")===h.name&&a(p,"from")===h.from),u((p,h)=>a(p,"name")===h.name&&a(p,"to")===h.to),u((p,h)=>a(p,"name")===h.name);let c=r.map((p,h)=>h).filter(p=>!s[p]),d=o.filter(p=>!l.has(p)),f=new Map;for(let p of d){let h=f.get(a(p,"name"));h?h.push(p):f.set(a(p,"name"),[p])}let m=new Map;for(let p of c){let h=m.get(r[p].name);h?h.push(p):m.set(r[p].name,[p])}for(let[p,h]of m){let g=(n=f.get(p))!==null&&n!==void 0?n:[];g.length===h.length&&h.forEach((b,w)=>{s[b]=g[w],l.add(g[w])})}r.forEach((p,h)=>{let g=s[h];if(g){Wk(e,g,p);return}let b=e.createElement("link-entity");Wk(e,b,p),i.appendChild(b)});for(let p of o)l.has(p)||i.removeChild(p)}var bee=new Set(["inner","outer"]);function vee(e,t,r,n){if(!t.getElementsByTagName("entity")[0])return;let o=new Set,a=t.getElementsByTagName("link-entity");for(let c=0;c<a.length;c+=1){let d=a[c],f=d.getAttribute("name"),m=d.getAttribute("alias");f&&o.add(f),m&&o.add(m)}let s=new Set;for(let c=0;c<a.length;c+=1)s.add(a[c]);let l=c=>{let d=n?.get(lb(c));return!!d&&d.every(f=>s.has(f))},u=r.filter(c=>c.relatedEntity&&!o.has(c.relatedEntity)&&!l(c));if(u.length!==0)throw new zk.ValidationError("view",e.id,u.map(c=>{var d;let f=((d=e.linkEntities)!==null&&d!==void 0?d:[]).some(m=>m.name===c.relatedEntity||m.alias===c.relatedEntity);return(0,jr.issue)(`/columns/${r.indexOf(c)}`,"view-column-dangling-link",`column '${c.name}' has relatedEntity '${c.relatedEntity}', but no matching join remains in linkEntities. `+(f?"Remove the column too, or keep the join.":"That join is NESTED (a join off a join), which the typed layer does not model, so it cannot be re-declared in linkEntities \u2014 it only survives while the join above it does. Remove the column, or restore the parent join this push replaced."))}))}function Wk(e,t,r){t.setAttribute("name",r.name),t.setAttribute("from",r.from),t.setAttribute("to",r.to),r.alias?t.setAttribute("alias",r.alias):t.removeAttribute("alias"),r.linkType?t.setAttribute("link-type",r.linkType):bee.has(t.getAttribute("link-type")||"")&&t.removeAttribute("link-type");let n=Mt(t,"filter").find(o=>!Yf(o)),i=r.filters&&(r.filters.conditions.length>0||r.filters.groups.length>0)?Qu(e,r.filters):null;n&&i?t.replaceChild(i,n):n?t.removeChild(n):i&&t.appendChild(i)}function wee(e){var t;let r=new DOMParser().parseFromString("<fetch/>","text/xml"),n=r.documentElement;n.setAttribute("version","1.0"),n.setAttribute("mapping","logical");let i=r.createElement("entity");i.setAttribute("name",e.entityLogicalName),n.appendChild(i);let o=new Map;for(let a of(t=e.linkEntities)!==null&&t!==void 0?t:[]){let s=r.createElement("link-entity");s.setAttribute("name",a.name),s.setAttribute("from",a.from),s.setAttribute("to",a.to),a.alias&&s.setAttribute("alias",a.alias),a.linkType&&s.setAttribute("link-type",a.linkType),a.filters&&(a.filters.conditions.length>0||a.filters.groups.length>0)&&s.appendChild(Qu(r,a.filters)),i.appendChild(s);for(let l of[a.alias||a.name,a.name])o.has(l)||o.set(l,s)}for(let a of[...e.columns].sort((s,l)=>s.order-l.order)){let s=r.createElement("attribute");if(a.relatedEntity){Xk(s,a);let l=o.get(a.relatedEntity);l||(l=r.createElement("link-entity"),l.setAttribute("name",a.relatedEntity),i.appendChild(l),o.set(a.relatedEntity,l)),l.appendChild(s)}else s.setAttribute("name",a.name),i.appendChild(s)}for(let a of e.sort){let s=r.createElement("order");s.setAttribute("attribute",a.attribute),s.setAttribute("descending",String(a.descending)),a.entityname&&s.setAttribute("entityname",a.entityname),i.appendChild(s)}return(e.filters.conditions.length>0||e.filters.groups.length>0)&&i.appendChild(Qu(r,e.filters)),new XMLSerializer().serializeToString(r)}function Qu(e,t){let r=e.createElement("filter");r.setAttribute("type",t.type);for(let n of t.conditions){let i=e.createElement("condition");i.setAttribute("attribute",n.attribute),i.setAttribute("operator",n.operator),n.entityname&&i.setAttribute("entityname",n.entityname),n.value!==void 0&&i.setAttribute("value",n.value),r.appendChild(i)}for(let n of t.groups)r.appendChild(Qu(e,n));return r}function Cee(e,t){var r;let n=new DOMParser().parseFromString("<grid/>","text/xml"),i=n.documentElement,o=[...e.columns].sort((s,l)=>s.order-l.order);i.setAttribute("name","resultset"),i.setAttribute("jump",((r=o[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 a=n.createElement("row");a.setAttribute("name","result"),a.setAttribute("id",t||`${e.entityLogicalName}id`),i.appendChild(a);for(let s of o){let l=n.createElement("cell");l.setAttribute("name",s.name),l.setAttribute("width",String(s.width)),a.appendChild(l)}return new XMLSerializer().serializeToString(n)}function Eee(){return{adapter:new Kf,api:ZZ.viewApi,publish:(e,t,r)=>(0,Uk.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,Uk.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}Ys.viewRegistration=Eee});function Qf(e,t){return e==="SetFieldValue"&&t!==void 0&&Aee.has(t.attributeType)&&(t.requiredLevel==="None"||t.requiredLevel==="Recommended")}var Aee,ub=L(()=>{"use strict";Aee=new Set(["Integer","Double","Decimal","Money","String","Memo","DateTime","Picklist","Lookup"])});function tL(e){return e!=="Entity"&&e!=="AllForms"&&typeof e=="string"&&e.trim()!==""}function cb(e){return e==="AllForms"||tL(e)?1:2}function db(e){return tL(e)?e:null}function rL(e,t){return{"@odata.type":"#Microsoft.Dynamics.CRM.workflow",name:e.name,description:e.description,workflowid:t,ondemand:!1,subprocess:!1,triggeroncreate:!1,triggerondelete:!1,category:Qs.WorkflowCategory.BusinessRule,type:Qs.WorkflowTypeCode.Definition,mode:1,scope:Qs.WorkflowScope.Organization,primaryentity:e.entityLogicalName,iscrmuiworkflow:!0,processtriggerscope:cb(e.scope),processtriggerformid:db(e.scope)}}var Qs,nL=L(()=>{"use strict";Qs=Ae(Qi());});function iL(e,t=0){return(Ut[e[t+0]]+Ut[e[t+1]]+Ut[e[t+2]]+Ut[e[t+3]]+"-"+Ut[e[t+4]]+Ut[e[t+5]]+"-"+Ut[e[t+6]]+Ut[e[t+7]]+"-"+Ut[e[t+8]]+Ut[e[t+9]]+"-"+Ut[e[t+10]]+Ut[e[t+11]]+Ut[e[t+12]]+Ut[e[t+13]]+Ut[e[t+14]]+Ut[e[t+15]]).toLowerCase()}var Ut,oL=L(()=>{Ut=[];for(let e=0;e<256;++e)Ut.push((e+256).toString(16).slice(1))});function fb(){return Xf>Zf.length-16&&((0,aL.randomFillSync)(Zf),Xf=0),Zf.slice(Xf,Xf+=16)}var aL,Zf,Xf,sL=L(()=>{aL=require("crypto"),Zf=new Uint8Array(256),Xf=Zf.length});var lL,pb,uL=L(()=>{lL=require("crypto"),pb={randomUUID:lL.randomUUID}});function See(e,t,r){if(pb.randomUUID&&!t&&!e)return pb.randomUUID();e=e||{};let n=e.random??e.rng?.()??fb();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 iL(n)}var pr,cL=L(()=>{uL();sL();oL();pr=See});var mb=L(()=>{cL()});var dL=L(()=>{"use strict";});function fL(e){return e!=null&&Nee.has(e)}function ep(e){if(e==null)return!1;let t=e.trim();if(!/^[+-]?\d+$/.test(t))return!1;let r=Number(t);return Number.isInteger(r)&&r>=-2147483648&&r<=2147483647}var Nee,hb=L(()=>{"use strict";Nee=new Set(["Picklist","State","Status"])});var tp=v(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.WorkflowConditionOperator=pn.WorkflowAttributeType=pn.SystemStep=pn.FieldRequiredLevelTypes=pn.AttributeDateTimeBehavior=void 0;pn.AttributeDateTimeBehavior={None:0,Dynamic:1,DateOnly:2,StaticTimeZoneInvariant:3,UserLocal:4};pn.FieldRequiredLevelTypes={None:"0",Required:"1",Recommended:"2"};pn.SystemStep={IdentifyContact:"IdentifyContact",IdentifyAccount:"IdentifyAccount",IdentifyCustomer:"IdentifyCustomer",IdentifyCase:"IdentifyCase",Solution:"Solution",Resolve:"Resolve"};pn.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"};pn.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 rp(e){return e!=null&&mL.includes(e)}function gb(e){return e===oe.WorkflowAttributeType.Integer}function yb(e,t){return t===oe.WorkflowConditionOperator.Equal||t===oe.WorkflowConditionOperator.NotEqual?e:_ee.includes(t)?mL.includes(e)||e===oe.WorkflowAttributeType.DateTime?e:oe.WorkflowAttributeType.String:t===oe.WorkflowConditionOperator.On||t===oe.WorkflowConditionOperator.NotOn?e===oe.WorkflowAttributeType.DateTime?e:oe.WorkflowAttributeType.String:oe.WorkflowAttributeType.String}function hL(e){let t=e.leftWorkflowType??e.valueWorkflowType??oe.WorkflowAttributeType.String,r=Xu[e.operator]??oe.WorkflowConditionOperator.Equal;return yb(t,r)}function gL(e,t){let r=e.trim(),i=(r.startsWith("+")||r.startsWith("-")?r.slice(1):r).split(".");if(i.length>2)return!1;let[o,a=""]=i;return o.length===0&&a.length===0||!pL.test(o)||!pL.test(a)||o.length>1&&o.startsWith("0")||o.length>Tee?!1:t!==oe.WorkflowAttributeType.Integer||i.length===1}var oe,Xu,mL,_ee,pL,Tee,bb=L(()=>{"use strict";oe=Ae(tp());Xu={Equals:oe.WorkflowConditionOperator.Equal,DoesNotEqual:oe.WorkflowConditionOperator.NotEqual,IsGreaterThan:oe.WorkflowConditionOperator.GreaterThan,IsLessThan:oe.WorkflowConditionOperator.LessThan,IsGreaterThanEqualTo:oe.WorkflowConditionOperator.GreaterThanOrEqual,IsLessThanEqualTo:oe.WorkflowConditionOperator.LessThanOrEqual,Contains:oe.WorkflowConditionOperator.Contains,DoesNotContain:oe.WorkflowConditionOperator.DoesNotContain,BeginsWith:oe.WorkflowConditionOperator.BeginsWith,DoesNotBeginWith:oe.WorkflowConditionOperator.DoesNotBeginWith,EndsWith:oe.WorkflowConditionOperator.EndsWith,DoesNotEndWith:oe.WorkflowConditionOperator.DoesNotEndWith,On:oe.WorkflowConditionOperator.On,NotOn:oe.WorkflowConditionOperator.NotOn,ContainsData:oe.WorkflowConditionOperator.NotNull,DoesNotContainData:oe.WorkflowConditionOperator.IsNull},mL=[oe.WorkflowAttributeType.Decimal,oe.WorkflowAttributeType.Float,oe.WorkflowAttributeType.Integer,oe.WorkflowAttributeType.Money],_ee=[oe.WorkflowConditionOperator.GreaterThan,oe.WorkflowConditionOperator.GreaterThanOrEqual,oe.WorkflowConditionOperator.LessThan,oe.WorkflowConditionOperator.LessThanOrEqual];pL=/^\d*$/,Tee=28});var yL=L(()=>{"use strict";});function Ln(e){return!Dee.has(e)}function vb(e){return e==="Equals"||e==="DoesNotEqual"}function np(e){return vL.has(e)?Iee:Lee.has(e)?Oee:wL.has(e)?Pee:xee.has(e)?kee:Ree}function CL(e){return np(e)[0]}function EL(e,t){return np(t).includes(e)}function bL(e){return vL.has(e)?"string":e==="Money"?"money":e==="Integer"||e==="BigInt"?"integer":e==="Decimal"||e==="Double"?"decimal":wL.has(e)?"date":$ee.has(e)?"boolean":"other"}function ip(e,t){let r=bL(e),n=bL(t);return r==="other"||n==="other"?e===t:r===n}var Dee,Iee,Oee,Pee,Ree,kee,vL,Lee,wL,$ee,xee,op=L(()=>{"use strict";yL();Dee=new Set(["ContainsData","DoesNotContainData"]);Iee=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],Oee=["Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],Pee=["On","NotOn","Equals","DoesNotEqual","IsGreaterThan","IsGreaterThanEqualTo","IsLessThan","IsLessThanEqualTo","ContainsData","DoesNotContainData"],Ree=["Equals","DoesNotEqual","ContainsData","DoesNotContainData"],kee=["Equals","DoesNotEqual","Contains","DoesNotContain","BeginsWith","DoesNotBeginWith","EndsWith","DoesNotEndWith","ContainsData","DoesNotContainData"],vL=new Set(["String","Memo","EntityName"]),Lee=new Set(["Integer","BigInt","Money","Decimal","Double"]),wL=new Set(["DateTime"]),$ee=new Set(["Boolean"]),xee=new Set(["Lookup","Owner","Customer"])});function _L(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 kL(e){return e&&e!==Fe.WorkflowAttributeType.String?e:void 0}function Uee(e){return{__class:RL,parameterName:"primaryEntity",entityName:e}}function AL(e){return{__class:Cb,type:wb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:TL,parameters:[e]}}function SL(e,t,r=Fe.WorkflowAttributeType.String){return{__class:IL,type:r,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,entity:Uee(t),attributeName:e}}function Bee(e,t=Fe.WorkflowAttributeType.String){return{__class:OL,type:t,behavior:Fe.AttributeDateTimeBehavior.None,typeSet:!1,primitiveValue:e}}function qee(e){return{__class:PL,type:wb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,days:e,hours:"0",minutes:"0",months:"0",years:"0"}}function LL(e,t){let r=Fee[e.operator],n=AL(SL(e.leftField,t,e.leftWorkflowType)),i;e.dateArithmetic?i=qee(e.right.value??"0"):e.right.kind==="field"?i=SL(e.right.field??"",t,e.right.workflowType):i=Bee(e.right.value??"",e.right.workflowType??e.leftWorkflowType);let o=AL(i);return{__class:Cb,type:wb,typeSet:!1,behavior:Fe.AttributeDateTimeBehavior.None,method:DL,parameters:[r,n,o]}}function $L(e){return typeof e=="object"&&e.__class===Cb}function Vee(e){return typeof e=="object"&&e.__class===PL}function ap(e){return $L(e)&&e.method===TL&&e.parameters.length>0?ap(e.parameters[0]):e}function NL(e){if(typeof e!="object"||e.__class!==IL)return null;let t=e.entity;if(t&&t.__class&&t.__class!==RL)return null;let r=e.attributeName;return r?{field:r,workflowType:kL(e.type)}:null}function xL(e){if(!e)return null;let t=ap(e);if(!$L(t)||t.method!==DL||t.parameters.length!==3)return null;let r=t.parameters[0],n=Mee[String(r)];if(!n)return null;let i=NL(ap(t.parameters[1]));if(!i)return null;let o=ap(t.parameters[2]);if(Vee(o))return n!=="+"&&n!=="-"?null:{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:String(o.days??"")},dateArithmetic:!0};let a=NL(o);if(a)return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"field",field:a.field,workflowType:a.workflowType}};if(typeof o=="object"&&o.__class===OL){let s=o.primitiveValue;return{leftField:i.field,leftWorkflowType:i.workflowType,operator:n,right:{kind:"value",value:s!=null?String(s):"",workflowType:kL(o.type)}}}return null}function Ab(e){let t=(e??"").trim();if(!/^\d+$/.test(t))return!1;let r=Number(t);return Number.isSafeInteger(r)&&r>=Eb&&r<=Xs}function wa(e){if(!e||!e.leftField)return"incomplete";if(e.right.kind==="field")return e.right.field&&e.right.field.trim()?null:"incomplete";let t=e.right.value;return!t||!t.trim()?"incomplete":e.dateArithmetic&&!Ab(t)?"invalidDayCount":null}function Zs(e){return wa(e)===null}var Fe,TL,DL,wb,IL,OL,Cb,PL,RL,Fee,Mee,Eb,Xs,Zu=L(()=>{"use strict";Fe=Ae(tp());op();TL="0",DL="3",wb="0",IL="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",OL="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",Cb="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",PL="TimeSpanExpression:#Microsoft.Crm.Workflow.Expressions",RL="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions";Fee={"+":0,"-":1,"*":2,"/":3},Mee={0:"+",1:"-",2:"*",3:"/"};Eb=0,Xs=2147483647});function Wee(e){return e.startsWith("__")&&!Gee.has(e)}function zee(e){let t=Object.create(null);return Object.keys(e).forEach(r=>{Wee(r)&&(t[r]=e[r])}),Object.keys(t).length>0?t:void 0}function YL(e){return e.__class==="BinaryExpression:#Microsoft.Crm.Workflow.Expressions"}function Ea(e){return e.__class==="UnaryExpression:#Microsoft.Crm.Workflow.Expressions"}function sp(e){return YL(e)||Ea(e)}function jee(e){return e.__class==="ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel"}function ec(){return{list:[]}}function Sb(e,t,r){return e&&e.list.length>0?{list:[{...e.list[0],description:t},...e.list.slice(1)]}:{list:[{labelId:pr(),languageCode:r,description:t}]}}function _b(e){return{__class:"PrimaryEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:"primaryEntity",entityName:e}}function dp(e,t,r,n=j.AttributeDateTimeBehavior.None){return{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:n,typeSet:!1,entity:_b(t),attributeName:e}}function Ca(e,t,r=j.AttributeDateTimeBehavior.None){return{__class:"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions",type:t,behavior:r,typeSet:!1,primitiveValue:e}}function Jee(e){return e.bpfField==="StageCategory"?e.stageType==="SelectedStage"?ZL:XL:QL}function e1(e){return e.bpfField==="StageCategory"?j.WorkflowAttributeType.BpfStageCategory:j.WorkflowAttributeType.BpfProcess}function Yee(e,t){let r=e1(e),n=e.bpfField==="StageCategory"?{__class:"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,entity:{__class:"RelatedEntity:#Microsoft.Crm.Workflow.Expressions",parameterName:`related_${ML}_${FL}`,entityName:FL,relatedAttributeName:ML},attributeName:Kee}:dp(Hee,t,r);return{__class:"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",type:r,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,method:Ib,parameters:[Jee(e),n]}}function t1(e){let t=e;if(t.__class!=="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"||String(t.method)!==Ib)return null;let r=(t.parameters??[])[0];if(typeof r!="string")return null;let n=r.replace(/^"+|"+$/g,"");return n===XL?{bpfField:"StageCategory",stageType:"ActiveStage"}:n===ZL?{bpfField:"StageCategory",stageType:"SelectedStage"}:n===QL?{bpfField:"ProcessName"}:null}function lp(e){if(!e)return!1;let t=e;if(t.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"&&String(t.method)===Ib){let r=(t.parameters??[])[0];if(typeof r=="string"&&Qee.has(r.replace(/^"+|"+$/g,"")))return!0}return Ea(e)?lp(e.operand):YL(e)?lp(e.left)||(e.right??[]).some(lp):!1}function r1(e){if(e?.__class!=="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.entity;return t==null||t.__class==="PrimaryEntity:#Microsoft.Crm.Workflow.Expressions"}function Xee(e){if(e?.__class!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions")return!1;let t=e.primitiveValue;return t===!0||typeof t=="string"&&t.toLowerCase()==="true"}function UL(e){if(!e)return!1;switch(e.__class){case"EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions":return r1(e);case"PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions":return e.primitiveValue!=null||e.type!==void 0;case"LookupExpression:#Microsoft.Crm.Workflow.Expressions":case"MethodCallExpression:#Microsoft.Crm.Workflow.Expressions":return!0;default:return!1}}function Zee(e){let t=Db[e.conditionOperatoroperator];if(!t)return!1;let r=t==="ContainsData"||t==="DoesNotContainData";if(Ea(e))return r&&BL(e.operand,!0);let n=e.right??[];return n.length!==(r?0:1)?!1:BL(e.left,r,n[0])}function BL(e,t,r){return t1(e)||r1(e)?t||UL(r):!1}function Tb(e){if(!e||!sp(e))return!1;let t=e.conditionOperatoroperator;if(!Ea(e)&&(t===j.WorkflowConditionOperator.LogicalAnd||t===j.WorkflowConditionOperator.LogicalOr)){let r=e.right??[];return r.length>0&&Tb(e.left)&&r.every(Tb)}return Zee(e)}function qL(e){return!e||Xee(e)?!1:lp(e)||!Tb(e)}function n1(e){return{__class:"LookupExpression:#Microsoft.Crm.Workflow.Expressions",type:e.workflowType??j.WorkflowAttributeType.Lookup,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,entityType:e.entityType,label:e.label??"",staticValue:Ca(e.id.replace(/[{}]/g,""),j.WorkflowAttributeType.UniqueIdentifier)}}function tte(e){return e===j.WorkflowAttributeType.DateTime?j.AttributeDateTimeBehavior.DateOnly:j.AttributeDateTimeBehavior.None}function rte(e,t){if(t!==j.WorkflowAttributeType.DateTime)return j.AttributeDateTimeBehavior.None;let r=e.leftDateTimeBehavior;return r!==void 0&&r!==j.AttributeDateTimeBehavior.None?r:tte(t)}function nte(e,t,r){if(t!==j.WorkflowAttributeType.DateTime)return j.AttributeDateTimeBehavior.None;let n=e.valueFieldDateTimeBehavior;return n!==void 0&&n!==j.AttributeDateTimeBehavior.None?n:r}function ote(e){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return"1";if(t==="false"||t==="0")return"0"}function pte(e){let t=fte.exec(e);if(t)return`${t[1]}T${t[2]}`;let r=dte.exec(e);if(!r)return;let[,n,i,o,a,s,l]=r,u=cte.indexOf(i.toLowerCase());if(u<0)return;let c=String(u+1).padStart(2,"0");return`${o}-${c}-${n}T${a}:${s}:${l}`}function mte(e){let t=pte(e.trim());return t!==void 0&&i1(t)?t:e}function i1(e){let t=e.trim(),r=t.indexOf("T")>=0?"T":" ",n=t.indexOf(r),i=n>=0?t.slice(0,n):t,o=n>=0?t.slice(n+1):"";if(!ate.test(i)||o.length>0&&!ste.test(o)&&!lte.test(o)&&!ute.test(o))return!1;let[a,s,l]=i.split("-"),u=new Date(`${a}-${s}-${l}T00:00:00Z`);return!Number.isNaN(u.getTime())&&u.getUTCFullYear()===Number(a)&&u.getUTCMonth()+1===Number(s)&&u.getUTCDate()===Number(l)}function hte(e,t){let r={value:e,type:j.WorkflowAttributeType.String};if(t===j.WorkflowAttributeType.String||ite.includes(t)||e.trim().length===0)return r;if(t===j.WorkflowAttributeType.Boolean){let n=ote(e);return n==null?r:{value:n,type:t}}return ete.includes(t)?ep(e)?{value:e.trim(),type:t}:r:rp(t)?{value:e.trim(),type:t}:t===j.WorkflowAttributeType.DateTime&&i1(e)?{value:e.trim(),type:t}:r}function VL(e){return e==="ContainsData"||e==="DoesNotContainData"}function GL(e){return gte.has(e)}function WL(e,t){return{__class:"UnaryExpression:#Microsoft.Crm.Workflow.Expressions",type:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:t,operand:e}}function zL(e,t){let r=e.leftWorkflowType??e.valueWorkflowType??j.WorkflowAttributeType.String,n=Xu[e.operator]??j.WorkflowConditionOperator.Equal,i=rte(e,r),o=yb(r,n);if(e.source==="BusinessProcess"){let l=Yee(e,t);if(VL(e.operator))return WL(l,n);let u=e1(e);return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:l,right:[Ca(e.value??"",u)]}}let a=dp(e.field,t,r,i);if(VL(e.operator))return WL(a,n);let s;if(e.valueType==="Field"&&e.valueField){let l=GL(o)&&GL(e.valueFieldWorkflowType??"")?e.valueFieldWorkflowType:o;s=[dp(e.valueField,t,l,nte(e,l,i))]}else if(e.valueType==="Lookup"){if(!e.lookupValue)throw new Error("Lookup condition is missing its record value.");s=[n1(e.lookupValue)]}else if(e.valueType==="Clear")s=[Ca(null,j.WorkflowAttributeType.String,i)];else if(e.valueType==="Expression")s=[cp(e.valueType,e.value,e.valueField,t,e.expression,e.rawExpression)];else{let l=hte(e.value??"",o);s=[Ca(l.value,l.type,i)]}return{__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:n,left:a,right:s}}function yte(){return Ca(!0,j.WorkflowAttributeType.Boolean)}function bte(e,t,r){if(e.length===0)return null;let n=zL(e[0],r);for(let i=1;i<e.length;i++){let o=e[i].connector??t;n={__class:"BinaryExpression:#Microsoft.Crm.Workflow.Expressions",type:j.WorkflowAttributeType.Boolean,behavior:j.AttributeDateTimeBehavior.None,typeSet:!1,conditionOperatoroperator:o==="AND"?j.WorkflowConditionOperator.LogicalAnd:j.WorkflowConditionOperator.LogicalOr,left:n,right:[zL(e[i],r)]}}return n}function up(e){if(!e)return{valueType:"Value",value:""};if(e.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions")return{valueType:"Field",valueField:e.attributeName,valueFieldWorkflowType:e.type};if(e.__class==="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"){if(e.primitiveValue==null)return{valueType:"Clear",valueWorkflowType:e.type};let t=String(e.primitiveValue);if(e.type===j.WorkflowAttributeType.Boolean){let r=t.trim().toLowerCase();if(r==="1"||r==="true")return{valueType:"Value",value:"true",valueWorkflowType:e.type};if(r==="0"||r==="false")return{valueType:"Value",value:"false",valueWorkflowType:e.type}}return e.type===j.WorkflowAttributeType.DateTime?{valueType:"Value",value:mte(t),valueWorkflowType:e.type}:{valueType:"Value",value:t,valueWorkflowType:e.type}}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!==j.WorkflowAttributeType.Lookup?{workflowType:e.type}:{}}}}if(e.__class==="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions"){let t=xL(e);return t?{valueType:"Expression",expression:t}:{valueType:"Expression",rawExpression:e}}return{valueType:"Value",value:""}}function vte(e){let t=Db[e.conditionOperatoroperator]??"Equals",r=t==="ContainsData"||t==="DoesNotContainData",n=Ea(e)?e.operand:e.left,i=Ea(e)?[]:e.right??[],o=t1(n);if(o){let g=i[0];return{id:pr(),field:"",fieldDisplayName:"",source:"BusinessProcess",bpfField:o.bpfField,...o.stageType?{stageType:o.stageType}:{},operator:t,valueType:"Value",value:g?.primitiveValue!=null&&!r?String(g.primitiveValue):""}}let a=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions",s=n.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"?n.attributeName:"",l=a?n.type:void 0,u=r?{valueType:"Value"}:up(i[0]),c=l,d=a&&n.type===j.WorkflowAttributeType.DateTime&&n.behavior!==j.AttributeDateTimeBehavior.None?n.behavior:void 0,f=u.valueWorkflowType??l,m=r?void 0:i[0],h=m?.__class==="EntityAttributeExpression:#Microsoft.Crm.Workflow.Expressions"&&m.type===j.WorkflowAttributeType.DateTime&&m.behavior!==j.AttributeDateTimeBehavior.None?m.behavior:void 0;return{id:pr(),field:s,fieldDisplayName:s,operator:t,...u,...f?{valueWorkflowType:f}:{},...c?{leftWorkflowType:c}:{},...d!==void 0?{leftDateTimeBehavior:d}:{},...h!==void 0?{valueFieldDateTimeBehavior:h}:{}}}function jL(e){if(!e||!sp(e))return{clauses:[],logic:"AND"};let t=[],r=(o,a)=>{let s=o.conditionOperatoroperator;if(Ea(o)||s!==j.WorkflowConditionOperator.LogicalAnd&&s!==j.WorkflowConditionOperator.LogicalOr){t.push({...vte(o),...a?{connector:a}:{}});return}let l=s===j.WorkflowConditionOperator.LogicalAnd?"AND":"OR";sp(o.left)&&r(o.left,a),(o.right??[]).filter(sp).forEach(u=>r(u,l))};r(e,void 0);let i=t.slice(1).map(o=>o.connector??"AND")[0]??"AND";return{clauses:t,logic:i}}function cp(e,t,r,n,i,o,a,s){if(e==="Field"&&r)return dp(r,n,j.WorkflowAttributeType.String);if(e==="Expression"){if(i)return LL(i,n);if(o!=null)return o}return e==="Lookup"&&a?n1(a):e==="Clear"?Ca(null,s??j.WorkflowAttributeType.String):Ca(t??"",j.WorkflowAttributeType.String)}function Nb(e,t){return{propertyName:e,propertyValueExpr:t}}function el(e){return`Step_${e.value++}`}function mn(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 HL(e,t,r){return e&&!r.used.has(e)?(r.used.add(e),e):mn(t,r)}function wte(e){return e===JL.StateCode.Activated?"Active":"Draft"}function Cte(e){let t={},r=e;typeof r.ismanaged=="boolean"&&(t.isManaged=r.ismanaged);let n=r.iscustomizable;return typeof n=="boolean"?t.isCustomizable=n:n!==null&&typeof n=="object"&&typeof n.Value=="boolean"&&(t.isCustomizable=n.Value),t}function Ete(e,t){let r=e.processtriggerscope,n=e.processtriggerformid;return r===1?n&&n.trim()!==""?n:"AllForms":r===2?"Entity":t??"Entity"}function o1(e,t=1033){return new tl({languageCode:t}).serialize(e)}function a1(e){return new tl().deserialize(e)}var JL,j,Gee,Db,Ib,QL,XL,ZL,Hee,Kee,FL,ML,Qee,ete,ite,ate,ste,lte,ute,cte,dte,fte,gte,Ob,tl,Pb=L(()=>{"use strict";mb();JL=Ae(Qi());dL();hb();bb();Zu();j=Ae(tp());Gee=new Set(["__class"]);Db={};for(let e of Object.keys(Xu))Db[Xu[e]]=e;Ib="23",QL="BpfProcess",XL="ActiveStageCategory",ZL="SelectedStageCategory",Hee="processid",Kee="stagecategory",FL="processstage",ML="stageid";Qee=new Set(["ActiveStage","SelectedStage","Stage"]);ete=[j.WorkflowAttributeType.Picklist,j.WorkflowAttributeType.State,j.WorkflowAttributeType.Status];ite=[j.WorkflowAttributeType.Lookup,j.WorkflowAttributeType.Customer,j.WorkflowAttributeType.Owner];ate=/^\d{4}-\d{2}-\d{2}$/,ste=/^\d{2}:\d{2}$/,lte=/^\d{2}:\d{2}:\d{2}$/,ute=/^\d{2}:\d{2}:\d{2}\.\d{1,7}$/,cte=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],dte=/^[A-Za-z]{3}, (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/,fte=/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}:\d{2}\.\d{1,7}|\d{2}:\d{2}:\d{2}|\d{2}:\d{2})Z$/;gte=new Set([j.WorkflowAttributeType.Lookup,j.WorkflowAttributeType.Owner,j.WorkflowAttributeType.Customer]);Ob={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"};tl=class{resolveLabel;languageCode;entityName="";stepCounter={value:0};idCounter={counts:{},used:new Set};constructor(t={}){this.resolveLabel=t.resolveLabel??(r=>Ob[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)]:[],o={...r?.reservedProperties??{},__class:"WorkflowStep:#Microsoft.Crm.Workflow.ObjectModel",id:r?.id??t.ruleId??pr(),name:r?.name??"Step_0",description:r!==void 0?r.description:t.description||null,stepLabels:ec(),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(o)}makeApplyActionStep(t){return{__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",id:mn("SetAttributeValueStep",this.idCounter),description:t.displayName||"New Action",name:t.stepName??el(this.stepCounter),stepLabels:{list:[]},specification:Nb(t.field,cp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType)),entity:_b(this.entityName)}}makeRecommendationActionStep(t,r,n){let i=r.map(l=>this.makeApplyActionStep(l)),o=t??"",a=n?.stepLabels,s=Sb(a,o,this.languageCode);return{__class:"ActionStep:#Microsoft.Crm.Workflow.ObjectModel",id:HL(n?.id,"ActionStep",this.idCounter),name:n?.name??el(this.stepCounter),description:n?.description??"Action step",stepLabels:s,steps:{list:i},actionId:null,actionType:n?.actionType??"4",processId:n?.processId??pr(),uniqueName:n?.uniqueName??`id_${pr().replace(/-/g,"")}ActionStep`}}serializeAction(t){let r=_b(this.entityName),n=t.stepName??el(this.stepCounter),i=t.stepLabels??ec(),o={name:n,stepLabels:i,description:t.displayName},a=t.type;switch(a){case"SetFieldValue":return{...o,id:mn("SetAttributeValueStep",this.idCounter),__class:"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:Nb(t.field,cp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"SetDefaultValue":return{...o,id:mn("SetDefaultValueStep",this.idCounter),__class:"SetDefaultValueStep:#Microsoft.Crm.Workflow.ObjectModel",entity:r,specification:Nb(t.field,cp(t.valueType,t.value,t.valueField,this.entityName,t.expression,t.rawExpression,t.lookupValue,t.valueWorkflowType))};case"LockUnlock":return{...o,id:mn("SetDisplayModeStep",this.idCounter),__class:"SetDisplayModeStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",isReadOnly:t.lock,entity:r};case"SetBusinessRequired":return{...o,id:mn("SetFieldRequiredLevelStep",this.idCounter),__class:"SetFieldRequiredLevelStep:#Microsoft.Crm.Workflow.ObjectModel",controlId:t.field,controlType:"standard",requiredLevel:t.required?j.FieldRequiredLevelTypes.Required:j.FieldRequiredLevelTypes.None,entity:r};case"SetVisibility":return{...o,id:mn("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=Sb(t.stepLabels,s,this.languageCode);return{...o,id:mn("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=Sb(t.stepLabels,s,this.languageCode),u={list:[this.makeRecommendationActionStep(t.acceptanceText,t.applyActions??[],t.recommendationActionStepMeta)]};return{...o,id:mn("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: ${a}`)}}serializeConditionNode(t){let r=t.stepName??el(this.stepCounter),n=mn("ConditionStep",this.idCounter),i=[],o=t,a=!0;for(;o;){let s=o.rawConditionExpression??bte(o.clauses,o.logic,this.entityName),l=a?o.branchName??el(this.stepCounter):el(this.stepCounter),c={__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:a?HL(o.branchId,"ConditionBranchStep",this.idCounter):mn("ConditionBranchStep",this.idCounter),name:l,description:o.displayName,stepLabels:ec(),conditionExpression:s??(a?yte():void 0),steps:{list:o.trueBranch.map(f=>this.serializeBranchItem(f))}};i.push(c);let d=o.falseBranch;if(d.length===1&&d[0].kind==="condition"){o=d[0],a=!1;continue}d.length>0&&i.push(this.makeTerminalElseBranch(d)),o=void 0}return{__class:"ConditionStep:#Microsoft.Crm.Workflow.ObjectModel",id:n,name:r,description:"",stepLabels:ec(),containsElsebranch:i.length>1,steps:{list:i}}}makeTerminalElseBranch(t){return{__class:"ConditionBranchStep:#Microsoft.Crm.Workflow.ObjectModel",id:mn("ConditionBranchStep",this.idCounter),name:"Else",description:null,stepLabels:ec(),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 o=JSON.parse(t.wfomJson);i={id:o.id==="WorkflowStep0"||!o.id?t.workflowid??pr():o.id,name:o.name,description:o.description,nextStepIndex:o.nextStepIndex,category:o.category==="0"||o.category===0?"2":o.category,businessProcessType:o.businessProcessType,mode:o.mode,title:o.title||t.name||"",primaryEntityName:o.primaryEntityName==="1"||!o.primaryEntityName?t.primaryentity??"":o.primaryEntityName,workflowEntityId:o.workflowEntityId==="00000000-0000-0000-0000-000000000000"||!o.workflowEntityId?t.workflowid??"":o.workflowEntityId,formId:o.formId,variables:o.variables,inputs:o.inputs,reservedProperties:zee(o)};let s=(o.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:Ete(r,i?.formId),status:wte(t.statecode),rootCondition:n,wfomRoot:i,...Cte(t)}}deserializeConditionStep(t){let r=(t.steps?.list??[]).filter(jee);return this.buildConditionNodeFromBranches(r,t,!0)}buildConditionNodeFromBranches(t,r,n){let[i,...o]=t,{clauses:a,logic:s}=jL(i?.conditionExpression),l=this.deserializeBranch(i?.steps?.list??[]),u=this.deserializeElseChain(o,r),c=i?.description||i?.name||r.description||r.name||this.label("condition");return{kind:"condition",id:(n?r.id:i?.id)??pr(),displayName:c,clauses:a,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,...qL(i?.conditionExpression)?{rawConditionExpression:i?.conditionExpression}:{}}}deserializeElseChain(t,r){if(t.length===0)return[];let[n]=t,{clauses:i}=jL(n.conditionExpression);return i.length===0&&!qL(n.conditionExpression)?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},o=n.stepLabels?.list,a=o&&o.length>0?o[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||pr(),field:u?.propertyName??"",stepName:l.name??void 0,displayName:l.description??void 0,...up(u?.propertyValueExpr)}}),meta:i,acceptanceText:a}}deserializeAction(t){switch(t.__class){case"SetAttributeValueStep:#Microsoft.Crm.Workflow.ObjectModel":{let r=up(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=up(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!==j.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:o,acceptanceText:a}=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:a,applyActions:i,recommendationActionStepMeta:o}}return{kind:"action",id:t.id,type:"ShowErrorMessage",displayName:t.description||this.label("showErrorMessage"),stepName:t.name,stepLabels:t.stepLabels,field:t.controlId,errorMessage:n||t.name||"",messageLevel:t.level??void 0,messageActionSteps:t.actionSteps}}case"ActionStep:#Microsoft.Crm.Workflow.ObjectModel":{let{applyActions:r,meta:n,acceptanceText:i}=this.parseRecommendationApplyActions({list:[t]});return{kind:"action",id:t.id,type:"Recommendation",displayName:t.name||this.label("recommendation"),stepName:t.name,stepLabels:t.stepLabels,field:t.actionControl?.controlId??"",recommendationTitle:t.name||"",messageText:t.description||"",acceptanceText:i,applyActions:r,recommendationActionStepMeta:n}}default:return null}}}});var s1=L(()=>{"use strict";});function Tte(e){return typeof e=="object"&&e!==null?e:null}function rl(e){let t=Tte(e);if(!t)return!1;if(t.__class===Nte){let r=t;return String(r.method)===_te?!0:Array.isArray(r.parameters)&&r.parameters.some(rl)}if(t.__class===Ste)return rl(t.operand);if(t.__class===Ate){let r=t;return rl(r.left)||Array.isArray(r.right)&&r.right.some(rl)}return!1}var Ate,Ste,Nte,_te,l1=L(()=>{"use strict";s1();Ate="BinaryExpression:#Microsoft.Crm.Workflow.Expressions",Ste="UnaryExpression:#Microsoft.Crm.Workflow.Expressions",Nte="MethodCallExpression:#Microsoft.Crm.Workflow.Expressions",_te="23"});function $b(e){return Dte.has(e.type)}function Rb(e,t,r,n,i,o,a){let s=i.get(r);!s||!d1.has(s.attributeType)||n!=="Value"||a?.operator&&!vb(a.operator)||o.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:a?.target,itemId:a?.itemId,messageKey:"Validation.InvalidValueTypeForField",messageParams:{label:t}})}function Ite(e,t){let r=t.get(e.field);return!!r&&d1.has(r.attributeType)&&vb(e.operator)}function kb(e){return!!(e?.entityType?.trim()&&e.id?.trim())}function Lb(e,t,r){return{nodeId:e,kind:"INVALID_DAY_COUNT",message:`Please enter a whole number of days between 0 and ${Xs}.`,target:t,itemId:r,messageKey:"Validation.InvalidDayCount",messageParams:{max:Xs}}}function u1(e,t,r,n,i,o,a,s){if(i!=="Clear")return;let l=o.get(n);Qf(r,l)||a.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 pp(e){if(!e)return!1;for(let t of[...e.trueBranch,...e.falseBranch])if(t.kind==="action"){if($b(t))return!0}else if(pp(t))return!0;return!1}function xb(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=xb(r,t);if(n)return n}}return null}function Ote(e){if(!e||typeof e!="object")return!1;let{__class:t,primitiveValue:r}=e;return t!=="PrimitiveExpression:#Microsoft.Crm.Workflow.Expressions"?!1:r===!0||typeof r=="string"&&r.toLowerCase()==="true"}function Pte(e){return e.clauses.length===0&&(e.rawConditionExpression===void 0||Ote(e.rawConditionExpression))}function kte(e){return!!e.clauses?.some(t=>t.source==="BusinessProcess")||rl(e.rawConditionExpression)}function nl(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=nl(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=nl(n,t);if(i)return i}}return null}function Fb(e,t){return{...e,trueBranch:c1(e.trueBranch,t),falseBranch:c1(e.falseBranch,t)}}function c1(e,t){return e.filter(r=>r.id!==t).map(r=>r.kind==="condition"?Fb(r,t):r)}function To(e,t,r){return e.id===t?r(e):{...e,trueBranch:e.trueBranch.map(n=>n.kind==="condition"?To(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="condition"?To(n,t,r):n)}}function fp(e,t,r){return{...e,trueBranch:e.trueBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?fp(n,t,r):n),falseBranch:e.falseBranch.map(n=>n.kind==="action"&&n.id===t?r(n):n.kind==="condition"?fp(n,t,r):n)}}function f1(e,t,r,n){return To(e,t,i=>({...i,trueBranch:r==="true"?[...i.trueBranch,n]:i.trueBranch,falseBranch:r==="false"?[...i.falseBranch,n]:i.falseBranch}))}function Mb(e){return e.length===1&&e[0].kind==="condition"}function $te(e){let t=0,r=e??void 0;for(;r;){t+=1;let{falseBranch:n}=r;if(Mb(n)){r=n[0];continue}n.length>0&&(t+=1),r=void 0}return t}function xte(e){return!!e&&$te(e)<Lte}function Fte(e,t){if(!e)return;let r=(n,i)=>{if(n.id===t)return i;let o=[];if(Mb(n.falseBranch)){let a=r(n.falseBranch[0],i);if(a)return a}else o.push(...n.falseBranch.filter(a=>a.kind==="condition"));o.push(...n.trueBranch.filter(a=>a.kind==="condition"));for(let a of o){let s=r(a,a);if(s)return s}};return r(e,e)}function p1(e,t,r){let n=Fte(e,t);return!n||!xte(n)?e:To(e,t,i=>m1(i,r))}function m1(e,t){if(Mb(e.falseBranch))return{...e,falseBranch:[m1(e.falseBranch[0],t)]};let r=Ub(t);return r.falseBranch=e.falseBranch,{...e,falseBranch:[r]}}function h1(e,t){let r=nl(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 To(e,r.node.id,o=>({...o,falseBranch:i}))}function g1(e,t,r){let n=nl(e,t);if(!n)return e;let i=o=>{let a=[...o],s=a[n.index+r];return s?(a[n.index+r]=a[n.index],a[n.index]=s,a):o};return To(e,n.node.id,o=>({...o,trueBranch:n.branch==="true"?i(o.trueBranch):o.trueBranch,falseBranch:n.branch==="false"?i(o.falseBranch):o.falseBranch}))}function Ub(e){return{kind:"condition",id:pr(),displayName:e??"New Condition",clauses:[],logic:"AND",trueBranch:[],falseBranch:[],isCollapsed:!1}}function y1(e,t){let r={kind:"action",id:pr(),type:e,displayName:t??`New ${e}`};switch(e){case"Recommendation":return{...r,type:"Recommendation",field:"",recommendationTitle:"",messageText:"",applyActions:[{id:pr(),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 b1(e){if(!e)return[];let t=[];return v1(e,t),[...new Set(t)]}function v1(e,t){e.clauses.forEach(r=>{r.field&&t.push(r.field)}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"?v1(r,t):"field"in r&&r.field&&t.push(r.field)})}function w1(e,t=[],r){if(!e)return[{nodeId:"root",kind:"NO_CONDITION",message:"A business rule must include at least one condition.",target:"node"}];let n=[],i=new Map(t.map(o=>[o.logicalName,o]));return E1(e,n,i,!0),r==="Entity"&&C1(e,n),pp(e)||n.push({nodeId:"root",kind:"NO_ACTION",message:"A business rule must include at least one action step.",target:"node"}),n}function C1(e,t){kte(e)&&t.push({nodeId:e.id,kind:"BPF_IN_ENTITY_SCOPE",message:"Process based conditions are not allowed in Entity scope.",target:"node",messageKey:"Validation.ProcessConditionNotAllowedInEntityScope"}),[...e.trueBranch,...e.falseBranch].forEach(r=>{r.kind==="condition"&&C1(r,t)})}function E1(e,t,r,n=!1){let i=n&&Pte(e),o=!!e.rawConditionExpression;e.clauses.length===0&&!n&&!o&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Add at least one clause to this condition.",target:"node",messageKey:"Validation.AddClause"}),i&&e.falseBranch.length>0&&t.push({nodeId:e.id,kind:"UNREACHABLE_ELSE",message:"Add a condition to the IF clause, or delete the ELSE clause it can never reach.",target:"node",messageKey:"Validation.UnreachableElse"}),e.clauses.forEach(a=>{if(o)return;if(a.source==="BusinessProcess"){a.bpfField?a.value||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id}):t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a business process field for this clause.",target:"clauseField",itemId:a.id,messageKey:"Validation.SelectBusinessProcessField"});return}let s=a.valueType==="Expression"&&!a.rawExpression?wa(a.expression):null;if(!a.field)t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_FIELD",message:"Please select a field for this clause.",target:"clauseField",itemId:a.id});else if(Ln(a.operator)&&a.valueType==="Value"&&!a.value&&!Ite(a,r))t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please enter a value for this clause.",target:"clauseValue",itemId:a.id});else if(Ln(a.operator)&&a.valueType==="Value"&&a.value){let u=r.get(a.field);u?.maxLength&&a.value.length>u.maxLength&&t.push({nodeId:e.id,kind:"CLAUSE_VALUE_TOO_LONG",message:`Value exceeds the field's maximum length of ${u.maxLength} characters.`,target:"clauseValue",itemId:a.id,messageParams:{maxLength:u.maxLength}})}else Ln(a.operator)&&a.valueType==="Expression"&&!a.rawExpression&&!Zs(a.expression)?t.push(s==="invalidDayCount"?Lb(e.id,"clauseValue",a.id):{nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please complete the formula for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.CompleteClauseFormula"}):Ln(a.operator)&&a.valueType==="Field"&&!a.valueField&&t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a field to compare to for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseCompareField"});Ln(a.operator)&&a.valueType==="Value"&&a.value&&fL(r.get(a.field)?.attributeType)&&!ep(a.value)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_OPTION_VALUE",message:"Please enter a whole number option value for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.InvalidClauseOptionValue"});let l=hL(a);Ln(a.operator)&&a.valueType==="Value"&&a.value&&rp(l)&&!gL(a.value,l)&&t.push({nodeId:e.id,kind:"INVALID_CLAUSE_NUMERIC_VALUE",message:gb(l)?"Please enter a whole number for this clause.":"Please enter a valid number for this clause.",target:"clauseValue",itemId:a.id,messageKey:gb(l)?"Validation.InvalidClauseWholeNumberValue":"Validation.InvalidClauseNumericValue"}),Ln(a.operator)&&a.valueType==="Lookup"&&(kb(a.lookupValue)||t.push({nodeId:e.id,kind:"EMPTY_CLAUSE_VALUE",message:"Please select a lookup record for this clause.",target:"clauseValue",itemId:a.id,messageKey:"Validation.EmptyClauseLookupValue"})),Ln(a.operator)&&Rb(e.id,"Condition",a.field,a.valueType,r,t,{operator:a.operator,target:"clauseValue",itemId:a.id})}),i&&e.trueBranch.forEach(a=>{a.kind==="action"&&Rte.has(a.type)&&t.push({nodeId:a.id,kind:"ACTION_REQUIRES_CONDITION",message:"Set field value, Show error message, and Recommendation actions require a condition. Add a condition to the IF clause, or use a different action.",target:"node",messageKey:"Validation.ActionRequiresCondition",messageParams:{actionType:a.type}})}),[...e.trueBranch,...e.falseBranch].forEach(a=>{if(a.kind==="condition")E1(a,t,r);else{if(!("field"in a)||!a.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:`${a.type}: a target field is required.`,target:"actionField",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&(a.valueType??"Value")==="Value"&&!a.value?.trim())t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please provide a value.`,target:"actionValue",messageParams:{actionType:a.type}});else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Value"&&a.value){let s=r.get(a.field);s?.maxLength&&a.value.length>s.maxLength&&t.push({nodeId:a.id,kind:"ACTION_VALUE_TOO_LONG",message:`${a.type}: value exceeds the field's maximum length of ${s.maxLength} characters.`,target:"actionValue",messageParams:{actionType:a.type,maxLength:s.maxLength}})}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Field"){if(!a.valueField)t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please select a field to copy from.`,target:"actionValue",messageKey:"Validation.SelectActionSourceField",messageParams:{actionType:a.type}});else if(r.size>0){let s=r.get(a.field),l=r.get(a.valueField);s&&l&&!ip(s.attributeType,l.attributeType)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: the source field's type is not compatible with the target field.`,target:"actionValue",messageKey:"Validation.IncompatibleActionSourceField",messageParams:{actionType:a.type}})}}else if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Expression"){let s=a.rawExpression?null:wa(a.expression);!a.rawExpression&&!Zs(a.expression)&&t.push(s==="invalidDayCount"?Lb(a.id,"actionValue"):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the formula.`,target:"actionValue",messageKey:"Validation.CompleteActionFormula",messageParams:{actionType:a.type}})}else(a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.valueType==="Lookup"&&!kb(a.lookupValue)&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:`${a.type}: please complete the lookup record.`,target:"actionValue",messageKey:"Validation.EmptyActionLookupValue",messageParams:{actionType:a.type}});if((a.type==="SetFieldValue"||a.type==="SetDefaultValue")&&a.field&&(Rb(a.id,a.type,a.field,a.valueType,r,t,{target:"actionValue"}),u1(a.id,a.type,a.type,a.field,a.valueType,r,t,{target:"actionValue"})),a.type==="ShowErrorMessage"&&!a.errorMessage?.trim()&&t.push({nodeId:a.id,kind:"EMPTY_ACTION_MESSAGE",message:"Show error message: please enter an error message.",target:"actionMessage"}),a.type==="Recommendation"){let s=a.applyActions??[];a.recommendationTitle?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_TITLE",message:"Recommendation: please enter a recommendation title.",target:"recommendationTitle"}),a.messageText?.trim()||t.push({nodeId:a.id,kind:"EMPTY_RECOMMENDATION_MESSAGE",message:"Recommendation: please enter a recommendation message.",target:"recommendationMessage"}),s.length===0&&t.push({nodeId:a.id,kind:"RECOMMENDATION_NO_APPLY_ACTION",message:"Recommendation: add at least one action to apply.",target:"node"}),s.forEach(l=>{if(!l.field)t.push({nodeId:a.id,kind:"EMPTY_ACTION_FIELD",message:"Recommendation: a target field is required for each action to apply.",target:"applyActionField",itemId:l.id,messageKey:"Validation.RecommendationApplyField"});else if(l.valueType==="Field")l.valueField||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please select a field to copy from.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplySourceField"});else if(l.valueType==="Expression"){let u=l.rawExpression?null:wa(l.expression);!l.rawExpression&&!Zs(l.expression)&&t.push(u==="invalidDayCount"?Lb(a.id,"applyActionValue",l.id):{nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the formula.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyFormula"})}else l.valueType==="Lookup"?kb(l.lookupValue)||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please complete the lookup record.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyLookupValue"}):l.valueType==="Clear"||l.value?.trim()||t.push({nodeId:a.id,kind:"EMPTY_ACTION_VALUE",message:"Recommendation: please enter a value for each action to apply.",target:"applyActionValue",itemId:l.id,messageKey:"Validation.RecommendationApplyValue"});l.field&&(Rb(a.id,"Recommendation",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}),u1(a.id,"Recommendation","SetFieldValue",l.field,l.valueType,r,t,{target:"applyActionValue",itemId:l.id}))})}}})}var Dte,d1,Rte,Lte,Bb=L(()=>{"use strict";mb();ub();op();Zu();l1();bb();hb();Dte=new Set(["LockUnlock","ShowErrorMessage","Recommendation","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]);d1=new Set(["Lookup","Customer","Owner"]);Rte=new Set(["SetFieldValue","ShowErrorMessage","Recommendation"]);Lte=10});var A1={};Jr(A1,{DAY_COUNT_MAX:()=>Xs,DAY_COUNT_MIN:()=>Eb,DEFAULT_DESERIALIZE_LABELS:()=>Ob,WorkflowJsonMapper:()=>tl,addElseIfInTree:()=>p1,appendToBranch:()=>f1,areFieldKindsCompatible:()=>ip,attributeTypeToWorkflowType:()=>_L,buildWorkflowEntity:()=>rL,collectUsedFields:()=>b1,createEmptyAction:()=>y1,createEmptyCondition:()=>Ub,deserializeWorkflowJson:()=>a1,findNode:()=>xb,findParent:()=>nl,getDefaultOperatorForFieldType:()=>CL,getExpressionModelIssue:()=>wa,getOperatorsForFieldType:()=>np,hasAnyTriggerGeneratingAction:()=>pp,isDayCountValid:()=>Ab,isExpressionModelComplete:()=>Zs,isOperatorCompatible:()=>EL,isTriggerGeneratingAction:()=>$b,moveBranchItemInTree:()=>g1,operatorNeedsValue:()=>Ln,processTriggerFormIdFromScope:()=>db,processTriggerScopeFromScope:()=>cb,removeElseIfInTree:()=>h1,removeNodeFromTree:()=>Fb,serializeToWorkflowJson:()=>o1,supportsClearForActionType:()=>Qf,updateActionInTree:()=>fp,updateConditionInTree:()=>To,validateBusinessRule:()=>w1});var S1=L(()=>{"use strict";ub();nL();Pb();Pb();Bb();Bb();op();Zu();Zu();});var qb=v(mp=>{"use strict";Object.defineProperty(mp,"__esModule",{value:!0});mp.cloneJson=void 0;function Mte(e){return JSON.parse(JSON.stringify(e))}mp.cloneJson=Mte});var x1=v(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.BUSINESS_RULE_NULL_GUID=Do.businessRuleRegistration=Do.BusinessRuleAdapter=void 0;var N1=pt(),tc=(S1(),Br(A1)),_1=Qr(),T1=Q(),Ute=qb(),oi=rn(),Bte=Fm(),qte=pt(),Vte=Jo(),Gte=new Set(["ShowErrorMessage","Recommendation"]);function P1(e){var t,r;return e?[...(t=e.trueBranch)!==null&&t!==void 0?t:[],...(r=e.falseBranch)!==null&&r!==void 0?r:[]].some(n=>Array.isArray(n.trueBranch)||Array.isArray(n.falseBranch)?P1(n):Gte.has(String(n.type))):!1}function Wte(e){return R1((0,Ute.cloneJson)(e))}function R1(e){var t,r;let n=i=>(i??[]).map(o=>zte(o)?R1(o):o);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 zte(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 jte(e){var t;if(e===null||typeof e!="object"||Array.isArray(e))throw new T1.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 T1.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 Hte="00000000-0000-0000-0000-000000000000";Do.BUSINESS_RULE_NULL_GUID=Hte;var Kte=new Set(["Recommendation","LockUnlock","ShowErrorMessage","SetFieldValue","SetDefaultValue","SetBusinessRequired","SetVisibility"]),Jte=["ruleId","name","description","entityLogicalName","scope","status","rootCondition"],Yte=["kind","id","displayName","logic","clauses","trueBranch","falseBranch"],Qte=["id","field","fieldDisplayName","operator","valueType","value","valueField","lookupValue","expression","rawExpression","valueWorkflowType"];function $n(e,t){return e===void 0?t:{...e,...t}}var Aa=["kind","id","type","displayName","field","stepName","stepLabels"],D1=["valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression"],Xte={Recommendation:[...Aa,"recommendationTitle","messageText","acceptanceText","applyActions","recommendationActionStepMeta"],LockUnlock:[...Aa,"lock"],ShowErrorMessage:[...Aa,"errorMessage","messageLevel","messageActionSteps"],SetFieldValue:[...Aa,...D1],SetDefaultValue:[...Aa,...D1],SetBusinessRequired:[...Aa,"required"],SetVisibility:[...Aa,"visible"]};function ne(e,t){return t===void 0?{}:{[e]:t}}function k1(e){var t;return e==null?void 0:{...e,label:(t=e.label)!==null&&t!==void 0?t:""}}function Vb(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",k1(e.lookupValue)),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function L1(e,t){let r=new Set(t),n={};for(let[i,o]of Object.entries(e))r.has(i)||o!==void 0&&(n[i]=o);return Object.keys(n).length>0?n:void 0}var Zte=["id","field","valueType","valueWorkflowType","value","valueField","lookupValue","expression","rawExpression","stepName","displayName"];function ere(e){return $n(e.bag,{id:e.id,field:e.field,...Vb(e),...ne("stepName",e.stepName),...ne("displayName",e.displayName)})}function tre(e){let t=L1(e,Zte);return{id:e.id,field:e.field,valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",e.lookupValue),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression),...ne("stepName",e.stepName),...ne("displayName",e.displayName),...ne("bag",t)}}function I1(e){return{valueType:e.valueType,...ne("valueWorkflowType",e.valueWorkflowType),...ne("value",e.value),...ne("valueField",e.valueField),...ne("lookupValue",e.lookupValue),...ne("expression",e.expression),...ne("rawExpression",e.rawExpression)}}function O1(e){throw new Error(`Unsupported business-rule action type: ${e.type}`)}var rre=new Set(["INVALID_CLEAR_FOR_FIELD","INVALID_VALUE_TYPE_FOR_FIELD","CLAUSE_VALUE_TOO_LONG","ACTION_VALUE_TOO_LONG"]),nre=new Set,ire="INVALID_CLEAR_FOR_FIELD";function ore(e){let t=n=>{var i;return(0,oi.isJsonObject)(n)&&(n.label===""||n.label===void 0)?{...n,label:String((i=n.id)!==null&&i!==void 0?i:"")}:n},r=n=>{if(!(0,oi.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 o of["clauses","trueBranch","falseBranch"])Array.isArray(i[o])&&(i[o]=i[o].map(r));return i};return r(e)}var hp=class{toArtifact(t){let r=this.residualBag(t,Jte),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 $n(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},o=(0,tc.deserializeWorkflowJson)(i);return this.toArtifact(o)}needsBaseLanguage(t){return P1(t.rootCondition)}toApiPayload(t,r,n){var i,o;let a=this.fromArtifact(t);a.wfomRoot&&(a.wfomRoot={...a.wfomRoot,name:t.name,title:t.name,primaryEntityName:t.entityLogicalName||a.wfomRoot.primaryEntityName},a.entityLogicalName=a.wfomRoot.primaryEntityName);let s=(0,tc.serializeToWorkflowJson)(a,(i=n?.baseLanguageCode)!==null&&i!==void 0?i:Vte.DEFAULT_LCID),l=(o=a.ruleId)!==null&&o!==void 0?o:(0,N1.newId)();return{Entity:this.buildWorkflowEntity(a,l),WfomJson:s,status:t.status}}createDefault(t){var r,n,i,o,a,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:(o=t.entityLogicalName)!==null&&o!==void 0?o:"",scope:(a=t.scope)!==null&&a!==void 0?a:"Entity",status:(s=t.status)!==null&&s!==void 0?s:"Draft",rootCondition:t.rootCondition===void 0?(0,tc.createEmptyCondition)():t.rootCondition===null?null:this.conditionFromJson(Wte(jte(t.rootCondition)))},u=this.toArtifact(l);return u.id||(u.id=(0,N1.newId)()),u}assignMissingIds(t){return(0,qte.assignMissingIds)(t)}validate(t){let r=[],n=t.rootCondition;return n==null?r:(0,oi.isJsonObject)(n)?($1(n,"/rootCondition",r),r):(r.push((0,oi.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(a){return[(0,oi.issue)("/rootCondition","rule-not-representable",a instanceof Error?a.message:String(a))]}let i=n.rootCondition===null?null:ore(n.rootCondition),o;return r.length===0?o=rre:r.some(a=>a.requiredLevel!==void 0)?o=nre:o=new Set([ire]),(0,tc.validateBusinessRule)(i,r).filter(a=>!o.has(a.kind)).map(a=>(0,oi.issue)(`/rootCondition (${a.nodeId})`,`business-rule-${a.kind}`,a.message))}issuesBlockingPush(t,r=[],n){return this.semanticIssues(t,r)}columnsCheckedAtPush(t){let r;try{r=this.fromArtifact(t)}catch{return[]}let n=new Set,i=a=>{a&&n.add(a)},o=a=>{var s;for(let l of a.clauses)i(l.field),i(l.valueField);for(let l of[...a.trueBranch,...a.falseBranch]){if(l.kind==="condition"){o(l);continue}if(i(l.field),l.type==="SetFieldValue"||l.type==="SetDefaultValue")i(l.valueField);else if(l.type==="Recommendation")for(let u of(s=l.applyActions)!==null&&s!==void 0?s:[])i(u.field),i(u.valueField)}};return r.rootCondition&&o(r.rootCondition),[...n]}residualBag(t,r){return L1(t,r)}buildWorkflowEntity(t,r){return(0,tc.buildWorkflowEntity)(t,r)}conditionToJson(t){let r=this.residualBag(t,Yte),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,Qte),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,Xte[t.type]),n={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...ne("stepName",t.stepName),...ne("stepLabels",t.stepLabels),...ne("bag",r)};switch(t.type){case"Recommendation":return{...n,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(tre),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)};case"LockUnlock":return{...n,type:"LockUnlock",lock:t.lock};case"ShowErrorMessage":return{...n,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)};case"SetFieldValue":return{...n,type:"SetFieldValue",...I1(t)};case"SetDefaultValue":return{...n,type:"SetDefaultValue",...I1(t)};case"SetBusinessRequired":return{...n,type:"SetBusinessRequired",required:t.required};case"SetVisibility":return{...n,type:"SetVisibility",visible:t.visible};default:return O1(t)}}conditionFromJson(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:{};return $n(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 $n(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,...ne("value",t.value),...ne("valueField",t.valueField),...ne("lookupValue",k1(t.lookupValue)),...ne("expression",t.expression),...ne("rawExpression",t.rawExpression),...ne("valueWorkflowType",t.valueWorkflowType)})}branchItemFromJson(t){return this.isConditionJson(t)?this.conditionFromJson(t):this.actionFromJson(t)}actionFromJson(t){if(!Kte.has(t.type))throw new Error(`Unsupported business-rule action type: ${t.type}`);sre(t);let r={kind:"action",id:t.id,displayName:t.displayName,field:t.field,...ne("stepName",t.stepName),...ne("stepLabels",t.stepLabels)};switch(t.type){case"Recommendation":return $n(t.bag,{...r,type:"Recommendation",recommendationTitle:t.recommendationTitle,messageText:t.messageText,...ne("acceptanceText",t.acceptanceText),applyActions:t.applyActions.map(ere),...ne("recommendationActionStepMeta",t.recommendationActionStepMeta)});case"LockUnlock":return $n(t.bag,{...r,type:"LockUnlock",lock:t.lock});case"ShowErrorMessage":return $n(t.bag,{...r,type:"ShowErrorMessage",errorMessage:t.errorMessage,...ne("messageLevel",t.messageLevel),...ne("messageActionSteps",t.messageActionSteps)});case"SetFieldValue":return $n(t.bag,{...r,type:"SetFieldValue",...Vb(t)});case"SetDefaultValue":return $n(t.bag,{...r,type:"SetDefaultValue",...Vb(t)});case"SetBusinessRequired":return $n(t.bag,{...r,type:"SetBusinessRequired",required:t.required});case"SetVisibility":return $n(t.bag,{...r,type:"SetVisibility",visible:t.visible});default:return O1(t)}}isConditionJson(t){return Object.prototype.hasOwnProperty.call(t,"clauses")&&Object.prototype.hasOwnProperty.call(t,"logic")&&!Object.prototype.hasOwnProperty.call(t,"type")}};Do.BusinessRuleAdapter=hp;function $1(e,t,r){(0,oi.optionalEnum)(e,"logic",["AND","OR"],t,"condition-logic-invalid",r),(0,oi.childObjects)(e,"clauses",t,"clause",r);for(let n of["trueBranch","falseBranch"])(0,oi.childObjects)(e,n,t,"branchItem",r).forEach(({node:o,index:a})=>{"clauses"in o||"trueBranch"in o||"falseBranch"in o?$1(o,`${t}/${n}/${a}`,r):are(o,`${t}/${n}/${a}`,r)})}function are(e,t,r){e.type==="SetDefaultValue"&&e.valueType==="Clear"&&r.push((0,oi.issue)(`${t}/valueType`,"clear-only-set-field-value","Clear is only supported for SetFieldValue actions."))}function sre(e){if(e.type==="SetDefaultValue"&&e.valueType==="Clear")throw new Error("Clear is only supported for SetFieldValue actions.")}function lre(){return{adapter:new hp,api:Bte.businessRuleApi,publish:(e,t,r)=>(0,_1.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,_1.boundEntityPublishScope)(t)}}Do.businessRuleRegistration=lre});var e$=v(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});Io.appRegistration=Io.AppAdapter=Io.HEADER_NAV_BOOLEAN_RULE=void 0;var qi=rn(),Ot=so(),ic=uo(),ure=Qr(),j1=zd(),Gb=Fd(),Wb=lo(),cre=pt(),dre=le(),H1=Jo(),K1=Q(),J1=Ud();Object.defineProperty(Io,"HEADER_NAV_BOOLEAN_RULE",{enumerable:!0,get:function(){return J1.HEADER_NAV_BOOLEAN_RULE}});var vp="7.0.0.0",F1=`<SiteMap IntroducedVersion="${vp}"></SiteMap>`,M1="/_imgs/imagestrips/transparent_spacer.gif",U1="/_imgs/TableIconsFluentV9/document_one_page_sparkle.svg",Y1=["Entity","Url","DefaultDashboard","Page","GenPageId"],rc="sitemapId",B1="sitemapName",zb="sitemapNameUnique",q1="aiDescription",V1="[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}",fre=new RegExp(`^(?:\\{${V1}\\}|${V1})$`);function G1(e,t){if(!fre.test(e.trim()))throw new K1.ValidationError("app",t,[{pointer:"/sitemapId",rule:"app-sitemapid-guid",message:`sitemapId must be a GUID; received '${e}'.`}]);return e.trim()}function W1(e,t,r){if(e===void 0)return r;if(typeof e!="boolean")throw new K1.ValidationError("app",t,[Q1(e)]);return e}function Q1(e){return(0,qi.issue)("/headerAndNavigationRefresh",J1.HEADER_NAV_BOOLEAN_RULE,`headerAndNavigationRefresh must be a boolean, got ${typeof e}`)}function pre(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,dre.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}}function mre(e){var t,r,n,i;let o=[];for(let a of(r=(t=e.siteMap)===null||t===void 0?void 0:t.areas)!==null&&r!==void 0?r:[])for(let s of(n=a.groups)!==null&&n!==void 0?n:[])for(let l of(i=s.subAreas)!==null&&i!==void 0?i:[])l.type==="Entity"&&l.entity&&o.push(l.entity);return o}var wp=class{constructor(t=H1.DEFAULT_LCID){this.lcid=t}toArtifact(t){let{bag:r,modeledEls:n}=gp(t,"Area");return{id:"",name:"",uniqueName:"",description:"",siteMap:{areas:n.map(i=>this.areaToJson(i)),bag:r},bag:(0,Ot.emptyBag)()}}fromArtifact(t){(0,Wb.installDomShim)();let r=this.assignMissingIds(JSON.parse(JSON.stringify(t))),n=new DOMParser().parseFromString("<root/>","text/xml"),i=this.rootToRaw(r);return(0,Ot.rebuildRaw)(i,(0,ic.domEngine)(n),null)}fromApiResponse(t){var r,n,i,o,a,s,l,u,c,d,f;(0,Wb.installDomShim)();let m=t??{},p=(r=m.$sitemap)!==null&&r!==void 0?r:m,h=(0,ic.parseXmlRoot)((n=p.sitemapxml)!==null&&n!==void 0?n:F1,F1),g=this.toArtifact(h);return g.id=(i=m.appmoduleid)!==null&&i!==void 0?i:"",g.name=(o=m.name)!==null&&o!==void 0?o:"",g.uniqueName=(a=m.uniquename)!==null&&a!==void 0?a:"",g.description=(s=m.description)!==null&&s!==void 0?s:"",m.aiappdescription&&(g.aiDescription=m.aiappdescription),g.bag={a:[[rc,(u=(l=p.sitemapid)!==null&&l!==void 0?l:m._sitemapid_value)!==null&&u!==void 0?u:""],[B1,(c=p.sitemapname)!==null&&c!==void 0?c:""],[zb,(d=p.sitemapnameunique)!==null&&d!==void 0?d:""],[q1,(f=m.aiappdescription)!==null&&f!==void 0?f:""]],c:[]},g}toApiPayload(t,r){var n,i,o,a,s,l,u,c,d,f,m,p,h,g,b;(0,Wb.installDomShim)();let w=(0,ic.serializeNode)(this.fromArtifact(t)),C=[],S=[];for(let k of(i=(n=t.siteMap)===null||n===void 0?void 0:n.areas)!==null&&i!==void 0?i:[])for(let I of(o=k.groups)!==null&&o!==void 0?o:[])for(let D of(a=I.subAreas)!==null&&a!==void 0?a:[])D.type==="Entity"&&D.entity?C.push(D.entity):D.type==="DashBoard"&&D.dashboardId&&S.push(D.dashboardId);let O=(s=t.bag)!==null&&s!==void 0?s:(0,Ot.emptyBag)();return{sitemapId:nc(O,rc)||(t.sitemapId?G1(t.sitemapId,t.id):""),sitemapxml:w,sitemapname:nc(O,B1)||t.name,...nc(O,zb)?{sitemapNameUnique:nc(O,zb)}:{},appModuleId:t.id,appModuleName:t.name,appModuleDescription:t.description,...t.aiDescription!==void 0&&t.aiDescription!==(r?r.aiDescription:nc(O,q1))?{appModuleAiDescription:t.aiDescription}:{},appModuleUniqueName:t.uniqueName,...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},...t.headerAndNavigationRefresh===void 0?{}:{appSettings:{[Gb.HEADER_AND_NAVIGATION_REFRESH]:W1(t.headerAndNavigationRefresh,(l=t.id)!==null&&l!==void 0?l:"(unknown)",!0)?Gb.APP_SETTING_ON:Gb.APP_SETTING_OFF}},...typeof t.published=="boolean"?{published:t.published}:{},entities:C,components:{forms:(c=(u=t.components)===null||u===void 0?void 0:u.forms)!==null&&c!==void 0?c:[],views:(f=(d=t.components)===null||d===void 0?void 0:d.views)!==null&&f!==void 0?f:[],charts:(p=(m=t.components)===null||m===void 0?void 0:m.charts)!==null&&p!==void 0?p:[],dashboards:[...(g=(h=t.components)===null||h===void 0?void 0:h.dashboards)!==null&&g!==void 0?g:[],...S],...((b=t.components)===null||b===void 0?void 0:b.mainFormsByTable)!==void 0?{mainFormsByTable:t.components.mainFormsByTable}:{}}}}createDefault(t){var r,n,i,o,a,s;let l=!((r=t.siteMap)===null||r===void 0)&&r.areas&&t.siteMap.areas.length>0?t.siteMap.areas:[{id:"",title:"Area",groups:[{id:"",title:"Group",subAreas:[]}]}],u=(n=t.id)!==null&&n!==void 0?n:(0,cre.newId)();return{id:u,name:(i=t.name)!==null&&i!==void 0?i:"New App",uniqueName:(o=t.uniqueName)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",...t.aiDescription?{aiDescription:t.aiDescription}:{},siteMap:{areas:l},...t.sitemapId?{sitemapId:G1(t.sitemapId,u)}:{},...t.iconWebResourceId?{iconWebResourceId:t.iconWebResourceId}:{},headerAndNavigationRefresh:W1(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(Kb):Array.isArray(r.areas)?r.areas.forEach(Kb):Array.isArray(r.groups)?Kb(r):Array.isArray(r.subAreas)?Z1(r):"type"in r&&Cp(r,"subarea"),t}validate(t){let r=[],n=t.published;n!==void 0&&typeof n!="boolean"&&r.push((0,qi.issue)("/published","published-must-be-boolean",`published must be a boolean, got ${typeof n}`));let i=t.siteMap,o=t.headerAndNavigationRefresh;if(o!==void 0&&typeof o!="boolean"&&r.push(Q1(o)),i==null)return r;if(!(0,qi.isJsonObject)(i))return r.push((0,qi.issue)("/siteMap","sitemap-must-be-object",`siteMap must be a JSON object, got ${typeof i}`)),r;let a=(0,qi.childObjects)(i,"areas","/siteMap","area",r),s=new Map;return a.forEach(({node:l,index:u})=>{let c=`/siteMap/areas/${u}`;(0,qi.childObjects)(l,"groups",c,"group",r).forEach(({node:f,index:m})=>{let p=`${c}/groups/${m}`;(0,qi.childObjects)(f,"subAreas",p,"subArea",r).forEach(({node:g,index:b})=>{let w=`${p}/subAreas/${b}`;(0,qi.optionalEnum)(g,"type",["Entity","URL","DashBoard","CustomPage","GenPage"],w,"subarea-type-invalid",r);let C=pre(g);if(!C)return;let S=s.get(C);if(S===void 0){s.set(C,w);return}r.push((0,qi.issue)(w,"subarea-duplicate-target",`the sitemap already navigates to this target at ${S}; a duplicate SubArea would pin it twice and a single removeElement would leave one behind`))})})}),r}issuesBlockingPush(t){var r;return(0,j1.mainFormSetShapeIssues)((r=t.components)===null||r===void 0?void 0:r.mainFormsByTable,mre(t))}applyServerIdentity(t,r){let n=r[rc];if(!n)return;t.bag||(t.bag=(0,Ot.emptyBag)());let i=t.bag.a.find(o=>o[0]===rc);i?i[1]=n:t.bag.a.push([rc,n])}areaToJson(t){var r;let{bag:n,modeledEls:i}=gp(t,"Group"),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:jb(t,this.lcid),groups:i.map(l=>this.groupToJson(l)),bag:n},a=t.getAttribute("Icon");a&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}groupToJson(t){var r;let{bag:n,modeledEls:i}=gp(t,"SubArea");return{id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",title:jb(t,this.lcid),subAreas:i.map(o=>this.subAreaToJson(o)),bag:n}}subAreaToJson(t){var r;let{bag:n}=gp(t,null),i=hre(t),o={id:(r=t.getAttribute("Id"))!==null&&r!==void 0?r:"",type:i,title:jb(t,this.lcid),bag:n};if(i==="Entity"){let l=t.getAttribute("Entity");l&&(o.entity=l)}else if(i==="DashBoard"){let l=t.getAttribute("DefaultDashboard");l&&(o.dashboardId=l);let u=t.getAttribute("Url");u&&(o.dashboardUrl=u)}else if(i==="CustomPage"){let l=t.getAttribute("Page");l&&(o.page=l)}else if(i==="GenPage"){let l=t.getAttribute("GenPageId");l&&(o.genPageId=l)}else{let l=t.getAttribute("Url");l&&(o.url=l)}let a=t.getAttribute("Icon");a&&a!==M1&&(o.icon=a);let s=t.getAttribute("VectorIcon");return s&&(o.vectorIcon=s),o}rootToRaw(t){var r,n,i,o;let a=(n=(r=t.siteMap)===null||r===void 0?void 0:r.bag)!==null&&n!==void 0?n:(0,Ot.emptyBag)(),l=yp(a)?[["IntroducedVersion",vp]]:[],u=((o=(i=t.siteMap)===null||i===void 0?void 0:i.areas)!==null&&o!==void 0?o:[]).map(c=>this.areaToRaw(c));return{n:"SiteMap",a:(0,Ot.mergeAttrs)(a.a,l),c:(0,Ot.spliceChildren)(a.c,u)}}areaToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,Ot.emptyBag)(),o=yp(i),a=[],s=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ShowGroups","true"],["ResourceId","SitemapDesigner.NewTitle"],["DescriptionResourceId","SitemapDesigner.NewTitle"],["IntroducedVersion",vp]),t.icon!==void 0?a.push(["Icon",t.icon]):bp(i.a,"Icon")&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):bp(i.a,"VectorIcon")&&s.push("VectorIcon");let l=((n=t.groups)!==null&&n!==void 0?n:[]).map(c=>this.groupToRaw(c)),u=Hb((0,Ot.spliceChildren)(i.c,l),t.title,o,this.lcid);return{n:"Area",a:(0,Ot.mergeAttrs)(i.a,a,s),c:u}}groupToRaw(t){var r,n;let i=(r=t.bag)!==null&&r!==void 0?r:(0,Ot.emptyBag)(),o=yp(i),a=[];t.id&&a.push(["Id",t.id]),o&&a.push(["ResourceId","SitemapDesigner.NewGroup"],["DescriptionResourceId","SitemapDesigner.NewGroup"],["ToolTipResourseId","SitemapDesigner.Unknown"],["IntroducedVersion",vp],["IsProfile","false"]);let s=((n=t.subAreas)!==null&&n!==void 0?n:[]).map(u=>this.subAreaToRaw(u)),l=Hb((0,Ot.spliceChildren)(i.c,s),t.title,o,this.lcid);return{n:"Group",a:(0,Ot.mergeAttrs)(i.a,a),c:l}}subAreaToRaw(t){var r;let n=(r=t.bag)!==null&&r!==void 0?r:(0,Ot.emptyBag)(),i=yp(n),o=yre(n.a,t.type),a=[],s=[];t.id&&a.push(["Id",t.id]);let l=!i&&!n.a.some(([c])=>Y1.includes(c));vre(a,t,l),i?(a.push(["ResourceId","SitemapDesigner.NewSubArea"],["Client","All,Outlook,OutlookLaptopClient,OutlookWorkstationClient,Web"],["Sku","All,OnPremise,Live,SPLA"],["AvailableOffline","true"],["PassParams","false"]),t.icon&&a.push(["Icon",t.icon])):t.icon!==void 0?a.push(["Icon",t.icon]):bp(o,"Icon",M1)&&s.push("Icon"),t.vectorIcon!==void 0?a.push(["VectorIcon",t.vectorIcon]):bp(o,"VectorIcon")?t.type==="GenPage"?a.push(["VectorIcon",U1]):s.push("VectorIcon"):t.type==="GenPage"&&!gre(o,"VectorIcon")&&a.push(["VectorIcon",U1]);let u=Hb((0,Ot.spliceChildren)(n.c,[]),t.title,i,this.lcid);return{n:"SubArea",a:(0,Ot.mergeAttrs)(o,a,s),c:u}}};Io.AppAdapter=wp;function gp(e,t){let r=(0,ic.nodeLikeFromDom)(e).getAllProperties().map(s=>[s.key,s.value]),n=[],i=[],o=e.childNodes,a=0;for(let s=0;s<o.length;s+=1){let l=o[s];l.nodeType!==1&&l.nodeType!==3||(l.nodeType===1&&t!==null&&l.tagName===t?i.push(l):n.push({i:a,node:(0,Ot.rawFromNode)((0,ic.nodeLikeFromDom)(l))}),a+=1)}return{bag:{a:r,c:n},modeledEls:i}}function z1(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName===t&&r.push(o)}return r}function jb(e,t){var r;let n=z1(e,"Titles")[0];if(!n)return"";let o=z1(n,"Title").find(a=>a.getAttribute("LCID")===String(t));return o&&(r=o.getAttribute("Title"))!==null&&r!==void 0?r:""}function hre(e){return e.getAttribute("GenPageId")?"GenPage":e.getAttribute("Entity")?"Entity":e.getAttribute("Page")?"CustomPage":e.getAttribute("DefaultDashboard")?"DashBoard":"URL"}function yp(e){return e.a.length===0&&e.c.length===0}function gre(e,t){return e.some(([r])=>r===t)}function bp(e,t,r){let n=e.find(([o])=>o===t),i=n?.[1];return!!i&&i!==r}function nc(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function yre(e,t){let r=bre(t);return e.filter(([n])=>!Y1.includes(n)||r.has(n)).map(n=>[n[0],n[1]])}function bre(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 vre(e,t,r){var n,i,o,a,s;switch(t.type){case"Entity":e.push(["Entity",(n=t.entity)!==null&&n!==void 0?n:""]);break;case"URL":(t.url!==void 0||!r)&&e.push(["Url",(i=t.url)!==null&&i!==void 0?i:""]);break;case"DashBoard":e.push(["DefaultDashboard",(o=t.dashboardId)!==null&&o!==void 0?o:""]),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",(s=t.genPageId)!==null&&s!==void 0?s:""]);break;default:break}}function Hb(e,t,r,n){if(!t)return e;let i=e.findIndex(o=>o.n==="Titles");if(i>=0){let o=e.slice();return o[i]=wre(e[i],t,n),o}return r?[Cre(t,n),...e]:e}function wre(e,t,r){let n=!1,i=e.c.map(o=>!n&&o.n==="Title"&&Ere(o,"LCID")===String(r)?(n=!0,{n:o.n,a:(0,Ot.mergeAttrs)(o.a,[["Title",t]]),c:o.c}):o);return n||i.unshift(X1(t,r)),{n:e.n,a:e.a.map(o=>[o[0],o[1]]),c:i}}function Cre(e,t){return{n:"Titles",a:[],c:[X1(e,t)]}}function X1(e,t){return{n:"Title",a:[["LCID",String(t)],["Title",e]],c:[]}}function Ere(e,t){let r=e.a.find(([n])=>n===t);return r?r[1]:void 0}function Are(e){let t="0123456789abcdef",r="";for(let n=0;n<e;n+=1)r+=t[Math.floor(Math.random()*t.length)];return r}function Cp(e,t){e&&(typeof e.id!="string"||e.id.length===0)&&(e.id=`${t}_${Are(8)}`)}function Kb(e){var t;Cp(e,"area");for(let r of(t=e.groups)!==null&&t!==void 0?t:[])Z1(r)}function Z1(e){var t;Cp(e,"group");for(let r of(t=e.subAreas)!==null&&t!==void 0?t:[])Cp(r,"subarea")}function Sre(e=H1.DEFAULT_LCID){return{adapter:new wp(e),api:j1.appApi,languageSensitive:!0,publish:(t,r)=>(0,ure.publishAppModule)(t,r),publishScope:t=>({envelope:"appmodule",targetIds:[t]}),rebaselineAfterPublish:"bracket"}}Io.appRegistration=Sre});var t$={};Jr(t$,{ActionType:()=>Yb,AppActionOrigin:()=>iv,AppActionVisibilityType:()=>nv,ButtonType:()=>Xb,CannotUpdateAppActionColumns:()=>Nre,Context:()=>ev,IconType:()=>Qb,Location:()=>Zb,OnClickEventType:()=>rv,Scope:()=>tv,VisibilityType:()=>Jb});var Jb,Yb,Qb,Xb,Zb,ev,tv,rv,nv,iv,Nre,r$=L(()=>{"use strict";(function(e){e[e.NotSupported=0]="NotSupported",e[e.Show=1]="Show",e[e.ClassicRules=2]="ClassicRules",e[e.Expression=3]="Expression"})(Jb||(Jb={}));(function(e){e[e.NotSupported=0]="NotSupported",e[e.None=1]="None",e[e.JavaScript=2]="JavaScript",e[e.Expression=3]="Expression"})(Yb||(Yb={}));(function(e){e[e.NoIcon=0]="NoIcon",e[e.UseIcon=1]="UseIcon",e[e.UseWebResource=2]="UseWebResource"})(Qb||(Qb={}));(function(e){e[e.Standard=0]="Standard",e[e.Dropdown=1]="Dropdown",e[e.Split=2]="Split",e[e.Group=3]="Group"})(Xb||(Xb={}));(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"})(Zb||(Zb={}));(function(e){e[e.All=0]="All",e[e.Entity=1]="Entity"})(ev||(ev={}));(function(e){e[e.App=0]="App",e[e.Entity=1]="Entity",e[e.Global=2]="Global"})(tv||(tv={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.JavaScript=2]="JavaScript"})(rv||(rv={}));(function(e){e[e.None=0]="None",e[e.Formula=1]="Formula",e[e.ClassicRules=2]="ClassicRules"})(nv||(nv={}));(function(e){e[e.Default=0]="Default",e[e.Migrated=1]="Migrated",e[e.MigratedClone=2]="MigratedClone"})(iv||(iv={}));Nre=["appactionid","appmoduleid","context","contextvalue","location","name","type","uniquename","isdisabled","origin"]});var u$=v(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.assertOneWritePerRow=Pt.commandApi=Pt.COMMAND_DUPLICATE_ROW_CODE=Pt.COMMAND_ROW_NOT_IN_BAR_CODE=Pt.COMMAND_TABLE_MISMATCH_CODE=void 0;var ov=Lt(),Lr=ye(),Vi=Q(),$r=le();Pt.COMMAND_TABLE_MISMATCH_CODE="COMMAND_TABLE_MISMATCH";Pt.COMMAND_ROW_NOT_IN_BAR_CODE="COMMAND_ROW_NOT_IN_BAR";Pt.COMMAND_DUPLICATE_ROW_CODE="COMMAND_DUPLICATE_ROW";var _re="OnClickEventJavaScriptWebResourceId($select=name,webresourceid),IconWebResourceId($select=name,webresourceid)";async function av(e,t){let r=`/EntityDefinitions(LogicalName='${(0,$r.odataPathLiteral)(t)}')${(0,$r.odataQuery)([["$select","MetadataId"]])}`,i=(0,Lr.ensureSuccess)(await e.get(r),e.apiUrl(r)).body,o=i?.MetadataId;return o?(0,$r.normalizeGuid)(o,"entityMetadataId"):""}function sv(e,t){return t?`_contextentity_value eq ${t}`:`contextvalue eq '${(0,$r.odataLiteral)(e)}'`}function oc(e){return`Nothing was written. Re-fetch the command with fetchArtifact('command', '${e}', { overwrite: true }) \u2014 this discards local edits \u2014 and re-apply the change.`}function n$(e,t){let r=e.entityLogicalName;if(t===void 0)return r;if(typeof r!="string"||r.toLowerCase()!==t.toLowerCase())throw new Vi.SdkError(Pt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': its JSON names table '${String(r)}'. A command's id is its table, so the push would write another table's command bar. Nothing was written. Fix its entityLogicalName, or push it under that table's id.`);return t}async function i$(e,t,r){let n=await av(e,t);if(r){let i=(0,$r.normalizeGuid)(r,"entityMetadataId");if(i!==n)throw new Vi.SdkError(Pt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': it was fetched for table id ${i}, but table '${t}' is ${n||"not resolvable"} on the server \u2014 the table was re-created, or the local copy edited. `+oc(t))}return n}Pt.commandApi={async get(e,t){let r=t,n=await av(e,r),i=sv(r,n),o=`/appactions${(0,$r.odataQuery)([["$expand",_re],["$filter",i]])}`,a,s=await(0,ov.collectPages)(e,o,"fetchArtifact('command')",c=>{a=c}),l={entityLogicalName:r,entityMetadataId:n,appActions:s},u={};for(let c of s){let d=typeof c.appactionid=="string"?c.appactionid:void 0;if(d){let f=c["@odata.etag"];u[(0,$r.normalizeGuid)(d,"appactionid")]=typeof f=="string"?f:null}}return{raw:l,etag:a?(0,Lr.readEtag)(a):null,memberEtags:u}},async list(e,t){let r=t?.entityLogicalName;return r?[{type:"command",id:r,name:`${r} commands`,entityLogicalName:r,isDirty:!1}]:[]},async create(e,t,r){let n=t,i=n$(n,r),o=await i$(e,i,n.entityMetadataId);return o$(e,i,{...n,entityMetadataId:o},!1)},async update(e,t,r,n,i){let o=r,a=n$(o,t),s=await i$(e,a,o.entityMetadataId);return o$(e,a,{...o,entityMetadataId:s},!0,i)},async delete(e,t){let r=await av(e,t),n=`/appactions${(0,$r.odataQuery)([["$select","appactionid"],["$filter",sv(t,r)]])}`,i=await(0,ov.collectPages)(e,n,"deleteArtifact('command')");for(let o of i)o.appactionid&&await(0,Lr.deleteRecord)(e,"appactions",o.appactionid)}};async function o$(e,t,r,n,i){let o=r.entityMetadataId?(0,$r.normalizeGuid)(r.entityMetadataId,"entityMetadataId"):"",a=await Dre(e,t,r,o,n,i),s={};try{await Ore(e,a,o,s)}catch(l){throw(0,Vi.withPartialTokens)(l,{memberEtags:s})}return{id:r.entityLogicalName,etag:null,memberEtags:s}}function lv(e){return e.replace(/[{}]/g,"").toLowerCase()}function l$(e,t){var r;let n=new Map,i=[...t.rows.map(o=>[o.appactionid,"written"]),...((r=t.deletedRowIds)!==null&&r!==void 0?r:[]).map(o=>[o,"deleted"])];for(let[o,a]of i){let s=lv(o),l=n.get(s);if(l===void 0){n.set(s,a);continue}throw new Vi.SdkError(Pt.COMMAND_DUPLICATE_ROW_CODE,l===a?`Refusing to push command '${e}': app action '${s}' appears twice in it \u2014 two of its controls or groups carry that id, as one copied together with its id or bag does \u2014 so one would silently replace or remove the other. Nothing was written. Remove the id and the bag from the copy, so it is created as a new one, and push again.`:`Refusing to push command '${e}': app action '${s}' would be both written and deleted \u2014 one of its controls or groups spells that id differently (case or braces) than the copy last fetched or pushed \u2014 so the delete would remove what the write saved. Nothing was written. Spell the id as it was, and push again.`)}}Pt.assertOneWritePerRow=l$;var Tre={entities:/^\/entities\(([^()]+)\)$/,appactions:/^\/appactions\(([^()]+)\)$/};function a$(e,t){let r=Tre[t].exec(e);return r?lv(r[1]):void 0}async function Dre(e,t,r,n,i,o){var a,s;l$(t,r);let l=Pre(r.rows),u=new Set(l.map(f=>lv(f.appactionid))),c={writes:[],deletes:[]};for(let f of l){let m=f.body["[email protected]"];if(m!==void 0&&!(typeof m=="string"&&n!==""&&a$(m,"entities")===n))throw new Vi.SdkError(Pt.COMMAND_TABLE_MISMATCH_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' binds to ${typeof m=="string"?`'${m}'`:String(m)}, not to table '${t}' (${n?`/entities(${n})`:"whose id is not resolvable"}). `+oc(t));let p=f.body["[email protected]"];if(typeof p=="string"){let h=a$(p,"appactions");if(h===void 0||!u.has(h))throw new Vi.SdkError(Pt.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': app action '${f.appactionid}' would be placed under '${p}', which is not a row of this command. `+oc(t))}if(i&&f.exists){let h=(0,$r.normalizeGuid)(f.appactionid,"id"),g=(a=o?.[h])!==null&&a!==void 0?a:f.etag;if(!(0,Lr.isVersionToken)(g))throw s$(t,h,"update",g);c.writes.push({kind:"patch",row:f,id:h,token:g})}else{if(m===void 0&&!n)throw new Vi.SdkError("COMMAND_CONTEXT_ENTITY_UNRESOLVED",`Cannot create app action '${f.appactionid}' for entity '${r.entityLogicalName}': the entity MetadataId could not be resolved, so the required ContextEntity bind cannot be set. A row written without it is created but is permanently unreadable \u2014 commandApi.get filters on _contextentity_value. Verify the entity logical name exists and is readable, then retry.`);c.writes.push({kind:"post",row:f})}}for(let f of(s=r.deletedRowIds)!==null&&s!==void 0?s:[]){let m=(0,$r.normalizeGuid)(f,"id"),p=o?.[m];if(!(0,Lr.isVersionToken)(p))throw s$(t,m,"delete",p);c.deletes.push({id:m,token:p})}let d=[...c.writes.flatMap(f=>f.kind==="patch"?[{id:f.id,verb:"update"}]:[]),...c.deletes.map(f=>({id:f.id,verb:"delete"}))];if(d.length>0){let f=await Ire(e,t,n),m=d.find(p=>!f.has(p.id));if(m)throw new Vi.SdkError(Pt.COMMAND_ROW_NOT_IN_BAR_CODE,`Refusing to push command '${t}': it would ${m.verb} app action '${m.id}', which is not in table '${t}''s command bar on the server \u2014 a row of another table, or one deleted since the fetch. `+oc(t))}return c}function s$(e,t,r,n){return new Vi.SdkError(Lr.UPDATE_NO_ETAG_CODE,`Refusing to push command '${e}': ${typeof n=="string"&&n!==""?`the token held for app action '${t}' ('${n}') is not a version`:`no token is held for app action '${t}'`}, so its ${r} could not be made conditional and would overwrite or remove a concurrent edit. `+oc(e))}async function Ire(e,t,r){let n=`/appactions${(0,$r.odataQuery)([["$select","appactionid"],["$filter",sv(t,r)]])}`,i=await(0,ov.collectPages)(e,n,"pushArtifact('command') bar membership"),o=new Set;for(let a of i)typeof a.appactionid=="string"&&o.add((0,$r.normalizeGuid)(a.appactionid,"appactionid"));return o}async function Ore(e,t,r,n){for(let i of t.writes)if(i.kind==="patch"){let o=(0,Lr.echoWrite)("appactionid",{"If-Match":i.token}),a=`/appactions(${i.id})${o.query}`,s=(0,Lr.ensureSuccess)(await e.patch(a,i.row.body,o.options),e.apiUrl(a));n[i.id]=(0,Lr.readEtag)(s)}else{let o=(0,Lr.echoWrite)("appactionid"),a=`/appactions${o.query}`,s={...i.row.body};s["[email protected]"]===void 0&&(s["[email protected]"]=`/entities(${r})`);let l=(0,Lr.ensureSuccess)(await e.post(a,s,o.options),e.apiUrl(a)),u=(0,Lr.readCreatedId)(l,"appactionid");u&&(n[(0,$r.normalizeGuid)(u,"appactionid")]=(0,Lr.readEtag)(l))}for(let{id:i,token:o}of[...t.deletes].reverse())await(0,Lr.deleteRecord)(e,"appactions",i,o),delete n[i]}function Pre(e){let t=new Map(e.map(o=>[o.appactionid,o])),r=new Set,n=[],i=o=>{if(r.has(o.appactionid))return;let a=o.body["[email protected]"];if(typeof a=="string"){let s=/\(([^)]+)\)/.exec(a),l=s?t.get(s[1]):void 0;l&&i(l)}r.add(o.appactionid),n.push(o)};return e.forEach(i),n}});var N$=v(il=>{"use strict";Object.defineProperty(il,"__esModule",{value:!0});il.commandRegistration=il.CommandAdapter=void 0;var ct=(r$(),Br(t$)),c$=Qr(),wt=rn(),p$=u$(),m$=pt(),ol=le(),h$=Q(),dv="$ClientSvg:",fv=".svg",Rre=2,kre=1,Lre=1,g$="entityMetadataId",$re=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"]),Ep=class{toArtifact(t){var r,n,i,o,a,s,l;let u=(r=t.appActions)!==null&&r!==void 0?r:[],c=(n=t.entityLogicalName)!==null&&n!==void 0?n:"",d=u.find(h=>typeof h.appactionid!="string"||h.appactionid==="");if(d)throw new h$.InvalidArgumentError(`Cannot read the command bar of '${c}': app action row '${String((i=d.name)!==null&&i!==void 0?i:"")}' has no appactionid (its primary key), so it cannot be placed in the bar or written back.`);let f=new Map;for(let h of u){let g=typeof h._parentappactionid_value=="string"&&h._parentappactionid_value?h._parentappactionid_value:"",b=(o=f.get(g))!==null&&o!==void 0?o:[];b.push(h),f.set(g,b)}let m=new Map;for(let h of(a=f.get(""))!==null&&a!==void 0?a:[]){let g=Bre(h.location),b=(s=m.get(g))!==null&&s!==void 0?s:[];b.push(h),m.set(g,b)}let p=[];for(let[h,g]of m)p.push({location:h,groups:Fre(g,f,w$(h),c)});return{id:c,entityLogicalName:c,commandBars:Ure(p),bag:{a:[[g$,(l=t.entityMetadataId)!==null&&l!==void 0?l:""]]}}}fromArtifact(t){return{entityLogicalName:t.entityLogicalName,entityMetadataId:mv(t),appActions:uv(t).map(r=>r.row)}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t,r){let n=new Set(r?uv(r).map(l=>l.appactionid):[]),i=uv(t,new Set([...n].map(l=>l.toLowerCase()))),o=new Set(i.map(l=>l.appactionid)),a=i.map(l=>{let u=l.exists||n.has(l.appactionid);return{appactionid:l.appactionid,exists:u,etag:l.etag,body:u?Zre(l.row):S$(l.row)}}),s=[...n].filter(l=>!o.has(l));return(0,p$.assertOneWritePerRow)(t.entityLogicalName,{rows:a,deletedRowIds:s}),{entityLogicalName:t.entityLogicalName,entityMetadataId:mv(t),rows:a,...s.length>0?{deletedRowIds:s}:{}}}createDefault(t){var r,n,i,o;let a=(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:a,entityLogicalName:a,commandBars:(o=t.commandBars)!==null&&o!==void 0?o:[]}}assignMissingIds(t){return(0,m$.assignMissingIds)(t)}normalize(t){let r=Wre(t),n=!1,i=(Array.isArray(t.commandBars)?t.commandBars:[]).map(o=>{let a=(0,wt.isJsonObject)(o)&&Array.isArray(o.groups)?o.groups:void 0;if(!a)return o;let s=!1,l=a.map(u=>{let c=(0,wt.isJsonObject)(u)&&Array.isArray(u.controls)?u.controls:void 0;if(!c)return u;let d=c.map(f=>E$(f,r));return d.every((f,m)=>f===c[m])?u:(s=!0,{...u,controls:d})});return s?(n=!0,{...o,groups:l}):o});return n?{...t,commandBars:i}:t}validate(t){let r=[];return(0,wt.childObjects)(t,"commandBars","","commandBar",r).forEach(({node:i,index:o})=>{let a=`/commandBars/${o}`;(0,wt.optionalEnum)(i,"location",["MainTab","ContextualTab","HomeTab"],a,"bar-location-invalid",r),(0,wt.childObjects)(i,"groups",a,"group",r).forEach(({node:l,index:u})=>{let c=`${a}/groups/${u}`;Np(l.bag)||((0,wt.optionalGuidId)(l,"id",c,"group-id-invalid",r),typeof l.title=="string"&&l.title.length>0&&r.push({pointer:`${c}/title`,rule:"group-toplevel-title-unsupported",message:"a new top-level command group cannot have a title: Dataverse rejects a Group row with no parent (0x80040265). Leave the title empty to hold the commands without creating a group row, or nest them under a FlyoutAnchor control, which supplies the parent a group needs."})),y$((0,wt.childObjects)(l,"controls",c,"control",r),`${c}/controls`,r)})}),r}};il.CommandAdapter=Ep;function Np(e){let t=e?.a;return Array.isArray(t)&&t.length>0}function y$(e,t,r){e.forEach(({node:n,index:i})=>{let o=`${t}/${i}`;Np(n.bag)||(0,wt.optionalGuidId)(n,"id",o,"control-id-invalid",r),(0,wt.optionalEnum)(n,"type",["Button","FlyoutAnchor","SplitButton"],o,"control-type-invalid",r);let a=n.location;a!==void 0&&(typeof a!="number"||!Number.isInteger(a)||a<0||a>6)&&r.push((0,wt.issue)(`${o}/location`,"control-location-invalid",`location must be an integer 0-6 when present, got ${JSON.stringify(a)}`)),n.action!==void 0&&n.action!==null&&((0,wt.isJsonObject)(n.action)?(0,wt.optionalEnum)(n.action,"type",["javascript"],`${o}/action`,"action-type-invalid",r):r.push((0,wt.issue)(`${o}/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",o,"control",r);s.length>0&&y$(s,`${o}/children`,r)})}function pv(e){return{a:Object.entries(e)}}function xre(e){return Object.fromEntries(e.a)}function ac(e,t){if(e){for(let[r,n]of e.a)if(r===t)return n}}function mv(e){let t=ac(e.bag,g$);return typeof t=="string"?t:""}function Fre(e,t,r,n){var i,o;let a=[],s=[];for(let l of Sp(e))l.type===ct.ButtonType.Group?a.push({id:v$(l.name,n),title:typeof l.grouptitle=="string"?l.grouptitle:"",controls:Sp((o=t.get((i=l.appactionid)!==null&&i!==void 0?i:""))!==null&&o!==void 0?o:[]).map(u=>Ap(u,t,r,n)),bag:pv(l)}):s.push(Ap(l,t,r,n));return s.length>0&&a.unshift({id:Xre(n,r),title:"",controls:s}),a}function hv(e){let t=e.bag?ac(e.bag,"appactionid"):void 0;return typeof t=="string"&&t.trim()!==""?t:e.id}function Ap(e,t,r,n){var i,o,a,s,l;let u=v$(e.name,n),c={id:u,type:qre(e.type),label:typeof e.buttonlabeltext=="string"?e.buttonlabeltext:"",command:typeof e.appactionid=="string"?e.appactionid:u,bag:pv(e)},d=b$(e);d&&(c.icon=d);let f=Mre(e);f&&(c.action=f),typeof e.hidden=="boolean"&&(c.hidden=e.hidden),typeof e.isdisabled=="boolean"&&(c.disabled=e.isdisabled),typeof e.location=="number"&&e.location!==r&&(c.location=e.location);let m=t.get((i=e.appactionid)!==null&&i!==void 0?i:"");if(m&&m.length>0){let p=[],h=[];for(let g of Sp(m))if(g.type===ct.ButtonType.Group){let b=(o=g.appactionid)!==null&&o!==void 0?o:"",w=pv(g);c.flyoutGroupId===void 0&&(c.flyoutGroupId=(a=g.appactionid)!==null&&a!==void 0?a:void 0,c.flyoutGroupBag=w);let C=[];for(let S of Sp((l=t.get((s=g.appactionid)!==null&&s!==void 0?s:""))!==null&&l!==void 0?l:[])){let O=Ap(S,t,r,n);p.push(O),C.push(hv(O))}h.push({id:b,bag:w,childIds:C})}else p.push(Ap(g,t,r,n));c.children=p,h.length>1&&(c.flyoutGroups=h)}return c}function b$(e){var t;if(!((t=e.IconWebResourceId)===null||t===void 0)&&t.name)return e.IconWebResourceId.name;if(e.fonticon)return e.fonticon.startsWith(dv)?e.fonticon.slice(dv.length)+fv:e.fonticon}function Mre(e){var t;let r=e.onclickeventjavascriptfunctionname;if(typeof r!="string"||!r)return;let n=e.OnClickEventJavaScriptWebResourceId,i=e._onclickeventjavascriptwebresourceid_value,o={type:"javascript",webResourceId:(t=typeof i=="string"?i:n?.webresourceid)!==null&&t!==void 0?t:"",functionName:r};n?.name&&(o.libraryName=n.name);let a=e.onclickeventjavascriptparameters;return typeof a=="string"&&a&&(o.parameters=a),o}function d$(e){return typeof e.sequence=="number"?e.sequence:typeof e.buttonsequencepriority=="number"?e.buttonsequencepriority:0}function Sp(e){return[...e].sort((t,r)=>d$(t)-d$(r))}function Ure(e){let t={MainTab:0,ContextualTab:1,HomeTab:2};return[...e].sort((r,n)=>{var i,o;return((i=t[r.location])!==null&&i!==void 0?i:9)-((o=t[n.location])!==null&&o!==void 0?o:9)})}function v$(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 Bre(e){switch(e){case ct.Location.Form:case ct.Location.QuickForm:return"MainTab";case ct.Location.HomePageGrid:case ct.Location.Dashboard:return"HomeTab";default:return"ContextualTab"}}function w$(e){switch(e){case"MainTab":return ct.Location.Form;case"HomeTab":return ct.Location.HomePageGrid;default:return ct.Location.SubGridStandard}}function qre(e){switch(e){case ct.ButtonType.Dropdown:return"FlyoutAnchor";case ct.ButtonType.Split:return"SplitButton";default:return"Button"}}function Vre(e){switch(e){case"FlyoutAnchor":return ct.ButtonType.Dropdown;case"SplitButton":return ct.ButtonType.Split;default:return ct.ButtonType.Standard}}function Gre(e){var t;return e.bag&&e.bag.a.length>0?!0:((t=e.title)!==null&&t!==void 0?t:"").length>0}function C$(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 uv(e,t=new Set){var r,n,i,o;let a=[],s=mv(e);for(let l of(r=e.commandBars)!==null&&r!==void 0?r:[]){let u=w$(l.location),c=((n=l.groups)!==null&&n!==void 0?n:[]).flatMap(m=>{var p;return(p=m.controls)!==null&&p!==void 0?p:[]}),d=c.length>0&&c.every(m=>!C$(m,t)),f=0;for(let m of(i=l.groups)!==null&&i!==void 0?i:[]){let p;if(Gre(m)){let h=jre(m,u,void 0,e,s);a.push(h),p=h.appactionid}for(let h of(o=m.controls)!==null&&o!==void 0?o:[])A$(h,u,p,e,s,a,d?f:void 0,t),f+=1}}return a}function E$(e,t){if(!(0,wt.isJsonObject)(e))return e;let r=e.children,n=r,i=!1;Array.isArray(r)&&(n=r.map(s=>E$(s,t)),i=n.some((s,l)=>s!==r[l]));let o=!Np(e.bag)&&(typeof e.id!="string"||e.id.trim()==="");if(!o&&!i)return e;let a;if(o){do a=(0,m$.newId)();while(t.has(a));t.add(a)}return{...e,...a!==void 0?{id:a}:{},...i?{children:n}:{}}}function Wre(e){let t=new Set,r=(o,...a)=>{if((0,wt.isJsonObject)(o))for(let s of[...a.map(l=>o[l]),Np(o.bag)?ac(o.bag,"appactionid"):void 0])typeof s=="string"&&s.trim()!==""&&t.add(s.toLowerCase())},n=o=>{(0,wt.isJsonObject)(o)&&(r(o,"id","flyoutGroupId"),r({bag:o.flyoutGroupBag}),(Array.isArray(o.flyoutGroups)?o.flyoutGroups:[]).forEach(a=>r(a,"id")),(Array.isArray(o.children)?o.children:[]).forEach(n))},i=e.commandBars;return(Array.isArray(i)?i:[]).forEach(o=>{let a=(0,wt.isJsonObject)(o)?o.groups:void 0;(Array.isArray(a)?a:[]).forEach(s=>{r(s,"id");let l=(0,wt.isJsonObject)(s)?s.controls:void 0;(Array.isArray(l)?l:[]).forEach(n)})}),t}function A$(e,t,r,n,i,o,a,s=new Set){var l;let u=zre(e,t,r,n,i,a);o.push(u);let c=(l=e.children)!==null&&l!==void 0?l:[];if(c.length===0&&!(e.flyoutGroups&&e.flyoutGroups.length>0))return;let d=c.every(h=>!C$(h,s)),f=(h,g,b)=>{A$(h,t,g,n,i,o,d?b:void 0,s)},m=e.flyoutGroups;if(m&&m.length>0){let h=new Map(c.map(S=>[hv(S),S])),g=new Set,b=0,w;for(let[S,O]of m.entries()){let k=O.id||(S===0?cv(u.appactionid):yv("flyout-group",`${u.appactionid}#${S}`)),I=f$(k,t,u.appactionid,n,i,O.bag);o.push(I);let D=I.appactionid;w===void 0&&(w=D);for(let P of O.childIds){let x=h.get(P);!x||g.has(P)||(g.add(P),f(x,D,b),b+=1)}}let C=w??cv(u.appactionid);for(let S of c){let O=hv(S);g.has(O)||(g.add(O),f(S,C,b),b+=1)}return}let p=e.flyoutGroupId||cv(u.appactionid);o.push(f$(p,t,u.appactionid,n,i,e.flyoutGroupBag));for(let[h,g]of c.entries())f(g,p,h)}function zre(e,t,r,n,i,o){let a=gv(e,t,r,n,i),s=a.row;o!==void 0&&typeof s.sequence!="number"&&(s.sequence=o);let l=b$(s);return e.location!==void 0&&(s.location=e.location),s.type=Vre(e.type),s.buttonlabeltext=e.label,Kre(s,e.icon,l),Yre(s,e.action),Jre(s),e.hidden!==void 0&&(s.hidden=e.hidden),e.disabled!==void 0&&(s.isdisabled=e.disabled),{...a,row:s}}function jre(e,t,r,n,i){let o=gv(e,t,r,n,i);return o.row.type=ct.ButtonType.Group,o.row.grouptitle=e.title,o}function f$(e,t,r,n,i,o){let a=gv({id:e,bag:o},t,r,n,i),s=a.row;return s["[email protected]"]=`/appactions(${(0,ol.normalizeGuid)(r,"Command flyout group id")})`,s.type=ct.ButtonType.Group,s.grouptitle===void 0&&(s.grouptitle=""),s.isgrouptitlehidden===void 0&&(s.isgrouptitlehidden=!0),a}function gv(e,t,r,n,i){let o,a,s,l;if(e.bag&&e.bag.a.length>0){o=xre(e.bag),a=!0;let u=ac(e.bag,"@odata.etag");s=typeof u=="string"?u:null;let c=ac(e.bag,"appactionid");l=typeof c=="string"&&c?c:e.id}else{if(typeof e.id!="string"||e.id.trim()==="")throw new h$.InvalidArgumentError(`Cannot serialize command '${n.entityLogicalName}': a new control has no id. Its primary key is minted once, before the first push, by normalize() \u2014 serialize the normalized artifact.`);l=e.id,o=Hre(l,t,n,i),a=!1,s=null}return r?o["[email protected]"]=`/appactions(${(0,ol.normalizeGuid)(r,"Command parent appaction id")})`:a&&typeof o._parentappactionid_value=="string"&&o._parentappactionid_value&&o.type!==ct.ButtonType.Group&&(o["[email protected]"]=null),delete o._parentappactionid_value,{appactionid:l,exists:a,etag:s,row:o}}function Hre(e,t,r,n){let i={appactionid:e,name:`${e}!${e.replace(/-/g,"").slice(0,32)}`,uniquename:"",location:t,context:ct.Context.Entity,contextvalue:r.entityLogicalName,scope:ct.Scope.Entity};return n&&(i["[email protected]"]=`/entities(${(0,ol.normalizeGuid)(n,"Command context entity metadata id")})`),i}function Kre(e,t,r){if(t===r){let n=e._iconwebresourceid_value;typeof n=="string"&&n&&!e.fonticon&&(e["[email protected]"]=`/webresourceset(${(0,ol.normalizeGuid)(n,"Command icon web resource id")})`);return}if(t===void 0){e.fonticon="",e.IconWebResourceId=null;return}e.fonticon=t.toLowerCase().endsWith(fv)?dv+t.slice(0,t.length-fv.length):t,e.IconWebResourceId=null}function Jre(e){let t=(n,i)=>{let o=e[n];if(typeof o!="string"||o.length===0||e[`${i}@odata.bind`]!==void 0)return;let a=(0,ol.normalizeGuid)(o,`Command ${i}`);e[`${i}@odata.bind`]=`/canvasapps(${a})`};e.onclickeventtype===kre&&t("_onclickeventformulacomponentlibraryid_value","OnClickEventFormulaComponentLibraryId");let r=e.visibilitytype;(!r||r===Lre)&&t("_visibilityformulacomponentlibraryid_value","VisibilityFormulaComponentLibraryId")}function Yre(e,t){if(!(!t||t.type!=="javascript")){if(e.onclickeventtype=Rre,t.webResourceId){let r=(0,ol.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 Qre(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 yv(e,t){let r="";for(let n=0;n<4;n+=1)r+=Qre(`${n}:${e}:${t}`).toString(16).padStart(8,"0");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20,32)}`}function cv(e){return yv("flyout-group",e)}function Xre(e,t){return yv("loose-group",`${e}|${t}`)}function S$(e){let t={...e};for(let r of $re)delete t[r];return t}function Zre(e){let t=S$(e);for(let r of ct.CannotUpdateAppActionColumns)delete t[r];return t}function ene(){return{adapter:new Ep,api:p$.commandApi,publish:(e,t,r)=>(0,c$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,c$.boundEntityPublishScope)(t)}}il.commandRegistration=ene});var T$=v(_p=>{"use strict";Object.defineProperty(_p,"__esModule",{value:!0});_p.chartApi=void 0;var tne=Lt(),xr=ye(),Sa=le(),_$="savedqueryvisualizationid,name,description,primaryentitytypecode,datadescription,presentationdescription,charttype,type,isdefault",rne="savedqueryvisualizationid,name,primaryentitytypecode,charttype,isdefault";_p.chartApi={async get(e,t){let r=(0,Sa.normalizeGuid)(t,"id"),n=await(0,xr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r),i=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Sa.odataQuery)([["$select",_$]]);return{raw:(0,xr.ensureSuccess)(await e.get(i),e.apiUrl(i)).body,etag:n}},async readContentThenToken(e,t){let r=(0,Sa.normalizeGuid)(t,"id"),n=`/savedqueryvisualizations(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,Sa.odataQuery)([["$select",_$]]),i=(0,xr.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=await(0,xr.readRowEtag)(e,"savedqueryvisualizations","savedqueryvisualizationid",r);return{raw:i.body,etag:o}},async list(e,t){let r=`/savedqueryvisualizations${(0,Sa.odataQuery)([["$select",rne],["$filter",t?.entityLogicalName?`primaryentitytypecode eq '${(0,Sa.odataLiteral)(t.entityLogicalName)}'`:void 0]])}`;return(await(0,tne.collectPages)(e,r,"listArtifacts('chart')")).map(i=>{var o,a;return{type:"chart",id:(o=i.savedqueryvisualizationid)!==null&&o!==void 0?o:"",name:(a=i.name)!==null&&a!==void 0?a:"",entityLogicalName:i.primaryentitytypecode,isDirty:!1}})},async create(e,t,r){let n=t,i=(0,xr.echoWrite)("savedqueryvisualizationid"),o=`/savedqueryvisualizations${i.query}`,a=(0,xr.ensureSuccess)(await e.post(o,(0,xr.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(o));return{id:(0,xr.resolveCreatedId)(a,"savedqueryvisualizationid","chart",r),etag:(0,xr.readEtag)(a)}},async update(e,t,r,n){let i=r,o=(0,Sa.normalizeGuid)(t,"id"),a=(0,xr.echoWrite)("savedqueryvisualizationid",{"If-Match":(0,xr.requireEtag)(n,"chart",o)}),s=`/savedqueryvisualizations(${o})${a.query}`,l=(0,xr.ensureSuccess)(await e.patch(s,{name:i.name,description:i.description,datadescription:i.datadescription,presentationdescription:i.presentationdescription},a.options),e.apiUrl(s));return{id:o,etag:(0,xr.readEtag)(l)}},delete(e,t){return(0,xr.deleteRecord)(e,"savedqueryvisualizations",t)}}});var W$=v(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});sl.chartRegistration=sl.ChartAdapter=void 0;var bv=so(),D$=rn(),ai=uo(),I$=Qr(),nne=T$(),vv=lo(),ine=pt(),one=["Column","StackedColumn","StackedColumn100","Bar","StackedBar","StackedBar100","Area","StackedArea","StackedArea100","Line","Pie","Doughnut","Funnel","Tag"],ane=new Map(one.map(e=>[e.toLowerCase(),e]));function L$(e){var t;return e&&(t=ane.get(e.toLowerCase()))!==null&&t!==void 0?t:"Column"}function sne(){return'<Chart Palette="BrightPastel"><Series><Series ChartType="Column" ChartArea="Default" /></Series><ChartAreas><ChartArea Name="Default" /></ChartAreas><Legends><Legend Name="Default" /></Legends></Chart>'}function lne(e){var t,r;let n=e.entityLogicalName,i=e.series.map((h,g)=>({alias:`agg_${g}`,series:h})),o=e.categories.map((h,g)=>({alias:`grp_${g}`,category:h})),a=h=>`<attribute alias="${h.alias}" name="${al(h.series.attribute)}" aggregate="${al(h.series.aggregate)}" />`,s=h=>`<attribute alias="${h.alias}" name="${al(h.category.attribute)}" groupby="true"${h.category.dateGrouping?` dategrouping="${al(h.category.dateGrouping)}"`:""} />`,l=[],u=new Map,c=(h,g)=>{if(!h){l.push(g);return}let b=u.get(h);b?b.push(g):u.set(h,[g])};i.forEach(h=>c(h.series.relatedEntity,a(h))),o.forEach(h=>c(h.category.relatedEntity,s(h)));let d=[...u.entries()].map(([h,g])=>`<link-entity name="${al(h)}">${g.join("")}</link-entity>`).join(""),f=l.join("")+d,m=i.map(h=>`<measurecollection><measure alias="${h.alias}" /></measurecollection>`).join(""),p=(r=(t=o[0])===null||t===void 0?void 0:t.alias)!==null&&r!==void 0?r:"";return`<datadefinition><fetchcollection><fetch mapping="logical" aggregate="true"><entity name="${al(n)}">${f}</entity></fetch></fetchcollection><categorycollection><category alias="${p}">${m}</category></categorycollection></datadefinition>`}var Tp=class{toArtifact(t){var r,n,i,o,a,s,l;(0,vv.installDomShim)();let u=(r=t.datadescription)!==null&&r!==void 0?r:"",c=(n=t.presentationdescription)!==null&&n!==void 0?n:"",d=(0,ai.parseXmlRoot)(u,"<datadefinition/>"),f=(0,ai.parseXmlRoot)(c,"<Chart/>");return{id:(i=t.savedqueryvisualizationid)!==null&&i!==void 0?i:"",name:(o=t.name)!==null&&o!==void 0?o:"",description:(a=t.description)!==null&&a!==void 0?a:"",entityLogicalName:(s=t.primaryentitytypecode)!==null&&s!==void 0?s:"",chartType:Dp(f),isDefault:(l=t.isdefault)!==null&&l!==void 0?l:!1,series:F$(d),categories:M$(d),presentation:$$(f),dataBag:u?(0,ai.projectElementBag)(d):void 0,presentationBag:c?(0,ai.projectElementBag)(f):void 0,rowBag:une(t.charttype,t.type)}}fromArtifact(t){(0,vv.installDomShim)();let{datadescription:r,presentationdescription:n}=cne(t);return{savedqueryvisualizationid:t.id,name:t.name,description:t.description,primaryentitytypecode:t.entityLogicalName,datadescription:r,presentationdescription:n,charttype:O$(t.rowBag,"charttype"),type:O$(t.rowBag,"type"),isdefault:t.isDefault}}fromApiResponse(t){return this.toArtifact(t??{})}toApiPayload(t){var r,n,i,o,a,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:(o=u.presentationdescription)!==null&&o!==void 0?o:"",primaryentitytypecode:(a=u.primaryentitytypecode)!==null&&a!==void 0?a:"",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,o,a,s,l;(0,vv.installDomShim)();let u=(r=t.entityLogicalName)!==null&&r!==void 0?r:"";return{id:(n=t.id)!==null&&n!==void 0?n:(0,ine.newId)(),name:(i=t.name)!==null&&i!==void 0?i:"New Chart",description:(o=t.description)!==null&&o!==void 0?o:"",entityLogicalName:u,chartType:(a=t.chartType)!==null&&a!==void 0?a:"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,D$.childObjects)(n,"series","","series",r),(0,D$.childObjects)(n,"categories","","category",r),r}};sl.ChartAdapter=Tp;function une(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 O$(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 Dp(e){let t=e.getElementsByTagName("Series");for(let r=0;r<t.length;r+=1)if(t[r].getAttribute("ChartType"))return L$(t[r].getAttribute("ChartType"));return"Column"}function $$(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],o=((t=i?.textContent)!==null&&t!==void 0?t:"").trim();return o&&(r.title=o),r}function Ip(e){return e.getElementsByTagName("fetch")[0]}function x$(e){let t=new Map;if(!e)return t;let r=e.getElementsByTagName("link-entity");for(let n=0;n<r.length;n+=1){let i=r[n],o=i.getAttribute("name");if(!o)continue;let a=i.getElementsByTagName("attribute");for(let s=0;s<a.length;s+=1){let l=a[s],u=l.getAttribute("alias")||l.getAttribute("name");u&&t.set(u,o)}}return t}function F$(e){let t=Ip(e);if(!t)return[];let r=x$(t),n=t.getElementsByTagName("attribute"),i=[];for(let o=0;o<n.length;o+=1){let a=n[o],s=a.getAttribute("aggregate");if(!s)continue;let l=a.getAttribute("name");if(!l)continue;let u={attribute:l,aggregate:s},c=a.getAttribute("charttype");c&&(u.seriesType=L$(c));let d=a.getAttribute("alias");d&&(u.alias=d);let f=d||l,m=r.get(f);m&&(u.relatedEntity=m),i.push(u)}return i}function M$(e){var t;let r=Ip(e);if(!r)return[];let n=x$(r),i=r.getElementsByTagName("attribute"),o=[];for(let a=0;a<i.length;a+=1){let s=i[a];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 f=d||l,m=n.get(f);m&&(u.relatedEntity=m),o.push(u)}return o}function cne(e){var t,r;let n=(t=e.series)!==null&&t!==void 0?t:[],i=(r=e.categories)!==null&&r!==void 0?r:[];if(!P$(e.dataBag)||!P$(e.presentationBag)){let c=lne({...e,series:n,categories:i});return{datadescription:c,presentationdescription:Ine(e,c)}}let o=new DOMParser().parseFromString("<root/>","text/xml"),a=R$(e.dataBag,"datadefinition",o),s=R$(e.presentationBag,"Chart",o),l=e.chartType||Dp(s),u=F$(a);if(!wv(n,u)){let c=Cv(a);dne(o,a,n);let d=Cv(a),f=d.length>0?d:n.map(()=>"");U$(o,s,f,c,l)}return wv(i,M$(a))||fne(o,a,i),e.chartType&&e.chartType!==Dp(s)&&V$(s,e.chartType),e.presentation&&!wv(e.presentation,$$(s))&&G$(s,e.presentation),{datadescription:(0,ai.serializeNode)(a),presentationdescription:(0,ai.serializeNode)(s)}}function P$(e){return!!e&&(e.c.length>0||e.a.length>0)}function U$(e,t,r,n,i){let o,a=t.childNodes;for(let d=0;d<a.length;d+=1)if(a[d].nodeType===1&&a[d].tagName==="Series"){o=a[d];break}o||(o=e.createElement("Series"),t.insertBefore(o,t.firstChild));let s=[],l=o.childNodes;for(let d=0;d<l.length;d+=1)l[d].nodeType===1&&l[d].tagName==="Series"&&s.push(l[d]);let u=new Map;n.forEach((d,f)=>{let m=s[f];if(!m)return;let p=u.get(d);p?p.push(m):u.set(d,[m])});let c=r.map(d=>{let f=u.get(d),m=f&&f.length>0?f.shift():void 0;if(m)return m;let p=e.createElement("Series");p.setAttribute("ChartType",i);let h=s.length>0?s[0].getAttribute("ChartArea"):null;return h&&p.setAttribute("ChartArea",h),p});for(let d of s)o.removeChild(d);for(let d of c)o.appendChild(d)}function Cv(e){let t=[],r=e.getElementsByTagName("measure");for(let n=0;n<r.length;n+=1)t.push(r[n].getAttribute("alias")||"");return t}function R$(e,t,r){let n={n:t,a:(0,bv.mergeAttrs)(e.a,[]),c:(0,bv.spliceChildren)(e.c,[])};return(0,bv.rebuildRaw)(n,(0,ai.domEngine)(r),null)}function dne(e,t,r){let n=Ip(t),i=n?.getElementsByTagName("entity")[0];!n||!i||B$(e,t,i,vne(n),r,Cne,{aliasPrefix:"aggregate_column",addRef:hne,removeRef:bne})}function fne(e,t,r){let n=Ip(t),i=n?.getElementsByTagName("entity")[0];!n||!i||B$(e,t,i,wne(n),r,Ene,{aliasPrefix:"groupby_column",addRef:gne,removeRef:yne})}function B$(e,t,r,n,i,o,a){let s=new Map;for(let m of n){let p=m.getAttribute("alias");p&&s.set(p,m)}let l=new Set,u=[],c=(m,p)=>{var h;let g=Ane(r,m),b=p.relatedEntity;(g??void 0)!==(b??void 0)&&((h=m.parentNode)===null||h===void 0||h.removeChild(m),k$(e,r,m,b))};for(let m of i){let p=m.alias?s.get(m.alias):void 0;p&&!l.has(p)?(o(p,m),c(p,m),l.add(p)):u.push(m)}let d=n.filter(m=>!l.has(m)),f=0;for(let m of u)if(f<d.length){let p=d[f];o(p,m),c(p,m),l.add(p),f+=1}else{let p=e.createElement("attribute"),h=m.alias||mne(t,a.aliasPrefix);p.setAttribute("alias",h),o(p,m),k$(e,r,p,m.relatedEntity),a.addRef(e,t,h)}for(let m of n)if(!l.has(m)){let p=m.getAttribute("alias");p&&a.removeRef(t,p),Nne(m)}}function pne(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 o=n[i].getAttribute("alias");o&&t.add(o)}}return t}function mne(e,t){let r=pne(e);if(!r.has(t))return t;for(let n=2;;n+=1){let i=`${t}_${n}`;if(!r.has(i))return i}}function q$(e,t){let r=t.getElementsByTagName("categorycollection")[0];if(r)return r;let n=e.createElement("categorycollection");return t.appendChild(n),n}function hne(e,t,r){let n=q$(e,t),i=n.getElementsByTagName("category")[0];i||(i=e.createElement("category"),n.appendChild(i));let o=e.createElement("measurecollection"),a=e.createElement("measure");a.setAttribute("alias",r),o.appendChild(a),i.appendChild(o)}function gne(e,t,r){let n=q$(e,t),i=e.createElement("category");i.setAttribute("alias",r),n.appendChild(i)}function yne(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 bne(e,t){var r;let n=e.getElementsByTagName("measure"),i=[];for(let o=0;o<n.length;o+=1)n[o].getAttribute("alias")===t&&i.push(n[o]);for(let o of i){let a=o.parentNode;a?.removeChild(o),a&&a.tagName==="measurecollection"&&!Tne(a)&&((r=a.parentNode)===null||r===void 0||r.removeChild(a))}}function vne(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 wne(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 Cne(e,t){e.setAttribute("name",t.attribute),e.setAttribute("aggregate",t.aggregate),t.seriesType&&e.setAttribute("charttype",t.seriesType)}function Ene(e,t){e.setAttribute("name",t.attribute),e.setAttribute("groupby","true"),t.dateGrouping?e.setAttribute("dategrouping",t.dateGrouping):e.hasAttribute("dategrouping")&&e.removeAttribute("dategrouping")}function Ane(e,t){let r=t.parentNode;for(;r&&r!==e;){let n=r;if(n.nodeType===1&&n.tagName==="link-entity")return n.getAttribute("name")||void 0;r=n.parentNode}}function k$(e,t,r,n){n?Sne(e,t,n).appendChild(r):t.appendChild(r)}function Sne(e,t,r){let n=t.getElementsByTagName("link-entity");for(let o=0;o<n.length;o+=1)if(n[o].getAttribute("name")===r)return n[o];let i=e.createElement("link-entity");return i.setAttribute("name",r),t.appendChild(i),i}function Nne(e){let t=e.parentNode;if(t&&(t.removeChild(e),t.tagName==="link-entity"&&!_ne(t))){let r=t.parentNode;r&&r.removeChild(t)}}function _ne(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 Tne(e){let t=e.childNodes;for(let r=0;r<t.length;r+=1)if(t[r].nodeType===1)return!0;return!1}function V$(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(!Dne(r[i])){r[i].setAttribute("ChartType",t);return}}}function Dne(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 G$(e,t){var r;let n=e.ownerDocument;if(t.palette!==void 0&&e.setAttribute("Palette",t.palette),t.showLegend!==void 0){let i=e.getElementsByTagName("Legend").length>0;if(t.showLegend&&!i){let o=e.getElementsByTagName("Legends")[0];o||(o=n.createElement("Legends"),e.appendChild(o));let a=n.createElement("Legend");a.setAttribute("Name","Default"),o.appendChild(a)}else if(!t.showLegend)for(let o of["Legends","Legend"]){let a=[],s=e.getElementsByTagName(o);for(let l=0;l<s.length;l+=1)a.push(s[l]);for(let l of a)(r=l.parentNode)===null||r===void 0||r.removeChild(l)}}if(t.title!==void 0){let i=e.getElementsByTagName("Title")[0];i&&(i.textContent=t.title)}}function Ine(e,t){let r=(0,ai.parseXmlRoot)(sne(),"<Chart/>"),n=e.chartType||Dp(r);V$(r,n),e.presentation&&G$(r,e.presentation);let i=Cv((0,ai.parseXmlRoot)(t,"<datadefinition/>"));return i.length>0&&U$(r.ownerDocument,r,i,i.slice(0,1),n),(0,ai.serializeNode)(r)}function wv(e,t){return JSON.stringify(e)===JSON.stringify(t)}function al(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function One(){return{adapter:new Tp,api:nne.chartApi,publish:(e,t,r)=>(0,I$.publishBoundEntity)(e,r),publishScope:(e,t)=>(0,I$.boundEntityPublishScope)(t),rebaselineAfterPublish:"bracket"}}sl.chartRegistration=One});var K$=v(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.dashboardApi=Na.dashboardEntity=void 0;var Pne=Lt(),Oo=ye(),ll=le(),Rne=Cg(),z$=ru();function j$(e){return e&&e.toLowerCase()!=="none"?e:void 0}Na.dashboardEntity=j$;var H$="formid,name,description,formxml,type,objecttypecode,istabletenabled,iscustomizable,componentstate,versionnumber",kne={select:H$,required:["name","type","objecttypecode","istabletenabled"]},Lne="formid,name,type,objecttypecode",$ne=0,xne=10;Na.dashboardApi={async get(e,t){let r=(0,ll.normalizeGuid)(t,"id"),n=`/systemforms(${r})/Microsoft.Dynamics.CRM.RetrieveUnpublished()`+(0,ll.odataQuery)([["$select",H$]]),i=(0,Oo.ensureSuccess)(await e.get(n),e.apiUrl(n));return(0,z$.assertSystemFormRecordKind)(i.body,r,"dashboard","fetch"),{raw:i.body,etag:(0,Oo.readEtag)(i)}},async list(e,t){let r=[`(type eq ${$ne} or type eq ${xne})`];t?.entityLogicalName&&r.push(`objecttypecode eq '${(0,ll.odataLiteral)(t.entityLogicalName)}'`);let n=`/systemforms${(0,ll.odataQuery)([["$select",Lne],["$filter",r.join(" and ")]])}`;return(await(0,Pne.collectPages)(e,n,"listArtifacts('dashboard')")).map(o=>{var a,s;let l=j$(o.objecttypecode);return{type:"dashboard",id:(a=o.formid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",...l?{entityLogicalName:l}:{},isDirty:!1}})},async create(e,t,r){let n=t,i=(0,Oo.echoWrite)("formid"),o=`/systemforms${i.query}`,a={name:n.name,description:n.description,formxml:n.formxml,istabletenabled:n.istabletenabled,type:n.type};n.objecttypecode&&(a.objecttypecode=n.objecttypecode);let s=(0,Oo.ensureSuccess)(await e.post(o,(0,Oo.withClientMintedId)(a,"formid",r),i.options),e.apiUrl(o));return{id:(0,Oo.resolveCreatedId)(s,"formid","dashboard",r),etag:(0,Oo.readEtag)(s)}},async update(e,t,r,n){let i=r;return(0,Rne.patchSystemForm)(e,(0,ll.normalizeGuid)(t,"id"),"dashboard",{name:i.name,description:i.description,formxml:i.formxml,istabletenabled:i.istabletenabled},n,kne)},readContentThenToken(e,t){return Na.dashboardApi.get(e,t)},async delete(e,t){let r=(0,ll.normalizeGuid)(t,"id");return await(0,z$.assertSystemFormKind)(e,r,"dashboard"),(0,Oo.deleteRecord)(e,"systemforms",r)}}});var sx=v(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.dashboardRegistration=si.TILE_CLASS_ID=si.DashboardAdapter=void 0;var lc=so(),hn=uo(),Ev=Qr(),sc=rn(),ex=K$(),Av=lo(),_a=pt(),tx=le(),rx=Jo(),Fne=$y(),J$="0",Sv="10",Mne=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"]]),Une="{3FF9A528-DD50-4ACA-8F10-2E5ED73513AD}",Pp=class{constructor(t=rx.DEFAULT_LCID){this.lcid=t}toArtifact(t){var r,n,i,o,a;(0,Av.installDomShim)();let s=(r=t.formxml)!==null&&r!==void 0?r:"",l=(0,hn.parseXmlRoot)(s,"<form/>");return{id:(n=t.formid)!==null&&n!==void 0?n:"",name:(i=t.name)!==null&&i!==void 0?i:"",description:(o=t.description)!==null&&o!==void 0?o:"",dashboardType:Bne(t.type),entityLogicalName:(a=(0,ex.dashboardEntity)(t.objecttypecode))!==null&&a!==void 0?a:null,enabledForMobile:!!t.istabletenabled,layoutType:qne(l),components:Y$(l,this.lcid),bag:(0,hn.projectElementBag)(l)}}fromArtifact(t){var r;return(0,Av.installDomShim)(),{formid:t.id,name:t.name,description:t.description,type:t.dashboardType==="Interactive"?Sv:J$,objecttypecode:(r=t.entityLogicalName)!==null&&r!==void 0?r:"",istabletenabled:t.enabledForMobile,formxml:Q$(t,this.lcid)}}fromApiResponse(t){return this.toArtifact(t??{})}completeAsStored(t,r){return(0,Fne.completeRecordAsStored)(t,r,this.lcid)}toApiPayload(t){return{name:t.name,description:t.description,formxml:Q$(t,this.lcid),istabletenabled:t.enabledForMobile,type:t.dashboardType==="Interactive"?Sv:J$,objecttypecode:t.entityLogicalName}}createDefault(t){var r,n,i,o,a,s,l,u;(0,Av.installDomShim)();let c=(0,hn.parseXmlRoot)(eie(),"<form/>");return{id:(r=t.id)!==null&&r!==void 0?r:(0,_a.newId)(),name:(n=t.name)!==null&&n!==void 0?n:"New Dashboard",description:(i=t.description)!==null&&i!==void 0?i:"",dashboardType:(o=t.dashboardType)!==null&&o!==void 0?o:"Standard",entityLogicalName:(a=t.entityLogicalName)!==null&&a!==void 0?a: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:Y$(c,this.lcid),bag:(0,hn.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,_a.newId)())}return t}validate(t){let r=[],n=(0,sc.childObjects)(t,"components","","component",r),i=new Set;return n.forEach(({node:o,index:a})=>{let s=`/components/${a}`;for(let l of["position","parameters"]){let u=o[l];u!==void 0&&!(0,sc.isJsonObject)(u)&&r.push((0,sc.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,sc.isJsonObject)(o.position)){let l=uc(o.position);i.has(l)?r.push((0,sc.issue)(`${s}/position`,"component-position-collision",`two components occupy the same dashboard position (${l}); move one to a free cell`)):i.add(l)}}),r}};si.DashboardAdapter=Pp;function Bne(e){return String(e??"")===Sv?"Interactive":"Standard"}function qne(e){let t=e?.getAttribute("formLayout")||e?.getAttribute("layoutType"),r=parseInt(t??"",10);return Number.isNaN(r)?0:r}function ae(e,t){let r=[],n=e.childNodes;for(let i=0;i<n.length;i+=1){let o=n[i];o.nodeType===1&&o.tagName.toLowerCase()===t&&r.push(o)}return r}function Y$(e,t){let r=[];return ae(e,"tabs").flatMap(i=>ae(i,"tab")).forEach((i,o)=>{ae(i,"columns").flatMap(s=>ae(s,"column")).forEach((s,l)=>{ae(s,"sections").flatMap(c=>ae(c,"section")).forEach((c,d)=>{Vne(c,{tabIndex:o,columnIndex:l,sectionIndex:d},r,t)})})}),r}function Vne(e,t,r,n){ae(e,"rows").flatMap(o=>ae(o,"row")).forEach((o,a)=>{ae(o,"cell").forEach((s,l)=>{let u=Gne(s,{...t,rowIndex:a,cellIndex:l},n);u&&r.push(u)})})}function Gne(e,t,r){var n,i;let o=ox((n=e.getAttribute("id"))!==null&&n!==void 0?n:"");if(o.toLowerCase().startsWith("spacer"))return null;let a=ae(e,"control")[0];if(!a)return null;let s=(i=a.getAttribute("classid"))!==null&&i!==void 0?i:"",l=jne(a),u=Hne(s,l,a),c=Wne(a);return{id:a.getAttribute("id")||o,type:u,name:ix(e,r),classId:s,position:t,colspan:Rp(e,"colspan",1),rowspan:Rp(e,"rowspan",1),parameters:l,bag:(0,hn.projectElementBag)(e),...c?{icProperties:c}:{}}}function nx(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 Wne(e){let t=nx(e);return t?(0,hn.serializeNode)(t):void 0}function zne(e,t,r){let n=nx(t);if(!r){n&&t.removeChild(n);return}let i=new DOMParser().parseFromString(r,"text/xml").documentElement,o=(0,lc.rebuildRaw)((0,lc.rawFromNode)((0,hn.nodeLikeFromDom)(i)),(0,hn.domEngine)(e),null);n&&(0,hn.serializeNode)(n)===(0,hn.serializeNode)(o)||(n?t.replaceChild(o,n):t.appendChild(o))}function ix(e,t){var r,n;let i=ae(e,"labels")[0];if(!i)return"";let o=ae(i,"label"),a=(r=o.find(s=>s.getAttribute("languagecode")===String(t)))!==null&&r!==void 0?r:o[0];return(n=a?.getAttribute("description"))!==null&&n!==void 0?n:""}function jne(e){var t;let r={},n=ae(e,"parameters")[0];if(!n)return r;let i=n.childNodes;for(let o=0;o<i.length;o+=1){let a=i[o];a.nodeType===1&&(r[a.tagName]=((t=a.textContent)!==null&&t!==void 0?t:"").trim())}return r}function Hne(e,t,r){var n;let i=Mne.get(e.toUpperCase());return i?i==="chart"?t.ChartGridMode==="Chart"?"chart":"list":i==="assistant"?((n=r.getAttribute("uniqueid"))!==null&&n!==void 0?n:"").toUpperCase()===Une?"assistant":t.ChartGridMode!==void 0||r.getAttribute("indicationOfSubgrid")==="true"?t.ChartGridMode==="Chart"?"chart":"list":"unknown":i:"unknown"}function Rp(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 ox(e){return e.replace(/^\{/,"").replace(/\}$/,"")}function Kne(e,t){let r={n:"form",a:(0,lc.mergeAttrs)(e.bag.a,[]),c:(0,lc.spliceChildren)(e.bag.c,[])};return(0,lc.rebuildRaw)(r,(0,hn.domEngine)(t),null)}function Q$(e,t){let r=new DOMParser().parseFromString("<root/>","text/xml"),n=Kne(e,r);return Qne(r,n,e.components,t),Jne(r,n,e.components,t),(0,hn.serializeNode)(n)}function Jne(e,t,r,n){let i=ax(t);for(let o of r)i.has(uc(o.position))||Yne(e,t,o,n)}function Yne(e,t,r,n){var i,o,a,s;let l=(o=(i=r.position)===null||i===void 0?void 0:i.sectionIndex)!==null&&o!==void 0?o:0,u=tie(t,e,l);for(let x of ae(u,"row"))ae(x,"cell").some(K=>ae(K,"control").length>0)||u.removeChild(x);let c=r.classId||si.TILE_CLASS_ID[r.type]||si.TILE_CLASS_ID.iframe,d=r.rowspan&&r.rowspan>0?r.rowspan:4,f=r.bag&&X$(r.bag,"id")?String(X$(r.bag,"id")):Op((0,_a.newId)()),m=r.id?Op(r.id):Op((0,_a.newId)()),p=u.parentNode,h=Math.max(1,parseInt(p&&p.getAttribute&&p.getAttribute("columns")||"1",10)||1),g=Math.min(Math.max(1,r.colspan&&r.colspan>0?r.colspan:1),h),b=ae(u,"row"),w=b[b.length-1],C=w?ae(w,"cell").reduce((x,K)=>x+Rp(K,"colspan",1),0):0;(!w||C+g>h)&&(w=e.createElement("row"),u.appendChild(w));let S=e.createElement("cell");S.setAttribute("id",f),S.setAttribute("colspan",String(g)),S.setAttribute("rowspan",String(d)),S.setAttribute("showlabel","true");let O=e.createElement("labels"),k=e.createElement("label");k.setAttribute("description",(a=r.name)!==null&&a!==void 0?a:""),k.setAttribute("languagecode",String(n)),O.appendChild(k),S.appendChild(O);let I=e.createElement("control");I.setAttribute("id",m),I.setAttribute("classid",Op(c));let D=e.createElement("parameters"),P=(s=r.parameters)!==null&&s!==void 0?s:{};for(let x of Object.keys(P)){let K=(0,tx.createSafeXmlElement)(e,x,"dashboard tile parameter");K.textContent=P[x],D.appendChild(K)}I.appendChild(D),S.appendChild(I),w.appendChild(S)}function X$(e,t){if(!e)return;let r=e.a.find(n=>n[0]===t);return r?r[1]:void 0}function Qne(e,t,r,n){var i;let o=ax(t),a=new Set(r.map(s=>uc(s.position)));for(let s of r){let l=o.get(uc(s.position));if(!l)continue;let u=ae(l,"control")[0];u&&(Xne(e,l,s.name,n),Zne(e,u,s.parameters),Z$(l,"colspan",s.colspan),Z$(l,"rowspan",s.rowspan),s.icProperties!==void 0&&zne(e,u,s.icProperties))}for(let[s,l]of o)a.has(s)||(i=l.parentNode)===null||i===void 0||i.removeChild(l)}function ax(e){let t=new Map;return ae(e,"tabs").flatMap(n=>ae(n,"tab")).forEach((n,i)=>{ae(n,"columns").flatMap(a=>ae(a,"column")).forEach((a,s)=>{ae(a,"sections").flatMap(u=>ae(u,"section")).forEach((u,c)=>{ae(u,"rows").flatMap(f=>ae(f,"row")).forEach((f,m)=>{ae(f,"cell").forEach((p,h)=>{var g;ox((g=p.getAttribute("id"))!==null&&g!==void 0?g:"").toLowerCase().startsWith("spacer")||ae(p,"control")[0]&&t.set(uc({tabIndex:i,columnIndex:s,sectionIndex:c,rowIndex:m,cellIndex:h}),p)})})})})}),t}function uc(e){let t=e??{};return`${t.tabIndex}.${t.columnIndex}.${t.sectionIndex}.${t.rowIndex}.${t.cellIndex}`}function Xne(e,t,r,n){if(r===ix(t,n))return;let i=ae(t,"labels")[0];i||(i=e.createElement("labels"),t.appendChild(i));let o=ae(i,"label").find(a=>a.getAttribute("languagecode")===String(n));o||(o=e.createElement("label"),o.setAttribute("languagecode",String(n)),i.appendChild(o)),o.setAttribute("description",r)}function Zne(e,t,r){var n;if(!r)return;let i=Object.keys(r);if(i.length===0)return;let o=ae(t,"parameters")[0];o||(o=e.createElement("parameters"),t.appendChild(o));let a=new Map,s=o.childNodes;for(let l=0;l<s.length;l+=1){let u=s[l];u.nodeType===1&&a.set(u.tagName,u)}for(let l of i){let u=r[l],c=a.get(l);if(c)((n=c.textContent)!==null&&n!==void 0?n:"")!==u&&(c.textContent=u);else{let d=(0,tx.createSafeXmlElement)(e,l,"dashboard component parameter");d.textContent=u,o.appendChild(d)}}}function Z$(e,t,r){Rp(e,t,1)!==r&&e.setAttribute(t,String(r))}function eie(e=2){let t=`{${(0,_a.newId)()}}`,r=`{${(0,_a.newId)()}}`,n=`{${(0,_a.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>`}si.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 Op(e){return`{${e.replace(/[{}]/g,"")}}`}function tie(e,t,r){var n;let i=ae(e,"tabs").flatMap(u=>ae(u,"tab"))[0];if(!i)throw new Error("addDashboardTile: dashboard formxml has no <tab>");let o=ae(i,"columns").flatMap(u=>ae(u,"column"))[0];if(!o)throw new Error("addDashboardTile: dashboard formxml has no <column>");let a=ae(o,"sections").flatMap(u=>ae(u,"section")),s=(n=a[r])!==null&&n!==void 0?n:a[0];if(!s)throw new Error("addDashboardTile: dashboard formxml has no <section>");let l=ae(s,"rows")[0];return l||(l=t.createElement("rows"),s.appendChild(l)),l}function rie(e=rx.DEFAULT_LCID){return{adapter:new Pp(e),api:ex.dashboardApi,languageSensitive:!0,publish:(t,r,n)=>n?.entityLogicalName?(0,Ev.publishBoundEntity)(t,n):(0,Ev.publishDashboardById)(t,r),publishScope:(t,r)=>r?.entityLogicalName?(0,Ev.boundEntityPublishScope)(r):{envelope:"dashboard",targetIds:[t]},rebaselineAfterPublish:"bracket"}}si.dashboardRegistration=rie});var _v=v(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.readEveryInOrder=Fr.readInOrder=Fr.plainRead=Fr.resolveReadConcurrency=Fr.MAX_READ_CONCURRENCY=void 0;var lx=Q();Fr.MAX_READ_CONCURRENCY=8;function nie(e){if(e===void 0)return 1;if(typeof e!="number"||!Number.isInteger(e)||e<1||e>Fr.MAX_READ_CONCURRENCY)throw new lx.InvalidArgumentError(`readConcurrency must be a whole number from 1 to ${Fr.MAX_READ_CONCURRENCY} (got ${typeof e=="string"?`'${e}'`:String(e)})`);return e}Fr.resolveReadConcurrency=nie;var iie=e=>({ok:!0,value:e}),Nv=e=>({ok:!1,error:e});function oie(e){let t=(async()=>e())().then(iie,Nv);return{outcome:t,finish:async r=>{await r()},discard:async()=>{await t}}}Fr.plainRead=oie;async function ux(e,t,r,n,i){if(!Number.isInteger(t)||t<1)throw new lx.InvalidArgumentError(`a read window holds a whole number of reads, at least 1 (got ${String(t)})`);let o=new Map,a=0,s=Promise.resolve(),l=!1,u=0,c,d=async f=>{if(l)return{refusal:new Error("The read was not started: an earlier read had already failed.")};try{let m=await r(e[f],f),p=m.outcome.catch(Nv);return i==="stop"&&p.then(h=>{l=l||!h.ok}),{read:m,outcome:p}}catch(m){return l=l||i==="stop",{refusal:m}}};try{for(let f=0;f<e.length;f+=1){for(;a<e.length&&a<f+t;){let g=a;a+=1;let b=s.then(()=>d(g));o.set(g,b),s=b}let m=await o.get(f),p="read"in m?await m.outcome:Nv(m.refusal);if(!p.ok&&i==="stop"){c={error:p.error};break}u=f+1,o.delete(f);let h=()=>n(p,e[f],f);"read"in m?await m.read.finish(h):await h()}}finally{l=!0;for(let f=u;f<a;f+=1){let m=await o.get(f);"read"in m&&await m.read.discard().catch(()=>{})}}if(c)throw c.error}function aie(e,t,r,n){return ux(e,t,r,(i,o,a)=>n(i.value,o,a),"stop")}Fr.readInOrder=aie;function sie(e,t,r,n){return ux(e,t,r,n,"continue")}Fr.readEveryInOrder=sie});var _x=v(Lp=>{"use strict";Object.defineProperty(Lp,"__esModule",{value:!0});Lp.genPageApi=void 0;var kp=Lt(),Cx=Kl(),Be=ye(),ve=le(),xn=xd(),Je=Q(),Ex=pt(),cx=_v();function lie(e){if(ArrayBuffer.isView(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}if(Object.prototype.toString.call(e)==="[object ArrayBuffer]")return new Uint8Array(e);let t=globalThis;if(t.Buffer&&t.Buffer.isBuffer(e)){let r=e;return new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}}var li="uxagentprojects",Da="uxagentprojectfiles",fc="agentconversationmessages",pc="uxagentprojectid",Bt="uxagentprojectfileid",Ia="agentconversationmessageid",cc=`${pc},name`,uie=`${Bt},filename,filetype`,Ax=2e8,Sx=200000001,Oa={"MSCRM.IncludeUnpublished":"true"},Tv={};function Ta(e,t){return{"MSCRM.VersioningChangeset":e,...Oa,...t}}async function Ov(e,t,r,n){var i;let o=`/${t}(${r})`+(0,ve.odataQuery)([["$select",n]]),a=(0,Be.ensureSuccess)(await e.get(o,{headers:{...Oa}}),e.apiUrl(o));return{row:(i=a.body)!==null&&i!==void 0?i:{},etag:(0,Be.readEtag)(a)}}async function mc(e,t,r=Oa){let n=`/${Da}(${t})/filecontent/$value`,i=await e.get(n,{headers:{...r}});if(i.status===404)return{status:"unavailable",reason:"missing"};(0,Be.ensureSuccess)(i,e.apiUrl(n));let o=i.body,a=lie(o);if(a)return{status:"available",data:(0,xn.bytesToBase64)(a)};if(typeof o=="string")return{status:"available",data:(0,xn.utf8ToBase64)(o)};throw new Je.SdkError("GENPAGE_CONTENT_UNREADABLE",`Read the content of file '${t}' but the injected HttpClient returned a body this SDK cannot encode (${typeof o}). Return the response as a string, Uint8Array, Buffer, or ArrayBuffer; a byte-returning transport is required to round-trip non-UTF8 assets.`)}function Nx(e){let t=e.lastIndexOf("/");return t>=0?e.slice(t+1):e}async function cie(e,t,r,n,i,o){if(!e.supportsBinaryPatch)throw new Je.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 a=`/${Da}(${t})/filecontent`,s=(0,xn.base64ToBytes)(n);(0,ve.assertNoControlChars)(r,"generative-page file name"),(0,Be.ensureSuccess)(await e.patchRaw(a,s,{headers:Ta(i,{"Content-Type":"application/octet-stream","Content-Length":String(s.byteLength),"x-ms-file-name":Nx(r),...o?{"If-Match":"*"}:{}})}),e.apiUrl(a))}async function dc(e,t,r=Oa){let n=`/${Da}`+(0,ve.odataQuery)([["$select",uie],["$filter",`_${pc}_value eq ${t}`]]);return(await(0,kp.collectPages)(e,n,"fetchArtifact('genPage')",void 0,{headers:{...r}})).map(o=>({row:o,etag:typeof o["@odata.etag"]=="string"?o["@odata.etag"]:null}))}async function Dv(e,t){let r=`/${fc}`+(0,ve.odataQuery)([["$select",`${Ia},message,messagesender,createdon`],["$filter",`_regardingobjectid_value eq ${t}`],["$orderby","createdon asc,versionnumber asc"]]);return(0,kp.collectPages)(e,r,"fetchArtifact('genPage')",void 0,{headers:{...Oa}})}async function dx(e,t){var r,n,i;let{row:o,etag:a}=await Ov(e,li,t,cc),s=new Map;for(let{row:l,etag:u}of await dc(e,t))s.set((0,ve.normalizeGuid)(String((r=l[Bt])!==null&&r!==void 0?r:""),Bt),{filename:String((n=l.filename)!==null&&n!==void 0?n:""),filetype:Number(l.filetype),etag:u});return{name:String((i=o.name)!==null&&i!==void 0?i:""),etag:a,rows:s}}function fx(e,t,r){var n,i,o,a,s;let l=[];r||l.push({kind:"createProject",name:t.name});let u=new Set;for(let c of(n=t.files)!==null&&n!==void 0?n:[]){let d=(0,ve.normalizeGuid)(c.id,"file id");u.add(d);let f=r?.rows.get(d);if(c.content.status==="retain"){if(!r)throw new Je.SdkError("GENPAGE_RETAIN_ON_CREATE",`Refusing to create generative page '${e}': file '${c.name}' asks to keep content the page does not have yet. This is an SDK defect \u2014 the page's rows were not written.`);if(!f)throw new Je.SdkError("GENPAGE_RETAINED_ROW_MISSING",`Refusing to write generative page '${e}': file '${c.name}' was to be kept unchanged but is not on the server. Re-fetch the page and retry.`);continue}f&&c.unchanged||(f?(f.filename!==c.name||f.filetype!==c.fileType)&&l.push({kind:"renameRow",file:c}):l.push({kind:"createRow",file:c}),c.content.status==="available"&&l.push({kind:"content",file:c,data:c.content.data,existing:f!==void 0}))}for(let c of(i=r?.rows.keys())!==null&&i!==void 0?i:[])u.has(c)||l.push({kind:"deleteRow",fileId:c});(!r||l.length>0||r.name!==t.name||((a=(o=t.messages)===null||o===void 0?void 0:o.length)!==null&&a!==void 0?a:0)>0)&&l.push({kind:"patchProject",name:t.name});for(let c of(s=t.messages)!==null&&s!==void 0?s:[])l.push({kind:"message",turn:c});return l}function Pv(e){let t=(0,xn.base64ToUtf8)(e);return(0,xn.utf8ToBase64)(t)===(0,xn.bytesToBase64)((0,xn.base64ToBytes)(e))?t:void 0}function die(e,t,r,n){var i,o,a,s,l,u,c,d;let f=t.sender==="user"?{changeSet:n,dataSources:(o=(i=r.messageContext)===null||i===void 0?void 0:i.dataSources)!==null&&o!==void 0?o:[],model:(s=(a=r.messageContext)===null||a===void 0?void 0:a.model)!==null&&s!==void 0?s:"",enabledTools:(u=(l=r.messageContext)===null||l===void 0?void 0:l.enabledTools)!==null&&u!==void 0?u:[],configurableTools:(d=(c=r.messageContext)===null||c===void 0?void 0:c.configurableTools)!==null&&d!==void 0?d:[]}:{changeSet:n};return{...t.id?{[Ia]:(0,ve.normalizeGuid)(t.id,"message id")}:{},"[email protected]":`/${li}(${e})`,message:t.message,messagecontext:JSON.stringify(f),messagesender:t.sender==="user"?Ax:Sx}}async function fie(e,t,r){var n,i,o,a;let s=((n=r.messages)!==null&&n!==void 0?n:[]).map(f=>f.id).filter(f=>typeof f=="string"&&f!=="").map(f=>(0,ve.normalizeGuid)(f,"message id"));if(s.length===0)return r;let l=`/${fc}`+(0,ve.odataQuery)([["$select",`${Ia},message,messagesender,_regardingobjectid_value`],["$filter",s.map(f=>`${Ia} eq ${f}`).join(" or ")]]),u=await(0,kp.collectPages)(e,l,"pushArtifact('genPage')",void 0,{headers:{...Oa}});if(u.length===0)return r;let c=new Map(u.map(f=>{var m;return[String((m=f[Ia])!==null&&m!==void 0?m:"").toLowerCase(),f]})),d=[];for(let f of(i=r.messages)!==null&&i!==void 0?i:[]){let m=f.id?c.get((0,ve.normalizeGuid)(f.id,"message id")):void 0;if(!m){d.push(f);continue}if(!(String((o=m.message)!==null&&o!==void 0?o:"")===f.message&&Number(m.messagesender)===(f.sender==="user"?Ax:Sx)&&String((a=m._regardingobjectid_value)!==null&&a!==void 0?a:"").toLowerCase()===t))throw new Je.SdkError("GENPAGE_TURN_CONFLICT",`Refusing to push generative page '${t}': its pending turn's identity is already recorded \u2014 as a DIFFERENT ${f.sender} message. An earlier push of this turn did commit (its response was lost), and the turn was changed since. Nothing was written, and the turn is still pending. To record it as a new turn, remove '/newTurn/id' (a new identity is minted on the next push); to keep only what was recorded, remove '/newTurn'.`)}return{...r,messages:d}}function Iv(e,t,r,n){switch(t.kind){case"createProject":return{method:"POST",path:`/${li}`,body:(0,Be.withClientMintedId)({name:t.name},pc,e),headers:Ta(n)};case"createRow":return{method:"POST",path:`/${Da}`,body:(0,Be.withClientMintedId)({filename:t.file.name,filetype:t.file.fileType,[`${pc}@odata.bind`]:`/${li}(${e})`},Bt,(0,ve.normalizeGuid)(t.file.id,"file id")),headers:Ta(n)};case"renameRow":return{method:"PATCH",path:`/${Da}(${(0,ve.normalizeGuid)(t.file.id,"file id")})`,body:{filename:t.file.name,filetype:t.file.fileType},headers:Ta(n,{"If-Match":"*"})};case"content":{let i=Pv(t.data);if(i===void 0)throw new Je.SdkError("GENPAGE_CONTENT_NOT_TEXT",`File '${t.file.name}' is not UTF-8 text and cannot ride in a change set.`);return(0,ve.assertNoControlChars)(t.file.name,"generative-page file name"),{method:"PATCH",path:`/${Da}(${(0,ve.normalizeGuid)(t.file.id,"file id")})/filecontent`,rawBody:i,contentType:"application/octet-stream; charset=utf-8",headers:Ta(n,{"x-ms-file-name":Nx(t.file.name),...t.existing?{"If-Match":"*"}:{}})}}case"deleteRow":return{method:"DELETE",path:`/${Da}(${t.fileId})`,headers:Ta(n,{"If-Match":"*"})};case"patchProject":return{method:"PATCH",path:`/${li}(${e})`,body:{name:t.name},headers:Ta(n,{"If-Match":"*"})};case"message":return{method:"POST",path:`/${fc}`,body:die(e,t.turn,r,n)};default:{let i=t;throw new Je.SdkError("GENPAGE_WRITE_UNKNOWN",`Unknown generative-page write: ${JSON.stringify(i)}`)}}}function px(e,t){return e.supportsAtomicBatch&&t.every(r=>r.kind!=="content"||Pv(r.data)!==void 0)}async function mx(e,t,r,n,i){await(0,Cx.postChangeSet)(e,r.map(o=>Iv(t,o,n,i)),`generative page '${t}' (${r.length} operation(s))`)}async function hx(e,t,r,n,i){var o;let a=[];for(let s of r){if(s.kind==="message"){a.push(s);continue}if(s.kind==="content"){await cie(e,(0,ve.normalizeGuid)(s.file.id,"file id"),s.file.name,s.data,i,s.existing);continue}let l=Iv(t,s,n,i),u={headers:(o=l.headers)!==null&&o!==void 0?o:{}},c=l.method==="POST"?await e.post(l.path,l.body,u):l.method==="PATCH"?await e.patch(l.path,l.body,u):await e.delete(l.path,u);(0,Be.ensureSuccess)(c,e.apiUrl(l.path))}if(a.length===0)return{warnings:[],turnRecorded:!0};try{let s=a.map(l=>Iv(t,l,n,i));if(e.supportsAtomicBatch)await(0,Cx.postChangeSet)(e,s,`the conversation turn of generative page '${t}'`);else for(let l of s)(0,Be.ensureSuccess)(await e.post(l.path,l.body),e.apiUrl(l.path));return{warnings:[],turnRecorded:!0}}catch(s){return{warnings:[`Generative page '${t}' was saved, but its conversation turn could not be recorded (${s instanceof Error?s.message:String(s)}). The turn is kept: the next push of the page records it.`],turnRecorded:!1}}}async function gx(e,t,r,n,i,o,a){var s;let l=u=>({id:t,etag:null,memberEtags:{},warnings:[...a,u]});try{let u=await dx(e,t),c=new Map;for(let C of r)(C.kind==="createRow"||C.kind==="renameRow"||C.kind==="content")&&c.set((0,ve.normalizeGuid)(C.file.id,"file id"),C.file);let d=[];u.name!==n.name&&d.push(`the page is named '${u.name}', not '${n.name}'`);for(let[C,S]of c){let O=u.rows.get(C);O&&(O.filename!==S.name||O.filetype!==S.fileType)&&d.push(`file '${S.name}' is stored as '${O.filename}' (type ${O.filetype})`)}for(let C of r){if(C.kind!=="content")continue;let S=await mc(e,(0,ve.normalizeGuid)(C.file.id,"file id")),O=(0,xn.bytesToBase64)((0,xn.base64ToBytes)(C.data));(S.status!=="available"||S.data!==O)&&d.push(S.status==="available"?`file '${C.file.name}' holds ${(0,xn.base64ToBytes)(S.data).byteLength} byte(s) that differ from the ${(0,xn.base64ToBytes)(O).byteLength} written`:`file '${C.file.name}' holds no content`)}let f=new Set(r.filter(C=>C.kind==="content").map(C=>(0,ve.normalizeGuid)(C.file.id,"file id")));for(let[C,S]of c)!f.has(C)&&(await mc(e,C)).status==="available"&&d.push(`file '${S.name}' holds content this push did not write`);if(d.length>0)return l(`Generative page '${t}' was written, but reading it back does not match what was sent: ${d.join("; ")}. The local baseline is now unusable: re-fetch the page to see what the server holds \u2014 the next push will refuse rather than overwrite blind.`);let m=await dx(e,t),p=[...m.rows.keys()],h=m.etag!==u.etag||m.rows.size!==u.rows.size||p.some(C=>{var S,O;return((S=u.rows.get(C))===null||S===void 0?void 0:S.etag)!==((O=m.rows.get(C))===null||O===void 0?void 0:O.etag)}),g=p.length!==i.size||p.some(C=>!i.has(C)),b={},w=[];for(let[C,S]of m.rows){let O=c.has(C)||!o?S.etag:(s=o.get(C))!==null&&s!==void 0?s:null;b[C]=O,O!==S.etag&&w.push(S.filename)}return h||g||!m.etag||Object.values(b).some(C=>!C)?l(`Generative page '${t}' was written, but its files changed on the server while the write was in progress, so the new concurrency tokens cannot be trusted. The local baseline is now unusable: re-fetch the page before editing it again \u2014 the next push will refuse rather than overwrite blind.`):pie({id:t,etag:m.etag,memberEtags:b},[...a,...w.map(C=>`Generative page '${t}' was written, but its file '${C}' changed on the server while this push ran \u2014 another writer edited it. This push did not touch that file, so the next one refuses until you re-fetch the page and see their change.`)])}catch(u){return l(`The generative page was written, but reading it back failed (${u instanceof Error?u.message:String(u)}). The local baseline is unusable: re-fetch the page before editing it \u2014 the next push will refuse rather than overwrite blind.`)}}async function yx(e,t,r,n=e.readConcurrency){var i;let o=(0,ve.normalizeGuid)(t,"id"),{row:a,etag:s}=await Ov(e,li,o,cc),l=await dc(e,o),u={},c=[];if(n>1)await(0,cx.readInOrder)(l,n,({row:f})=>{var m;let p=(0,ve.normalizeGuid)(String((m=f[Bt])!==null&&m!==void 0?m:""),Bt);return(0,cx.plainRead)(async()=>({fileId:p,content:await mc(e,p)}))},({fileId:f,content:m},{row:p,etag:h})=>{u[f]=h,c.push({...p,content:m})});else for(let{row:f,etag:m}of l){let p=(0,ve.normalizeGuid)(String((i=f[Bt])!==null&&i!==void 0?i:""),Bt);u[p]=m;let h=await mc(e,p);c.push({...f,content:h})}return{raw:r?{project:a,files:c,conversation:await Dv(e,o)}:{project:a,files:c},etag:s,memberEtags:u}}Lp.genPageApi={get(e,t,r){return yx(e,t,!0,r?.fileConcurrency)},getForRebaseline(e,t){return yx(e,t,!1)},async getPublished(e,t){var r,n;let i=(0,ve.normalizeGuid)(t,"id"),o=`/${li}(${i})`+(0,ve.odataQuery)([["$select",cc]]),a=await e.get(o);if(a.status===404)return null;(0,Be.ensureSuccess)(a,e.apiUrl(o));let s=(r=a.body)!==null&&r!==void 0?r:{},l={},u=[],c=await dc(e,i,Tv);for(let{row:g,etag:b}of c){let w=(0,ve.normalizeGuid)(String((n=g[Bt])!==null&&n!==void 0?n:""),Bt);l[w]=b,u.push({...g,content:await mc(e,w,Tv)})}let d=g=>g.map(({row:b,etag:w})=>`${String(b[Bt])}@${String(w)}`).sort().join("|"),f=()=>new Je.SdkError("GENPAGE_PUBLISHED_READ_MOVED",`The published projection of generative page '${i}' changed while it was being read, so what was read is not one published state. PublishXml is asynchronous \u2014 re-read shortly.`),m=await e.get(o);if(m.status===404)throw f();(0,Be.ensureSuccess)(m,e.apiUrl(o));let p=await dc(e,i,Tv);if([(0,Be.readEtag)(a),(0,Be.readEtag)(m),...[...c,...p].map(g=>g.etag)].some(g=>!g))throw new Je.SdkError("GENPAGE_PUBLISHED_READ_UNVERSIONED",`The published projection of generative page '${i}' answered without a version token for the page or one of its rows, so what was read cannot be proven to be one published state.`);if((0,Be.readEtag)(m)!==(0,Be.readEtag)(a)||d(p)!==d(c))throw f();return{raw:{project:s,files:u,conversation:[]},etag:(0,Be.readEtag)(a),memberEtags:l}},async list(e,t){let r=`/${li}`+(0,ve.odataQuery)([["$select",cc]]);return(await(0,kp.collectPages)(e,r,"listArtifacts('genPage')",void 0,{headers:{...Oa}})).map(i=>{var o,a;return{type:"genPage",id:String((o=i[pc])!==null&&o!==void 0?o:""),name:String((a=i.name)!==null&&a!==void 0?a:""),isDirty:!1}})},async create(e,t,r){var n;let i=t,o=r?(0,ve.normalizeGuid)(r,"id"):(0,Ex.newId)(),a=fx(o,i,void 0);wx(e,a),vx(e,o,i);let s=bx(),l=[],u=!0;px(e,a)?await mx(e,o,a,i,s):{warnings:l,turnRecorded:u}=await hx(e,o,a,i,s);let c=new Set(((n=i.files)!==null&&n!==void 0?n:[]).map(f=>(0,ve.normalizeGuid)(f.id,"file id"))),d=await gx(e,o,a,i,c,void 0,l);return u?d:{...d,intentPending:!0}},async update(e,t,r,n,i){var o,a;let s=r,l=(0,ve.normalizeGuid)(t,"id");if(!Array.isArray(s.files))throw new Je.SdkError("GENPAGE_FILES_REQUIRED",`Refusing to update generative page '${l}': its payload has no files list. A page's files are its complete set of rows \u2014 a row the list omits is deleted \u2014 so an omitted list would delete every row of the page. Nothing was written.`);let u=await fie(e,l,s);vx(e,l,u);let c=await dc(e,l),{row:d,etag:f}=await Ov(e,li,l,cc);if(n&&f&&n!==f)throw new Je.SdkError(Be.VERSION_CONFLICT_CODE,`Generative page '${l}' changed on the server after it was fetched (baseline ${n}, server ${f}) \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||!f)throw new Je.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify generative page '${l}' before writing: ${n?"the server did not return the page's current token":"no baseline token was recorded"}. This entity accepts no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let m=new Map(c.map(({row:I})=>{var D,P;return[(0,ve.normalizeGuid)(String((D=I[Bt])!==null&&D!==void 0?D:""),Bt),{filename:String((P=I.filename)!==null&&P!==void 0?P:""),filetype:Number(I.filetype)}]})),p=new Set(m.keys()),h=new Set(((o=u.files)!==null&&o!==void 0?o:[]).map(I=>(0,ve.normalizeGuid)(I.id,"file id")));if(!i)throw new Je.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify the files of generative page '${l}' before writing: no child baseline was recorded. These rows accept no If-Match validator, so an unverified write would silently overwrite any concurrent edit. Re-fetch the page and retry.`);let g=new Set(Object.keys(i).map(I=>I.toLowerCase()));for(let I of h)if(!p.has(I)&&g.has(I))throw new Je.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${I}' existed when this page was fetched but is gone from the server now \u2014 another writer deleted it. Refusing to recreate it, because a blind re-create would undo that delete. Re-fetch the page and re-apply the edit.`);for(let I of p)if(!g.has(I))throw new Je.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${I}' is on the server but absent from this page's baseline \u2014 another writer added it after the page was fetched, so its contents cannot be verified. Refusing to write over or delete it. Re-fetch the page so the addition is part of your baseline.`);let b=new Map(c.map(({row:I,etag:D})=>{var P;return[(0,ve.normalizeGuid)(String((P=I[Bt])!==null&&P!==void 0?P:""),Bt),D]}));for(let[I,D]of Object.entries(i)){let P=I.toLowerCase();if(!p.has(P))continue;let x=b.get(P);if(!D||!x)throw new Je.SdkError(Be.VERSION_CONFLICT_CODE,`Cannot verify generative-page file '${P}' before writing: ${D?"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(D!==x)throw new Je.SdkError(Be.VERSION_CONFLICT_CODE,`Generative-page file '${P}' changed on the server after this page was fetched (baseline ${D}, server ${x}) \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 w=fx(l,u,{rows:m,name:String((a=d.name)!==null&&a!==void 0?a:"")});if(wx(e,w),w.length===0)return{id:l,etag:f,memberEtags:Object.fromEntries(c.map(({row:I,etag:D})=>{var P;return[(0,ve.normalizeGuid)(String((P=I[Bt])!==null&&P!==void 0?P:""),Bt),D]}))};let C=bx(),S=[],O=!0;px(e,w)?await mx(e,l,w,u,C):{warnings:S,turnRecorded:O}=await hx(e,l,w,u,C);let k=await gx(e,l,w,u,h,b,S);return O?k:{...k,intentPending:!0}},async delete(e,t){var r;let n=(0,ve.normalizeGuid)(t,"id"),i=await Dv(e,n);await(0,Be.deleteRecord)(e,li,n);let o=new Set(i.map(l=>{var u;return String((u=l[Ia])!==null&&u!==void 0?u:"")}).filter(l=>l!=="")),a=!1;try{for(let l of await Dv(e,n)){let u=String((r=l[Ia])!==null&&r!==void 0?r:"");u!==""&&o.add(u)}}catch{a=!0}let s=[];for(let l of o)try{await(0,Be.deleteRecord)(e,fc,l)}catch(u){u instanceof Je.ConnectionError&&u.statusCode===404||s.push(l)}if(s.length>0||a)throw new Je.SdkError("GENPAGE_HISTORY_NOT_DELETED",`Generative page '${n}' was deleted, but its conversation history was not fully removed`+(s.length>0?` \u2014 ${s.length} of ${o.size} message(s) could not be (${s.join(", ")})`:"")+(a?" \u2014 and re-reading it after the delete failed, so a late turn may remain":"")+`. They no longer belong to any page; delete them as ${fc} rows regarding '${n}'.`)}};function bx(){return`uxagentproject_${(0,Ex.newId)()}`}function pie(e,t){var r;return t.length===0?e:{...e,warnings:[...(r=e.warnings)!==null&&r!==void 0?r:[],...t]}}function vx(e,t,r){var n,i;if(((i=(n=r.messages)===null||n===void 0?void 0:n.length)!==null&&i!==void 0?i:0)>1&&!e.supportsAtomicBatch)throw new Je.SdkError("GENPAGE_TURN_NOT_ATOMIC",`Refusing to write generative page '${t}': its new turn has a prompt AND a reply, which must be recorded together, and the injected HttpClient does not implement postRaw() \u2014 one request at a time, a failure between the two would leave half a turn. Implement postRaw(), or record the prompt alone (omit newTurn.agentMessage). Nothing was written.`)}function wx(e,t){let r=t.filter(i=>i.kind==="content");if(r.length>0&&!e.supportsBinaryPatch&&!e.supportsAtomicBatch)throw new Je.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: it has file content to upload, but the injected HttpClient implements neither patchRaw() nor postRaw(). A Dataverse File column is not writable through a JSON body, so proceeding would create the page and its rows and then fail, leaving a page whose source never uploaded.");if(r.some(i=>Pv(i.data)===void 0)&&!e.supportsBinaryPatch)throw new Je.SdkError("GENPAGE_CONTENT_WRITE_UNSUPPORTED","Refusing to write this generative page: a file's content is not UTF-8 text, which only the binary channel can carry, and the injected HttpClient does not implement patchRaw().")}});var Gx=v(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});cl.genPageRegistration=cl.GenPageAdapter=void 0;var mie=_x(),hie=Qr(),Ie=rn(),Up=pt(),Bp=xd(),gie=le(),Pa=Q(),Fx=$g(),Rv=rh(),Po=2e8,Mx=200000001,Wi={source:{name:"src/pages/page.tsx",fileType:Po},output:{name:"src/pages/page.compiled",fileType:Mx},config:{name:"config.json",fileType:Po},prompt:{name:"firstPrompt.json",fileType:Po}},Ux=Object.keys(Wi),yie=["dataSources","model","connectorBindings","actionBindings"],bie=["userMessage","agentMessage"],Tx=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,vie={source:"6f1c2a4e9b3d47a1b85c0e2f7d914a63",output:"a8e53d17c2f64b09a1d7e4b8c3f2069d",config:"3b97f0c64e2a4d8f95b1c7a0e6d3f814",prompt:"d24e8b51f7a34c6e8b09d5f1a2c7e3b6"},wie="9c3e7a15d2b84f6e8a01c5d7b3f9e240";function Bx(e,t,r){let n=(0,gie.normalizeGuid)(e,r).replace(/-/g,""),i=[];for(let a=0;a<32;a+=1)i.push(parseInt(n[a],16)^parseInt(t[a],16));i[12]=4,i[16]=i[16]&3|8;let o=i.map(a=>a.toString(16)).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function $p(e,t){return Bx(e,vie[t],"id")}function Cie(e,t){let r=Bx(e,wie,"newTurn.id"),n=parseInt(r.slice(24),16)%2**47+(t==="agent"?1:0);return`${r.slice(0,24)}${n.toString(16).padStart(12,"0")}`}function Dx(e){return typeof e=="string"&&e.trim()!==""?e:(0,Up.newId)()}function Gi(e){return(0,Ie.isJsonObject)(e)?e:{}}function ul(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function xp(e){return JSON.parse(JSON.stringify(e))}function Eie(e){let t=Gi(e);return t.status==="available"&&typeof t.data=="string"?{status:"available",data:t.data}:{status:"unavailable",reason:t.reason==="unpublished"?"unpublished":"missing"}}function gc(e){if(!e||e.status!=="available")return;let t=(0,Bp.base64ToUtf8)(e.data);return(0,Bp.utf8ToBase64)(t)===e.data?t:void 0}function qx(e,t,r){var n,i,o,a;return e.source!==void 0&&t!==void 0&&t?.source===e.source&&ul((n=t?.dataSources)!==null&&n!==void 0?n:[],(i=e.dataSources)!==null&&i!==void 0?i:[])&&((a=(o=e.bag)===null||o===void 0?void 0:o.rows)!==null&&a!==void 0?a:{}).output!==void 0&&(0,Fx.isLoadableGenPageOutput)(r)}function Aie(e,t){var r;try{return qx(e,t,gc((r=e.bag)===null||r===void 0?void 0:r.output))}catch{return!1}}function Fp(e){if(e!==void 0)try{let t=JSON.parse(e.replace(/^\uFEFF/,""));return(0,Ie.isJsonObject)(t)?t:void 0}catch{return}}function Ix(e,t){if(t===Po&&e.includes("page.tsx"))return"source";if(t===Mx&&e.includes(".compiled"))return"output";if(t===Po&&e===Wi.config.name)return"config";if(t===Po&&e===Wi.prompt.name)return"prompt"}function Ox(e){let t=e.toLowerCase();return Ux.some(r=>Wi[r].name.toLowerCase()===t)}function kv(e){return Object.fromEntries(e)}function Vx(e,t,r,n){let i=[],o=new Set,a=new Set(t),s=l=>{if(o.has(l))return;let u=a.has(l)?e[l]:r&&Object.prototype.hasOwnProperty.call(r,l)?r[l]:void 0;u!==void 0&&(o.add(l),i.push([l,u]))};return(n??[]).forEach(s),t.forEach(s),Object.keys(r??{}).forEach(s),kv(i)}function Px(e){var t,r,n;return Vx({dataSources:(t=e.dataSources)!==null&&t!==void 0?t:[],model:e.model,connectorBindings:e.connectorBindings,actionBindings:e.actionBindings},yie,(r=e.bag)===null||r===void 0?void 0:r.config,(n=e.bag)===null||n===void 0?void 0:n.configKeys)}function Rx(e){var t,r;return Vx({userMessage:e.firstPrompt,agentMessage:e.firstAgentMessage},bie,(t=e.bag)===null||t===void 0?void 0:t.prompt,(r=e.bag)===null||r===void 0?void 0:r.promptKeys)}function kx(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="dataSources"){if(!Array.isArray(o)||!o.every(a=>typeof a=="string"))return!1;e.dataSources=o}else if(i==="model"){if(typeof o!="string")return!1;e.model=o}else i==="connectorBindings"?e.connectorBindings=o:i==="actionBindings"?e.actionBindings=o:n.push([i,o]);return t.configKeys=Object.keys(r),n.length>0&&(t.config=kv(n)),!0}function Lx(e,t,r){let n=[];for(let[i,o]of Object.entries(r))if(i==="userMessage"||i==="agentMessage"){if(typeof o!="string")return!1;i==="userMessage"?e.firstPrompt=o:e.firstAgentMessage=o}else n.push([i,o]);return t.promptKeys=Object.keys(r),n.length>0&&(t.prompt=kv(n)),!0}function yc(e){var t,r;return e.source!==void 0||Object.keys((r=(t=e.bag)===null||t===void 0?void 0:t.rows)!==null&&r!==void 0?r:{}).length>0}var Sie=["dataSources","model","connectorBindings","actionBindings","firstPrompt","firstAgentMessage"];function $x(e){return yc(e)?[]:Sie.filter(t=>e[t]!==void 0).map(t=>(0,Ie.issue)(`/${t}`,"genpage-raw-structured-field",`${t} cannot be applied: this page is in raw-file mode \u2014 it has no source and no managed rows, so a push writes its files[] exactly as they are, and ${t} nowhere. Set source to make the page managed (the SDK then writes config.json and firstPrompt.json from the typed fields; a file in files[] holding one of those names must be removed first), or change the file that stores the value in files[] directly.`))}function xx(){return(0,Ie.issue)("/source","genpage-source-required","the page's source cannot be removed: its source row still exists, and a page without one cannot run. Set a new source, or delete the page with deleteRemoteArtifact.")}function Mp(e){return{status:"available",data:(0,Bp.utf8ToBase64)(e)}}function hc(e,t){var r,n;return{id:String((r=e.uxagentprojectid)!==null&&r!==void 0?r:""),name:String((n=e.name)!==null&&n!==void 0?n:""),files:t}}var qp=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){let r=t,n=Gi(r?.project),i=(Array.isArray(r?.files)?r.files:[]).map(g=>{var b,w,C;let S=Gi(g);return{id:String((b=S.uxagentprojectfileid)!==null&&b!==void 0?b:""),name:String((w=S.filename)!==null&&w!==void 0?w:""),fileType:Number((C=S.filetype)!==null&&C!==void 0?C:Po),content:Eie(S.content)}}),o=Array.isArray(r?.conversation)?r.conversation.map(g=>{var b,w;let C=Gi(g);return{sender:Number(C.messagesender)===200000001?"agent":"user",message:String((b=C.message)!==null&&b!==void 0?b:""),createdOn:String((w=C.createdon)!==null&&w!==void 0?w:"")}}):void 0,a=g=>o?{...g,conversation:o}:g,s=new Map,l=[],u=!0;for(let g of i){let b=Ix(g.name,g.fileType);b?((s.has(b)||g.name!==Wi[b].name)&&(u=!1),s.set(b,g)):(Ox(g.name)&&(u=!1),l.push(g))}if(!u||s.size===0)return a(hc(n,i));let c=hc(n,l),d={rows:{}};for(let[g,b]of s)d.rows[g]=b.id;let f=s.get("source");if(f){let g=gc(f.content);if(g===void 0)return a(hc(n,i));c.source=g}let m=s.get("output");m&&(d.output=m.content);let p=s.get("config");if(p){let g=Fp(gc(p.content));if(!g||!kx(c,d,g))return a(hc(n,i))}let h=s.get("prompt");if(h){let g=Fp(gc(h.content));if(!g||!Lx(c,d,g))return a(hc(n,i))}return c.bag=d,a(c)}async toApiPayload(t,r,n){var i,o,a,s,l,u,c,d,f,m,p,h,g;if(r&&!ul((i=t.conversation)!==null&&i!==void 0?i:[],(o=r.conversation)!==null&&o!==void 0?o:[]))throw new Pa.ValidationError("genPage",t.id,[(0,Ie.issue)("/conversation","genpage-conversation-read-only","conversation is the page's recorded history and cannot be edited. Record a new turn with newTurn; revert the edit to conversation before pushing.")]);let b=$x(t);if(b.length>0)throw new Pa.ValidationError("genPage",t.id,b);let w=[],C=r===void 0,S=C&&t.firstPrompt===void 0&&t.newTurn?{...t,firstPrompt:t.newTurn.prompt,...t.newTurn.agentMessage!==void 0?{firstAgentMessage:t.newTurn.agentMessage}:{}}:t;if(yc(S)){let I=(s=(a=S.bag)===null||a===void 0?void 0:a.rows)!==null&&s!==void 0?s:{},D=Xe=>{var Ne;return(Ne=I[Xe])!==null&&Ne!==void 0?Ne:$p(S.id,Xe)},P=(Xe,Ne,se)=>{w.push({id:D(Xe),name:Wi[Xe].name,fileType:Wi[Xe].fileType,content:Ne,unchanged:se})};if(S.source!==void 0){P("source",Mp(S.source),!C&&r?.source===S.source&&I.source!==void 0);let Xe=gc((l=S.bag)===null||l===void 0?void 0:l.output);qx(S,r,Xe)?P("output",{status:"retain"},!0):P("output",Mp(await this.compile(S,S.source,n)),!1)}else{if(I.source!==void 0)throw new Pa.ValidationError("genPage",S.id,[xx()]);if(I.output!==void 0){if(!C&&!ul((u=r?.dataSources)!==null&&u!==void 0?u:[],(c=S.dataSources)!==null&&c!==void 0?c:[]))throw new Pa.ValidationError("genPage",S.id,[(0,Ie.issue)("/dataSources","genpage-source-required","the page has no source row, so its output cannot be recompiled for new data sources; set a source to change them.")]);P("output",{status:"retain"},!0)}}let x=Px(S),K=!C&&r!==void 0&&ul(Px(r),x);(C||I.config!==void 0||!K)&&P("config",Mp(JSON.stringify(x)),K&&I.config!==void 0);let Oe=Rx(S),Vt=!C&&r!==void 0&&ul(Rx(r),Oe);(I.prompt!==void 0||Object.keys(Oe).length>0&&!Vt)&&P("prompt",Mp(JSON.stringify(Oe)),Vt&&I.prompt!==void 0)}for(let I of(d=S.files)!==null&&d!==void 0?d:[]){let D=(f=r?.files)===null||f===void 0?void 0:f.find(P=>P.id===I.id);w.push({id:I.id,name:I.name,fileType:I.fileType,content:I.content,unchanged:D!==void 0&&ul(D,I)})}let O=[];if(S.newTurn){let I=S.newTurn.id,D=P=>I?{id:Cie(I,P)}:{};O.push({...D("user"),sender:"user",message:S.newTurn.prompt}),S.newTurn.agentMessage&&O.push({...D("agent"),sender:"agent",message:S.newTurn.agentMessage})}let k=(p=(m=S.bag)===null||m===void 0?void 0:m.config)!==null&&p!==void 0?p:{};return{name:S.name,files:w,...O.length>0?{messages:O,messageContext:{dataSources:(h=S.dataSources)!==null&&h!==void 0?h:[],model:(g=S.model)!==null&&g!==void 0?g:"",enabledTools:Array.isArray(k.enabledTools)?k.enabledTools:[],configurableTools:Array.isArray(k.configurableTools)?k.configurableTools:[]}}:{}}}committed(t,r,n={intentPending:!1}){let i=this.serverState(t,r);return n.intentPending&&t.newTurn!==void 0?{artifact:{...i,newTurn:xp(t.newTurn)},baseline:i}:{artifact:i,baseline:i}}serverState(t,r){var n,i,o,a,s,l;if(!yc(t)&&!t.newTurn)return t;let u=xp(t);if(delete u.newTurn,!yc(t))return u;let c={...(n=u.bag)!==null&&n!==void 0?n:{},rows:{...(o=(i=u.bag)===null||i===void 0?void 0:i.rows)!==null&&o!==void 0?o:{}}};for(let d of(a=r.files)!==null&&a!==void 0?a:[]){let f=Ux.find(p=>Wi[p].name===d.name&&Wi[p].fileType===d.fileType);if(!f||u.files.some(p=>p.id===d.id)||(c.rows[f]=d.id,d.content.status!=="available"))continue;let m=(0,Bp.base64ToUtf8)(d.content.data);f==="output"?c.output={status:"available",data:d.content.data}:f==="config"?(delete c.config,delete u.dataSources,delete u.model,delete u.connectorBindings,delete u.actionBindings,kx(u,c,(s=Fp(m))!==null&&s!==void 0?s:{})):f==="prompt"&&(delete c.prompt,delete u.firstPrompt,delete u.firstAgentMessage,Lx(u,c,(l=Fp(m))!==null&&l!==void 0?l:{}))}return u.bag=c,u}baselineContent(t){var r;let n={...t};return delete n.conversation,delete n.newTurn,n.files=[...(r=t.files)!==null&&r!==void 0?r:[]].sort((i,o)=>i.id<o.id?-1:i.id>o.id?1:0),n}normalize(t){let r=t.newTurn;return!(0,Ie.isJsonObject)(r)||typeof r.id=="string"&&Tx.test(r.id)?t:{...t,newTurn:{...r,id:(0,Up.newId)()}}}async compile(t,r,n){var i;let o=(i=t.dataSources)!==null&&i!==void 0?i:[],a=[],s=[];if(o.forEach((f,m)=>{var p;let h=(p=n?.resolveEntity)===null||p===void 0?void 0:p.call(n,f);h&&h.columnDetailComplete===!0?a.push(h):s.push((0,Ie.issue)(`/dataSources/${m}`,h?"genpage-data-source-incomplete":"genpage-data-source-unresolved",h?`the column metadata of data source '${f}' could not be read completely (a choice or lookup read failed, or returned options with no label), so the page cannot be compiled with its enums. Retry the push.`:`the metadata of data source '${f}' could not be read, so the page cannot be compiled with its enums. Check the table's logical name and that it exists in this environment.`))}),s.length>0)throw new Pa.ValidationError("genPage",t.id,s);if(!n?.loadTypeScript)throw new Pa.ValidationError("genPage",t.id,[(0,Ie.issue)("/source","genpage-compiler-unavailable","no TypeScript compiler is available to compile the page")]);let l=await n.loadTypeScript(),u=a.length>0?(0,Rv.buildGenPageRuntimeTypes)(a):void 0,c=a.length>0?(0,Rv.buildGenPageLegacyEnums)(a):void 0,d=(0,Fx.compileGenPage)(l,r,u,c);if(d.diagnostics.length>0)throw new Pa.ValidationError("genPage",t.id,d.diagnostics.map(Nie));return d.code}metadataNeeds(t,r){if(t.source===void 0||!Array.isArray(t.dataSources))return[];let n=Aie(t,r)?{fetchRequired:!1}:{};return t.dataSources.filter(i=>typeof i=="string"&&i!=="").map(i=>({entityLogicalName:i,fieldName:"",needsColumnDetail:!0,...n}))}createDefault(t){var r,n;let i=Dx(t.id),o={id:i,name:(r=t.name)!==null&&r!==void 0?r:"New page",files:((n=t.files)!==null&&n!==void 0?n:[]).map(a=>{var s,l,u;return{id:Dx(a.id),name:(s=a.name)!==null&&s!==void 0?s:"index.tsx",fileType:(l=a.fileType)!==null&&l!==void 0?l:Po,content:(u=a.content)!==null&&u!==void 0?u:{status:"available",data:""}}})};t.source!==void 0&&(o.source=t.source),t.dataSources!==void 0&&(o.dataSources=[...t.dataSources]);for(let a of["model","firstPrompt","firstAgentMessage"])t[a]!==void 0&&(o[a]=t[a]);return t.newTurn!==void 0&&(o.newTurn={...t.newTurn}),t.connectorBindings!==void 0&&(o.connectorBindings=xp(t.connectorBindings)),t.actionBindings!==void 0&&(o.actionBindings=xp(t.actionBindings)),o.source!==void 0&&(o.bag={rows:{source:$p(i,"source"),output:$p(i,"output"),config:$p(i,"config")}}),o}assignMissingIds(t){if(t==null)return{id:(0,Up.newId)()};if(!(0,Ie.isJsonObject)(t))return t;let r=t;return(Object.keys(r).length===0||"id"in r||"content"in r||"fileType"in r||Array.isArray(r.files))&&(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Up.newId)()),r}validate(t){let r=[],n=t;for(let s of["source","model","firstPrompt","firstAgentMessage"])n[s]!==void 0&&typeof n[s]!="string"&&r.push((0,Ie.issue)(`/${s}`,"genpage-field-type",`${s} must be a string, got ${typeof n[s]}`));if(n.source===void 0&&Gi(Gi(n.bag).rows).source!==void 0&&r.push(xx()),r.push(...$x(t)),n.newTurn!==void 0){let s=Gi(n.newTurn);(!(0,Ie.isJsonObject)(n.newTurn)||typeof s.prompt!="string"||s.prompt.trim()==="")&&r.push((0,Ie.issue)("/newTurn/prompt","genpage-turn-prompt","newTurn needs a non-empty prompt")),s.agentMessage!==void 0&&typeof s.agentMessage!="string"&&r.push((0,Ie.issue)("/newTurn/agentMessage","genpage-field-type","newTurn.agentMessage must be a string")),s.id!==void 0&&(typeof s.id!="string"||!Tx.test(s.id))&&r.push((0,Ie.issue)("/newTurn/id","genpage-turn-id","newTurn.id is the turn's identity, which the SDK mints \u2014 remove it, or keep the GUID it minted"))}if(n.dataSources!==void 0)if(!Array.isArray(n.dataSources))r.push((0,Ie.issue)("/dataSources","genpage-data-sources-array","dataSources must be an array of table logical names"));else{let s=new Set;n.dataSources.forEach((l,u)=>{typeof l!="string"||!Rv.TABLE_LOGICAL_NAME.test(l)?r.push((0,Ie.issue)(`/dataSources/${u}`,"genpage-data-source-name",`a data source must be a table logical name (lowercase, e.g. 'account'), got '${String(l)}'`)):s.has(l)?r.push((0,Ie.issue)(`/dataSources/${u}`,"genpage-data-source-duplicate",`data source '${l}' is listed twice`)):s.add(l)})}n.conversation!==void 0&&!Array.isArray(n.conversation)&&r.push((0,Ie.issue)("/conversation","genpage-conversation-array","conversation must be an array"));let i=n.files;if(i!==void 0&&!Array.isArray(i))return r.push((0,Ie.issue)("/files","files-must-be-array",`files must be an array, got ${typeof i}`)),r;let o=yc(t),a=new Map;return(Array.isArray(i)?i:[]).forEach((s,l)=>{let u=`/files/${l}`,c=Gi(s),d=typeof c.id=="string"?c.id.trim().toLowerCase():"";if(d==="")r.push((0,Ie.issue)(u,"file-id-required","a generative-page file needs an id"));else{let g=a.get(d);g!==void 0?r.push((0,Ie.issue)(u,"file-id-duplicate",`two files share the id '${c.id}' (also at /files/${g}); a file's id is its identity, so a duplicate makes an edit ambiguous`)):a.set(d,l)}let f=typeof c.name=="string"?c.name:"",m=f.split("/");f===""||/[\u0000-\u001F\u007F]/.test(f)||f.includes("\\")||m.some(g=>g===""||g==="."||g==="..")?r.push((0,Ie.issue)(u+"/name","file-name-invalid",`a file name must be a relative path of non-empty '/'-separated segments (no '.', '..', backslash or control character \u2014 its last segment is sent as an HTTP header); got '${f}'`)):o&&(Ox(f)||Ix(f,Number(c.fileType))!==void 0)&&r.push((0,Ie.issue)(u+"/name","file-name-reserved",`'${f}' would be read by the maker portal as one of the page's managed rows (its source, output, config or first prompt), which the SDK writes from source and the configuration fields; it cannot also be a file in files[]`));let p=c.content;if(p===void 0){r.push((0,Ie.issue)(u+"/content","file-content-required","content is required: omitting it is indistinguishable from an empty file, and the two have opposite effects on the next push"));return}let h=Gi(p);h.status==="available"?typeof h.data!="string"&&r.push((0,Ie.issue)(u+"/content/data","file-content-data-invalid","available content needs base64 `data`")):h.status!=="unavailable"&&r.push((0,Ie.issue)(u+"/content/status","file-content-status-invalid",`content.status must be 'available' or 'unavailable', got ${String(h.status)}`))}),r}};cl.GenPageAdapter=qp;function Nie(e){let t=`line ${e.line}, column ${e.column}`;return e.rule==="genpage-source-syntax"?(0,Ie.issue)("/source",e.rule,`${t}: ${e.message} (TS${e.code}) \u2014 the page cannot run, so it was not pushed`):(0,Ie.issue)("/source",e.rule,`${t}: ${e.message}`)}function _ie(){return{adapter:new qp,api:mie.genPageApi,publish:(e,t)=>(0,hie.publishGenPageById)(e,t),publishScope:e=>({envelope:"uxagentproject",targetIds:[e]}),rebaselineAfterPublish:"snapshot"}}cl.genPageRegistration=_ie});var zx=v(Gp=>{"use strict";Object.defineProperty(Gp,"__esModule",{value:!0});Gp.reconcileBpfSecurityRoles=void 0;var Wx=Lt(),$v=Q(),Vp=ye(),bc=le(),Tie="Global",Lv={create:"Create",read:"Read",write:"Write",delete:"Delete"};async function Die(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,bc.odataPathLiteral)(t)}')?$select=LogicalName,Privileges`,i=(0,Vp.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.Privileges;if(!Array.isArray(o))throw new $v.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of business process flow table '${t}' returned no 'Privileges' array (got ${(0,Wx.describeMalformedValue)(o)}), so which access it can grant is unknown.`);let a=o,s={},l=new Set;return Object.keys(Lv).forEach(u=>{let c=a.find(d=>d.PrivilegeType===Lv[u]);if(c){let d=(0,bc.normalizeGuid)(c.PrivilegeId,"PrivilegeId");s[u]=d,l.add(d)}}),{byAccess:s,all:l}}async function Iie(e,t){var r;let n=`/RetrieveRolePrivilegesRole(RoleId=${t})`,i=(0,Vp.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.RolePrivileges;if(!Array.isArray(o))throw new $v.ConnectionError(e.apiUrl(n),i.status,`reading the privileges of role '${t}' returned no 'RolePrivileges' array (got ${(0,Wx.describeMalformedValue)(o)}), so what it holds is unknown.`);return new Set(o.map(a=>(0,bc.normalizeGuid)(a.PrivilegeId,"PrivilegeId")))}async function Oie(e,t,r){if(r.length===0)return;let n={Privileges:r.map(o=>({Depth:Tie,PrivilegeId:o}))},i=`/roles(${t})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;(0,Vp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function Pie(e,t,r){let n={Privilege:{"@odata.type":"Microsoft.Dynamics.CRM.privilege",privilegeid:r}},i=`/roles(${t})/Microsoft.Dynamics.CRM.RemovePrivilegeRole`;(0,Vp.ensureSuccess)(await e.post(i,n),e.apiUrl(i))}async function Rie(e,t,r){var n,i,o;if(!r||r.length===0)return;let a=await Die(e,t.toLowerCase());for(let s of r){let l=(0,bc.normalizeGuid)(s.roleId,"roleId"),u=((n=s.access)!==null&&n!==void 0?n:[]).find(c=>!a.byAccess[c]);if(u!==void 0)throw new $v.InvalidArgumentError(`Cannot grant '${u}' access to role '${l}' on business process flow table '${t.toLowerCase()}': its metadata lists no '${(i=Lv[u])!==null&&i!==void 0?i:u}' privilege. No security role was changed.`)}for(let s of r){let l=(0,bc.normalizeGuid)(s.roleId,"roleId"),u=new Set(((o=s.access)!==null&&o!==void 0?o:[]).map(p=>a.byAccess[p]).filter(p=>!!p)),c=await Iie(e,l),d=new Set([...c].filter(p=>a.all.has(p))),f=[...u].filter(p=>!d.has(p)),m=[...d].filter(p=>!u.has(p));await Oie(e,l,f);for(let p of m)await Pie(e,l,p)}}Gp.reconcileBpfSecurityRoles=Rie});var iF=v(jp=>{"use strict";Object.defineProperty(jp,"__esModule",{value:!0});jp.bpfApi=void 0;var mr=Qi(),jx=Kl(),kie=Lt(),Qe=Q(),Ye=ye(),gn=le(),Lie=zx(),$ie=Lm(),vc=xm(),xie={"Content-Type":"application/json",Accept:"application/json"},xv={...xie,Prefer:"return=representation"},Fie=`category eq ${mr.WorkflowCategory.BusinessProcessFlow} and type eq ${mr.WorkflowTypeCode.Definition} and businessprocesstype eq ${mr.BusinessProcessType.BusinessFlow}`,Mie="workflowid,name,description,primaryentity,statecode,category,type,businessprocesstype,processorder",Uie="workflowid,name,uniquename,description,primaryentity,statecode,statuscode,category,type,businessprocesstype,processorder,xaml,clientdata",Bie=["xaml","name","description","processorder"];async function Wp(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,Lie.reconcileBpfSecurityRoles)(e,n,t.securityRoles)}async function Mv(e,t,r){let n={statecode:mr.StateCode.Activated,statuscode:mr.StatusCode.Activated},i=`/workflows(${t})`,{response:o,resent:a}=await nF(e,i,n,r,null);try{return(0,Ye.ensureSuccess)(o,e.apiUrl(i))}catch(s){throw a?tF(s):s}}var eF=new WeakSet;function tF(e){return typeof e=="object"&&e!==null&&eF.add(e),e}function rF(e){return typeof e=="object"&&e!==null&&eF.has(e)}function Hx(e){return e instanceof Qe.ConnectionError&&(e.statusCode===0||Ye.AMBIGUOUS_WRITE_STATUSES.has(e.statusCode))}async function nF(e,t,r,n,i){let o=n??i,a=0;try{return{response:await(0,Ye.resendWhile)(Ye.isConcurrencyLockRefusal,()=>{a+=1;let l=a===1?n:o,u={...xv};return l&&(u["If-Match"]=l),e.patch(t,r,{headers:u})},o?Ye.LOCK_BACKOFF_MS:[]),resent:a>1}}catch(s){throw a>1?tF(s):s}}async function Kx(e,t,r){return(0,Ye.readEtag)(await Mv(e,t,r))}function Jx(e,t){return new Qe.SdkError("BPF_WRITE_NOT_ECHOED",`The ${t} of business process flow '${e}' was applied, but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next step could not be conditioned on a token this push produced and was NOT sent. `+zp(e))}async function wc(e,t){var r;let n=`/workflows(${t})${(0,gn.odataQuery)([["$select","statecode"]])}`,i=(0,Ye.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.statecode,a=Number(o);if(o==null||o===""||!Number.isFinite(a))throw new Qe.SdkError("BPF_STATE_UNREADABLE",`Reading the state of business process flow '${t}' answered HTTP ${i.status} without a usable statecode, so whether it is Active cannot be decided.`);return a}async function Fv(e,t,r,n,i=null){if((n??await wc(e,t))!==mr.StateCode.Activated)return{deactivated:!1,etag:null};let o={statecode:mr.StateCode.Draft,statuscode:mr.StatusCode.Draft},a=`/workflows(${t})`,s,l;try{({response:s,resent:l}=await nF(e,a,o,r,i))}catch(c){return await Yx(e,t,c,rF(c))}if(Ye.AMBIGUOUS_WRITE_STATUSES.has(s.status))return await Yx(e,t,new Qe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",`Deactivating business process flow '${t}' answered HTTP ${s.status} from an intermediary, so whether it committed is unknown.`),l);let u=(0,Ye.ensureSuccess)(s,e.apiUrl(a));return{deactivated:!0,etag:(0,Ye.readEtag)(u)}}async function Yx(e,t,r,n){let i;try{i=await wc(e,t)}catch{i=void 0}if(i===mr.StateCode.Draft&&!n)return{deactivated:!0,etag:null,uncertainCause:r};if(i===mr.StateCode.Activated)throw r;let o=new Qe.SdkError("BPF_DEACTIVATE_OUTCOME_UNKNOWN",i===mr.StateCode.Draft?`Deactivating business process flow '${t}' waited for the platform's concurrency lock, and its last attempt ended without a definitive answer. The process now reads Draft, but whether this deactivate or another writer's change put it there is unknown \u2014 the row may even have been replaced at the same id \u2014 so nothing more was sent: no edit, no re-activation, no delete. It MAY be left DISABLED: read it before retrying. Original failure: ${r instanceof Error?r.message:String(r)}`:`Deactivating business process flow '${t}' did not complete, and its state could not be re-read \u2014 it MAY be left DISABLED and needs reconciling. Original failure: ${r instanceof Error?r.message:String(r)}`);throw(0,Qe.attachCause)(o,r),o}async function qie(e,t){let r=(0,gn.normalizeGuid)(t,"workflowid");try{return await Mv(e,r,null),"restored"}catch{return Uv(e,r)}}async function Vie(e,t,r){let n=(0,gn.normalizeGuid)(t,"workflowid");try{let i=await Mv(e,n,r);return{outcome:"restored",acknowledged:!0,echo:(0,Ye.readEtag)(i)}}catch(i){return i instanceof Qe.SdkError&&i.code===Ye.VERSION_CONFLICT_CODE?{outcome:"changed",acknowledged:!1,echo:null}:{outcome:await Uv(e,n),acknowledged:!1,echo:null}}}async function Uv(e,t){try{let r=await wc(e,t);return r===mr.StateCode.Activated?"restored":r===mr.StateCode.Draft?"disabled":"unknown"}catch{return"unknown"}}async function Qx(e,t,r,n){return r?{...await Vie(e,t,r),attempted:!0}:n?{outcome:await Uv(e,(0,gn.normalizeGuid)(t,"workflowid")),attempted:!1,acknowledged:!1,echo:null}:{outcome:await qie(e,t),attempted:!0,acknowledged:!1,echo:null}}function Gie(e,t){let r=new Qe.SdkError(vc.WORKFLOW_DELETE_UNSETTLED_CODE,`Deleting business process flow '${e}' failed${(0,vc.failedAfterResend)(t)?" after it was re-sent":""}, and re-activating the process this delete had deactivated was refused (HTTP 412): the row at that id is no longer the version this delete deactivated \u2014 it was edited, or deleted and re-created at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read the row before deleting it again. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function Xx(e,t,r,n,i=!0){let o=`Original failure: ${n instanceof Error?n.message:String(n)}`,a="it was NOT re-activated: it waited for the platform's concurrency lock, and no write of this operation proves the row is still its own, so a re-activation could have enabled another writer's edit",s;return r==="changed"?s=new Qe.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",`Business process flow '${e}' was deactivated ${t}, and re-activating it was refused (HTTP 412): the row is no longer the version this operation last wrote \u2014 another writer changed it, or replaced it at the same id \u2014 so it was NOT re-activated, and it MAY be left DISABLED. Read it before retrying. ${o}`):r==="disabled"?s=new Qe.SdkError("BPF_LEFT_DEACTIVATED",i?`Business process flow '${e}' was deactivated ${t}, and it could NOT be reactivated \u2014 it is left DISABLED. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a} \u2014 it is left DISABLED. ${o}`):s=new Qe.SdkError("BPF_REACTIVATE_OUTCOME_UNKNOWN",i?`Business process flow '${e}' was deactivated ${t}, and whether it was reactivated could not be confirmed \u2014 it MAY be left DISABLED and needs checking. ${o}`:`Business process flow '${e}' was deactivated ${t}, and ${a}; its state could not be read \u2014 it MAY be left DISABLED and needs checking. ${o}`),(0,Qe.attachCause)(s,n),s}async function Wie(e,t){try{return await wc(e,t),"survived"}catch(r){return r instanceof Qe.ConnectionError&&r.statusCode===404?"removed":"unknown"}}async function zie(e,t,r){if(r)try{let{deactivated:n,etag:i}=await Fv(e,t,r),o=n?i:r;if(o)return await(0,vc.deleteWorkflowResending)(e,t,{bindingToken:o,kindName:"business process flow",resendDeadlockVictim:!0,ifMatchOnFirst:!0}),"removed"}catch{}return Wie(e,t)}function zp(e){return`Adopt the server's copy with fetchArtifact('bpf', '${e}', { overwrite: true }) \u2014 it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push.`}function Zx(e,t){return new Qe.SdkError("BPF_CREATE_NO_TOKEN",`Created business process flow '${e}' but the server returned no concurrency token for it (this environment did not honour 'Prefer: return=representation'), so the next push would have nothing to condition on. ${t} It was NOT rolled back: deleting it without a token could remove an edit made since. ${zp(e)}`)}function jie(e,t){let r=new Qe.SdkError("BPF_CREATE_NOT_ROLLED_BACK",`Creating business process flow '${e}' failed part-way, and the rollback could NOT remove it \u2014 it still EXISTS, possibly Active and half-configured. (The rollback deletes only on a token this create produced, so a row somebody has since edited is left in place on purpose; a delete the platform refused or failed leaves it too.) ${zp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function Hie(e,t){let r=new Qe.SdkError("BPF_CREATE_ROLLBACK_OUTCOME_UNKNOWN",`Creating business process flow '${e}' failed part-way, and whether its rollback removed the process could not be confirmed \u2014 it MAY still exist, possibly Active and half-configured. ${zp(e)} Or delete it. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function Kie(e,t){let r=new Qe.SdkError("BPF_CREATE_REMOVED_AFTER_CONFLICT",`Creating business process flow '${e}' was interrupted: another writer changed it right after it was created, so this push's next step was refused rather than overwrite or activate their edit \u2014 and the process has since been removed. Nothing is left behind and there is nothing to fetch. If the removal was deliberate, stop here; otherwise push again to re-create it at the same id. Original failure: ${t instanceof Error?t.message:String(t)}`);return(0,Qe.attachCause)(r,t),r}function Bv(e){let t={};for(let r of Bie)e[r]!==void 0&&(t[r]=e[r]);return t}var Jie=["name,processorder","description,name,processorder"];function Yie(e){let{xaml:t,...r}=Bv(e);return typeof t=="string"&&Jie.includes(Object.keys(r).sort().join(","))}async function Qie(e,t,r,n){let{xaml:i,...o}=Bv(r),[,a]=await(0,jx.sendChangeSet)(e,[{method:"PATCH",path:`/workflows(${t})`,body:o,etag:n},{method:"PATCH",path:`/workflows(${t})${(0,gn.odataQuery)([["$select","workflowid"]])}`,body:{xaml:i},headers:{Prefer:"return=representation"}}],`business process flow '${t}'`,{resendWhileLockRefused:!0});return(0,Ye.readEtag)((0,jx.partResponse)(a))}jp.bpfApi={async get(e,t){let n=`/workflows(${(0,gn.normalizeGuid)(t,"id")})${(0,gn.odataQuery)([["$select",Uie]])}`,i=(0,Ye.ensureSuccess)(await e.get(n),e.apiUrl(n));return{raw:i.body,etag:(0,Ye.readEtag)(i)}},async list(e,t){let r=[Fie];t?.entityLogicalName&&r.push(`primaryentity eq '${(0,gn.odataLiteral)(t.entityLogicalName)}'`);let n=`/workflows${(0,gn.odataQuery)([["$select",Mie],["$filter",r.join(" and ")]])}`;return(await(0,kie.collectPages)(e,n,"listArtifacts('bpf')")).map(o=>{var a,s;return{type:"bpf",id:(a=o.workflowid)!==null&&a!==void 0?a:"",name:(s=o.name)!==null&&s!==void 0?s:"",entityLogicalName:o.primaryentity,isDirty:!1}})},async create(e,t){let r=t,n=(0,gn.normalizeGuid)(r.record.workflowid,"workflowid"),i="/workflows",o=(0,Ye.ensureSuccess)(await e.post(i,r.record,{headers:xv}),e.apiUrl(i)),a=(0,Ye.readEtag)(o);if(!a)throw Zx(n,r.status==="Active"?"The process EXISTS as Draft and was NOT activated \u2014 an activation that cannot be conditioned on our own write could activate somebody else's edit.":"The process EXISTS as Draft.");let s=a;try{r.status==="Active"&&(s=await Kx(e,n,a)),await Wp(e,r)}catch(l){let u=await zie(e,n,s);throw u==="survived"?jie(n,l):u==="unknown"?Hie(n,l):l instanceof Qe.SdkError&&l.code===Ye.VERSION_CONFLICT_CODE?Kie(n,l):l}if(!s)throw Zx(n,"The process EXISTS and IS Active, but its activation returned no token.");return{id:n,etag:s}},async update(e,t,r,n){let i=r,o=(0,gn.normalizeGuid)(t,"id"),a=(0,Ye.requireEtag)(n,"bpf",o),s=await wc(e,o);if(s===mr.StateCode.Activated&&i.status==="Active"&&e.supportsAtomicBatch&&Yie(i.record)){let p=await Qie(e,o,i.record,a);return await Wp(e,i),{id:o,etag:p}}let{deactivated:l,etag:u,uncertainCause:c}=await Fv(e,o,a,s),d=u,f=!1,m=!1;try{if(c!==void 0)throw c;let p=a;if(l){if(!u)throw Jx(o,"deactivation");p=u}let h=`/workflows(${o})`,g;try{g=(0,Ye.ensureSuccess)(await e.patch(h,Bv(i.record),{headers:{...xv,"If-Match":p}}),e.apiUrl(h))}catch(w){throw Hx(w)&&(d=null),w}let b=(0,Ye.readEtag)(g);if(d=b,i.status==="Active"){if(!b)throw Jx(o,"definition write");try{b=await Kx(e,o,b)}catch(w){throw Hx(w)&&(d=null),m=(0,Ye.isConcurrencyLockRefusalError)(w),w}f=!0}return await Wp(e,i),{id:o,etag:b}}catch(p){if(l&&!f){let{outcome:h,attempted:g,acknowledged:b,echo:w}=await Qx(e,o,d,rF(p));if(m&&b)return f=!0,await Wp(e,i),{id:o,etag:w};if(h!=="restored")throw Xx(o,"to apply an edit, the edit failed",h,p,g)}throw p}},async delete(e,t){let r=(0,gn.normalizeGuid)(t,"id"),n=await(0,$ie.assertWorkflowKind)(e,r,mr.WorkflowCategory.BusinessProcessFlow),{deactivated:i,etag:o}=await Fv(e,r,null,void 0,n);try{await(0,vc.deleteWorkflowResending)(e,r,{bindingToken:i?o:n,kindName:"business process flow",deactivated:i,resendDeadlockVictim:!0})}catch(a){if(i&&!(0,vc.isWorkflowDeleteUnsettled)(a)){let{outcome:s,attempted:l}=await Qx(e,r,o,!1);if(s==="changed")throw Gie(r,a);if(s!=="restored")throw Xx(r,"so it could be deleted, the delete failed",s,a,l)}throw a}}}});var qF=v(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});fl.bpfRegistration=fl.BpfAdapter=void 0;var Hp=Qi(),Xie=iF(),qv=so(),Ra=uo(),yF=lo(),Hr=rn(),Mr=pt(),Fn=Q(),Zie=100,Vv='<?xml version="1.0" encoding="utf-16"?>',oF=1033,bF="mxswa:Workflow",eoe="mxswa:ActivityReference.Properties",toe="mcwo:StepLabel",roe="mcwb:Control",aF="mcwb:Control.ControlDisplayName",vF="mcwb:Control.DataFieldName",wF="DataFieldName",sF="ControlDisplayName",CF="Literal",Jp="x:Null",lF="x:String",Gv="x:Key",Wv="DisplayName",Qp="Activities",noe="StepLabels",EF="StageId",AF="StageCategory",SF="NextStageId",NF="ProcessStepId",Kp="IsProcessRequired",_F="EntityComposite",TF="StageComposite",DF="StepComposite";function Cc(e){return(0,Hr.isJsonObject)(e)?e:{}}function ci(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 ka(e,t){var r;return(r=ci(e).find(n=>n.tagName===t))!==null&&r!==void 0?r:null}function fi(e){return ka(e,eoe)}function hr(e,t){var r;return(r=ci(e).find(n=>n.getAttribute(Gv)===t))!==null&&r!==void 0?r:null}function dl(e,t){var r;return((r=e.getAttribute("AssemblyQualifiedName"))!==null&&r!==void 0?r:"").includes(t)}function di(e){var t;return!e||!e.firstChild?"":(t=e.firstChild.nodeValue)!==null&&t!==void 0?t:""}function IF(e,t,r){e.firstChild?e.firstChild.nodeValue=r:e.appendChild(t.createTextNode(r))}function Ec(e){var t;let r=(t=e.getAttribute(Wv))!==null&&t!==void 0?t:"",n=r.indexOf(": ");return n>=0?r.slice(n+2):r}function OF(e,t){var r;let n=(r=e.getAttribute(Wv))!==null&&r!==void 0?r:"",i=n.indexOf(": ");e.setAttribute(Wv,i>=0?n.slice(0,i+2)+t:t)}function PF(e,t){let r=hr(e,noe),n=ka(r,toe);n&&n.setAttribute("Description",t)}function ioe(e){let t=hr(e,AF);if(!t||t.tagName===Jp)return;let r=di(t).trim();return r===""?void 0:Number(r)}function ooe(e){let t=hr(e,SF);if(!t||t.tagName===Jp)return;let r=di(t).trim();return r===""?void 0:r}function RF(e){let t=kF(e);if(!t)return;let r=$F(t,wF,vF);return r===""?void 0:r}function zv(e,t){let r=ci(e);for(;r.length>0;){let n=r.pop();if(n.tagName===t)return n;for(let i of ci(n))r.push(i)}return null}function kF(e){let t=hr(fi(e),Qp);return t?zv(t,roe):null}function LF(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 $F(e,t,r){var n;return LF(e,t)?(n=e.getAttribute(t))!==null&&n!==void 0?n:"":coe(e,r)}function uF(e,t,r,n){if(LF(e,t)){e.setAttribute(t,n);return}if(ka(e,r)){aoe(e,r,n);return}throw new Fn.InvalidArgumentError(`BPF step control exposes neither a '${t}' attribute nor a <${r}> wrapper to bind a column`)}function aoe(e,t,r){let n=ka(e,t),i=n?zv(n,CF):null;if(!i)throw new Fn.InvalidArgumentError(`BPF step control's <${t}> wrapper holds no <Literal> to bind a column`);i.setAttribute("Value",r)}function xF(e){return Ec(e)}function Xp(e){let t=ka(e,bF),r=[];for(let n of ci(t).filter(i=>dl(i,_F))){let i=hr(fi(n),Qp);for(let o of ci(i).filter(a=>dl(a,TF)))r.push({el:o,entity:xF(n)})}return r}function jv(e){let t=hr(fi(e),Qp);return ci(t).filter(r=>dl(r,DF))}function soe(e){let t=fi(e),r=di(hr(t,Kp)).trim().toLowerCase(),n=RF(e),i={id:di(hr(t,NF)),name:Ec(e)};return n!==void 0&&(i.fieldName=n),r==="true"&&(i.required=!0),i}function loe(e,t){let r=fi(e),n=ioe(r),i=ooe(r),o={id:di(hr(r,EF)),name:Ec(e),entityLogicalName:t,steps:jv(e).map(soe)};return n!==void 0&&(o.category=n),i!==void 0&&(o.nextStageId=i),o}function uoe(e){return Xp(e).map(({el:t,entity:r})=>loe(t,r))}function ui(e){return new Fn.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 coe(e,t){var r;let n=ka(e,t),i=n?zv(n,CF):null;return(r=i?.getAttribute("Value"))!==null&&r!==void 0?r:""}function Hv(e,t){var r;let n=e.createElement(t.tagName),i=t.attributes;for(let a=0;a<i.length;a+=1)n.setAttribute(i[a].name,i[a].value);let o=t.childNodes;for(let a=0;a<o.length;a+=1){let s=o[a];s.nodeType===1?n.appendChild(Hv(e,s)):s.nodeType===3&&n.appendChild(e.createTextNode((r=s.nodeValue)!==null&&r!==void 0?r:""))}return n}function FF(e){return hr(fi(e),Qp)}function doe(e,t,r){var n;let i=t.entityLogicalName&&t.entityLogicalName.trim()!==""?t.entityLogicalName:r,o=!((n=t.steps[0])===null||n===void 0)&&n.id&&t.steps[0].id.trim()!==""?t.steps[0].id:(0,Mr.newId)(),{body:a}=Zp(Kv(i,(0,Mr.newId)(),t.id,o));return Hv(e,Xp((0,Ra.parseXmlRoot)(a,"<Activity/>"))[0].el)}function foe(e,t){let{body:r}=Zp(Kv("account",(0,Mr.newId)(),(0,Mr.newId)(),t.id));return Hv(e,jv(Xp((0,Ra.parseXmlRoot)(r,"<Activity/>"))[0].el)[0])}function MF(e,t){for(;e.firstChild;)e.removeChild(e.firstChild);for(let r of t)e.appendChild(r)}function UF(e,t,r,n){let i=hr(e,r);if(!i||!i.parentNode){if(n!==void 0&&n!=="")throw ui(`setting '${r}' on a stage whose xaml does not expose that slot`);return}let o=i.parentNode;if(n===void 0||n===""){if(i.tagName!==Jp&&di(i).trim()!==""){let s=t.createElement(Jp);s.setAttribute(Gv,r),o.replaceChild(s,i)}return}if(i.tagName===lF){di(i).trim()!==n&&IF(i,t,n);return}let a=t.createElement(lF);a.setAttribute(Gv,r),a.appendChild(t.createTextNode(n)),o.replaceChild(a,i)}function poe(e,t,r){UF(e,t,AF,r===void 0?void 0:String(r))}function moe(e,t,r){UF(e,t,SF,r)}function BF(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 cF(e){return di(hr(fi(e),EF))}function dF(e){return di(hr(fi(e),NF))}function fF(e,t,r){var n,i,o,a;let s=fi(e);r.name!==Ec(e)&&(OF(e,r.name),PF(s,r.name));let l=di(hr(s,Kp)).trim().toLowerCase()==="true";if(((n=r.required)!==null&&n!==void 0?n:!1)!==l){let u=hr(s,Kp);if(!u)throw ui(`setting '${Kp}' on a step whose xaml does not expose that slot`);IF(u,t,r.required?"True":"False")}if(((i=r.fieldName)!==null&&i!==void 0?i:"")!==((o=RF(e))!==null&&o!==void 0?o:"")){let u=kF(e);if(!u)throw new Fn.InvalidArgumentError("BPF step has no <mcwb:Control> element to bind a column to");let c=(a=r.fieldName)!==null&&a!==void 0?a:"";uF(u,wF,vF,c),c!==""&&$F(u,sF,aF)===""&&uF(u,sF,aF,c)}}function pF(e,t,r,n){var i;let o=fi(e);if(!o)throw new Fn.InvalidArgumentError("BPF stage composite has no <\u2026ActivityReference.Properties>");if(r.name!==Ec(e)&&(OF(e,r.name),PF(o,r.name)),poe(o,t,r.category),moe(o,t,n),r.relationshipName&&r.relationshipName.trim()!=="")throw ui("a stage relationship / table change (multi-table authoring)");if(r.actions&&r.actions.length>0||r.branch)throw ui("stage actions or conditional branching");let a=FF(e);if(!a)throw new Fn.InvalidArgumentError("BPF stage has no [Activities] collection");let s=(i=r.steps)!==null&&i!==void 0?i:[];if(s.length===0)throw new Fn.InvalidArgumentError(`BPF stage '${r.name}' must have at least one step`);let l=jv(e);if(BF(l,s.map(d=>d.id),dF)){l.forEach((d,f)=>fF(d,t,s[f]));return}let u=new Map(l.map(d=>[dF(d),d]));if(ci(a).some(d=>!dl(d,DF)))throw ui("adding, removing or reordering steps on a stage that also contains branching or actions");let c=s.map(d=>{var f;return(f=u.get(d.id))!==null&&f!==void 0?f:foe(t,d)});MF(a,c),c.forEach((d,f)=>fF(d,t,s[f]))}function hoe(e,t,r){let n=ka(e,bF);if(!n)throw new Fn.InvalidArgumentError("BPF xaml has no <mxswa:Workflow> root activity");if(r.globalActions&&r.globalActions.length>0)throw ui("global (process-completed/abandoned) actions");if(!r.stages||r.stages.length===0)throw new Fn.InvalidArgumentError("a BPF must have at least one stage");let i=Xp(e),o=i.map(f=>f.el);if(BF(o,r.stages.map(f=>f.id),cF)){i.forEach(({el:f,entity:m},p)=>{let h=r.stages[p];if(h.entityLogicalName&&h.entityLogicalName.trim()!==""&&h.entityLogicalName!==m)throw ui(`changing a stage's table ('${h.entityLogicalName}' vs the process's '${m}')`);pF(f,t,h,h.nextStageId)});return}let a=ci(n).filter(f=>dl(f,_F));if(a.length!==1)throw ui("adding, removing or reordering stages on a multi-table process");let s=a[0],l=xF(s),u=FF(s);if(!u)throw new Fn.InvalidArgumentError("BPF primary entity composite has no [Activities] collection");if(ci(u).some(f=>!dl(f,TF)))throw ui("adding, removing or reordering stages on a process whose primary composite holds non-stage activities (multi-table nesting or advanced constructs)");for(let f of r.stages)if(f.entityLogicalName&&f.entityLogicalName.trim()!==""&&f.entityLogicalName!==l)throw ui(`a stage on a different table ('${f.entityLogicalName}') than the process primary ('${l}')`);let c=new Map(o.map(f=>[cF(f),f])),d=r.stages.map(f=>{var m;return(m=c.get(f.id))!==null&&m!==void 0?m:doe(t,f,l)});MF(u,d),d.forEach((f,m)=>{let p=m<d.length-1?r.stages[m+1].id:void 0;pF(f,t,r.stages[m],p)})}function Zp(e){let t=e.match(/^<\?xml[^>]*\?>\s*/),r=t?t[0]:"";return{prolog:r,body:e.slice(r.length)}}function goe(e){var t,r,n,i,o,a;(0,yF.installDomShim)();let s=(t=e.bag)===null||t===void 0?void 0:t.xaml;if(s){let f=new DOMParser().parseFromString("<root/>","text/xml"),m={n:"Activity",a:(0,qv.mergeAttrs)(s.a,[]),c:(0,qv.spliceChildren)(s.c,[])};return{root:(0,qv.rebuildRaw)(m,(0,Ra.domEngine)(f),null),prolog:(n=(r=e.bag)===null||r===void 0?void 0:r.xamlProlog)!==null&&n!==void 0?n:Vv,eol:(o=(i=e.bag)===null||i===void 0?void 0:i.xamlEol)!==null&&o!==void 0?o:"lf"}}let l=e.stages[0],u=(a=l?.steps)===null||a===void 0?void 0:a[0],c=Kv(e.entityLogicalName,(0,Mr.newId)(),l?.id&&l.id.trim()!==""?l.id:(0,Mr.newId)(),u?.id&&u.id.trim()!==""?u.id:(0,Mr.newId)()),{body:d}=Zp(c);return{root:(0,Ra.parseXmlRoot)(d,"<Activity/>"),prolog:Vv,eol:"lf"}}function yoe(e){let{root:t,prolog:r,eol:n}=goe(e);hoe(t,t.ownerDocument,e);let i=(0,Ra.serializeNode)(t);return n==="crlf"&&(i=i.replace(/\n/g,`\r
+`)),r+i}function boe(e){return e.uniqueName&&e.uniqueName.trim()!==""?e.uniqueName:`new_${(e.name||"businessprocessflow").toLowerCase().replace(/[^a-z0-9]/g,"")||"businessprocessflow"}`}var Yp=class{toArtifact(t){return t}fromArtifact(t){return t}fromApiResponse(t){var r,n;(0,yF.installDomShim)();let i=t,o=typeof i.xaml=="string"?i.xaml:"",a={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&&(a.uniqueName=String(i.uniquename)),i.description!=null&&i.description!==""&&(a.description=String(i.description)),i.processorder!=null&&i.processorder!==""&&(a.order=Number(i.processorder)),o.trim()!==""){let{prolog:s,body:l}=Zp(o),u=(0,Ra.parseXmlRoot)(l,"<Activity/>");a.stages=uoe(u),a.bag={xaml:(0,Ra.projectElementBag)(u),xamlProlog:s,xamlEol:/\r\n/.test(o)?"crlf":"lf"}}return a}toApiPayload(t){var r;let n={workflowid:t.id&&t.id.trim()!==""?t.id:(0,Mr.newId)(),name:t.name,uniquename:boe(t),primaryentity:t.entityLogicalName,xaml:yoe(t),category:Hp.WorkflowCategory.BusinessProcessFlow,type:Hp.WorkflowTypeCode.Definition,businessprocesstype:Hp.BusinessProcessType.BusinessFlow,scope:Hp.WorkflowScope.Organization,processorder:(r=t.order)!==null&&r!==void 0?r:Zie};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 Fn.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 o=t.stages&&t.stages.length>0?t.stages.map(hF):[hF({id:(0,Mr.newId)(),name:"New Stage",steps:[]})],a={id:t.id&&t.id.trim()!==""?t.id:(0,Mr.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:o};return t.uniqueName&&(a.uniqueName=t.uniqueName),t.description!==void 0&&(a.description=t.description),t.order!==void 0&&(a.order=t.order),t.globalActions!==void 0&&(a.globalActions=t.globalActions),t.securityRoles!==void 0&&(a.securityRoles=t.securityRoles),a}assignMissingIds(t){let r=Cc(t);(typeof r.id!="string"||r.id.trim()==="")&&(r.id=(0,Mr.newId)());for(let n of["stages","steps","actions","globalActions"]){let i=r[n];Array.isArray(i)&&i.forEach(o=>this.assignMissingIds(o))}return r}validate(t){let r=[],n=t.stages;if(n!==void 0&&!Array.isArray(n))return r.push((0,Hr.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,Hr.issue)("/stages","too-many-stages",`a BPF allows at most 30 stages, got ${i.length}`));let o=new Set,a=new Map;i.forEach((l,u)=>{let c=`/stages/${u}`,d=Cc(l),f=typeof d.id=="string"?d.id.trim():"";f===""?r.push((0,Hr.issue)(`${c}/id`,"stage-id-required","a stage needs an id")):a.has(f.toLowerCase())?r.push((0,Hr.issue)(`${c}/id`,"stage-id-duplicate",`two stages share the id '${d.id}' (also at /stages/${a.get(f.toLowerCase())})`)):a.set(f.toLowerCase(),u),typeof d.entityLogicalName=="string"&&d.entityLogicalName!==""&&o.add(d.entityLogicalName);let m=Array.isArray(d.steps)?d.steps:[];m.length===0&&r.push((0,Hr.issue)(`${c}/steps`,"stage-needs-step","a BPF stage must have at least one step")),m.length>30&&r.push((0,Hr.issue)(`${c}/steps`,"too-many-steps",`a stage allows at most 30 steps, got ${m.length}`));let p=new Map;m.forEach((h,g)=>{let b=`${c}/steps/${g}`,w=typeof Cc(h).id=="string"?h.id.trim():"";w===""?r.push((0,Hr.issue)(`${b}/id`,"step-id-required","a step needs an id")):p.has(w.toLowerCase())?r.push((0,Hr.issue)(`${b}/id`,"step-id-duplicate",`two steps in this stage share the id '${h.id}'`)):p.set(w.toLowerCase(),g)}),d.branch&&!mF(i,d.branch.nextStageId)&&r.push((0,Hr.issue)(`${c}/branch/nextStageId`,"branch-target-unknown",`branch nextStageId '${d.branch.nextStageId}' does not match any stage id`)),typeof d.nextStageId=="string"&&d.nextStageId!==""&&!mF(i,d.nextStageId)&&r.push((0,Hr.issue)(`${c}/nextStageId`,"next-stage-unknown",`nextStageId '${d.nextStageId}' does not match any stage id`))}),o.size>5&&r.push((0,Hr.issue)("/stages","too-many-tables",`a BPF spans at most 5 tables, got ${o.size}`));let s=voe(i);return s>=0&&r.push((0,Hr.issue)(`/stages/${s}/nextStageId`,"next-stage-cycle","the stage nextStageId links form a cycle; the flow must be acyclic")),r}};fl.BpfAdapter=Yp;function voe(e){let t=new Map(e.map(r=>[Cc(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 mF(e,t){return e.some(r=>Cc(r).id===t)}function hF(e){var t,r;let n=e.steps&&e.steps.length>0?e.steps.map(gF):[gF({id:(0,Mr.newId)(),name:"New Step"})],i={id:e.id&&e.id.trim()!==""?e.id:(0,Mr.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 gF(e){var t;let r={id:e.id&&e.id.trim()!==""?e.id:(0,Mr.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 Kv(e,t,r,n){return`${Vv}<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="${oF}" /></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="${oF}" /></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 woe(){return{adapter:new Yp,api:Xie.bpfApi,languageSensitive:!0}}fl.bpfRegistration=woe});var VF=v(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});em.buildRegistrations=void 0;var Coe=Lk(),Eoe=eL(),Aoe=x1(),Soe=e$(),Noe=N$(),_oe=W$(),Toe=sx(),Doe=Gx(),Ioe=qF();function Ooe(e){let t=new Map;return t.set("form",(0,Coe.formRegistration)(e)),t.set("view",(0,Eoe.viewRegistration)()),t.set("businessRule",(0,Aoe.businessRuleRegistration)()),t.set("app",(0,Soe.appRegistration)(e)),t.set("command",(0,Noe.commandRegistration)()),t.set("chart",(0,_oe.chartRegistration)()),t.set("dashboard",(0,Toe.dashboardRegistration)(e)),t.set("genPage",(0,Doe.genPageRegistration)()),t.set("bpf",(0,Ioe.bpfRegistration)()),t}em.buildRegistrations=Ooe});var rM=v(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE=Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE=Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE=Te.removeRowSummary=Te.configureRowSummary=Te.buildGptDynamicPrompt=Te.setAppAiFeatures=Te.getAiReadiness=Te.saveSettingValue=Te.retrieveSetting=Te.AI_GATE=void 0;var zi=Lt(),yn=ye(),qe=le(),GF=pt(),Ve=Q();Te.AI_GATE={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabled",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"EnableNLGridSearch",nlChart:"NLChartVisualizationSetting",summaries:"EnableFormInsights",m365:"m365copilotmodelappenabled"};var JF={formFill:"FormFillBarUXEnabled",formFillSuggestions:"FormPredictEnabled",formFillSmartPaste:"FormPredictSmartPasteEnabledOnByDefault",formFillFiles:"FormFillFileUploadEnabled",nlSearch:"NLGridSearchSetting",nlChart:"NLChartDataVisualizationSetting",m365:"m365copilotmodelappenabled"},Poe=new Set(Object.entries(Te.AI_GATE).filter(([e,t])=>JF[e]===t).map(([e])=>e)),Roe={formFill:{enabled:"2",disabled:"1"},formFillSuggestions:{enabled:"2",disabled:"1"},formFillSmartPaste:{enabled:"2",disabled:"1"},formFillFiles:{enabled:"2",disabled:"1"}};function Jv(e){return Roe[e]}var tm=1e6;function koe(e,t){let r=Jv(t),n=()=>{throw new Ve.InvalidArgumentError(`setAppAiFeatures: '${t}' must be a boolean or an integer between 0 and ${tm} (e.g. 0, 1, 2); got '${String(e)}'.`)},i=o=>r?o?r.enabled:r.disabled:o?"1":"0";if(typeof e=="boolean")return i(e);if(typeof e=="number")return!Number.isSafeInteger(e)||e<0||e>tm?n():String(e);if(typeof e=="string"){let o=e.trim(),a=o.toLowerCase();if(a==="true")return i(!0);if(a==="false")return i(!1);if(/^[0-9]+$/.test(o)){let s=o.replace(/^0+(?=[0-9])/,"");return s.length>String(tm).length||Number(s)>tm?n():s}}return n()}function Loe(e,t){let r=Jv(t);return r?e===r.enabled:e!=="0"}async function $oe(e,t){var r,n;let i=`/appmodules${(0,qe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,o=await e.get(i);if(o.status<200||o.status>=300)return;let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ve.ConnectionError(e.apiUrl(i),o.status,`the app lookup for '${t}' returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(a)}`);return(n=a[0])===null||n===void 0?void 0:n.appmoduleid}async function xoe(e,t){var r,n;let i=`/appmodules${(0,qe.odataQuery)([["$select","appmoduleid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,o;try{o=await e.get(i)}catch(l){throw new Ve.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(o.status<200||o.status>=300)throw new Ve.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned HTTP ${o.status}. Retry, or omit appModuleId to verify by name.`);let a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ve.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a malformed body.`);if(a.length===0)return;let s=(n=a[0])===null||n===void 0?void 0:n.appmoduleid;if(!s)throw new Ve.InvalidArgumentError(`setAppAiFeatures: cannot confirm that the supplied appModuleId belongs to app '${t}' \u2014 the lookup returned a row with no appmoduleid.`);return s}var WF=new WeakMap;async function Foe(e,t){var r,n;let i=WF.get(e);if(i||(i=new Map,WF.set(e,i)),i.has(t))return i.get(t);let o=`/settingdefinitions${(0,qe.odataQuery)([["$select","settingdefinitionid"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(t)}'`]])}`,a=await e.get(o);if(a.status<200||a.status>=300)return;let s=(r=a.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(s))throw new Ve.ConnectionError(e.apiUrl(o),a.status,`the setting definition lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(s)}`);let l=(n=s[0])===null||n===void 0?void 0:n.settingdefinitionid;return l&&i.set(t,l),l}async function Moe(e,t,r){var n,i;let o=await Foe(e,r);if(!t||!o)return;let a=`/appsettings/Microsoft.Dynamics.CRM.RetrieveUnpublishedMultiple()${(0,qe.odataQuery)([["$select","value,componentstate"],["$filter",`_parentappmoduleid_value eq ${t} and _settingdefinitionid_value eq ${o}`]])}`,s=await e.get(a);if(s.status<200||s.status>=300)return;let l=(n=s.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(l))throw new Ve.ConnectionError(e.apiUrl(a),s.status,`the app-scope override read returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(l)}`);let u=l;if(u.length===0)return{exists:!1};let c=(i=u.find(d=>d?.componentstate===1))!==null&&i!==void 0?i:u[0];return{exists:!0,value:c.value,pendingPublish:c.componentstate===1}}var Uoe=4,Boe=500,zF=20,jF=3e4;function qoe(e){if(e===void 0)return Uoe;if(!Number.isFinite(e))throw new Ve.InvalidArgumentError(`setAppAiFeatures: verifyAttempts must be a finite integer between 1 and ${zF}; got ${e}.`);return Math.min(zF,Math.max(1,Math.floor(e)))}function Voe(e){if(e===void 0)return Boe;if(!Number.isFinite(e))throw new Ve.InvalidArgumentError(`setAppAiFeatures: verifyDelayMs must be a finite number between 0 and ${jF}; got ${e}.`);return Math.min(jF,Math.max(0,Math.floor(e)))}async function Goe(e,t,r,n,i,o,a){let s,l,u,c=!1;for(let d=0;d<o;d+=1){d>0&&await new Promise(m=>setTimeout(m,a*d));let f;try{let m=await t();m?(f=await Moe(e,m,n),f===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){f=void 0,u=m.message}c=f!==void 0,l=f?.exists;try{s=(await rm(e,n,{appUniqueName:r})).value}catch{}if(f?.exists&&f.value===i)return{result:"proven",effectiveValue:f.value,appOverrideExists:!0,...f.pendingPublish?{pendingPublish:!0}:{}}}return c?{result:"absent",effectiveValue:s,appOverrideExists:l}:{result:"unverifiable",effectiveValue:s,appOverrideExists:void 0,reason:u}}function YF(e,t,r){if(t===2)return String(e).toLowerCase()==="true";let n=r?Jv(r):void 0;return n?e===n.enabled:e!=null&&e!=="0"&&e!==""}async function rm(e,t,r={}){var n;let i=[`SettingName='${(0,qe.odataPathLiteral)(t)}'`];r.appUniqueName&&i.push(`AppUniqueName='${(0,qe.odataPathLiteral)(r.appUniqueName)}'`);let o=`/RetrieveSetting(${i.join(",")})`,a=(0,yn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.SettingDetail;if(s===null||typeof s!="object"||Array.isArray(s)||!("Value"in s))throw new Ve.ConnectionError(e.apiUrl(o),a.status,`RetrieveSetting for '${t}' returned a malformed answer \u2014 expected a SettingDetail with a Value`);let{Value:l,DataType:u}=s;return{value:l,dataType:u}}Te.retrieveSetting=rm;async function QF(e,t,r,n={}){let i={SettingName:t,Value:r};n.appUniqueName&&(i.AppUniqueName=n.appUniqueName),n.solutionUniqueName&&(i.SolutionUniqueName=n.solutionUniqueName),(0,yn.ensureSuccess)(await e.post("/SaveSettingValue",i),e.apiUrl("/SaveSettingValue"))}Te.saveSettingValue=QF;async function Woe(e,t={}){let r={};for(let[n,i]of Object.entries(Te.AI_GATE)){let{value:o,dataType:a}=await rm(e,i,t);r[n]={enabled:YF(o,a,n),setting:i,value:o}}return r}Te.getAiReadiness=Woe;async function zoe(e,t,r,n={}){var i;if(!t||!t.trim())throw new Ve.InvalidArgumentError("setAppAiFeatures: a non-empty appUniqueName is required (an empty value would write the setting at organization scope, affecting every app).");let o=qoe(n.verifyAttempts),a=Voe(n.verifyDelayMs),s=[];for(let[p,h]of Object.entries(r)){if(h===void 0)continue;let g=JF[p];g&&s.push({feature:p,setting:g,requestedValue:koe(h,p)})}let l=[],u=n.appModuleId?(0,qe.normalizeGuid)(n.appModuleId,"appModuleId"):void 0;if(u){let p=await xoe(e,t);if(p&&(0,qe.normalizeGuid)(p,"appModuleId")!==u)throw new Ve.InvalidArgumentError(`setAppAiFeatures: appModuleId '${u}' does not belong to app '${t}' (which resolves to '${p}'). Settings are written by unique name, so verifying against a different app would report success for a write that never landed.`)}let c,d=async()=>u||(c||(c=await $oe(e,t)),c),f=new Map,m=async p=>{if(Poe.has(p))return;let h=Te.AI_GATE[p];if(h){if(!f.has(h))try{let{value:g,dataType:b}=await rm(e,h);f.set(h,{enabled:YF(g,b,p),setting:h,value:g})}catch{f.set(h,void 0)}return f.get(h)}};for(let{feature:p,setting:h,requestedValue:g}of s)try{await QF(e,h,g,{appUniqueName:t,solutionUniqueName:n.solutionUniqueName});let b=await Goe(e,d,t,h,g,o,a),w={feature:p,setting:h,requestedValue:g,effectiveValue:b.effectiveValue,appOverrideExists:b.appOverrideExists};if(b.result==="proven")l.push({...w,status:"applied",...b.pendingPublish?{pendingPublish:!0}:{}});else if(b.result==="absent"){let C=Loe(g,p)?await m(p):void 0;C&&!C.enabled?l.push({...w,status:"skipped",reason:`the write was issued and no app-scope override holding '${g}' was observed for '${h}' after ${o} attempt(s); the org readiness gate '${C.setting}' reads '${C.value}', so an environment admin must enable it before this app can turn the feature on`}):l.push({...w,status:"notPersisted",reason:`the write reported success but no app-scope override holding '${g}' was observed for '${h}' after ${o} attempt(s) \u2014 ${b.effectiveValue===void 0?"the value in effect for this app could not be read":`it reads '${b.effectiveValue}' for this app`} (Dataverse can accept an app-scope write without storing it)`})}else l.push({...w,status:"unverified",reason:`the write was issued but could not be confirmed: ${(i=b.reason)!==null&&i!==void 0?i:"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(b){l.push({feature:p,setting:h,requestedValue:g,status:"failed",reason:b.message})}return{applied:l.filter(p=>p.status==="applied").map(p=>p.feature),skipped:l.filter(p=>p.status==="skipped").map(p=>p.feature),notPersisted:l.filter(p=>p.status==="notPersisted").map(p=>p.feature),unverified:l.filter(p=>p.status==="unverified").map(p=>p.feature),failed:l.filter(p=>p.status==="failed").map(p=>p.feature),outcomes:l}}Te.setAppAiFeatures=zoe;var XF="GptPowerPrompt",joe='{ "consumptionSource": "Api", "partnerSource": "AIBuilder", "consumptionSourceVersion": "GptApiClient"}';function ZF(e){var t,r,n,i;let o=e.entityLogicalName,a=[{type:"literal",text:e.instruction.replace(/\s*$/,"")+" "}];return e.columns.forEach((s,l)=>{a.push({type:"data",id:`${o}.${s.logical}`,text:s.display}),l<e.columns.length-1&&a.push({type:"literal",text:", "})}),{version:"GptDynamicPrompt-2",prompt:a,definitions:{inputs:[{id:"RecordId",text:"RecordId",type:"text"},{id:"LanguageCode",text:"LanguageCode",type:"text"}],formulas:[],data:[{id:o,displayName:o,type:"dataverseTable",filters:[{filterType:"equal",attribute:e.primaryKey,valueType:"inputVariable",value:"RecordId"}]}],output:{formats:[(t=e.outputFormat)!==null&&t!==void 0?t:"text"]}},modelParameters:{modelType:"default",gptParameters:{temperature:(r=e.temperature)!==null&&r!==void 0?r:0}},settings:{recordRetrievalLimit:(n=e.recordRetrievalLimit)!==null&&n!==void 0?n:30,shouldPreserveRecordLinks:null,runtime:null,enableReasoning:(i=e.enableReasoning)!==null&&i!==void 0?i:!0},code:"",signature:""}}Te.buildGptDynamicPrompt=ZF;async function Hoe(e,t){var r;let n=`/EntityDefinitions(LogicalName='${(0,qe.odataPathLiteral)(t)}')${(0,qe.odataQuery)([["$select","MetadataId"]])}`,i=(0,yn.ensureSuccess)(await e.get(n),e.apiUrl(n)),o=(r=i.body)===null||r===void 0?void 0:r.MetadataId;if(typeof o!="string"||o==="")throw new Ve.ConnectionError(e.apiUrl(n),i.status,`the table metadata read for '${t}' returned a malformed answer \u2014 expected a MetadataId but got ${o===""?"an empty string":(0,zi.describeMalformedValue)(o)}`);return o}function Yv(e,t,r,n){if(e.length===0)return;let i=e[0];if(typeof i!="object"||i===null||Array.isArray(i))throw new Ve.ConnectionError(t,r,`${n} returned a malformed row \u2014 expected an object but got ${Array.isArray(i)?"an array":(0,zi.describeMalformedValue)(i)}`);return i}async function eM(e){var t;let r=`/msdyn_aitemplates${(0,qe.odataQuery)([["$select","msdyn_aitemplateid"],["$filter",`msdyn_uniquename eq '${XF}'`],["$top",1]])}`,n=(0,yn.ensureSuccess)(await e.get(r),e.apiUrl(r)),i=(t=n.body)===null||t===void 0?void 0:t.value;if(!Array.isArray(i))throw new Ve.ConnectionError(e.apiUrl(r),n.status,`the row-summary template lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(i)}`);let o=Yv(i,e.apiUrl(r),n.status,"the row-summary template lookup");if(!o)return;let a=o.msdyn_aitemplateid;if(typeof a=="string"&&a!=="")try{return(0,qe.normalizeGuid)(a,"msdyn_aitemplateid")}catch{}throw new Ve.ConnectionError(e.apiUrl(r),n.status,`the row-summary template lookup returned a malformed row \u2014 expected a GUID 'msdyn_aitemplateid' but got ${a===""?"an empty string":typeof a=="string"?"a string that is not a GUID":(0,zi.describeMalformedValue)(a)}`)}function tM(e){return`${e} row summary`}async function Koe(e,t,r){var n;let i=`/msdyn_aimodels(${t})${(0,qe.odataQuery)([["$select","msdyn_name,_msdyn_templateid_value"]])}`,o=await e.get(i);if(o.status===404)return!1;let a=(n=(0,yn.ensureSuccess)(o,e.apiUrl(i)).body)!==null&&n!==void 0?n:{},s=await eM(e);return typeof a.msdyn_name=="string"&&a.msdyn_name.toLowerCase()===tM(r).toLowerCase()&&typeof a._msdyn_templateid_value=="string"&&s!==void 0&&a._msdyn_templateid_value.toLowerCase()===s.toLowerCase()}async function Joe(e,t,r={}){var n;let i=`ais_RowSummary_${t.entityLogicalName}`,o=`/aiskillconfigs${(0,qe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(i)}'`],["$top",1]])}`,a=(0,yn.ensureSuccess)(await e.get(o),e.apiUrl(o)),s=(n=a.body)===null||n===void 0?void 0:n.value;if(!Array.isArray(s))throw new Ve.ConnectionError(e.apiUrl(o),a.status,`the existing row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(s)}`);let l=Yv(s,e.apiUrl(o),a.status,"the existing row-summary skill lookup");if(l)return{modelId:l._aimodel_value,aiSkillConfigId:l.aiskillconfigid};let u=await Hoe(e,t.entityLogicalName),c=await eM(e);if(c===void 0)throw new Ve.SdkError(Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE,`Cannot configure the row summary of '${t.entityLogicalName}': this org has no AI template '${XF}' (msdyn_aitemplates), which a row-summary model is built from. Nothing was written.`);let d=(0,GF.newId)(),f=(0,GF.newId)(),m=JSON.stringify(ZF(t)),p={ModelId:d,RunConfigurationId:f,ModelName:tM(t.entityLogicalName),TemplateId:c,CustomConfiguration:m,Source:joe,RunConfiguration:""};(0,yn.ensureSuccess)(await e.post("/AIModelPublish",p),e.apiUrl("/AIModelPublish"));try{let h={uniquename:i,description:`${t.entityLogicalName} row summary`,"[email protected]":`/entities(${u})`,"[email protected]":`/msdyn_aimodels(${d})`,aiskill:"RowSummary"},g=(0,yn.ensureSuccess)(await e.post("/aiskillconfigs",h),e.apiUrl("/aiskillconfigs")),b=(0,yn.requireCreatedId)(g,"aiskillconfigid","row-summary skill");return{modelId:d,aiSkillConfigId:b}}catch(h){try{await e.delete(`/msdyn_aimodels(${d})`)}catch{}throw h}}Te.configureRowSummary=Joe;async function Yoe(e,t){var r;let n=`ais_RowSummary_${t.entityLogicalName}`,i=`/aiskillconfigs${(0,qe.odataQuery)([["$select","aiskillconfigid,_aimodel_value"],["$filter",`uniquename eq '${(0,qe.odataLiteral)(n)}'`],["$top",1]])}`,o=(0,yn.ensureSuccess)(await e.get(i),e.apiUrl(i)),a=(r=o.body)===null||r===void 0?void 0:r.value;if(!Array.isArray(a))throw new Ve.ConnectionError(e.apiUrl(i),o.status,`the row-summary skill lookup returned a malformed answer \u2014 expected an OData 'value' array but got ${(0,zi.describeMalformedValue)(a)}`);let s=Yv(a,e.apiUrl(i),o.status,"the row-summary skill lookup");if(!s)return{removed:!1};let l=(0,qe.normalizeGuid)(s.aiskillconfigid,"aiskillconfigid"),u=s._aimodel_value?(0,qe.normalizeGuid)(s._aimodel_value,"_aimodel_value"):void 0,c=u?await Koe(e,u,t.entityLogicalName):!1,d=t.entityLogicalName,f=`/aiskillconfigs(${l})`,m=await HF(e,f,`${f}${(0,qe.odataQuery)([["$select","aiskillconfigid"]])}`);if(m.kind==="failed")throw m.stillThere===void 0&&u&&c?(0,Ve.attachCause)(new Ve.SdkError(Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE,`Removing the row summary of '${d}' could not be confirmed: deleting its skill row failed (${KF(m.failure)}) and the row could not be read back. If it is gone, its AI model '${u}' is left behind, unreferenced. Retry removeRowSummary: while the skill row exists it removes both; once it is gone, delete that model.`),m.failure):m.failure;if(u&&c){let p=`/msdyn_aimodels(${u})`,h=await HF(e,p,`${p}${(0,qe.odataQuery)([["$select","msdyn_aimodelid"]])}`,Xoe);if(h.kind==="failed")throw(0,Ve.attachCause)(new Ve.SdkError(Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE,`The row summary of '${d}' was removed, but its AI model '${u}' ${h.stillThere?"was not deleted":"could not be confirmed deleted"} (${KF(h.failure)}). The model is no longer used by the row summary; delete it before configuring a row summary for '${d}' again, which needs its name.`),h.failure)}return{removed:!0}}Te.removeRowSummary=Yoe;Te.ROW_SUMMARY_MODEL_NOT_DELETED_CODE="ROW_SUMMARY_MODEL_NOT_DELETED";Te.ROW_SUMMARY_REMOVAL_UNCONFIRMED_CODE="ROW_SUMMARY_REMOVAL_UNCONFIRMED";Te.ROW_SUMMARY_TEMPLATE_NOT_FOUND_CODE="ROW_SUMMARY_TEMPLATE_NOT_FOUND";var Qoe="0x8004f01f";function Xoe(e){var t,r;let n=(r=(t=e.body)===null||t===void 0?void 0:t.error)===null||r===void 0?void 0:r.code;return e.status===400&&typeof n=="string"&&n.toLowerCase()===Qoe}function Zoe(e){if(e.status!==400&&e.status!==500||e.body===void 0||e.body===null)return!1;let t=typeof e.body=="string"?e.body:JSON.stringify(e.body);return/chosen as the deadlock victim|\bSql Number:\s*1205\b/i.test(t)}async function HF(e,t,r,n=()=>!1){let i;try{let o=await(0,yn.resendWhile)(Zoe,()=>e.delete(t));if(o.status>=200&&o.status<300||o.status===404)return{kind:"gone"};if(n(o))return{kind:"kept"};try{(0,yn.ensureSuccess)(o,e.apiUrl(t))}catch(a){i=a}}catch(o){i=o}try{let o=await e.get(r);return o.status===404?{kind:"gone"}:{kind:"failed",failure:i,stillThere:o.status>=200&&o.status<300?!0:void 0}}catch{return{kind:"failed",failure:i,stillThere:void 0}}}function KF(e){return e instanceof Error?e.message:String(e)}});var oM=v(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});pl.findArtifact=pl.resolveArtifact=void 0;var qt=le(),ji=$d(),eae=zd(),tae=Lt(),rae=ye(),nM=Q();async function iM(e,t,r){let n="/uxagentprojects"+(0,qt.odataQuery)([["$select","uxagentprojectid,name"],["$filter",`name eq '${(0,qt.odataLiteral)(t)}'`],...r!==void 0?[["$top",String(r)]]:[]]);return(await(0,tae.collectPages)(e,n,"resolveArtifact('genPage')",void 0,{headers:{"MSCRM.IncludeUnpublished":"true"}})).map(o=>({id:String(o.uxagentprojectid),name:String(o.name)}))}async function nae(e,t,r){var n,i,o,a,s,l,u,c,d,f,m,p;switch(t){case"app":{let h=(0,eae.unpublishedAppModulesQuery)("appmoduleid,name,appmoduleidunique",`uniquename eq '${(0,qt.odataLiteral)((n=r.uniqueName)!==null&&n!==void 0?n:"")}'`,1),b=(i=(0,rae.ensureSuccess)(await e.get(h),e.apiUrl(h)).body)===null||i===void 0?void 0:i.value,w=b&&b[0];return w?[{id:String(w.appmoduleid),name:String(w.name),appModuleIdUnique:String(w.appmoduleidunique)}]:[]}case"dashboard":return(await(0,ji.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,qt.odataLiteral)((o=r.name)!==null&&o!==void 0?o:"")}' and type eq 0`,top:10})||[]).map(g=>({id:String(g.formid),name:String(g.name)}));case"command":{if(!r.entity)return[];let h=await(0,ji.queryRecords)(e,"appaction",{select:["appactionid","buttonlabeltext"],filter:`contextvalue eq '${(0,qt.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?[{id:r.entity,entity:r.entity}]:[]}case"form":return(await(0,ji.queryRecords)(e,"systemform",{select:["formid","name"],filter:`name eq '${(0,qt.odataLiteral)((a=r.name)!==null&&a!==void 0?a:"")}' and objecttypecode eq '${(0,qt.odataLiteral)((s=r.entity)!==null&&s!==void 0?s:"")}'`,top:10})||[]).map(g=>({id:String(g.formid),name:String(g.name)}));case"chart":return(await(0,ji.queryRecords)(e,"savedqueryvisualization",{select:["savedqueryvisualizationid","name"],filter:`name eq '${(0,qt.odataLiteral)((l=r.name)!==null&&l!==void 0?l:"")}' and primaryentitytypecode eq '${(0,qt.odataLiteral)((u=r.entity)!==null&&u!==void 0?u:"")}'`,top:10})||[]).map(g=>({id:String(g.savedqueryvisualizationid),name:String(g.name)}));case"view":return(await(0,ji.queryRecords)(e,"savedquery",{select:["savedqueryid","name"],filter:`name eq '${(0,qt.odataLiteral)((c=r.name)!==null&&c!==void 0?c:"")}' and returnedtypecode eq '${(0,qt.odataLiteral)((d=r.entity)!==null&&d!==void 0?d:"")}'`,top:10})||[]).map(g=>({id:String(g.savedqueryid),name:String(g.name)}));case"webResource":return(await(0,ji.queryRecords)(e,"webresource",{select:["webresourceid","name"],filter:`name eq '${(0,qt.odataLiteral)((f=r.name)!==null&&f!==void 0?f:"")}'`,top:1})||[]).map(g=>({id:String(g.webresourceid),name:String(g.name)}));case"solution":return(await(0,ji.queryRecords)(e,"solution",{select:["solutionid","uniquename"],filter:`uniquename eq '${(0,qt.odataLiteral)((m=r.uniqueName)!==null&&m!==void 0?m:"")}'`,top:1})||[]).map(g=>({id:String(g.solutionid),name:String(g.uniquename)}));case"genPage":return iM(e,(p=r.name)!==null&&p!==void 0?p:"");default:return[]}}pl.resolveArtifact=nae;async function iae(e,t,r){var n,i,o,a,s,l;let u=(0,qt.odataLiteral)((n=r.name)!==null&&n!==void 0?n:""),c=(0,qt.odataLiteral)((i=r.entity)!==null&&i!==void 0?i:"");if(t==="command"){if(!r.entity)return null;let h=await(0,ji.queryRecords)(e,"appaction",{select:["appactionid"],filter:`contextvalue eq '${(0,qt.odataLiteral)(r.entity)}'`,top:1});return h&&h.length?r.entity:null}if(t==="genPage"){let h=await iM(e,(o=r.name)!==null&&o!==void 0?o:"",2);if(h.length>1)throw new nM.AmbiguousArtifactError(t,(a=r.name)!==null&&a!==void 0?a:"",h.length);return h.length===1?h[0].id:null}let d=oae(t,u,c,r),f=t!=="app",m=await(0,ji.queryRecords)(e,d.set,{select:[d.idField],filter:d.filter,top:f?2:1});if(f&&m&&m.length>1)throw new nM.AmbiguousArtifactError(t,(l=(s=r.name)!==null&&s!==void 0?s:r.uniqueName)!==null&&l!==void 0?l:"",m.length);let p=m&&m[0]&&m[0][d.idField];return p!=null?String(p):null}pl.findArtifact=iae;function oae(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,qt.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 sM=v(im=>{"use strict";Object.defineProperty(im,"__esModule",{value:!0});im.seedRecordGraph=void 0;var aM=$d(),aae=bd(),nm=le(),sae=Q();async function lae(e,t,r={}){var n,i,o,a,s;let l=(n=r.createdIds)!==null&&n!==void 0?n:{},u=(i=r.entitySetFor)!==null&&i!==void 0?i:(f=>(0,aae.resolveEntitySetName)(e,f)),c={},d=f=>{var m;return(m=c[f])!==null&&m!==void 0?m:l[f]};for(let f of t){let m=f.entityLogical.toLowerCase(),p=(o=f.matchOn)===null||o===void 0?void 0:o.toLowerCase(),h=[];for(let k of f.records){let I={...k.body};for(let D of(a=k.binds)!==null&&a!==void 0?a:[]){let P=D.parentEntity.toLowerCase(),x=(s=d(P))===null||s===void 0?void 0:s[D.parentIndex];if(!x)throw new sae.InvalidArgumentError(`Cannot resolve bind '${D.navProperty}' on a '${m}' record: parent '${D.parentEntity}'[${D.parentIndex}] has no created id. Seed the parent group before the child, or supply it via options.createdIds.`);let K=(0,nm.assertODataName)(await u(P),`entity set for parent '${D.parentEntity}'`),Oe=(0,nm.normalizeGuid)(x,`parent id for bind '${D.navProperty}'`);I[`${D.navProperty}@odata.bind`]=`/${K}(${Oe})`}h.push(I)}let g=p?h.map(k=>{let I=k[p];return I!=null&&I!==""?String(I):null}):h.map(()=>null),b=new Map;if(p){let k=(0,nm.assertODataName)(p,"RecordGraph matchOn key"),I=[...new Set(g.filter(D=>D!==null))];if(I.length){let D=I.map(x=>`${k} eq '${(0,nm.odataLiteral)(x)}'`).join(" or "),P=await(0,aM.queryRecords)(e,m,{select:[k,`${m}id`],filter:D,top:5e3});for(let x of P??[]){let K=x[k];K!=null&&b.set(String(K).toLowerCase(),String(x[`${m}id`]))}}}let w=[],C=new Map,S=h.map((k,I)=>{let D=g[I];if(D&&b.has(D.toLowerCase()))return null;if(D){let P=D.toLowerCase(),x=C.get(P);if(x!==void 0)return x;let K=w.push(k)-1;return C.set(P,K),K}return w.push(k)-1}),O=w.length?await(0,aM.createRecordsBulk)(e,m,w):[];c[m]=h.map((k,I)=>{let D=g[I];return D&&b.has(D.toLowerCase())?b.get(D.toLowerCase()):O[S[I]]})}return{createdIds:c}}im.seedRecordGraph=lae});var yM=v(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.getEntityPrivileges=tr.addEntityPrivilegesToRole=tr.deleteSecurityRole=tr.createPersonaRole=tr.createSecurityRole=tr.SDK_ROLE_MARKER=void 0;var Mn=ye(),Rt=le(),Kr=Q(),om={read:"Read",create:"Create",write:"Write",delete:"Delete",append:"Append",appendTo:"AppendTo",assign:"Assign",share:"Share"},Xv={user:"Basic",businessUnit:"Local",parentChild:"Deep",organization:"Global"},lM={user:1,businessUnit:2,parentChild:3,organization:4},Qv={user:"CanBeBasic",businessUnit:"CanBeLocal",parentChild:"CanBeDeep",organization:"CanBeGlobal"};tr.SDK_ROLE_MARKER="Authored by @maker-studio/cds-maker-sdk (persona/security role).";function uae(e){return Object.prototype.hasOwnProperty.call(om,e)?om[e]:void 0}function cae(e){return Object.prototype.hasOwnProperty.call(Xv,e)}var uM=new WeakMap,cM=new WeakMap;async function pM(e,t){var r,n;(0,Rt.assertODataName)(t,"entity logical name");let i=uM.get(e);i||(i=new Map,uM.set(e,i));let o=i.get(t);if(o)return o;let a=`/EntityDefinitions(LogicalName='${(0,Rt.odataPathLiteral)(t)}')${(0,Rt.odataQuery)([["$select","LogicalName,Privileges"]])}`,l=(n=(r=(0,Mn.ensureSuccess)(await e.get(a),e.apiUrl(a)).body)===null||r===void 0?void 0:r.Privileges)!==null&&n!==void 0?n:[];if(l.length===0)throw new Kr.InvalidArgumentError(`Entity '${t}' exposes no privileges (unknown or non-securable entity).`);return i.set(t,l),l}async function dae(e){var t,r,n;let i=cM.get(e);if(i)return i;let o=`/businessunits${(0,Rt.odataQuery)([["$select","businessunitid"],["$filter","_parentbusinessunitid_value eq null"],["$top",1]])}`,l=(n=((r=(t=(0,Mn.ensureSuccess)(await e.get(o),e.apiUrl(o)).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 Kr.InvalidArgumentError("Could not resolve the root business unit.");let u=(0,Rt.normalizeGuid)(l,"businessUnitId");return cM.set(e,u),u}async function mM(e,t){var r;let n=new Map;for(let i of t){if(!i.access||i.access.length===0)throw new Kr.InvalidArgumentError(`Entity '${i.entity}' privilege request has no access levels.`);let o=(r=i.scope)!==null&&r!==void 0?r:"user";if(!cae(o))throw new Kr.InvalidArgumentError(`Unknown privilege scope '${o}' for entity '${i.entity}'.`);let a=await pM(e,i.entity);for(let s of i.access){let l=uae(s);if(!l)throw new Kr.InvalidArgumentError(`Unknown access level '${s}' for entity '${i.entity}'.`);let u=a.find(p=>p.PrivilegeType===l);if(!u)throw new Kr.InvalidArgumentError(`Entity '${i.entity}' does not support '${s}' access.`);let c=Qv[o];if(u[c]===!1)throw new Kr.InvalidArgumentError(`Privilege '${u.Name}' on '${i.entity}' does not support the '${o}' scope.`);let d=(0,Rt.normalizeGuid)(u.PrivilegeId,"PrivilegeId"),f=n.get(d);if(!f){n.set(d,{privilegeName:u.Name,privilegeType:l,scope:o,entities:new Set([i.entity])});continue}if(f.scope===o){f.entities.add(i.entity);continue}if(!(f.entities.size===1&&f.entities.has(i.entity))){let p=[...f.entities].sort().join(", ");throw new Kr.InvalidArgumentError(`Entities '${p}' 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.`)}f.scope=lM[o]>lM[f.scope]?o:f.scope}}return[...n.entries()].map(([i,o])=>({entity:[...o.entities].sort().join(", "),privilegeId:i,privilegeName:o.privilegeName,privilegeType:o.privilegeType,scope:o.scope}))}async function fae(e,t,r,n){if(r.length===0&&!n)return;let i={Privileges:r.map(a=>({Depth:Xv[a.scope],PrivilegeId:a.privilegeId}))},o=`/roles(${t})/Microsoft.Dynamics.CRM.ReplacePrivilegesRole`;(0,Mn.ensureSuccess)(await e.post(o,i),e.apiUrl(o))}async function dM(e,t,r,n,i){var o,a;let s=`/${t}(${r})/${n}${(0,Rt.odataQuery)([["$select","roleid"],["$filter",`roleid eq ${i}`]])}`;return((a=(o=(0,Mn.ensureSuccess)(await e.get(s),e.apiUrl(s)).body)===null||o===void 0?void 0:o.value)!==null&&a!==void 0?a:[]).length>0}async function pae(e,t,r){var n,i;let o=[],a=[],s={"@odata.id":e.apiUrl(`/roles(${t})`)};for(let l of(n=r?.teams)!==null&&n!==void 0?n:[]){let u=(0,Rt.normalizeGuid)(l,"teamId");if(!await dM(e,"teams",u,"teamroles_association",t)){let c=`/teams(${u})/teamroles_association/$ref`;(0,Mn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}o.push(u)}for(let l of(i=r?.users)!==null&&i!==void 0?i:[]){let u=(0,Rt.normalizeGuid)(l,"userId");if(!await dM(e,"systemusers",u,"systemuserroles_association",t)){let c=`/systemusers(${u})/systemuserroles_association/$ref`;(0,Mn.ensureSuccess)(await e.post(c,s),e.apiUrl(c))}a.push(u)}return{teams:o,users:a}}async function fM(e,t,r){var n,i;let o=`/roles${(0,Rt.odataQuery)([["$select","roleid,description,ismanaged"],["$filter",`name eq '${(0,Rt.odataLiteral)(t)}' and _businessunitid_value eq ${r}`]])}`,l=((i=(n=(0,Mn.ensureSuccess)(await e.get(o),e.apiUrl(o)).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 f;return d.ismanaged!==!0&&((f=d.description)!==null&&f!==void 0?f:"")===tr.SDK_ROLE_MARKER};if(l.some(d=>!u(d)))throw new Kr.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 Kr.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,Rt.normalizeGuid)(c,"roleId"):void 0}function mae(e){var t,r;return{teams:((t=e?.teams)!==null&&t!==void 0?t:[]).map(n=>(0,Rt.normalizeGuid)(n,"teamId")),users:((r=e?.users)!==null&&r!==void 0?r:[]).map(n=>(0,Rt.normalizeGuid)(n,"userId"))}}function hM(e){return e.map(t=>({entity:t.entity,privilegeName:t.privilegeName,privilegeType:t.privilegeType,scope:t.scope}))}async function gM(e,t){var r,n;let i=(r=t.name)===null||r===void 0?void 0:r.trim();if(!i)throw new Kr.InvalidArgumentError("createSecurityRole: a non-empty role name is required.");let o=t.businessUnitId?(0,Rt.normalizeGuid)(t.businessUnitId,"businessUnitId"):await dae(e),a=await mM(e,(n=t.privileges)!==null&&n!==void 0?n:[]),s=mae(t.assignTo),l=await fM(e,i,o),u=l!==void 0;if(!l){let d="/roles",f={name:i,description:tr.SDK_ROLE_MARKER,"[email protected]":`/businessunits(${o})`};try{let m=(0,Mn.ensureSuccess)(await e.post(d,f),e.apiUrl(d));l=(0,Rt.normalizeGuid)((0,Mn.requireCreatedId)(m,"roleid","role"),"roleId")}catch(m){let p;try{p=await fM(e,i,o)}catch{p=void 0}if(!p)throw m;l=p}}await fae(e,l,a,u);let c=await pae(e,l,s);return{roleId:l,name:i,reused:u,appliedPrivileges:hM(a),assignedTeams:c.teams,assignedUsers:c.users}}tr.createSecurityRole=gM;async function hae(e,t){var r,n;let i=(r=t.persona)===null||r===void 0?void 0:r.trim();if(!i)throw new Kr.InvalidArgumentError("createPersonaRole: a non-empty persona name is required.");let o=[...t.jobs.flatMap(a=>{var s;return(s=a.privileges)!==null&&s!==void 0?s:[]}),...(n=t.additionalPrivileges)!==null&&n!==void 0?n:[]];return gM(e,{name:i,businessUnitId:t.businessUnitId,privileges:o,assignTo:t.assignTo})}tr.createPersonaRole=hae;async function gae(e,t){let n=`/roles(${(0,Rt.normalizeGuid)(t,"roleId")})`;(0,Mn.ensureSuccess)(await e.delete(n),e.apiUrl(n))}tr.deleteSecurityRole=gae;async function yae(e,t,r){let n=(0,Rt.normalizeGuid)(t,"roleId");if(r.length===0)throw new Kr.InvalidArgumentError("addEntityPrivilegesToRole requires at least one entity privilege (an empty grant would be a silent no-op).");let i=await mM(e,r),o={Privileges:i.map(s=>({Depth:Xv[s.scope],PrivilegeId:s.privilegeId}))},a=`/roles(${n})/Microsoft.Dynamics.CRM.AddPrivilegesRole`;return(0,Mn.ensureSuccess)(await e.post(a,o),e.apiUrl(a)),hM(i)}tr.addEntityPrivilegesToRole=yae;var bae=new Map(Object.keys(om).map(e=>[om[e],e]));async function vae(e,t){return(await pM(e,t)).map(n=>{let i=Object.keys(Qv).filter(a=>n[Qv[a]]!==!1),o=bae.get(n.PrivilegeType);return{name:n.Name,privilegeId:n.PrivilegeId,privilegeType:n.PrivilegeType,...o?{access:o}:{},scopes:i}})}tr.getEntityPrivileges=vae});var LM=v(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.createMakerSdk=yr.MakerSdk=yr.PUSH_NOT_ATTEMPTED_CODE=yr.ALREADY_EXISTS_CODE=void 0;var bM=Fm(),vM=Qr(),Z=Q(),bn=Ma(),wae=MC(),OM=zC(),ml=QC(),Cae=Um(),Eae=bE(),hl=CE(),Aae=$E(),Sae=qE(),Nae=bA(),wM=mS(),kt=bd(),Zv=_g(),CM=_N(),am=ru(),Hi=$d(),sm=$N(),gl=Fd(),_ae=Ud(),rr=Tg(),Tae=$g(),Dae=zg(),EM=xg(),Iae=VF(),lm=pt(),Oae=Jo(),pi=qb(),vn=Wm(),ew=_v(),Pae=3e5,gr=ye(),La=le(),yl=rM(),AM=oM(),Rae=sM(),kae=nb(),Ac=yM(),PM=Symbol("cds-maker-sdk.committedWrite");function Lae(e){return typeof e=="object"&&e!==null&&(e[PM]=!0),e}function $ae(e){return typeof e=="object"&&e!==null&&e[PM]===!0}var xae={fileConcurrency:1},tw="SOLUTION_COMPONENT_UNCLASSIFIED",Fae=2,Mae=4,Uae="This table is in the solution with ALL its subcomponents. Those are members the solution does not list one by one, so fetchSolution did not enumerate or fetch them: none of its forms, views, charts or dashboards were fetched here. To fetch them, read the table's logical name from its metadata (EntityDefinitions(<componentId>), $select=LogicalName), list each kind with fetchArtifactList \u2014 'form' with formTypes Main, QuickView, QuickCreate and Card; 'view'; 'chart'; 'dashboard' \u2014 passing { entityLogicalName }, and fetch each listed id with fetchArtifact: listing returns ids and names only.";function SM(e){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"unsupported",...e.includesAllSubcomponents?{detail:Uae}:{}}}function NM(e,t){return{componentId:e.objectId,componentType:e.componentType,workflowCategory:e.workflowCategory,reason:"failed",error:Ro(t)}}function _M(e,t,r){let n=r;return{type:e,id:t.objectId,name:typeof n.name=="string"?n.name:t.objectId,entityLogicalName:typeof n.entityLogicalName=="string"?n.entityLogicalName:void 0,lastFetched:(0,gr.nowIso)(),isDirty:!1}}var Bae=new Set(["entity","appmodule","dashboard","uxagentproject"]);function qae(e){var t;let r={entity:[],appmodule:[],dashboard:[],uxagentproject:[]},n=new Set,i=(s,l)=>{let u=`${s}\0${l.toLowerCase()}`;n.has(u)||(n.add(u),r[s].push(l))};for(let{scope:s}of e)if(s?.envelope==="entity")s.entityLogicalName&&i("entity",s.entityLogicalName);else if(s&&s.envelope!=="webresource")for(let l of(t=s.targetIds)!==null&&t!==void 0?t:[])i(s.envelope,l);let o=(s,l,u)=>u.length>0?`<${s}>${u.map(c=>`<${l}>${(0,La.xmlText)(c)}</${l}>`).join("")}</${s}>`:"",a=o("entities","entity",r.entity)+o("appmodules","appmodule",r.appmodule)+o("dashboards","dashboard",r.dashboard)+o("uxagentprojects","uxagentproject",r.uxagentproject);return a?`<importexportxml>${a}</importexportxml>`:void 0}function Vae(e){let t=e.workspaceStorage;if(t==null)throw new Error("createMakerSdk requires a workspaceStorage. Node callers can build one with `createNodeWorkspaceStorage(path)` from '@maker-studio/cds-maker-sdk/node'; a host with no filesystem implements WorkspaceStorage directly.");return new OM.WorkspaceManager(Wae,e.instanceUrl,(0,Cae.assertStorageContract)(t))}yr.ALREADY_EXISTS_CODE="ARTIFACT_ALREADY_EXISTS";var Gae="this build answers a replayed create with HTTP 404, and the unpublished read of an existing row is not authoritative after another writer's save on it, so the row cannot be proven to be what this create wrote";yr.PUSH_NOT_ATTEMPTED_CODE="PUSH_NOT_ATTEMPTED";var Wae="<injected workspaceStorage>",um=class{constructor(t){var r,n;if(this.artifactLocks=new Map,this.observedGenerations=new Map,this.baselineObserved=new Map,this.generationHighWater=new Map,this.entityMetadataLoads=new Map,this.entityMetadataLoadEpochs=new WeakMap,this.schemaWrites=new Map,this.undroppedMetadata=new Set,this.metadataPublications=new Set,t.createRecovery!==void 0&&t.createRecovery!=="adoptExact")throw new Z.InvalidArgumentError(`createRecovery must be 'adoptExact' or omitted (got '${String(t.createRecovery)}').`);this.createRecovery=t.createRecovery,this.readConcurrency=(0,ew.resolveReadConcurrency)(t.readConcurrency),this.languageCode=(r=t.languageCode)!==null&&r!==void 0?r:Oae.DEFAULT_LCID,this.cacheStalenessMs=(n=t.cacheStalenessMs)!==null&&n!==void 0?n:Pae,this.compiler={load:(0,Tae.createGenPageTypeScriptLoader)(t.typescript)},this.workspace=Vae(t),this.versions=new ml.VersionManager(this.workspace),this.dataverse=new Eae.DataverseClient(t.instanceUrl,t.httpClient,t.solutionUniqueName,this.readConcurrency),this.connectivity=new Nae.ConnectivityRouter(this.dataverse,t.instanceUrl,{powerAppsServiceClient:t.powerAppsServiceClient,powerPlatformApiClient:t.powerPlatformApiClient,connectorRuntimeClient:t.connectorRuntimeClient}),this.registrations=(0,Iae.buildRegistrations)(this.languageCode)}async initWorkspace(){await this.workspace.init()}async getManifest(){return this.workspace.getManifest()}async cleanWorkspace(){await this.workspace.clean()}withArtifactLock(t,r,n){var i;let o=this.artifactKey(t,r),s=((i=this.artifactLocks.get(o))!==null&&i!==void 0?i:Promise.resolve()).then(n,n),l=s.then(()=>{},()=>{});return this.artifactLocks.set(o,l),l.then(()=>{this.artifactLocks.get(o)===l&&this.artifactLocks.delete(o)}),s}async fetchArtifact(t,r,n){return this.withArtifactLock(t,r,async()=>{let i=await this.fetchArtifactUnlocked(t,r,n);return await this.acknowledgeRefresh(t,r),i})}async fetchArtifactUnlocked(t,r,n){let i=this.requireRegistration(t,"fetchArtifact"),o=await i.api.get(this.dataverse,r);return this.applyFetchedArtifactUnlocked(t,r,i,o,n)}async applyFetchedArtifactUnlocked(t,r,n,i,o){var a,s,l;let{raw:u,etag:c,memberEtags:d,siblingEtags:f}=i,m=n.adapter.fromApiResponse(u);if(!o?.overwrite&&await this.versions.isDirty(t,r)){let h=(s=(a=await this.versions.getMeta(t,r))===null||a===void 0?void 0:a.etag)!==null&&s!==void 0?s:null;if(h&&c&&h!==c)throw new Z.LocalEditsWouldBeLostError(t,r,h,c);let g=await this.workspace.readArtifact(t,r);if(g){let b=await this.versions.getMeta(t,r);if(b&&!b.etag&&c){if(!(0,vn.deepEqual)(b.snapshot,m))throw new Z.LocalEditsWouldBeLostError(t,r,h,c);await this.versions.storeMeta(t,r,{...b,etag:c,fetchedAt:(0,gr.nowIso)()},b)}return(0,pi.cloneJson)(g)}}await this.workspace.writeArtifact(t,r,m);let p=await this.versions.getMeta(t,r);return await this.versions.storeMeta(t,r,{etag:c,languageCode:this.languageCode,projectionVersion:ml.PROJECTION_VERSION,fetchedAt:(0,gr.nowIso)(),snapshot:(0,pi.cloneJson)(m),...d?{memberEtags:d}:{},...f?{siblingEtags:f}:{},...p?.refreshGeneration?{refreshGeneration:p.refreshGeneration,observedGeneration:(l=p.observedGeneration)!==null&&l!==void 0?l:0}:{}},p),(0,pi.cloneJson)(m)}async fetchArtifactList(t,r){return this.requireRegistration(t,"fetchArtifactList").api.list(this.dataverse,r)}async fetchSolution(t){await this.workspace.ensureReady();let r=await(0,rr.fetchSolutionComponents)(this.dataverse,t),n=[],i=[];if(this.readConcurrency>1)await this.fetchComponentsOverlapped(r,n,i);else for(let o of r)try{let a=await this.resolveComponentType(o);if(!a){i.push(SM(o));continue}let s=await this.fetchArtifact(a,o.objectId);n.push(_M(a,o,s))}catch(a){i.push(NM(o,a))}return await this.workspace.updateManifest({lastSyncAt:(0,gr.nowIso)()}),{summaries:n,skipped:i}}async fetchComponentsOverlapped(t,r,n){await(0,ew.readEveryInOrder)(t,this.readConcurrency,i=>this.beginComponentRead(i),async(i,o)=>{try{if(!i.ok)throw i.error;let a=i.value;if(a.kind==="unsupported"){n.push(SM(o));return}let s=await this.applyFetchedArtifactUnlocked(a.type,o.objectId,a.reg,a.fetched);await this.acknowledgeRefresh(a.type,o.objectId),r.push(_M(a.type,o,s))}catch(a){n.push(NM(o,a))}})}async beginComponentRead(t){let r=await this.resolveComponentType(t);return r?this.lockedRead(r,t.objectId,async()=>{let n=this.requireRegistration(r,"fetchArtifact"),i=await n.api.get(this.dataverse,t.objectId,xae);return{kind:"artifact",type:r,reg:n,fetched:i}}):(0,ew.plainRead)(async()=>({kind:"unsupported"}))}lockedRead(t,r,n){let i,o=new Promise(u=>{i=u}),a,s=new Promise(u=>{a=u}),l=this.withArtifactLock(t,r,async()=>{try{i({ok:!0,value:await n()})}catch(c){i({ok:!1,error:c})}let u=await s;await u?.()});return{outcome:o,finish:u=>(a(u),l),discard:async()=>{a(void 0),await l}}}async fetchEntityMetadata(t){let r=t.toLowerCase(),n=this.schemaEpoch(r),i=await(0,hl.fetchEntityMetadataFromApi)(this.dataverse,t);if(this.schemaEpoch(r)!==n)return i;let o=this.workspace.writeEntityMetadata(t,i),a={key:r,settled:o.then(()=>{},()=>{})};this.metadataPublications.add(a);try{await o}finally{this.metadataPublications.delete(a)}return this.schemaEpoch(r)===n&&this.undroppedMetadata.delete(r),i}schemaEpoch(t){var r,n;return`${(r=this.schemaWrites.get("*"))!==null&&r!==void 0?r:0}:${(n=this.schemaWrites.get(t.toLowerCase()))!==null&&n!==void 0?n:0}`}async schemaWrite(t,r){try{return await r()}finally{await this.forgetEntityMetadata(t)}}async forgetEntityMetadata(t){let r=i=>{var o;this.schemaWrites.set(i,((o=this.schemaWrites.get(i))!==null&&o!==void 0?o:0)+1)};if(t===void 0){r("*"),await this.publicationsSettled(void 0),await this.dropCachedMetadata(void 0);return}let n=[...new Set(t.filter(i=>typeof i=="string"&&i!=="").map(i=>i.toLowerCase()))];n.forEach(r),await this.publicationsSettled(n);for(let i of n)await this.dropCachedMetadata(i)}async publicationsSettled(t){let r=t===void 0?void 0:new Set(t);await Promise.all([...this.metadataPublications].filter(n=>r===void 0||r.has(n.key)).map(n=>n.settled))}async dropCachedMetadata(t){try{await this.workspace.dropEntityMetadata(t)}catch(r){r instanceof Z.WorkspaceNotInitializedError||r instanceof Z.WorkspaceOrgMismatchError||this.undroppedMetadata.add(t??"*");return}t===void 0?this.undroppedMetadata.clear():this.undroppedMetadata.delete(t)}async readCachedEntityMetadata(t){let r=t.toLowerCase();return this.undroppedMetadata.has("*")&&await this.dropCachedMetadata(void 0),this.undroppedMetadata.has(r)&&await this.dropCachedMetadata(r),this.undroppedMetadata.has("*")||this.undroppedMetadata.has(r)?null:this.workspace.readEntityMetadata(t)}loadMissedEntityMetadata(t){let r=this.schemaEpoch(t),n=this.entityMetadataLoads.get(t);if(n&&this.entityMetadataLoadEpochs.get(n)===r)return n;let i=this.fetchEntityMetadata(t).then(()=>{});this.entityMetadataLoads.set(t,i),this.entityMetadataLoadEpochs.set(i,r);let o=()=>{this.entityMetadataLoads.get(t)===i&&this.entityMetadataLoads.delete(t)};return i.then(o,o),i}generateGenPageRuntimeTypes(t,r){return(0,Aae.generateGenPageRuntimeTypes)(n=>this.fetchEntityMetadata(n),t,r)}findTables(t,r){return(0,hl.findTables)(this.dataverse,t,r)}getEnvironmentLanguages(){return(0,Sae.getEnvironmentLanguages)(this.dataverse)}listConnections(){return this.connectivity.listConnections()}listConnectorOperations(t){return this.connectivity.listConnectorOperations(t)}getConnectorOperationSchema(t,r){return this.connectivity.getConnectorOperationSchema(t,r)}listConnectorTables(t,r,n){return this.connectivity.listConnectorTables(t,r,n)}getConnectorTableSchema(t,r,n,i){return this.connectivity.getConnectorTableSchema(t,r,n,i)}findColumns(t,r,n){return(0,hl.findColumns)(this.dataverse,t,r,n)}createTable(t){return this.schemaWrite([t.schemaName],()=>(0,kt.createTable)(this.dataverse,t))}createColumn(t,r){return this.schemaWrite([t],()=>(0,kt.createColumn)(this.dataverse,t,r))}createColumns(t,r){return this.schemaWrite([t],()=>(0,kt.createColumns)(this.dataverse,t,r))}updateColumn(t,r,n){return this.schemaWrite([t],()=>(0,kt.updateColumn)(this.dataverse,t,r,n))}deleteColumn(t,r){return this.schemaWrite([t],()=>(0,kt.deleteColumn)(this.dataverse,t,r))}setFormSecurityRoles(t,r){return(0,Zv.setFormSecurityRoles)(this.dataverse,t,r)}getFormSecurityRoles(t){return(0,Zv.getFormSecurityRoles)(this.dataverse,t)}setColumnVisualization(t,r,n){return(0,kt.setColumnVisualization)(this.dataverse,t,r,n)}getColumnVisualization(t,r){return(0,kt.getColumnVisualization)(this.dataverse,t,r)}createCustomerColumn(t,r){return this.schemaWrite([t,"account","contact"],()=>(0,kt.createCustomerColumn)(this.dataverse,t,r))}insertStatusValue(t,r){return this.schemaWrite([t],()=>(0,kt.insertStatusValue)(this.dataverse,t,r))}updateTable(t,r){return this.schemaWrite([t],()=>(0,kt.updateTable)(this.dataverse,t,r))}async setEntityIcon(t,r){if(await this.schemaWrite([t],()=>(0,kt.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,La.xmlText)(t)}</entity></entities></importexportxml>`;(0,gr.ensureSuccess)(await this.dataverse.post("/PublishXml",{ParameterXml:n}),this.dataverse.apiUrl("/PublishXml"))}}createAlternateKey(t,r){return(0,kt.createAlternateKey)(this.dataverse,t,r)}deleteAlternateKey(t,r){return(0,kt.deleteAlternateKey)(this.dataverse,t,r)}createRelationship(t){let r=t.type==="ManyToMany"?[t.entity1,t.entity2]:[t.referencedEntity,t.referencingEntity];return this.schemaWrite(r,()=>(0,kt.createRelationship)(this.dataverse,t))}deleteRelationship(t){return this.schemaWrite(void 0,()=>(0,kt.deleteRelationship)(this.dataverse,t))}createGlobalOptionSet(t){return(0,kt.createGlobalOptionSet)(this.dataverse,t)}deleteGlobalOptionSet(t){return(0,kt.deleteGlobalOptionSet)(this.dataverse,t)}deleteTable(t){return this.schemaWrite(void 0,()=>(0,kt.deleteTable)(this.dataverse,t))}createSecurityRole(t){return(0,Ac.createSecurityRole)(this.dataverse,t)}createPersonaRole(t){return(0,Ac.createPersonaRole)(this.dataverse,t)}deleteSecurityRole(t){return(0,Ac.deleteSecurityRole)(this.dataverse,t)}addEntityPrivilegesToRole(t,r){return(0,Ac.addEntityPrivilegesToRole)(this.dataverse,t,r)}getEntityPrivileges(t){return(0,Ac.getEntityPrivileges)(this.dataverse,t)}createRecord(t,r){return(0,Hi.createRecord)(this.dataverse,t,r)}createRecordsBulk(t,r){return(0,Hi.createRecordsBulk)(this.dataverse,t,r)}updateRecord(t,r,n){return(0,Hi.updateRecord)(this.dataverse,t,r,n)}upsertRecord(t,r,n){return(0,Hi.upsertRecord)(this.dataverse,t,r,n)}deleteRecord(t,r){return(0,Hi.deleteRecord)(this.dataverse,t,r)}getRecord(t,r,n){return(0,Hi.getRecord)(this.dataverse,t,r,n)}queryRecords(t,r){return(0,Hi.queryRecords)(this.dataverse,t,r)}seedRecordGraph(t,r){return(0,Rae.seedRecordGraph)(this.dataverse,t,r)}resolveArtifact(t,r){return(0,AM.resolveArtifact)(this.dataverse,t,r)}findArtifact(t,r){return(0,AM.findArtifact)(this.dataverse,t,r)}async deleteAppCascade(t,r){await this.workspace.ensureReady();let n=await(0,Dae.deleteAppCascade)(this.dataverse,t,r),i=(0,La.normalizeGuid)(t,"appModuleId");return await this.workspace.readArtifact("app",i)&&await this.workspace.deleteArtifact("app",i),n}associateRecords(t,r,n){return(0,Hi.associateRecords)(this.dataverse,t,r,n)}disassociateRecords(t,r,n,i){return(0,Hi.disassociateRecords)(this.dataverse,t,r,n,i)}createWebResource(t){return(0,sm.createWebResource)(this.dataverse,t)}updateWebResource(t,r){return(0,sm.updateWebResource)(this.dataverse,t,r)}getWebResource(t){return(0,sm.getWebResource)(this.dataverse,t)}deleteWebResource(t){return(0,sm.deleteWebResource)(this.dataverse,t)}getAppSettings(t){return(0,gl.readAppSettings)(this.dataverse,t)}setAppSetting(t,r,n){return(0,gl.setAppSetting)(this.dataverse,t,r,n)}setHeaderAndNavigationRefresh(t,r){if(typeof r!="boolean")throw new Z.ValidationError("app",t,[{pointer:"/headerAndNavigationRefresh",rule:_ae.HEADER_NAV_BOOLEAN_RULE,message:`enabled must be a boolean, got ${typeof r}`}]);return(0,gl.setAppSetting)(this.dataverse,t,gl.HEADER_AND_NAVIGATION_REFRESH,r?gl.APP_SETTING_ON:gl.APP_SETTING_OFF)}getSolution(t){return(0,rr.getSolution)(this.dataverse,t)}createPublisher(t){return(0,rr.createPublisher)(this.dataverse,t)}createSolution(t){return(0,rr.createSolution)(this.dataverse,t)}setSolutionVersion(t,r){return(0,rr.setSolutionVersion)(this.dataverse,t,r)}addSolutionComponent(t){return(0,rr.addSolutionComponent)(this.dataverse,t)}removeSolutionComponent(t,r,n){return(0,rr.removeSolutionComponent)(this.dataverse,t,r,n)}exportSolution(t){return(0,rr.exportSolution)(this.dataverse,t)}importSolution(t){return this.schemaWrite(void 0,()=>(0,rr.importSolution)(this.dataverse,t))}getDeploymentSettingsTemplate(t){return(0,rr.getDeploymentSettingsTemplate)(this.dataverse,t)}deleteSolution(t){return this.schemaWrite(void 0,()=>(0,rr.deleteSolution)(this.dataverse,t))}async getArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let{artifact:n,meta:i}=await this.readWhole(t,r);return await this.acknowledgeRefresh(t,r,i),n})}async getArtifactUnlocked(t,r){return this.readRaw(t,r)}async readWhole(t,r){let{meta:n}=await this.revalidate(t,r);return{artifact:await this.readLocal(t,r),meta:n}}async acknowledgeRefresh(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=n===void 0?await this.versions.getMeta(t,r):n;this.baselineObserved.has(s)||this.baselineObserved.set(s,(i=l?.observedGeneration)!==null&&i!==void 0?i:0);let u=(o=l?.refreshGeneration)!==null&&o!==void 0?o:0;this.raiseGenerationHighWater(s,u),l&&u!==((a=l.observedGeneration)!==null&&a!==void 0?a:0)&&await this.versions.storeMeta(t,r,{...l,observedGeneration:u},l),this.observedGenerations.set(s,u)}raiseGenerationHighWater(t,r){var n;r>((n=this.generationHighWater.get(t))!==null&&n!==void 0?n:0)&&this.generationHighWater.set(t,r)}async observedAtInvocation(t,r,n){var i,o;if(n!==void 0)return n;let a=this.baselineObserved.get(this.artifactKey(t,r));return a!==void 0?a:(o=(i=await this.versions.getMeta(t,r))===null||i===void 0?void 0:i.observedGeneration)!==null&&o!==void 0?o:0}artifactKey(t,r){return`${t}\0${(0,OM.canonicalArtifactId)(r)}`}nextRefreshGeneration(t,r,n){var i,o,a;let s=this.artifactKey(t,r),l=Math.max((i=n?.refreshGeneration)!==null&&i!==void 0?i:0,(o=n?.observedGeneration)!==null&&o!==void 0?o:0,(a=this.generationHighWater.get(s))!==null&&a!==void 0?a:0)+1;return this.raiseGenerationHighWater(s,l),l}async readRaw(t,r){return await this.revalidateIfStale(t,r),this.readLocal(t,r)}async readForMutation(t,r,n,i){var o,a;let s=await this.observedAtInvocation(t,r,i);if(((a=(o=await this.versions.getMeta(t,r))===null||o===void 0?void 0:o.refreshGeneration)!==null&&a!==void 0?a:0)>s)throw new Z.StaleArtifactError(t,r,n,"pushed");if(await this.revalidateIfStale(t,r)==="refreshed-changed")throw new Z.StaleArtifactError(t,r,n);return this.readLocal(t,r)}async readLocal(t,r){let n=await this.workspace.readArtifact(t,r);if(!n)throw new Z.ArtifactNotFoundError(t,r);return n}async revalidateIfStale(t,r){return(await this.revalidate(t,r)).outcome}async revalidate(t,r){let n=await this.versions.getMeta(t,r);if(!n)return{outcome:"skipped",meta:null};let i=n.fetchedAt?Date.parse(n.fetchedAt):NaN,o=Date.now()-i;if(!Number.isNaN(i)&&this.cacheStalenessMs>0&&o<=this.cacheStalenessMs)return{outcome:"fresh",meta:n};if(await this.versions.isDirty(t,r,n))return{outcome:"skipped",meta:n};let a=await this.workspace.readArtifact(t,r);await this.fetchArtifactUnlocked(t,r);let s=await this.workspace.readArtifact(t,r);return{outcome:(0,vn.deepEqual)(a,s)?"refreshed-unchanged":"refreshed-changed"}}async queryTree(t,r,n){return this.withArtifactLock(t,r,async()=>{let{artifact:i,meta:o}=await this.readWhole(t,r),a=bn.JsonPointer.resolve(i,n);if(a===void 0)throw new Z.PathNotFoundError(t,r,n);return n===""&&await this.acknowledgeRefresh(t,r,o),a})}async findElements(t,r,n){return this.withArtifactLock(t,r,async()=>(0,wae.findElements)(await this.getArtifactUnlocked(t,r),n))}async withDirtyFlags(t){let r=[];for(let n of t)r.push({...n,isDirty:await this.versions.isDirty(n.type,n.id)});return r}async listArtifacts(t,r){return this.withDirtyFlags(await this.workspace.listArtifacts(t,r))}async getEntityMetadata(t){let r=await this.readCachedEntityMetadata(t);if(!r)throw new Z.ArtifactNotFoundError("entityMetadata",t);return r}async getFieldMetadata(t,r){let i=(await this.getEntityMetadata(t)).attributes.find(o=>o.logicalName===r);if(!i)throw new Z.PathNotFoundError("entityMetadata",t,r);return i}async updateElement(t,r,n,i){let o=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let a=await this.readForMutation(t,r,n,o),s=bn.JsonPointer.resolve(a,n);if(s===void 0)throw new Z.PathNotFoundError(t,r,n);let l=Ki(s)&&Ki(i)?{...s,...i}:i;return bn.JsonPointer.set(a,n,(0,pi.cloneJson)(l)),this.assertStructurallyValid(t,r,a,n),await this.workspace.writeArtifact(t,r,a),this.getArtifactUnlocked(t,r)})}async addElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let s=await this.readForMutation(t,r,n,a),l=bn.JsonPointer.resolve(s,n);if(l===void 0)throw new Z.PathNotFoundError(t,r,n);if(!Array.isArray(l)){if(!Ki(l)||!Ki(i))throw new Z.ValidationError(t,r,n,"parent must be an array, or an object with an object of properties to add");if(o?.position!==void 0)throw new Z.ValidationError(t,r,n,"position is not supported for an object parent");let d={};for(let f of Object.keys(i)){if(f==="id")throw new Z.ValidationError(t,r,n,"refusing to write 'id' \u2014 that re-keys the node rather than adding a property");let m=(0,pi.cloneJson)(i[f]),p=(0,lm.isValueMapKey)(f)||(0,lm.pointerTouchesValueMap)(n);d[f]=p?m:Array.isArray(m)?m.map(h=>Ki(h)?this.assignMissingIds(t,h):h):Ki(m)?this.assignMissingIds(t,m):m}for(let f of Object.keys(d))bn.JsonPointer.set(s,bn.JsonPointer.append(n,f),d[f]);return this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)}let u=(0,lm.pointerTouchesValueMap)(n)?(0,pi.cloneJson)(i):this.assignMissingIds(t,(0,pi.cloneJson)(i)),c=Kae(l,o?.position);return l.splice(c,0,u),this.assertStructurallyValid(t,r,s,n),await this.workspace.writeArtifact(t,r,s),this.getArtifactUnlocked(t,r)})}async moveElement(t,r,n,i,o){let a=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{var s;let l=await this.readForMutation(t,r,n,a),u=bn.JsonPointer.resolve(l,n);if(u===void 0)throw new Z.PathNotFoundError(t,r,n);let c=bn.JsonPointer.resolve(l,i);if(c===void 0)throw new Z.PathNotFoundError(t,r,i);if(!Array.isArray(c))throw new Z.ValidationError(t,r,i,"move target must be an array");if(i===n||i.startsWith(`${n}/`))throw new Z.ValidationError(t,r,i,"cannot move an element into its own subtree");bn.JsonPointer.remove(l,n);let d=(s=o?.index)!==null&&s!==void 0?s:c.length;c.splice(Math.max(0,Math.min(d,c.length)),0,u),IM(c);let f=bn.JsonPointer.resolve(l,DM(n));return Array.isArray(f)&&f!==c&&IM(f),this.assertStructurallyValid(t,r,l,i),await this.workspace.writeArtifact(t,r,l),this.getArtifactUnlocked(t,r)})}async removeElement(t,r,n){let i=this.observedGenerations.get(this.artifactKey(t,r));return this.withArtifactLock(t,r,async()=>{let o=await this.readForMutation(t,r,n,i);if(bn.JsonPointer.resolve(o,n)===void 0)throw new Z.PathNotFoundError(t,r,n);return bn.JsonPointer.remove(o,n),this.assertStructurallyValid(t,r,o,DM(n)),await this.workspace.writeArtifact(t,r,o),this.getArtifactUnlocked(t,r)})}assertStructurallyValid(t,r,n,i){var o,a,s;let l=this.registrations.get(t),u=(s=(a=l==null?void 0:(o=l.adapter).validate)===null||a===void 0?void 0:a.call(o,n,i))!==null&&s!==void 0?s:[];if(u.length>0)throw new Z.ValidationError(t,r,u)}retrieveSetting(t,r){return(0,yl.retrieveSetting)(this.dataverse,t,r)}saveSettingValue(t,r,n){return(0,yl.saveSettingValue)(this.dataverse,t,r,n)}getAiReadiness(t){return(0,yl.getAiReadiness)(this.dataverse,t)}setAppAiFeatures(t,r,n){return(0,yl.setAppAiFeatures)(this.dataverse,t,r,n)}configureRowSummary(t,r){return(0,yl.configureRowSummary)(this.dataverse,t,r)}removeRowSummary(t){return(0,yl.removeRowSummary)(this.dataverse,t)}async enrichDefaultViews(t,r,n={}){let i=await(0,kae.findDefaultViews)(this.dataverse,t,{excludeViewIds:n.excludeViewIds}),o=n.publish===!1,a=[],s=[],l=()=>({updated:[...a],results:[...s],pendingPublish:a.length>0?[{scope:(0,vM.boundEntityPublishScope)({entityLogicalName:t}),artifacts:a.map(c=>({type:"view",id:c}))}]:[]}),u;try{for(let c of i){await this.fetchArtifact("view",c.id),await this.updateElement("view",c.id,"/columns",r),u=c.id;let d=await this.pushArtifact("view",c.id);u=void 0,s.push(d),d.saved&&a.push(c.id)}}catch(c){throw u&&$ae(c)&&a.push(u),o?(0,Z.withPartialEnrichment)(c,l()):c}if(o)return l();if(a.length){let c=await this.publishArtifact("view",a[0]);if(c.publish.kind==="failed")throw new Z.SdkError("ENRICH_DEFAULT_VIEWS_PUBLISH_FAILED",`enrichDefaultViews: ${a.length} view(s) on '${t}' were saved but the publish FAILED, so none of them is live (${c.publish.error.message}). Re-publish the entity to make them visible; the saves themselves are unaffected.`)}return{updated:a}}async createArtifact(t,r){let n=this.requireRegistration(t,"createArtifact"),i=n.adapter.assignMissingIds(n.adapter.createDefault(r)),o=i.id;if(!o)throw new Z.ValidationError(t,"(new)","/id","created artifact must have an id");return this.withArtifactLock(t,o,async()=>(await this.workspace.writeArtifact(t,o,i),(0,pi.cloneJson)(i)))}async deleteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{await this.workspace.deleteArtifact(t,r)})}async deleteRemoteArtifact(t,r){return this.withArtifactLock(t,r,async()=>{let n=this.requireRegistration(t,"deleteRemoteArtifact");await this.workspace.ensureReady(),await n.api.delete(this.dataverse,r),await this.workspace.readArtifact(t,r)&&await this.workspace.deleteArtifact(t,r)})}async publishArtifact(t,r,n){let{result:i,siblings:o}=await this.withArtifactLock(t,r,()=>this.publishArtifactUnlocked(t,r,n));for(let a of o)await this.withArtifactLock(a.type,a.id,()=>this.adoptBracket(a));return i}async publishArtifacts(t,r){var n,i;let o=new Map;for(let p of t){let h=this.artifactKey(p.type,p.id);o.has(h)||o.set(h,{type:p.type,id:p.id})}let a=[];for(let[p,h]of o)a.push(await this.withArtifactLock(h.type,h.id,()=>this.preparePublish(p,h.type,h.id)));let s=new Set(o.keys()),l=[],u=new Set;for(let p of a){let h=((n=p.scope)===null||n===void 0?void 0:n.envelope)==="entity"?(i=p.scope.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;p.scope&&h&&!u.has(h)&&(u.add(h),l.push(p.scope))}let c=await this.captureSiblings(l,s),d=qae(a),f;if(d)try{await(0,vM.publishXml)(this.dataverse,d)}catch(p){f=Ro(p)}let m=new Map;for(let p of a)m.set(p.key,await this.withArtifactLock(p.type,p.id,()=>this.settlePublish(p,f,r)));for(let p of c)await this.withArtifactLock(p.type,p.id,()=>this.adoptBracket(p));return t.map(p=>({...m.get(this.artifactKey(p.type,p.id))}))}async preparePublish(t,r,n){var i;let o=await this.readRaw(r,n),a=this.registrations.get(r);if(!a?.publish)return{key:t,type:r,id:n,artifact:o,notApplicable:!0};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,n,o);if(!s||!Bae.has(s.envelope))throw new Z.InvalidArgumentError(`publishArtifacts: ${r} '${n}' publishes through ${s?`a '${s.envelope}'`:"no declared"} scope, which one PublishXml envelope cannot carry. Publish it with publishArtifact.`);let l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,r,n):void 0;return{key:t,type:r,id:n,artifact:o,reg:a,scope:s,...l?{own:l}:{}}}async settlePublish(t,r,n){let{type:i,id:o}=t;if(t.notApplicable||!t.reg)return{type:i,id:o,shipped:!1,publish:{kind:"notApplicable"}};let a=t.scope?{publishScope:t.scope}:{};if(t.reg.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(t.reg,i,o),t.own&&await this.adoptBracket(t.own),r)return{type:i,id:o,shipped:!1,publish:{kind:"failed",error:r},...a};if(!n?.verify)return{type:i,id:o,shipped:!1,publish:{kind:"submitted"},...a};let s=await this.workspace.readArtifact(i,o).catch(()=>null);if(!s||!(0,vn.deepEqual)(s,t.artifact))return{type:i,id:o,shipped:!1,publish:{kind:"unverifiable",reason:`the local ${i} was ${s?"edited":"deleted"} while the publish was in flight, so what shipped cannot be told from what is local now; verify it with publishArtifact`},...a};let l=await this.verifyPublished(i,o,t.artifact);return{type:i,id:o,shipped:l.kind==="verified",publish:l,...a}}async publishArtifactUnlocked(t,r,n){var i;let o=await this.readRaw(t,r),a=this.registrations.get(t);if(!a?.publish)return{result:{type:t,id:r,shipped:!1,publish:{kind:"notApplicable"}},siblings:[]};let s=(i=a.publishScope)===null||i===void 0?void 0:i.call(a,r,o),l=a.rebaselineAfterPublish==="bracket"?await this.captureBracket(a,t,r):void 0,u=s?await this.captureSiblings([s],new Set([this.artifactKey(t,r)])):[];try{await a.publish(this.dataverse,r,o)}catch(d){return{result:{type:t,id:r,shipped:!1,publish:{kind:"failed",error:Ro(d)},...s?{publishScope:s}:{}},siblings:[]}}if(a.rebaselineAfterPublish==="snapshot"&&await this.rebaselineAfterPublish(a,t,r),l&&await this.adoptBracket(l),!n?.verify)return{result:{type:t,id:r,shipped:!1,publish:{kind:"submitted"},...s?{publishScope:s}:{}},siblings:u};let c=await this.verifyPublished(t,r,o);return{result:{type:t,id:r,shipped:c.kind==="verified",publish:c,...s?{publishScope:s}:{}},siblings:u}}async captureBracket(t,r,n){try{let i=await this.versions.getMeta(r,n),o=i?.etag;if(!(0,gr.isVersionToken)(o)||!t.api.readContentThenToken)return;let{raw:a,etag:s,siblingEtags:l}=await t.api.readContentThenToken(this.dataverse,n),u=i?.siblingEtags;return s!==o||!jae(u,l)?void 0:{type:r,id:n,reg:t,heldEtag:o,...u?{heldSiblings:u}:{},content:this.bracketContent(t,a)}}catch{return}}async captureSiblings(t,r){var n,i,o;let a=new Map;for(let u of t){let c=u.envelope==="entity"?(n=u.entityLogicalName)===null||n===void 0?void 0:n.toLowerCase():void 0;c&&!a.has(c)&&a.set(c,[])}if(a.size===0)return[];let s;try{s=await this.workspace.listArtifacts()}catch{return[]}for(let u of s){let c=this.registrations.get(u.type);if(!(r.has(this.artifactKey(u.type,u.id))||c?.rebaselineAfterPublish!=="bracket"||!c.publishScope))try{let d=await this.workspace.readArtifact(u.type,u.id),f=d?c.publishScope(u.id,d):void 0,m=f?.envelope==="entity"?(i=f.entityLogicalName)===null||i===void 0?void 0:i.toLowerCase():void 0;m!==void 0&&((o=a.get(m))===null||o===void 0||o.push(u))}catch{continue}}let l=[];for(let u of a.values())for(let c of u){let d=this.registrations.get(c.type),f=d?await this.captureBracket(d,c.type,c.id):void 0;f&&l.push(f)}return l}async adoptBracket(t){var r;try{let n=await this.versions.getMeta(t.type,t.id);if(!n||n.etag!==t.heldEtag||!(0,vn.deepEqual)((r=n.siblingEtags)!==null&&r!==void 0?r:void 0,t.heldSiblings))return;let{raw:i,etag:o,siblingEtags:a}=await t.reg.api.get(this.dataverse,t.id);if(!(0,gr.isVersionToken)(o)||!RM(a,t.heldSiblings)||!kM(a)||!(o!==t.heldEtag||!(0,vn.deepEqual)(a??void 0,t.heldSiblings))||!(0,vn.deepEqual)(this.bracketContent(t.reg,i),t.content))return;await this.versions.storeMeta(t.type,t.id,{...n,etag:o,...t.heldSiblings?{siblingEtags:{...a}}:{},fetchedAt:(0,gr.nowIso)()},n)}catch{}}bracketContent(t,r){var n,i,o;let a=t.adapter.fromApiResponse(r);return(o=(i=(n=t.adapter).baselineContent)===null||i===void 0?void 0:i.call(n,a))!==null&&o!==void 0?o:a}adoptReadBack(t,r){try{return{artifact:t.adapter.fromApiResponse(r)}}catch(n){return{warning:`The write was saved, but the record read back after it could not be read into the local copy (${Ro(n).message}). The SDK holds no version for it now, so the next push is refused: re-fetch before editing again.`}}}adoptedAsSent(t,r,n,i){try{let o={...n,...i},a=t.adapter.fromApiResponse(t.adapter.completeAsStored?t.adapter.completeAsStored(o,n):o);return(0,vn.deepEqual)(r,a)}catch{return!1}}async rebaselineAfterPublish(t,r,n){try{let i=await this.versions.getMeta(r,n);if(!i)return;let{raw:o,etag:a,memberEtags:s,siblingEtags:l}=t.api.getForRebaseline?await t.api.getForRebaseline(this.dataverse,n):await t.api.get(this.dataverse,n),u=t.adapter.fromApiResponse(o),c=d=>{var f,m,p;return(p=(m=(f=t.adapter).baselineContent)===null||m===void 0?void 0:m.call(f,d))!==null&&p!==void 0?p:d};if(!a||!(0,vn.deepEqual)(c(i.snapshot),c(u)))return;await this.versions.storeMeta(r,n,{...i,etag:a,fetchedAt:(0,gr.nowIso)(),...s?{memberEtags:s}:{},...l?{siblingEtags:l}:{}},i)}catch{}}async verifyPublished(t,r,n){var i;if(t!=="app"){let o=this.registrations.get(t);return o?.api.getPublished?this.verifyPublishedContent(o,t,r,n):{kind:"unverifiable",reason:`published-projection verification is not characterised for '${t}'; the publish was submitted`}}try{let o=`/appmodules(${(0,La.normalizeGuid)(r,"id")})${(0,La.odataQuery)([["$select","appmoduleid,name,description"]])}`,a=await this.dataverse.get(o);if(a.status>=200&&a.status<300){let s=(i=a.body)!==null&&i!==void 0?i:{},l=n;if(!l)return{kind:"unverifiable",reason:"there is no local copy of the app to compare the published projection with"};let u=["name","description"].filter(d=>l[d]!==void 0);if(u.length===0)return{kind:"unverifiable",reason:"the local copy of the app holds neither a name nor a description to compare the published projection with, and its presence alone proves nothing for a re-publish"};let c=u.filter(d=>{var f,m;return((f=l[d])!==null&&f!==void 0?f:"")!==((m=s[d])!==null&&m!==void 0?m:"")});return c.length>0?{kind:"unverifiable",reason:`the published projection does not yet match the saved app (${c.join(", ")} still differ). PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}:{kind:"verified"}}return{kind:"unverifiable",reason:`the published projection answered HTTP ${a.status}`}}catch(o){return{kind:"unverifiable",reason:Ro(o).message}}}async verifyPublishedContent(t,r,n,i){var o,a,s;try{let l=f=>{var m,p,h;return(h=(p=(m=t.adapter).baselineContent)===null||p===void 0?void 0:p.call(m,f))!==null&&h!==void 0?h:f},u=l(i),c=(o=await this.versions.getMeta(r,n))===null||o===void 0?void 0:o.snapshot;if(c===void 0||!(0,vn.deepEqual)(u,l(c)))return{kind:"unverifiable",reason:`the local ${r} holds edits that were never pushed, so no publish could have shipped them \u2014 push, then publish again`};let d=await((s=(a=t.api).getPublished)===null||s===void 0?void 0:s.call(a,this.dataverse,n));return d?(0,vn.deepEqual)(u,l(t.adapter.fromApiResponse(d.raw)))?{kind:"verified"}:{kind:"unverifiable",reason:"the published projection does not show what was pushed. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists"}:{kind:"unverifiable",reason:`the ${r} is not in the published projection yet. PublishXml is asynchronous \u2014 re-read shortly, or re-publish if it persists`}}catch(l){return{kind:"unverifiable",reason:Ro(l).message}}}async pushArtifact(t,r){return this.withArtifactLock(t,r,()=>this.pushArtifactUnlocked(t,r))}async prepareArtifactUnlocked(t,r,n){var i,o;let a=this.requireRegistration(t,"pushArtifact"),s=await this.workspace.readArtifactWithText(t,r);if(!s)throw new Z.ArtifactNotFoundError(t,r);let l=s.artifact,u=s.text,c=(o=(i=a.adapter).normalize)===null||o===void 0?void 0:o.call(i,l);c&&c!==l&&(await this.workspace.writeArtifact(t,r,c),l=c,u=void 0);let d=await this.versions.getMeta(t,r);this.assertLanguageMatches(t,r,d,a),this.assertProjectionMatches(t,r,d);let f=await this.buildMetadataContext(a.adapter,l,d?.snapshot),m=await a.adapter.toApiPayload(l,d?.snapshot,f);return await this.assertSemanticallyComplete(a,t,r,l,d===null,d?.everActivated,n),{type:t,id:r,reg:a,json:l,...u!==void 0?{storedText:u}:{},meta:d,payload:m}}async assertSemanticallyComplete(t,r,n,i,o,a,s){let l=t.adapter.issuesBlockingPush;if(!l)return;let u=i.entityLogicalName,d=(u?await this.columnsForCheck(t,u,i,s):[]).map(m=>({logicalName:m.logicalName,displayName:m.displayName,attributeType:m.attributeType,isCustomAttribute:m.isCustomAttribute,...m.maxLength!==void 0?{maxLength:m.maxLength}:{},...m.options?{options:m.options.map(p=>({value:p.value,label:p.label}))}:{},...m.targets?{targets:m.targets}:{}})),f=l.call(t.adapter,i,d,{isCreate:o,everActivated:a});if(f.length>0)throw new Z.ValidationError(r,n,f)}columnsForCheck(t,r,n,i){var o,a,s;let l=(s=(a=(o=t.adapter).columnsCheckedAtPush)===null||a===void 0?void 0:a.call(o,n))!==null&&s!==void 0?s:[],u=async()=>{let f=await this.readCachedEntityMetadata(r);if(f)return f.attributes;try{return await(0,hl.readCheckColumns)(this.dataverse,r,l)}catch{return[]}};if(!i)return u();let c=[r,...[...new Set(l)].sort()].join("\0"),d=i.get(c);return d||(d=u(),i.set(c,d)),d}async pushArtifactUnlocked(t,r,n){return this.executePrepared(await this.prepareArtifactUnlocked(t,r,n))}async executePrepared(t){var r,n,i,o,a,s,l,u,c;let{type:d,id:f,reg:m,json:p,meta:h,payload:g}=t,b=!1;try{let w;if(h)w=await m.api.update(this.dataverse,f,g,h.etag,h.memberEtags,h.siblingEtags);else{let P=await this.createWithMintedId(m,d,f,g,p);if("adopted"in P)return await this.persistAdoption(d,f,p,P.adopted);w=P.written}b=!0;let C=f;h||(w.serverIdentity&&m.adapter.applyServerIdentity&&m.adapter.applyServerIdentity(p,w.serverIdentity),w.id&&w.id!==f&&(p.id=w.id,await this.workspace.deleteArtifact(d,f),C=w.id));let S=h&&w.readBack!==void 0?this.adoptReadBack(m,w.readBack):void 0,O=S?.artifact?{artifact:S.artifact,baseline:S.artifact}:m.adapter.committed?m.adapter.committed(p,g,{intentPending:w.intentPending===!0}):{artifact:p,baseline:p};await this.workspace.writeArtifact(d,C,O.artifact,h&&C===f?t.storedText:void 0);let k=S?.artifact!==void 0&&!(0,vn.deepEqual)(S.artifact,p),I=k?this.nextRefreshGeneration(d,C,h):(r=h?.refreshGeneration)!==null&&r!==void 0?r:0,D=[...(n=w.warnings)!==null&&n!==void 0?n:[],...S?.warning?[S.warning]:[],...S?.artifact!==void 0&&!this.adoptedAsSent(m,S.artifact,w.readBack,g)?[`Saved, but the server holds something other than what was pushed (another writer saved in between, or the platform rewrote something the SDK does not model \u2014 a label in a language the org does not provision, a hand-written fragment); the local ${d} now holds the server's version. Read it (getArtifact) before the next edit: a mutation whose pointer was derived from the earlier copy is refused (StaleArtifactError).`]:[]];return await this.versions.storeMeta(d,C,{etag:S&&!S.artifact?null:w.etag,...I>0?{refreshGeneration:I,observedGeneration:(i=h?.observedGeneration)!==null&&i!==void 0?i:0}:{},languageCode:this.languageCode,projectionVersion:ml.PROJECTION_VERSION,fetchedAt:(0,gr.nowIso)(),snapshot:(0,pi.cloneJson)(O.baseline),...w.memberEtags?{memberEtags:w.memberEtags}:{},...w.siblingEtags?{siblingEtags:w.siblingEtags}:{}},C===f?h:void 0),{type:d,id:C,saved:!0,shipped:!1,publish:(o=w.publish)!==null&&o!==void 0?o:{kind:"notRequested"},...w.publish&&w.publish.kind!=="notRequested"?(()=>{var P;let x=(P=m.publishScope)===null||P===void 0?void 0:P.call(m,C,p);return x?{publishScope:x}:{}})():{},...k?{refreshed:!0}:{},...D.length>0?{warnings:D}:{}}}catch(w){let C=(0,Z.readPartialTokens)(w);if(C&&h){let S={...(a=h.memberEtags)!==null&&a!==void 0?a:{},...(s=C.memberEtags)!==null&&s!==void 0?s:{}},O={...(l=h.siblingEtags)!==null&&l!==void 0?l:{},...(u=C.siblingEtags)!==null&&u!==void 0?u:{}};await this.versions.storeMeta(d,f,{...h,...Object.keys(S).length>0?{memberEtags:S}:{},...Object.keys(O).length>0?{siblingEtags:O}:{}},h)}if(w instanceof Z.SdkError&&w.code===yr.ALREADY_EXISTS_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===bM.WFOM_API_UNAVAILABLE_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===bM.BUSINESS_RULE_LEFT_DEACTIVATED_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:w};if(w instanceof Z.SdkError&&w.code===gr.VERSION_CONFLICT_CODE)return{type:d,id:f,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:(0,EM.isFailureAfterPrimaryWrite)(w)?w:new Z.VersionConflictError(d,f,(c=h?.etag)!==null&&c!==void 0?c:null,null,w.message)};throw b?Lae(w):w}}assertLanguageMatches(t,r,n,i){if(i?.languageSensitive&&!(n?.languageCode===void 0||n.languageCode===this.languageCode))throw new Z.SdkError("ARTIFACT_LANGUAGE_MISMATCH",`Refusing to push ${t} '${r}': it was fetched with languageCode ${n.languageCode} but this SDK is configured with ${this.languageCode}. Pushing would rewrite labels read in one language as labels in another. Re-fetch with languageCode ${this.languageCode}, or create the SDK with languageCode ${n.languageCode}.`)}assertProjectionMatches(t,r,n){var i;if(n&&n.projectionVersion!==ml.PROJECTION_VERSION)throw new Z.SdkError("ARTIFACT_PROJECTION_STALE",`Refusing to push ${t} '${r}': its workspace copy was produced by projection version ${(i=n.projectionVersion)!==null&&i!==void 0?i:"unknown (pre-versioning)"}, but this SDK produces version ${ml.PROJECTION_VERSION}. The parsers changed in between, so an unedited part of this artifact can no longer be told apart from an edited one and pushing could overwrite server content the caller never touched. Re-fetch it with fetchArtifact('${t}', '${r}') and re-apply any local edits.`)}async createWithMintedId(t,r,n,i,o){try{return{written:await t.api.create(this.dataverse,i,n)}}catch(a){let s=r==="form"?(0,Zv.readPrimaryCreateRefusal)(a):void 0;if(s?.status===404&&await(0,CM.formExistsAtId)(()=>t.api.get(this.dataverse,n),s.sent.formid)){let u=`the platform answered the create with ${a.message} \u2014 this build refuses a replayed create that way \u2014 but a read of that id finds the record`;throw(0,Z.attachCause)(new Z.SdkError(yr.ALREADY_EXISTS_CODE,rw(r,n,u)+(this.createRecovery==="adoptExact"?` ${TM(Gae)}`:"")),a)}if(!(a instanceof Z.SdkError)||a.code!==gr.VERSION_CONFLICT_CODE||(0,EM.isFailureAfterPrimaryWrite)(a))throw a;if(this.createRecovery==="adoptExact"&&s?.status===412){let l=await(0,CM.recoverFormCreate)({client:this.dataverse,read:()=>t.api.get(this.dataverse,n),sent:s.sent,authoredFormType:o.formType,project:u=>t.adapter.fromApiResponse(u)});if("adopted"in l)return{adopted:l.adopted};throw new Z.SdkError(yr.ALREADY_EXISTS_CODE,`${rw(r,n)} ${TM(l.refused)}`)}throw new Z.SdkError(yr.ALREADY_EXISTS_CODE,rw(r,n))}}async persistAdoption(t,r,n,i){let{artifact:o,etag:a}=i,s=!(0,vn.deepEqual)(o,n);return await this.versions.storeMeta(t,r,{etag:a,...s?{refreshGeneration:this.nextRefreshGeneration(t,r,null),observedGeneration:0}:{},languageCode:this.languageCode,projectionVersion:ml.PROJECTION_VERSION,fetchedAt:(0,gr.nowIso)(),snapshot:(0,pi.cloneJson)(o)},null),s&&await this.workspace.writeArtifact(t,r,o),{type:t,id:r,saved:!1,adoptedExisting:!0,shipped:!1,publish:{kind:"notRequested"},...s?{refreshed:!0}:{}}}async buildMetadataContext(t,r,n){var i,o,a,s;let l=(o=(i=t.metadataNeeds)===null||i===void 0?void 0:i.call(t,r,n))!==null&&o!==void 0?o:[],u=new Set(l.map(k=>k.entityLogicalName).filter(k=>!!k)),c=new Set(l.filter(k=>k.needsColumnDetail).map(k=>k.entityLogicalName)),d=new Set(l.filter(k=>k.needsColumnDetail||!k.fieldName).map(k=>k.entityLogicalName)),f=k=>l.filter(I=>I.entityLogicalName===k).every(I=>I.fetchRequired===!1),m=new Map,p=new Map;for(let k of u){let I=await this.readCachedEntityMetadata(k);if(I&&c.has(k)&&(I.columnDetailComplete!==!0||!(typeof I.columnDetailVersion=="number"&&I.columnDetailVersion>=hl.COLUMN_DETAIL_VERSION)||I.attributes.some(D=>typeof D.attributeTypeName!="string"))&&(I=null),!I&&!d.has(k)){if(!f(k)){let D=l.filter(P=>P.entityLogicalName===k).map(P=>P.fieldName);try{let P=await(0,hl.readColumnHints)(this.dataverse,k,D);p.set(k,new Map(P.map(x=>[x.logicalName,x])))}catch{}}continue}if(!I&&!f(k))try{await this.loadMissedEntityMetadata(k),I=await this.readCachedEntityMetadata(k)}catch{}I&&m.set(k,I)}let h=(k,I)=>{var D,P,x;return(P=(D=m.get(k))===null||D===void 0?void 0:D.attributes.find(K=>K.logicalName===I))!==null&&P!==void 0?P:(x=p.get(k))===null||x===void 0?void 0:x.get(I)},g=this.languageCode,w=l.some(k=>{if(!k.needsLabel||!k.fieldName)return!1;let I=h(k.entityLogicalName,k.fieldName);return I?.localizedDisplayName!==void 0&&!I.localizedDisplayName[g]})?await this.readBaseLanguage():void 0,C=!((a=t.needsBaseLanguage)===null||a===void 0)&&a.call(t,r)?await this.readBaseLanguage():void 0,S=(s=t.customControlNeeds)===null||s===void 0?void 0:s.call(t,r,n),O=S&&(S.controls.length>0||S.columns.length>0)?await this.readPcfNeeds(S):void 0;return{resolveField:(k,I)=>{let D=h(k,I);return D?{displayName:Hae(D,g,w),attributeType:D.attributeType}:void 0},resolveEntity:k=>m.get(k),loadTypeScript:()=>this.compiler.load(),...C!==void 0?{baseLanguageCode:C}:{},...O?{pcf:O}:{}}}async readPcfNeeds(t){let r=new Map;for(let i of t.controls)r.set(i,await(0,wM.readControlManifest)(this.dataverse,i));let n=new Map;for(let i of t.columns)n.set(i,await(0,wM.readPcfColumn)(this.dataverse,t.entityLogicalName,i,t.requireCreateEligibility?{requireCreateEligibility:!0}:void 0));return{control:i=>r.get(i),column:(i,o)=>i===t.entityLogicalName?n.get(o):void 0}}readBaseLanguage(){if(!this.baseLanguage){let t=(async()=>{var r,n,i;try{let o=await this.dataverse.get("/organizations?$select=languagecode");if(o.status<200||o.status>=300)return;let a=Number((i=(n=(r=o.body)===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n[0])===null||i===void 0?void 0:i.languagecode);return Number.isInteger(a)&&a>0?a:void 0}catch{return}})();this.baseLanguage=t,t.then(r=>{r===void 0&&this.baseLanguage===t&&(this.baseLanguage=void 0)})}return this.baseLanguage}async pushAll(){let t=await this.getDirtyArtifacts();await this.warmBatchMetadata(t);let r=new Map,n=new Map;for(let o=0;o<t.length;o+=1){let a=t[o];try{await this.withArtifactLock(a.type,a.id,()=>this.prepareArtifactUnlocked(a.type,a.id,r))}catch(s){n.set(o,{type:a.type,id:a.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Ro(s)})}}if(n.size>0)return t.map((o,a)=>{var s;return(s=n.get(a))!==null&&s!==void 0?s:{type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:new Z.SdkError(yr.PUSH_NOT_ATTEMPTED_CODE,`Not attempted: ${n.size} artifact(s) in this batch could not be prepared, so no writes were issued. Fix the reported failures and push again.`)}});let i=[];for(let o of t)try{i.push(await this.withArtifactLock(o.type,o.id,()=>this.pushArtifactUnlocked(o.type,o.id,r)))}catch(a){i.push({type:o.type,id:o.id,saved:!1,shipped:!1,publish:{kind:"notRequested"},error:Ro(a)})}return i}async warmBatchMetadata(t){var r,n,i;let o=new Set;for(let a of t){let s=this.registrations.get(a.type);if(!s)continue;let l;try{l=await this.readLocal(a.type,a.id)}catch{continue}let u=l.entityLogicalName;u&&o.add(u);for(let c of(i=(n=(r=s.adapter).metadataNeeds)===null||n===void 0?void 0:n.call(r,l))!==null&&i!==void 0?i:[])c.entityLogicalName&&o.add(c.entityLogicalName)}for(let a of o)if(!await this.readCachedEntityMetadata(a))try{await this.loadMissedEntityMetadata(a)}catch{}}async getDirtyArtifacts(){return(await this.withDirtyFlags(await this.workspace.listArtifacts())).filter(r=>r.isDirty)}async diffArtifact(t,r){return this.versions.diff(t,r)}assignMissingIds(t,r){let n=this.registrations.get(t);return n?n.adapter.assignMissingIds(r):(0,lm.assignMissingIds)(r)}async resolveComponentType(t){if(t.genPage)return"genPage";switch(t.componentType){case rr.SolutionComponentType.SavedQuery:return"view";case rr.SolutionComponentType.SavedQueryVisualization:return"chart";case rr.SolutionComponentType.AppModule:return"app";case rr.SolutionComponentType.Workflow:return this.workflowArtifactType(t);case rr.SolutionComponentType.SystemForm:return this.systemFormArtifactType(t.objectId);default:return}}async systemFormArtifactType(t){let r=await(0,am.readSystemFormType)(this.dataverse,t);if(Number.isNaN(r))throw new Z.SdkError(tw,`System form '${t}' answered without a readable type, so whether it is a form or a dashboard cannot be told.`);return(0,am.systemFormKindOf)(r)}async workflowArtifactType(t){let r=(0,La.normalizeGuid)(t.objectId,"workflowId"),n=`/workflows(${r})${(0,La.odataQuery)([["$select","category,businessprocesstype"]])}`,o=(0,gr.ensureSuccess)(await this.dataverse.get(n),this.dataverse.apiUrl(n)).body,a=(0,am.decodeCode)(o?.category);if(Number.isNaN(a))throw new Z.SdkError(tw,`Workflow '${r}' answered without a readable category, so its kind cannot be told.`);if(t.workflowCategory=a,a===Fae)return"businessRule";if(a===Mae){let s=(0,am.decodeCode)(o?.businessprocesstype);if(Number.isNaN(s))throw new Z.SdkError(tw,`Workflow '${r}' (category 4) answered without a readable businessprocesstype, so whether it is a business process flow or a task flow cannot be told.`);return s===0?"bpf":void 0}}requireRegistration(t,r){let n=this.registrations.get(t);if(!n)throw new Z.NotImplementedError(r,`no adapter registered for artifact type '${t}'`);return n}};yr.MakerSdk=um;function zae(e){return new um(e)}yr.createMakerSdk=zae;function Ro(e){return e instanceof Error?e:new Error(String(e))}function RM(e,t){let r=Object.keys(e??{}),n=Object.keys(t??{});return r.length===n.length&&r.every(i=>Object.prototype.hasOwnProperty.call(t??{},i))}function kM(e){return Object.values(e??{}).every(gr.isVersionToken)}function jae(e,t){return RM(e,t)&&kM(e)&&Object.keys(e??{}).every(r=>t?.[r]===e?.[r])}function TM(e){return`createRecovery 'adoptExact' did not adopt it: ${e}.`}function rw(e,t,r){return`Cannot create ${e} '${t}': a record already exists at that id${r?` (${r})`:""}, so an earlier push of this artifact committed before its local version metadata was saved. No duplicate was created. Run fetchArtifact('${e}', '${t}', { overwrite: true }) to adopt the existing record's identity, etag and snapshot \u2014 the overwrite is required, because this local copy has never been pushed, so a plain fetch keeps it and adopts nothing; it REPLACES the local copy, so keep any outstanding local changes aside first \u2014 then re-apply them and push again: a conditional update, provided the adopted record is complete. If the earlier push committed only PART of a multi-row artifact (e.g. an app's appmodule without its sitemap), that update refuses, naming what is missing and how to remove the partial record. This is not done automatically because the only recovery available here would be an UNCONDITIONAL overwrite, which would destroy any edit made to the record in the meantime.`}function Hae(e,t,r){let n=e.localizedDisplayName;return n?.[t]||(r===void 0?void 0:n?.[r])||e.displayName}function Ki(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function DM(e){let t=e.lastIndexOf("/");return t<=0?"":e.slice(0,t)}function IM(e){e.length===0||!e.every(t=>Ki(t)&&typeof t.order=="number")||e.forEach((t,r)=>{t.order=r})}function Kae(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=>Ki(i)&&i.id===t.before);return n<0?e.length:n}let r=e.findIndex(n=>Ki(n)&&n.id===t.after);return r<0?e.length:r+1}});var $M=v(cm=>{"use strict";Object.defineProperty(cm,"__esModule",{value:!0});cm.ARTIFACT_TYPES=void 0;cm.ARTIFACT_TYPES=["form","view","businessRule","app","command","chart","dashboard","genPage","bpf"]});var FM=v(xM=>{"use strict";Object.defineProperty(xM,"__esModule",{value:!0})});var UM=v(MM=>{"use strict";Object.defineProperty(MM,"__esModule",{value:!0})});var qM=v(BM=>{"use strict";Object.defineProperty(BM,"__esModule",{value:!0})});var GM=v(VM=>{"use strict";Object.defineProperty(VM,"__esModule",{value:!0})});var zM=v(WM=>{"use strict";Object.defineProperty(WM,"__esModule",{value:!0})});var HM=v(jM=>{"use strict";Object.defineProperty(jM,"__esModule",{value:!0})});var JM=v(KM=>{"use strict";Object.defineProperty(KM,"__esModule",{value:!0})});var QM=v(YM=>{"use strict";Object.defineProperty(YM,"__esModule",{value:!0})});var ZM=v(XM=>{"use strict";Object.defineProperty(XM,"__esModule",{value:!0})});var tU=v(eU=>{"use strict";Object.defineProperty(eU,"__esModule",{value:!0})});var nU=v(rU=>{"use strict";Object.defineProperty(rU,"__esModule",{value:!0})});var oU=v(iU=>{"use strict";Object.defineProperty(iU,"__esModule",{value:!0})});var sU=v(aU=>{"use strict";Object.defineProperty(aU,"__esModule",{value:!0})});var uU=v(lU=>{"use strict";Object.defineProperty(lU,"__esModule",{value:!0})});var dU=v(cU=>{"use strict";Object.defineProperty(cU,"__esModule",{value:!0})});var pU=v(fU=>{"use strict";Object.defineProperty(fU,"__esModule",{value:!0})});var hU=v(mU=>{"use strict";Object.defineProperty(mU,"__esModule",{value:!0})});var yU=v(gU=>{"use strict";Object.defineProperty(gU,"__esModule",{value:!0})});var vU=v(bU=>{"use strict";Object.defineProperty(bU,"__esModule",{value:!0})});var CU=v(wU=>{"use strict";Object.defineProperty(wU,"__esModule",{value:!0})});var AU=v(EU=>{"use strict";Object.defineProperty(EU,"__esModule",{value:!0})});var NU=v(pe=>{"use strict";var Jae=pe&&pe.__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]})),Ge=pe&&pe.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&Jae(t,e,r)};Object.defineProperty(pe,"__esModule",{value:!0});pe.projectConnectorOperationSchema=pe.projectConnectorOperations=pe.createMakerSdk=void 0;var Yae=LM();Object.defineProperty(pe,"createMakerSdk",{enumerable:!0,get:function(){return Yae.createMakerSdk}});Ge($M(),pe);Ge(FM(),pe);Ge(UM(),pe);Ge(qM(),pe);Ge(GM(),pe);Ge(zM(),pe);Ge(HM(),pe);Ge(JM(),pe);Ge(QM(),pe);Ge(ZM(),pe);Ge(tU(),pe);Ge(nU(),pe);Ge(oU(),pe);Ge(sU(),pe);Ge(uU(),pe);Ge(Ud(),pe);Ge(dU(),pe);Ge(pU(),pe);Ge(hU(),pe);Ge(yU(),pe);Ge(vU(),pe);Ge(CU(),pe);Ge(AU(),pe);Ge(Q(),pe);var SU=Tl();Object.defineProperty(pe,"projectConnectorOperations",{enumerable:!0,get:function(){return SU.projectConnectorOperations}});Object.defineProperty(pe,"projectConnectorOperationSchema",{enumerable:!0,get:function(){return SU.projectConnectorOperationSchema}})});var iw=v(mi=>{"use strict";var Qae=mi&&mi.__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]})),Xae=mi&&mi.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),DU=mi&&mi.__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)&&Qae(t,e,r);return Xae(t,e),t};Object.defineProperty(mi,"__esModule",{value:!0});mi.NodeFileSystemStorage=void 0;var Ct=DU(require("fs")),nr=DU(require("path")),_U=Q(),TU=Bm();async function IU(e){let t;try{t=await Ct.promises.lstat(e)}catch{return}if(t.isSymbolicLink()){try{await Ct.promises.unlink(e)}catch{await Ct.promises.rmdir(e)}return}if(!t.isDirectory()){await Ct.promises.unlink(e);return}for(let r of await Ct.promises.readdir(e))await IU(nr.join(e,r));await Ct.promises.rmdir(e)}var nw=class{constructor(t){this.root=t}getRoot(){return this.root}pathFor(t,r=!0){return this.assertWithinRoot(nr.join(this.root,...t),r)}realPathThroughNearestAncestor(t){let r=t,n=[];for(;!Ct.existsSync(r);){n.unshift(nr.basename(r));let i=nr.dirname(r);if(i===r)return nr.resolve(t);r=i}return nr.resolve(Ct.realpathSync(r),...n)}assertWithinRoot(t,r){let n=nr.resolve(this.root),i=nr.resolve(t);if(i!==n&&!i.startsWith(n+nr.sep))throw new _U.PathTraversalError(t,this.root);let o=this.realPathThroughNearestAncestor(n),a=r?this.realPathThroughNearestAncestor(i):nr.resolve(this.realPathThroughNearestAncestor(nr.dirname(i)),nr.basename(i));if(a!==o&&!a.startsWith(o+nr.sep))throw new _U.PathTraversalError(t,this.root);return i}async readText(t){let r=this.pathFor(t);if(!Ct.existsSync(r))return null;try{return await(0,TU.retryTransientIoAsync)(()=>Ct.promises.readFile(r,"utf8"))}catch(n){if(n.code==="ENOENT")return null;throw n}}async writeTextAtomic(t,r){let n=this.pathFor(t),i=nr.dirname(n);await Ct.promises.mkdir(i,{recursive:!0});let o=nr.join(i,`.${nr.basename(n)}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);try{await Ct.promises.writeFile(o,r,"utf8"),await(0,TU.retryTransientIoAsync)(()=>Ct.promises.rename(o,n))}catch(a){try{Ct.existsSync(o)&&await Ct.promises.unlink(o)}catch{}throw a}}async deleteFile(t){let r=this.pathFor(t);Ct.existsSync(r)&&await Ct.promises.unlink(r)}async deleteByPrefix(t){await IU(this.pathFor(t,!1))}async ensureContainer(t){await Ct.promises.mkdir(this.pathFor(t),{recursive:!0})}async exists(t){return Ct.existsSync(this.pathFor(t))}};mi.NodeFileSystemStorage=nw});var OU=v(Ur=>{"use strict";var Zae=Ur&&Ur.__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]})),ese=Ur&&Ur.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),tse=Ur&&Ur.__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)&&Zae(t,e,r);return ese(t,e),t};Object.defineProperty(Ur,"__esModule",{value:!0});Ur.loadNodeTypeScript=Ur.createNodeWorkspaceStorage=Ur.NodeFileSystemStorage=void 0;var rse=iw(),nse=iw();Object.defineProperty(Ur,"NodeFileSystemStorage",{enumerable:!0,get:function(){return nse.NodeFileSystemStorage}});function ise(e){return new rse.NodeFileSystemStorage(e)}Ur.createNodeWorkspaceStorage=ise;async function ose(){return await Promise.resolve().then(()=>tse(require("typescript")))}Ur.loadNodeTypeScript=ose});var Ji={};module.exports=Br(Ji);Yi(Ji,Ae(NU()),module.exports);Yi(Ji,Ae(OU()),module.exports);