An open source design system that's fully customizable and agent ready
TypeScript
chore(changesets): categorized, contributor-attributed, patch-only changesets (#2981)
Cindy Zhang5a258a1289b4
diff --git a/.changeset/changelog.cjs b/.changeset/changelog.cjsnew file mode 100644index 0000000000..9107f5b150--- /dev/null+++ b/.changeset/changelog.cjs@@ -0,0 +1,48 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Custom changesets changelog module for XDS.+ *+ * Implements the { getReleaseLine, getDependencyReleaseLine } contract that+ * @changesets/apply-release-plan expects. Wired via `.changeset/config.json`:+ *+ * "changelog": "./changelog.cjs"+ *+ * Responsibilities:+ * - Render each changeset as a categorized, contributor-attributed bullet+ * (parsing the XDS body convention via scripts/changeset-entry-format).+ * - Suppress the noisy "Updated dependencies" lines that the default+ * generator emits for every internal bump. Under our `fixed` lockstep+ * every package bumps together on every release, so those lines are pure+ * noise in per-package changelogs. The post-version formatter+ * (scripts/format-changelogs.mjs) produces the polished output.+ */++const {+ parseEntry,+ renderReleaseLine,+} = require('../scripts/changeset-entry-format.cjs');++/**+ * @param {{summary: string}} changeset+ */+async function getReleaseLine(changeset /*, type, changelogOpts */) {+ const parsed = parseEntry(changeset.summary);+ return renderReleaseLine(parsed);+}++/**+ * Internal dependency bumps. Returns empty so lockstep dependency churn does+ * not pollute changelogs. (All publishable packages are in `fixed`, so they+ * always co-bump; listing "Updated dependencies" on each is meaningless.)+ */+async function getDependencyReleaseLine() {+ return '';+}++module.exports = {+ getReleaseLine,+ getDependencyReleaseLine,+ // changesets unwraps `.default` under ESM-interop; expose it both ways.+ default: {getReleaseLine, getDependencyReleaseLine},+};diff --git a/.changeset/config.json b/.changeset/config.jsonindex 20b8491186..d22da8e1f4 100644--- a/.changeset/config.json+++ b/.changeset/config.json@@ -1,14 +1,26 @@{"$schema": "https://unpkg.com/@changesets/[email protected]/schema.json",- "changelog": "@changesets/cli/changelog",+ "changelog": "./changelog.cjs","commit": false,- "fixed": [],+ "fixed": [+ [+ "@xds/build",+ "@xds/cli",+ "@xds/core",+ "@xds/theme-butter",+ "@xds/theme-chocolate",+ "@xds/theme-daily",+ "@xds/theme-default",+ "@xds/theme-gothic",+ "@xds/theme-matcha",+ "@xds/theme-neutral",+ "@xds/theme-stone",+ "@xds/theme-y2k"+ ]+ ],"linked": [],"access": "public","baseBranch": "main","updateInternalDependencies": "patch",- "ignore": [- "@xds/storybook",- "@xds/sandbox"- ]+ "ignore": ["@xds/storybook", "@xds/sandbox"]}diff --git a/.changeset/remove-meta-codemod-from-oss.md b/.changeset/remove-meta-codemod-from-oss.mdindex 3c0f34d32e..c41e3e142f 100644--- a/.changeset/remove-meta-codemod-from-oss.md+++ b/.changeset/remove-meta-codemod-from-oss.md@@ -2,4 +2,7 @@'@xds/cli': patch----Remove the internal `drop-xds-meta-prefix` codemod from the OSS repo. This codemod targeted the Meta-internal `@xds/core` package and has been moved to that package's own tooling, where it belongs. It was registered as an optional, version-independent transform and is not part of any standard upgrade path, so removing it does not affect the public `0.0.13 → 0.0.15` migration.+[chore] Remove the internal `drop-xds-meta-prefix` codemod from the OSS repo (#2970)+@ejhammond++This codemod has been moved to its own package's tooling, where it belongs. It was registered as an optional, version-independent transform and is not part of any standard upgrade path, so removing it does not affect the public `0.0.13 → 0.0.15` migration.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 5318ea7775..ae05b6a051 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -3,6 +3,7 @@For the full contribution process — what we accept, how to propose new components, and how API decisions are made — read the **[Contributing wiki](https://github.com/facebookexperimental/xds/wiki/Contributing)**.Key pages:+- **[API Conventions](https://github.com/facebookexperimental/xds/wiki/API-Conventions)** — naming, prop patterns, composition rules (read before submitting an RFC)- **[Specification Protocol](https://github.com/facebookexperimental/xds/wiki/Component-Specification-Protocol)** — the 9-phase process for new components- **[API Arbitration](https://github.com/facebookexperimental/xds/wiki/API-Arbitration)** — how we resolve API design questions@@ -288,36 +289,64 @@ src/Button/## Versioning & Releases-We use [Changesets](https://github.com/changesets/changesets) for versioning.+We use [Changesets](https://github.com/changesets/changesets) for versioning, with a thin XDS layer on top so changelogs stay categorized, contributor-attributed, and aligned with our pre-1.0 conventions.### Adding a ChangesetWhen you make a change that should be released:```bash-pnpm changeset+pnpm changeset:new```-Follow the prompts to:+This wrapper:-1. Select changed packages-2. Choose bump type (patch/minor/major)-3. Write a summary+1. **Detects which packages you changed** from your git diff and pre-selects them — no hand-enumerating the frontmatter.+2. **Asks for a category** (`breaking`, `component`, `feat`, `fix`, `perf`, `docs`, `chore`) — this drives changelog grouping, _not_ the semver bump.+3. **Captures the contributor(s)** — defaults to your `gh`/git identity, so credit is recorded at authoring time (not reconstructed from the release bot's commit).+4. **Forces a `patch` bump** while we're pre-1.0 (see below).-This creates a file in `.changeset/` — commit it with your PR.+It writes a normal `.changeset/<id>.md` — commit it with your PR. The body looks like:++```md+---+'@xds/core': patch+---++[fix] Spinner inherits the variant foreground on themed buttons (#2717)+@yourhandle+```++You can also pass everything as flags for non-interactive use:++```bash+pnpm changeset:new --category fix --summary "…" --pr 2717 --contributor yourhandle+```++> The bare `pnpm changeset` CLI still works, but you must follow the body+> convention by hand (`[category]` first line + `@handle` line). CI+> (`pnpm check:changesets`) rejects changesets missing a category or+> contributor, or declaring a `minor`/`major` bump while pre-1.0.### Version Bumps-- **patch**: Bug fixes, no API changes-- **minor**: New features, backward compatible-- **major**: Breaking changes+- **Pre-1.0 (current): always `patch`.** The Changesets CLI maps `minor` → 0.0.x → 0.1.0 and `major` → 1.0.0. While we're on 0.0.x we ship every change — features, fixes, and breaking changes alike — as a `patch`. Signal a breaking change with the `[breaking]` **category**, not a `major` bump. `pnpm changeset:new` enforces this; `pnpm check:changesets` is the CI backstop.+- All publishable packages are a `fixed` group, so a single change co-bumps them to the same version. Only genuinely-affected packages get a changelog entry — the rest get a clean version-only bump.++### How a release is cut++```bash+pnpm version-packages # changeset version + scripts/format-changelogs.mjs+```++`format-changelogs.mjs` rewrites each just-bumped package CHANGELOG into the doc-site format (h1 version, `#### <Category>` sections in canonical order, and a `#### Contributors` section aggregated from the changeset `@handle`s). It's idempotent and has a `--check` mode for CI drift detection.## Pull Request Guidelines1. Create a feature branch from `main`2. Make your changes with tests3. Run `pnpm test` and `pnpm lint`-4. Add a changeset if needed: `pnpm changeset`+4. Add a changeset if needed: `pnpm changeset:new`5. Open a PR with a clear description## Code Style@@ -351,7 +380,6 @@ You can also download the binary directly fromopen the project in your IDE — `node_modules` is on the local filesystemand doesn't need network to use.-### Storybook Issues**"Failed to fetch dynamically imported module"**diff --git a/eslint.config.js b/eslint.config.jsindex 000b6207d3..93d998f6c5 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -36,6 +36,10 @@ export default tseslint.config("**/internal/eslint-plugin-xds/**",".github/scripts/**","scripts/**",+ // Changesets tooling (custom changelog module + config) is CommonJS+ // build/release glue, not shipped source — keep it out of the TS/ESM+ // lint pass (consistent with scripts/** above).+ ".changeset/**",// .mjs is ignored everywhere EXCEPT the CLI package, whose runtime is// entirely .mjs. The negations below opt packages/cli back into linting// (see the dedicated CLI block lower down). Scoped to packages/cli ondiff --git a/package.json b/package.jsonindex 5abc40a6a3..76813a21a7 100644--- a/package.json+++ b/package.json@@ -10,7 +10,8 @@"test:watch": "vitest","test:coverage": "vitest --coverage","check:package-boundaries": "node scripts/check-package-boundaries.js",- "check:repo": "pnpm check:sync && pnpm check:package-boundaries && pnpm compat:aliases:check",+ "check:repo": "pnpm check:sync && pnpm check:package-boundaries && pnpm compat:aliases:check && pnpm check:changesets",+ "check:changesets": "node scripts/check-changesets.mjs","check:sync": "node scripts/check-sync.js","lint": "pnpm check:repo && eslint . --cache","lint:strict": "pnpm check:repo && XDS_STRICT_LINT=1 eslint . --cache",@@ -22,7 +23,9 @@"xds": "pnpm -F @xds/cli xds","package:source": "node scripts/package-source.js","changeset": "changeset",- "version-packages": "changeset version",+ "changeset:new": "node scripts/changeset-new.mjs",+ "version-packages": "changeset version && node scripts/format-changelogs.mjs",+ "format-changelogs": "node scripts/format-changelogs.mjs","verify-exports": "node scripts/verify-exports.mjs","release": "pnpm build && changeset publish","prepare": "husky install",diff --git a/scripts/changeset-entry-format.cjs b/scripts/changeset-entry-format.cjsnew file mode 100644index 0000000000..53d5c72f8b--- /dev/null+++ b/scripts/changeset-entry-format.cjs@@ -0,0 +1,162 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * Shared parser/formatter for XDS changeset bodies.+ *+ * XDS encodes two extra signals in the changeset *body* (not frontmatter,+ * because @changesets/parse treats every frontmatter key as a package→bump+ * mapping and rejects anything else):+ *+ * [category] one-line user-facing summary (#1234)+ * @contributor1 @contributor2+ * ...optional extra body (codemod notes, etc.)+ *+ * - category -> editorial grouping for the changelog, decoupled from semver.+ * - @handle -> contributor(s), captured at authoring time (correct human,+ * not the release bot).+ *+ * This module is the single source of truth for that convention. It is used+ * by:+ * - .changeset/changelog.cjs (release-line rendering)+ * - scripts/changeset-new.mjs (the authoring wrapper)+ * - scripts/check-changesets.mjs (CI lint)+ * - scripts/format-changelogs.mjs (post-version formatter)+ *+ * NOTE: lives in scripts/ (not .changeset/) on purpose — @changesets/read+ * treats every *subdirectory* of .changeset/ as a legacy v1 changeset, so a+ * .changeset/lib/ dir breaks `changeset version`.+ */++// Canonical category set. Order here is the order sections render in the+// changelog. `label` is the changelog section heading.+const CATEGORIES = [+ {key: 'breaking', label: 'Breaking Changes'},+ {key: 'component', label: 'New Components'},+ {key: 'feat', label: 'New Features'},+ {key: 'fix', label: 'Fixes'},+ {key: 'perf', label: 'Performance'},+ {key: 'docs', label: 'Documentation'},+ {key: 'chore', label: 'Other Changes'},+];++const CATEGORY_KEYS = CATEGORIES.map(c => c.key);++// Aliases people are likely to type.+const CATEGORY_ALIASES = {+ bug: 'fix',+ bugfix: 'fix',+ fixes: 'fix',+ feature: 'feat',+ features: 'feat',+ break: 'breaking',+ major: 'breaking',+ components: 'component',+ new: 'component',+ performance: 'perf',+ doc: 'docs',+ refactor: 'chore',+ internal: 'chore',+};++function normalizeCategory(raw) {+ if (!raw) return null;+ const k = String(raw).trim().toLowerCase();+ if (CATEGORY_KEYS.includes(k)) return k;+ if (CATEGORY_ALIASES[k]) return CATEGORY_ALIASES[k];+ return null;+}++function labelFor(key) {+ const c = CATEGORIES.find(x => x.key === key);+ return c ? c.label : 'Other Changes';+}++const CONTRIB_LINE = /^@[\w-]+(\s+@[\w-]+)*\s*$/;+const HANDLE = /@([\w-]+)/g;++/**+ * Parse a changeset summary body into structured parts.+ * Tolerant: missing category/contributors are reported, not thrown — the+ * checker decides severity.+ */+function parseEntry(summary) {+ const lines = String(summary || '')+ .replace(/\r\n/g, '\n')+ .split('\n');++ let category = null;+ let headline = '';+ const contributors = [];+ const extra = [];++ let consumedHeadline = false;++ for (const rawLine of lines) {+ const line = rawLine.trimEnd();+ if (!consumedHeadline) {+ if (line.trim() === '') continue; // skip leading blanks+ // First non-empty line is the headline; may carry a [category] prefix.+ const m = line.match(/^\s*\[([^\]]+)\]\s*(.*)$/);+ if (m) {+ category = normalizeCategory(m[1]);+ headline = m[2].trim();+ } else {+ headline = line.trim();+ }+ consumedHeadline = true;+ continue;+ }++ // After the headline: a line that is only @handles is a contributor line.+ if (CONTRIB_LINE.test(line.trim()) && line.trim().startsWith('@')) {+ let mm;+ const re = new RegExp(HANDLE.source, 'g');+ while ((mm = re.exec(line)) !== null) {+ if (!contributors.includes(mm[1])) contributors.push(mm[1]);+ }+ continue;+ }+ extra.push(rawLine);+ }++ // Trim leading/trailing blank lines from extra.+ while (extra.length && extra[0].trim() === '') extra.shift();+ while (extra.length && extra[extra.length - 1].trim() === '') extra.pop();++ return {+ category,+ headline,+ contributors,+ extra: extra.join('\n'),+ };+}++/**+ * Render a single changelog bullet for a parsed entry. Used by getReleaseLine.+ * Keeps the [category] tag inline so the post-version formatter can regroup,+ * and appends contributor attribution.+ */+function renderReleaseLine(parsed) {+ const cat = parsed.category || 'chore';+ let line = `- [${cat}] ${parsed.headline}`;+ if (parsed.contributors.length) {+ line += ` — thanks ${parsed.contributors.map(c => `@${c}`).join(', ')}`;+ }+ if (parsed.extra) {+ const indented = parsed.extra+ .split('\n')+ .map(l => (l.trim() ? ` ${l}` : ''))+ .join('\n');+ line += `\n${indented}`;+ }+ return line;+}++module.exports = {+ CATEGORIES,+ CATEGORY_KEYS,+ normalizeCategory,+ labelFor,+ parseEntry,+ renderReleaseLine,+};diff --git a/scripts/changeset-new.mjs b/scripts/changeset-new.mjsnew file mode 100755index 0000000000..10ca8acb2c--- /dev/null+++ b/scripts/changeset-new.mjs@@ -0,0 +1,292 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * XDS changeset authoring wrapper — `pnpm changeset:new`.+ *+ * Encapsulates the three things our release process needs but the bare+ * `changeset` CLI does not capture well (see [[Release Process]] wiki):+ *+ * 1. Repo-wide changes / per-package changelogs — auto-detects which+ * publishable packages your working tree touched and pre-selects them,+ * so you don't hand-enumerate the frontmatter. Only genuinely-affected+ * packages get the changelog entry; the `fixed` lockstep co-bumps the+ * rest so versions stay aligned without polluting their changelogs.+ * 2. semver vs v0 — forces `patch` while the repo is < 1.0. No way to+ * accidentally author a `minor` that jumps 0.0.x -> 0.1.0.+ * 3. Contributor encapsulation — captures the human contributor(s) at+ * authoring time (defaulting to your `gh` / git identity) and writes them+ * into the changeset body, where the custom changelog module reads them.+ *+ * Output is a normal `.changeset/<id>.md` — fully compatible with the stock+ * `changeset version`. The only convention is the body format, validated by+ * scripts/check-changesets.mjs.+ *+ * Flags (all optional; missing values are prompted):+ * --category <key> breaking|component|feat|fix|perf|docs|chore+ * --summary <text> one-line headline+ * --contributor <h> repeatable; defaults to detected identity+ * --pr <number> PR number (appended as (#n) if not already in summary)+ * --packages <a,b> override detected package list+ * --yes non-interactive; use flags/defaults, no prompts+ */++import fs from 'node:fs';+import path from 'node:path';+import readline from 'node:readline';+import {execSync} from 'node:child_process';+import {fileURLToPath} from 'node:url';+import {createRequire} from 'node:module';++const require = createRequire(import.meta.url);+const {+ CATEGORIES,+ CATEGORY_KEYS,+ normalizeCategory,+} = require('./changeset-entry-format.cjs');++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');++// ---- args ----------------------------------------------------------------+function parseArgs(argv) {+ const out = {contributor: []};+ for (let i = 0; i < argv.length; i++) {+ const a = argv[i];+ if (a === '--yes' || a === '-y') out.yes = true;+ else if (a === '--category') out.category = argv[++i];+ else if (a === '--summary') out.summary = argv[++i];+ else if (a === '--pr') out.pr = argv[++i];+ else if (a === '--packages') out.packages = argv[++i];+ else if (a === '--contributor') out.contributor.push(argv[++i]);+ }+ return out;+}+const args = parseArgs(process.argv.slice(2));++// ---- shell helper --------------------------------------------------------+function sh(cmd) {+ try {+ return execSync(cmd, {+ cwd: ROOT,+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'ignore'],+ }).trim();+ } catch {+ return '';+ }+}++function readConfig() {+ return JSON.parse(+ fs.readFileSync(path.join(ROOT, '.changeset/config.json'), 'utf8'),+ );+}++// ---- discover publishable packages --------------------------------------+function discoverPackages() {+ const ws = fs.readFileSync(path.join(ROOT, 'pnpm-workspace.yaml'), 'utf8');+ const globs = [...ws.matchAll(/^\s*-\s*["']?([^"'\n]+)["']?/gm)].map(m =>+ m[1].trim(),+ );+ const dirs = new Set();+ for (const g of globs) {+ const base = g.replace(/\/\*+$/, '');+ const abs = path.join(ROOT, base);+ if (!fs.existsSync(abs)) continue;+ if (g.endsWith('*')) {+ for (const d of fs.readdirSync(abs, {withFileTypes: true})) {+ if (d.isDirectory()) dirs.add(path.join(abs, d.name));+ }+ } else {+ dirs.add(abs);+ }+ }+ const pkgs = [];+ for (const dir of dirs) {+ const pj = path.join(dir, 'package.json');+ if (!fs.existsSync(pj)) continue;+ const p = JSON.parse(fs.readFileSync(pj, 'utf8'));+ if (!p.name) continue;+ pkgs.push({name: p.name, dir, private: !!p.private, version: p.version});+ }+ return pkgs;+}++function publishable(pkgs, config) {+ const ignore = new Set(config.ignore || []);+ return pkgs.filter(p => !p.private && !ignore.has(p.name));+}++// Map changed files -> owning packages (longest-prefix match).+function detectChangedPackages(pkgs) {+ const base = readConfig().baseBranch || 'main';+ let changed = sh(`git diff --name-only origin/${base}...HEAD`)+ .split('\n')+ .filter(Boolean);+ changed = changed.concat(+ sh('git diff --name-only HEAD').split('\n').filter(Boolean),+ );+ changed = changed.concat(+ sh('git diff --name-only --cached').split('\n').filter(Boolean),+ );+ changed = [...new Set(changed)];+ const rels = pkgs+ .map(p => ({...p, rel: path.relative(ROOT, p.dir)}))+ .sort((a, b) => b.rel.length - a.rel.length);+ const hit = new Set();+ for (const f of changed) {+ for (const p of rels) {+ if (f === p.rel || f.startsWith(p.rel + '/')) {+ hit.add(p.name);+ break;+ }+ }+ }+ return hit;+}++// ---- identity ------------------------------------------------------------+function detectContributor() {+ const ghLogin = sh('gh api user --jq .login');+ if (ghLogin) return ghLogin;+ const ghName = sh('git config user.name');+ if (ghName) return ghName.replace(/\s+/g, '');+ return '';+}++// ---- prompt --------------------------------------------------------------+function makeAsk() {+ const rl = readline.createInterface({+ input: process.stdin,+ output: process.stdout,+ });+ const ask = q => new Promise(res => rl.question(q, a => res(a.trim())));+ return {ask, close: () => rl.close()};+}++function isPre1(pkgs) {+ // patch-only enforced while every publishable package is < 1.0.0+ return pkgs.every(p => /^0\./.test(String(p.version || '0')));+}++async function main() {+ const config = readConfig();+ const all = discoverPackages();+ const pub = publishable(all, config);+ const pre1 = isPre1(pub);++ let selected;+ if (args.packages) {+ selected = args.packages+ .split(',')+ .map(s => s.trim())+ .filter(Boolean);+ } else {+ const detected = detectChangedPackages(pub);+ selected = pub.map(p => p.name).filter(n => detected.has(n));+ }++ let {category, summary, pr} = args;+ let contributors = args.contributor.slice();++ if (!args.yes) {+ const {ask, close} = makeAsk();+ console.log(+ `\nPublishable packages (${pub.length}): ${pub.map(p => p.name).join(', ')}`,+ );+ if (selected.length) {+ console.log(`Detected changes in: ${selected.join(', ')}`);+ } else {+ console.log('No package changes detected from git diff.');+ }+ const pkgAns = await ask(+ `Packages for this changeset${selected.length ? ` [${selected.join(', ')}]` : ''} (comma-sep, or "all"): `,+ );+ if (pkgAns) {+ if (pkgAns.toLowerCase() === 'all') selected = pub.map(p => p.name);+ else+ selected = pkgAns+ .split(/[\s,]+/)+ .map(s => s.trim())+ .filter(Boolean);+ }++ if (!category) {+ console.log('\nCategory:');+ CATEGORIES.forEach((c, i) =>+ console.log(` ${i + 1}. ${c.key.padEnd(10)} ${c.label}`),+ );+ const ans = await ask(+ 'Pick a category [1-' + CATEGORIES.length + ' or name]: ',+ );+ const byNum = CATEGORIES[parseInt(ans, 10) - 1];+ category = byNum ? byNum.key : normalizeCategory(ans);+ }+ if (!summary) summary = await ask('One-line summary: ');+ if (!pr) pr = await ask('PR number (optional, just the digits): ');+ if (contributors.length === 0) {+ const def = detectContributor();+ const ans = await ask(`Contributor handle(s)${def ? ` [${def}]` : ''}: `);+ const raw = ans || def;+ contributors = raw+ .split(/[\s,]+/)+ .map(h => h.replace(/^@/, ''))+ .filter(Boolean);+ }+ close();+ } else {+ if (contributors.length === 0) {+ const def = detectContributor();+ if (def) contributors = [def];+ }+ }++ // ---- validate ----------------------------------------------------------+ const errs = [];+ const catKey = normalizeCategory(category);+ if (!catKey)+ errs.push(+ `category must be one of: ${CATEGORY_KEYS.join(', ')} (got ${JSON.stringify(category)})`,+ );+ if (!summary) errs.push('summary is required');+ if (selected.length === 0) errs.push('at least one package must be selected');+ if (contributors.length === 0)+ errs.push('at least one contributor is required');+ if (errs.length) {+ console.error(+ '\n✗ Cannot write changeset:\n' + errs.map(e => ' - ' + e).join('\n'),+ );+ process.exit(1);+ }++ // ---- compose body ------------------------------------------------------+ let headline = summary.trim();+ const prNum = String(pr || '').replace(/[^\d]/g, '');+ if (prNum && !/\(#\d+\)/.test(headline)) headline += ` (#${prNum})`;+ const body = `[${catKey}] ${headline}\n${contributors.map(c => '@' + c).join(' ')}`;++ // ---- bump (patch-only pre-1.0) ----------------------------------------+ const bump = 'patch'; // intentionally patch; minor/major gated by checker pre-1.0+ const frontmatter = selected.map(n => `'${n}': ${bump}`).join('\n');++ // ---- filename (human-id style without the dep) ------------------------+ const slug =+ headline+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 48) || 'change';+ const rand = Math.random().toString(36).slice(2, 6);+ const file = path.join(ROOT, '.changeset', `${slug}-${rand}.md`);++ const contents = `---\n${frontmatter}\n---\n\n${body}\n`;+ fs.writeFileSync(file, contents, 'utf8');++ console.log(`\n✓ Wrote ${path.relative(ROOT, file)}\n`);+ console.log(contents);+ if (pre1) console.log('(pre-1.0: bump forced to patch)');+}++main().catch(e => {+ console.error(e);+ process.exit(1);+});diff --git a/scripts/check-changesets.mjs b/scripts/check-changesets.mjsnew file mode 100755index 0000000000..360d942e27--- /dev/null+++ b/scripts/check-changesets.mjs@@ -0,0 +1,147 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * CI gate for XDS changesets — `node scripts/check-changesets.mjs`.+ *+ * Enforces the conventions the release process depends on:+ * 1. Pre-1.0 patch-only: while every publishable package is < 1.0.0, no+ * changeset may declare a `minor` or `major` bump (would jump 0.0.x ->+ * 0.1.0 / 1.0.0).+ * 2. Every changeset body must carry a recognized [category] tag.+ * 3. Every changeset body must credit at least one @contributor.+ * 4. Frontmatter packages must be real, publishable, non-ignored packages.+ *+ * Exits 1 with a readable report on any violation. config.json and README.md+ * are skipped.+ */++import fs from 'node:fs';+import path from 'node:path';+import {fileURLToPath} from 'node:url';+import {createRequire} from 'node:module';++const require = createRequire(import.meta.url);+const {parseEntry} = require('./changeset-entry-format.cjs');++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const CS_DIR = path.join(ROOT, '.changeset');++function readConfig() {+ return JSON.parse(fs.readFileSync(path.join(CS_DIR, 'config.json'), 'utf8'));+}++function discoverPackages() {+ const ws = fs.readFileSync(path.join(ROOT, 'pnpm-workspace.yaml'), 'utf8');+ const globs = [...ws.matchAll(/^\s*-\s*["']?([^"'\n]+)["']?/gm)].map(m =>+ m[1].trim(),+ );+ const pkgs = [];+ for (const g of globs) {+ const base = g.replace(/\/\*+$/, '');+ const abs = path.join(ROOT, base);+ if (!fs.existsSync(abs)) continue;+ const dirs = g.endsWith('*')+ ? fs+ .readdirSync(abs, {withFileTypes: true})+ .filter(d => d.isDirectory())+ .map(d => path.join(abs, d.name))+ : [abs];+ for (const dir of dirs) {+ const pj = path.join(dir, 'package.json');+ if (!fs.existsSync(pj)) continue;+ const p = JSON.parse(fs.readFileSync(pj, 'utf8'));+ if (p.name)+ pkgs.push({name: p.name, private: !!p.private, version: p.version});+ }+ }+ return pkgs;+}++function parseFrontmatter(contents) {+ const m = /^\s*---([^]*?)\n\s*---(\s*(?:\n|$)[^]*)/.exec(contents);+ if (!m) return null;+ const releases = {};+ for (const line of m[1].split('\n')) {+ const mm = /^\s*['"]?([^'":]+)['"]?\s*:\s*(\w+)\s*$/.exec(line);+ if (mm) releases[mm[1].trim()] = mm[2].trim();+ }+ return {releases, summary: m[2].trim()};+}++const SKIP = new Set(['config.json', 'README.md']);+function isChangesetFile(name) {+ return name.endsWith('.md') && !SKIP.has(name);+}++function main() {+ const config = readConfig();+ const pkgs = discoverPackages();+ const pub = pkgs.filter(+ p => !p.private && !(config.ignore || []).includes(p.name),+ );+ const pubNames = new Set(pub.map(p => p.name));+ const allNames = new Set(pkgs.map(p => p.name));+ const pre1 = pub.every(p => /^0\./.test(String(p.version || '0')));++ const files = fs.readdirSync(CS_DIR).filter(isChangesetFile);+ const problems = [];++ for (const f of files) {+ const contents = fs.readFileSync(path.join(CS_DIR, f), 'utf8');+ const fm = parseFrontmatter(contents);+ if (!fm) {+ problems.push(`${f}: missing or invalid frontmatter`);+ continue;+ }+ const names = Object.keys(fm.releases);+ if (names.length === 0)+ problems.push(`${f}: frontmatter lists no packages`);+ for (const [name, type] of Object.entries(fm.releases)) {+ if (!allNames.has(name)) {+ problems.push(`${f}: unknown package "${name}"`);+ } else if (!pubNames.has(name)) {+ problems.push(+ `${f}: "${name}" is private/ignored and cannot be released`,+ );+ }+ if (pre1 && (type === 'minor' || type === 'major')) {+ problems.push(+ `${f}: "${name}" declares "${type}" — repo is pre-1.0, use "patch" ` ++ `(minor/major would jump 0.0.x). Use [breaking] in the body to signal a breaking change.`,+ );+ }+ if (!['major', 'minor', 'patch', 'none'].includes(type)) {+ problems.push(`${f}: "${name}" has invalid bump "${type}"`);+ }+ }++ const parsed = parseEntry(fm.summary);+ if (!parsed.category) {+ problems.push(+ `${f}: body must start with a [category] tag, e.g. "[fix] ...". ` ++ `Run \`pnpm changeset:new\` to author one correctly.`,+ );+ }+ if (!parsed.headline) problems.push(`${f}: body has no summary headline`);+ if (parsed.contributors.length === 0) {+ problems.push(+ `${f}: body must credit at least one contributor, e.g. "@yourhandle" ` ++ `on its own line. Run \`pnpm changeset:new\`.`,+ );+ }+ }++ if (problems.length) {+ console.error(+ `\n✗ check:changesets found ${problems.length} problem(s):\n`,+ );+ for (const p of problems) console.error(' - ' + p);+ console.error('\nSee the Release-Process wiki and `pnpm changeset:new`.\n');+ process.exit(1);+ }+ console.log(+ `✓ check:changesets — ${files.length} changeset(s) valid${pre1 ? ' (pre-1.0 patch-only enforced)' : ''}`,+ );+}++main();diff --git a/scripts/format-changelogs.mjs b/scripts/format-changelogs.mjsnew file mode 100755index 0000000000..88bd8da2bb--- /dev/null+++ b/scripts/format-changelogs.mjs@@ -0,0 +1,257 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * Post-`changeset version` changelog formatter — `node scripts/format-changelogs.mjs`.+ *+ * `changeset version` (with our custom .changeset/changelog.cjs) writes raw+ * entries per package in the form:+ *+ * ## 0.0.16+ *+ * ### Patch Changes+ *+ * - [fix] XDSButton: spinner contrast (#2717) — thanks @cindyxz+ * - [breaking] Stack element -> as (#2441) — thanks @ejhammond+ *+ * This rewrites the just-added version block of every package CHANGELOG into+ * the doc-site format the Release-Process wiki mandates:+ *+ * # 0.0.16 (h1, was ## )+ *+ * #### Breaking Changes (h4 category sections, canonical order)+ * - Stack element -> as (#2441)+ *+ * #### Fixes+ * - XDSButton: spinner contrast (#2717)+ *+ * #### Contributors (aggregated, de-duped, sorted)+ *+ * Thanks to everyone who contributed to this release:+ *+ * - @cindyxz+ * - @ejhammond+ *+ * --- (divider before the previous version)+ *+ * Idempotent: a block already in `# x.y.z` form with no `### Patch Changes`+ * subheading and no `- [cat]` bullets is left untouched. Run right after+ * `pnpm version-packages` (which calls it automatically).+ *+ * Flags:+ * --check exit 1 if any CHANGELOG would change (CI drift guard)+ */++import fs from 'node:fs';+import path from 'node:path';+import {fileURLToPath} from 'node:url';+import {createRequire} from 'node:module';++const require = createRequire(import.meta.url);+const {+ CATEGORIES,+ labelFor,+ normalizeCategory,+} = require('./changeset-entry-format.cjs');++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const CHECK = process.argv.includes('--check');++function discoverChangelogs() {+ const ws = fs.readFileSync(path.join(ROOT, 'pnpm-workspace.yaml'), 'utf8');+ const globs = [...ws.matchAll(/^\s*-\s*["']?([^"'\n]+)["']?/gm)].map(m =>+ m[1].trim(),+ );+ const files = [];+ for (const g of globs) {+ const base = g.replace(/\/\*+$/, '');+ const abs = path.join(ROOT, base);+ if (!fs.existsSync(abs)) continue;+ const dirs = g.endsWith('*')+ ? fs+ .readdirSync(abs, {withFileTypes: true})+ .filter(d => d.isDirectory())+ .map(d => path.join(abs, d.name))+ : [abs];+ for (const dir of dirs) {+ const cl = path.join(dir, 'CHANGELOG.md');+ if (fs.existsSync(cl)) files.push(cl);+ }+ }+ return files;+}++// A bullet may span multiple lines (continuation lines are indented).+function splitBullets(body) {+ const lines = body.split('\n');+ const bullets = [];+ let cur = null;+ for (const line of lines) {+ if (/^\s*-\s+/.test(line)) {+ if (cur) bullets.push(cur);+ cur = line;+ } else if (cur && line.trim() !== '') {+ cur += '\n' + line;+ } else if (cur && line.trim() === '') {+ bullets.push(cur);+ cur = null;+ }+ }+ if (cur) bullets.push(cur);+ return bullets;+}++// Parse one rendered bullet: "- [cat] headline — thanks @a, @b"+function parseBullet(bullet) {+ const firstNl = bullet.indexOf('\n');+ const head = firstNl === -1 ? bullet : bullet.slice(0, firstNl);+ const rest = firstNl === -1 ? '' : bullet.slice(firstNl + 1);++ let text = head.replace(/^\s*-\s+/, '');+ let category = 'chore';+ const cm = text.match(/^\[([^\]]+)\]\s*(.*)$/);+ if (cm) {+ category = normalizeCategory(cm[1]) || 'chore';+ text = cm[2];+ }+ const contributors = [];+ text = text+ .replace(/\s*[—-]+\s*thanks\s+(.+)$/i, (_, who) => {+ let mm;+ const re = /@([\w-]+)/g;+ while ((mm = re.exec(who)) !== null) contributors.push(mm[1]);+ return '';+ })+ .trim();++ return {category, text, contributors, extra: rest.trimEnd()};+}++function formatVersionBlock(version, body) {+ const bullets = splitBullets(body)+ .map(parseBullet)+ .filter(b => b.text);+ const byCat = new Map();+ const contributors = new Set();+ for (const b of bullets) {+ b.contributors.forEach(c => contributors.add(c));+ if (!byCat.has(b.category)) byCat.set(b.category, []);+ byCat.get(b.category).push(b);+ }++ const out = [`# ${version}`, ''];+ for (const {key} of CATEGORIES) {+ const items = byCat.get(key);+ if (!items || !items.length) continue;+ out.push(`#### ${labelFor(key)}`, '');+ for (const it of items) {+ let line = `- ${it.text}`;+ if (it.extra) line += '\n' + it.extra;+ out.push(line);+ }+ out.push('');+ }++ if (contributors.size) {+ out.push(+ '#### Contributors',+ '',+ 'Thanks to everyone who contributed to this release:',+ '',+ );+ for (const c of [...contributors].sort((a, b) => a.localeCompare(b)))+ out.push(`- @${c}`);+ out.push('');+ }+ return (+ out+ .join('\n')+ .replace(/\n{3,}/g, '\n\n')+ .trimEnd() + '\n'+ );+}++// Returns { changed, contents }+function processFile(file) {+ const original = fs.readFileSync(file, 'utf8');+ const lines = original.split('\n');++ let i = 0;+ const titleLines = [];+ while (i < lines.length && !/^#{1,2}\s+\d+\.\d+\.\d+/.test(lines[i])) {+ titleLines.push(lines[i]);+ i++;+ }+ if (i >= lines.length) return {changed: false, contents: original};++ const headMatch = lines[i].match(/^(#{1,2})\s+(\d+\.\d+\.\d+.*)$/);+ if (!headMatch) return {changed: false, contents: original};+ const version = headMatch[2].trim();+ const startedAsH2 = headMatch[1] === '##';+ i++;++ const bodyLines = [];+ while (i < lines.length && !/^#{1,2}\s+\d+\.\d+\.\d+/.test(lines[i])) {+ bodyLines.push(lines[i]);+ i++;+ }+ const rawBody = bodyLines.join('\n');++ // Only transform raw (changesets-native) blocks.+ const looksRaw =+ startedAsH2 ||+ /^###\s+(Patch|Minor|Major)\s+Changes/m.test(rawBody) ||+ /^\s*-\s*\[[a-z]+\]/im.test(rawBody);+ if (!looksRaw) return {changed: false, contents: original};++ const cleanedBody = rawBody.replace(+ /^###\s+(Patch|Minor|Major)\s+Changes\s*$/gm,+ '',+ );+ const formatted = formatVersionBlock(version, cleanedBody);++ const rest = lines.slice(i).join('\n').replace(/^\n+/, '');+ const head = titleLines.join('\n').replace(/\n+$/, '');+ const parts = [head, '', formatted.trimEnd()];+ if (rest.trim()) parts.push('', '---', '', rest.trimEnd());+ const contents =+ parts+ .join('\n')+ .replace(/\n{3,}/g, '\n\n')+ .trimEnd() + '\n';++ return {changed: contents !== original, contents};+}++function main() {+ const files = discoverChangelogs();+ const drifted = [];+ for (const f of files) {+ const {changed, contents} = processFile(f);+ if (!changed) continue;+ drifted.push(path.relative(ROOT, f));+ if (!CHECK) fs.writeFileSync(f, contents, 'utf8');+ }++ if (CHECK) {+ if (drifted.length) {+ console.error(+ `✗ ${drifted.length} CHANGELOG(s) not formatted:\n` ++ drifted.map(d => ' - ' + d).join('\n'),+ );+ console.error(+ '\nRun `node scripts/format-changelogs.mjs` (or `pnpm version-packages`).',+ );+ process.exit(1);+ }+ console.log('✓ all CHANGELOGs formatted');+ return;+ }+ if (drifted.length)+ console.log(+ `✓ formatted ${drifted.length} CHANGELOG(s):\n` ++ drifted.map(d => ' - ' + d).join('\n'),+ );+ else console.log('✓ no CHANGELOGs needed formatting');+}++main();