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.

41.0 KB
Raw Blame
'use strict';

const assert = require('assert');
const { spawnSync } = require('node:child_process');
const fs = require('fs');
const Module = require('module');
const path = require('path');
const test = require('node:test');

const {
  HOST_TSCONFIG,
  WEB_PREVIEW_ENV,
  assertFreshTemplate,
  ensureWebPreviewOutput,
  parseArgs,
  prepareMobileTemplate,
  prepareRootLayout,
} = require('../prepare-mobile-template');

const pluginRoot = path.resolve(__dirname, '../..');
const templateRoot = path.join(pluginRoot, 'template');
const guidanceFiles = ['AGENTS.md', 'CLAUDE.md', '.github/copilot-instructions.md'];
const copyableGuidanceFiles = ['AGENTS.md', 'CLAUDE.md'];
const nestedGuidanceFiles = ['.github/copilot-instructions.md'];
const fixtureDirectories = [];

test.after(() => {
  for (const directory of fixtureDirectories) {
    fs.rmSync(directory, { recursive: true, force: true });
  }
});

function tempDirectory(name) {
  const directory = fs.mkdtempSync(path.join(__dirname, `.${name}-`));
  fixtureDirectories.push(directory);
  return directory;
}

function copyTemplate(sourceRoot = templateRoot, relativeDirectory = '') {
  const projectRoot = path.join(tempDirectory('mobile-template'), relativeDirectory);
  fs.cpSync(sourceRoot, projectRoot, {
    recursive: true,
    filter: (source) => path.basename(source) !== 'node_modules',
  });
  fs.mkdirSync(path.join(projectRoot, 'node_modules', 'expo'), { recursive: true });
  return projectRoot;
}

function loadAppConfig(configPath) {
  const originalLoad = Module._load;
  Module._load = function load(request, parent, isMain) {
    if (request === '@microsoft/power-apps-native-host/config/expoConfig') {
      return {
        createPowerAppsExpoConfig(baseConfig, settings, customize) {
          return customize({
            ...baseConfig,
            name: settings.name,
            slug: settings.slug,
          });
        },
      };
    }
    return originalLoad.call(this, request, parent, isMain);
  };
  try {
    delete require.cache[require.resolve(configPath)];
    return require(configPath);
  } finally {
    Module._load = originalLoad;
  }
}

function fileSnapshot(projectRoot) {
  const snapshot = new Map();
  function visit(directory) {
    for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
      if (entry.name === 'node_modules') continue;
      const absolutePath = path.join(directory, entry.name);
      if (entry.isDirectory()) visit(absolutePath);
      else snapshot.set(path.relative(projectRoot, absolutePath), fs.readFileSync(absolutePath));
    }
  }
  visit(projectRoot);
  return snapshot;
}

function assertSnapshotsEqual(left, right) {
  assert.deepStrictEqual([...left.keys()].sort(), [...right.keys()].sort());
  for (const [relativePath, content] of left) {
    assert.deepStrictEqual(right.get(relativePath), content, relativePath);
  }
}

test('template test fixtures exclude installed dependencies and local dependency caches', (context) => {
  const sourceRoot = tempDirectory('mobile-template-source');
  context.after(() => fs.rmSync(sourceRoot, { recursive: true, force: true }));
  fs.writeFileSync(path.join(sourceRoot, 'package.json'), '{"name":"fixture"}\n');
  fs.mkdirSync(path.join(sourceRoot, 'node_modules', '.cache'), { recursive: true });
  fs.writeFileSync(path.join(sourceRoot, 'node_modules', '.cache', 'local-run.txt'), 'not template source');
  const projectRoot = copyTemplate(sourceRoot);
  context.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));
  assert.equal(fs.readFileSync(path.join(projectRoot, 'package.json'), 'utf8'), '{"name":"fixture"}\n');
  assert.deepStrictEqual(fs.readdirSync(path.join(projectRoot, 'node_modules')), ['expo']);
});

function removeGuidance(projectRoot) {
  for (const relativePath of guidanceFiles) {
    fs.unlinkSync(path.join(projectRoot, relativePath));
  }
}

const guidanceOptions = { displayName: 'Guidance App', slug: 'guidance-app' };

test('preparation CLI copies POSIX-relative guidance beneath a native root with spaces', () => {
  const projectRoot = copyTemplate(templateRoot, "app's folder [test]");
  removeGuidance(projectRoot);
  fs.rmdirSync(path.join(projectRoot, '.github'));
  assert.ok(path.isAbsolute(projectRoot));
  const result = spawnSync(process.execPath, [
    path.resolve(__dirname, '../prepare-mobile-template.js'),
    '--working-dir', projectRoot,
    '--display-name', 'Native Path Probe',
    '--slug', 'native-path-probe',
  ], { cwd: path.dirname(projectRoot), encoding: 'utf8', timeout: 10000 });
  assert.strictEqual(result.status, 0, result.stderr);
  const report = JSON.parse(result.stdout);
  assert.deepStrictEqual(report.copiedGuidanceFiles, copyableGuidanceFiles);
  assert.deepStrictEqual(report.skippedGuidanceFiles, nestedGuidanceFiles);
  for (const relativePath of copyableGuidanceFiles) {
    assert.ok(report.writtenFiles.includes(relativePath));
    assert.deepStrictEqual(
      fs.readFileSync(path.join(projectRoot, ...relativePath.split('/'))),
      fs.readFileSync(path.join(templateRoot, relativePath)),
    );
  }
});

