@postxl/cli 1.8.2 → 1.9.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,235 @@
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
+ const node_child_process_1 = require("node:child_process");
38
+ const path = __importStar(require("node:path"));
39
+ const generator_1 = require("@postxl/generator");
40
+ const utils_1 = require("@postxl/utils");
41
+ const cli_helpers_1 = require("./helpers/cli-helpers");
42
+ const project_status_1 = require("./helpers/project-status");
43
+ function register(program) {
44
+ program
45
+ .command('status')
46
+ .argument('[path]', 'Path to project directory. Default is current directory', process.cwd())
47
+ .summary('Show eject/drift status of generated files.')
48
+ .description(`Shows the eject/drift status of generated files based on postxl-lock.json and disk.
49
+
50
+ States:
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`)
56
+ .option('-m, --modified', 'only files that drifted from their generated checksum')
57
+ .option('-e, --ejected', 'only files marked as ejected')
58
+ .option('-o, --orphans', 'only lockfile entries with no file on disk')
59
+ .option('-u, --untracked', 'only files in generated paths not present in the lockfile')
60
+ .option('-s, --since <ref>', 'diff against a git ref and report state changes')
61
+ .option('-j, --json', 'machine-readable output')
62
+ .action(async (inputPath, options) => {
63
+ const projectPath = await (0, cli_helpers_1.resolveProjectPath)(inputPath, program);
64
+ const status = await (0, project_status_1.computeProjectStatus)({ projectPath });
65
+ if (options.since) {
66
+ await runSinceMode({
67
+ projectPath,
68
+ ref: options.since,
69
+ json: !!options.json,
70
+ program,
71
+ currentStatus: status,
72
+ });
73
+ return;
74
+ }
75
+ const filter = {
76
+ ...(options.modified ? { modified: true } : {}),
77
+ ...(options.ejected ? { ejected: true } : {}),
78
+ ...(options.orphans ? { orphan: true } : {}),
79
+ ...(options.untracked ? { untracked: true } : {}),
80
+ };
81
+ const filtered = (0, project_status_1.filterStatus)(status, filter);
82
+ if (options.json) {
83
+ process.stdout.write(JSON.stringify({
84
+ projectPath: status.projectPath,
85
+ counts: status.counts,
86
+ files: filtered.map((f) => ({
87
+ path: f.path,
88
+ state: f.state,
89
+ lockfileHash: f.lockfileHash,
90
+ diskHash: f.diskHash,
91
+ })),
92
+ }, null, 2) + '\n');
93
+ }
94
+ else {
95
+ printStatusText({ projectPath, status, filtered, filter });
96
+ }
97
+ process.exit((0, project_status_1.statusExitCode)(status));
98
+ });
99
+ }
100
+ function printStatusText(params) {
101
+ const { projectPath, status, filtered, filter } = params;
102
+ const projectName = path.basename(projectPath);
103
+ const summary = `${projectName}/ ` +
104
+ `${(0, utils_1.green)(`${status.counts.clean} clean`)} ` +
105
+ `${status.counts.modified > 0 ? (0, utils_1.red)(`${status.counts.modified} modified`) : `${status.counts.modified} modified`} ` +
106
+ `${status.counts.ejected} ejected ` +
107
+ `${status.counts.orphan > 0 ? (0, utils_1.yellow)(`${status.counts.orphan} orphan`) : `${status.counts.orphan} orphan`} ` +
108
+ `${status.counts['untracked-generated'] > 0
109
+ ? (0, utils_1.yellow)(`${status.counts['untracked-generated']} untracked`)
110
+ : `${status.counts['untracked-generated']} untracked`}`;
111
+ console.log(summary);
112
+ console.log();
113
+ const sections = [
114
+ { state: 'modified', label: 'modified', show: !anyFilter(filter) || !!filter.modified },
115
+ { state: 'ejected', label: 'ejected', show: !anyFilter(filter) || !!filter.ejected },
116
+ { state: 'orphan', label: 'orphan', show: !anyFilter(filter) || !!filter.orphan },
117
+ { state: 'untracked-generated', label: 'untracked', show: !anyFilter(filter) || !!filter.untracked },
118
+ ];
119
+ for (const section of sections) {
120
+ if (!section.show) {
121
+ continue;
122
+ }
123
+ const inSection = filtered.filter((f) => f.state === section.state);
124
+ if (inSection.length === 0) {
125
+ continue;
126
+ }
127
+ console.log(`${section.label}:`);
128
+ for (const f of inSection) {
129
+ console.log(` ${stripLeadingSlash(f.path)}`);
130
+ }
131
+ console.log();
132
+ }
133
+ if (filtered.length === 0) {
134
+ console.log((0, utils_1.gray)('No files matched the requested filter.'));
135
+ }
136
+ }
137
+ function anyFilter(filter) {
138
+ return !!(filter.modified || filter.ejected || filter.orphan || filter.untracked);
139
+ }
140
+ function stripLeadingSlash(p) {
141
+ return p.replace(/^\/+/, '').replace(/^\.\//, '');
142
+ }
143
+ /**
144
+ * `--since <ref>`: lockfile-only diff. Compares the lock file at `<ref>`
145
+ * against the lock file at HEAD/working tree and reports state transitions
146
+ * (clean → ejected, missing → present, hash changed, entry removed).
147
+ *
148
+ * Running generation against a worktree to compute a "true" diff is
149
+ * deliberately out of scope here.
150
+ */
151
+ async function runSinceMode(params) {
152
+ const { projectPath, ref, json, program } = params;
153
+ // Validate ref against the set of characters git allows (plus the few extras
154
+ // that show up in the wild like `~`, `^`, `[`, `]`). This is the first line
155
+ // of defense — we still pass the ref via `execFileSync` (no shell), so
156
+ // it cannot be interpreted as a separate command even on weird locales.
157
+ if (!/^[A-Za-z0-9_./~^[\]@{}-]+$/.test(ref)) {
158
+ return program.error(`Invalid git ref "${ref}".`, { exitCode: 2 });
159
+ }
160
+ const lockFileRel = path.relative(gitRootOrThrow(projectPath, program), path.join(projectPath, 'postxl-lock.json'));
161
+ let oldContent;
162
+ try {
163
+ oldContent = (0, node_child_process_1.execFileSync)('git', ['show', `${ref}:${lockFileRel}`], {
164
+ cwd: projectPath,
165
+ encoding: 'utf8',
166
+ stdio: ['ignore', 'pipe', 'pipe'],
167
+ });
168
+ }
169
+ catch (error) {
170
+ return program.error(`Failed to read postxl-lock.json at ref "${ref}": ${error.message}`, {
171
+ exitCode: 2,
172
+ });
173
+ }
174
+ let oldEntries;
175
+ try {
176
+ const parsed = JSON.parse(oldContent);
177
+ oldEntries = new Map(Object.entries(parsed));
178
+ }
179
+ catch (e) {
180
+ return program.error(`Could not parse postxl-lock.json at ref "${ref}": ${e.message}`, { exitCode: 2 });
181
+ }
182
+ const newLock = await (0, generator_1.readLockFile)(path.join(projectPath, 'postxl-lock.json'));
183
+ const newEntries = new Map();
184
+ if (newLock) {
185
+ for (const [k, v] of newLock) {
186
+ newEntries.set(String(k), v);
187
+ }
188
+ }
189
+ const changes = [];
190
+ const allPaths = new Set([...oldEntries.keys(), ...newEntries.keys()]);
191
+ for (const p of [...allPaths].sort()) {
192
+ const before = entryToStatusKind(oldEntries.get(p));
193
+ const after = entryToStatusKind(newEntries.get(p));
194
+ if (before !== after) {
195
+ changes.push({ path: p, from: before, to: after });
196
+ }
197
+ else if (before === 'clean' && after === 'clean') {
198
+ // Hash changed without a state change.
199
+ if (oldEntries.get(p) !== newEntries.get(p)) {
200
+ changes.push({ path: p, from: 'clean', to: 'clean' });
201
+ }
202
+ }
203
+ }
204
+ if (json) {
205
+ process.stdout.write(JSON.stringify({ ref, changes }, null, 2) + '\n');
206
+ return;
207
+ }
208
+ if (changes.length === 0) {
209
+ console.log((0, utils_1.gray)(`No lockfile changes since ${ref}.`));
210
+ return;
211
+ }
212
+ console.log(`Lockfile changes since ${ref}:`);
213
+ console.log();
214
+ for (const c of changes) {
215
+ const arrow = `${c.from} → ${c.to}`;
216
+ console.log(` ${stripLeadingSlash(c.path)} ${(0, utils_1.gray)(arrow)}`);
217
+ }
218
+ }
219
+ function entryToStatusKind(entry) {
220
+ if (entry === undefined) {
221
+ return 'absent';
222
+ }
223
+ if ((0, generator_1.isEjected)(entry)) {
224
+ return 'ejected';
225
+ }
226
+ return 'clean';
227
+ }
228
+ function gitRootOrThrow(cwd, program) {
229
+ try {
230
+ return (0, node_child_process_1.execSync)('git rev-parse --show-toplevel', { cwd, encoding: 'utf8' }).trim();
231
+ }
232
+ catch {
233
+ return program.error('--since requires the project to be inside a git repository.', { exitCode: 2 });
234
+ }
235
+ }
@@ -38,6 +38,7 @@ const fs = __importStar(require("node:fs/promises"));
38
38
  const path = __importStar(require("node:path"));
39
39
  const schema_1 = require("@postxl/schema");
40
40
  const utils_1 = require("@postxl/utils");
41
+ const load_project_schema_1 = require("./helpers/load-project-schema");
41
42
  const log_schema_error_1 = require("./helpers/log-schema-error");
42
43
  function register(program) {
43
44
  program
@@ -52,40 +53,46 @@ This reads the schema from the specified file or from postxl-schema.json in the
52
53
  if (!path.isAbsolute(inputPath)) {
53
54
  inputPath = path.join(process.cwd(), inputPath);
54
55
  }
55
- // Check if input path exists
56
- let schemaPath;
56
+ // Check if input path exists and decide between project-directory and raw-file modes.
57
+ // For a directory or a `postxl-schema.json` file we go through `loadAndMergeRawSchema`
58
+ // so split files under `schema/*.model.json` / `schema/*.enum.json` are merged into
59
+ // the validated input — otherwise validate would disagree with `generate` on
60
+ // multi-file schemas. For any other file path we treat it as a raw schema JSON
61
+ // (the single-file escape hatch for validating arbitrary fragments).
62
+ let jsonSchema;
57
63
  try {
58
64
  const stats = await fs.stat(inputPath);
59
65
  if (stats.isDirectory()) {
60
- // If it's a directory, look for postxl-schema.json
61
- schemaPath = path.join(inputPath, 'postxl-schema.json');
66
+ jsonSchema = await (0, load_project_schema_1.loadAndMergeRawSchema)({ projectPath: inputPath, program });
62
67
  }
63
68
  else if (stats.isFile()) {
64
- // If it's a file, use it directly
65
- schemaPath = inputPath;
69
+ if (path.basename(inputPath) === 'postxl-schema.json') {
70
+ jsonSchema = await (0, load_project_schema_1.loadAndMergeRawSchema)({ projectPath: path.dirname(inputPath), program });
71
+ }
72
+ else {
73
+ try {
74
+ const content = await fs.readFile(inputPath, 'utf-8');
75
+ jsonSchema = JSON.parse(content);
76
+ }
77
+ catch (error) {
78
+ const message = error instanceof Error ? error.message : String(error);
79
+ program.error(`Error reading or parsing JSON from ${inputPath}: ${message}`);
80
+ }
81
+ }
66
82
  }
67
83
  else {
68
84
  program.error(`Path ${inputPath} is neither a file nor a directory!`);
69
85
  }
70
86
  }
71
- catch {
72
- program.error(`Cannot find path ${inputPath}!`);
73
- }
74
- // Check if schema file exists
75
- try {
76
- await fs.access(schemaPath);
77
- }
78
- catch {
79
- program.error(`Cannot find schema file at ${schemaPath}`);
80
- }
81
- // Read and parse JSON
82
- let jsonSchema;
83
- try {
84
- const content = await fs.readFile(schemaPath, 'utf-8');
85
- jsonSchema = JSON.parse(content);
86
- }
87
87
  catch (error) {
88
- program.error(`Error reading or parsing JSON from ${schemaPath}: ${error.message}`);
88
+ // Only mask the missing-path case here — real errors from `loadAndMergeRawSchema`
89
+ // (bad split-file casing, duplicate model names, etc.) must surface so users can
90
+ // act on them. validate is the command they reach for to debug schema problems.
91
+ const code = error?.code;
92
+ if (code === 'ENOENT' || code === 'ENOTDIR') {
93
+ program.error(`Cannot find path ${inputPath}!`);
94
+ }
95
+ throw error;
89
96
  }
90
97
  // Validate schema
91
98
  const result = schema_1.zProjectSchema.safeParse(jsonSchema);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@postxl/cli",
3
- "version": "1.8.2",
3
+ "version": "1.9.0",
4
4
  "description": "Command-line interface for PostXL code generation framework",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -43,8 +43,9 @@
43
43
  "dependencies": {
44
44
  "commander": "14.0.3",
45
45
  "dotenv": "17.4.2",
46
+ "ts-morph": "26.0.0",
46
47
  "zod-validation-error": "5.0.0",
47
- "@postxl/generator": "^1.6.1",
48
+ "@postxl/generator": "^1.6.2",
48
49
  "@postxl/generators": "^2.0.1",
49
50
  "@postxl/schema": "^2.0.1",
50
51
  "@postxl/utils": "^1.4.1"
@@ -62,6 +63,8 @@
62
63
  "build": "tsc -b tsconfig.build.json",
63
64
  "lint": "eslint .",
64
65
  "prettier:check": "prettier --check \"**/*.{ts,tsx}\" --config ../../prettier.config.js --ignore-path ../../.prettierignore",
66
+ "test:jest": "cross-env NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules\" jest",
67
+ "test:coverage": "cross-env NODE_OPTIONS=\"$NODE_OPTIONS --experimental-vm-modules\" jest --coverage",
65
68
  "test:types": "tsc --noEmit"
66
69
  }
67
70
  }