Skip to content

An open source design system that's fully customizable and agent ready

TypeScript
11.2 KB
Raw Blame
// Copyright (c) Meta Platforms, Inc. and affiliates.

import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {execFileSync} from 'node:child_process';
import {afterEach, describe, expect, it} from 'vitest';
import {createRepository} from './git-fixture.mjs';
import {readDiff} from './review-diff.mjs';
import {collectConcernMatches} from '../check-knowledge.mjs';
import {loadKnowledgeIndex} from '../specs-for-file.mjs';
import {routeReviewBaselines} from '../review-global-baselines.mjs';

const HERE = import.meta.dirname;
const ROOT = path.resolve(HERE, '../..');
const fixture = name =>
  fs.readFileSync(path.join(HERE, '__fixtures__/review-diff', name), 'utf8');

/** The repository's own records, as `pnpm specs:for` reads them. */
const records = loadKnowledgeIndex(ROOT).records.map(record => ({
  path: record.path,
  content: record.content,
}));
const routed = name =>
  collectConcernMatches(records, readDiff(fixture(name)).addedLines, null).map(
    match => `${match.recordId}/${match.claimId}`,
  );

describe('readDiff', () => {
  it('reads a hunk line that starts with --- or +++ as content, and counts changed lines', () => {
    const diff = [
      'diff --git a/docs/a.md b/docs/a.md',
      '--- a/docs/a.md',
      '+++ b/docs/a.md',
      '@@ -1,2 +1,2 @@',
      '---- a rule',
      '+++ a heading',
      ' context',
    ].join('\n');
    const {addedByFile, changedCountByFile} = readDiff(diff);
    expect(addedByFile).toEqual({'docs/a.md': ['++ a heading']});
    expect(changedCountByFile).toEqual({'docs/a.md': 2});
  });

  it('keeps every added line of each path in addedByFile', () => {
    const diff = [
      'diff --git a/docs/a.md b/docs/a.md',
      '--- a/docs/a.md',
      '+++ b/docs/a.md',
      '@@ -1,1 +1,2 @@',
      ' context',
      '+added',
      '-removed',
    ].join('\n');
    const {addedLines, addedByFile} = readDiff(diff);
    expect(addedLines).toEqual([]);
    expect(addedByFile).toEqual({'docs/a.md': ['added']});
  });

  it('keeps every added line of any file with its new line number', () => {
    const diff = [
      'diff --git a/docs/a.md b/docs/a.md',
      '--- a/docs/a.md',
      '+++ b/docs/a.md',
      '@@ -3,0 +4,2 @@',
      '+one',
      '+++ two',
      '@@ -9 +11 @@',
      '-old',
      '+new',
    ].join('\n');
    expect(readDiff(diff).everyAddedLine).toEqual([
      {file: 'docs/a.md', line: 4, text: 'one'},
      {file: 'docs/a.md', line: 5, text: '++ two'},
      {file: 'docs/a.md', line: 11, text: 'new'},
    ]);
  });

  it('reads a path with a space, or a quoted non-ASCII path, from the +++ header', () => {
    const diff = [
      'diff --git a/My notes.md b/My notes.md',
      'new file mode 100644',
      '--- /dev/null',
      '+++ b/My notes.md\t',
      '@@ -0,0 +1 @@',
      '+first',
      'diff --git "a/caf\\303\\251.md" "b/caf\\303\\251.md"',
      '--- "a/caf\\303\\251.md"',
      '+++ "b/caf\\303\\251.md"',
      '@@ -1 +1 @@',
      '-old',
      '+second',
    ].join('\n');
    const {files, everyAddedLine, unreadable} = readDiff(diff);
    expect(files).toEqual(['My notes.md', 'café.md']);
    expect(everyAddedLine).toEqual([
      {file: 'My notes.md', line: 1, text: 'first'},
      {file: 'café.md', line: 1, text: 'second'},
    ]);
    expect(unreadable).toBe(false);
  });

  it('reads a deleted file by its old path, and flags a hunk with no readable path', () => {
    expect(
      readDiff(
        [
          'diff --git a/gone file.md b/gone file.md',
          '--- a/gone file.md',
          '+++ /dev/null',
          '@@ -1 +0,0 @@',
          '-removed',
        ].join('\n'),
      ).files,
    ).toEqual(['gone file.md']);
    const odd = readDiff(
      ['diff --git a/x y b/x y', '@@ -0,0 +1 @@', '+lost'].join('\n'),
    );
    expect(odd.unreadable).toBe(true);
    expect(odd.everyAddedLine).toEqual([]);
  });

  it('reads added shipped-source lines with their new line numbers', () => {
    const {files, addedLines} = readDiff(fixture('pr-8381.diff'));
    expect(files).toEqual([
      'packages/core/src/Dialog/Dialog.tsx',
      'packages/core/src/utils/interactionModality.ts',
    ]);
    expect(addedLines).toContainEqual({
      file: 'packages/core/src/Dialog/Dialog.tsx',
      line: 548,
      text: '  useEffect(() => {',
    });
  });

  it('reads no lines from fixture files or directories', () => {
    for (const file of [
      'internal/a11y-spec/src/patterns/accordion.fixtures.ts',
      'packages/core/src/A/fixtures/data.ts',
    ]) {
      const diff = [
        `diff --git a/${file} b/${file}`,
        `--- a/${file}`,
        `+++ b/${file}`,
        '@@ -1,0 +1,1 @@',
        "+el.addEventListener('keydown', onKey);",
      ].join('\n');
      expect(readDiff(diff).addedLines).toEqual([]);
    }
  });

  it('reads no lines from tests, stories or fixtures', () => {
    const {files, addedLines} = readDiff(fixture('pr-8381-dialog-test.diff'));
    expect(files).toEqual(['packages/core/src/Dialog/Dialog.test.tsx']);
    expect(addedLines).toEqual([]);
  });
});