test('preparation adds only missing guidance and reports exact writer ownership', () => {
  const projectRoot = copyTemplate();
  removeGuidance(projectRoot);
  fs.rmdirSync(path.join(projectRoot, '.github'));
  const before = fileSnapshot(projectRoot);
  const result = prepareMobileTemplate({ workingDir: projectRoot, ...guidanceOptions });
  const after = fileSnapshot(projectRoot);

  assert.deepStrictEqual(result.copiedGuidanceFiles, copyableGuidanceFiles);
  assert.deepStrictEqual(result.preservedGuidanceFiles, []);
  assert.deepStrictEqual(result.skippedGuidanceFiles, nestedGuidanceFiles);
  assert.deepStrictEqual(result.writtenFiles, [...after]
    .filter(([name, content]) => !before.has(name) || !content.equals(before.get(name)))
    .map(([name]) => name.split(path.sep).join('/'))
    .sort());
  for (const relativePath of copyableGuidanceFiles) {
    assert.deepStrictEqual(
      fs.readFileSync(path.join(projectRoot, relativePath)),
      fs.readFileSync(path.join(templateRoot, relativePath)),
    );
    assert.ok(result.writtenFiles.includes(relativePath));
  }

  const repeated = prepareMobileTemplate({ workingDir: projectRoot, ...guidanceOptions });
  assert.deepStrictEqual(repeated.writtenFiles, []);
  assert.deepStrictEqual(repeated.copiedGuidanceFiles, []);
  assert.deepStrictEqual(repeated.preservedGuidanceFiles, copyableGuidanceFiles);
  assert.deepStrictEqual(repeated.skippedGuidanceFiles, nestedGuidanceFiles);
  assertSnapshotsEqual(after, fileSnapshot(projectRoot));
});

test('preparation preserves customer guidance bytes and fills a partial set', () => {
  const projectRoot = copyTemplate();
  const customAgents = Buffer.from('\ufeff# Customer rules\r\nPreserve exactly.\r\n');
  fs.writeFileSync(path.join(projectRoot, 'AGENTS.md'), customAgents);
  fs.writeFileSync(path.join(projectRoot, 'CLAUDE.md'), '');
  fs.unlinkSync(path.join(projectRoot, '.github', 'copilot-instructions.md'));
  const unrelated = path.join(projectRoot, '.github', 'customer.txt');
  fs.writeFileSync(unrelated, 'customer-owned\n');

  const result = prepareMobileTemplate({ workingDir: projectRoot, ...guidanceOptions });
  assert.deepStrictEqual(result.copiedGuidanceFiles, []);
  assert.deepStrictEqual(result.preservedGuidanceFiles, copyableGuidanceFiles);
  assert.deepStrictEqual(result.skippedGuidanceFiles, nestedGuidanceFiles);
  assert.deepStrictEqual(fs.readFileSync(path.join(projectRoot, 'AGENTS.md')), customAgents);
  assert.strictEqual(fs.readFileSync(path.join(projectRoot, 'CLAUDE.md'), 'utf8'), '');
  assert.strictEqual(fs.readFileSync(unrelated, 'utf8'), 'customer-owned\n');
  assert.ok(!result.writtenFiles.includes('AGENTS.md'));
  assert.ok(!result.writtenFiles.includes('CLAUDE.md'));
  assert.strictEqual(
    fs.existsSync(path.join(projectRoot, '.github', 'copilot-instructions.md')),
    false,
  );
});

test('preparation preserves all existing customer guidance byte-for-byte', () => {
  const projectRoot = copyTemplate();
  for (const relativePath of guidanceFiles) {
    fs.writeFileSync(path.join(projectRoot, relativePath), `Customer: ${relativePath}\r\n`);
  }
  const before = fileSnapshot(projectRoot);
  const result = prepareMobileTemplate({ workingDir: projectRoot, ...guidanceOptions });
  assert.deepStrictEqual(result.copiedGuidanceFiles, []);
  assert.deepStrictEqual(result.preservedGuidanceFiles, guidanceFiles);
  assert.deepStrictEqual(result.skippedGuidanceFiles, []);
  for (const relativePath of guidanceFiles) {
    assert.deepStrictEqual(
      fs.readFileSync(path.join(projectRoot, relativePath)),
      before.get(relativePath.split('/').join(path.sep)),
    );
    assert.ok(!result.writtenFiles.includes(relativePath));
  }
});

for (const keepParent of [false, true]) {
  test(`guidance rollback restores missing files and ${keepParent ? 'preserves' : 'removes new'} parent`, () => {
    const projectRoot = copyTemplate();
    removeGuidance(projectRoot);
    if (!keepParent) fs.rmdirSync(path.join(projectRoot, '.github'));
    // The error occurs after guidance copying, so rollback must undo real writes.
    const layoutPath = path.join(projectRoot, 'app', '_layout.tsx');
    fs.writeFileSync(layoutPath, fs.readFileSync(layoutPath, 'utf8')
      .replace('<Slot />', '<SafeAreaView><Slot /></SafeAreaView>'));
    const before = fileSnapshot(projectRoot);
    assert.throws(() => prepareMobileTemplate({
      workingDir: projectRoot, ...guidanceOptions,
    }), /must not wrap Slot with SafeAreaView/);
    assertSnapshotsEqual(before, fileSnapshot(projectRoot));
    assert.strictEqual(fs.existsSync(path.join(projectRoot, '.github')), keepParent);
  });
}

test('guidance rollback preserves custom files and unrelated parent contents', () => {
  const projectRoot = copyTemplate();
  fs.writeFileSync(path.join(projectRoot, 'AGENTS.md'), 'Customer-owned\r\n');
  fs.unlinkSync(path.join(projectRoot, 'CLAUDE.md'));
  fs.unlinkSync(path.join(projectRoot, '.github', 'copilot-instructions.md'));
  fs.writeFileSync(path.join(projectRoot, '.github', 'customer.txt'), 'Keep me\n');
  const layoutPath = path.join(projectRoot, 'app', '_layout.tsx');
  fs.writeFileSync(layoutPath, fs.readFileSync(layoutPath, 'utf8')
    .replace('<Slot />', '<SafeAreaView><Slot /></SafeAreaView>'));
  const before = fileSnapshot(projectRoot);
  assert.throws(() => prepareMobileTemplate({
    workingDir: projectRoot, ...guidanceOptions,
  }), /must not wrap Slot with SafeAreaView/);
  assertSnapshotsEqual(before, fileSnapshot(projectRoot));
});

