@postxl/cli 1.8.3 → 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,233 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.register = register;
4
+ const utils_1 = require("@postxl/utils");
5
+ const cli_helpers_1 = require("./helpers/cli-helpers");
6
+ const generate_ts_editor_1 = require("./helpers/generate-ts-editor");
7
+ const generators_registry_1 = require("./helpers/generators-registry");
8
+ function register(program) {
9
+ const cmd = program
10
+ .command('generators')
11
+ .summary('Manage the generators in generate.ts.')
12
+ .description(`Manage which PostXL generators are enabled in generate.ts.
13
+
14
+ Use the subcommands to list, add, remove, or configure generators without
15
+ hand-editing the TypeScript file. The command refuses to operate on a
16
+ heavily customized generate.ts and falls back to suggesting a manual edit.`);
17
+ cmd
18
+ .command('list')
19
+ .argument('[path]', 'Path to project directory. Default is current directory', process.cwd())
20
+ .option('-j, --json', 'machine-readable output')
21
+ .action(async (inputPath, options) => {
22
+ const parsed = await parseOrExit(inputPath, program);
23
+ if (options.json) {
24
+ process.stdout.write(JSON.stringify(buildListJson(parsed), null, 2) + '\n');
25
+ return;
26
+ }
27
+ printList(parsed);
28
+ });
29
+ cmd
30
+ .command('add')
31
+ .argument('<name>', 'Generator name (e.g. backend-actions, frontend-admin)')
32
+ .argument('[path]', 'Path to project directory. Default is current directory', process.cwd())
33
+ .option('--dry-run', 'preview the change to generate.ts without writing')
34
+ .action(async (name, inputPath, options) => {
35
+ const parsed = await parseOrExit(inputPath ?? process.cwd(), program);
36
+ const result = (0, generate_ts_editor_1.addGenerator)(parsed, name);
37
+ if (!result.changed) {
38
+ if (result.reason) {
39
+ console.log((0, utils_1.yellow)(result.reason));
40
+ }
41
+ if (!generators_registry_1.RECOGNIZED_NAMES.includes(name)) {
42
+ console.log(`Recognized names: ${generators_registry_1.RECOGNIZED_NAMES.join(', ')}`);
43
+ process.exit(2);
44
+ }
45
+ return;
46
+ }
47
+ if (options.dryRun) {
48
+ printDryRunPreview(parsed, `add "${name}"`);
49
+ return;
50
+ }
51
+ await (0, generate_ts_editor_1.saveGenerateTs)(parsed);
52
+ console.log((0, utils_1.green)(`Added generator "${name}" to ${parsed.filePath}.`));
53
+ });
54
+ cmd
55
+ .command('remove')
56
+ .argument('<name>', 'Generator name')
57
+ .argument('[path]', 'Path to project directory. Default is current directory', process.cwd())
58
+ .option('--dry-run', 'preview the change to generate.ts without writing')
59
+ .action(async (name, inputPath, options) => {
60
+ const parsed = await parseOrExit(inputPath ?? process.cwd(), program);
61
+ const result = (0, generate_ts_editor_1.removeGenerator)(parsed, name);
62
+ if (!result.changed) {
63
+ if (result.reason) {
64
+ console.log((0, utils_1.yellow)(result.reason));
65
+ }
66
+ return;
67
+ }
68
+ if (options.dryRun) {
69
+ printDryRunPreview(parsed, `remove "${name}"`);
70
+ return;
71
+ }
72
+ await (0, generate_ts_editor_1.saveGenerateTs)(parsed);
73
+ console.log((0, utils_1.green)(`Removed generator "${name}" from ${parsed.filePath}.`));
74
+ });
75
+ cmd
76
+ .command('configure')
77
+ .argument('<name>', 'Generator name (must be a configure-style generator like backend-mail or devops)')
78
+ .argument('[path]', 'Path to project directory. Default is current directory', process.cwd())
79
+ .option('--options <objectLiteral>', "Replacement options as a JS object literal, e.g. \"{ adapters: ['log', 'smtp'] }\"")
80
+ .option('--dry-run', 'preview the change to generate.ts without writing')
81
+ .action(async (name, inputPath, options) => {
82
+ const reg = (0, generators_registry_1.findRegistryByName)(name);
83
+ if (!reg || reg.kind !== 'configure') {
84
+ program.error(`Generator "${name}" is not configurable. Configurable generators: ${generators_registry_1.GENERATOR_REGISTRY.filter((g) => g.kind === 'configure')
85
+ .map((g) => g.name)
86
+ .join(', ')}`, { exitCode: 2 });
87
+ }
88
+ if (!options.options) {
89
+ program.error('Provide options via --options "{ ... }"', { exitCode: 2 });
90
+ }
91
+ const parsed = await parseOrExit(inputPath ?? process.cwd(), program);
92
+ const result = (0, generate_ts_editor_1.configureGenerator)(parsed, name, options.options);
93
+ if (!result.changed) {
94
+ if (result.reason) {
95
+ console.log((0, utils_1.yellow)(result.reason));
96
+ }
97
+ return;
98
+ }
99
+ if (options.dryRun) {
100
+ printDryRunPreview(parsed, `configure "${name}"`);
101
+ return;
102
+ }
103
+ await (0, generate_ts_editor_1.saveGenerateTs)(parsed);
104
+ console.log((0, utils_1.green)(`Updated configuration for "${name}" in ${parsed.filePath}.`));
105
+ });
106
+ cmd
107
+ .command('preset')
108
+ .argument('<preset>', `Preset to apply (${Object.keys(generators_registry_1.PRESETS).join(', ')})`)
109
+ .argument('[path]', 'Path to project directory. Default is current directory', process.cwd())
110
+ .option('--dry-run', 'preview the change to generate.ts without writing')
111
+ .action(async (presetName, inputPath, options) => {
112
+ const target = generators_registry_1.PRESETS[presetName];
113
+ if (!target) {
114
+ program.error(`Unknown preset "${presetName}". Available: ${Object.keys(generators_registry_1.PRESETS).join(', ')}`, { exitCode: 2 });
115
+ }
116
+ const parsed = await parseOrExit(inputPath ?? process.cwd(), program);
117
+ // Apply the preset: ensure all entries in `target` are present; remove any
118
+ // recognized entries that aren't in the preset. Untracked/unknown entries are
119
+ // left alone — those represent custom user calls we can't safely remove.
120
+ const enabled = new Set(parsed.entries.flatMap((e) => (e.kind !== 'unknown' ? [e.name] : [])));
121
+ let changes = 0;
122
+ for (const name of target) {
123
+ if (!enabled.has(name)) {
124
+ const r = (0, generate_ts_editor_1.addGenerator)(parsed, name);
125
+ if (r.changed) {
126
+ changes++;
127
+ }
128
+ }
129
+ }
130
+ // Remove anything recognized but not in the preset.
131
+ const toRemove = [...enabled].filter((n) => !target.includes(n));
132
+ for (const name of toRemove) {
133
+ const r = (0, generate_ts_editor_1.removeGenerator)(parsed, name);
134
+ if (r.changed) {
135
+ changes++;
136
+ }
137
+ }
138
+ if (changes === 0) {
139
+ console.log((0, utils_1.yellow)(`No changes — generate.ts already matches preset "${presetName}".`));
140
+ return;
141
+ }
142
+ if (options.dryRun) {
143
+ printDryRunPreview(parsed, `preset "${presetName}" (${changes} change${changes === 1 ? '' : 's'})`);
144
+ return;
145
+ }
146
+ await (0, generate_ts_editor_1.saveGenerateTs)(parsed);
147
+ console.log((0, utils_1.green)(`Applied preset "${presetName}" (${changes} change${changes === 1 ? '' : 's'}).`));
148
+ });
149
+ }
150
+ /**
151
+ * Render a dry-run summary: print the new file content so the user can
152
+ * eyeball it before committing. Keeps the editor's in-memory state, doesn't
153
+ * touch disk.
154
+ */
155
+ function printDryRunPreview(parsed, label) {
156
+ console.log((0, utils_1.yellow)(`Dry run: ${label}. No changes written.`));
157
+ console.log();
158
+ console.log((0, utils_1.gray)(`--- ${parsed.filePath} (preview) ---`));
159
+ console.log(parsed.sourceFile.getFullText());
160
+ console.log((0, utils_1.gray)('--- end preview ---'));
161
+ }
162
+ async function parseOrExit(inputPath, program) {
163
+ const projectPath = await (0, cli_helpers_1.resolveProjectPath)(inputPath, program);
164
+ try {
165
+ return await (0, generate_ts_editor_1.parseGenerateTs)(projectPath);
166
+ }
167
+ catch (e) {
168
+ if (e instanceof generate_ts_editor_1.GenerateTsParseError) {
169
+ program.error(e.message, { exitCode: 2 });
170
+ }
171
+ throw e;
172
+ }
173
+ }
174
+ function buildListJson(parsed) {
175
+ const enabled = [];
176
+ for (const e of parsed.entries) {
177
+ if (e.kind === 'identifier') {
178
+ enabled.push({ name: e.name, kind: 'identifier' });
179
+ }
180
+ else if (e.kind === 'configure') {
181
+ enabled.push({
182
+ name: e.name,
183
+ kind: 'configure',
184
+ ...(e.optionsText !== undefined ? { options: e.optionsText } : {}),
185
+ });
186
+ }
187
+ else {
188
+ enabled.push({ name: '<unknown>', kind: 'unknown', text: e.text });
189
+ }
190
+ }
191
+ const enabledNames = new Set(enabled.filter((e) => e.kind !== 'unknown').map((e) => e.name));
192
+ const disabled = generators_registry_1.RECOGNIZED_NAMES.filter((n) => !enabledNames.has(n));
193
+ return { enabled, disabled };
194
+ }
195
+ function printList(parsed) {
196
+ const recognized = parsed.entries.filter((e) => e.kind !== 'unknown');
197
+ const unknown = parsed.entries.filter((e) => e.kind === 'unknown');
198
+ console.log((0, utils_1.green)(`Enabled (${recognized.length}):`));
199
+ for (const entry of recognized) {
200
+ if (entry.kind === 'configure') {
201
+ const opts = entry.optionsText ? ` ${(0, utils_1.gray)(formatOptions(entry.optionsText))}` : '';
202
+ console.log(` ${entry.name}${opts}`);
203
+ }
204
+ else {
205
+ console.log(` ${entry.name}`);
206
+ }
207
+ }
208
+ if (unknown.length > 0) {
209
+ console.log();
210
+ console.log((0, utils_1.yellow)(`Unrecognized entries (${unknown.length}) — left alone:`));
211
+ for (const e of unknown) {
212
+ console.log(` ${(0, utils_1.gray)(truncate(e.text, 80))}`);
213
+ }
214
+ }
215
+ const enabledNames = new Set(recognized.map((e) => e.name));
216
+ const disabled = generators_registry_1.RECOGNIZED_NAMES.filter((n) => !enabledNames.has(n));
217
+ if (disabled.length > 0) {
218
+ console.log();
219
+ console.log((0, utils_1.red)(`Disabled (${disabled.length}):`));
220
+ console.log(` ${disabled.join(', ')}`);
221
+ }
222
+ }
223
+ function formatOptions(text) {
224
+ // Strip braces & whitespace for a one-liner like (key: val, key2: val2).
225
+ const inner = text
226
+ .replace(/^\s*\{|\}\s*$/g, '')
227
+ .trim()
228
+ .replace(/\s+/g, ' ');
229
+ return `(${inner})`;
230
+ }
231
+ function truncate(text, max) {
232
+ return text.length <= max ? text : text.slice(0, max - 1) + '…';
233
+ }
@@ -0,0 +1,18 @@
1
+ import { Command } from 'commander';
2
+ /**
3
+ * Resolve a `[path]` argument from a CLI command to an absolute project
4
+ * directory, or exit with code 2 if the path is missing or not a directory.
5
+ *
6
+ * Every introspection command takes the same `[path]` argument with the same
7
+ * "must be a directory" semantics, so the resolution lives here.
8
+ */
9
+ export declare function resolveProjectPath(inputPath: string, program: Command): Promise<string>;
10
+ export declare function fileExists(p: string): Promise<boolean>;
11
+ /**
12
+ * Number of bytes to read from the start of a file when sniffing for binary
13
+ * content (NUL byte = binary, used to skip files that aren't worth scanning
14
+ * for custom blocks or running checksum comparisons against). Shared so all
15
+ * call sites use the same threshold.
16
+ */
17
+ export declare const BINARY_SNIFF_BYTES = 4096;
18
+ export declare function looksBinary(buf: Buffer): boolean;
@@ -0,0 +1,89 @@
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.BINARY_SNIFF_BYTES = void 0;
37
+ exports.resolveProjectPath = resolveProjectPath;
38
+ exports.fileExists = fileExists;
39
+ exports.looksBinary = looksBinary;
40
+ const fs = __importStar(require("node:fs/promises"));
41
+ const path = __importStar(require("node:path"));
42
+ /**
43
+ * Resolve a `[path]` argument from a CLI command to an absolute project
44
+ * directory, or exit with code 2 if the path is missing or not a directory.
45
+ *
46
+ * Every introspection command takes the same `[path]` argument with the same
47
+ * "must be a directory" semantics, so the resolution lives here.
48
+ */
49
+ async function resolveProjectPath(inputPath, program) {
50
+ let resolved = inputPath;
51
+ if (!path.isAbsolute(resolved)) {
52
+ resolved = path.resolve(process.cwd(), resolved);
53
+ }
54
+ try {
55
+ const stats = await fs.stat(resolved);
56
+ if (!stats.isDirectory()) {
57
+ program.error(`Path ${resolved} is not a directory!`, { exitCode: 2 });
58
+ }
59
+ }
60
+ catch {
61
+ program.error(`Cannot find path ${resolved}!`, { exitCode: 2 });
62
+ }
63
+ return resolved;
64
+ }
65
+ async function fileExists(p) {
66
+ try {
67
+ await fs.access(p);
68
+ return true;
69
+ }
70
+ catch {
71
+ return false;
72
+ }
73
+ }
74
+ /**
75
+ * Number of bytes to read from the start of a file when sniffing for binary
76
+ * content (NUL byte = binary, used to skip files that aren't worth scanning
77
+ * for custom blocks or running checksum comparisons against). Shared so all
78
+ * call sites use the same threshold.
79
+ */
80
+ exports.BINARY_SNIFF_BYTES = 4096;
81
+ function looksBinary(buf) {
82
+ const slice = buf.subarray(0, Math.min(buf.length, exports.BINARY_SNIFF_BYTES));
83
+ for (const byte of slice) {
84
+ if (byte === 0) {
85
+ return true;
86
+ }
87
+ }
88
+ return false;
89
+ }
@@ -0,0 +1,76 @@
1
+ import { ArrayLiteralExpression, CallExpression, Identifier, Node, Project, PropertyAccessExpression, SourceFile } from 'ts-morph';
2
+ import { type RegistryEntry } from './generators-registry';
3
+ /**
4
+ * One entry in the array literal of `generate.ts`. Either a plain identifier
5
+ * reference (e.g. `backendGenerator`), a recognized configure call
6
+ * (e.g. `configureBackendMailGenerator({ adapters: ['log'] })`), or an
7
+ * unknown expression we don't try to interpret.
8
+ */
9
+ export type GenerateTsEntry = {
10
+ kind: 'identifier';
11
+ name: string;
12
+ registry: RegistryEntry;
13
+ node: Identifier | PropertyAccessExpression;
14
+ } | {
15
+ kind: 'configure';
16
+ name: string;
17
+ registry: RegistryEntry;
18
+ optionsText: string | undefined;
19
+ node: CallExpression;
20
+ } | {
21
+ kind: 'unknown';
22
+ text: string;
23
+ node: Node;
24
+ };
25
+ export type ParsedGenerateTs = {
26
+ filePath: string;
27
+ sourceFile: SourceFile;
28
+ arrayLiteral: ArrayLiteralExpression;
29
+ entries: GenerateTsEntry[];
30
+ /**
31
+ * The Project instance — keep around so the same edit session can save the
32
+ * file. (ts-morph reuses TypeScript's module resolution machinery and is
33
+ * not cheap to construct.)
34
+ */
35
+ project: Project;
36
+ };
37
+ export declare class GenerateTsParseError extends Error {
38
+ constructor(message: string);
39
+ }
40
+ /**
41
+ * Read and parse a project's `generate.ts`. Returns the array literal that
42
+ * holds the generator list along with a structured view of each entry.
43
+ *
44
+ * Refuses (throws {@link GenerateTsParseError}) when the file is too custom
45
+ * for safe automated edits — anything beyond `export default function () {
46
+ * return [<calls>] }` (or the equivalent `export default () => [...]`).
47
+ */
48
+ export declare function parseGenerateTs(projectPath: string): Promise<ParsedGenerateTs>;
49
+ /**
50
+ * Append a generator entry to the array. Inserts an import if needed.
51
+ * Returns true if the file was modified. No-ops (returns false) if the
52
+ * generator is already present.
53
+ */
54
+ export declare function addGenerator(parsed: ParsedGenerateTs, name: string): {
55
+ changed: boolean;
56
+ reason?: string;
57
+ };
58
+ /**
59
+ * Remove the entry whose name matches. Removes the import too if no other
60
+ * reference remains in the source.
61
+ */
62
+ export declare function removeGenerator(parsed: ParsedGenerateTs, name: string): {
63
+ changed: boolean;
64
+ reason?: string;
65
+ };
66
+ /**
67
+ * Replace the options object of a configure-style generator. The options text
68
+ * must parse as a single object-literal expression — we validate it through
69
+ * ts-morph before substituting so a malformed `--options` flag can't
70
+ * silently corrupt `generate.ts`.
71
+ */
72
+ export declare function configureGenerator(parsed: ParsedGenerateTs, name: string, optionsObjectLiteral: string): {
73
+ changed: boolean;
74
+ reason?: string;
75
+ };
76
+ export declare function saveGenerateTs(parsed: ParsedGenerateTs): Promise<void>;