describe('concern routing on real diffs', () => {
  it("routes #8381's Dialog effect and modality listeners to their owners", () => {
    expect(routed('pr-8381.diff')).toEqual(
      expect.arrayContaining([
        'architecture:interaction-modality/INV1',
        'architecture:interaction-modality/INV2',
        'architecture:interaction-modality/INV3',
        'architecture:react-component-runtime/INV2',
        'architecture:react-component-runtime/INV3',
        'architecture:react-component-runtime/INV5',
        'architecture:react-component-runtime/INV6',
        'architecture:react-component-runtime/INV16',
      ]),
    );
  });

  it('routes a call to the document-scoped modality hook', () => {
    const file = 'packages/core/src/Layer/useTouchTrigger.ts';
    const diff = [
      `diff --git a/${file} b/${file}`,
      `--- a/${file}`,
      `+++ b/${file}`,
      '@@ -1,0 +1,1 @@',
      '+  useInteractionModalityTrackingFor(ownerDocument);',
    ].join('\n');
    const claims = collectConcernMatches(
      records,
      readDiff(diff).addedLines,
      null,
    ).map(match => `${match.recordId}/${match.claimId}`);
    expect(claims).toEqual(
      expect.arrayContaining([
        'architecture:interaction-modality/INV1',
        'architecture:react-component-runtime/INV16',
      ]),
    );
  });

  it("routes #8236's hand-written slot check to INV16, naming isRenderable", () => {
    const matches = collectConcernMatches(
      records,
      readDiff(fixture('pr-8236-badge.diff')).addedLines,
      null,
    );
    expect(matches).toContainEqual(
      expect.objectContaining({
        recordId: 'architecture:react-component-runtime',
        concern: 'slot-presence',
        claimId: 'INV16',
        utilities: ['isRenderable'],
      }),
    );
    expect(
      matches.find(match => match.concern === 'slot-presence').matchReason,
    ).toContain('(shared: isRenderable)');
  });

  it("routes #8513's MonthScroller listeners to the runtime claims", () => {
    expect(routed('pr-8513-month-scroller.diff')).toEqual(
      expect.arrayContaining([
        'architecture:react-component-runtime/INV3',
        'architecture:react-component-runtime/INV5',
      ]),
    );
  });

  it('routes nothing for a CSS-only change', () => {
    expect(routed('css-only.diff')).toEqual([]);
  });

  it('routes nothing for listeners a test adds', () => {
    expect(routed('pr-8381-dialog-test.diff')).toEqual([]);
  });
});

