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.

10.1 KB
Raw Blame
'use strict';
// Shared REAL-BUNDLE harness for the form-layout tests that need the SDK's own serializer and fetch:
// the vendored SDK against a stub HTTP client that stores ONE systemform row. A form "exists" once it has
// formxml (the fixture's, or one the engine created), so the same harness serves a create and a rebuild.
//
// The stub answers only what a `forms`-phase build and `--verify` read; anything else fails the test, so a
// new request a change introduces shows up here instead of being silently absorbed.
const assert = require('node:assert');
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 { verifySpec } = require('../../lib/verify-spec.js');
const { readerFor } = require('../../verify-model-app.js');
const { EXPORT_PATH } = require('./translation-export.js');

const guid = (n) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;
const clone = (v) => JSON.parse(JSON.stringify(v));
const NOTES_CLASS_ID = '06375649-C143-495E-A496-C962E5B4488E';
const SUBGRID_CLASS_ID = 'E7A81278-8635-4D9E-8D4D-59480B391C5B';
const VIEW_ID = guid(7777);
const DEFAULT_ATTRIBUTES = { new_name: 'String', new_code: 'String', new_notes: 'Memo', new_area: 'String', new_extra: 'String' };

// The labels of a FormXML in the languages `languages` (LCIDs) only. Measured live: a form published with Spanish (3082) captions in an
// organization whose base language is English (1033) stores both languages — a translation export finds them — yet the published FormXML the
// Web API returns carries the labels in 1033 alone, with or without an Accept-Language of the other language. `store.readLanguages` makes a
// harness read that way (see createHarness); a label the SDK serializes is `<label description="…" languagecode="1036" />`.
const onlyLanguages = (formxml, languages) => String(formxml).replace(/<label\b[^>]*?\blanguagecode="(\d+)"[^>]*?\/>/g, (label, lcid) => (languages.includes(Number(lcid)) ? label : ''));

