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.

7.5 KB
Raw Blame
#!/usr/bin/env node
'use strict';
// Record or check the base marker an upload compares against (#673).
//
//   node scripts/genpage-base.js record --page-id <id> --file <page.tsx> [--app-id <id>]
//        [--deployed-sha256 <hash>]
//   node scripts/genpage-base.js check --env <url> --app-id <id> --page-id <id> --file <local.tsx>
//
// `record` without `--deployed-sha256` is the post-download case: the file IS the deployed page,
// so both hashes are the file's. `--deployed-sha256` binds a chosen local file to the hash `check`
// observed, which is not the local file's hash when the user picked a different base.
//
// `--app-id` is optional for `record`: a page needs no app, and a first page is created before the app that
// will hold it (apps.js create takes the page's id), so such a page is recorded with the page alone — a marker
// with no app, which lib/genpage-base.js already allows. The first update that names the app the page was
// then placed in proves the page is in that app's navigation, goes ahead on that marker, and records the app.
// `check` still takes the app: it reads the deployed page the way an update of it would.
//
// `check` reads the deployed page, compares, and — only when the normalized texts differ — writes
// `<basename>.deployed.tsx` next to the local file for review. The SDK's throwaway workspace is
// removed before the result is emitted: the real emitter calls `process.exit`, so a cleanup after
// `emit` would never run. A folder it could not remove, which holds the page's source, is a `warnings` entry of the result.

const path = require('node:path');
const { parseArgs, validateFlags, emitResult } = require('./lib/dataverse-auth.js');
const { makeGenpageSdk } = require('./lib/genpage-sdk.js');
const { leftOnDiskWarning } = require('./lib/left-on-disk.js');
const { writeFileSafe } = require('./lib/safe-fs.js');
const {
  pageHash,
  readMarker,
  writeMarker,
  compareWithMarker,
  lineDelta,
  deployedCopyPath,
  readPlainText,
  markerPath,
} = require('./lib/genpage-base.js');
const { makeWritesBlocking } = require('./lib/output-redaction.js');

const USAGE = 'Usage: node scripts/genpage-base.js record --page-id <id> --file <page.tsx> [--app-id <id>] [--deployed-sha256 <hash>]\n'
  + '       node scripts/genpage-base.js check --env <url> --app-id <id> --page-id <id> --file <local.tsx>';

const RECORD_FLAGS = ['app-id', 'page-id', 'file', 'deployed-sha256'];
const CHECK_FLAGS = ['env', 'app-id', 'page-id', 'file'];
const SHA256_RE = /^[0-9a-fA-F]{64}$/;

function required(flags, names, emit) {
  for (const name of names) {
    if (typeof flags[name] !== 'string' || !flags[name].trim()) {
      return emit(false, { error: `--${name} is required\n${USAGE}` });
    }
  }
  return null;
}

function record(flags, emit) {
  const missing = required(flags, ['page-id', 'file'], emit);
  if (missing) return missing;
  let text;
  try {
    text = readPlainText(path.resolve(flags.file));
  } catch (e) {
    return emit(false, { error: e.message });
  }
  const localSha256 = pageHash(text);
  let deployedSha256 = localSha256;
  if (typeof flags['deployed-sha256'] === 'string') {
    if (!SHA256_RE.test(flags['deployed-sha256'])) {
      return emit(false, { error: '--deployed-sha256 must be a sha256 hex hash from genpage-base.js check' });
    }
    deployedSha256 = flags['deployed-sha256'].toLowerCase();
  }
  try {
    const body = writeMarker(flags.file, {
      version: 1,
      pageId: flags['page-id'],
      // No key for a page no app holds yet: the marker then records the page alone (see the header).
      ...(flags['app-id'] ? { appId: flags['app-id'] } : {}),
      deployedSha256,
      localSha256,
      source: 'download',
    });
    return emit(true, {
      ok: true,
      marker: markerPath(flags.file),
      pageId: body.pageId,
      ...(body.appId ? { appId: body.appId } : {}),
      deployedSha256: body.deployedSha256,
      localSha256: body.localSha256,
      source: body.source,
      recordedAt: body.recordedAt,
    });
  } catch (e) {
    return emit(false, { error: e.message });
  }
}

