@r_masseater/msch 0.129.4 → 0.130.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.
@@ -1,869 +0,0 @@
1
- import { Array, Effect, Layer, ManagedRuntime, Option, Record, String as String$1, pipe } from "effect";
2
- import { a as textlintFilters, f as requiredStack, g as decisionTestRules, i as zennMarkdown, o as textlintPresets, p as lint$1, r as markdownOf, s as structureOf, x as exempt } from "./define-lint-preset-PLWK5HYf.mjs";
3
- import { recommended } from "@r_masseater/fu4/presets";
4
- import { definePlugin, defineRule } from "@r_masseater/fu4";
5
- import { NOOP, actionOf, keysOf, pairsOf, runOf, valueAt, workflowRule } from "@r_masseater/fu4/rules";
6
- import { a as nodeServicesLayer, i as nodeRepositoryFiles, r as RepositoryFiles, s as groupOf } from "./repository-files-C_GzAnYp.mjs";
7
- import { c as TASK_NAMES, i as workspaceProjects } from "./workspace-projects-eapoa0az.mjs";
8
- import { fileURLToPath } from "node:url";
9
- import { RuleConfigSeverity } from "@commitlint/types";
10
- import { RUNTIME_SECTIONS } from "@r_masseater/masseater-utils/kestrion";
11
- import { i as USAGE_SPOOL } from "./config-B3SYjao5.mjs";
12
- import manifest from "@r_masseater/mdlct/package.json" with { type: "json" };
13
- import { betterleaks } from "@r_masseater/h56m/presets";
14
- // src/entities/workspace/model/workspace-names.ts
15
- const ALTERNATIVE = "|";
16
- const SCOPE = /^@[^/]+\//u;
17
- const SPECIAL = /[$()*+.?[\\\]^{|}]/gu;
18
- /** @internal */
19
- const patternOf = (names) => {
20
- const alternatives = pipe(names, Array.map(String$1.replaceAll(SPECIAL, String.raw`\$&`)));
21
- return new RegExp(`(?<![\\p{L}\\p{N}_-])(?:${Array.join(alternatives, ALTERNATIVE)})(?![\\p{L}\\p{N}_-])`, "gu");
22
- };
23
- const namedIn = (basename) => ({ directory, packageName }) => {
24
- const unscoped = pipe(packageName, Option.map(String$1.replace(SCOPE, "")));
25
- return {
26
- directory,
27
- names: pipe([
28
- Option.some(directory),
29
- Option.some(basename(directory)),
30
- packageName,
31
- unscoped
32
- ], Array.getSomes, Array.dedupe),
33
- packageName
34
- };
35
- };
36
- /** @internal */
37
- const namedWorkspaces = Effect.fn("namedWorkspaces")(function* namedWorkspaces(root) {
38
- const files = yield* RepositoryFiles;
39
- const projects = yield* workspaceProjects(root);
40
- return pipe(projects, Array.map(namedIn((directory) => files.basename(directory))));
41
- });
42
- // src/shared/lib/path-existence.ts
43
- const WILDCARD = /[*?[]/u;
44
- const SEPARATOR$3 = "/";
45
- const FIRST = 0;
46
- /** @internal */
47
- const existsAt = Effect.fn("existsAt")(function* existsAt(root, path) {
48
- const files = yield* RepositoryFiles;
49
- return yield* files.exists(files.join(root, path));
50
- });
51
- /** @internal */
52
- const isDirectoryAt = Effect.fn("isDirectoryAt")(function* isDirectoryAt(root, path) {
53
- const files = yield* RepositoryFiles;
54
- const directory = yield* files.isDirectory(files.join(root, path));
55
- return Option.getOrElse(directory, () => false);
56
- });
57
- /** @internal */
58
- const staticPrefix = (path) => {
59
- const prefix = Array.headNonEmpty(String$1.split(path, WILDCARD));
60
- if (String$1.endsWith(SEPARATOR$3)(prefix)) return String$1.slice(FIRST, -1)(prefix);
61
- return prefix;
62
- };
63
- /** @internal */
64
- const isIgnored = Effect.fn("isIgnored")(function* isIgnored(root, path) {
65
- const prefix = staticPrefix(path);
66
- if (String$1.isEmpty(prefix)) return false;
67
- const ignored = yield* (yield* RepositoryFiles).ignoredPaths(root, [prefix, `${prefix}${SEPARATOR$3}`]);
68
- return Array.isReadonlyArrayNonEmpty(ignored);
69
- });
70
- // src/features/guard-workflows/model/yaml.ts
71
- const rootOf = ({ source }) => Option.fromNullishOr(source.yaml);
72
- const stringOf = (node) => pipe(node, Option.filter(({ kind }) => kind === "scalar"), Option.map(({ value, line, column }) => ({
73
- text: value,
74
- line,
75
- column
76
- })));
77
- const childOf = (key) => (node) => pipe(node, Option.flatMap(valueAt(key)));
78
- const keyNodeOf = (key) => (node) => pipe(node, Option.flatMap((mapping) => pipe(pairsOf(mapping), Array.findFirst((pair) => pair.key.value === key), Option.map((pair) => pair.key))));
79
- const itemsOf = (node) => pipe(node, Option.filter(({ kind }) => kind === "sequence"), Option.map(({ children }) => children), Option.getOrElse(() => []));
80
- const entriesOf = (node) => pipe(node, Option.map(pairsOf), Option.getOrElse(() => []), Array.map((pair) => [pair.key.value, pair.value]));
81
- const scalarsIn = (node) => {
82
- if (node.kind === "scalar") return [{
83
- text: node.value,
84
- line: node.line,
85
- column: node.column
86
- }];
87
- return pipe(node.children, Array.flatMap((child) => scalarsIn(child)));
88
- };
89
- const ownValuesNamed = (name, node) => {
90
- if (node.kind !== "mapping") return [];
91
- return pipe(pairsOf(node), Array.filter((pair) => pair.key.value === name), Array.map((pair) => pair.value));
92
- };
93
- const valuesNamed = (name) => (node) => [...ownValuesNamed(name, node), ...pipe(node.children, Array.flatMap(valuesNamed(name)))];
94
- const descend = (...keys) => (node) => {
95
- let found = node;
96
- for (const key of keys) found = pipe(found, childOf(key));
97
- return found;
98
- };
99
- // src/features/guard-workflows/model/publish-trigger.ts
100
- const PUBLISH = /\bmsch\s+publish\s+(?:plan|npm|release)\b/u;
101
- const MANUAL = "workflow_dispatch";
102
- const TRIGGER_KEY = "on";
103
- const MESSAGE$5 = "publishes with `msch publish plan`, `npm` or `release` from a trigger other than `workflow_dispatch`. Keep those steps in a workflow that only `workflow_dispatch` starts, and start it on a push to main with `msch publish dispatch`.";
104
- const triggersOf = (node) => {
105
- if (node.kind === "scalar") return [node.value];
106
- if (node.kind === "sequence") return pipe(node.children, Array.map(({ value }) => value));
107
- return keysOf(node);
108
- };
109
- /** @internal */
110
- const publishTrigger = workflowRule({
111
- description: "Reports msch publish steps in a workflow that something other than workflow_dispatch starts",
112
- visitor: (fail, context) => {
113
- const publishing = [];
114
- return {
115
- ...NOOP,
116
- step: (step) => {
117
- if (pipe(runOf(step), Option.flatMap(({ run }) => Option.fromNullishOr(run)), Option.exists(({ value }) => PUBLISH.test(value)))) publishing.push(MANUAL);
118
- },
119
- workflowPost: () => {
120
- const root = rootOf(context);
121
- const triggers = pipe(childOf(TRIGGER_KEY)(root), Option.map(triggersOf), Option.getOrElse(() => []));
122
- const manualOnly = pipe(triggers, Array.every((trigger) => trigger === MANUAL));
123
- if (Array.isReadonlyArrayNonEmpty(publishing) && !manualOnly) for (const key of pipe(root, keyNodeOf(TRIGGER_KEY), Option.toArray)) fail(key, MESSAGE$5);
124
- }
125
- };
126
- }
127
- });
128
- // src/features/guard-workflows/model/release-please.ts
129
- const RELEASE_PLEASE = /^googleapis\/release-please-action(?:@|$)/u;
130
- const MESSAGE$4 = "releases with release-please. Releases are manual: bump the version in a PR, then run the publish workflow, which runs `msch publish` for the workspace.";
131
- /** @internal */
132
- const releasePlease = workflowRule({
133
- description: "Reports the release-please action, because releases here are manual",
134
- visitor: (fail) => ({
135
- ...NOOP,
136
- step: (step) => {
137
- const uses = pipe(actionOf(step), Option.flatMap(({ uses: text }) => Option.fromNullishOr(text)), Option.filter(({ value }) => RELEASE_PLEASE.test(value)), Option.toArray);
138
- for (const found of uses) fail(found, MESSAGE$4);
139
- }
140
- })
141
- });
142
- // src/features/guard-workflows/model/workflow-commit.ts
143
- const GIT_WRITE = /\bgit\s+(?:-{1,2}\S+\s+(?:\S+\s+)?)*(?:commit|push)\b/u;
144
- const COMMIT_ACTION = /^[^@/]+\/[^@]*(?:commit|push)[^@]*(?:@|$)/iu;
145
- const MESSAGE$3 = "commits or pushes from a workflow. A bot commit leaves generated files out of review and races the next push. Regenerate the files in a commit hook (for example `.vite-hooks/pre-commit`) so they land in the author's commit, and let CI only check that they are current.";
146
- /** @internal */
147
- const workflowCommit = workflowRule({
148
- description: "Reports git commit, git push and commit actions in a workflow",
149
- visitor: (fail) => ({
150
- ...NOOP,
151
- step: (step) => {
152
- const writes = pipe(runOf(step), Option.flatMap((exec) => {
153
- const position = Option.orElse(Option.fromNullishOr(exec.runPosition), () => Option.fromNullishOr(exec.run));
154
- return Option.fromNullishOr(exec.run).pipe(Option.filter(({ value }) => GIT_WRITE.test(value)), Option.zipRight(position));
155
- }));
156
- const commits = pipe(actionOf(step), Option.flatMap(({ uses }) => Option.fromNullishOr(uses)), Option.filter(({ value }) => COMMIT_ACTION.test(value)));
157
- const flagged = writes.pipe(Option.orElse(() => commits), Option.toArray);
158
- for (const found of flagged) fail(found, MESSAGE$3);
159
- }
160
- })
161
- });
162
- // src/features/guard-workflows/model/repository-services.ts
163
- const runtime = nodeRepositoryFiles.pipe(Layer.provide(nodeServicesLayer), ManagedRuntime.make);
164
- /** @internal */
165
- const inRepository = (effect) => Effect.promise(() => runtime.runPromise(effect));
166
- // src/features/guard-workflows/model/workflow-references.ts
167
- const ROOT = ".";
168
- const LOCAL = "./";
169
- const NEGATION = "!";
170
- const SEPARATOR$2 = "/";
171
- const LINE = "\n";
172
- const UNRESOLVED_MARKERS = [
173
- "${{",
174
- "$",
175
- "{"
176
- ];
177
- const ABSOLUTE_MARKERS = ["/", "~"];
178
- const FILE_INPUT_SUFFIX = "-file";
179
- const DEPENDENCY_PATH_INPUT = "cache-dependency-path";
180
- const FILTER_KEYS$1 = ["paths", "paths-ignore"];
181
- const HASH_FILES = /hashFiles\((?<arguments>[^)]*)\)/gu;
182
- const QUOTED$1 = /'(?<path>[^']*)'/gu;
183
- const SCRIPT = /^[\w.@/-]+\.(?:ts|mts|cts|sh)$/u;
184
- const TOKEN_SEPARATOR = /[\s;&|()<>"'`=]+/u;
185
- const ACTION_DEFINITIONS = ["action.yml", "action.yaml"];
186
- const containsAny = (markers) => (path) => pipe(markers, Array.some((marker) => String$1.includes(marker)(path)));
187
- const startsWithAny = (markers) => (path) => pipe(markers, Array.some((marker) => String$1.startsWith(marker)(path)));
188
- const isLiteralPath = (path) => String$1.isNonEmpty(path) && !containsAny(UNRESOLVED_MARKERS)(path) && !startsWithAny(ABSOLUTE_MARKERS)(path);
189
- const withoutLocal = (path) => {
190
- if (String$1.startsWith(LOCAL)(path)) return String$1.slice(2)(path);
191
- return path;
192
- };
193
- const joinPath = (base, path) => {
194
- const relative = withoutLocal(String$1.trim(path));
195
- if (base === ROOT) return relative;
196
- return `${base}${SEPARATOR$2}${relative}`;
197
- };
198
- const reference = (kind, field, base = ROOT) => ({ text, line, column }) => {
199
- const path = String$1.trim(text);
200
- if (!isLiteralPath(path) || !isLiteralPath(base)) return [];
201
- return [{
202
- kind,
203
- field,
204
- path: joinPath(base, path),
205
- text,
206
- line,
207
- column
208
- }];
209
- };
210
- const isPositive = ({ text }) => !String$1.startsWith(NEGATION)(String$1.trim(text));
211
- const globsIn = (field, node) => pipe(itemsOf(node), Array.flatMap((item) => pipe(item, Option.some, stringOf, Option.toArray)), Array.filter(isPositive), Array.flatMap(reference("glob", field)));
212
- const filtersOf$1 = ([event, filters]) => pipe(FILTER_KEYS$1, Array.flatMap((key) => globsIn(`on.${event}.${key}`, pipe(filters, Option.some, childOf(key)))));
213
- const workingDirectoryOf = (owner) => pipe(owner, descend("defaults", "run", "working-directory"), stringOf);
214
- const directoryOf = (found, base) => pipe(found, Option.map(({ text }) => joinPath(ROOT, text)), Option.getOrElse(() => base));
215
- const located = (kind, field, base = ROOT) => (found) => pipe(found, Option.toArray, Array.flatMap(reference(kind, field, base)));
216
- const localUses = (node) => pipe(node, childOf("uses"), stringOf, Option.filter(({ text }) => String$1.startsWith(LOCAL)(text)));
217
- const scriptsIn = (field, base) => ({ text, line, column }) => pipe(String$1.split(text, TOKEN_SEPARATOR), Array.filter((token) => SCRIPT.test(token)), Array.dedupe, Array.flatMap((token) => pipe({
218
- text: token,
219
- line,
220
- column
221
- }, reference("script", field, base))));
222
- const isFileInput = ([key]) => String$1.endsWith(FILE_INPUT_SUFFIX)(key) || key === DEPENDENCY_PATH_INPUT;
223
- const linesOf = ({ text, line, column }) => pipe(String$1.split(text, LINE), Array.map((each) => ({
224
- text: each,
225
- line,
226
- column
227
- })));
228
- const fileInputOf = (field) => ([key, value]) => pipe(value, Option.some, stringOf, Option.toArray, Array.flatMap(linesOf), Array.flatMap(reference("glob", `${field}.with.${key}`)));
229
- const fileInputsIn = (field, step) => pipe(step, Option.some, childOf("with"), entriesOf, Array.filter(isFileInput), Array.flatMap(fileInputOf(field)));
230
- const scriptReferencesOf = (field, directory, step) => pipe(step, Option.some, childOf("run"), stringOf, Option.toArray, Array.flatMap(scriptsIn(`${field}.run`, directory)));
231
- const stepReferences = (job, base) => (step, index) => {
232
- const field = `jobs.${job}.steps[${index}]`;
233
- const own = pipe(step, Option.some, childOf("working-directory"), stringOf);
234
- const directory = directoryOf(own, base);
235
- return [
236
- ...pipe(step, Option.some, localUses, located("action", `${field}.uses`)),
237
- ...pipe(own, located("directory", `${field}.working-directory`)),
238
- ...scriptReferencesOf(field, directory, step),
239
- ...fileInputsIn(field, step)
240
- ];
241
- };
242
- const jobReferences = (base) => ([job, node]) => {
243
- const own = pipe(node, Option.some, workingDirectoryOf);
244
- const steps = pipe(node, Option.some, childOf("steps"), itemsOf);
245
- const directory = directoryOf(own, base);
246
- return [
247
- ...pipe(node, Option.some, localUses, located("file", `jobs.${job}.uses`)),
248
- ...pipe(own, located("directory", `jobs.${job}.defaults.run.working-directory`)),
249
- ...pipe(steps, Array.flatMap(stepReferences(job, directory)))
250
- ];
251
- };
252
- const groupsOf = (pattern, group) => ({ text, line, column }) => pipe(Array.fromIterable(String$1.matchAll(pattern)(text)), Array.flatMap((match) => pipe(Option.fromNullishOr(match.groups), Option.flatMap((groups) => Option.fromNullishOr(groups[group])), Option.toArray)), Array.map((value) => ({
253
- text: value,
254
- line,
255
- column
256
- })));
257
- const hashFilesIn = (root) => pipe(scalarsIn(root), Array.flatMap(groupsOf(HASH_FILES, "arguments")), Array.flatMap(groupsOf(QUOTED$1, "path")), Array.filter(isPositive), Array.flatMap(reference("glob", "hashFiles")));
258
- const jobsOf = (root) => pipe(root, Option.some, childOf("jobs"), entriesOf);
259
- /** @internal */
260
- const workflowReferences = (root) => {
261
- const workflowDefault = pipe(root, Option.some, workingDirectoryOf);
262
- const base = directoryOf(workflowDefault, ROOT);
263
- return [
264
- ...pipe(root, Option.some, childOf("on"), entriesOf, Array.flatMap(filtersOf$1)),
265
- ...pipe(workflowDefault, located("directory", "defaults.run.working-directory")),
266
- ...pipe(jobsOf(root), Array.flatMap(jobReferences(base))),
267
- ...hashFilesIn(root)
268
- ];
269
- };
270
- const outputPathsOf = (step) => pipe(step, Option.some, descend("with", "path"), stringOf, Option.toArray, Array.flatMap(linesOf), Array.map(({ text }) => joinPath(ROOT, text)), Array.filter(isLiteralPath));
271
- /** @internal */
272
- const producedPaths = (root) => pipe(jobsOf(root), Array.flatMap(([, job]) => pipe(job, Option.some, childOf("steps"), itemsOf)), Array.flatMap(outputPathsOf));
273
- // src/features/guard-workflows/model/workflow-package.ts
274
- const WORKFLOW = /(?:^|\/)\.github\/workflows\/(?<name>[^/]+)\.ya?ml$/u;
275
- const ACTION = /(?:^|\/)\.github\/actions\/(?<name>[^/]+)\/action\.ya?ml$/u;
276
- const PACKAGE_FILTER = /(?:^|\s)(?:--filter|-F)(?:\s+|=)(?<quote>["']?)(?<value>[^\s"'$][^\s"']*)\k<quote>/gu;
277
- const SEPARATOR$1 = "/";
278
- const WORD_SEPARATORS = /[-_]/gu;
279
- const SPACE = " ";
280
- const FIRST_LINE = {
281
- text: "",
282
- line: 1,
283
- column: 1
284
- };
285
- const packageMessage = (what, directory) => `${what} names the workspace ${directory}. A workflow or job made for one package does not scale: give the package a vp task and let the generic pipeline (verify, deploy, release, daily, task) find it.`;
286
- const matching = (workspaces, text) => pipe(workspaces, Array.findFirst(({ names }) => Array.isReadonlyArrayNonEmpty(names) && Option.isSome(String$1.match(patternOf(names))(text))), Option.map(({ directory }) => directory));
287
- const named = (workspaces, text) => Option.orElse(matching(workspaces, text), () => matching(workspaces, String$1.replaceAll(WORD_SEPARATORS, SPACE)(text)));
288
- const containing = (workspaces, path) => pipe(workspaces, Array.findFirst(({ directory }) => path === directory || String$1.startsWith(`${directory}${SEPARATOR$1}`)(path)), Option.map(({ directory }) => directory));
289
- const filtersIn = (scalars) => pipe(scalars, Array.flatMap(({ text, line, column }) => pipe(Array.fromIterable(String$1.matchAll(PACKAGE_FILTER)(text)), Array.flatMap((match) => pipe(Option.fromNullishOr(match.groups), Option.flatMap((groups) => Option.fromNullishOr(groups["value"])), Option.toArray)), Array.map((value) => ({
290
- text: value,
291
- line,
292
- column
293
- })))));
294
- const findingFor = (what, found, directory) => pipe(directory, Option.map((workspace) => ({
295
- line: found.line,
296
- column: found.column,
297
- message: packageMessage(what, workspace)
298
- })), Option.toArray);
299
- const namesIn = (stem, root) => [
300
- {
301
- ...FIRST_LINE,
302
- text: stem
303
- },
304
- ...pipe(root, childOf("name"), stringOf, Option.toArray),
305
- ...pipe(root, childOf("jobs"), Option.map((jobs) => pipe(pairsOf(jobs), Array.map(({ key }) => ({
306
- text: key.value,
307
- line: key.line,
308
- column: key.column
309
- })))), Option.getOrElse(() => []))
310
- ];
311
- const workflowFindings = (workspaces, stem, root) => {
312
- const fromNames = pipe(namesIn(stem, Option.some(root)), Array.flatMap((found) => findingFor(`"${found.text}"`, found, named(workspaces, found.text))));
313
- const referenced = pipe(workflowReferences(root), Array.filter(({ field }) => !String$1.startsWith("on.")(field)), Array.flatMap((found) => findingFor(found.field, found, containing(workspaces, found.path))));
314
- const filtered = pipe(filtersIn(scalarsIn(root)), Array.flatMap((found) => findingFor(`--filter ${found.text}`, found, matching(workspaces, found.text))));
315
- return [
316
- ...fromNames,
317
- ...referenced,
318
- ...filtered
319
- ];
320
- };
321
- const workflowPackage = defineRule({
322
- meta: {
323
- description: "Reports workflows, jobs, actions and paths that are made for one workspace",
324
- kinds: ["workflow", "action"]
325
- },
326
- check: ({ filename, project, source, report }) => Effect.gen(function* checkPackages() {
327
- const workspaces = yield* namedWorkspaces(project.root);
328
- const asWorkflow = groupOf("name")(WORKFLOW.exec(filename));
329
- const asAction = groupOf("name")(ACTION.exec(filename));
330
- const found = [...pipe(asAction, Option.flatMap((name) => named(workspaces, name)), Option.map((directory) => ({
331
- ...FIRST_LINE,
332
- message: packageMessage(`The action ${Option.getOrElse(asAction, () => "")}`, directory)
333
- })), Option.toArray), ...pipe(Option.all([asWorkflow, Option.fromNullishOr(source.yaml)]), Option.map(([stem, root]) => workflowFindings(workspaces, stem, root)), Option.getOrElse(() => []))];
334
- for (const each of found) report(each);
335
- }).pipe(inRepository)
336
- });
337
- // src/features/guard-workflows/model/workflow-path-filter.ts
338
- const FILTER_KEYS = ["paths", "paths-ignore"];
339
- const PATHS_FILTER_ACTION = /(?:^|\/)paths-filter@/u;
340
- const MESSAGE$2 = "A workflow that reacts to changes under listed paths needs a new entry for every package and drifts from the packages it is meant to cover. Run the generic pipeline on every push and let it decide from the workspace what changed.";
341
- /** @internal */
342
- const workflowPathFilter = defineRule({
343
- meta: {
344
- description: "Reports paths and paths-ignore triggers and the paths-filter action",
345
- kinds: ["workflow"]
346
- },
347
- check: (context) => {
348
- const root = rootOf(context);
349
- const triggers = pipe(root, childOf("on"), entriesOf, Array.flatMap(([, trigger]) => pipe(FILTER_KEYS, Array.flatMap((key) => pipe(Option.some(trigger), keyNodeOf(key), Option.toArray)))));
350
- const actions = pipe(Option.toArray(root), Array.flatMap((node) => scalarsIn(node)), Array.filter(({ text }) => PATHS_FILTER_ACTION.test(text)));
351
- for (const found of [...triggers, ...actions]) context.report({
352
- line: found.line,
353
- column: found.column,
354
- message: MESSAGE$2
355
- });
356
- }
357
- });
358
- // src/features/guard-workflows/model/workflow-path.ts
359
- const SEPARATOR = "/";
360
- const EXPECTED = {
361
- action: "a directory with action.yml",
362
- directory: "a directory",
363
- file: "a file",
364
- glob: "a pattern that matches a tracked file",
365
- script: "a file"
366
- };
367
- const matchesAny = Effect.fn("matchesAny")(function* matchesAny(root, pathspecs) {
368
- const matched = yield* (yield* RepositoryFiles).matchingFiles(root, pathspecs);
369
- return Array.isReadonlyArrayNonEmpty(matched);
370
- });
371
- const matchesGlob = (root, path) => matchesAny(root, [`:(glob)${path}`]);
372
- const hasAction = Effect.fn("hasAction")(function* hasAction(root, path) {
373
- const found = yield* Effect.forEach(ACTION_DEFINITIONS, (name) => existsAt(root, `${path}${SEPARATOR}${name}`), { concurrency: 1 });
374
- return pipe(found, Array.some(Boolean));
375
- });
376
- const suffixAt = (segments) => (index) => `:(glob)**/${pipe(segments, Array.drop(index), Array.join(SEPARATOR))}`;
377
- const RESOLVERS = {
378
- action: hasAction,
379
- directory: isDirectoryAt,
380
- file: existsAt,
381
- glob: matchesGlob,
382
- script: Effect.fn("findsScript")(function* findsScript(root, path) {
383
- if (yield* existsAt(root, path)) return true;
384
- const segments = String$1.split(path, SEPARATOR);
385
- return yield* matchesAny(root, Array.makeBy(segments.length, suffixAt(segments)));
386
- })
387
- };
388
- const overlaps = (path) => (produced) => produced === path || String$1.startsWith(`${path}${SEPARATOR}`)(produced) || String$1.startsWith(`${produced}${SEPARATOR}`)(path);
389
- const isMissing = Effect.fn("isMissing")(function* isMissing(root, produced, found) {
390
- const prefix = staticPrefix(found.path);
391
- if (pipe(produced, Array.some(overlaps(prefix)))) return false;
392
- if (yield* RESOLVERS[found.kind](root, found.path)) return false;
393
- return !(yield* isIgnored(root, found.path));
394
- });
395
- const workflowPath = defineRule({
396
- meta: {
397
- description: "Reports a path that a workflow names and the repository does not have",
398
- kinds: ["workflow"]
399
- },
400
- check: ({ project, source, report }) => Effect.gen(function* checkPaths() {
401
- for (const yaml of Option.toArray(Option.fromNullishOr(source.yaml))) {
402
- const produced = producedPaths(yaml);
403
- const missing = yield* Effect.filter(workflowReferences(yaml), (found) => isMissing(project.root, produced, found));
404
- for (const found of missing) report({
405
- line: found.line,
406
- column: found.column,
407
- message: `${found.field} names ${found.path}, which is not ${EXPECTED[found.kind]} in this repository. Point it at a path that exists or remove it.`
408
- });
409
- }
410
- }).pipe(inRepository)
411
- });
412
- // src/features/guard-workflows/model/workflow-queue.ts
413
- const CONCURRENCY_KEY = "concurrency";
414
- const QUEUE_KEY = "queue";
415
- const MESSAGE$1 = "queues runs with `queue`. A queued group runs every old push one by one, so a long run holds back the newest commit for hours. Drop `queue`: a job that later pushes redo gets `cancel-in-progress: true`, and a deploy or release job keeps the default, which lets the running one finish and replaces the waiting one with the newest run.";
416
- /** @internal */
417
- const workflowQueue = defineRule({
418
- meta: {
419
- description: "Reports queue on a concurrency group, because a queued group holds back the newest commit",
420
- kinds: ["workflow"]
421
- },
422
- check: (context) => {
423
- const keys = pipe(rootOf(context), Option.toArray, Array.flatMap((root) => valuesNamed(CONCURRENCY_KEY)(root)), Array.filter((group) => Array.contains(keysOf(group), QUEUE_KEY)), Array.flatMap((group) => pipe(Option.some(group), keyNodeOf(QUEUE_KEY), Option.toArray)));
424
- for (const key of keys) context.report({
425
- line: key.line,
426
- column: key.column,
427
- message: MESSAGE$1
428
- });
429
- }
430
- });
431
- // src/features/guard-workflows/model/workflow-script.ts
432
- const COMMAND_CHAIN = /&&|\|\||;|\|/u;
433
- const QUOTED = /\$\{\{.*?\}\}|"(?:[^"\\]|\\.)*"|'[^']*'/gu;
434
- const COMMENT = "#";
435
- const ONE_COMMAND = 1;
436
- const MESSAGE = "runs more than one command. Keep a step to one command, `vp run <task>` or `vp exec <bin>`, and put the logic in a Vite+ task in TypeScript.";
437
- const isCommand = (line) => String$1.isNonEmpty(line) && !String$1.startsWith(COMMENT)(line);
438
- const chainsCommands = (line) => COMMAND_CHAIN.test(String$1.replaceAll(QUOTED, "")(line));
439
- const runsMoreThanOneCommand = (text) => {
440
- const lines = pipe(String$1.split("\n")(text), Array.map(String$1.trim), Array.filter(isCommand));
441
- return lines.length > ONE_COMMAND || pipe(lines, Array.some(chainsCommands));
442
- };
443
- /** @internal */
444
- const workflowScript = workflowRule({
445
- description: "Reports a run step with more than one command, because the logic belongs in a task",
446
- visitor: (fail) => ({
447
- ...NOOP,
448
- step: (step) => {
449
- const runs = pipe(runOf(step), Option.flatMap(({ run }) => Option.fromNullishOr(run)), Option.filter(({ value }) => runsMoreThanOneCommand(value)), Option.toArray);
450
- for (const found of runs) fail(found, MESSAGE);
451
- }
452
- })
453
- });
454
- // src/features/guard-workflows/model/policy.ts
455
- const NAME = "msch";
456
- const plugin = definePlugin({ rules: {
457
- "publish-trigger": publishTrigger,
458
- "release-please": releasePlease,
459
- "workflow-commit": workflowCommit,
460
- "workflow-package": workflowPackage,
461
- "workflow-path": workflowPath,
462
- "workflow-path-filter": workflowPathFilter,
463
- "workflow-queue": workflowQueue,
464
- "workflow-script": workflowScript
465
- } });
466
- /** @internal */
467
- const workflowPolicy = () => ({
468
- plugins: Record.singleton(NAME, plugin),
469
- rules: pipe(Record.keys(plugin.rules), Array.map((rule) => [`${NAME}/${rule}`, "error"]), Record.fromEntries)
470
- });
471
- // src/features/guard-workflows/model/fu4-config.ts
472
- /** @internal */
473
- const fu4Of = () => ({ extends: [recommended(), workflowPolicy()] });
474
- const COMMIT_LINT = { extends: [fileURLToPath(import.meta.resolve("@commitlint/config-conventional"))] };
475
- const SUBJECT_SCRIPT = "subject-script";
476
- const commitlintOf = (commit) => pipe(Option.fromUndefinedOr(commit), Option.match({
477
- onNone: () => COMMIT_LINT,
478
- onSome: ({ subjectScripts }) => ({
479
- ...COMMIT_LINT,
480
- rules: { [SUBJECT_SCRIPT]: [
481
- RuleConfigSeverity.Error,
482
- "always",
483
- [...subjectScripts]
484
- ] }
485
- })
486
- }));
487
- // src/app/repository-dependencies.ts
488
- const allowedIn = (allowances, fields) => pipe(allowances, Record.map(({ workspaces, dependencies }) => ({
489
- workspaces,
490
- dependencies,
491
- fields: [...fields]
492
- })));
493
- const PLUGIN_DEPENDENCIES = "Claude Code installs a plugin's dependencies from its own package.json and lockfile, where only exact registry versions install";
494
- const dependencyRulesOf = (workspace) => ({
495
- allowed: {
496
- ...allowedIn(workspace.devDependencies, ["devDependencies"]),
497
- ...allowedIn(workspace.dependencies, RUNTIME_SECTIONS)
498
- },
499
- banned: requiredStack,
500
- exactDependencies: { [PLUGIN_DEPENDENCIES]: workspace.plugins },
501
- peerRanges: "intersect"
502
- });
503
- // src/shared/lib/mdlct.ts
504
- /** @internal */
505
- const MDLCT_BIN = fileURLToPath(new URL(manifest.bin.mdlct, import.meta.resolve("@r_masseater/mdlct/package.json")));
506
- // src/app/repository-tasks.ts
507
- const NOT_INPUTS = [
508
- "!node_modules/.pnpm-store",
509
- "!node_modules/.pnpm-store/**",
510
- "!node_modules/.tmp",
511
- "!node_modules/.tmp/**",
512
- "!target/**",
513
- "!node_modules/.vitest-cache/**",
514
- "!node_modules/.cache/**"
515
- ];
516
- const UNTRACKED_ENV = [
517
- "CLOUDFLARE_ACCOUNT_ID",
518
- "CLOUDFLARE_AI_GATEWAY_ID",
519
- "CLOUDFLARE_API_TOKEN",
520
- "CLAUDECODE",
521
- "CLAUDE_CODE_REMOTE",
522
- "GITHUB_ACTIONS",
523
- "HTTPS_PROXY",
524
- "https_proxy",
525
- "NO_PROXY",
526
- "no_proxy",
527
- "SSL_CERT_FILE",
528
- "NODE_EXTRA_CA_CERTS"
529
- ];
530
- const FALLOW = pipe([
531
- "--skip dupes --fail-on-issues --quiet --format compact",
532
- "dead-code --no-production --fail-on-issues --quiet --format compact",
533
- "dead-code --no-production --quiet --format json | jq -n 'input | {prop_drilling_chains, thin_wrappers, duplicate_prop_shapes} | with_entries(select(.value | length > 0)) | if length > 0 then halt_error else empty end'",
534
- "dupes --fail-on-issues --quiet --format compact",
535
- "security --fail-on-issues --quiet"
536
- ], Array.map((args) => `FALLOW_TYPE_AWARE_BACKEND=tsrs fallow ${args}`));
537
- const CHECK = `TSRS_LINT_RUN_EXTERNAL_CODE=1 msch changed --batch-sources ${String(1e3)} -- vp check --deny-warnings --continue-on-error --no-error-on-unmatched-pattern`;
538
- const COMPAT = "msch changed -- msch publish compat-changed";
539
- const SKILLS = `node ${MDLCT_BIN} check`;
540
- const AUDIT = Array.join([
541
- "copy=\"$(mktemp -d)\"",
542
- `trap 'rm -rf "$copy"' EXIT`,
543
- `for file in ${Array.join([
544
- "package.json",
545
- "pnpm-workspace.yaml",
546
- "pnpm-lock.yaml",
547
- ".npmrc"
548
- ], " ")}; do if [ -f "$file" ]; then cp "$file" "$copy/"; fi; done`,
549
- "(cd \"$copy\" && vp pm audit --fix >/dev/null) || exit",
550
- `added="$(diff pnpm-workspace.yaml "$copy/pnpm-workspace.yaml" | sed -n 's/^> \\(.*\\)$/\\1 # exit: unused/p')"`,
551
- "if [ -z \"$added\" ]; then exit 0; fi",
552
- `printf '%s\\n' "vp pm audit --fix found vulnerable versions. First update them within their ranges with vp update -r --no-save <package>... -- --depth Infinity. For each one still reported by vp pm audit, add its line to overrides in pnpm-workspace.yaml and run vp install:" "$added" >&2`,
553
- "exit 1"
554
- ], "; ");
555
- const BROKER_TOKEN = `GH_TOKEN="\${GITHUB_APP_TOKEN:-$GH_TOKEN}"`;
556
- const DAILY = `msch exits; ${BROKER_TOKEN} msch upstream; ${BROKER_TOKEN} msch callers; ${BROKER_TOKEN} msch refs; refs=$?; msch agents "\${RUNNER_TEMP:-\${TMPDIR:-/tmp}}/msch-agents" && exit "$refs"`;
557
- const TEST = "msch changed -- vp test run --passWithNoTests";
558
- const CARGO = "cargo fmt --all --check && cargo clippy --workspace --all-targets --locked -- -D warnings";
559
- const cargoTasks = (cargo) => Option.match(cargo, {
560
- onNone: () => ({}),
561
- onSome: (inputs) => ({ cargo: {
562
- command: CARGO,
563
- cache: {
564
- input: [...inputs],
565
- output: [],
566
- untrackedEnv: UNTRACKED_ENV
567
- }
568
- } })
569
- });
570
- const MSCH_VERIFY_COMMANDS = {
571
- fallow: FALLOW,
572
- check: CHECK,
573
- msch: "msch",
574
- audit: AUDIT,
575
- published: "msch published",
576
- compat: COMPAT,
577
- skills: SKILLS
578
- };
579
- const MSCH_TASK_COMMANDS = {
580
- ...MSCH_VERIFY_COMMANDS,
581
- test: TEST
582
- };
583
- const CI_TASKS = [TASK_NAMES.verify, TASK_NAMES.test];
584
- const USAGE_TASK = "usage";
585
- const METERED_TASKS = ["check", "msch"];
586
- const meteredCommand = (command) => `USAGE_METER_SPOOL="$PWD/${USAGE_SPOOL}" ${command}`;
587
- const usageCommandOf = ({ endpoint, apiKeyEnv }) => pipe(Option.fromUndefinedOr(apiKeyEnv), Option.match({
588
- onNone: () => `msch usage --endpoint ${endpoint}`,
589
- onSome: (name) => `msch usage --endpoint ${endpoint} --api-key-env ${name}`
590
- }));
591
- const commandOf = (usage) => (command) => Option.match(usage, {
592
- onNone: () => command,
593
- onSome: () => meteredCommand(command)
594
- });
595
- const usageTasks = (usage) => Option.match(usage, {
596
- onNone: () => ({}),
597
- onSome: (options) => ({ [USAGE_TASK]: {
598
- command: usageCommandOf(options),
599
- dependsOn: [...METERED_TASKS],
600
- cache: false
601
- } })
602
- });
603
- const tasksOf = ({ workspace, commands, usage, cargo }) => {
604
- const inputs = [
605
- { auto: true },
606
- ...workspace.ignoredDirectories,
607
- ...NOT_INPUTS
608
- ];
609
- const run = commandOf(usage);
610
- const checks = {
611
- ...commands,
612
- fallow: {
613
- command: FALLOW,
614
- cache: {
615
- input: [
616
- ...inputs,
617
- "!.fallow/**",
618
- "!**/dist/**",
619
- "!**/.fallow-verified"
620
- ],
621
- output: []
622
- }
623
- },
624
- check: {
625
- command: run(CHECK),
626
- cache: {
627
- input: inputs,
628
- untrackedEnv: UNTRACKED_ENV
629
- }
630
- },
631
- msch: {
632
- command: run(MSCH_VERIFY_COMMANDS.msch),
633
- dependsOn: ["check", ...workspace.tasks.native],
634
- cache: false
635
- },
636
- audit: {
637
- command: AUDIT,
638
- cache: false
639
- },
640
- skills: {
641
- command: SKILLS,
642
- cache: {
643
- input: inputs,
644
- output: []
645
- }
646
- },
647
- published: {
648
- command: MSCH_TASK_COMMANDS.published,
649
- cache: false
650
- },
651
- compat: {
652
- command: COMPAT,
653
- dependsOn: ["msch", "fallow"],
654
- cache: false
655
- },
656
- ...cargoTasks(cargo),
657
- ...usageTasks(usage)
658
- };
659
- return {
660
- ...checks,
661
- test: {
662
- command: TEST,
663
- dependsOn: ["check", ...workspace.tasks.native],
664
- cache: { input: [...inputs, "!**/.cache/**"] }
665
- },
666
- daily: {
667
- command: DAILY,
668
- dependsOn: [...workspace.tasks.native],
669
- cache: false
670
- },
671
- verify: {
672
- command: [],
673
- dependsOn: [...workspace.tasks.verify, ...Record.keys(checks)]
674
- },
675
- ci: {
676
- command: [],
677
- dependsOn: [...CI_TASKS, ...workspace.tasks.test]
678
- }
679
- };
680
- };
681
- const REINSTALL = "vp install";
682
- const GIT_HOOKS = {
683
- "pre-commit": ["vp staged", "vp exec msch --staged"],
684
- "commit-msg": ["vp exec msch --commit-msg \"$1\""],
685
- "pre-push": ["vp exec msch --pre-push", "vp run verify"],
686
- "post-checkout": [`[ "$3" = 0 ] || ${REINSTALL}`],
687
- "post-merge": [REINSTALL],
688
- "post-rewrite": [REINSTALL]
689
- };
690
- const gitHooksOf = (hooks = {}) => ({
691
- ...GIT_HOOKS,
692
- ...hooks
693
- });
694
- // src/app/repository-text.ts
695
- const TEXT_IGNORES = [
696
- "AGENTS.md",
697
- "CLAUDE.md",
698
- ".agents/skills/**",
699
- "CHANGELOG.md",
700
- ...exempt
701
- ];
702
- const ZENN_MARKDOWN = "zenn-markdown";
703
- const QUOTATION = String.raw`/「(?:[^「」]|「[^「」]*」)*」|『(?:[^『』]|『[^『』]*』)*』/`;
704
- const SPEAKER = String.raw`/^:::[\w-]+\n[\s\S]*?\n:::$/m`;
705
- const ELLIPSIS = "…";
706
- const filtersOf = (properNouns) => ({
707
- comments: true,
708
- "node-types": { nodeTypes: ["BlockQuote"] },
709
- allowlist: { allow: [
710
- QUOTATION,
711
- SPEAKER,
712
- ...properNouns
713
- ] }
714
- });
715
- const SENTENCE_LENGTH = 120;
716
- const KANJI_RUN = 6;
717
- const PUBLIC_LINES = [
718
- String.raw`\bCF_BEACON_TOKEN = "[0-9a-f]{32}"`,
719
- String.raw`\b\w*DISCORD_\w*ID = "[0-9]{17,20}"`,
720
- String.raw`untrusted comment: minisign public key: [0-9A-F]{16}`
721
- ];
722
- const EXEMPT_PATHS = [String.raw`(?:^|/)(?:fixtures|upstream|hooks/vendor)/`];
723
- const builtRules = (style) => ({
724
- "@textlint-ja/preset-ai-writing": true,
725
- "@r_masseater/preset-ja": true,
726
- "preset-ja-technical-writing": {
727
- "sentence-length": { max: SENTENCE_LENGTH },
728
- "ja-no-mixed-period": { allowPeriodMarks: [":"] },
729
- "no-mix-dearu-desumasu": {
730
- preferInBody: style,
731
- preferInList: style
732
- },
733
- "max-kanji-continuous-len": { max: KANJI_RUN },
734
- "ja-no-successive-word": { allow: [ELLIPSIS] }
735
- }
736
- });
737
- const builtTextRuleNames = Record.keys(builtRules("である"));
738
- const textlintOf = ({ properNouns = [], rules = {}, sources = [], articles }) => {
739
- const textRules = {
740
- ...rules,
741
- ...builtRules("である")
742
- };
743
- const filters = filtersOf(properNouns);
744
- const articleSources = Array.filter([{
745
- files: [...articles],
746
- plugins: { [ZENN_MARKDOWN]: true },
747
- rules: {
748
- ...rules,
749
- ...builtRules("ですます")
750
- },
751
- filters
752
- }], () => Array.isReadonlyArrayNonEmpty(articles));
753
- return {
754
- ignores: [...TEXT_IGNORES, ...articles],
755
- presets: textlintPresets,
756
- filterModules: textlintFilters,
757
- pluginModules: { [ZENN_MARKDOWN]: zennMarkdown },
758
- reportUnusedDirectives: true,
759
- sources: pipe(sources, Array.map(({ files, plugins }) => ({
760
- files: [...files],
761
- plugins: { ...plugins },
762
- rules: textRules,
763
- filters
764
- })), Array.appendAll(articleSources)),
765
- filters,
766
- rules: textRules
767
- };
768
- };
769
- const anyOf = (subject) => (patterns) => {
770
- if (Array.isReadonlyArrayEmpty(patterns)) return [];
771
- return [`matchesAny(${subject}, [${pipe(patterns, Array.map((pattern) => `\`${pattern}\``), Array.join(", "))}])`];
772
- };
773
- const secretsOf = () => ({
774
- extend: { path: betterleaks },
775
- filter: pipe([...anyOf("finding.line")(PUBLIC_LINES), ...anyOf(`attributes["path"]`)(EXEMPT_PATHS)], Array.join(" || "))
776
- });
777
- // src/app/repository-config.ts
778
- const cacheOf = (remoteCache) => pipe(Option.fromNullishOr(remoteCache), Option.match({
779
- onNone: () => true,
780
- onSome: (url) => ({
781
- scripts: true,
782
- tasks: true,
783
- remote: { url }
784
- })
785
- }));
786
- const STAGED = { "*": "vp fmt --no-error-on-unmatched-pattern" };
787
- const FORMAT = {
788
- ignorePatterns: exempt,
789
- sortImports: true,
790
- sortTailwindcss: true,
791
- sortPackageJson: true
792
- };
793
- const added = ({ files, excludeFiles, rules }) => pipe(Option.fromUndefinedOr(excludeFiles), Option.match({
794
- onNone: () => ({
795
- files: [...files],
796
- rules: { ...rules }
797
- }),
798
- onSome: (excluded) => ({
799
- files: [...files],
800
- excludeFiles: [...excluded],
801
- rules: { ...rules }
802
- })
803
- }));
804
- const lintOf = ({ workspace, overrides = [] }) => ({
805
- ...lint$1,
806
- ignorePatterns: exempt,
807
- overrides: [
808
- ...lint$1.overrides,
809
- {
810
- files: [...workspace.lint.shadcnUi],
811
- rules: { "react/jsx-props-no-spreading": "off" }
812
- },
813
- {
814
- files: [
815
- ...workspace.lint.publicEntries,
816
- ...workspace.lint.deployEntries,
817
- ...workspace.lint.siteEntries
818
- ],
819
- rules: { "import/no-default-export": "off" }
820
- },
821
- ...pipe(overrides, Array.map(added)),
822
- ...workspace.lint.overrides,
823
- {
824
- files: ["**/*.test.ts"],
825
- rules: decisionTestRules
826
- }
827
- ]
828
- });
829
- const repositoryConfig = (options) => {
830
- const { workspace, commit, textlint = {}, markdown = {}, run = {}, usage, cargo, gitHooks } = options;
831
- return {
832
- commitlint: commitlintOf(commit),
833
- dependencyRules: dependencyRulesOf(workspace),
834
- h56m: secretsOf(),
835
- wism: structureOf({
836
- members: workspace.members,
837
- ignorePatterns: exempt
838
- }),
839
- textlint: textlintOf({
840
- ...textlint,
841
- articles: workspace.articles
842
- }),
843
- y8: markdownOf({
844
- ...markdown,
845
- indexSkill: workspace.indexSkill
846
- }),
847
- fu4: fu4Of(),
848
- test: {
849
- projects: [...workspace.testProjects],
850
- passWithNoTests: true
851
- },
852
- staged: STAGED,
853
- gitHooks: gitHooksOf(gitHooks),
854
- fmt: FORMAT,
855
- lint: lintOf(options),
856
- run: {
857
- cache: cacheOf(run.remoteCache),
858
- tasks: tasksOf({
859
- workspace,
860
- commands: run.tasks ?? {},
861
- usage: Option.fromUndefinedOr(usage),
862
- cargo: Option.map(Option.fromUndefinedOr(cargo), ({ inputs }) => inputs)
863
- })
864
- }
865
- };
866
- };
867
- export { existsAt as _, builtTextRuleNames as a, patternOf as b, GIT_HOOKS as c, meteredCommand as d, MDLCT_BIN as f, fu4Of as g, SUBJECT_SCRIPT as h, TEXT_IGNORES as i, MSCH_TASK_COMMANDS as l, COMMIT_LINT as m, STAGED as n, secretsOf as o, PLUGIN_DEPENDENCIES as p, repositoryConfig as r, CI_TASKS as s, FORMAT as t, MSCH_VERIFY_COMMANDS as u, isIgnored as v, namedWorkspaces as y };
868
-
869
- //# sourceMappingURL=repository-config-Dq5OIwyx.mjs.map