test('exclusive guidance creation and rollback do not claim a concurrent customer write', (t) => {
  const projectRoot = copyTemplate();
  removeGuidance(projectRoot);
  const before = fileSnapshot(projectRoot);
  const customerPath = path.join(projectRoot, 'CLAUDE.md');
  const originalCopy = fs.copyFileSync;
  t.mock.method(fs, 'copyFileSync', (source, destination, flags) => {
    if (destination === customerPath) fs.writeFileSync(customerPath, 'Concurrent customer rules\n');
    return originalCopy(source, destination, flags);
  });
  assert.throws(() => prepareMobileTemplate({
    workingDir: projectRoot, ...guidanceOptions,
  }), { code: 'EEXIST' });
  before.set('CLAUDE.md', Buffer.from('Concurrent customer rules\n'));
  assertSnapshotsEqual(before, fileSnapshot(projectRoot));
  assert.ok(fs.statSync(path.join(projectRoot, '.github')).isDirectory());
});

test('guidance rollback preserves a customer replacement made after exclusive copy', (t) => {
  const projectRoot = copyTemplate();
  removeGuidance(projectRoot);
  const layoutPath = path.join(projectRoot, 'app', '_layout.tsx');
  fs.writeFileSync(layoutPath, fs.readFileSync(layoutPath, 'utf8')
    .replace('<Slot />', '<SafeAreaView><Slot /></SafeAreaView>'));
  const before = fileSnapshot(projectRoot);
  const customerPath = path.join(projectRoot, 'AGENTS.md');
  const customerContent = Buffer.from('Customer replaced guidance after copy\n');
  const originalCopy = fs.copyFileSync;
  t.mock.method(fs, 'copyFileSync', (source, destination, flags) => {
    const result = originalCopy(source, destination, flags);
    if (destination === customerPath) fs.writeFileSync(customerPath, customerContent);
    return result;
  });

  assert.throws(() => prepareMobileTemplate({
    workingDir: projectRoot, ...guidanceOptions,
  }), /rollback failed: customer-modified guidance preserved: AGENTS\.md/);
  before.set('AGENTS.md', customerContent);
  assertSnapshotsEqual(before, fileSnapshot(projectRoot));
});

test('preparation rejects a symlinked project root without mutations', (t) => {
  const projectRoot = copyTemplate();
  const before = fileSnapshot(projectRoot);
  const link = path.join(tempDirectory('guidance-project-link'), 'app');
  try {
    fs.symlinkSync(projectRoot, link, 'junction');
  } catch (error) {
    if (!['EPERM', 'EACCES', 'ENOTSUP'].includes(error.code)) throw error;
    t.skip('Symlink creation is unavailable on this host');
    return;
  }
  assert.throws(() => prepareMobileTemplate({
    workingDir: link, ...guidanceOptions,
  }), /must not traverse a symlink: project root/);
  assertSnapshotsEqual(before, fileSnapshot(projectRoot));
});

for (const relativePath of [...guidanceFiles, '.github']) {
  for (const dangling of [false, true]) {
    test(`preparation rejects ${dangling ? 'dangling ' : ''}guidance symlink ${relativePath}`, (t) => {
      const projectRoot = copyTemplate();
      const externalRoot = tempDirectory('guidance-link-target');
      const targetIsDirectory = relativePath === '.github';
      const target = path.join(externalRoot, targetIsDirectory ? 'instructions' : 'rules.md');
      if (!dangling) {
        if (targetIsDirectory) fs.mkdirSync(target);
        else fs.writeFileSync(target, 'External rules\n');
      }
      const link = path.join(projectRoot, relativePath);
      fs.rmSync(link, { recursive: true });
      const before = fileSnapshot(projectRoot);
      const externalBefore = fileSnapshot(externalRoot);
      try {
        fs.symlinkSync(target, link, targetIsDirectory ? 'junction' : 'file');
      } catch (error) {
        if (!['EPERM', 'EACCES', 'ENOTSUP'].includes(error.code)) throw error;
        t.skip('Symlink creation is unavailable on this host');
        return;
      }
      assert.throws(() => prepareMobileTemplate({
        workingDir: projectRoot, ...guidanceOptions,
      }), /must not traverse a symlink/);
      assert.ok(fs.lstatSync(link).isSymbolicLink());
      fs.unlinkSync(link);
      assertSnapshotsEqual(before, fileSnapshot(projectRoot));
      assertSnapshotsEqual(externalBefore, fileSnapshot(externalRoot));
    });
  }
}

test('preparation rejects a non-directory guidance parent without mutations', () => {
  const projectRoot = copyTemplate();
  fs.rmSync(path.join(projectRoot, '.github'), { recursive: true });
  fs.writeFileSync(path.join(projectRoot, '.github'), 'Customer file\n');
  const before = fileSnapshot(projectRoot);
  assert.throws(() => prepareMobileTemplate({
    workingDir: projectRoot, ...guidanceOptions,
  }), /target must be a directory: \.github/);
  assertSnapshotsEqual(before, fileSnapshot(projectRoot));
});