async function check(flags, emit, deps) {
  const missing = required(flags, ['env', 'app-id', 'page-id', 'file'], emit);
  if (missing) return missing;
  let localText;
  try {
    localText = readPlainText(path.resolve(flags.file));
  } catch (e) {
    return emit(false, { error: e.message });
  }
  const makeBackend = deps.makeGenpageSdk || makeGenpageSdk;
  let deployedText = null;
  let downloadError = null;
  let genpage;
  let leftOnDisk = null;
  try {
    genpage = makeBackend(flags.env);
    deployedText = (await genpage.read(flags['page-id'])).source;
  } catch (e) {
    downloadError = (e && e.message) || String(e);
  } finally {
    // Before any emit. emitResult calls process.exit, so a cleanup placed after it never runs
    // and the SDK's throwaway workspace — which holds the page source — stays on disk. Awaited: the folder is removed once the storage calls the backend had under way have settled.
    // A folder it could not remove (`{ left }`) is a warning in the result: a check that read a page and left its source in the temp directory says so.
    try { if (genpage && typeof genpage.dispose === 'function') leftOnDisk = leftOnDiskWarning(await genpage.dispose()); } catch { /* leave the temp dir */ }
  }

  const comparison = compareWithMarker(readMarker(flags.file), {
    pageId: flags['page-id'],
    appId: flags['app-id'],
    deployedText,
    localText,
  });
  const localSha256 = pageHash(localText);
  const deployedSha256 = deployedText == null ? null : pageHash(deployedText);
  const lines = deployedText == null ? null : lineDelta(localText, deployedText);
  const contentSame = deployedSha256 != null && deployedSha256 === localSha256;
  let deployedCopy;
  let copyError;
  if (deployedText != null && !contentSame) {
    try {
      // Raw text, not the normalized form: the copy is what the page holds, for the user to diff.
      deployedCopy = writeFileSafe(deployedCopyPath(flags.file), deployedText, { encoding: 'utf8' });
    } catch (e) {
      copyError = e.message;
    }
  }
  const payload = {
    ...comparison,
    deployedSha256,
    localSha256,
    contentSame,
    ...(lines ? { lines } : {}),
    ...(deployedCopy ? { deployedCopy } : {}),
    ...(copyError ? { copyError } : {}),
    ...(leftOnDisk ? { warnings: [leftOnDisk] } : {}),
  };
  if (downloadError) {
    return emit(false, {
      ok: false,
      code: 'deployed-unreadable',
      error: `cannot read the deployed page ${flags['page-id']} (${downloadError})`,
      ...payload,
    });
  }
  return emit(true, { ok: true, ...payload });
}

async function main(argv = process.argv.slice(2), deps = {}) {
  const emit = deps.emit || emitResult;
  const { positional, flags } = parseArgs(argv);
  const command = positional[0];
  if (command !== 'record' && command !== 'check') {
    return emit(false, { error: `expected 'record' or 'check'\n${USAGE}` });
  }
  if (positional.length > 1) {
    return emit(false, { error: `unexpected argument '${positional[1]}'\n${USAGE}` });
  }
  const known = command === 'record' ? RECORD_FLAGS : CHECK_FLAGS;
  const flagError = validateFlags(argv, { known, needValue: known });
  if (flagError) return emit(false, { error: `${flagError}\n${USAGE}` });
  if (command === 'record') return record(flags, emit);
  return check(flags, emit, deps);
}

if (require.main === module) {
  main().catch((e) => {
    makeWritesBlocking(process.stdout, process.stderr);
    process.stderr.write(`${e && e.message ? e.message : e}\n`);
    process.exit(1);
  });
}

module.exports = { main };