@postxl/cli 1.11.2 → 2.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.
@@ -204,7 +204,7 @@ async function loadCustomSchema(providedPath) {
204
204
  if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
205
205
  throw new Error(`Schema file not found: ${resolvedPath}`);
206
206
  }
207
- throw new Error(`Failed to read schema file: ${error instanceof Error ? error.message : error}`);
207
+ throw new Error(`Failed to read schema file: ${error instanceof Error ? error.message : String(error)}`);
208
208
  }
209
209
  let json;
210
210
  try {
@@ -260,7 +260,7 @@ async function createFolderOrThrow(targetPath) {
260
260
  await fs.mkdir(targetPath, { recursive: true });
261
261
  return;
262
262
  }
263
- throw new Error(`Cannot access target path "${targetPath}": ${error instanceof Error ? error.message : error}`);
263
+ throw new Error(`Cannot access target path "${targetPath}": ${error instanceof Error ? error.message : String(error)}`);
264
264
  }
265
265
  if (!stat.isDirectory()) {
266
266
  throw new Error(`Target path "${targetPath}" already exists and is not a directory! Please choose a different path.`);
@@ -277,7 +277,7 @@ async function createFolderOrThrow(targetPath) {
277
277
  if (error instanceof Error && error.message.includes('already exists')) {
278
278
  throw error;
279
279
  }
280
- throw new Error(`Cannot read target path "${targetPath}": ${error instanceof Error ? error.message : error}`);
280
+ throw new Error(`Cannot read target path "${targetPath}": ${error instanceof Error ? error.message : String(error)}`);
281
281
  }
282
282
  }
