@houserules/payload 0.0.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.
@@ -0,0 +1,224 @@
1
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
2
+ import { join, relative } from 'node:path';
3
+ /**
4
+ * Parsed JSON, or null when the file is missing or unparseable. Defaults to
5
+ * `PackageJson` because that is the overwhelming caller; pass `T` for the others.
6
+ */
7
+ export function readJson(path) {
8
+ try {
9
+ return JSON.parse(readFileSync(path, 'utf8'));
10
+ }
11
+ catch {
12
+ return null;
13
+ }
14
+ }
15
+ /** Strip surrounding quotes and a trailing `# comment` from one scalar item. */
16
+ function cleanItem(raw) {
17
+ const unquoted = /^\s*(['"])([\s\S]*?)\1\s*$/.exec(raw.trim());
18
+ if (unquoted)
19
+ return unquoted[2].trim();
20
+ return raw.replace(/#.*$/, '').trim();
21
+ }
22
+ // Split a flow sequence's interior on commas that are not inside quotes, so a glob
23
+ // containing a comma survives quoting.
24
+ function splitFlow(inner) {
25
+ const items = [];
26
+ let current = '';
27
+ let quote = null;
28
+ for (const ch of inner) {
29
+ if (quote) {
30
+ current += ch;
31
+ if (ch === quote)
32
+ quote = null;
33
+ }
34
+ else if (ch === '"' || ch === "'") {
35
+ current += ch;
36
+ quote = ch;
37
+ }
38
+ else if (ch === ',') {
39
+ items.push(current);
40
+ current = '';
41
+ }
42
+ else
43
+ current += ch;
44
+ }
45
+ items.push(current);
46
+ return items.map(cleanItem).filter(Boolean);
47
+ }
48
+ /**
49
+ * Extracts the `packages:` list from pnpm-workspace.yaml. Hand-rolled on purpose: the
50
+ * payload ships into user repos and runs on bare node, so it cannot import a YAML
51
+ * library. This is not a YAML parser. It reads one key in the shapes real workspace files
52
+ * use, and never throws. `__test__/workspaces.test.ts` pins that contract case by case.
53
+ *
54
+ * Sibling top-level blocks such as `catalog:` and `catalogMode:` must not confuse it, so
55
+ * only lines inside the packages block are read and the block ends at the next
56
+ * non-indented line. Both YAML list forms occur in the wild and both are read, block
57
+ * sequences and flow sequences, and a flow sequence may span lines.
58
+ */
59
+ export function parsePnpmWorkspaceGlobs(yamlText) {
60
+ const globs = [];
61
+ let inPackages = false;
62
+ let flow = null;
63
+ for (const raw of yamlText.split('\n')) {
64
+ const line = raw.replace(/\t/g, ' ').replace(/\r$/, '');
65
+ // Mid-flow-sequence: keep accumulating until the closing bracket.
66
+ if (flow !== null) {
67
+ const end = line.indexOf(']');
68
+ flow += end === -1 ? `\n${line}` : `\n${line.slice(0, end)}`;
69
+ if (end === -1)
70
+ continue;
71
+ globs.push(...splitFlow(flow));
72
+ return globs;
73
+ }
74
+ const key = /^packages\s*:(.*)$/.exec(line);
75
+ if (key) {
76
+ inPackages = true;
77
+ const inline = key[1].trim();
78
+ if (!inline.startsWith('['))
79
+ continue; // block sequence follows
80
+ const end = inline.indexOf(']');
81
+ if (end === -1) {
82
+ flow = inline.slice(1); // spans lines — accumulate
83
+ continue;
84
+ }
85
+ globs.push(...splitFlow(inline.slice(1, end)));
86
+ return globs;
87
+ }
88
+ if (!inPackages)
89
+ continue;
90
+ if (/^\S/.test(line))
91
+ break; // next top-level key ends the block
92
+ const item = /^\s*-\s*(.+)$/.exec(line);
93
+ if (item) {
94
+ const value = cleanItem(item[1]);
95
+ if (value)
96
+ globs.push(value);
97
+ }
98
+ }
99
+ return globs;
100
+ }
101
+ function workspaceGlobs(root) {
102
+ const yamlPath = join(root, 'pnpm-workspace.yaml');
103
+ if (existsSync(yamlPath)) {
104
+ try {
105
+ return parsePnpmWorkspaceGlobs(readFileSync(yamlPath, 'utf8'));
106
+ }
107
+ catch {
108
+ return [];
109
+ }
110
+ }
111
+ const ws = readJson(join(root, 'package.json'))?.workspaces;
112
+ if (Array.isArray(ws))
113
+ return ws;
114
+ if (ws && Array.isArray(ws.packages))
115
+ return ws.packages;
116
+ return [];
117
+ }
118
+ // Directories a workspace glob can never mean. Recursing into node_modules would be
119
+ // both wrong (a dependency is not a workspace member) and ruinously slow.
120
+ const SKIP_DIRS = new Set(['node_modules', '.git']);
121
+ function subdirectories(base) {
122
+ try {
123
+ return readdirSync(base, { withFileTypes: true })
124
+ .filter((e) => e.isDirectory() && !SKIP_DIRS.has(e.name))
125
+ .map((e) => join(base, e.name));
126
+ }
127
+ catch (e) {
128
+ // A read failure and a genuinely empty directory both feed workspace detection as a
129
+ // plain array, with no return channel to tell them apart, so the diagnostic goes to
130
+ // stderr rather than looking identical to an empty dir.
131
+ console.error(`houserules: could not read directory ${base}: ${e.message}`);
132
+ return [];
133
+ }
134
+ }
135
+ // Recursion cap for `descendants`. No real workspace nests packages this deep; this guards
136
+ // against a symlink loop or a pathological tree rather than encoding a known layout.
137
+ const MAX_WORKSPACE_DEPTH = 12;
138
+ /** Every directory at or below `base`, excluding `base` itself. Depth-capped. */
139
+ function descendants(base, depth = MAX_WORKSPACE_DEPTH) {
140
+ if (depth <= 0)
141
+ return [];
142
+ return subdirectories(base).flatMap((dir) => [
143
+ dir,
144
+ ...descendants(dir, depth - 1),
145
+ ]);
146
+ }
147
+ // `**` recurses to any depth, so a package under an intermediate directory is found.
148
+ // `*` matches one segment.
149
+ function expandGlob(root, glob) {
150
+ const clean = glob.trim().replace(/\/+$/, '');
151
+ if (!clean || clean.startsWith('!'))
152
+ return [];
153
+ if (clean.endsWith('/**'))
154
+ return descendants(join(root, clean.slice(0, -3)));
155
+ if (clean.endsWith('/*'))
156
+ return subdirectories(join(root, clean.slice(0, -2)));
157
+ const dir = join(root, clean);
158
+ try {
159
+ if (statSync(dir).isDirectory())
160
+ return [dir];
161
+ }
162
+ catch {
163
+ /* not a dir */
164
+ }
165
+ return [];
166
+ }
167
+ // Matches over root-relative, forward-slashed paths. `**` spans separators, `*` does
168
+ // not, and every other character is literal.
169
+ function negationMatcher(glob) {
170
+ const pattern = glob
171
+ .trim()
172
+ .replace(/^!/, '')
173
+ .replace(/\/+$/, '')
174
+ .split('/')
175
+ .map((segment) => segment === '**'
176
+ ? '.*'
177
+ : segment.replace(/[.+^${}()|[\]\\]/g, '\\$&').replaceAll('*', '[^/]*'))
178
+ .join('/');
179
+ // A negated directory excludes everything beneath it, not just the dir itself.
180
+ const re = new RegExp(`^${pattern}(?:/.*)?$`);
181
+ return (relDir) => re.test(relDir);
182
+ }
183
+ /**
184
+ * Every workspace member that has a named package.json. Empty scaffold directories
185
+ * holding only a `.gitkeep` are silently skipped. Shared by the payload scripts and by
186
+ * the installer's detection, so validation and detection can never disagree.
187
+ *
188
+ * Negated globs are exclusions rather than patterns to expand, so they filter the set the
189
+ * positive globs produced. That is why they are applied here rather than in `expandGlob`.
190
+ */
191
+ export function listWorkspacePackages(root) {
192
+ const globs = workspaceGlobs(root);
193
+ const excluded = globs
194
+ .filter((g) => g.trim().startsWith('!'))
195
+ .map(negationMatcher);
196
+ const seen = new Set();
197
+ const out = [];
198
+ for (const glob of globs) {
199
+ for (const dir of expandGlob(root, glob)) {
200
+ if (seen.has(dir))
201
+ continue;
202
+ seen.add(dir);
203
+ const relDir = relative(root, dir).replaceAll('\\', '/');
204
+ if (excluded.some((matches) => matches(relDir)))
205
+ continue;
206
+ const pkg = readJson(join(dir, 'package.json'));
207
+ if (!pkg?.name)
208
+ continue;
209
+ out.push({ name: pkg.name, dir, relDir, pkg });
210
+ }
211
+ }
212
+ return out;
213
+ }
214
+ /**
215
+ * Every valid `--pkg` name for changeset-write: the workspace members, or for a
216
+ * single-package repo the root package itself.
217
+ */
218
+ export function listPublishablePackageNames(root) {
219
+ const members = listWorkspacePackages(root);
220
+ if (members.length)
221
+ return members.map((m) => m.name);
222
+ const rootPkg = readJson(join(root, 'package.json'));
223
+ return rootPkg?.name ? [rootPkg.name] : [];
224
+ }