test('preparation is idempotent and preserves generated and existing helper files', () => {
  const projectRoot = copyTemplate();
  const tsconfigPath = path.join(projectRoot, 'tsconfig.json');
  const originalTsconfig = fs.readFileSync(tsconfigPath);
  const generatedPath = path.join(projectRoot, 'src', 'generated', 'index.ts');
  const existingHelperPath = path.join(projectRoot, 'src', 'components', 'index.tsx');
  fs.mkdirSync(path.dirname(generatedPath), { recursive: true });
  fs.mkdirSync(path.dirname(existingHelperPath), { recursive: true });
  fs.writeFileSync(generatedPath, '// generated-owner sentinel\n');
  fs.writeFileSync(existingHelperPath, '// existing-helper sentinel\n');
  fs.mkdirSync(path.join(projectRoot, 'src', 'hooks'), { recursive: true });
  fs.writeFileSync(path.join(projectRoot, 'src', 'hooks', 'useContacts.ts'), '// legacy example\n');
  fs.writeFileSync(path.join(projectRoot, 'power.config.json'), '{"environmentId":""}\n');
  fs.writeFileSync(path.join(projectRoot, 'native-app-plan.md'), '# Approved plan\n');

  const beforeFirstRun = fileSnapshot(projectRoot);
  const first = prepareMobileTemplate({
    workingDir: projectRoot,
    displayName: "R&D $& Inspector's Workspace",
    slug: 'inspectors-workspace',
  });

  assert.strictEqual(first.removedPowerConfig, true);
  const changedFiles = [...fileSnapshot(projectRoot)]
    .filter(([relativePath, content]) => (
      !beforeFirstRun.has(relativePath) || !content.equals(beforeFirstRun.get(relativePath))
    ))
    .map(([relativePath]) => relativePath.split(path.sep).join('/'))
    .sort();
  assert.deepStrictEqual(first.writtenFiles, changedFiles);
  assert.ok(!first.writtenFiles.includes('power.config.json'));
  assert.ok(!first.writtenFiles.includes('src/hooks/useContacts.ts'));
  assert.ok(first.removedLegacyFiles.includes('src/hooks/useContacts.ts'));
  assert.ok(!first.writtenFiles.includes('src/components/index.tsx'));
  assert.ok(!first.writtenFiles.includes('src/generated/index.ts'));
  // Without `--screens-first` the app gets no data layer: screen-builder and /edit-app read an
  // existing src/hooks/data/ as a data-layer app.
  assert.ok(!first.writtenFiles.includes('src/hooks/data/core.ts'));
  assert.ok(!fs.existsSync(path.join(projectRoot, 'src', 'hooks', 'data')));
  assert.strictEqual(first.webPreviewOutput, 'not-requested');
  assert.deepStrictEqual(fs.readFileSync(generatedPath, 'utf8'), '// generated-owner sentinel\n');
  assert.deepStrictEqual(fs.readFileSync(existingHelperPath, 'utf8'), '// existing-helper sentinel\n');
  assert.deepStrictEqual(
    fs.readFileSync(path.join(projectRoot, 'native-app-plan.md'), 'utf8'),
    '# Approved plan\n',
  );
  assert.match(
    fs.readFileSync(path.join(projectRoot, 'app.config.js'), 'utf8'),
    /R&D \$& Inspector\\'s Workspace/,
  );
  assert.strictEqual(require(path.join(projectRoot, 'package.json')).name, 'inspectors-workspace');

  const tsconfig = require(path.join(projectRoot, 'tsconfig.json'));
  assert.strictEqual(tsconfig.extends, HOST_TSCONFIG);
  assert.strictEqual(tsconfig.compilerOptions, undefined);
  assert.deepStrictEqual(fs.readFileSync(tsconfigPath), originalTsconfig);

  const layout = fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8');
  assert.match(layout, /<SafeAreaProvider>/);
  assert.match(layout, /offlineProfile=\{offlineProfile\}/);
  assert.match(layout, /tamaguiConfig=\{tamaguiConfig\}/);
  assert.match(layout, /defaultTheme=/);
  assert.doesNotMatch(layout, /theme=\{lightTheme\}/);
  assert.doesNotMatch(layout, /darkTheme=\{darkTheme\}/);
  assert.doesNotMatch(layout, /<SafeAreaView[\s\S]*<Slot\s*\/>/);
  assert.match(layout, /@ts-ignore - power\.config\.json/);
  assert.match(layout, /@ts-ignore - connectorSchemas/);

  const beforeSecondRun = fileSnapshot(projectRoot);
  const second = prepareMobileTemplate({
    workingDir: projectRoot,
    displayName: "R&D $& Inspector's Workspace",
    slug: 'inspectors-workspace',
  });
  const afterSecondRun = fileSnapshot(projectRoot);
  assert.ok(second.preservedSharedFiles.length > 0);
  assert.deepStrictEqual(second.writtenFiles, []);
  assertSnapshotsEqual(beforeSecondRun, afterSecondRun);
});

