@ref0/workspace 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,6 +24,8 @@ export const lint = merge(base.lint, {
24
24
 
25
25
  - `base.fmt` and `base.lint`: the shared format and lint settings. `REF0_LINT_TYPES=none` turns off
26
26
  the type-aware rules, for a local check that runs them only on changed files.
27
+ - `base.staged`: what `vp staged` runs before each commit, `vp check --fix` on the staged files,
28
+ which a repo's `vite.config.ts` takes as `staged: base.staged` for its `pre-commit` hook.
27
29
  - `merge(base, local)`: base first, local last. Ignores, plugins and overrides are joined, rules
28
30
  and options merged, so a local rule wins; any other setting is local's.
29
31
  - `@ref0/workspace/lint/plugins`: each plugin's file, as an absolute path for `jsPlugins`.
@@ -73,6 +75,61 @@ entry point's source:
73
75
  its source under the condition first. `--packages` is `packages/*` and `--condition`
74
76
  `@ref0/source` unless given. The `package-exports` skill reviews the rest: what each runtime
75
77
  resolves, side effects and each entry point's bundle.
78
+ - `commit-message <message-file>` and `commit-message --title <title>`: a commit's subject, as
79
+ the `commit-msg` hook passes it, or a pull request's title, as CI does, is
80
+ `type(scope): subject`, or `type: subject` for a change across the repo. It accepts a `!` before
81
+ the colon and ignores it, since no repo tracks breaking changes. The types are `feat`, `fix`,
82
+ `perf`, `refactor`, `test`, `docs`, `build`, `ci`, `chore` and `revert`, in every repo. The
83
+ scopes are the repo's own, in its root `package.json` as
84
+ `"ref0-workspace": { "commitScopes": ["git", "cli"] }`, or `[]` for none. A commit may also carry
85
+ git's own merge, autosquash and revert subjects, and a title may not.
86
+ - `changelog --repo <owner/name> [--path <pathspec>]... [--version <version> [--date <yyyy-mm-dd>]] [--prepend <file>] [--most-bytes <n>] <range>`:
87
+ a release's section, `## <version> (<date>)` or `## Unreleased`, from the subjects of main's own
88
+ commits in `<range>`, its first parents, that touch a `--path`, each with its pull request linked
89
+ in `--repo`. git-cliff writes them. A release's range runs from the tag before it to its own, as
90
+ `v0.4.0..HEAD` for 0.5.0, so a changelog holds one section for each tag. The section it prints
91
+ lists features, fixes and performance, each by scope, then one line that counts the other changes
92
+ and links the changelog. The section `--prepend` writes first in that file, over one for the same
93
+ version, lists every type, then the subjects in no format. Each entry's first word is lower case
94
+ unless it's a name, as `properNouns` in `changelog.ts` lists them, or has a capital, a digit or a
95
+ mark inside it, as `GitHub`, `CLI` or `` `Schema` `` do. A range with no such commit says "Nothing
96
+ published changed." The section it prints holds at most `--most-bytes`, 50,000 unless given, for
97
+ a release's pull request to carry: a longer one leaves out its oldest listed changes and ends with
98
+ a line linking the changelog, and the section `--prepend` writes is always whole.
99
+ - `pre-commit`: Git's pre-commit hook, which a repo runs from `.vite-hooks/pre-commit`. It runs
100
+ the repo's `vp staged`, which reads `staged` from its `vite.config.ts`: `vp check --fix` on the
101
+ staged files only, whose fixes it stages again. A problem `--fix` can't fix refuses the commit.
102
+ - `pre-push <remote> <url>`: Git's pre-push hook, which a repo runs from `.vite-hooks/pre-push`
103
+ with the ref lines Git writes on stdin. It refuses a push that deletes `main`, a `deploy/*` or a
104
+ `release/*` branch, or moves one to a commit that doesn't descend from where it is, and names each
105
+ ref. Creating one passes, and so does every other branch. Only `REF0_REWRITE=<repo>`, where
106
+ `<repo>` is the remote's repo name, the last part of its URL without `.git`, lets a refused push
107
+ through, so a rewrite meant for one repo opens no other.
108
+
109
+ Then a push that sends a commit runs the checks the root `package.json` names, each a script, run
110
+ through `vp run --cache` so one whose inputs haven't changed since it passed replays:
111
+
112
+ ```json
113
+ "ref0-workspace": {
114
+ "prePush": {
115
+ "always": ["check", "check:types"],
116
+ "packages": { "paths": ["packages/"], "run": ["test:lint"] }
117
+ }
118
+ }
119
+ ```
120
+
121
+ `always` runs on every such push, and `packages.run` too when a pushed commit no remote-tracking
122
+ branch holds changes a path `packages.paths` names, as Git's pathspecs. A key it doesn't know, or
123
+ a script `package.json` doesn't have, refuses the push and names it. The first check that fails
124
+ refuses the push, and the hook prints each check's time. It waits first, up to 10 minutes, for
125
+ the machine's 1-minute load to drop under 18, and refuses the push when it hasn't.
126
+ `REF0_SKIP_PUSH_CHECKS=1` skips the checks, and says which, but not the refusals above.
127
+
128
+ `pre-commit` and `pre-push` stop accidents and aren't a boundary: `git commit --no-verify` and
129
+ `git push --no-verify` skip them, as they do every hook, and so do `VP_GIT_HOOKS=0` and `HUSKY=0`, which turn off every Vite+ hook, and a checkout
130
+ that never installed the repo's hooks. A job that force-pushes a
131
+ `release/*` branch, as a release workflow's `release/next` does, doesn't install the hooks or sets
132
+ `VP_GIT_HOOKS=0`, and a repo's adoption checks each of its workflows for one.
76
133
 
77
134
  `types` and `type-coverage` run the repo's own `@effect/tsgo`, `tsrs` and `typescript`, its
78
135
  optional peers, resolved from its root, at the versions its catalog pins.
package/dist/bin.mjs CHANGED
@@ -1,12 +1,17 @@
1
1
  #!/usr/bin/env node
2
+ import { changelog } from "./changelog.mjs";
3
+ import { commitMessage } from "./commit-message.mjs";
2
4
  import { docsBudget } from "./docs-budget.mjs";
3
5
  import { defaultCondition, packageExports } from "./package-exports.mjs";
6
+ import { preCommit } from "./pre-commit.mjs";
7
+ import { prePush } from "./pre-push.mjs";
4
8
  import { symbolsCheck } from "./symbols/check.mjs";
5
9
  import { symbolsFind } from "./symbols/find.mjs";
6
10
  import { typeCoverage } from "./type-coverage.mjs";
7
11
  import { types } from "./types/types.mjs";
8
12
  import { execFileSync } from "node:child_process";
9
- import { argv, cwd, exit } from "node:process";
13
+ import { readFileSync } from "node:fs";
14
+ import { argv, cwd, env, exit } from "node:process";
10
15
  import { parseArgs } from "node:util";
11
16
  // src/bin.ts
12
17
  /**
@@ -21,6 +26,15 @@ import { parseArgs } from "node:util";
21
26
  * ref0-workspace type-coverage every TypeScript file in a project, and linted
22
27
  * ref0-workspace package-exports [--packages <glob>]... [--condition <name>]
23
28
  * each package's exports name files it has
29
+ * ref0-workspace commit-message <message-file> a commit's subject is in the format
30
+ * ref0-workspace commit-message --title <title> a pull request's title is in the format
31
+ * ref0-workspace changelog --repo <owner/name> [--path <pathspec>]... [--version <version>
32
+ * [--date <yyyy-mm-dd>]] [--prepend <file>] [--most-bytes <n>] <range>
33
+ * a release's notes, from main's subjects
34
+ * ref0-workspace pre-commit Git's pre-commit hook: `vp staged`
35
+ * ref0-workspace pre-push <remote> <url> Git's pre-push hook: no force-push or delete
36
+ * of main, deploy/* or release/*, then the
37
+ * repo's checks
24
38
  */
25
39
  /** The root of the Git checkout the command runs in, or where it runs outside one. */
26
40
  const root = () => {
@@ -99,6 +113,25 @@ const checks = /* @__PURE__ */ new Map([
99
113
  if (parsed === void 0) return usageError();
100
114
  return packageExports(root(), parsed);
101
115
  }
116
+ }],
117
+ ["pre-commit", plain("Git's pre-commit hook: vp check --fix on the staged files", preCommit)],
118
+ ["commit-message", {
119
+ args: "<message-file> | --title <title>",
120
+ about: "a commit's subject, or a pull request's title, is type(scope): subject",
121
+ run: (args) => commitMessage(args, root())
122
+ }],
123
+ ["changelog", {
124
+ args: "--repo <owner/name> [--path <pathspec>]... [--version <version> [--date <yyyy-mm-dd>]] [--prepend <file>] [--most-bytes <n>] <range>",
125
+ about: "a release's notes, from the subjects of main's commits in the range, by type",
126
+ run: (args) => changelog(args, root())
127
+ }],
128
+ ["pre-push", {
129
+ args: "<remote> <url>",
130
+ about: "Git's pre-push hook: refuses a force-push or delete of main, deploy/* or release/*, then runs the checks the root package.json names",
131
+ run: ([remote, url, ...extra]) => {
132
+ if (remote === void 0 || url === void 0 || extra.length > 0) return usageError();
133
+ return prePush(root(), url, readFileSync(0, "utf8"), env);
134
+ }
102
135
  }]
103
136
  ]);
