@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,175 @@
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.computeProjectStatus = computeProjectStatus;
37
+ exports.filterStatus = filterStatus;
38
+ exports.statusExitCode = statusExitCode;
39
+ const fs = __importStar(require("node:fs/promises"));
40
+ const path = __importStar(require("node:path"));
41
+ const generator_1 = require("@postxl/generator");
42
+ /**
43
+ * Compute the status of every file mentioned in the lock file plus any file
44
+ * that lives in a "generated path" but has no lock entry.
45
+ *
46
+ * "Generated paths" are derived from the lock file itself: every directory
47
+ * that contains at least one tracked file is considered a generated path.
48
+ * This avoids hard-coding allowlists like `backend/` or `frontend/` and stays
49
+ * accurate as generators move output around.
50
+ */
51
+ async function computeProjectStatus(params) {
52
+ const { projectPath } = params;
53
+ const lockFilePath = path.join(projectPath, 'postxl-lock.json');
54
+ const diskPathNormalized = (0, generator_1.normalize)(projectPath);
55
+ const lockFile = await (0, generator_1.readLockFile)(lockFilePath);
56
+ const files = [];
57
+ // Track directories that contain at least one lock-file entry. A file in
58
+ // these directories that is missing from the lock is considered
59
+ // `untracked-generated`. Use `Set<string>` keyed by absolute directory path.
60
+ const generatedDirs = new Set();
61
+ const trackedDiskPaths = new Set();
62
+ if (lockFile) {
63
+ for (const [lockPath, entry] of lockFile) {
64
+ const onDiskPath = path.join(projectPath, lockPath);
65
+ trackedDiskPaths.add(path.resolve(onDiskPath));
66
+ generatedDirs.add(path.dirname(path.resolve(onDiskPath)));
67
+ const fileStatus = await classifyTrackedFile({ lockPath, entry, onDiskPath });
68
+ files.push(fileStatus);
69
+ }
70
+ }
71
+ // Walk every directory that holds tracked files and look for files that
72
+ // aren't in the lock — those are `untracked-generated`. We exclude the
73
+ // generator's own inputs (lockfile, schema, generate script) from this
74
+ // check; they live alongside outputs but are owned by the developer.
75
+ const inputFileBasenames = new Set(['postxl-lock.json', 'postxl-schema.json', 'generate.ts']);
76
+ for (const dir of generatedDirs) {
77
+ let entries;
78
+ try {
79
+ entries = await fs.readdir(dir, { withFileTypes: true });
80
+ }
81
+ catch {
82
+ continue;
83
+ }
84
+ for (const entry of entries) {
85
+ if (!entry.isFile()) {
86
+ continue;
87
+ }
88
+ const absPath = path.resolve(dir, entry.name);
89
+ if (trackedDiskPaths.has(absPath)) {
90
+ continue;
91
+ }
92
+ if (inputFileBasenames.has(entry.name)) {
93
+ continue;
94
+ }
95
+ const relPosix = '/' + path.relative(projectPath, absPath).split(path.sep).join('/');
96
+ files.push({
97
+ path: relPosix,
98
+ state: 'untracked-generated',
99
+ lockfileHash: undefined,
100
+ diskHash: await safeChecksum(absPath),
101
+ });
102
+ }
103
+ }
104
+ files.sort((a, b) => String(a.path).localeCompare(String(b.path)));
105
+ const counts = {
106
+ clean: 0,
107
+ modified: 0,
108
+ ejected: 0,
109
+ orphan: 0,
110
+ 'untracked-generated': 0,
111
+ };
112
+ for (const f of files) {
113
+ counts[f.state]++;
114
+ }
115
+ return {
116
+ projectPath: diskPathNormalized,
117
+ files,
118
+ counts,
119
+ };
120
+ }
121
+ async function classifyTrackedFile(params) {
122
+ const { lockPath, entry, onDiskPath } = params;
123
+ if ((0, generator_1.isEjected)(entry)) {
124
+ return { path: lockPath, state: 'ejected', lockfileHash: entry, diskHash: await safeChecksum(onDiskPath) };
125
+ }
126
+ const diskHash = await safeChecksum(onDiskPath);
127
+ if (diskHash === undefined) {
128
+ return { path: lockPath, state: 'orphan', lockfileHash: entry, diskHash: undefined };
129
+ }
130
+ if (diskHash === entry) {
131
+ return { path: lockPath, state: 'clean', lockfileHash: entry, diskHash };
132
+ }
133
+ return { path: lockPath, state: 'modified', lockfileHash: entry, diskHash };
134
+ }
135
+ async function safeChecksum(absPath) {
136
+ try {
137
+ const buf = await fs.readFile(absPath);
138
+ return await (0, generator_1.calculateChecksum)(buf);
139
+ }
140
+ catch {
141
+ return undefined;
142
+ }
143
+ }
144
+ function filterStatus(status, filter) {
145
+ const noFilters = !filter.modified && !filter.ejected && !filter.orphan && !filter.untracked;
146
+ if (noFilters) {
147
+ return status.files;
148
+ }
149
+ return status.files.filter((f) => {
150
+ if (filter.modified && f.state === 'modified') {
151
+ return true;
152
+ }
153
+ if (filter.ejected && f.state === 'ejected') {
154
+ return true;
155
+ }
156
+ if (filter.orphan && f.state === 'orphan') {
157
+ return true;
158
+ }
159
+ if (filter.untracked && f.state === 'untracked-generated') {
160
+ return true;
161
+ }
162
+ return false;
163
+ });
164
+ }
165
+ /**
166
+ * Exit code for `pxl status` (and reused by `pxl doctor`):
167
+ * - 0 if every file is `clean` or `ejected`
168
+ * - 1 if any file is `modified`, `orphan`, or `untracked-generated`
169
+ */
170
+ function statusExitCode(status) {
171
+ if (status.counts.modified > 0 || status.counts.orphan > 0 || status.counts['untracked-generated'] > 0) {
172
+ return 1;
173
+ }
174
+ return 0;
175
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * One JSON file (`postxl-schema.json` or a `schema/*.model.json`) loaded into
3
+ * memory along with its on-disk path. The renamer mutates `value` in place
4
+ * and writes it back through {@link saveDocs} when commit is called.
5
+ */
6
+ export type SchemaDoc = {
7
+ filePath: string;
8
+ value: Record<string, unknown>;
9
+ /**
10
+ * For a split file, the camelCase basename of the model or enum the file
11
+ * defines (e.g. `country` for `schema/country.model.json`,
12
+ * `actionOperation` for `schema/actionOperation.model.json`). Undefined for
13
+ * the root `postxl-schema.json`. Use together with `splitKind` to know
14
+ * what the file represents.
15
+ */
16
+ splitName?: string;
17
+ /**
18
+ * Whether the split file is a model definition or an enum definition.
19
+ * Undefined for the root schema file. The two have different namespaces
20
+ * (a model named `Role` does NOT collide with an enum named `Role`), so
21
+ * the renamer treats them separately.
22
+ */
23
+ splitKind?: 'model' | 'enum';
24
+ };
25
+ /**
26
+ * Plan of changes the rename command intends to perform. Renderable as a diff
27
+ * (`--dry-run`) or applied to disk (`commit`).
28
+ */
29
+ export type RenamePlan = {
30
+ /** Human-readable lines describing the changes (for `--dry-run`). */
31
+ summary: string[];
32
+ /** Write each doc to disk. */
33
+ docWrites: {
34
+ filePath: string;
35
+ before: string;
36
+ after: string;
37
+ }[];
38
+ /** Files to rename on disk (split-schema files containing the renamed model). */
39
+ fileRenames: {
40
+ from: string;
41
+ to: string;
42
+ }[];
43
+ /** Lockfile entries to delete so the matching old generated files are removed on next regen. */
44
+ lockfileDeletions: string[];
45
+ /** Files in the project whose content references the old name (e.g. inside custom blocks). Reported for the user, never modified. */
46
+ customBlockReferences: string[];
47
+ };
48
+ /**
49
+ * Load the project's root schema doc plus any split schema files under `schema/`.
50
+ * Mutating any returned `value` will be persisted by `applyPlan`.
51
+ */
52
+ export declare function loadSchemaDocs(projectPath: string): Promise<SchemaDoc[]>;
53
+ /**
54
+ * Rename a model across the loaded docs. References:
55
+ * - `models[OldName]` → renamed key
56
+ * - `field.type === 'OldName'` → updated string
57
+ * - any other property whose value exactly matches OldName is **left alone**
58
+ * (we don't want to rewrite arbitrary string contents).
59
+ * - split-file basenames `oldName.model.json` → `newName.model.json`.
60
+ *
61
+ * Returns a plan that can be reviewed (`--dry-run`) or committed.
62
+ */
63
+ export declare function planRenameModel(params: {
64
+ projectPath: string;
65
+ oldName: string;
66
+ newName: string;
67
+ }): Promise<RenamePlan>;
68
+ /**
69
+ * Rename a single field on a model. Updates:
70
+ * - the field key inside `models[Model].fields`
71
+ * - any `indexes` entries that reference the old field name
72
+ * - any `defaultSort`, `keyField`, `labelField`, `defaultField` references
73
+ * (still scoped to the model whose field is being renamed)
74
+ * - `seed` records (replaces the property name on each row)
75
+ */
76
+ export declare function planRenameField(params: {
77
+ projectPath: string;
78
+ modelName: string;
79
+ oldField: string;
80
+ newField: string;
81
+ }): Promise<RenamePlan>;
82
+ /**
83
+ * Apply a rename plan to disk. Writes are NOT atomic across the three stages
84
+ * (doc rewrites → file renames → lockfile prune); a process crash or fs
85
+ * error mid-way leaves the project partially renamed. Recovery is manual:
86
+ * inspect `git status`, restore via `git checkout -- <paths>`, and re-run.
87
+ *
88
+ * Always run with `--dry-run` first on a clean working tree, and prefer
89
+ * doing the rename on a fresh branch so revert is a `git reset`.
90
+ */
91
+ export declare function applyPlan(plan: RenamePlan, projectPath: string): Promise<void>;
@@ -0,0 +1,408 @@
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.loadSchemaDocs = loadSchemaDocs;
37
+ exports.planRenameModel = planRenameModel;
38
+ exports.planRenameField = planRenameField;
39
+ exports.applyPlan = applyPlan;
40
+ const fs = __importStar(require("node:fs/promises"));
41
+ const path = __importStar(require("node:path"));
42
+ const generator_1 = require("@postxl/generator");
43
+ const cli_helpers_1 = require("./cli-helpers");
44
+ /**
45
+ * Load the project's root schema doc plus any split schema files under `schema/`.
46
+ * Mutating any returned `value` will be persisted by `applyPlan`.
47
+ */
48
+ async function loadSchemaDocs(projectPath) {
49
+ const docs = [];
50
+ const rootPath = path.join(projectPath, 'postxl-schema.json');
51
+ docs.push({
52
+ filePath: rootPath,
53
+ value: JSON.parse(await fs.readFile(rootPath, 'utf8')),
54
+ });
55
+ const splitDir = path.join(projectPath, 'schema');
56
+ let splitFiles;
57
+ try {
58
+ splitFiles = await fs.readdir(splitDir);
59
+ }
60
+ catch {
61
+ splitFiles = [];
62
+ }
63
+ for (const f of splitFiles) {
64
+ const isModel = f.endsWith('.model.json');
65
+ const isEnum = f.endsWith('.enum.json');
66
+ if (!isModel && !isEnum) {
67
+ continue;
68
+ }
69
+ const filePath = path.join(splitDir, f);
70
+ docs.push({
71
+ filePath,
72
+ value: JSON.parse(await fs.readFile(filePath, 'utf8')),
73
+ splitName: f.replace(/\.(model|enum)\.json$/, ''),
74
+ splitKind: isModel ? 'model' : 'enum',
75
+ });
76
+ }
77
+ return docs;
78
+ }
79
+ /**
80
+ * Rename a model across the loaded docs. References:
81
+ * - `models[OldName]` → renamed key
82
+ * - `field.type === 'OldName'` → updated string
83
+ * - any other property whose value exactly matches OldName is **left alone**
84
+ * (we don't want to rewrite arbitrary string contents).
85
+ * - split-file basenames `oldName.model.json` → `newName.model.json`.
86
+ *
87
+ * Returns a plan that can be reviewed (`--dry-run`) or committed.
88
+ */
89
+ async function planRenameModel(params) {
90
+ const { projectPath, oldName, newName } = params;
91
+ const docs = await loadSchemaDocs(projectPath);
92
+ // Collision detection: does the new name already exist anywhere?
93
+ const collision = docs.some((d) => modelNamesIn(d).includes(newName));
94
+ if (collision) {
95
+ throw new Error(`Cannot rename: a model named "${newName}" already exists in the schema.`);
96
+ }
97
+ // Existence check: does the old name exist?
98
+ const exists = docs.some((d) => modelNamesIn(d).includes(oldName));
99
+ if (!exists) {
100
+ throw new Error(`Cannot rename: no model named "${oldName}" in this schema.`);
101
+ }
102
+ const summary = [];
103
+ const docWrites = [];
104
+ const fileRenames = [];
105
+ const oldBase = camelize(oldName);
106
+ const newBase = camelize(newName);
107
+ for (const doc of docs) {
108
+ const beforeText = JSON.stringify(doc.value, null, 2);
109
+ let changes = 0;
110
+ // Rename model entry in inline `models`.
111
+ if (isObject(doc.value.models) && oldName in doc.value.models) {
112
+ const models = doc.value.models;
113
+ models[newName] = models[oldName];
114
+ Reflect.deleteProperty(models, oldName);
115
+ changes++;
116
+ summary.push(`${displayPath(doc.filePath, projectPath)}: renamed model "${oldName}" → "${newName}"`);
117
+ }
118
+ // Update relation `type: "OldName"` references inside any model's fields.
119
+ const refUpdates = updateModelTypeReferences(doc.value, oldName, newName);
120
+ changes += refUpdates;
121
+ if (refUpdates > 0) {
122
+ summary.push(`${displayPath(doc.filePath, projectPath)}: updated ${refUpdates} relation reference${refUpdates === 1 ? '' : 's'}`);
123
+ }
124
+ // Update `standardModels` entries.
125
+ if (Array.isArray(doc.value.standardModels)) {
126
+ const list = doc.value.standardModels;
127
+ for (let i = 0; i < list.length; i++) {
128
+ if (list[i] === oldName) {
129
+ list[i] = newName;
130
+ changes++;
131
+ summary.push(`${displayPath(doc.filePath, projectPath)}: updated standardModels entry`);
132
+ }
133
+ }
134
+ }
135
+ // Split-file: the file basename encodes the model name. The body itself
136
+ // doesn't reference the name, so the only doc-level "rename" is the file
137
+ // rename below — but we still need to walk for relation references.
138
+ // Restrict to `.model.json` files; `.enum.json` lives in a different
139
+ // namespace and shouldn't be touched by `rename-model`.
140
+ if (doc.splitKind === 'model' && doc.splitName === oldBase) {
141
+ // Schedule the file rename. The file body is rewritten only if relation
142
+ // references inside it changed (handled via `refUpdates` above).
143
+ fileRenames.push({
144
+ from: doc.filePath,
145
+ to: path.join(path.dirname(doc.filePath), `${newBase}.model.json`),
146
+ });
147
+ summary.push(`${displayPath(doc.filePath, projectPath)} → ${displayPath(path.join(path.dirname(doc.filePath), `${newBase}.model.json`), projectPath)}`);
148
+ }
149
+ if (changes > 0) {
150
+ const afterText = JSON.stringify(doc.value, null, 2) + '\n';
151
+ docWrites.push({ filePath: doc.filePath, before: beforeText + '\n', after: afterText });
152
+ }
153
+ }
154
+ const lockfileDeletions = await collectLockfileDeletions(projectPath, oldBase, newBase);
155
+ if (lockfileDeletions.length > 0) {
156
+ summary.push(`Lockfile: will drop ${lockfileDeletions.length} entr${lockfileDeletions.length === 1 ? 'y' : 'ies'} that embed the old name (next regen will rewrite them)`);
157
+ }
158
+ const customBlockReferences = await scanCustomBlockReferences(projectPath, oldName, oldBase);
159
+ return { summary, docWrites, fileRenames, lockfileDeletions, customBlockReferences };
160
+ }
161
+ /**
162
+ * Rename a single field on a model. Updates:
163
+ * - the field key inside `models[Model].fields`
164
+ * - any `indexes` entries that reference the old field name
165
+ * - any `defaultSort`, `keyField`, `labelField`, `defaultField` references
166
+ * (still scoped to the model whose field is being renamed)
167
+ * - `seed` records (replaces the property name on each row)
168
+ */
169
+ async function planRenameField(params) {
170
+ const { projectPath, modelName, oldField, newField } = params;
171
+ const docs = await loadSchemaDocs(projectPath);
172
+ // Locate the model object (could be inline or split-file).
173
+ const target = locateModel(docs, modelName);
174
+ if (!target) {
175
+ throw new Error(`Cannot rename: no model named "${modelName}" in this schema.`);
176
+ }
177
+ const fieldsObj = target.model.fields ?? {};
178
+ if (newField in fieldsObj) {
179
+ throw new Error(`Cannot rename: model "${modelName}" already has a field "${newField}".`);
180
+ }
181
+ if (!(oldField in fieldsObj)) {
182
+ throw new Error(`Cannot rename: model "${modelName}" has no field "${oldField}".`);
183
+ }
184
+ const beforeText = JSON.stringify(target.doc.value, null, 2);
185
+ fieldsObj[newField] = fieldsObj[oldField];
186
+ Reflect.deleteProperty(fieldsObj, oldField);
187
+ let referenceUpdates = 0;
188
+ if (Array.isArray(target.model.indexes)) {
189
+ for (const index of target.model.indexes) {
190
+ if (Array.isArray(index)) {
191
+ for (let i = 0; i < index.length; i++) {
192
+ if (index[i] === oldField) {
193
+ index[i] = newField;
194
+ referenceUpdates++;
195
+ }
196
+ }
197
+ }
198
+ }
199
+ }
200
+ for (const key of ['defaultSort', 'keyField', 'labelField', 'defaultField']) {
201
+ const v = target.model[key];
202
+ if (typeof v === 'string' && v === oldField) {
203
+ target.model[key] = newField;
204
+ referenceUpdates++;
205
+ }
206
+ else if (Array.isArray(v)) {
207
+ for (let i = 0; i < v.length; i++) {
208
+ if (v[i] === oldField) {
209
+ v[i] = newField;
210
+ referenceUpdates++;
211
+ }
212
+ }
213
+ }
214
+ }
215
+ // Seed records: replace the property name on each entry.
216
+ if (Array.isArray(target.model.seed)) {
217
+ for (const seedEntry of target.model.seed) {
218
+ if (isObject(seedEntry) && oldField in seedEntry) {
219
+ const obj = seedEntry;
220
+ obj[newField] = obj[oldField];
221
+ Reflect.deleteProperty(obj, oldField);
222
+ referenceUpdates++;
223
+ }
224
+ }
225
+ }
226
+ const afterText = JSON.stringify(target.doc.value, null, 2) + '\n';
227
+ const summary = [
228
+ `${displayPath(target.doc.filePath, projectPath)}: renamed field "${modelName}.${oldField}" → "${modelName}.${newField}"`,
229
+ ];
230
+ if (referenceUpdates > 0) {
231
+ summary.push(`${displayPath(target.doc.filePath, projectPath)}: updated ${referenceUpdates} field reference${referenceUpdates === 1 ? '' : 's'}`);
232
+ }
233
+ // Custom block references: just the field name. A camelCased identifier
234
+ // typically appears verbatim in user code, no second form to look for.
235
+ const customBlockReferences = await scanCustomBlockReferences(projectPath, oldField);
236
+ return {
237
+ summary,
238
+ docWrites: [{ filePath: target.doc.filePath, before: beforeText + '\n', after: afterText }],
239
+ fileRenames: [],
240
+ lockfileDeletions: [],
241
+ customBlockReferences,
242
+ };
243
+ }
244
+ /**
245
+ * Apply a rename plan to disk. Writes are NOT atomic across the three stages
246
+ * (doc rewrites → file renames → lockfile prune); a process crash or fs
247
+ * error mid-way leaves the project partially renamed. Recovery is manual:
248
+ * inspect `git status`, restore via `git checkout -- <paths>`, and re-run.
249
+ *
250
+ * Always run with `--dry-run` first on a clean working tree, and prefer
251
+ * doing the rename on a fresh branch so revert is a `git reset`.
252
+ */
253
+ async function applyPlan(plan, projectPath) {
254
+ for (const w of plan.docWrites) {
255
+ await fs.writeFile(w.filePath, w.after);
256
+ }
257
+ for (const r of plan.fileRenames) {
258
+ await fs.rename(r.from, r.to);
259
+ }
260
+ if (plan.lockfileDeletions.length > 0) {
261
+ const lockPath = path.join(projectPath, 'postxl-lock.json');
262
+ const raw = JSON.parse(await fs.readFile(lockPath, 'utf8'));
263
+ let dirty = false;
264
+ for (const key of plan.lockfileDeletions) {
265
+ if (key in raw) {
266
+ Reflect.deleteProperty(raw, key);
267
+ dirty = true;
268
+ }
269
+ }
270
+ if (dirty) {
271
+ const sortedKeys = Object.keys(raw).sort((a, b) => a.localeCompare(b));
272
+ const sorted = {};
273
+ for (const k of sortedKeys) {
274
+ sorted[k] = raw[k];
275
+ }
276
+ await fs.writeFile(lockPath, JSON.stringify(sorted, null, 2));
277
+ }
278
+ }
279
+ }
280
+ function modelNamesIn(doc) {
281
+ const names = [];
282
+ if (isObject(doc.value.models)) {
283
+ names.push(...Object.keys(doc.value.models));
284
+ }
285
+ // Split-file model: the doc itself is the model definition; the name is the
286
+ // PascalCase form of the basename (e.g. `country.model.json` → `Country`,
287
+ // `actionOperation.model.json` → `ActionOperation`). Enums live in a
288
+ // separate namespace and are deliberately excluded — a model and an enum
289
+ // can share a name without collision.
290
+ if (doc.splitKind === 'model' && doc.splitName) {
291
+ names.push(pascalize(doc.splitName));
292
+ }
293
+ return names;
294
+ }
295
+ function locateModel(docs, modelName) {
296
+ for (const doc of docs) {
297
+ if (isObject(doc.value.models)) {
298
+ const models = doc.value.models;
299
+ const m = models[modelName];
300
+ if (isObject(m)) {
301
+ return { doc, model: m };
302
+ }
303
+ }
304
+ if (doc.splitKind === 'model' && doc.splitName && pascalize(doc.splitName) === modelName) {
305
+ // Split file: the doc.value itself is the model body.
306
+ return { doc, model: doc.value };
307
+ }
308
+ }
309
+ return null;
310
+ }
311
+ function pascalize(name) {
312
+ if (name.length === 0) {
313
+ return name;
314
+ }
315
+ return name[0].toUpperCase() + name.slice(1);
316
+ }
317
+ function updateModelTypeReferences(node, oldName, newName) {
318
+ let count = 0;
319
+ walk(node, (parent, key, value) => {
320
+ // A relation field carries `type: "<ModelName>"`. Walking every
321
+ // `"type": "<value>"` pair and matching by the model name is good enough
322
+ // here — model names are PascalCase and won't collide with scalar type
323
+ // strings ("String", "Boolean", ...) that share the same key.
324
+ if (key === 'type' && typeof value === 'string' && value === oldName && isObject(parent)) {
325
+ ;
326
+ parent[key] = newName;
327
+ count++;
328
+ }
329
+ });
330
+ return count;
331
+ }
332
+ function walk(node, visit) {
333
+ if (Array.isArray(node)) {
334
+ for (let i = 0; i < node.length; i++) {
335
+ visit(node, i, node[i]);
336
+ walk(node[i], visit);
337
+ }
338
+ }
339
+ else if (isObject(node)) {
340
+ for (const key of Object.keys(node)) {
341
+ const value = node[key];
342
+ visit(node, key, value);
343
+ walk(value, visit);
344
+ }
345
+ }
346
+ }
347
+ function isObject(value) {
348
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
349
+ }
350
+ function camelize(name) {
351
+ // Convert "Country" → "country", "ActionOperation" → "actionOperation".
352
+ if (name.length === 0) {
353
+ return name;
354
+ }
355
+ return name[0].toLowerCase() + name.slice(1);
356
+ }
357
+ function displayPath(filePath, projectPath) {
358
+ return path.relative(projectPath, filePath) || filePath;
359
+ }
360
+ async function collectLockfileDeletions(projectPath, oldBase, newBase) {
361
+ if (oldBase === newBase) {
362
+ return [];
363
+ }
364
+ const lockFile = await (0, generator_1.readLockFile)(path.join(projectPath, 'postxl-lock.json'));
365
+ if (!lockFile) {
366
+ return [];
367
+ }
368
+ const out = [];
369
+ // Match files that embed the camelCased old name as a whole word fragment in the basename.
370
+ const re = new RegExp(`(^|[/\\W_-])${escapeRegex(oldBase)}([\\W_.-]|$)`);
371
+ for (const [k] of lockFile) {
372
+ if (re.test(String(k))) {
373
+ out.push(String(k));
374
+ }
375
+ }
376
+ return out;
377
+ }
378
+ function escapeRegex(s) {
379
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
380
+ }
381
+ async function scanCustomBlockReferences(projectPath, ...needles) {
382
+ const lockFile = await (0, generator_1.readLockFile)(path.join(projectPath, 'postxl-lock.json'));
383
+ if (!lockFile) {
384
+ return [];
385
+ }
386
+ const out = [];
387
+ for (const [k] of lockFile) {
388
+ const absPath = path.join(projectPath, String(k));
389
+ let content;
390
+ try {
391
+ const buf = await fs.readFile(absPath);
392
+ if ((0, cli_helpers_1.looksBinary)(buf)) {
393
+ continue;
394
+ }
395
+ content = buf.toString('utf8');
396
+ }
397
+ catch {
398
+ continue;
399
+ }
400
+ if (!content.includes('@custom-start')) {
401
+ continue;
402
+ }
403
+ if (needles.some((n) => content.includes(n))) {
404
+ out.push(String(k).replace(/^\/+/, ''));
405
+ }
406
+ }
407
+ return out;
408
+ }