test('scaffold validation uses preparation writes, not later generator output', (t) => {
  const projectRoot = copyTemplate();
  t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));
  const configPath = path.join(projectRoot, 'power.config.json');
  fs.writeFileSync(configPath, '{"environmentId":""}\n');
  const options = { workingDir: projectRoot, displayName: 'Validation App', slug: 'validation-app' };
  const prepared = prepareMobileTemplate(options);
  assert.strictEqual(prepared.removedPowerConfig, true);

  // Simulate init recreating the deleted placeholder and schema generation writing output.
  const generatedConfig = '{"environmentId":"approved-environment","appDisplayName":"Validation App"}\n';
  fs.writeFileSync(configPath, generatedConfig);
  const generatedPath = path.join(projectRoot, 'src', 'generated', 'index.ts');
  fs.mkdirSync(path.dirname(generatedPath), { recursive: true });
  fs.writeFileSync(generatedPath, 'export {};\n');
  const repeated = prepareMobileTemplate(options);
  assert.strictEqual(repeated.removedPowerConfig, false);
  assert.deepStrictEqual(repeated.writtenFiles, []);
  assert.strictEqual(fs.readFileSync(configPath, 'utf8'), generatedConfig);
  fs.writeFileSync(path.join(projectRoot, 'memory-bank.md'), '# Verified scaffold\n');

  function validate(files) {
    return spawnSync(process.execPath, [
      path.join(pluginRoot, 'scripts', 'validate-mobile-files.js'),
      '--project-root', projectRoot,
      ...files.flatMap((file) => ['--file', file]),
    ], {
      cwd: projectRoot,
      encoding: 'utf8',
      env: { ...process.env, POWER_PLATFORM_SKILLS_TELEMETRY_MOBILE_APP_OPTOUT: '1' },
    });
  }

  // The bundled fixture is not a verified runtime release. Source preparation
  // can still be tested, but its package write must not bypass native admission.
  const packageValidation = validate(['package.json']);
  assert.strictEqual(packageValidation.status, 2, packageValidation.stderr);
  assert.match(packageValidation.stderr, /package-lock\.json/i);
  const manualFiles = [...prepared.writtenFiles.filter((file) => file !== 'package.json'), 'memory-bank.md'];
  const valid = validate(manualFiles);
  assert.strictEqual(valid.status, 0, valid.stderr);
  for (const file of ['power.config.json', path.relative(projectRoot, generatedPath)]) {
    const blocked = validate([file]);
    assert.strictEqual(blocked.status, 2, blocked.stderr);
    assert.match(blocked.stderr, /BLOCKED: protected path/);
  }

  fs.writeFileSync(configPath, '{"environmentId":"manual-edit"}\n');
  const manualEdit = validate(['power.config.json']);
  assert.strictEqual(manualEdit.status, 2, manualEdit.stderr);
  assert.match(manualEdit.stderr, /owned by `pa app init`/);
});

test('preparation round-trips JavaScript line terminators in app display names', () => {
  const projectRoot = copyTemplate();
  const displayName = "Line 1\nLine 2\rLine 3\u2028Line 4\u2029Inspector's App";
  prepareMobileTemplate({
    workingDir: projectRoot,
    displayName,
    slug: 'line-safe-app',
  });

  const configPath = path.join(projectRoot, 'app.config.js');
  const source = fs.readFileSync(configPath, 'utf8');
  assert.match(source, /Line 1\\nLine 2\\rLine 3\\u2028Line 4\\u2029Inspector\\'s App/);
  const createConfig = loadAppConfig(configPath);
  assert.strictEqual(createConfig({ config: {} }).name, displayName);
});

test('preparation rejects a template that does not inherit the host tsconfig', () => {
  const projectRoot = copyTemplate();
  const tsconfigPath = path.join(projectRoot, 'tsconfig.json');
  fs.writeFileSync(tsconfigPath, JSON.stringify({
    extends: 'expo/tsconfig.base',
    compilerOptions: { paths: {} },
  }, null, 2));
  const before = fileSnapshot(projectRoot);

  assert.throws(() => prepareMobileTemplate({
    workingDir: projectRoot,
    displayName: 'Unsupported Template',
    slug: 'unsupported-template',
  }), /must extend @microsoft\/power-apps-native-host\/config\/tsconfig/);

  assertSnapshotsEqual(before, fileSnapshot(projectRoot));
});

test('fresh-template validation allows the approved plan but blocks created-app markers', () => {
  const projectRoot = copyTemplate();
  fs.writeFileSync(path.join(projectRoot, 'native-app-plan.md'), '# Approved plan\n');
  assert.doesNotThrow(() => assertFreshTemplate(projectRoot));

  fs.writeFileSync(path.join(projectRoot, 'memory-bank.md'), '# Created app\n');
  assert.throws(() => assertFreshTemplate(projectRoot), /memory-bank\.md/);
  fs.unlinkSync(path.join(projectRoot, 'memory-bank.md'));

  fs.writeFileSync(path.join(projectRoot, '.datamodel-manifest.json'), '{}\n');
  assert.throws(() => assertFreshTemplate(projectRoot), /\.datamodel-manifest\.json/);
  fs.unlinkSync(path.join(projectRoot, '.datamodel-manifest.json'));

  const generatedServices = path.join(projectRoot, 'src', 'generated', 'services');
  fs.mkdirSync(generatedServices, { recursive: true });
  fs.writeFileSync(path.join(generatedServices, 'CreatedService.ts'), 'export {};\n');
  assert.throws(() => assertFreshTemplate(projectRoot), /src\/generated\/services\/\*\.ts/);
});

test('fresh-template validation requires the template-owned dev lifecycle scripts, not their bodies', (context) => {
  const projectRoot = copyTemplate();
  context.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));
  const packagePath = path.join(projectRoot, 'package.json');
  const pkg = JSON.parse(fs.readFileSync(packagePath, 'utf8'));

  // Any non-empty body is the template's choice.
  fs.writeFileSync(packagePath, JSON.stringify({ ...pkg, scripts: { ...pkg.scripts, dev: 'custom-dev', predev: 'custom-predev' } }));
  assert.doesNotThrow(() => assertFreshTemplate(projectRoot));

  for (const scriptName of ['dev', 'predev']) {
    for (const value of [undefined, '   ', 42]) {
      const scripts = { ...pkg.scripts, [scriptName]: value };
      if (value === undefined) delete scripts[scriptName];
      fs.writeFileSync(packagePath, JSON.stringify({ ...pkg, scripts }));
      assert.throws(() => assertFreshTemplate(projectRoot), new RegExp(`scripts\\.${scriptName} to be a non-empty command`));
    }
  }
});