104
137
  function usage() {
@@ -0,0 +1,431 @@
1
+ import { commitTypes } from "./commit-message.mjs";
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
+ import { execPath, stdout } from "node:process";
5
+ import { parseArgs } from "node:util";
6
+ import { Buffer } from "node:buffer";
7
+ import { tmpdir } from "node:os";
8
+ import { join, relative, resolve } from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ import { Option, Schema } from "effect";
11
+ // src/changelog.ts
12
+ /**
13
+ * A release's notes, from the subjects of the commits on main since the last release, grouped by
14
+ * their type, as `commit-message.ts` reads them, and within it by scope:
15
+ *
16
+ * ref0-workspace changelog --repo <owner/name> [--path <pathspec>]...
17
+ * [--version <version> [--date <yyyy-mm-dd>]] [--prepend <file>]
18
+ * [--most-bytes <n>] <range>
19
+ *
20
+ * A release's range runs from the tag before it to its own, such as `v0.4.0..HEAD` for 0.5.0, so a
21
+ * changelog holds one section for each tag, each written by its own run.
22
+ *
23
+ * It prints the release's section, `## <version> (<date>)`, or `## Unreleased` with no version:
24
+ * its features, fixes and performance changes, `listedTypes`, then a line that counts the rest and
25
+ * links the changelog. With `--prepend` it writes the section first in that file, under
26
+ * `# Changelog`, over a section for the same version already there, and that one lists every type.
27
+ *
28
+ * The section it prints holds at most `--most-bytes`, `notesBytesMost` by default, since a release's
29
+ * pull request and its GitHub release carry it. One that's longer leaves out its oldest listed
30
+ * changes, says how many in a line linking the changelog, which holds every one, and says so on
31
+ * stderr: a bound too small for even its heading and those lines prints those alone. The section
32
+ * `--prepend` writes is always whole.
33
+ *
34
+ * The commits are main's own, its first parents in `<range>`, as `git log --first-parent` lists
35
+ * them, that touch a `--path` when it names one: a merged pull request is one line, under its title,
36
+ * and the commits on its branch are none. git-cliff reads them and writes the notes, from a config
37
+ * this module makes from `commitTypes`. Its own `--include-path` isn't used: it reads every commit
38
+ * in the range, merged branches' too, and on a merge it misses what the merge brought and keeps what
39
+ * it didn't.
40
+ *
41
+ * A `<range>` without `..`, such as `HEAD` for a first release, is every commit it reaches. git-cliff
42
+ * reads only `a..b`, so for one it reads all of HEAD's history, and the commit has to be in it.
43
+ */
44
+ /** Each type's heading in the notes, which list them in `commitTypes`' order. */
45
+ const typeHeadings = {
46
+ feat: "Features",
47
+ fix: "Fixes",
48
+ perf: "Performance",
49
+ refactor: "Refactors",
50
+ test: "Tests",
51
+ docs: "Docs",
52
+ build: "Build",
53
+ ci: "CI",
54
+ chore: "Chores",
55
+ revert: "Reverts"
56
+ };
57
+ /** The types a release's notes list. The rest are counted there, and only the changelog lists them. */
58
+ const listedTypes = [
59
+ "feat",
60
+ "fix",
61
+ "perf"
62
+ ];
63
+ /** The heading for a subject in no format, which the notes list last. */
64
+ const otherHeading = "Other";
65
+ /** A type's group in git-cliff's config: its heading, after its place in `commitTypes`, hidden. */
66
+ const groupOf = (type) => `<!-- ${String(commitTypes.indexOf(type)).padStart(2, "0")} -->${typeHeadings[type]}`;
67
+ const listedGroups = new Set(listedTypes.map(groupOf));
68
+ /**
69
+ * The words an entry keeps capitalised when one starts it: names, as git's and home's subjects use
70
+ * them, and the cast's.
71
+ */
72
+ const properNouns = /* @__PURE__ */ new Set([
73
+ "Acme",
74
+ "Blacksmith",
75
+ "Bun",
76
+ "Claude",
77
+ "Cloudflare",
78
+ "Codex",
79
+ "Cursor",
80
+ "Deno",
81
+ "Effect",
82
+ "Gemini",
83
+ "Git",
84
+ "Mo",
85
+ "Neon",
86
+ "Node",
87
+ "Nuxt",
88
+ "Pip",
89
+ "Postgres",
90
+ "Schema",
91
+ "Sol",
92
+ "Turso",
93
+ "Vercel",
94
+ "Vite",
95
+ "Vitest"
96
+ ]);
97
+ /**
98
+ * An entry's words, with its first word in lower case when it's an ordinary word written with a
99
+ * capital, such as `Add` or `The`. A name in `properNouns`, and a word with another capital, a
100
+ * digit, an apostrophe or a mark, such as `GitHub`, `CLI`, `R2`, `Git's` or `` `Schema` ``, stays
101
+ * as written.
102
+ */
103
+ const entryText = (text) => {
104
+ const [word = ""] = text.split(/\s/u, 1);
105
+ if (!/^(?:A|[A-Z][a-z]+)$/u.test(word) || properNouns.has(word)) return text;
106
+ return `${word.toLowerCase()}${text.slice(word.length)}`;
107
+ };
108
+ /** What a section says when no commit in its range touched what's published. */
109
+ const nothingChanged = "Nothing published changed.";
110
+ /**
111
+ * The most UTF-8 bytes the section `changelog` prints may hold. A release's pull request carries it
112
+ * in its body, which GitHub caps at 65,536 characters, beside its own lines.
113
+ */
114
+ const notesBytesMost = 5e4;
115
+ /** The most a git or git-cliff run may print: a release's context is about 2 KiB a commit. */
116
+ const outputLimit = 268435456;
117
+ /** A GitHub repository's `owner/name`, which the notes link each pull request in. */
118
+ const repoName = /^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/u;
119
+ /** git-cliff's command, which runs the binary its platform's package installs. */
120
+ const gitCliff = fileURLToPath(import.meta.resolve("git-cliff/cli"));
121
+ /** One commit's line, by its subject: the scope in bold, then its words, and as written in none. */
122
+ const line = [
123
+ "{% if commit.group is ending_with(\"",
124
+ otherHeading,
125
+ "\") %}{{ commit.raw_message | split(pat=\"\\n\") | first | trim }}",
126
+ "{% else %}{% if commit.scope %}**{{ commit.scope }}:** {% endif %}",
127
+ "{{ commit.message | split(pat=\"\\n\") | first | trim }}{% endif %}"
128
+ ].join("");
129
+ /**
130
+ * git-cliff's config for `repo`: a group for each type, in order, then the rest, with GitHub's old
131
+ * merge subject read as the title it merged, and each `(#N)` linked to its pull request. A release's
132
+ * own commit, `chore: release <version>`, or `Release: <version>` from before the format, is no
133
+ * change of its own, and nor is a merge no pull request made, such as `Merge branch 'x'`; a change
134
+ * to how releases run, such as `chore(ci): release.yml …`, is one. No
135
+ * repo tracks breaking changes, so a `!` a person writes lists under its type like any other.
136
+ */
137
+ const cliffConfig = (repo) => {
138
+ const groups = commitTypes.map((type) => ` { message = '^${type}(\\([^)]*\\))?!?: ', group = "${groupOf(type)}" },`);
139
+ return [
140
+ "[changelog]",
141
+ "header = \"\"",
142
+ `body = """\n${[
143
+ "{% for group, commits in commits | group_by(attribute=\"group\") %}",
144
+ "### {{ group | striptags | trim }}",
145
+ `{% for commit in commits %}\n- ${line}`,
146
+ "{%- endfor %}",
147
+ "{% endfor %}"
148
+ ].join("\n")}\n"""`,
149
+ "footer = \"\"",
150
+ "trim = true",
151
+ "",
152
+ "[git]",
153
+ "conventional_commits = true",
154
+ "filter_unconventional = false",
155
+ "split_commits = false",
156
+ "protect_breaking_commits = false",
157
+ "filter_commits = false",
158
+ "topo_order = false",
159
+ "sort_commits = \"oldest\"",
160
+ "commit_preprocessors = [",
161
+ ` { pattern = '^Merge pull request #(\\d+) from \\S+\\n\\n([^\\n]+)(?s:.*)$', replace = "\${2} (#\${1})" },`,
162
+ ` { pattern = '\\(#(\\d+)\\)$', replace = "([#\${1}](https://github.com/${repo}/pull/\${1}))" },`,
163
+ ` { pattern = '\\(#(\\d+)\\)\\n', replace = "([#\${1}](https://github.com/${repo}/pull/\${1}))\\n" },`,
164
+ "]",
165
+ "commit_parsers = [",
166
+ " { message = '^chore(\\([^)]*\\))?: release v?[0-9]+\\.[0-9]+\\.[0-9]+\\b', skip = true },",
167
+ " { message = '^Release: v?[0-9]+\\.[0-9]+\\.[0-9]+\\b', skip = true },",
168
+ " { message = '^Merge (branch(es)? |remote-tracking branch(es)? |commits? \\x27|tags? \\x27)', skip = true },",
169
+ ...groups,
170
+ ` { message = '.*', group = "<!-- ${commitTypes.length} -->${otherHeading}" },`,
171
+ "]",
172
+ ""
173
+ ].join("\n");
174
+ };
175
+ /** main's own commits in `range` that touch one of `paths`, or any when it names none, oldest first. */
176
+ const mainCommits = (root, range, paths) => execFileSync("git", [
177
+ "log",
178
+ "--first-parent",
179
+ "--reverse",
180
+ "--format=%H",
181
+ range,
182
+ "--",
183
+ ...paths.length === 0 ? ["."] : paths
184
+ ], {
185
+ cwd: root,
186
+ encoding: "utf8",
187
+ maxBuffer: outputLimit,
188
+ stdio: [
189
+ "ignore",
190
+ "pipe",
191
+ "pipe"
192
+ ]
193
+ }).split("\n").filter((sha) => sha !== "");
194
+ /** Every other field git-cliff's context holds, which goes back to it as it came. */
195
+ const rest = [Schema.Record(Schema.String, Schema.Unknown)];
196
+ /**
197
+ * A commit as git-cliff's context holds it: its SHA, the group its config gave it, its scope, its
198
+ * words after the type and scope, its whole message, and the rest.
199
+ */
200
+ const Commit = Schema.StructWithRest(Schema.Struct({
201
+ id: Schema.String,
202
+ group: Schema.String,
203
+ scope: Schema.NullOr(Schema.String),
204
+ message: Schema.String,
205
+ raw_message: Schema.String
206
+ }), rest);
207
+ /** A release as git-cliff's context holds it: the commits it read, and the rest. */
208
+ const Release = Schema.StructWithRest(Schema.Struct({ commits: Schema.Array(Commit) }), rest);
209
+ const decodeContext = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Array(Release)));
210
+ /** What a run git or git-cliff refused said, as `execFileSync`'s error holds it. */
211
+ const decodeRefused = Schema.decodeUnknownOption(Schema.Struct({ stderr: Schema.String }));
212
+ /** The line of a refusal that says why: git's `fatal: …` or git-cliff's `Error: …`, not its logs. */
213
+ const refusal = /^(?:fatal|error|Error): .*$/mu;
214
+ const none = {
215
+ full: "",
216
+ listed: "",
217
+ others: 0,
218
+ cut: 0
219
+ };
220
+ /**
221
+ * The notes for main's commits in `range` that touch `paths`, linked in `repo`: each heading and its
222
+ * lines, or "" when there are none. When `fits` refuses the whole of `listed`, it leaves out the
223
+ * fewest oldest changes it takes for `fits` to take them.
224
+ */
225
+ const releaseNotes = (options) => {
226
+ const { root, repo, range, paths, fits = () => true } = options;
227
+ const shas = mainCommits(root, range, paths);
228
+ if (shas.length === 0) return none;
229
+ const walked = range.includes("..") ? [range] : [];
230
+ const inHead = () => spawnSync("git", [
231
+ "merge-base",
232
+ "--is-ancestor",
233
+ range,
234
+ "HEAD"
235
+ ], { cwd: root }).status === 0;
236
+ if (walked.length === 0 && !inHead()) throw new Error(`${range} isn't in HEAD's history, which is all a range without .. can read`);
237
+ const scratch = mkdtempSync(join(tmpdir(), "ref0-changelog-"));
238
+ try {
239
+ const config = join(scratch, "cliff.toml");
240
+ writeFileSync(config, cliffConfig(repo));
241
+ const cliff = (args) => execFileSync(execPath, [
242
+ gitCliff,
243
+ "--config",
244
+ config,
245
+ ...args
246
+ ], {
247
+ cwd: root,
248
+ encoding: "utf8",
249
+ maxBuffer: outputLimit,
250
+ stdio: [
251
+ "ignore",
252
+ "pipe",
253
+ "pipe"
254
+ ]
255
+ });
256
+ const releases = decodeContext(cliff([
257
+ "--repository",
258
+ root,
259
+ "--context",
260
+ ...walked
261
+ ]));
262
+ const [first] = releases;
263
+ if (first === void 0) return none;
264
+ const read = new Map(releases.flatMap(({ commits }) => commits.map((commit) => [commit.id, commit])));
265
+ const commits = shas.flatMap((sha) => read.get(sha) ?? []);
266
+ if (commits.length === 0) return none;
267
+ const context = join(scratch, "context.json");
268
+ const render = (kept) => {
269
+ if (kept.length === 0) return "";
270
+ const entries = kept.map((commit) => {
271
+ if (commit.group.endsWith(otherHeading)) return commit;
272
+ const message = entryText(commit.message);
273
+ const raw_message = commit.raw_message.replace(commit.message, () => message);
274
+ return {
275
+ ...commit,
276
+ message,
277
+ raw_message
278
+ };
279
+ }).toSorted((a, b) => order(a.scope ?? "~", b.scope ?? "~"));
280
+ writeFileSync(context, JSON.stringify([{
281
+ ...first,
282
+ version: null,
283
+ commits: entries
284
+ }]));
285
+ return tidy(cliff(["--from-context", context]));
286
+ };
287
+ const full = render(commits);
288
+ const listed = commits.filter((commit) => listedGroups.has(commit.group));
289
+ const others = commits.length - listed.length;
290
+ const without = (cut) => render(listed.slice(cut));
291
+ const whole = without(0);
292
+ if (listed.length === 0 || fits(whole, 0, others)) return {
293
+ full,
294
+ listed: whole,
295
+ others,
296
+ cut: 0
297
+ };
298
+ let [low, high] = [1, listed.length];
299
+ while (low < high) {
300
+ const cut = Math.floor((low + high) / 2);
301
+ if (fits(without(cut), cut, others)) high = cut;
302
+ else low = cut + 1;
303
+ }
304
+ return {
305
+ full,
306
+ listed: without(low),
307
+ others,
308
+ cut: low
309
+ };
310
+ } finally {
311
+ rmSync(scratch, {
312
+ recursive: true,
313
+ force: true
314
+ });
315
+ }
316
+ };
317
+ /** -1, 0 or 1 as `a` sorts before, with or after `b`, by code unit, as every machine sorts. */
318
+ const order = (a, b) => a < b ? -1 : a > b ? 1 : 0;
319
+ /** Notes with one blank line before each heading and between blocks, and none at either end. */
320
+ const tidy = (notes) => notes.replace(/\n*^(### )/gmu, "\n\n$1").replace(/\n{3,}/gu, "\n\n").trim();
321
+ /** A release's section: its heading, `## <version> (<date>)` or `## Unreleased`, then its notes. */
322
+ const section = (version, date, notes) => {
323
+ return `${version === void 0 ? "## Unreleased" : `## ${version} (${date})`}\n\n${notes.trim() === "" ? nothingChanged : notes.trim()}\n`;
324
+ };
325
+ /** The line that ends notes missing their `cut` oldest changes, linking `file`, which holds them. */
326
+ const cutLine = (cut, repo, file) => `_${cut} older ${cut === 1 ? "change isn't" : "changes aren't"} listed here: [${file}](https://github.com/${repo}/blob/main/${file}) lists every one._`;
327
+ /** The line that counts the `others` the notes don't list, linking `file`, which lists them. */
328
+ const othersLine = (others, repo, file) => `${others} other ${others === 1 ? "change" : "changes"} (refactors, tests, CI, docs, chores) ${others === 1 ? "is" : "are"} in [${file}](https://github.com/${repo}/blob/main/${file}).`;
329
+ /** The section `changelog` prints: its listed notes, then `cutLine` and `othersLine` when they say any. */
330
+ const printedSection = (version, date, listed, lines) => {
331
+ const heading = version === void 0 ? "## Unreleased" : `## ${version} (${date})`;
332
+ if (lines.length === 0) return section(version, date, listed);
333
+ return `${heading}\n\n${[listed.trim(), ...lines].filter((part) => part !== "").join("\n\n")}\n`;
334
+ };
335
+ const changelogHead = "# Changelog\n";
336
+ /**
337
+ * A changelog with `fresh`, a release's section, first, under `# Changelog`. A section with the
338
+ * same heading's version already there, as on a run that makes the release again, is written over,
339
+ * not added twice.
340
+ */
341
+ const prepend = (existing, fresh) => {
342
+ const heading = /^## \S+/u.exec(fresh)?.[0] ?? fresh;
343
+ const kept = (existing ?? changelogHead).replace(/^# Changelog\n+/u, "").split(/(?=^## )/mu).filter((part) => part.trim() !== "").filter((part) => !part.startsWith(`${heading} `) && !part.startsWith(`${heading}\n`));
344
+ return `${changelogHead}\n${[fresh, ...kept].map((part) => part.trimEnd()).join("\n\n")}\n`;
345
+ };
346
+ const usage = "usage: ref0-workspace changelog --repo <owner/name> [--path <pathspec>]... [--version <version> [--date <yyyy-mm-dd>]] [--prepend <file>] [--most-bytes <n>] <range>";
347
+ /** The command, on `args`, for the repo at `root`: prints the section, and answers its exit code. */
348
+ const changelog = (args, root) => {
349
+ const parsed = (() => {
350
+ try {
351
+ return parseArgs({
352
+ args: [...args],
353
+ allowPositionals: true,
354
+ options: {
355
+ repo: { type: "string" },
356
+ path: {
357
+ type: "string",
358
+ multiple: true,
359
+ default: []
360
+ },
361
+ version: { type: "string" },
362
+ date: { type: "string" },
363
+ prepend: { type: "string" },
364
+ "most-bytes": { type: "string" }
365
+ }
366
+ });
367
+ } catch {
368
+ return;
369
+ }
370
+ })();
371
+ const values = parsed?.values;
372
+ const [range, ...extra] = parsed?.positionals ?? [];
373
+ if (values === void 0 || range === void 0 || range.startsWith("-") || extra.length > 0 || values.date !== void 0 && values.version === void 0) {
374
+ console.error(usage);
375
+ return 2;
376
+ }
377
+ if (values.repo === void 0 || !repoName.test(values.repo)) {
378
+ console.error(`changelog: --repo is the GitHub repository's owner/name, such as ref-0/home.\n${usage}`);
379
+ return 2;
380
+ }
381
+ if (values.date !== void 0 && !/^\d{4}-\d{2}-\d{2}$/u.test(values.date)) {
382
+ console.error(`changelog: --date is the release's day, as yyyy-mm-dd.\n${usage}`);
383
+ return 2;
384
+ }
385
+ const most = values["most-bytes"] === void 0 ? notesBytesMost : Number(values["most-bytes"]);
386
+ if (!Number.isSafeInteger(most) || most < 1 || !/^\d+$/u.test(values["most-bytes"] ?? "1")) {
387
+ console.error(`changelog: --most-bytes is a count of bytes, such as ${notesBytesMost}.\n${usage}`);
388
+ return 2;
389
+ }
390
+ const { repo } = values;
391
+ const date = values.date ?? (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
392
+ const file = values.prepend === void 0 ? "CHANGELOG.md" : relative(root, resolve(values.prepend));
393
+ const printed = (listed, cut, others) => printedSection(values.version, date, listed, [...cut === 0 ? [] : [cutLine(cut, repo, file)], ...others === 0 ? [] : [othersLine(others, repo, file)]]);
394
+ const fits = (listed, cut, others) => Buffer.byteLength(printed(listed, cut, others)) <= most;
395
+ const read = (() => {
396
+ try {
397
+ return { notes: releaseNotes({
398
+ root,
399
+ repo,
400
+ range,
401
+ paths: values.path,
402
+ fits
403
+ }) };
404
+ } catch (error) {
405
+ const said = Option.match(decodeRefused(error), {
406
+ onNone: () => "",
407
+ onSome: ({ stderr }) => refusal.exec(stderr)?.[0] ?? stderr.trim()
408
+ });
409
+ return { failed: said === "" ? String(error) : said };
410
+ }
411
+ })();
412
+ if ("failed" in read) {
413
+ console.error(`changelog: couldn't read ${range}: ${read.failed}`);
414
+ return 1;
415
+ }
416
+ const { full, listed, others, cut } = read.notes;
417
+ if (values.prepend !== void 0) {
418
+ const existing = (() => {
419
+ try {
420
+ return readFileSync(values.prepend, "utf8");
421
+ } catch {
422
+ return;
423
+ }
424
+ })();
425
+ writeFileSync(values.prepend, prepend(existing, section(values.version, date, full)));
426
+ }
427
+ if (cut > 0) console.error(`changelog: left out the ${cut} oldest of the changes to print at most ${most} bytes; ${file} lists every one.`);
428
+ stdout.write(printed(listed, cut, others));
429
+ return 0;
430
+ };
431
+ export { changelog, cliffConfig, cutLine, entryText, listedTypes, mainCommits, notesBytesMost, nothingChanged, othersLine, prepend, properNouns, releaseNotes, section, typeHeadings };
@@ -0,0 +1,138 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { Option, Schema } from "effect";
4
+ // src/commit-message.ts
5
+ /**
6
+ * The commit format every ref-0 repo keeps, `type(scope): subject`, on a commit on a branch and on
7
+ * a pull request's title, which main's merge commit takes as its subject.
8
+ *
9
+ * ref0-workspace commit-message <message-file> the commit-msg hook, on each commit
10
+ * ref0-workspace commit-message --title <title> CI, on the pull request's title
11
+ *
12
+ * The types are the same in every repo, and the release notes group by them, as `changelog.ts`
13
+ * says. Each repo names its own scopes in its root `package.json`, under `ref0-workspace`, as
14
+ * `{ "commitScopes": ["git", "cli"] }`, and its `.agents/repo/commits.md` says what each names.
15
+ *
16
+ * A commit may also carry one of git's own subjects: a merge's, `Merge branch …`,
17
+ * `Merge remote-tracking branch …`, `Merge commit '…'` or `Merge tag '…'`, or the plural git writes
18
+ * for an octopus merge, such as `Merge branches 'a' and 'b'`, an autosquash's,
19
+ * `fixup! …`, `squash! …` or `amend! …`, and a revert's, `Revert "…"` or `Reapply "…"`, which
20
+ * `git revert` writes without running `commit-msg`. A title may not, since it becomes main's
21
+ * subject.
22
+ */
23
+ /** The kinds of change, in the order the release notes list them. */
24
+ const commitTypes = [
25
+ "feat",
26
+ "fix",
27
+ "perf",
28
+ "refactor",
29
+ "test",
30
+ "docs",
31
+ "build",
32
+ "ci",
33
+ "chore",
34
+ "revert"
35
+ ];
36
+ /**
37
+ * git's own subjects, which a commit may carry and a title may not: a merge's, as `fmt-merge-msg`
38
+ * writes it for one or several of a kind, an autosquash's and a revert's.
39
+ */
40
+ const gitsOwn = /^(?:Merge (?:branch(?:es)? |remote-tracking branch(?:es)? |commits? '|tags? ')|(?:fixup|squash|amend)! |(?:Revert|Reapply) ")/u;
41
+ /** `type`, then `(scope)` or nothing, then `!` or nothing, then `: ` and the words. */
42
+ const subjectLine = /^([^\s(!:]+)(?:\(([^()]*)\))?!?: (\S(?:.*\S)?)$/u;
43
+ /** A scope's name, as a repo may give it: lower case words joined by `-`. */
44
+ const scopeName = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
45
+ const read = (line, scopes) => {
46
+ const match = subjectLine.exec(line);
47
+ if (match === null) return {
48
+ valid: false,
49
+ problem: `"${line}" isn't "type(scope): subject", or "type: subject" for a change across the repo`
50
+ };
51
+ const [, word = "", named, text = ""] = match;
52
+ const type = commitTypes.find((each) => each === word);
53
+ if (type === void 0) return {
54
+ valid: false,
55
+ problem: `"${word}" isn't a type: use one of ${commitTypes.join(", ")}`
56
+ };
57
+ if (named !== void 0 && !scopes.includes(named)) return {
58
+ valid: false,
59
+ problem: `"${named}" isn't a scope: ${scopes.length === 0 ? "this repo names none, so leave it off" : `use one of ${scopes.join(", ")}, or none`}`
60
+ };
61
+ return {
62
+ valid: true,
63
+ subject: {
64
+ type,
65
+ scope: named,
66
+ text
67
+ }
68
+ };
69
+ };
70
+ /** What's wrong with `line` as a commit's subject or a pull request's title, or undefined. */
71
+ const subjectProblem = (line, checked, scopes) => {
72
+ if (checked === "commit" && gitsOwn.test(line)) return void 0;
73
+ const subject = read(line, scopes);
74
+ return subject.valid ? void 0 : subject.problem;
75
+ };
76
+ /**
77
+ * A comment as git's editor and a commit template write one: `#` alone, or `#` and a space. `-m`
78
+ * keeps every line, so a line such as `#123: a fix` is a subject, never a comment. In the editor,
79
+ * git strips a person's own `#foo` line only after the hook has run, so the hook refuses it as the
80
+ * subject: rare, and it refuses, never lets a subject through.
81
+ */
82
+ const comment = /^#(?: |$)/u;
83
+ /**
84
+ * A commit message's subject, as git keeps it: its first line that isn't blank or a comment,
85
+ * before the `>8` line `commit -v` adds, or undefined for a message with none, which git refuses.
86
+ */
87
+ const messageSubject = (message) => {
88
+ for (const raw of message.split("\n")) {
89
+ if (/^# -+ >8 -+$/u.test(raw)) return void 0;
90
+ const line = raw.trimEnd();
91
+ if (line !== "" && !comment.test(line)) return line;
92
+ }
93
+ };
94
+ /** What's wrong with a commit message's subject, or undefined: an empty one is git's to refuse. */
95
+ const messageProblem = (message, scopes) => {
96
+ const subject = messageSubject(message);
97
+ return subject === void 0 ? void 0 : subjectProblem(subject, "commit", scopes);
98
+ };
99
+ /** The part of a repo's root `package.json` that names its scopes. */
100
+ const Manifest = Schema.Struct({ "ref0-workspace": Schema.Struct({ commitScopes: Schema.Array(Schema.String) }) });
101
+ const decodeManifest = Schema.decodeUnknownOption(Schema.fromJsonString(Manifest));
102
+ /** The repo's scopes from its root `package.json`, or what's wrong with how it names them. */
103
+ const commitScopes = (root) => {
104
+ const file = join(root, "package.json");
105
+ const where = `${file}'s "ref0-workspace"."commitScopes"`;
106
+ const text = (() => {
107
+ try {
108
+ return readFileSync(file, "utf8");
109
+ } catch {
110
+ return "";
111
+ }
112
+ })();
113
+ const manifest = decodeManifest(text);
114
+ if (Option.isNone(manifest)) return { problem: `${where} isn't a list of words: name the repo's scopes, or [] for none` };
115
+ const scopes = manifest.value["ref0-workspace"].commitScopes;
116
+ const wrong = scopes.find((scope) => !scopeName.test(scope));
117
+ if (wrong !== void 0) return { problem: `${where} holds ${JSON.stringify(wrong)}: a scope is lower case words joined by -` };
118
+ return { scopes };
119
+ };
120
+ /** The command, on `args`, for the repo at `root`: answers its exit code. */
121
+ const commitMessage = (args, root) => {
122
+ const [first, second, ...rest] = args;
123
+ const title = first === "--title";
124
+ if (first === void 0 || rest.length > 0 || title !== (second !== void 0)) {
125
+ console.error("usage: ref0-workspace commit-message <message-file> | --title <title>");
126
+ return 2;
127
+ }
128
+ const config = commitScopes(root);
129
+ if ("problem" in config) {
130
+ console.error(`commit-message: ${config.problem}.`);
131
+ return 2;
132
+ }
133
+ const problem = title ? subjectProblem(second ?? "", "title", config.scopes) : messageProblem(readFileSync(first, "utf8"), config.scopes);
134
+ if (problem === void 0) return 0;
135
+ console.error(`${title ? "The pull request's title" : "The commit's subject"}: ${problem}. .agents/repo/commits.md says how.`);
136
+ return 1;
137
+ };
138
+ export { commitMessage, commitScopes, commitTypes, messageProblem, messageSubject, subjectProblem };
@@ -38,6 +38,15 @@ const budgets = {
38
38
  rules: 8e3,
39
39
  glossaryEntry: 400
40
40
  };
41
+ /** The `model-tier` values a skill's frontmatter may name, as `select-model` defines them. */
42
+ const modelTiers = [
43
+ "lookup",
44
+ "research",
45
+ "code",
46
+ "perf",
47
+ "frontier"
48
+ ];
49
+ const validModelTiers = new Set(modelTiers);
41
50
  const history = /\b\d{1,2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]* \d{4}\b/;
42
51
  /** `text` without fenced blocks or inline code, where a date is an example, not history. */
43
52
  const prose = (text) => text.replace(/^(```|~~~)[^\n]*\n[\s\S]*?^\1[^\n]*$/gm, "").replace(/`[^`\n]*`/g, "");
@@ -94,6 +103,14 @@ const description = (text) => {
94
103
  const folded = (end === -1 ? rest : rest.slice(0, end)).map((line) => line.trim());
95
104
  return (/^[>|]-?$/.test(first) ? folded.join(" ") : first).replace(/^(["'])([\s\S]*)\1$/, "$2");
96
105
  };
106
+ /**
107
+ * A `SKILL.md`'s frontmatter `model-tier`, trimmed and unquoted. `undefined` when it has none.
108
+ */
109
+ const modelTier = (text) => {
110
+ const line = (/^---\n([\s\S]*?)\n---/.exec(text)?.[1])?.split("\n").find((entry) => entry.startsWith("model-tier:"));
111
+ if (line === void 0) return void 0;
112
+ return line.slice(11).trim().replace(/^(["'])([\s\S]*)\1$/, "$2");
113
+ };
97
114
  /** What the docs break, one line each, with what to do about it. */
98
115
  const problems = (docs, upstream) => {
99
116
  const found = [];
@@ -109,6 +126,8 @@ const problems = (docs, upstream) => {
109
126
  if (skill !== void 0) {
110
127
  const about = description(text) ?? "";
111
128
  if (about.length > budgets.description) found.push(`${path}: its description is ${about.length} characters, over ${budgets.description}. Say what it does, when to use it and which sibling to use instead; cut the method.`);
129
+ const tier = modelTier(text);
130
+ if (ours && tier !== void 0 && !validModelTiers.has(tier)) found.push(`${path}: model-tier "${tier}" is not one of ${modelTiers.join(", ")}. See the select-model skill for the tiers.`);
112
131
  if (ours && bytes(text) > budgets.skill) found.push(`${path}: ${kb(bytes(text))}, over ${kb(budgets.skill)}. ${move(path, text)}`);
113
132
  }
114
133
  if (agents || rules) {
@@ -178,4 +197,4 @@ const docsBudget = (from) => {
178
197
  warnings: warnings(docs, upstream)
179
198
  };
180
199
  };
181
- export { budgets, description, docsBudget, problems, sections, trackedDocs, upstreamSkills, warnings };
200
+ export { budgets, description, docsBudget, modelTier, modelTiers, problems, sections, trackedDocs, upstreamSkills, warnings };
@@ -1,14 +1,17 @@
1
1
  import { ViteUserConfig } from "vite-plus";
2
2
  type Format = NonNullable<ViteUserConfig['fmt']>;
3
3
  type Lint = NonNullable<ViteUserConfig['lint']>;
4
- /** A repo's format and lint settings, as Vite+'s config takes them. */
4
+ type Staged = NonNullable<ViteUserConfig['staged']>;
5
+ /** A repo's format, lint and staged-file settings, as Vite+'s config takes them. */
5
6
  export interface Settings {
6
7
  readonly fmt: Format;
7
8
  readonly lint: Lint;
9
+ readonly staged: Staged;
8
10
  }
9
11
  /**
10
- * The format and lint settings every ref-0 repo shares. A repo's `lint/config.ts` merges its own
11
- * over them with `merge`, and registers the shared plugins beside its own.
12
+ * The format, lint and staged-file settings every ref-0 repo shares. A repo's `lint/config.ts`
13
+ * merges its own over them with `merge`, and registers the shared plugins beside its own, and its
14
+ * `vite.config.ts` takes `staged` as it is.
12
15
  */
13
16
  export declare const base: Settings;
14
17
  /**
@@ -22,8 +22,9 @@ const unsafeAnyRules = [
22
22
  ];
23
23
  const typeAware = process.env["REF0_LINT_TYPES"] !== "none";
24
24
  /**
25
- * The format and lint settings every ref-0 repo shares. A repo's `lint/config.ts` merges its own
26
- * over them with `merge`, and registers the shared plugins beside its own.
25
+ * The format, lint and staged-file settings every ref-0 repo shares. A repo's `lint/config.ts`
26
+ * merges its own over them with `merge`, and registers the shared plugins beside its own, and its
27
+ * `vite.config.ts` takes `staged` as it is.
27
28
  */
28
29
  const base = {
29
30
  fmt: {
@@ -101,7 +102,8 @@ const base = {
101
102
  }
102
103
  }
103
104
  ]
104
- }
105
+ },
106
+ staged: { "*": "vp check --fix" }
105
107
  };
106
108
  /** Two lists, the shared one first, or nothing when neither config sets it. */
107
109
  const lists = (shared, own) => shared == null && own == null ? void 0 : [...shared ?? [], ...own ?? []];
@@ -0,0 +1,23 @@
1
+ import { vitePlusAt } from "./types/projects.mjs";
2
+ import { spawnSync } from "node:child_process";
3
+ import { execPath } from "node:process";
4
+ // src/pre-commit.ts
5
+ /**
6
+ * Checks what a commit stages, run as Git's pre-commit hook:
7
+ *
8
+ * ref0-workspace pre-commit
9
+ *
10
+ * It runs the repo's own `vp staged`, which reads the `staged` block of its `vite.config.ts`, the
11
+ * shared `base.staged` from `./lint/config`: `vp check --fix` on the staged files only, whatever
12
+ * the repo's size. lint-staged, which `vp staged` bundles, stages each fix again, so the commit
13
+ * holds the fixed file, and hides the unstaged part of a partly staged file while it runs. A
14
+ * problem `--fix` can't fix refuses the commit, and so does a repo with no `staged` block.
15
+ *
16
+ * `git commit --no-verify` skips it, as it skips every commit hook.
17
+ */
18
+ /** Runs `vp staged` in the checkout at `root`, and answers the hook's exit code. */
19
+ const preCommit = (root) => spawnSync(execPath, [vitePlusAt(root), "staged"], {
20
+ cwd: root,
21
+ stdio: "inherit"
22
+ }).status ?? 1;
23
+ export { preCommit };
@@ -0,0 +1,228 @@
1
+ import { vitePlusAt } from "./types/projects.mjs";
2
+ import { spawnSync } from "node:child_process";
3
+ import { readFileSync } from "node:fs";
4
+ import { execPath } from "node:process";
5
+ import { loadavg } from "node:os";
6
+ import { join } from "node:path";
7
+ import { Result, Schema } from "effect";
8
+ /** How long the checks wait for the load to drop, in milliseconds, before refusing the push. */
9
+ const loadWait = 6e5;
10
+ /** How often the wait reads the load again, in milliseconds. */
11
+ const loadPoll = 15e3;
12
+ /** The branches a push may only move forward. */
13
+ const isGuarded = (ref) => ref === "refs/heads/main" || /^refs\/heads\/(?:deploy|release)\/./s.test(ref);
14
+ /**
15
+ * The repo a remote's URL names: `git` for `git@github.com:ref-0/git.git` or `.../ref-0/git/`. It's
16
+ * the path's last part, or what follows `host:` when the path has no `/`, so a colon inside a local
17
+ * folder's name, as in `/srv/project:git.git`, stays in it.
18
+ */
19
+ const repoName = (url) => {
20
+ const path = url.replace(/\/+$/, "");
21
+ return (path.includes("/") ? path.slice(path.lastIndexOf("/") + 1) : path.slice(path.indexOf(":") + 1)).replace(/\.git$/, "");
22
+ };
23
+ const isZero = (sha) => /^0+$/.test(sha);
24
+ /** Whether `ancestor` is in `head`'s history, in the checkout at `at`. */
25
+ const isAncestor = (at, ancestor, head) => spawnSync("git", [
26
+ "merge-base",
27
+ "--is-ancestor",
28
+ ancestor,
29
+ head
30
+ ], {
31
+ cwd: at,
32
+ stdio: "ignore"
33
+ }).status === 0;
34
+ /** A line Git writes, the remote ref with each sha, or nothing when it isn't one. */
35
+ const parse = (line) => {
36
+ const [localRef, local, ref, remote, ...extra] = line.split(" ");
37
+ if (localRef === void 0 || local === void 0 || ref === void 0 || remote === void 0) return void 0;
38
+ return extra.length === 0 ? {
39
+ local,
40
+ ref,
41
+ remote
42
+ } : void 0;
43
+ };
44
+ /** What the update does that the guard refuses, or nothing. */
45
+ const refusal = (at, { local, ref, remote }) => {
46
+ if (!isGuarded(ref)) return void 0;
47
+ if (isZero(local)) return `deletes ${ref}`;
48
+ if (isZero(remote) || isAncestor(at, remote, local)) return void 0;
49
+ return `moves ${ref} from ${remote.slice(0, 12)} to ${local.slice(0, 12)}, not a descendant`;
50
+ };
51
+ /** The checks a repo names, under its root `package.json`'s `"ref0-workspace"."prePush"`. */
52
+ const Checks = Schema.Struct({
53
+ always: Schema.Array(Schema.String),
54
+ packages: Schema.optionalKey(Schema.Struct({
55
+ paths: Schema.Array(Schema.String),
56
+ run: Schema.Array(Schema.String)
57
+ }))
58
+ });
59
+ /** The root `package.json`, as far as the checks read it. */
60
+ const Manifest = Schema.Struct({
61
+ scripts: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
62
+ "ref0-workspace": Schema.optionalKey(Schema.Unknown)
63
+ });
64
+ /** The repo's `"ref0-workspace"`, every key it may hold, so a misspelt one is named. */
65
+ const Settings = Schema.Struct({
66
+ commitScopes: Schema.optionalKey(Schema.Unknown),
67
+ prePush: Schema.optionalKey(Checks)
68
+ });
69
+ const decodeManifest = Schema.decodeUnknownResult(Schema.fromJsonString(Manifest));
70
+ const decodeSettings = Schema.decodeUnknownResult(Settings, { onExcessProperty: "error" });
71
+ /**
72
+ * The checks the repo at `root` names, none when it names none, or what's wrong with how it names
73
+ * them.
74
+ */
75
+ const checksAt = (root) => {
76
+ const file = join(root, "package.json");
77
+ const text = (() => {
78
+ try {
79
+ return readFileSync(file, "utf8");
80
+ } catch {
81
+ return;
82
+ }
83
+ })();
84
+ if (text === void 0) return { checks: void 0 };
85
+ const manifest = decodeManifest(text);
86
+ if (Result.isFailure(manifest)) return { problem: `${file} isn't JSON a manifest holds` };
87
+ const settings = decodeSettings(manifest.success["ref0-workspace"] ?? {});
88
+ if (Result.isFailure(settings)) return { problem: `${file}'s "ref0-workspace": ${settings.failure.message}` };
89
+ const checks = settings.success.prePush;
90
+ if (checks === void 0) return { checks: void 0 };
91
+ const scripts = manifest.success.scripts ?? {};
92
+ const missing = [...checks.always, ...checks.packages?.run ?? []].filter((name) => !Object.hasOwn(scripts, name));
93
+ if (missing.length > 0) return { problem: `${file}'s "ref0-workspace"."prePush" names ${missing.join(", ")}, not a script it has` };
94
+ return { checks };
95
+ };
96
+ /** Whether a commit the updates push, held by no remote-tracking branch, changes `paths`. */
97
+ const changes = (at, updates, paths) => paths.length > 0 && updates.some(({ local, remote }) => {
98
+ const held = !isZero(remote) && spawnSync("git", [
99
+ "cat-file",
100
+ "-e",
101
+ `${remote}^{commit}`
102
+ ], {
103
+ cwd: at,
104
+ stdio: "ignore"
105
+ }).status === 0;
106
+ const { stdout } = spawnSync("git", [
107
+ "rev-list",
108
+ "-1",
109
+ local,
110
+ ...held ? [`^${remote}`] : [],
111
+ "--not",
112
+ "--remotes",
113
+ "--",
114
+ ...paths
115
+ ], {
116
+ cwd: at,
117
+ encoding: "utf8"
118
+ });
119
+ return stdout.trim() !== "";
120
+ });
121
+ const host = {
122
+ load: () => loadavg()[0] ?? 0,
123
+ sleep: (ms) => {
124
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
125
+ }
126
+ };
127
+ /** Whether the machine's load drops under `loadCeiling` within `loadWait`, saying when it waits. */
128
+ const loadDrops = (machine) => {
129
+ const load = machine.load();
130
+ if (load < 18) return true;
131
+ console.error(`ref0-workspace pre-push: the load is ${load.toFixed(1)}, so the checks wait up to ${loadWait / 6e4} min for it to drop under 18`);
132
+ const dropped = Array.from({ length: Math.ceil(loadWait / loadPoll) }).some(() => {
133
+ machine.sleep(loadPoll);
134
+ return machine.load() < 18;
135
+ });
136
+ if (!dropped) console.error(`ref0-workspace pre-push: refused, the load stayed at 18 or more for ${loadWait / 6e4} min. Push again later, or set REF0_SKIP_PUSH_CHECKS=1 to push without the checks.`);
137
+ return dropped;
138
+ };
139
+ /** Runs the script `name` through the task cache, and answers whether it passed and how long it took. */
140
+ const runScript = (root, name) => {
141
+ const started = performance.now();
142
+ const { status } = spawnSync(execPath, [
143
+ vitePlusAt(root),
144
+ "run",
145
+ "--cache",
146
+ name
147
+ ], {
148
+ cwd: root,
149
+ stdio: [
150
+ "ignore",
151
+ "inherit",
152
+ "inherit"
153
+ ]
154
+ });
155
+ return {
156
+ name,
157
+ status,
158
+ seconds: (performance.now() - started) / 1e3
159
+ };
160
+ };
161
+ /** Runs the checks the repo at `root` names for the updates, and answers the hook's exit code. */
162
+ const runChecks = (root, updates, skip, machine) => {
163
+ const sent = updates.filter(({ local }) => !isZero(local));
164
+ if (sent.length === 0) return 0;
165
+ const named = checksAt(root);
166
+ if ("problem" in named) {
167
+ console.error(`ref0-workspace pre-push: refused, ${named.problem}`);
168
+ return 1;
169
+ }
170
+ const { checks } = named;
171
+ if (checks === void 0) return 0;
172
+ const extra = checks.packages !== void 0 && changes(root, sent, checks.packages.paths) ? checks.packages.run : [];
173
+ const names = [...checks.always, ...extra];
174
+ if (skip === "1") {
175
+ console.error(`ref0-workspace pre-push: REF0_SKIP_PUSH_CHECKS=1, so these didn't run: ${names.join(", ")}`);
176
+ return 0;
177
+ }
178
+ if (!loadDrops(machine)) return 1;
179
+ const ran = [];
180
+ const failed = names.find((name) => {
181
+ const result = runScript(root, name);
182
+ ran.push(result);
183
+ return result.status !== 0;
184
+ });
185
+ const times = ran.map(({ name, seconds }) => `${name} ${seconds.toFixed(1)} s`).join(", ");
186
+ if (failed !== void 0) {
187
+ console.error(`ref0-workspace pre-push: refused, ${failed} failed (${times}). Fix it and push again, or set REF0_SKIP_PUSH_CHECKS=1 to push without the checks.`);
188
+ return 1;
189
+ }
190
+ const why = extra.length > 0 ? `, ${extra.join(", ")} since it changes the packages` : "";
191
+ console.error(`ref0-workspace pre-push: ran ${times}${why}`);
192
+ return 0;
193
+ };
194
+ /**
195
+ * Answers the hook's exit code for the push to `url`, whose ref lines are `input`, from the checkout
196
+ * at `at`, printing each refusal, then each check's result.
197
+ */
198
+ const prePush = (at, url, input, env, machine = host) => {
199
+ const lines = input.split("\n").filter((line) => line.trim() !== "");
200
+ const updates = lines.map(parse);
201
+ const malformed = lines.find((_, index) => updates[index] === void 0);
202
+ if (malformed !== void 0) {
203
+ console.error(`ref0-workspace pre-push: can't read the ref line "${malformed}"`);
204
+ return 2;
205
+ }
206
+ const read = updates.filter((update) => update !== void 0);
207
+ const refused = read.flatMap((update) => {
208
+ const found = refusal(at, update);
209
+ return found === void 0 ? [] : [found];
210
+ });
211
+ const guarded = guard(url, refused, env.REF0_REWRITE);
212
+ if (guarded !== 0) return guarded;
213
+ return runChecks(at, read, env.REF0_SKIP_PUSH_CHECKS, machine);
214
+ };
215
+ /** Answers the guard's exit code for the refusals it found, printing them. */
216
+ const guard = (url, refused, rewrite) => {
217
+ if (refused.length === 0) return 0;
218
+ const repo = repoName(url);
219
+ if (repo !== "" && rewrite === repo) {
220
+ console.error(`ref0-workspace pre-push: REF0_REWRITE=${repo}, so this push ${refused.join(", ")}`);
221
+ return 0;
222
+ }
223
+ for (const line of refused) console.error(`ref0-workspace pre-push: refused, this push ${line}`);
224
+ const other = rewrite === void 0 || rewrite === "" ? "" : ` REF0_REWRITE is ${rewrite}, not ${repo}.`;
225
+ console.error(`Only a rewrite of ${repo} itself, on purpose, moves these back: set REF0_REWRITE=${repo}.${other}`);
226
+ return 1;
227
+ };
228
+ export { checksAt, isGuarded, loadDrops, loadPoll, loadWait, prePush, repoName };
@@ -1,6 +1,6 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { pid } from "node:process";
3
2
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { pid } from "node:process";
4
4
  import { dirname, join } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { createHash } from "node:crypto";
@@ -1,8 +1,8 @@
1
- import { fromRoot, reachedProjects } from "./types/projects.mjs";
1
+ import { reachedProjects, vitePlusAt } from "./types/projects.mjs";
2
2
  import { execFile } from "node:child_process";
3
3
  import { execPath } from "node:process";
4
4
  import { promisify } from "node:util";
5
- import { dirname, join } from "node:path";
5
+ import { join } from "node:path";
6
6
  // src/type-coverage.ts
7
7
  /**
8
8
  * Fails when a tracked TypeScript file is in no project the root `tsconfig.json` reaches, or when
@@ -25,9 +25,8 @@ const run = promisify(execFile);
25
25
  const generated = /\.gen\.(?:d\.)?ts$/u;
26
26
  /** The files lint reads in the workspace at `root`, by path from it. */
27
27
  const lintedFiles = async (root) => {
28
- const vp = join(dirname(fromRoot(root, "vite-plus/package.json")), "bin/vp");
29
28
  const { stdout } = await run(execPath, [
30
- vp,
29
+ vitePlusAt(root),
31
30
  "lint",
32
31
  "--debug=files"
33
32
  ], {
@@ -1,10 +1,10 @@
1
1
  import { manifestInputs, sha256, workspaceFiles } from "./inputs.mjs";
2
2
  import { env } from "node:process";
3
+ import { homedir } from "node:os";
3
4
  import { isAbsolute, join, relative, resolve } from "node:path";
4
5
  import { Option, Schema } from "effect";
5
6
  import { randomBytes } from "node:crypto";
6
7
  import { mkdir, readFile, readdir, rename, stat, unlink, utimes, writeFile } from "node:fs/promises";
7
- import { homedir } from "node:os";
8
8
  // src/types/cache.ts
9
9
  /**
10
10
  * Each project's type check results, kept for every worktree on the machine in one folder,
@@ -16,6 +16,8 @@ const run = promisify(execFile);
16
16
  * tools a check runs are the repo's, at the versions it pins, and this package's peers.
17
17
  */
18
18
  const fromRoot = (root, specifier) => createRequire(join(root, "package.json")).resolve(specifier);
19
+ /** The repo's own `vp`, the Vite+ it pins, run with Node's `execPath`. */
20
+ const vitePlusAt = (root) => join(dirname(fromRoot(root, "vite-plus/package.json")), "bin/vp");
19
21
  /** A project's config as TypeScript resolves it: the files it includes, and its references. */
20
22
  const decodeConfig = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Struct({
21
23
  files: Schema.optionalKey(Schema.Array(Schema.String)),
@@ -62,4 +64,4 @@ const reachedProjects = async (root, config) => {
62
64
  }
63
65
  return projects;
64
66
  };
65
- export { fromRoot, reachedProjects };
67
+ export { fromRoot, reachedProjects, vitePlusAt };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ref0/workspace",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "The lint and workspace checks every ref-0 repo shares",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -34,7 +34,8 @@
34
34
  "access": "public"
35
35
  },
36
36
  "dependencies": {
37
- "effect": "4.1.4"
37
+ "effect": "4.1.4",
38
+ "git-cliff": "2.14.2"
38
39
  },
39
40
  "devDependencies": {
40
41
  "@effect/tsgo": "0.70.0",