describe('review-global-baselines.mjs', () => {
  const roots = [];
  afterEach(() => {
    for (const root of roots.splice(0)) {
      fs.rmSync(root, {recursive: true, force: true});
    }
  });

  function git(root, ...args) {
    return execFileSync('git', ['-C', root, ...args], {
      encoding: 'utf8',
      env: {
        ...process.env,
        GIT_AUTHOR_NAME: 'Test',
        GIT_AUTHOR_EMAIL: '[email protected]',
        GIT_COMMITTER_NAME: 'Test',
        GIT_COMMITTER_EMAIL: '[email protected]',
      },
    }).trim();
  }

  function write(root, relative, content) {
    const file = path.join(root, relative);
    fs.mkdirSync(path.dirname(file), {recursive: true});
    fs.writeFileSync(file, content);
  }

  /** A base whose runtime record owns an effects concern; a head changing `source`. */
  function repository(source) {
    const root = fs.mkdtempSync(path.join(os.tmpdir(), 'review-baselines-'));
    roots.push(root);
    const record = [
      '---',
      'authority: current',
      'kind: architecture',
      'id: architecture:react-component-runtime',
      '---',
      '',
      '# React component runtime',
      '',
      '<!-- review-applicability:v1 -->',
      '',
      '```json',
      JSON.stringify({
        scope: 'global',
        triggers: {styling: ['INV2']},
        concerns: {
          effects: {patterns: ['\\buseEffect\\b'], claims: ['INV1']},
        },
      }),
      '```',
      '',
      '## Requirements',
      '',
      '- **INV1 — Effects clean up.** Detail.',
      '- **INV2 — Styles stay static.** Detail.',
      '',
    ].join('\n');
    const before = 'export function A() {}\n';
    write(root, 'docs/architecture/react-component-runtime.md', record);
    write(root, 'packages/core/src/A/A.tsx', source);
    const {base, head} = createRepository(
      root,
      [
        {
          ref: 'refs/heads/main',
          name: 'base',
          message: 'base',
          files: {
            'docs/architecture/react-component-runtime.md': record,
            'packages/core/src/A/A.tsx': before,
          },
        },
        {
          ref: 'refs/heads/main',
          name: 'head',
          message: 'head',
          files: {'packages/core/src/A/A.tsx': source},
        },
      ],
      {refs: {'refs/remotes/origin/main': 'base'}},
    );
    return {root, base, head};
  }

  function route({root, base, head}) {
    return JSON.parse(
      execFileSync(
        'node',
        [
          path.join(ROOT, 'scripts/review-global-baselines.mjs'),
          '--root',
          root,
          '--authority-commit',
          base,
          '--review-head',
          head,
          '--triggers',
          'styling',
        ],
        {encoding: 'utf8'},
      ),
    );
  }

  // The router runs in this process; the case below runs the command once.
  it("routes a concern the head's added lines match, beside the requested triggers", () => {
    const {root, base, head} = repository(
      'export function A() {\n  useEffect(() => () => {}, []);\n}\n',
    );
    const result = routeReviewBaselines({
      root,
      authorityCommit: base,
      reviewHead: head,
      requestedTriggers: ['styling'],
    });
    expect(result.matches.map(match => match.claimId)).toEqual(['INV2']);
    expect(result.concernMatches).toEqual([
      expect.objectContaining({
        recordId: 'architecture:react-component-runtime',
        concern: 'effects',
        claimId: 'INV1',
        evidence: [
          expect.objectContaining({
            file: 'packages/core/src/A/A.tsx',
            line: 2,
            matched: 'useEffect',
          }),
        ],
      }),
    ]);
  });

  it('routes no concern when no added line matches', () => {
    const result = route(
      repository('export function A() {\n  return null;\n}\n'),
    );
    expect(result.concernMatches).toEqual([]);
  });
});