Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

16.0 KB
Raw Blame
// Source patterns the guidance forbids, held by a gate instead of prose.
//
//   node scripts/check-source-bans.mjs [--self-test]
//
// Each ban below is written in AGENTS.md or a `.claude/rules/` file and is
// mechanical enough that a scan decides it:
//
// - No Chinese comments in any source (AGENTS.md Code Conventions): CJK text
//   inside a comment. Strings are data (menu titles, dialog text, fixtures)
//   and never count. The comments listed in CJK_COMMENTS quote the literal
//   text a test or parser matches.
// - A helper in `bin/utils/` or `bin/helpers/` needs a matching test in
//   `tests/unit/`: `<basename>.test.ts`, `<basename>-*.test.ts` or
//   `<basename>.*.test.ts` (AGENTS.md Review Hard Stops). The helpers listed
//   in UNTESTED_HELPERS predate the gate.
// - In machine mode stdout carries one JSON result, so code in `bin/` never
//   names `process.stdout` (reading `isTTY`, `columns` or `rows` aside),
//   destructures `stdout` from `process`, or names a console method that
//   writes to stdout (`log`, `info`, `debug`, `dir`, `dirxml`, `table`,
//   `count`, `group`, `groupCollapsed`, `timeLog`, `timeEnd`), whether as
//   `console.x`, `console["x"]` or `const { x } = console`
//   (`.claude/rules/cli.md`). `warn`, `error`, `trace` and `assert` write to
//   stderr. STDOUT_WRITERS lists the one writer of the JSON result.
// - No WeChat (`.claude/rules/docs.md`): `wx.qq.com` never appears in the app
//   list, the gallery, the READMEs, `.github/` or the source.
//
// The comment splitter is a line scanner, not a parser. It knows `//` and
// `/* */` comments, `#` comments in shell, Python, YAML and TOML, quoted
// strings, JS template literals, JS regex literals (by the token before the
// slash), Rust multi-line and raw strings (`r"..."`, `r#"..."#`), Rust char
// literals versus lifetimes, and an apostrophe inside a word in shell, YAML and
// TOML (`don't`). Known limits: Python and Swift triple-quoted strings are
// read as an empty string followed by code, a regex literal after `)` (as in
// `if (x) /re/.test(s)`) is read as division, and a shell heredoc body is
// read as code. A miss there can only hide a comment, never invent one in a
// string, except a `#` inside a Python or Swift triple-quoted string.
//
// A list only shrinks: an entry that no longer matches fails, so drop it.
// tests/unit/check-source-bans.test.ts runs the check and the self-test, so
// `npx vitest run` (in release:check and the CI fast suite) fails on a ban.

import { spawnSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

export const ROOT = path.resolve(
  path.dirname(fileURLToPath(import.meta.url)),
  "..",
);

// file -> exact trimmed comment lines allowed to carry CJK text.
export const CJK_COMMENTS = {
  "src-tauri/src/app/invoke.rs": [
    "/// `(3) Inbox`, `[12] Slack`, `(5)消息`, `【8】通知`, or `(99+) Chat`.",
  ],
  "src-tauri/src/app/nav_buttons.rs": [
    "/// Back and Forward as the system's own web views name them: 返回 and 前进",
    "/// in Simplified Chinese, 上一頁 and 下一頁 in Traditional (WebCore's strings).",
  ],
  "tests/unit/macos-script-dialogs.test.ts": [
    '// AppKit binds Escape only to a button titled "Cancel"; 取消 is not.',
  ],
  "tests/unit/xiaohongshu-recipe.test.js": [
    '// User intentionally clicks the "点点 AI" button -> manual open stays open!',
  ],
};

export const UNTESTED_HELPERS = [
  "bin/helpers/cli-program.ts",
  "bin/helpers/tauriConfig.ts",
  "bin/utils/dir.ts",
  "bin/utils/info.ts",
  "bin/utils/mirror.ts",
  "bin/utils/output.ts",
  "bin/utils/platform.ts",
  "bin/utils/targets.ts",
];

// file -> exact trimmed code lines allowed to write to stdout.
export const STDOUT_WRITERS = {
  "bin/utils/output.ts": [
    "process.stdout.write(`${JSON.stringify(result)}\\n`);",
  ],
};

const CJK = new RegExp(
  "[\\u3000-\\u303f\\u3040-\\u30ff\\u3400-\\u4dbf\\u4e00-\\u9fff\\uac00-\\ud7af\\uff00-\\uffef]",
);
const STDOUT_METHODS =
  "log|info|debug|dir|dirxml|table|count|group|groupCollapsed|timeLog|timeEnd";
const STDOUT = new RegExp(
  [
    `\\bconsole\\s*(?:\\.\\s*|\\[\\s*["'\`])(?:${STDOUT_METHODS})\\b`,
    `\\{[^}]*\\b(?:${STDOUT_METHODS})\\b[^}]*\\}\\s*=\\s*console\\b`,
    "\\bprocess\\s*\\.\\s*stdout\\b(?!\\s*\\.\\s*(?:isTTY|columns|rows)\\b)",
    "\\{[^}]*\\bstdout\\b[^}]*\\}\\s*=\\s*process\\b",
  ].join("|"),
);
const WECHAT = /wx\.qq\.com/;

const SLASH_COMMENTS = /\.(?:rs|ts|tsx|js|mjs|cjs|swift|css)$/;
const HASH_COMMENTS = /\.(?:sh|py|yml|yaml|toml)$/;
const HELPER = /^bin\/(?:utils|helpers)\/([^/]+)\.ts$/;
const WECHAT_SCOPE =
  /^(?:default_app_list\.json|README[^/]*\.md|gallery\/|bin\/|src-tauri\/src\/|\.github\/)/;

const JS = /\.(?:ts|tsx|js|mjs|cjs)$/;
const REGEX_BEFORE =
  /(?:^|[(,=:[!&|?{};+\-*%<>~^]|\b(?:return|typeof|case|in|of|delete|void|throw|new|yield|await))\s*$/;

// Split a source file into comment text and code text, line by line, so a
// ban can look at one without the other. Strings stay in the code text; a
// comment marker inside a string is not a comment. The header lists what the
// scanner knows and where it stops.
export function splitComments(rel, text) {
  const slash = SLASH_COMMENTS.test(rel);
  const hash = HASH_COMMENTS.test(rel);
  const rust = rel.endsWith(".rs");
  const js = JS.test(rel);
  const python = rel.endsWith(".py");
  const out = [];
  let block = false;
  // An open string carried across lines: { close, raw, hashes }.
  let open = null;
  for (const line of text.split("\n")) {
    let comment = "";
    let code = "";
    let continued = false;
    for (let i = 0; i < line.length; i++) {
      const ch = line[i];
      const next = line[i + 1];
      if (block) {
        if (ch === "*" && next === "/") {
          comment += "*/";
          block = false;
          i++;
        } else comment += ch;
        continue;
      }
      if (open) {
        code += ch;
        if (open.raw) {
          if (ch === '"' && line.startsWith("#".repeat(open.hashes), i + 1)) {
            code += "#".repeat(open.hashes);
            i += open.hashes;
            open = null;
          }
        } else if (ch === "\\") {
          if (i + 1 >= line.length) continued = true;
          code += next ?? "";
          i++;
        } else if (ch === open.close) open = null;
        continue;
      }
      if (slash && ch === "/" && next === "/") {
        comment += line.slice(i);
        break;
      }
      if (slash && ch === "/" && next === "*") {
        block = true;
        comment += "/*";
        i++;
        continue;
      }
      if (hash && ch === "#") {
        comment += line.slice(i);
        break;
      }
      if (js && ch === "/" && REGEX_BEFORE.test(code)) {
        // A regex literal runs to the next unescaped slash outside a class.
        let j = i + 1;
        let inClass = false;
        for (; j < line.length; j++) {
          if (line[j] === "\\") j++;
          else if (line[j] === "[") inClass = true;
          else if (line[j] === "]") inClass = false;
          else if (line[j] === "/" && !inClass) break;
        }
        code += line.slice(i, j + 1);
        i = j;
        continue;
      }
      if (rust && (ch === "r" || ch === "b") && !/[\w]$/.test(code)) {
        const raw = /^b?r(#*)"/.exec(line.slice(i));
        if (raw) {
          code += raw[0];
          i += raw[0].length - 1;
          open = { raw: true, hashes: raw[1].length };
          continue;
        }
      }
      if (rust && ch === "'") {
        // A char literal ('x', '\n', a full-width bracket); anything else is a
        // lifetime.
        const literal = /^'(?:\\.|[^\\'])'/u.exec(line.slice(i));
        if (literal) {
          code += literal[0];
          i += literal[0].length - 1;
          continue;
        }
        code += ch;
        continue;
      }
      if (hash && !python && ch === "'" && /\w$/.test(code)) {
        // An apostrophe inside a word (don't), not a quote.
        code += ch;
        continue;
      }
      if (ch === '"' || ch === "'" || (ch === "`" && (js || slash))) {
        open = { close: ch, raw: false };
        code += ch;
        continue;
      }
      code += ch;
    }
    // Template literals, Rust strings and an escaped line end span lines.
    if (
      open &&
      !open.raw &&
      !continued &&
      open.close !== "`" &&
      !(rust && open.close === '"')
    ) {
      open = null;
    }
    out.push({ comment, code });
  }
  return out;
}

function listedLines(found, rel, allowed, seen, label) {
  for (const line of allowed[rel] ?? []) {
    if (!seen.has(line)) {
      found.push(`${rel}: listed in ${label} but no longer has: ${line}`);
    }
  }
}

export function problems(files) {
  const found = [];
  const helperTests = Object.keys(files).filter((rel) =>
    /^tests\/unit\/[^/]+\.test\.ts$/.test(rel),
  );
  const untested = new Set();
  for (const rel of Object.keys(files).sort()) {
    const text = files[rel];
    const commented =
      SLASH_COMMENTS.test(rel) || HASH_COMMENTS.test(rel)
        ? splitComments(rel, text)
        : null;

    if (commented) {
      const seen = new Set();
      const allowed = new Set(CJK_COMMENTS[rel] ?? []);
      commented.forEach(({ comment }, i) => {
        if (!CJK.test(comment)) return;
        const line = text.split("\n")[i].trim();
        if (allowed.has(line)) seen.add(line);
        else found.push(`${rel}:${i + 1}: Chinese text in a comment`);
      });
      listedLines(found, rel, CJK_COMMENTS, seen, "CJK_COMMENTS");
    }

    const helper = HELPER.exec(rel);
    if (helper && !/\.(?:test|spec|d)\.ts$/.test(rel)) {
      const name = helper[1];
      const matching = (test) =>
        test === `tests/unit/${name}.test.ts` ||
        test.startsWith(`tests/unit/${name}-`) ||
        test.startsWith(`tests/unit/${name}.`);
      if (!helperTests.some(matching)) {
        untested.add(rel);
        if (!UNTESTED_HELPERS.includes(rel)) {
          found.push(
            `${rel}: helper without a tests/unit/${name}.test.ts, ${name}-*.test.ts or ${name}.*.test.ts`,
          );
        }
      }
    }

    if (rel.startsWith("bin/") && rel.endsWith(".ts") && commented) {
      const seen = new Set();
      const allowed = new Set(STDOUT_WRITERS[rel] ?? []);
      commented.forEach(({ code }, i) => {
        if (!STDOUT.test(code)) return;
        const line = text.split("\n")[i].trim();
        if (allowed.has(line)) seen.add(line);
        else found.push(`${rel}:${i + 1}: writes to stdout in bin/`);
      });
      listedLines(found, rel, STDOUT_WRITERS, seen, "STDOUT_WRITERS");
    }

    if (WECHAT_SCOPE.test(rel)) {
      const body = commented
        ? commented.map(({ code }) => code).join("\n")
        : text;
      if (WECHAT.test(body))
        found.push(`${rel}: packages wx.qq.com (No WeChat)`);
    }
  }
  for (const rel of UNTESTED_HELPERS) {
    if (!untested.has(rel)) {
      found.push(
        `${rel}: listed in UNTESTED_HELPERS but now tested or gone; drop the entry`,
      );
    }
  }
  for (const rel of [
    ...Object.keys(CJK_COMMENTS),
    ...Object.keys(STDOUT_WRITERS),
  ]) {
    if (!(rel in files))
      found.push(`${rel}: listed but no longer exists; drop the entry`);
  }
  return found;
}

const SCANNED = new RegExp(
  `${SLASH_COMMENTS.source}|${HASH_COMMENTS.source}|^default_app_list\\.json$|^README[^/]*\\.md$|^gallery/`,
);

export function load() {
  const out = spawnSync(
    "git",
    ["-C", ROOT, "ls-files", "--cached", "--others", "--exclude-standard"],
    { encoding: "utf8" },
  );
  if (out.status !== 0) throw new Error("git ls-files failed");
  const files = {};
  for (const rel of out.stdout.split("\n").filter(Boolean)) {
    if (rel.startsWith("dist/") || rel.startsWith("filters/")) continue;
    if (!SCANNED.test(rel)) continue;
    const full = path.join(ROOT, rel);
    if (!fs.existsSync(full) || fs.lstatSync(full).isSymbolicLink()) continue;
    files[rel] = fs.readFileSync(full, "utf8");
  }
  return files;
}

// One bad sample per ban, each of which must be caught, plus the forms each
// ban must leave alone.
export const SELF_TEST = {
  caught: {
    "Chinese comment": [
      "src-tauri/src/app/sample.rs",
      "// 中文注释\nfn a() {}\n",
    ],
    "Chinese block comment": ["bin/sample.ts", "/* 中文\n */\nexport {};\n"],
    "untested helper": ["bin/utils/sample-helper.ts", "export const a = 1;\n"],
    "stdout write": ["bin/builders/Sample.ts", 'console.log("built");\n'],
    "stdout write via process": [
      "bin/builders/Sample.ts",
      "process.stdout.write('x');\n",
    ],
    "WeChat recipe": [
      "default_app_list.json",
      '[{"name": "wechat", "url": "https://wx.qq.com/"}]\n',
    ],
    "WeChat in a workflow": [
      ".github/workflows/sample.yml",
      "env:\n  URL: https://wx.qq.com/\n",
    ],
    "Chinese # comment in Python": ["scripts/sample.py", "x = 1  # 中文\n"],
    "Chinese # comment in YAML": [
      ".github/workflows/sample.yml",
      "on: push # 中文\n",
    ],
    "Chinese comment after an apostrophe": [
      ".github/workflows/sample.yml",
      "run: echo don't # 中文\n",
    ],
    "Chinese comment after a regex holding a backtick": [
      "bin/sample.ts",
      "const r = /`/; // 中文\n",
    ],
    "Chinese comment after a raw string ending in a backslash": [
      "src-tauri/src/app/sample.rs",
      'let p = r"C:\\"; // 中文\n',
    ],
    "helper matched only by a longer name": [
      "bin/helpers/icon-compose.ts",
      "export const a = 1;\n",
    ],
    "stdout via a bracketed console method": [
      "bin/builders/Sample.ts",
      'console["log"]("x");\n',
    ],
    "stdout via a console alias": [
      "bin/builders/Sample.ts",
      "const { log } = console;\n",
    ],
    "stdout via console.table": [
      "bin/builders/Sample.ts",
      "console.table(x);\n",
    ],
    "stdout as a pipe target": [
      "bin/builders/Sample.ts",
      "child.stdout.pipe(process.stdout);\n",
    ],
  },
  ignored: {
    "Chinese string": [
      "src-tauri/src/app/sample.rs",
      'let s = "中文"; // ok\n',
    ],
    "Chinese char literal": [
      "src-tauri/src/app/sample.rs",
      "let c = '('; // x\n",
    ],
    "comment marker in a string": [
      "src-tauri/src/app/sample.rs",
      'let u = "https://例子.测试/app";\n',
    ],
    "stdout in a comment": ["bin/builders/Sample.ts", "// console.log(x)\n"],
    "WeChat in a comment": [
      "src-tauri/src/app/sample.rs",
      "// never wx.qq.com\n",
    ],
    "comment marker inside a Rust multi-line string": [
      "src-tauri/src/app/sample.rs",
      'let s = "line one\n    // 中文 still the string";\n',
    ],
    "Chinese in a YAML string": [
      ".github/workflows/sample.yml",
      'default: "推特" # ok\n',
    ],
    "a stdout TTY check": [
      "bin/builders/Sample.ts",
      "const tty = process.stdout.isTTY;\n",
    ],
    "console.warn": ["bin/builders/Sample.ts", 'console.warn("x");\n'],
    "a helper with a separated test name": [
      "bin/utils/merge.ts",
      "export const a = 1;\n",
    ],
  },
};

export function selfTest(base = load()) {
  const failures = [];
  if (problems(base).length) failures.push("the current tree is not clean");
  for (const [name, [rel, text]] of Object.entries(SELF_TEST.caught)) {
    if (problems({ ...base, [rel]: text }).length === 0) {
      failures.push(`${name} was not caught`);
    }
  }
  for (const [name, [rel, text]] of Object.entries(SELF_TEST.ignored)) {
    if (problems({ ...base, [rel]: text }).length !== 0) {
      failures.push(`${name} was flagged`);
    }
  }
  return failures;
}

if (
  process.argv[1] &&
  path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
) {
  if (process.argv.includes("--self-test")) {
    const failures = selfTest();
    for (const line of failures) console.log(`self-test: ${line}`);
    console.log(
      failures.length
        ? "source-bans-self-test-failed"
        : "source-bans-self-test-ok",
    );
    process.exit(failures.length ? 1 : 0);
  }
  const found = problems(load());
  for (const line of found) console.log(`source ban: ${line}`);
  if (!found.length) console.log("source-bans-ok");
  process.exit(found.length ? 1 : 0);
}