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.

12.3 KB
Raw Blame
'use strict';

const assert = require('node:assert/strict');
const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const test = require('node:test');
const vm = require('node:vm');
const { createSkillDataModelFirst, createSkillWorkflow } = require('./helpers/create-skill');

function caretVersionAtLeast(value, minimum) {
  const match = /^\^(\d+)\.(\d+)\.(\d+)$/.exec(value);
  assert.ok(match, `expected a caret semver range, received ${value}`);
  const actual = match.slice(1).map(Number);
  for (let index = 0; index < minimum.length; index += 1) {
    if (actual[index] !== minimum[index]) return actual[index] > minimum[index];
  }
  return true;
}

function extractMetroCollector(debugSkill) {
  const normalizedSkill = debugSkill.replace(/\r\n?/g, '\n');
  const collector = /node - "\$LOG_PATH" <saved-cursor> 262144 5000 <<'NODE'\n([\s\S]*?)\nNODE/.exec(normalizedSkill);
  assert.ok(collector, 'expected the foreground Metro log collector snippet');
  return collector[1];
}

function metroCollectorSource() {
  const pluginRoot = path.resolve(__dirname, '..', '..');
  const debugSkill = fs.readFileSync(path.join(pluginRoot, 'skills', 'debug-app', 'SKILL.md'), 'utf8');
  return extractMetroCollector(debugSkill);
}

function runMetroCollector(source, logPath, cursor, observationMs) {
  const result = spawnSync(
    process.execPath,
    ['-', logPath, String(cursor), '262144', String(observationMs)],
    { input: source, encoding: 'utf8', timeout: 2000 },
  );
  assert.equal(result.status, 0, result.stderr || result.error?.message);
  return JSON.parse(result.stdout);
}