283
283
  async function createProjectStructure({ name, slug, schema, projectPath, }) {
@@ -0,0 +1,53 @@
1
+ import { Command } from 'commander';
2
+ import { type FileStatus } from './helpers/project-status';
3
+ /**
4
+ * `pxl decline` — stop the generator emitting a file.
5
+ *
6
+ * ## This command writes the `"ejected"` sentinel. There is no second mechanism.
7
+ *
8
+ * `postxl-lock.json` has always accepted `"ejected"` in place of a checksum, and sync
9
+ * has always short-circuited those paths: never written, never deleted, never merged,
10
+ * sticky across runs, and respected even under `-f`. Delete the file, mark the path
11
+ * `"ejected"`, and the generator will not emit it again — including when a release
12
+ * changes what it would contain.
13
+ *
14
+ * So declining a file is *ejecting a file that is not there*: `"ejected"` means "this
15
+ * path is mine, not the generator's", and what you own at that path is nothing. This
16
+ * command exists because #898's reporter did not know that, and hand-maintained 23
17
+ * paths of a fragile substitute (delete the file, leave the checksum, hope it keeps
18
+ * matching) instead — a mechanism that breaks the moment a release changes the file.
19
+ * The docs not saying so was the actual defect; this command is the ergonomics half:
20
+ * globs, one invocation, and the generated files removed for you.
21
+ *
22
+ * `pxl status` renders an ejected path whose file is absent as `declined`, because
23
+ * "you own a file that does not exist" is not a useful thing to tell a reader.
24
+ */
25
+ export declare function register(program: Command): void;
26
+ type DeclinePlan = {
27
+ /** Every tracked path the patterns matched. */
28
+ matched: string[];
29
+ /** Paths to mark `"ejected"` — the matches that are not already ejected. */
30
+ toMark: string[];
31
+ /** Matches whose disk content is byte-identical to the generator's output, so removing them loses nothing. */
32
+ deletable: string[];
33
+ /**
34
+ * Matches with a file on disk that is *not* the generator's output — edited,
35
+ * or the consumer's own file at a path the generator also claims.
36
+ */
37
+ notDeletable: string[];
38
+ /** Matches already marked `"ejected"`; nothing to do. */
39
+ alreadyDeclined: string[];
40
+ };
41
+ /**
42
+ * Works out what `add` would do, before it does any of it.
43
+ *
44
+ * Split out from the command so the plan can be printed and confirmed as one piece.
45
+ * A glob that matches more than the user pictured is the obvious way this bites, and
46
+ * expanding it here — against the concrete paths in the lock file — is what makes the
47
+ * blast radius something a human can read before agreeing to it.
48
+ */
49
+ export declare function planDecline(params: {
50
+ files: FileStatus[];
51
+ patterns: string[];
52
+ }): DeclinePlan;
53
+ export {};
@@ -0,0 +1,326 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.register = register;
37
+ exports.planDecline = planDecline;
38
+ const fs = __importStar(require("node:fs/promises"));
39
+ const path = __importStar(require("node:path"));
40
+ const readline = __importStar(require("node:readline/promises"));
41
+ const generator_1 = require("@postxl/generator");
42
+ const utils_1 = require("@postxl/utils");
43
+ const cli_helpers_1 = require("./helpers/cli-helpers");
44
+ const project_status_1 = require("./helpers/project-status");
45
+ /**
46
+ * `pxl decline` — stop the generator emitting a file.
47
+ *
48
+ * ## This command writes the `"ejected"` sentinel. There is no second mechanism.
49
+ *
50
+ * `postxl-lock.json` has always accepted `"ejected"` in place of a checksum, and sync
51
+ * has always short-circuited those paths: never written, never deleted, never merged,
52
+ * sticky across runs, and respected even under `-f`. Delete the file, mark the path
53
+ * `"ejected"`, and the generator will not emit it again — including when a release
54
+ * changes what it would contain.
55
+ *
56
+ * So declining a file is *ejecting a file that is not there*: `"ejected"` means "this
57
+ * path is mine, not the generator's", and what you own at that path is nothing. This
58
+ * command exists because #898's reporter did not know that, and hand-maintained 23
59
+ * paths of a fragile substitute (delete the file, leave the checksum, hope it keeps
60
+ * matching) instead — a mechanism that breaks the moment a release changes the file.
61
+ * The docs not saying so was the actual defect; this command is the ergonomics half:
62
+ * globs, one invocation, and the generated files removed for you.
63
+ *
64
+ * `pxl status` renders an ejected path whose file is absent as `declined`, because
65
+ * "you own a file that does not exist" is not a useful thing to tell a reader.
66
+ */
67
+ function register(program) {
68
+ const cmd = program
69
+ .command('decline')
70
+ .summary('Stop the generator emitting given paths (writes the "ejected" sentinel).')
71
+ .description(`Marks generated paths as declined: the generator will not write them again.
72
+
73
+ This writes the SAME "ejected" entry into postxl-lock.json that marks a file as
74
+ yours to maintain — there is no separate "declined" sentinel. "ejected" means "this
75
+ path is mine, not the generator's"; declining is that applied to a path where what
76
+ you keep is nothing. Sync skips these paths entirely, even under -f, and even when
77
+ a release changes what the file would contain. \`pxl status\` shows them as
78
+ "declined" only because the file is absent from disk.
79
+
80
+ Patterns are expanded once, here, against the paths already in postxl-lock.json.
81
+ What gets marked is the concrete list printed at the time you run the command — so
82
+ a glob cannot quietly capture files a future release adds.`);
83
+ cmd
84
+ .command('list')
85
+ .argument('[path]', 'Path to project directory. Default is current directory', process.cwd())
86
+ .summary('Show declined paths (ejected entries with no file on disk).')
87
+ .option('-j, --json', 'machine-readable output')
88
+ .action(async (inputPath, options) => {
89
+ const projectPath = await (0, cli_helpers_1.resolveProjectPath)(inputPath, program);
90
+ const status = await (0, project_status_1.computeProjectStatus)({ projectPath });
91
+ const declined = status.files.filter((f) => f.state === 'declined').map((f) => String(f.path));
92
+ if (options.json) {
93
+ process.stdout.write(JSON.stringify({ declined }, null, 2) + '\n');
94
+ return;
95
+ }
96
+ if (declined.length === 0) {
97
+ console.log((0, utils_1.gray)('No declined paths. (Nothing in postxl-lock.json is marked "ejected" with no file on disk.)'));
98
+ return;
99
+ }
100
+ console.log(`${declined.length} declined path${declined.length === 1 ? '' : 's'}:`);
101
+ for (const p of declined) {
102
+ console.log((0, utils_1.gray)(` ${stripLeadingSlash(p)}`));
103
+ }
104
+ console.log((0, utils_1.gray)('\nEach is marked "ejected" in postxl-lock.json. `pxl decline remove <path>` un-declines it.'));
105
+ });
106
+ cmd
107
+ .command('add')
108
+ .argument('<patterns...>', 'Paths or glob patterns to decline (matched against postxl-lock.json)')
109
+ .summary('Decline paths: mark them "ejected" and remove the generated files.')
110
+ .description(`Expands each pattern against the paths tracked in postxl-lock.json, marks the
111
+ matches "ejected", and removes the generated files from disk.
112
+
113
+ A file is only removed when its content is byte-for-byte what the lockfile recorded
114
+ the generator writing. Anything you have edited is reported and left alone — never
115
+ overwritten or deleted on the way to declining a path. Use --keep-files to skip
116
+ removal entirely.
117
+
118
+ The full list of what will be marked and deleted is printed before anything is
119
+ touched, and confirmed interactively unless you pass --yes.`)
120
+ .option('-p, --project <path>', 'Path to project directory', process.cwd())
121
+ .option('-y, --yes', 'skip the confirmation prompt (for scripts)')
122
+ .option('--keep-files', 'do not remove matching files from disk')
123
+ .option('-j, --json', 'machine-readable output (implies --yes)')
124
+ .action(async (patterns, options) => {
125
+ const projectPath = await (0, cli_helpers_1.resolveProjectPath)(options.project, program);
126
+ const status = await (0, project_status_1.computeProjectStatus)({ projectPath });
127
+ const plan = planDecline({ files: status.files, patterns });
128
+ if (plan.matched.length === 0) {
129
+ const message = `No path in postxl-lock.json matches ${patterns.map((p) => `"${p}"`).join(', ')}.`;
130
+ if (options.json) {
131
+ process.stdout.write(JSON.stringify({ error: message }, null, 2) + '\n');
132
+ }
133
+ return program.error(message, { exitCode: 1 });
134
+ }
135
+ const willDelete = options.keepFiles ? [] : plan.deletable;
136
+ if (!options.json) {
137
+ printPlan({ plan, willDelete, keepFiles: !!options.keepFiles });
138
+ if (!options.yes && !(await confirm(`Decline ${plan.toMark.length} path(s)?`))) {
139
+ console.log((0, utils_1.gray)('Aborted. Nothing was changed.'));
140
+ return;
141
+ }
142
+ }
143
+ for (const p of willDelete) {
144
+ await fs.rm(path.join(projectPath, p), { force: true });
145
+ }
146
+ await (0, generator_1.setLockEntries)(path.join(projectPath, 'postxl-lock.json'), new Map(plan.toMark.map((p) => [p, generator_1.EJECTED_SENTINEL])));
147
+ if (options.json) {
148
+ process.stdout.write(JSON.stringify({ marked: plan.toMark, deleted: willDelete, skipped: plan.notDeletable }, null, 2) + '\n');
149
+ return;
150
+ }
151
+ console.log((0, utils_1.green)(`\n${plan.toMark.length} path${plan.toMark.length === 1 ? '' : 's'} marked "ejected" in postxl-lock.json${willDelete.length > 0 ? `, ${willDelete.length} file${willDelete.length === 1 ? '' : 's'} removed` : ''}.`));
152
+ console.log((0, utils_1.gray)('The generator will no longer emit them. `pxl decline remove <path>` reverses this.'));
153
+ });
154
+ cmd
155
+ .command('remove')
156
+ .argument('<patterns...>', 'Paths or glob patterns to stop declining')
157
+ .summary('Un-decline paths: drop their lockfile entries so the generator emits them again.')
158
+ .option('-p, --project <path>', 'Path to project directory', process.cwd())
159
+ .option('-j, --json', 'machine-readable output')
160
+ .action(async (patterns, options) => {
161
+ const projectPath = await (0, cli_helpers_1.resolveProjectPath)(options.project, program);
162
+ const status = await (0, project_status_1.computeProjectStatus)({ projectPath });
163
+ const declined = status.files
164
+ .filter((f) => f.state === 'declined')
165
+ .map((f) => String(f.path))
166
+ .filter((p) => patterns.some((pattern) => (0, generator_1.matchesPathPattern)(p, pattern)));
167
+ // The entry is removed rather than set back to a checksum: with no entry the
168
+ // next run sees `L:empty / D:empty` and writes the file as new. Restoring a
169
+ // checksum we cannot verify would claim a previous generation that never
170
+ // happened for this path.
171
+ await (0, generator_1.setLockEntries)(path.join(projectPath, 'postxl-lock.json'), new Map(declined.map((p) => [p, null])));
172
+ if (options.json) {
173
+ process.stdout.write(JSON.stringify({ removed: declined }, null, 2) + '\n');
174
+ process.exit(declined.length === 0 ? 1 : 0);
175
+ }
176
+ if (declined.length === 0) {
177
+ console.log((0, utils_1.yellow)('No declined path matched.'));
178
+ process.exit(1);
179
+ }
180
+ console.log((0, utils_1.green)(`${declined.length} path${declined.length === 1 ? '' : 's'} un-declined:`));
181
+ for (const p of declined) {
182
+ console.log((0, utils_1.gray)(` ${stripLeadingSlash(p)}`));
183
+ }
184
+ console.log((0, utils_1.gray)('Run `pxl generate` to write the files again.'));
185
+ });
186
+ cmd
187
+ .command('adopt-orphans')
188
+ .argument('[path]', 'Path to project directory. Default is current directory', process.cwd())
189
+ .summary('Migrate: mark every lockfile entry with no file on disk as "ejected".')
190
+ .description(`The migration path for projects that declined files by deleting them and leaving
191
+ their checksum in postxl-lock.json.
192
+
193
+ That worked only by accident — sync compared the checksum with the generator's
194
+ output, saw no change, and skipped the path — and it broke whenever a release
195
+ changed the file. It is also exactly what a FAILED WRITE leaves behind, so it can no
196
+ longer be read as deliberate: \`pxl generate\` now restores such a file and exits
197
+ non-zero.
198
+
199
+ Run this BEFORE your first generate on this version. It rewrites each such entry to
200
+ "ejected", which is the real mechanism and has been there all along. No file on disk
201
+ is touched.`)
202
+ .option('--dry-run', 'show what would be marked without writing the lockfile')
203
+ .option('-y, --yes', 'skip the confirmation prompt (for scripts)')
204
+ .option('-j, --json', 'machine-readable output (implies --yes)')
205
+ .action(async (inputPath, options) => {
206
+ const projectPath = await (0, cli_helpers_1.resolveProjectPath)(inputPath, program);
207
+ const status = await (0, project_status_1.computeProjectStatus)({ projectPath });
208
+ const orphans = status.files.filter((f) => f.state === 'orphan').map((f) => String(f.path));
209
+ if (options.json) {
210
+ if (!options.dryRun && orphans.length > 0) {
211
+ await writeEjected(projectPath, orphans);
212
+ }
213
+ process.stdout.write(JSON.stringify({ orphans, dryRun: !!options.dryRun }, null, 2) + '\n');
214
+ return;
215
+ }
216
+ if (orphans.length === 0) {
217
+ console.log((0, utils_1.green)('No lockfile entries without a file on disk — nothing to migrate.'));
218
+ return;
219
+ }
220
+ console.log(`${orphans.length} lockfile entr${orphans.length === 1 ? 'y has' : 'ies have'} no file on disk and would be marked "ejected":`);
221
+ for (const p of orphans) {
222
+ console.log((0, utils_1.gray)(` ${stripLeadingSlash(p)}`));
223
+ }
224
+ console.log((0, utils_1.gray)('\nNo file on disk will be touched. If any of these is a file the generator failed to write rather than one you deleted on purpose, leave it out and let `pxl generate` restore it.'));
225
+ if (options.dryRun) {
226
+ return;
227
+ }
228
+ if (!options.yes && !(await confirm(`Mark ${orphans.length} path(s) as declined?`))) {
229
+ console.log((0, utils_1.gray)('Aborted. Nothing was changed.'));
230
+ return;
231
+ }
232
+ await writeEjected(projectPath, orphans);
233
+ console.log((0, utils_1.green)(`\n${orphans.length} path${orphans.length === 1 ? '' : 's'} marked "ejected".`));
234
+ console.log((0, utils_1.gray)('Review the postxl-lock.json diff, then run `pxl generate`.'));
235
+ });
236
+ }
237
+ async function writeEjected(projectPath, paths) {
238
+ await (0, generator_1.setLockEntries)(path.join(projectPath, 'postxl-lock.json'), new Map(paths.map((p) => [p, generator_1.EJECTED_SENTINEL])));
239
+ }
240
+ /**
241
+ * Works out what `add` would do, before it does any of it.
242
+ *
243
+ * Split out from the command so the plan can be printed and confirmed as one piece.
244
+ * A glob that matches more than the user pictured is the obvious way this bites, and
245
+ * expanding it here — against the concrete paths in the lock file — is what makes the
246
+ * blast radius something a human can read before agreeing to it.
247
+ */
248
+ function planDecline(params) {
249
+ const { files, patterns } = params;
250
+ const plan = { matched: [], toMark: [], deletable: [], notDeletable: [], alreadyDeclined: [] };
251
+ for (const file of files) {
252
+ if (file.state === 'untracked-generated') {
253
+ continue;
254
+ }
255
+ if (!patterns.some((pattern) => (0, generator_1.matchesPathPattern)(file.path, pattern))) {
256
+ continue;
257
+ }
258
+ const p = String(file.path);
259
+ plan.matched.push(p);
260
+ if (file.state === 'declined') {
261
+ plan.alreadyDeclined.push(p);
262
+ continue;
263
+ }
264
+ plan.toMark.push(p);
265
+ if (file.diskHash === undefined) {
266
+ continue;
267
+ }
268
+ // `clean` is the only state where the bytes on disk are reproducible from the
269
+ // generator, so deleting them cannot lose anything. `modified` and `ejected`
270
+ // both mean a human's work is in that file.
271
+ if (file.state === 'clean') {
272
+ plan.deletable.push(p);
273
+ }
274
+ else {
275
+ plan.notDeletable.push(p);
276
+ }
277
+ }
278
+ return plan;
279
+ }
280
+ function printPlan(params) {
281
+ const { plan, willDelete, keepFiles } = params;
282
+ console.log((0, utils_1.bold)(`${plan.toMark.length} path${plan.toMark.length === 1 ? '' : 's'} will be marked "ejected":`));
283
+ for (const p of plan.toMark) {
284
+ console.log((0, utils_1.gray)(` ${stripLeadingSlash(p)}`));
285
+ }
286
+ if (willDelete.length > 0) {
287
+ console.log((0, utils_1.bold)((0, utils_1.red)(`\n${willDelete.length} file${willDelete.length === 1 ? '' : 's'} will be DELETED from disk:`)));
288
+ for (const p of willDelete) {
289
+ console.log((0, utils_1.gray)(` ${stripLeadingSlash(p)}`));
290
+ }
291
+ console.log((0, utils_1.gray)('(each is byte-identical to what the generator wrote, so nothing of yours is lost)'));
292
+ }
293
+ else if (!keepFiles) {
294
+ console.log((0, utils_1.gray)('\nNo file will be deleted.'));
295
+ }
296
+ if (plan.notDeletable.length > 0) {
297
+ console.log((0, utils_1.yellow)(`\n${plan.notDeletable.length} file${plan.notDeletable.length === 1 ? ' is' : 's are'} NOT what the generator wrote and will be left in place:`));
298
+ for (const p of plan.notDeletable) {
299
+ console.log((0, utils_1.gray)(` ${stripLeadingSlash(p)}`));
300
+ }
301
+ console.log((0, utils_1.gray)('(the path is still declined — the generator stops emitting it, and your file stays)'));
302
+ }
303
+ if (plan.alreadyDeclined.length > 0) {
304
+ console.log((0, utils_1.gray)(`\n${plan.alreadyDeclined.length} path(s) already declined; skipped.`));
305
+ }
306
+ console.log();
307
+ }
308
+ async function confirm(question) {
309
+ // A non-interactive stdin cannot answer, and defaulting to "yes" there would make
310
+ // the confirmation decorative in exactly the place it matters most (CI, scripts).
311
+ if (!process.stdin.isTTY) {
312
+ console.log((0, utils_1.yellow)('Refusing to continue: stdin is not a terminal. Re-run with --yes if this is intentional.'));
313
+ return false;
314
+ }
315
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
316
+ try {
317
+ const answer = await rl.question(`${question} [y/N] `);
318
+ return /^y(es)?$/i.test(answer.trim());
319
+ }
320
+ finally {
321
+ rl.close();
322
+ }
323
+ }
324
+ function stripLeadingSlash(p) {
325
+ return String(p).replace(/^\/+/, '').replace(/^\.\//, '');
326
+ }
@@ -56,6 +56,7 @@ function register(program) {
56
56
  const status = await (0, project_status_1.computeProjectStatus)({ projectPath });
57
57
  checks.push(checkNoDrift(status));
58
58
  checks.push(checkNoOrphans(status));
59
+ checks.push(checkDeclined(status));
59
60
  checks.push(checkNoUntracked(status));
60
61
  checks.push(await checkCustomBlocks(projectPath));
61
62
  checks.push(await checkEnvPresent(projectPath));
@@ -118,13 +119,38 @@ function checkNoDrift(status) {
118
119
  detail: `${n} modified file${n === 1 ? '' : 's'} (run \`pxl status -m\`)`,
119
120
  };
120
121
  }
122
+ /**
123
+ * Orphans stay a `warn` rather than a `fail` on purpose.
124
+ *
125
+ * `pxl doctor` is advisory — its own exit code ignores warnings — and the
126
+ * authoritative signal is now `pxl generate`, which restores these files and exits
127
+ * non-zero. Failing here as well would mean a developer who deleted one file to
128
+ * force its regeneration cannot get a green preflight, and the remedy for that is
129
+ * simply to run generate.
130
+ *
131
+ * What did change is the message. An orphan used to be ambiguous — a failed write and
132
+ * a deliberate deletion looked identical — so nothing could be recommended. Now it is
133
+ * either a failed write (run generate, it repairs itself) or a project still relying
134
+ * on the delete-and-keep-the-checksum trick, which has one migration command and
135
+ * should hear about it here, before generate restores 23 files it does not want.
136
+ */
121
137
  function checkNoOrphans(status) {
122
138
  const n = status.counts.orphan ?? 0;
123
139
  if (n === 0) {
124
140
  return { name: 'No orphans', severity: 'pass', detail: 'no orphan lockfile entries' };
125
141
  }
126
- return { name: 'No orphans', severity: 'warn', detail: `${n} orphan entr${n === 1 ? 'y' : 'ies'}` };
142
+ return {
143
+ name: 'No orphans',
144
+ severity: 'warn',
145
+ detail: `${n} orphan entr${n === 1 ? 'y' : 'ies'} — \`pxl generate\` will restore ${n === 1 ? 'this file' : 'these files'} and exit non-zero. If ${n === 1 ? 'it is' : 'they are'} missing on purpose, run \`pxl decline adopt-orphans\` first.`,
146
+ };
127
147
  }
148
+ /**
149
+ * Declined paths are not a problem — they are a decision — so this is `info`, never a
150
+ * warning. It exists because #898's reporter maintained 23 of these without the tool
151
+ * ever acknowledging one: a preflight that lists every other relationship the project
152
+ * has with its generated files should not be silent about the one they declared.
153
+ */
128
154
  function checkNoUntracked(status) {
129
155
  const n = status.counts['untracked-generated'] ?? 0;
130
156
  if (n === 0) {
@@ -132,6 +158,17 @@ function checkNoUntracked(status) {
132
158
  }
133
159
  return { name: 'No untracked-generated files', severity: 'warn', detail: `${n} untracked file${n === 1 ? '' : 's'}` };
134
160
  }
161
+ function checkDeclined(status) {
162
+ const n = status.counts.declined ?? 0;
163
+ if (n === 0) {
164
+ return { name: 'Declined paths', severity: 'info', detail: 'none' };
165
+ }
166
+ return {
167
+ name: 'Declined paths',
168
+ severity: 'info',
169
+ detail: `${n} path${n === 1 ? '' : 's'} marked "ejected" with no file on disk (run \`pxl decline list\`)`,
170
+ };
171
+ }
135
172
  async function checkCustomBlocks(projectPath) {
136
173
  const lockFile = await (0, generator_1.readLockFile)(path.join(projectPath, 'postxl-lock.json'));
137
174
  if (!lockFile) {
@@ -12,6 +12,19 @@ export declare function register(program: Command): void;
12
12
  * (issue #850 - it may carry an authorization grant). None of those may be built
13
13
  * straight through.
14
14
  *
15
+ * Two more, added with issue #897:
16
+ *
17
+ * - **A write that failed.** `sync` collected these in `errors` and the run exited
18
+ * 0 anyway, which is how a project shipped a tree that did not compile: two files
19
+ * were never written and the files importing them were. A generation that did not
20
+ * generate something cannot be a success.
21
+ * - **A restored file.** The lock file held a *checksum* for it and it was not on
22
+ * disk. Either a previous run failed to write it — see above — or a human deleted
23
+ * it and expected it to stay deleted, which used to work with a checksum and now
24
+ * requires the `"ejected"` sentinel (`pxl decline`). The generator cannot tell
25
+ * which, and both want a human once. It clears itself: the file is on disk
26
+ * afterwards, so the next run is green whichever way the human decides.
27
+ *
15
28
  * Conflict markers on their own keep their existing exit 0. That predates this
16
29
  * change and flipping it would break every pipeline that tolerates conflicts, so
17
30
  * it is a separate call to make.
@@ -214,6 +214,19 @@ This reads the schema from ${(0, utils_1.yellow)('schema.json')} and runs the ge
214
214
  * (issue #850 - it may carry an authorization grant). None of those may be built
215
215
  * straight through.
216
216
  *
217
+ * Two more, added with issue #897:
218
+ *
219
+ * - **A write that failed.** `sync` collected these in `errors` and the run exited
220
+ * 0 anyway, which is how a project shipped a tree that did not compile: two files
221
+ * were never written and the files importing them were. A generation that did not
222
+ * generate something cannot be a success.
223
+ * - **A restored file.** The lock file held a *checksum* for it and it was not on
224
+ * disk. Either a previous run failed to write it — see above — or a human deleted
225
+ * it and expected it to stay deleted, which used to work with a checksum and now
226
+ * requires the `"ejected"` sentinel (`pxl decline`). The generator cannot tell
227
+ * which, and both want a human once. It clears itself: the file is on disk
228
+ * afterwards, so the next run is green whichever way the human decides.
229
+ *
217
230
  * Conflict markers on their own keep their existing exit 0. That predates this
218
231
  * change and flipping it would break every pipeline that tolerates conflicts, so
219
232
  * it is a separate call to make.
@@ -222,10 +235,14 @@ function needsAttention(result) {
222
235
  if (!result.success) {
223
236
  return true;
224
237
  }
225
- return Object.values(result.files).some((file) => file.action.type === 'MergeConflict' &&
226
- (file.action.hasUnverifiedBase ||
227
- file.action.mergeIsUnparseable ||
228
- file.action.unplacedCustomBlocks !== undefined));
238
+ if (result.errors.length > 0) {
239
+ return true;
240
+ }
241
+ return Object.values(result.files).some((file) => file.isRestored ||
242
+ (file.action.type === 'MergeConflict' &&
243
+ (file.action.hasUnverifiedBase ||
244
+ file.action.mergeIsUnparseable ||
245
+ file.action.unplacedCustomBlocks !== undefined)));
229
246
  }
230
247
  /**
231
248
  * Whether this run may advance `.postxl/base-snapshot.json` to the current schema.
@@ -369,16 +386,17 @@ async function getLocalGenerators(params) {
369
386
  await execAsync(`tsc -b tsconfig.generate.json`);
370
387
  }
371
388
  catch (err) {
372
- if (err.stdout) {
373
- console.log(err.stdout);
389
+ const { stdout, stderr } = err;
390
+ if (stdout) {
391
+ console.log(stdout);
374
392
  }
375
- else if (err.stderr) {
376
- console.log(err.stderr);
393
+ else if (stderr) {
394
+ console.log(stderr);
377
395
  }
378
396
  else {
379
397
  console.log(JSON.stringify(err, null, 2));
380
398
  }
381
- params.program.error(`Failed to compile ${generateTsPath}:`, err);
399
+ params.program.error(`Failed to compile ${generateTsPath}:`);
382
400
  }
383
401
  // Check if `dist/generate.js` exists
384
402
  try {
@@ -409,7 +427,7 @@ async function getLocalGenerators(params) {
409
427
  }
410
428
  catch (e) {
411
429
  console.error(e);
412
- params.program.error(`Error importing local generate.js at ${generateJsPath}`, e);
430
+ params.program.error(`Error importing local generate.js at ${generateJsPath}`);
413
431
  }
414
432
  // Delete the tsconfig.generate.json file
415
433
  try {
@@ -7,14 +7,29 @@ import { type LockEntry, type PosixPath } from '@postxl/generator';
7
7
  * generators. The categorization is deterministic from `(lock, disk)`:
8
8
  *
9
9
  * - clean : disk hash === lock hash
10
- * - modified : disk hash !== lock hash, lock entry is not ejected
11
- * - ejected : lock entry is the `"ejected"` sentinel
12
- * - orphan : lock has an entry but the file is missing on disk
10
+ * - modified : disk hash !== lock hash, lock entry is not the sentinel
11
+ * - ejected : lock entry is the `"ejected"` sentinel and the file exists
12
+ * - declined : lock entry is the `"ejected"` sentinel and the file does
13
+ * not exist
14
+ * - orphan : lock has a *checksum* but the file is missing on disk
13
15
  * - untracked-generated : file is present on disk in a directory that holds
14
16
  * tracked files (a "generated path") but has no
15
17
  * lock entry of its own
18
+ *
19
+ * `ejected` and `declined` are one lock-file state, told apart purely by whether the
20
+ * file is on disk. There is no second sentinel and deliberately so: `"ejected"`
21
+ * already means "this path is mine, not the generator's", and sync short-circuits it
22
+ * identically either way. They are *named* apart here because "you own a file that
23
+ * does not exist" is not a useful thing to tell a reader — what it means is that the
24
+ * generator will not emit that file.
25
+ *
26
+ * `declined` and `orphan` looked identical before issue #897: a checksum with no file
27
+ * on disk was how projects declined files *and* what a failed write left behind, so
28
+ * `orphan` reported both and could not mean anything actionable. Declining via the
29
+ * sentinel makes `orphan` mean only the second — which is why it, and not `declined`,
30
+ * fails {@link statusExitCode}.
16
31
  */
17
- export type FileStatusState = 'clean' | 'modified' | 'ejected' | 'orphan' | 'untracked-generated';
32
+ export type FileStatusState = 'clean' | 'modified' | 'ejected' | 'declined' | 'orphan' | 'untracked-generated';
18
33
  export type FileStatus = {
19
34
  path: PosixPath;
20
35
  state: FileStatusState;
@@ -45,13 +60,19 @@ export declare function computeProjectStatus(params: {
45
60
  export type StatusFilter = {
46
61
  modified?: boolean;
47
62
  ejected?: boolean;
63
+ declined?: boolean;
48
64
  orphan?: boolean;
49
65
  untracked?: boolean;
50
66
  };
51
67
  export declare function filterStatus(status: ProjectStatus, filter: StatusFilter): FileStatus[];
52
68
  /**
53
69
  * Exit code for `pxl status` (and reused by `pxl doctor`):
54
- * - 0 if every file is `clean` or `ejected`
70
+ * - 0 if every file is `clean`, `ejected` or `declined`
55
71
  * - 1 if any file is `modified`, `orphan`, or `untracked-generated`
72
+ *
73
+ * `declined` passes for the same reason `ejected` always did: it is a declaration the
74
+ * project made on purpose, and it is the same sentinel. `orphan` keeps failing, and
75
+ * now means only the thing worth failing for — a file the lock file tracks with a
76
+ * checksum that nobody said should be missing.
56
77
  */
57
78
  export declare function statusExitCode(status: ProjectStatus): 0 | 1;
@@ -106,6 +106,7 @@ async function computeProjectStatus(params) {
106
106
  clean: 0,
107
107
  modified: 0,
108
108
  ejected: 0,
109
+ declined: 0,
109
110
  orphan: 0,
110
111
  'untracked-generated': 0,
111
112
  };
@@ -121,7 +122,13 @@ async function computeProjectStatus(params) {
121
122
  async function classifyTrackedFile(params) {
122
123
  const { lockPath, entry, onDiskPath } = params;
123
124
  if ((0, generator_1.isEjected)(entry)) {
124
- return { path: lockPath, state: 'ejected', lockfileHash: entry, diskHash: await safeChecksum(onDiskPath) };
125
+ const ejectedDiskHash = await safeChecksum(onDiskPath);
126
+ return {
127
+ path: lockPath,
128
+ state: ejectedDiskHash === undefined ? 'declined' : 'ejected',
129
+ lockfileHash: entry,
130
+ diskHash: ejectedDiskHash,
131
+ };
125
132
  }
126
133
  const diskHash = await safeChecksum(onDiskPath);
127
134
  if (diskHash === undefined) {
@@ -142,7 +149,7 @@ async function safeChecksum(absPath) {
142
149
  }
143
150
  }
144
151
  function filterStatus(status, filter) {
145
- const noFilters = !filter.modified && !filter.ejected && !filter.orphan && !filter.untracked;
152
+ const noFilters = !filter.modified && !filter.ejected && !filter.declined && !filter.orphan && !filter.untracked;
146
153
  if (noFilters) {
147
154
  return status.files;
148
155
  }
@@ -153,6 +160,9 @@ function filterStatus(status, filter) {
153
160
  if (filter.ejected && f.state === 'ejected') {
154
161
  return true;
155
162
  }
163
+ if (filter.declined && f.state === 'declined') {
164
+ return true;
165
+ }
156
166
  if (filter.orphan && f.state === 'orphan') {
157
167
  return true;
158
168
  }
@@ -164,8 +174,13 @@ function filterStatus(status, filter) {
164
174
  }
165
175
  /**
166
176
  * Exit code for `pxl status` (and reused by `pxl doctor`):
167
- * - 0 if every file is `clean` or `ejected`
177
+ * - 0 if every file is `clean`, `ejected` or `declined`
168
178
  * - 1 if any file is `modified`, `orphan`, or `untracked-generated`
179
+ *
180
+ * `declined` passes for the same reason `ejected` always did: it is a declaration the
181
+ * project made on purpose, and it is the same sentinel. `orphan` keeps failing, and
182
+ * now means only the thing worth failing for — a file the lock file tracks with a
183
+ * checksum that nobody said should be missing.
169
184
  */
170
185
  function statusExitCode(status) {
171
186
  if (status.counts.modified > 0 || status.counts.orphan > 0 || status.counts['untracked-generated'] > 0) {
package/dist/index.js CHANGED
@@ -8,6 +8,7 @@ const commander_1 = require("commander");
8
8
  const node_path_1 = __importDefault(require("node:path"));
9
9
  const create_project_command_1 = require("./create-project.command");
10
10
  const custom_block_command_1 = require("./custom-block.command");
11
+ const decline_command_1 = require("./decline.command");
11
12
  const doctor_command_1 = require("./doctor.command");
12
13
  const generate_command_1 = require("./generate.command");
13
14
  const generate_types_command_1 = require("./generate-types.command");
@@ -34,6 +35,7 @@ program
34
35
  (0, generators_command_1.register)(program);
35
36
  (0, info_command_1.register)(program);
36
37
  (0, custom_block_command_1.register)(program);
38
+ (0, decline_command_1.register)(program);
37
39
  // schema show registers the `schema` parent — schemaRenameCommand reuses it.
38
40
  (0, schema_show_command_1.register)(program);
39
41
  (0, schema_rename_command_1.register)(program);
@@ -49,12 +49,22 @@ function register(program) {
49
49
 
50
50
  States:
51
51
  clean — file matches the lockfile checksum
52
- modified — file differs from the lockfile, no eject sentinel
53
- ejected — lockfile entry is "ejected"
54
- orphan — lockfile has an entry but the file is missing on disk
55
- untracked-generated — file in a generated directory has no lockfile entry`)
52
+ modified — file differs from the lockfile, no sentinel
53
+ ejected — lockfile entry is "ejected" and the file exists (it is yours)
54
+ declined — lockfile entry is "ejected" and the file does not exist, so
55
+ the generator will not emit it (see \`pxl decline\`)
56
+ orphan — lockfile has a checksum but the file is missing on disk
57
+ untracked-generated — file in a generated directory has no lockfile entry
58
+
59
+ "ejected" and "declined" are one lockfile entry, told apart by whether the file is
60
+ on disk — there is no second sentinel.
61
+
62
+ An orphan is a defect: it means the generator did not write a file it tracks, and
63
+ \`pxl generate\` will restore it and exit non-zero. If a file is missing because you
64
+ do not want it, declare that with \`pxl decline add\` — then it reports as declined.`)
56
65
  .option('-m, --modified', 'only files that drifted from their generated checksum')
57
66
  .option('-e, --ejected', 'only files marked as ejected')
67
+ .option('-D, --declined', 'only ejected paths whose file is absent (declined)')
58
68
  .option('-o, --orphans', 'only lockfile entries with no file on disk')
59
69
  .option('-u, --untracked', 'only files in generated paths not present in the lockfile')
60
70
  .option('-s, --since <ref>', 'diff against a git ref and report state changes')
@@ -75,6 +85,7 @@ States:
75
85
  const filter = {
76
86
  ...(options.modified ? { modified: true } : {}),
77
87
  ...(options.ejected ? { ejected: true } : {}),
88
+ ...(options.declined ? { declined: true } : {}),
78
89
  ...(options.orphans ? { orphan: true } : {}),
79
90
  ...(options.untracked ? { untracked: true } : {}),
80
91
  };
@@ -104,6 +115,7 @@ function printStatusText(params) {
104
115
  `${(0, utils_1.green)(`${status.counts.clean} clean`)} ` +
105
116
  `${status.counts.modified > 0 ? (0, utils_1.red)(`${status.counts.modified} modified`) : `${status.counts.modified} modified`} ` +
106
117
  `${status.counts.ejected} ejected ` +
118
+ `${status.counts.declined} declined ` +
107
119
  `${status.counts.orphan > 0 ? (0, utils_1.yellow)(`${status.counts.orphan} orphan`) : `${status.counts.orphan} orphan`} ` +
108
120
  `${status.counts['untracked-generated'] > 0
109
121
  ? (0, utils_1.yellow)(`${status.counts['untracked-generated']} untracked`)
@@ -113,6 +125,7 @@ function printStatusText(params) {
113
125
  const sections = [
114
126
  { state: 'modified', label: 'modified', show: !anyFilter(filter) || !!filter.modified },
115
127
  { state: 'ejected', label: 'ejected', show: !anyFilter(filter) || !!filter.ejected },
128
+ { state: 'declined', label: 'declined', show: !anyFilter(filter) || !!filter.declined },
116
129
  { state: 'orphan', label: 'orphan', show: !anyFilter(filter) || !!filter.orphan },
117
130
  { state: 'untracked-generated', label: 'untracked', show: !anyFilter(filter) || !!filter.untracked },
118
131
  ];
@@ -135,7 +148,7 @@ function printStatusText(params) {
135
148
  }
136
149
  }
137
150
  function anyFilter(filter) {
138
- return !!(filter.modified || filter.ejected || filter.orphan || filter.untracked);
151
+ return !!(filter.modified || filter.ejected || filter.declined || filter.orphan || filter.untracked);
139
152
  }
140
153
  function stripLeadingSlash(p) {
141
154
  return p.replace(/^\/+/, '').replace(/^\.\//, '');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@postxl/cli",
3
- "version": "1.11.2",
3
+ "version": "2.0.0",
4
4
  "description": "Command-line interface for PostXL code generation framework",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -45,9 +45,9 @@
45
45
  "dotenv": "17.4.2",
46
46
  "ts-morph": "26.0.0",
47
47
  "zod-validation-error": "5.0.0",
48
- "@postxl/generator": "^1.9.0",
49
- "@postxl/generators": "^4.0.0",
48
+ "@postxl/generators": "^6.0.0",
50
49
  "@postxl/schema": "^2.4.0",
50
+ "@postxl/generator": "^2.0.0",
51
51
  "@postxl/utils": "^1.4.2"
52
52
  },
53
53
  "devDependencies": {},