function writeLayoutFixture(source) {
  const projectRoot = tempDirectory('root-layout');
  fs.mkdirSync(path.join(projectRoot, 'app'), { recursive: true });
  fs.writeFileSync(path.join(projectRoot, 'app', '_layout.tsx'), source);
  return projectRoot;
}

const providerBody = `
      <PowerAppsProvider
        msalConfig={authConfig.msal}
        offlineProfile={offlineProfile}
        customHostProp="preserve-me"
      >
        <CustomNavigation>
          <Slot />
        </CustomNavigation>
      </PowerAppsProvider>`;

const fixtureImports = `import { Slot } from 'expo-router';
import { PowerAppsProvider } from '@microsoft/power-apps-native-host';
import authConfig from '../auth.config.json';
import { offlineProfile } from '../offline';
`;

test('root preparation handles import-only safe-area state', () => {
  const projectRoot = writeLayoutFixture(`${fixtureImports}
import { SafeAreaProvider } from 'react-native-safe-area-context';
export default function RootLayout() {
  return (${providerBody}
  );
}
`);
  prepareRootLayout(projectRoot);
  const result = fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8');
  assert.match(result, /<SafeAreaProvider>[\s\S]*<PowerAppsProvider/);
  assert.match(result, /customHostProp="preserve-me"/);
  assert.match(result, /<CustomNavigation>/);
});