test('template uses the host Metro factory that installs project-local logging', () => {
  const pluginRoot = path.resolve(__dirname, '..', '..');
  const workflow = fs.readFileSync(
    path.resolve(pluginRoot, '..', '..', '.github', 'workflows', 'mobile-apps-script-tests.yml'),
    'utf8',
  );
  const metroConfig = fs.readFileSync(path.join(pluginRoot, 'template', 'metro.config.js'), 'utf8');
  const gitignore = fs.readFileSync(path.join(pluginRoot, 'template', 'gitignore'), 'utf8');
  const packageJson = JSON.parse(fs.readFileSync(path.join(pluginRoot, 'template', 'package.json'), 'utf8'));

  assert.match(
    metroConfig,
    /const \{ createPowerAppsMetroConfig \} = require\('@microsoft\/power-apps-native-host\/config\/metroConfig'\);/,
  );
  assert.doesNotMatch(
    metroConfig,
    /power-apps-native-host\/metro-logger|SENSITIVE_LINE_PATTERN|appendMetroLog|process\.stdout\.write/,
  );
  assert.ok(
    caretVersionAtLeast(packageJson.dependencies['@microsoft/power-apps-native-host'], [0, 2, 26]),
    'the host package must include the Metro logger introduced in 0.2.26',
  );
  assert.match(gitignore, /^\.powernative\//m);
  const workflowCoversMobileApps = /plugins\/mobile-apps\/\*\*/.test(workflow);
  assert.ok(workflowCoversMobileApps || /plugins\/mobile-apps\/template\/metro\.config\.js/.test(workflow));
  assert.ok(workflowCoversMobileApps || /plugins\/mobile-apps\/template\/package\.json/.test(workflow));
  assert.match(workflow, /appDisplayName: 'Template Quality Probe'/);
  assert.match(workflow, /npm run predev/);
});

test('skill contracts read logs and persist host-neutral state under .powernative', () => {
  const pluginRoot = path.resolve(__dirname, '..', '..');
  const createSkill = createSkillWorkflow();
  const debugSkill = fs.readFileSync(path.join(pluginRoot, 'skills', 'debug-app', 'SKILL.md'), 'utf8');
  const deploySkill = fs.readFileSync(path.join(pluginRoot, 'skills', 'deploy', 'SKILL.md'), 'utf8');
  const reportIssueSkill = fs.readFileSync(path.join(pluginRoot, 'skills', 'report-issue', 'SKILL.md'), 'utf8');
  const agentsGuide = fs.readFileSync(path.join(pluginRoot, 'AGENTS.md'), 'utf8');

  const createFrontmatter = createSkill.split('---', 3)[1];
  assert.match(createFrontmatter, /allowed-tools:.*\bSkill\b/);
  assert.match(createSkill, /\.powernative\/metro-logs/);
  assert.match(createSkill, /npm run dev/);
  assert.match(createSkill, /^### Step 16 [^\r\n]*Metro writes project-local logs/m);
  // Screens first has run one `npm run dev` since Step 3.5; Step 16 confirms it through Metro's
  // own health endpoint and must not start a second server beside it.
  const reuse = createSkill.slice(createSkill.indexOf('**Screens first: reuse the running server.**'),
    createSkill.indexOf('**Launch command:**'));
  assert.match(reuse, /Do not start a second one/);
  assert.match(reuse, /\/status'[\s\S]*packager-status:running/);
  assert.match(reuse, /fell back to `--localhost`: stop that server/);
  // Template preparation's explanation of each fix lives beside SKILL.md, read when a fix fails.
  const templatePreparation = fs.readFileSync(path.join(pluginRoot, 'skills', 'create-mobile-app', 'references', 'template-preparation.md'), 'utf8');
  assert.match(templatePreparation, /createPowerAppsMetroConfig/);
  assert.match(createSkill, /template owns the `dev` and `predev` command bodies/);
  assert.match(createSkill, /does not require either script to expand to a particular command/);
  // Preparation, not the model, checks the lifecycle scripts exist (and only that).
  const prepareScript = fs.readFileSync(path.join(pluginRoot, 'scripts', 'prepare-mobile-template.js'), 'utf8');
  assert.match(prepareScript, /for \(const scriptName of \['dev', 'predev'\]\)/);
  assert.match(prepareScript, /typeof pkg\.scripts\?\.\[scriptName\] !== 'string'/);
  assert.match(prepareScript, /pkg\.scripts\[scriptName\]\.trim\(\) === ''/);
  assert.match(templatePreparation, /verifyLifecycleScripts/);
  assert.match(createSkill, /always receives a scannable code even when Metro runs in a background terminal/);
  assert.match(createSkill, /Do not rely on Expo's terminal-rendered QR as the only presentation path/);
  // The QR generator must come from the template's pinned devDependency, never a registry fetch.
  assert.match(createSkill, /npx --no-install qrcode -o "\$METRO_QR"/);
  assert.doesNotMatch(createSkill, /npx --yes|npm_config_registry=/);
  assert.match(createSkill, /continue through the optional debug handoff and print the summary/);
  assert.doesNotMatch(createSkill, /stops after Step 16/);
  assert.doesNotMatch(createSkill, /npx expo start|without rerunning the `predev` schema hook/);
  assert.doesNotMatch(createSkill, /delegates Metro terminal output.*power-apps-native-host\/metro-logger/);
  assert.doesNotMatch(createSkill, /scripts\/metro-session\.js|dev:expo|copy the plugin wrapper/i);

  // The data-model-first order launches Metro at its own Step 12 through the same shared
  // dev-server step, and checks the lifecycle scripts inline, as it always has.
  const dataModelFirst = createSkillDataModelFirst();
  assert.match(dataModelFirst, /^### Step 12 [^\r\n]*Metro writes project-local logs/m);
  assert.match(dataModelFirst, /createPowerAppsMetroConfig/);
  assert.match(dataModelFirst, /template owns the `dev` and `predev` command bodies/);
  assert.match(dataModelFirst, /for \(const scriptName of \['dev', 'predev'\]\)/);
  assert.match(dataModelFirst, /npx --no-install qrcode -o "\$METRO_QR"/);
  assert.match(dataModelFirst, /continue through the optional debug handoff and print the summary/);
  assert.doesNotMatch(dataModelFirst, /npx --yes|npm_config_registry=|npx expo start/);
  assert.match(debugSkill, /\.powernative\/metro-logs/);
  assert.match(debugSkill, /\.powernative\/debug-app/);
  assert.doesNotMatch(debugSkill, /\.claude\/debug-app/);
  assert.match(debugSkill, /--working-dir <path>/);
  assert.match(debugSkill, /Use `workingDir` from argument parsing as `<working_dir>`/);
  assert.match(debugSkill, /every relative project path and command below runs from that directory/);
  assert.match(debugSkill, /Early-return subcommands/);
  assert.match(debugSkill, /execute only Phase 0\.0 discovery through the status branch/);
  assert.match(debugSkill, /read `\.powernative\/debug-app\/metro-cursor\.json` only when it is nonempty valid JSON/);
  assert.match(debugSkill, /process\.kill\(pid, 0\)/);
  assert.match(debugSkill, /Treat a missing, empty, malformed, or shape-invalid file as no saved cursor/);
  assert.match(debugSkill, /discover valid project-local Metro sessions/i);
  assert.match(debugSkill, /"logPath":/);
  assert.match(debugSkill, /"pid":/);
  assert.match(debugSkill, /predates project-local Metro logging/);
  assert.match(debugSkill, /createPowerAppsMetroConfig/);
  assert.match(debugSkill, /factory installs project-local logging internally/);
  assert.match(debugSkill, /exact subpath resolves from the project's installed dependencies/);
  assert.match(debugSkill, /dependency version string alone does not prove/);
  assert.doesNotMatch(debugSkill, /raw return value|any auth\/data props passed in|JSON\.stringify\(value\) for objects/);
  assert.match(debugSkill, /Never log raw records, response bodies, arbitrary objects/);
  assert.doesNotMatch(debugSkill, /recorded as `NEEDS ATTENTION`/);
  assert.doesNotMatch(debugSkill, /status\.running|verbatim error|<exact error line>/);
  assert.match(debugSkill, /Output contains only the logger startup line/);
  assert.match(debugSkill, /append only the verifier's output/);
  assert.match(debugSkill, /logging instrumentation failed/);
  assert.match(debugSkill, /baseline read gets `ENOENT`/);
  assert.match(debugSkill, /watcher = fs\.watch/);
  assert.match(debugSkill, /observation: interval/);
  assert.match(debugSkill, /a frame under `node_modules\/@microsoft\/power-apps-native-\*` is evidence, not proof/i);
  assert.match(debugSkill, /confirmed package-owned defect routes to `\/report-issue`/i);
  assert.match(debugSkill, /do not edit `node_modules\/`, generate `patch-package` artifacts or postinstall rewrites/i);
  assert.match(debugSkill, /replace the dependency with a git\/tarball\/local path/i);
  assert.match(reportIssueSkill, /collect its declared and lockfile-resolved versions from `package\.json` and `package-lock\.json`/);
  assert.match(reportIssueSkill, /Do not read package source or metadata from `node_modules\/`/);
  assert.match(reportIssueSkill, /### Affected native package/);
  assert.match(agentsGuide, /First-party native package defects are reported, not patched in customer projects/);
  assert.doesNotMatch(debugSkill, /ordinary tool execution provides the cadence/);
  assert.doesNotThrow(() => new vm.Script(metroCollectorSource()));
  assert.doesNotThrow(() => new vm.Script(extractMetroCollector(debugSkill.replace(/\n/g, '\r\n'))));
  const traceScanCount = (debugSkill.match(/find app src -type f/g) || []).length;
  const generatedExclusionCount = (debugSkill.match(/! -path 'src\/generated\/\*'/g) || []).length;
  assert.ok(traceScanCount >= 2, 'expected trace discovery and verification scans');
  assert.equal(generatedExclusionCount, traceScanCount, 'every trace scan must exclude generated code');
  assert.doesNotMatch(debugSkill, /tail -n 500 "\$LOG_PATH"/);
  assert.doesNotMatch(debugSkill, /BashOutput|METRO_TERMINAL_ID|metro-session\.js|start --project-root/);
  assert.match(deploySkill, /\.powernative/);
  assert.match(agentsGuide, /user-owned `npm run dev`/);
  assert.doesNotMatch(agentsGuide, /detached project-local process|start\/status\/tail\/stop/);
});

test('Metro collector returns already-appended bytes without waiting', (context) => {
  const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'metro-collector-backlog-'));
  context.after(() => fs.rmSync(directory, { recursive: true, force: true }));
  const logPath = path.join(directory, 'metro.log');
  fs.writeFileSync(logPath, 'new output');

  const result = runMetroCollector(metroCollectorSource(), logPath, 0, 1000);

  assert.equal(result.observation, 'initial');
  assert.equal(result.output, 'new output');
  assert.equal(result.nextCursor, 10);
  assert.equal(result.readError, null);
});

test('Metro collector waits for a complete idle observation interval', (context) => {
  const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'metro-collector-idle-'));
  context.after(() => fs.rmSync(directory, { recursive: true, force: true }));
  const logPath = path.join(directory, 'metro.log');
  fs.writeFileSync(logPath, 'existing');

  const result = runMetroCollector(metroCollectorSource(), logPath, 8, 50);

  assert.equal(result.observation, 'interval');
  assert.equal(result.output, '');
  assert.ok(result.observedMs >= 40, `expected an idle wait, received ${result.observedMs}ms`);
  assert.equal(result.readError, null);
});