// `languageCode` is the organization's base language, what a read of the organization answers. `sdkLanguageCode` is the language the SDK is MADE
// for — the one the build writes its labels in, which `--language-code` can set apart from the organization's — and is the SDK's own default
// when it is left out. `createSdk` makes the SDK (the raw bundle's factory unless a test names another: the production factory over the production HTTP client, say).
function createHarness({ formId = guid(1), entity = 'new_ticket', formName = 'Main', attributes = DEFAULT_ATTRIBUTES, languageCode = 1033, sdkLanguageCode, createSdk = createMakerSdk } = {}) {
  const dirs = [];
  const store = { row: { formid: formId, name: formName, objecttypecode: entity, type: 2, isdefault: true } };
  // A form as a read returns it: whole, unless `store.readLanguages` (a list of LCIDs) limits the languages its labels are shown in.
  const shown = (row) => (store.readLanguages && row.formxml ? { ...clone(row), formxml: onlyLanguages(row.formxml, store.readLanguages) } : clone(row));
  const writes = [];
  const reads = [];
  // The translation exports a verify asked for. `store.exportTranslation` is what the platform answers one with — an `{ status, headers, body }`, or a function of the request body
  // that gives one — and a verify is given the reader's translationLabels only when it is set (see verifyForms), so a test that does not configure an export never reaches it.
  const exportsAsked = [];
  let revision = 1;
  const response = (body, status = 200) => ({ status, headers: { etag: `W/"${revision}"` }, body });
  const httpClient = {
    get: async (url) => {
      reads.push(url);
      const decoded = decodeURIComponent(url);
      if (decoded.includes(`EntityDefinitions(LogicalName='${entity}')`)) {
        return response({ LogicalName: entity, EntitySetName: `${entity}s`,
          Attributes: Object.entries(attributes).map(([LogicalName, AttributeType]) => ({ LogicalName, AttributeType })) });
      }
      if (/EntityDefinitions\(LogicalName='systemform'\)/.test(decoded)) return response({ EntitySetName: 'systemforms' });
      // The organization's base language: `--verify` reads it to know which language the build wrote a string tab or section label in.
      if (/EntityDefinitions\(LogicalName='organization'\)/.test(decoded)) return response({ EntitySetName: 'organizations' });
      if (/\/organizations(?:\?|$)/i.test(url)) return response({ value: [{ languagecode: languageCode }] });
      if (/systemforms\(/i.test(url)) {
        assert.ok(store.row.formxml, 'a fetch reads a form that has been serialized');
        return response(shown(store.row));
      }
      if (/\/systemforms(?:\?|$)/i.test(url)) return response({ value: store.row.formxml ? [shown(store.row)] : [] });
      assert.fail(`unexpected GET: ${url}`);
    },
    post: async (url, body) => {
      if (EXPORT_PATH.test(url)) {
        exportsAsked.push({ url, body: clone(body) });
        assert.ok(store.exportTranslation, 'a translation export was asked for, and this harness has none to answer with');
        return typeof store.exportTranslation === 'function' ? store.exportTranslation(body) : store.exportTranslation;
      }
      writes.push({ method: 'post', url, body: clone(body) });
      if (/\/systemforms(?:\?|$)/i.test(url)) {
        store.row = { ...store.row, ...body, formid: formId };
        return { ...response({}, 204), headers: { 'odata-entityid': `https://contoso.crm.dynamics.com/api/data/v9.2/systemforms(${formId})` } };
      }
      if (/\/(?:PublishXml|AddSolutionComponent)(?:\?|$)/.test(url)) return response({}, 204);
      assert.fail(`unexpected POST: ${url}`);
    },
    patch: async (url, body) => {
      assert.match(url, /\/systemforms\(/i);
      writes.push({ method: 'patch', url, body: clone(body) });
      store.row = { ...store.row, ...body };
      revision += 1;
      return response({}, 204);
    },
    put: async (url) => assert.fail(`unexpected PUT: ${url}`),
    delete: async (url) => assert.fail(`unexpected DELETE: ${url}`),
  };
  // A new SDK over a new workspace: a second apply must not lean on the first one's local copy.
  const freshSdk = async (workspaceDir) => {
    const dir = workspaceDir || fs.mkdtempSync(path.join(os.tmpdir(), 'form-layout-rt-'));
    if (!workspaceDir) dirs.push(dir);
    const sdk = createSdk({ workspaceStorage: createNodeWorkspaceStorage(dir),
      instanceUrl: 'https://contoso.crm.dynamics.com', httpClient, ...(sdkLanguageCode ? { languageCode: sdkLanguageCode } : {}) });
    await sdk.initWorkspace();
    const mutations = [];
    // These wrappers record calls and delegate every one to the real bundle.
    for (const method of ['createArtifact', 'addElement', 'updateElement', 'moveElement', 'removeElement', 'updateRecord', 'setFormSecurityRoles']) {
      const original = sdk[method].bind(sdk);
      sdk[method] = async (...args) => {
        mutations.push({ method, args: clone(args) });
        return original(...args);
      };
    }
    // A sub-grid embeds the id of its child table's view, which the build looks up with a query of its own (the
    // table's default public view); the stub answers it with one view and delegates every other query.
    const queryRecords = sdk.queryRecords.bind(sdk);
    sdk.queryRecords = async (set, options) => (set === 'savedquery' ? [{ savedqueryid: VIEW_ID, isdefault: true }] : queryRecords(set, options));
    return { sdk, mutations, dir };
  };
  const cleanup = () => { for (const d of dirs) fs.rmSync(d, { recursive: true, force: true }); };
  return { store, writes, reads, exportsAsked, freshSdk, cleanup, formId, entity, attributes };
}

// Put a form on the server the way the engine's create does — a minimal artifact, each compiled tab added
// whole, the seed tab dropped, one push — from the given tabs. Returns the server's form id.
async function seedForm(h, tabs, { name = 'Main', entity = h.entity } = {}) {
  const seed = await h.freshSdk();
  const art = await seed.sdk.createArtifact('form', { name, entityLogicalName: entity, formType: 'Main' });
  for (const tab of tabs) await seed.sdk.addElement('form', art.id, '/tabs', tab);
  await seed.sdk.removeElement('form', art.id, '/tabs/0');
  const pushed = await seed.sdk.pushArtifact('form', art.id);
  assert.ok(pushed && pushed.saved !== false, `the fixture form is pushed: ${JSON.stringify(pushed && pushed.error)}`);
  return h.formId;
}

// `--verify` over what the server holds, through the plugin's own reader (the published formxml query). `opts` are verifySpec's own. The reader also asks for a translation
// export (its translationLabels) when the harness has one to answer with (`store.exportTranslation`).
async function verifyForms(h, spec, opts) {
  const fetched = await h.freshSdk();
  const live = readerFor(fetched.sdk, spec.app.uniqueName);
  const read = {
    findTable: async () => ({ logicalName: h.entity }),
    findColumns: async () => Object.keys(h.attributes).map((logicalName) => ({ logicalName })),
    sitemapXml: async () => '',
    queryRecords: live.queryRecords,
    formTopology: live.formTopology,
    ...(h.store.exportTranslation ? { translationLabels: live.translationLabels } : {}),
  };
  return verifySpec(spec, read, opts);
}

// The FormXML of the section `name`.
function sectionXml(formxml, name) {
  const at = formxml.indexOf(`name="${name}"`);
  assert.ok(at > 0, `section ${name} is in the formxml`);
  const start = formxml.lastIndexOf('<section', at);
  const end = formxml.indexOf('</section>', at) + '</section>'.length;
  return formxml.slice(start, end);
}

// A run of empty rows written as a count — `<row />×22` — so a test can state the exact shape of a
// timeline host without a 22-row literal.
const collapseEmptyRows = (xml) => String(xml).replace(/(?:<row \/>)+/g, (run) => `<row />×${run.length / '<row />'.length}`);

module.exports = { guid, clone, createHarness, seedForm, verifyForms, sectionXml, collapseEmptyRows, NOTES_CLASS_ID, SUBGRID_CLASS_ID, VIEW_ID, DEFAULT_ATTRIBUTES };