test('root preparation reuses semicolonless combined, named, and default imports', () => {
  const projectRoot = writeLayoutFixture(`import { Slot } from 'expo-router'
import ReactNative, { useColorScheme } from 'react-native'
import { SafeAreaProvider } from 'react-native-safe-area-context'
import { PowerAppsProvider } from '@microsoft/power-apps-native-host'
import tamaguiConfig, { appLightTheme } from '../tamagui.config'
import authConfig from '../auth.config.json'
import { offlineProfile } from '../offline'

export default function RootLayout() {
  const colorScheme = useColorScheme()
  return (${providerBody}
  )
}
`);
  prepareRootLayout(projectRoot);
  const result = fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8');

  assert.strictEqual((result.match(/from ['"]react-native['"]/g) || []).length, 1);
  assert.strictEqual(
    (result.match(/from ['"]react-native-safe-area-context['"]/g) || []).length,
    1,
  );
  assert.strictEqual(
    (result.match(/from ['"]@microsoft\/power-apps-native-host['"]/g) || []).length,
    1,
  );
  assert.strictEqual((result.match(/from ['"]\.\.\/tamagui\.config['"]/g) || []).length, 1);
  assert.match(result, /import tamaguiConfig,\s*\{\s*appLightTheme\s*\}\s*from\s*'\.\.\/tamagui\.config'/s);
  assert.match(result, /import ReactNative,\s*\{[^}]*\buseColorScheme\b[^}]*\}\s*from\s*'react-native'/s);
  assert.doesNotMatch(result, /\blightTheme\b|\bdarkTheme\b/);
  assert.match(result, /<SafeAreaProvider>[\s\S]*<PowerAppsProvider/);
});

test('root preparation creates the required colorScheme binding when the hook uses another name', () => {
  const projectRoot = writeLayoutFixture(`${fixtureImports}
import { useColorScheme } from 'react-native';
export default function RootLayout() {
  const scheme = useColorScheme();
  return (${providerBody}
  );
}
`);
  prepareRootLayout(projectRoot);
  const result = fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8');
  assert.match(result, /const scheme = useColorScheme\(\);/);
  assert.match(result, /const colorScheme = useColorScheme\(\);/);
  assert.match(result, /defaultTheme=\{colorScheme === 'dark' \? 'dark' : 'light'\}/);
});

test('root preparation handles wrapper-only and already-correct states idempotently', () => {
  const projectRoot = writeLayoutFixture(`${fixtureImports}
export default function RootLayout() {
  return (
    <SafeAreaProvider>${providerBody}
    </SafeAreaProvider>
  );
}
`);
  prepareRootLayout(projectRoot);
  const first = fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8');
  prepareRootLayout(projectRoot);
  const second = fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8');
  assert.strictEqual(second, first);
  assert.strictEqual((second.match(/<SafeAreaProvider>/g) || []).length, 1);
  assert.match(second, /offlineProfile=\{offlineProfile\}/);
});

test('root preparation preserves custom outer provider nesting', () => {
  const projectRoot = writeLayoutFixture(`${fixtureImports}
export default function RootLayout() {
  return (
    <TelemetryBoundary>
${providerBody}
    </TelemetryBoundary>
  );
}
`);
  prepareRootLayout(projectRoot);
  const result = fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8');
  assert.match(result, /<TelemetryBoundary>[\s\S]*<SafeAreaProvider>[\s\S]*<PowerAppsProvider/);
  assert.match(result, /<\/PowerAppsProvider>[\s\S]*<\/SafeAreaProvider>[\s\S]*<\/TelemetryBoundary>/);
});

test('safe-area wrapping preserves multiline provider prop values byte-for-byte', () => {
  const multilineValue = `customMessage={\`first line
        intentionally indented second line\`}`;
  const multilineProvider = `<PowerAppsProvider
      ${multilineValue}
    >
      <Slot />
    </PowerAppsProvider>`;
  const projectRoot = writeLayoutFixture(`${fixtureImports}
export default function RootLayout() {
  return (
    ${multilineProvider}
  );
}
`);
  prepareRootLayout(projectRoot);
  const result = fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8');
  assert.ok(result.includes(multilineValue));
});

test('provider preparation preserves JSX and callback prop values byte-for-byte', () => {
  const jsxValue = 'customHeader={<Header title="A > B" tamaguiConfig={nestedConfig} theme={nestedLight} darkTheme={nestedDark} />}';
  const callbackValue = 'renderHeader={() => <Header compact />}';
  const projectRoot = writeLayoutFixture(`${fixtureImports}
export default function RootLayout() {
  return (
    <PowerAppsProvider
      ${jsxValue}
      ${callbackValue}
    >
      <Slot />
    </PowerAppsProvider>
  );
}
`);
  prepareRootLayout(projectRoot);
  const first = fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8');
  assert.ok(first.includes(jsxValue));
  assert.ok(first.includes(callbackValue));
  assert.match(first, /\n\s+tamaguiConfig=\{tamaguiConfig\}\n/);
  assert.doesNotMatch(first, /\n\s+theme=\{lightTheme\}\n/);
  assert.doesNotMatch(first, /\n\s+darkTheme=\{darkTheme\}\n/);
  prepareRootLayout(projectRoot);
  assert.strictEqual(
    fs.readFileSync(path.join(projectRoot, 'app', '_layout.tsx'), 'utf8'),
    first,
  );
});

test('root preparation rejects a root-owned SafeAreaView around Slot', () => {
  const projectRoot = writeLayoutFixture(`${fixtureImports}
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context';
export default function RootLayout() {
  return (
    <SafeAreaProvider>
      <PowerAppsProvider tamaguiConfig={tamaguiConfig} defaultTheme="light">
        <SafeAreaView><Slot /></SafeAreaView>
      </PowerAppsProvider>
    </SafeAreaProvider>
  );
}
`);
  assert.throws(() => prepareRootLayout(projectRoot), /must not wrap Slot with SafeAreaView/);
});

test('failed full preparation restores every mutated file', () => {
  const projectRoot = copyTemplate();
  const layoutPath = path.join(projectRoot, 'app', '_layout.tsx');
  const invalidLayout = fs.readFileSync(layoutPath, 'utf8')
    .replace('<Slot />', '<SafeAreaView><Slot /></SafeAreaView>');
  fs.writeFileSync(layoutPath, invalidLayout);
  fs.writeFileSync(path.join(projectRoot, 'power.config.json'), '{"environmentId":""}\n');
  const before = fileSnapshot(projectRoot);

  assert.throws(() => prepareMobileTemplate({
    workingDir: projectRoot,
    displayName: 'Rollback Probe',
    slug: 'rollback-probe',
  }), /must not wrap Slot with SafeAreaView/);

  assertSnapshotsEqual(before, fileSnapshot(projectRoot));
});

test('only the screens-first order gets the data layer and the web-preview override', () => {
  const dataModelFirst = copyTemplate();
  const configBefore = fs.readFileSync(path.join(dataModelFirst, 'app.config.js'), 'utf8');
  const plain = prepareMobileTemplate({ workingDir: dataModelFirst, displayName: 'Plain App', slug: 'plain-app' });
  assert.strictEqual(plain.webPreviewOutput, 'not-requested');
  assert.doesNotMatch(fs.readFileSync(path.join(dataModelFirst, 'app.config.js'), 'utf8'), new RegExp(WEB_PREVIEW_ENV));
  assert.match(configBefore, /customizeExpoConfig/);
  assert.ok(!fs.existsSync(path.join(dataModelFirst, 'src', 'hooks', 'data')));

  // The preview data layer's shared contract sits one folder deeper than the other helpers; the
  // screens built before any data source exists import it, so it is copied with its folder.
  const screensFirst = copyTemplate();
  const preview = prepareMobileTemplate({
    workingDir: screensFirst, displayName: 'Preview App', slug: 'preview-app', screensFirst: true,
  });
  assert.ok(preview.writtenFiles.includes('src/hooks/data/core.ts'));
  assert.ok(fs.existsSync(path.join(screensFirst, 'src', 'hooks', 'data', 'core.ts')));
  assert.strictEqual(preview.webPreviewOutput, 'added');

  assert.deepStrictEqual(parseArgs(['--working-dir', '.', '--screens-first']).screensFirst, true);
});

test('the sample-data web preview opts out of per-request server rendering, and nothing else does', () => {
  const projectRoot = copyTemplate();
  const result = prepareMobileTemplate({
    workingDir: projectRoot, displayName: 'Preview App', slug: 'preview-app', screensFirst: true,
  });
  assert.strictEqual(result.webPreviewOutput, 'added');
  assert.ok(result.writtenFiles.includes('app.config.js'));

  // The host's default is static output; only the preview env var switches it to single.
  const createConfig = loadAppConfig(path.join(projectRoot, 'app.config.js'));
  const hostDefault = { web: { bundler: 'metro', output: 'static' } };
  const previous = process.env[WEB_PREVIEW_ENV];
  try {
    delete process.env[WEB_PREVIEW_ENV];
    assert.strictEqual(createConfig({ config: hostDefault }).web.output, 'static');
    process.env[WEB_PREVIEW_ENV] = '1';
    const preview = createConfig({ config: hostDefault }).web;
    assert.deepStrictEqual(preview, { bundler: 'metro', output: 'single' });
  } finally {
    if (previous === undefined) delete process.env[WEB_PREVIEW_ENV];
    else process.env[WEB_PREVIEW_ENV] = previous;
  }

  // Idempotent: a second pass finds the override and changes nothing.
  const before = fs.readFileSync(path.join(projectRoot, 'app.config.js'), 'utf8');
  assert.strictEqual(ensureWebPreviewOutput(projectRoot), 'present');
  assert.strictEqual(fs.readFileSync(path.join(projectRoot, 'app.config.js'), 'utf8'), before);
});

test('an unrecognized customization hook is reported, not rewritten', () => {
  const projectRoot = copyTemplate();
  const configPath = path.join(projectRoot, 'app.config.js');
  const custom = fs.readFileSync(configPath, 'utf8').replace(
    'function customizeExpoConfig(config) {',
    'const customizeExpoConfig = (config) => {',
  );
  fs.writeFileSync(configPath, custom);
  assert.strictEqual(ensureWebPreviewOutput(projectRoot), 'unsupported');
  assert.strictEqual(fs.readFileSync(configPath, 'utf8'), custom);
});

test('a CRLF checkout of the template still gets the web-preview override, in its own line endings', () => {
  // A Windows checkout with core.autocrlf gives app.config.js CRLF endings; the override must still
  // go in, without leaving the file half LF and half CRLF.
  const projectRoot = copyTemplate();
  const configPath = path.join(projectRoot, 'app.config.js');
  const crlf = fs.readFileSync(configPath, 'utf8').replace(/\r?\n/g, '\r\n');
  fs.writeFileSync(configPath, crlf);
  assert.strictEqual(ensureWebPreviewOutput(projectRoot), 'added');
  const updated = fs.readFileSync(configPath, 'utf8');
  assert.match(updated, new RegExp(WEB_PREVIEW_ENV));
  assert.doesNotMatch(updated, /[^\r]\n/, 'every line still ends in CRLF');
  assert.strictEqual(ensureWebPreviewOutput(projectRoot), 'present');
});

test('a failed screens-first preparation leaves no directory it created behind', () => {
  // Directory presence is meaningful: screen-builder and /edit-app treat an existing src/hooks/data/
  // as a data-layer app. So rollback must remove the folders it made (the template has no src/ at
  // all), deepest first, while keeping any folder that was already there.
  function directories(root) {
    const found = [];
    (function visit(relative) {
      for (const entry of fs.readdirSync(path.join(root, relative), { withFileTypes: true })) {
        if (!entry.isDirectory() || entry.name === 'node_modules') continue;
        found.push(path.join(relative, entry.name));
        visit(path.join(relative, entry.name));
      }
    })('');
    return found.sort();
  }
  function failPreparation(projectRoot) {
    const layoutPath = path.join(projectRoot, 'app', '_layout.tsx');
    fs.writeFileSync(layoutPath, fs.readFileSync(layoutPath, 'utf8').replace('<Slot />', '<SafeAreaView><Slot /></SafeAreaView>'));
    const before = { files: fileSnapshot(projectRoot), directories: directories(projectRoot) };
    assert.throws(() => prepareMobileTemplate({
      workingDir: projectRoot, displayName: 'Rollback Probe', slug: 'rollback-probe', screensFirst: true,
    }), /must not wrap Slot with SafeAreaView/);
    assertSnapshotsEqual(before.files, fileSnapshot(projectRoot));
    assert.deepStrictEqual(directories(projectRoot), before.directories);
  }

  const fresh = copyTemplate();
  assert.ok(!fs.existsSync(path.join(fresh, 'src')));
  failPreparation(fresh);

  const existing = copyTemplate();
  fs.mkdirSync(path.join(existing, 'src', 'hooks'), { recursive: true });
  failPreparation(existing);
  assert.ok(fs.existsSync(path.join(existing, 'src', 'hooks')), 'a folder that was already there stays');
});

test('preparation preserves compatibility, customer extras, instructions and explicit aliases', (t) => {
  const projectRoot = copyTemplate();
  t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));
  const appConfig = JSON.parse(fs.readFileSync(path.join(projectRoot, 'app.json'), 'utf8'));
  appConfig.expo.extra.powerappsNative = {
    schemaVersion: 1, templateVersion: 7, nativeRuntimeVersions: { android: 4, ios: 6 },
  };
  appConfig.expo.extra.customerSetting = { enabled: true, nested: ['keep'] };
  const preservedFiles = {
    'app.json': JSON.stringify(appConfig),
    'AGENTS.md': '# Customer rules\nDo not replace this file.\n',
    'CLAUDE.md': '@AGENTS.md\n# Custom extension\n',
    '.github/copilot-instructions.md': 'Follow the customer rules.\n',
    'tsconfig.json': JSON.stringify({
      extends: HOST_TSCONFIG,
      compilerOptions: {
        baseUrl: '.',
        paths: { '@/*': ['./src/*'], '@/native/*': ['./src/native/*'] },
      },
    }),
    'power.config.json': '{"environmentId":"","connectionReferences":{"customer":{"keep":true}}}',
  };
  for (const [file, content] of Object.entries(preservedFiles)) {
    fs.mkdirSync(path.dirname(path.join(projectRoot, file)), { recursive: true });
    fs.writeFileSync(path.join(projectRoot, file), content);
  }
  const result = prepareMobileTemplate({
    workingDir: projectRoot, displayName: 'Preservation probe', slug: 'preservation-probe',
  });
  assert.equal(result.removedPowerConfig, false);
  for (const [file, content] of Object.entries(preservedFiles)) {
    assert.equal(fs.readFileSync(path.join(projectRoot, file), 'utf8'), content, file);
  }
});

test('missing or malformed compatibility metadata blocks before any preparation edits', (t) => {
  const projectRoot = copyTemplate();
  t.after(() => fs.rmSync(projectRoot, { recursive: true, force: true }));
  for (const powerappsNative of [
    undefined,
    { schemaVersion: 1, templateVersion: 1, nativeRuntimeVersions: { android: 1 } },
    { schemaVersion: 1, templateVersion: '1.0.0', nativeRuntimeVersions: { android: 1, ios: 1 } },
  ]) {
    fs.writeFileSync(path.join(projectRoot, 'app.json'), JSON.stringify({ expo: { extra: { powerappsNative } } }));
    const before = fileSnapshot(projectRoot);
    assert.throws(() => prepareMobileTemplate({
      workingDir: projectRoot, displayName: 'Do not write', slug: 'do-not-write',
    }), /powerappsNative|metadata|runtime|templateVersion/i);
    assertSnapshotsEqual(before, fileSnapshot(projectRoot));
  }
});