@conloca/cli 0.1.16 → 0.2.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.
- package/README.md +145 -29
- package/dist/conloca.js +3742 -216
- package/package.json +65 -8
package/dist/conloca.js
CHANGED
|
@@ -1,63 +1,3333 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
//
|
|
3
|
-
|
|
2
|
+
// ../../node_modules/.bun/commander@15.0.0/node_modules/commander/lib/error.js
|
|
3
|
+
class CommanderError extends Error {
|
|
4
|
+
constructor(exitCode, code, message) {
|
|
5
|
+
super(message);
|
|
6
|
+
Error.captureStackTrace(this, this.constructor);
|
|
7
|
+
this.name = this.constructor.name;
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.exitCode = exitCode;
|
|
10
|
+
this.nestedError = undefined;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
class InvalidArgumentError extends CommanderError {
|
|
15
|
+
constructor(message) {
|
|
16
|
+
super(1, "commander.invalidArgument", message);
|
|
17
|
+
Error.captureStackTrace(this, this.constructor);
|
|
18
|
+
this.name = this.constructor.name;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// ../../node_modules/.bun/commander@15.0.0/node_modules/commander/lib/argument.js
|
|
23
|
+
class Argument {
|
|
24
|
+
constructor(name, description) {
|
|
25
|
+
this.description = description || "";
|
|
26
|
+
this.variadic = false;
|
|
27
|
+
this.parseArg = undefined;
|
|
28
|
+
this.defaultValue = undefined;
|
|
29
|
+
this.defaultValueDescription = undefined;
|
|
30
|
+
this.argChoices = undefined;
|
|
31
|
+
switch (name[0]) {
|
|
32
|
+
case "<":
|
|
33
|
+
this.required = true;
|
|
34
|
+
this._name = name.slice(1, -1);
|
|
35
|
+
break;
|
|
36
|
+
case "[":
|
|
37
|
+
this.required = false;
|
|
38
|
+
this._name = name.slice(1, -1);
|
|
39
|
+
break;
|
|
40
|
+
default:
|
|
41
|
+
this.required = true;
|
|
42
|
+
this._name = name;
|
|
43
|
+
break;
|
|
44
|
+
}
|
|
45
|
+
if (this._name.endsWith("...")) {
|
|
46
|
+
this.variadic = true;
|
|
47
|
+
this._name = this._name.slice(0, -3);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
name() {
|
|
51
|
+
return this._name;
|
|
52
|
+
}
|
|
53
|
+
_collectValue(value, previous) {
|
|
54
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
55
|
+
return [value];
|
|
56
|
+
}
|
|
57
|
+
previous.push(value);
|
|
58
|
+
return previous;
|
|
59
|
+
}
|
|
60
|
+
default(value, description) {
|
|
61
|
+
this.defaultValue = value;
|
|
62
|
+
this.defaultValueDescription = description;
|
|
63
|
+
return this;
|
|
64
|
+
}
|
|
65
|
+
argParser(fn) {
|
|
66
|
+
this.parseArg = fn;
|
|
67
|
+
return this;
|
|
68
|
+
}
|
|
69
|
+
choices(values) {
|
|
70
|
+
this.argChoices = values.slice();
|
|
71
|
+
this.parseArg = (arg, previous) => {
|
|
72
|
+
if (!this.argChoices.includes(arg)) {
|
|
73
|
+
throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
74
|
+
}
|
|
75
|
+
if (this.variadic) {
|
|
76
|
+
return this._collectValue(arg, previous);
|
|
77
|
+
}
|
|
78
|
+
return arg;
|
|
79
|
+
};
|
|
80
|
+
return this;
|
|
81
|
+
}
|
|
82
|
+
argRequired() {
|
|
83
|
+
this.required = true;
|
|
84
|
+
return this;
|
|
85
|
+
}
|
|
86
|
+
argOptional() {
|
|
87
|
+
this.required = false;
|
|
88
|
+
return this;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
function humanReadableArgName(arg) {
|
|
92
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
93
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// ../../node_modules/.bun/commander@15.0.0/node_modules/commander/lib/command.js
|
|
97
|
+
import { EventEmitter } from "node:events";
|
|
98
|
+
import childProcess from "node:child_process";
|
|
99
|
+
import path from "node:path";
|
|
100
|
+
import fs from "node:fs";
|
|
101
|
+
import process2 from "node:process";
|
|
102
|
+
import { stripVTControlCharacters as stripVTControlCharacters2 } from "node:util";
|
|
103
|
+
|
|
104
|
+
// ../../node_modules/.bun/commander@15.0.0/node_modules/commander/lib/help.js
|
|
105
|
+
import { stripVTControlCharacters } from "node:util";
|
|
106
|
+
|
|
107
|
+
class Help {
|
|
108
|
+
constructor() {
|
|
109
|
+
this.helpWidth = undefined;
|
|
110
|
+
this.minWidthToWrap = 40;
|
|
111
|
+
this.sortSubcommands = false;
|
|
112
|
+
this.sortOptions = false;
|
|
113
|
+
this.showGlobalOptions = false;
|
|
114
|
+
}
|
|
115
|
+
prepareContext(contextOptions) {
|
|
116
|
+
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
|
|
117
|
+
}
|
|
118
|
+
visibleCommands(cmd) {
|
|
119
|
+
const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
|
|
120
|
+
const helpCommand = cmd._getHelpCommand();
|
|
121
|
+
if (helpCommand && !helpCommand._hidden) {
|
|
122
|
+
visibleCommands.push(helpCommand);
|
|
123
|
+
}
|
|
124
|
+
if (this.sortSubcommands) {
|
|
125
|
+
visibleCommands.sort((a, b) => {
|
|
126
|
+
return a.name().localeCompare(b.name());
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
return visibleCommands;
|
|
130
|
+
}
|
|
131
|
+
compareOptions(a, b) {
|
|
132
|
+
const getSortKey = (option) => {
|
|
133
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
134
|
+
};
|
|
135
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
136
|
+
}
|
|
137
|
+
visibleOptions(cmd) {
|
|
138
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
139
|
+
const helpOption = cmd._getHelpOption();
|
|
140
|
+
if (helpOption && !helpOption.hidden) {
|
|
141
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
142
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
143
|
+
if (!removeShort && !removeLong) {
|
|
144
|
+
visibleOptions.push(helpOption);
|
|
145
|
+
} else if (helpOption.long && !removeLong) {
|
|
146
|
+
visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
|
|
147
|
+
} else if (helpOption.short && !removeShort) {
|
|
148
|
+
visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
if (this.sortOptions) {
|
|
152
|
+
visibleOptions.sort(this.compareOptions);
|
|
153
|
+
}
|
|
154
|
+
return visibleOptions;
|
|
155
|
+
}
|
|
156
|
+
visibleGlobalOptions(cmd) {
|
|
157
|
+
if (!this.showGlobalOptions)
|
|
158
|
+
return [];
|
|
159
|
+
const globalOptions = [];
|
|
160
|
+
for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
161
|
+
const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
|
|
162
|
+
globalOptions.push(...visibleOptions);
|
|
163
|
+
}
|
|
164
|
+
if (this.sortOptions) {
|
|
165
|
+
globalOptions.sort(this.compareOptions);
|
|
166
|
+
}
|
|
167
|
+
return globalOptions;
|
|
168
|
+
}
|
|
169
|
+
visibleArguments(cmd) {
|
|
170
|
+
if (cmd._argsDescription) {
|
|
171
|
+
cmd.registeredArguments.forEach((argument) => {
|
|
172
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) {
|
|
176
|
+
return cmd.registeredArguments;
|
|
177
|
+
}
|
|
178
|
+
return [];
|
|
179
|
+
}
|
|
180
|
+
subcommandTerm(cmd) {
|
|
181
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
182
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
|
|
183
|
+
}
|
|
184
|
+
optionTerm(option) {
|
|
185
|
+
return option.flags;
|
|
186
|
+
}
|
|
187
|
+
argumentTerm(argument) {
|
|
188
|
+
return argument.name();
|
|
189
|
+
}
|
|
190
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
191
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
192
|
+
return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
|
|
193
|
+
}, 0);
|
|
194
|
+
}
|
|
195
|
+
longestOptionTermLength(cmd, helper) {
|
|
196
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
197
|
+
return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
|
|
198
|
+
}, 0);
|
|
199
|
+
}
|
|
200
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
201
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
202
|
+
return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
|
|
203
|
+
}, 0);
|
|
204
|
+
}
|
|
205
|
+
longestArgumentTermLength(cmd, helper) {
|
|
206
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
207
|
+
return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
|
|
208
|
+
}, 0);
|
|
209
|
+
}
|
|
210
|
+
commandUsage(cmd) {
|
|
211
|
+
let cmdName = cmd._name;
|
|
212
|
+
if (cmd._aliases[0]) {
|
|
213
|
+
cmdName = cmdName + "|" + cmd._aliases[0];
|
|
214
|
+
}
|
|
215
|
+
let ancestorCmdNames = "";
|
|
216
|
+
for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
217
|
+
ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
218
|
+
}
|
|
219
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
220
|
+
}
|
|
221
|
+
commandDescription(cmd) {
|
|
222
|
+
return cmd.description();
|
|
223
|
+
}
|
|
224
|
+
subcommandDescription(cmd) {
|
|
225
|
+
return cmd.summary() || cmd.description();
|
|
226
|
+
}
|
|
227
|
+
optionDescription(option) {
|
|
228
|
+
const extraInfo = [];
|
|
229
|
+
if (option.argChoices) {
|
|
230
|
+
extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
|
|
231
|
+
}
|
|
232
|
+
if (option.defaultValue !== undefined) {
|
|
233
|
+
const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
|
|
234
|
+
if (showDefault) {
|
|
235
|
+
extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
if (option.presetArg !== undefined && option.optional) {
|
|
239
|
+
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
240
|
+
}
|
|
241
|
+
if (option.envVar !== undefined) {
|
|
242
|
+
extraInfo.push(`env: ${option.envVar}`);
|
|
243
|
+
}
|
|
244
|
+
if (extraInfo.length > 0) {
|
|
245
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
246
|
+
if (option.description) {
|
|
247
|
+
return `${option.description} ${extraDescription}`;
|
|
248
|
+
}
|
|
249
|
+
return extraDescription;
|
|
250
|
+
}
|
|
251
|
+
return option.description;
|
|
252
|
+
}
|
|
253
|
+
argumentDescription(argument) {
|
|
254
|
+
const extraInfo = [];
|
|
255
|
+
if (argument.argChoices) {
|
|
256
|
+
extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
|
|
257
|
+
}
|
|
258
|
+
if (argument.defaultValue !== undefined) {
|
|
259
|
+
extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
|
|
260
|
+
}
|
|
261
|
+
if (extraInfo.length > 0) {
|
|
262
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
263
|
+
if (argument.description) {
|
|
264
|
+
return `${argument.description} ${extraDescription}`;
|
|
265
|
+
}
|
|
266
|
+
return extraDescription;
|
|
267
|
+
}
|
|
268
|
+
return argument.description;
|
|
269
|
+
}
|
|
270
|
+
formatItemList(heading, items, helper) {
|
|
271
|
+
if (items.length === 0)
|
|
272
|
+
return [];
|
|
273
|
+
return [helper.styleTitle(heading), ...items, ""];
|
|
274
|
+
}
|
|
275
|
+
groupItems(unsortedItems, visibleItems, getGroup) {
|
|
276
|
+
const result = new Map;
|
|
277
|
+
unsortedItems.forEach((item) => {
|
|
278
|
+
const group = getGroup(item);
|
|
279
|
+
if (!result.has(group))
|
|
280
|
+
result.set(group, []);
|
|
281
|
+
});
|
|
282
|
+
visibleItems.forEach((item) => {
|
|
283
|
+
const group = getGroup(item);
|
|
284
|
+
if (!result.has(group)) {
|
|
285
|
+
result.set(group, []);
|
|
286
|
+
}
|
|
287
|
+
result.get(group).push(item);
|
|
288
|
+
});
|
|
289
|
+
return result;
|
|
290
|
+
}
|
|
291
|
+
formatHelp(cmd, helper) {
|
|
292
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
293
|
+
const helpWidth = helper.helpWidth ?? 80;
|
|
294
|
+
function callFormatItem(term, description) {
|
|
295
|
+
return helper.formatItem(term, termWidth, description, helper);
|
|
296
|
+
}
|
|
297
|
+
let output = [
|
|
298
|
+
`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
|
|
299
|
+
""
|
|
300
|
+
];
|
|
301
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
302
|
+
if (commandDescription.length > 0) {
|
|
303
|
+
output = output.concat([
|
|
304
|
+
helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
|
|
305
|
+
""
|
|
306
|
+
]);
|
|
307
|
+
}
|
|
308
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
309
|
+
return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
|
|
310
|
+
});
|
|
311
|
+
output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
|
|
312
|
+
const optionGroups = this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:");
|
|
313
|
+
optionGroups.forEach((options, group) => {
|
|
314
|
+
const optionList = options.map((option) => {
|
|
315
|
+
return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
|
|
316
|
+
});
|
|
317
|
+
output = output.concat(this.formatItemList(group, optionList, helper));
|
|
318
|
+
});
|
|
319
|
+
if (helper.showGlobalOptions) {
|
|
320
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
321
|
+
return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
|
|
322
|
+
});
|
|
323
|
+
output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
|
|
324
|
+
}
|
|
325
|
+
const commandGroups = this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:");
|
|
326
|
+
commandGroups.forEach((commands, group) => {
|
|
327
|
+
const commandList = commands.map((sub) => {
|
|
328
|
+
return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
|
|
329
|
+
});
|
|
330
|
+
output = output.concat(this.formatItemList(group, commandList, helper));
|
|
331
|
+
});
|
|
332
|
+
return output.join(`
|
|
333
|
+
`);
|
|
334
|
+
}
|
|
335
|
+
displayWidth(str) {
|
|
336
|
+
return stripVTControlCharacters(str).length;
|
|
337
|
+
}
|
|
338
|
+
styleTitle(str) {
|
|
339
|
+
return str;
|
|
340
|
+
}
|
|
341
|
+
styleUsage(str) {
|
|
342
|
+
return str.split(" ").map((word) => {
|
|
343
|
+
if (word === "[options]")
|
|
344
|
+
return this.styleOptionText(word);
|
|
345
|
+
if (word === "[command]")
|
|
346
|
+
return this.styleSubcommandText(word);
|
|
347
|
+
if (word[0] === "[" || word[0] === "<")
|
|
348
|
+
return this.styleArgumentText(word);
|
|
349
|
+
return this.styleCommandText(word);
|
|
350
|
+
}).join(" ");
|
|
351
|
+
}
|
|
352
|
+
styleCommandDescription(str) {
|
|
353
|
+
return this.styleDescriptionText(str);
|
|
354
|
+
}
|
|
355
|
+
styleOptionDescription(str) {
|
|
356
|
+
return this.styleDescriptionText(str);
|
|
357
|
+
}
|
|
358
|
+
styleSubcommandDescription(str) {
|
|
359
|
+
return this.styleDescriptionText(str);
|
|
360
|
+
}
|
|
361
|
+
styleArgumentDescription(str) {
|
|
362
|
+
return this.styleDescriptionText(str);
|
|
363
|
+
}
|
|
364
|
+
styleDescriptionText(str) {
|
|
365
|
+
return str;
|
|
366
|
+
}
|
|
367
|
+
styleOptionTerm(str) {
|
|
368
|
+
return this.styleOptionText(str);
|
|
369
|
+
}
|
|
370
|
+
styleSubcommandTerm(str) {
|
|
371
|
+
return str.split(" ").map((word) => {
|
|
372
|
+
if (word === "[options]")
|
|
373
|
+
return this.styleOptionText(word);
|
|
374
|
+
if (word[0] === "[" || word[0] === "<")
|
|
375
|
+
return this.styleArgumentText(word);
|
|
376
|
+
return this.styleSubcommandText(word);
|
|
377
|
+
}).join(" ");
|
|
378
|
+
}
|
|
379
|
+
styleArgumentTerm(str) {
|
|
380
|
+
return this.styleArgumentText(str);
|
|
381
|
+
}
|
|
382
|
+
styleOptionText(str) {
|
|
383
|
+
return str;
|
|
384
|
+
}
|
|
385
|
+
styleArgumentText(str) {
|
|
386
|
+
return str;
|
|
387
|
+
}
|
|
388
|
+
styleSubcommandText(str) {
|
|
389
|
+
return str;
|
|
390
|
+
}
|
|
391
|
+
styleCommandText(str) {
|
|
392
|
+
return str;
|
|
393
|
+
}
|
|
394
|
+
padWidth(cmd, helper) {
|
|
395
|
+
return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
|
|
396
|
+
}
|
|
397
|
+
preformatted(str) {
|
|
398
|
+
return /\n[^\S\r\n]/.test(str);
|
|
399
|
+
}
|
|
400
|
+
formatItem(term, termWidth, description, helper) {
|
|
401
|
+
const itemIndent = 2;
|
|
402
|
+
const itemIndentStr = " ".repeat(itemIndent);
|
|
403
|
+
if (!description)
|
|
404
|
+
return itemIndentStr + term;
|
|
405
|
+
const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
|
|
406
|
+
const spacerWidth = 2;
|
|
407
|
+
const helpWidth = this.helpWidth ?? 80;
|
|
408
|
+
const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
|
|
409
|
+
let formattedDescription;
|
|
410
|
+
if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
|
|
411
|
+
formattedDescription = description;
|
|
412
|
+
} else {
|
|
413
|
+
const wrappedDescription = helper.boxWrap(description, remainingWidth);
|
|
414
|
+
formattedDescription = wrappedDescription.replace(/\n/g, `
|
|
415
|
+
` + " ".repeat(termWidth + spacerWidth));
|
|
416
|
+
}
|
|
417
|
+
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
|
|
418
|
+
${itemIndentStr}`);
|
|
419
|
+
}
|
|
420
|
+
boxWrap(str, width) {
|
|
421
|
+
if (width < this.minWidthToWrap)
|
|
422
|
+
return str;
|
|
423
|
+
const rawLines = str.split(/\r\n|\n/);
|
|
424
|
+
const chunkPattern = /[\s]*[^\s]+/g;
|
|
425
|
+
const wrappedLines = [];
|
|
426
|
+
rawLines.forEach((line) => {
|
|
427
|
+
const chunks = line.match(chunkPattern);
|
|
428
|
+
if (chunks === null) {
|
|
429
|
+
wrappedLines.push("");
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
let sumChunks = [chunks.shift()];
|
|
433
|
+
let sumWidth = this.displayWidth(sumChunks[0]);
|
|
434
|
+
chunks.forEach((chunk) => {
|
|
435
|
+
const visibleWidth = this.displayWidth(chunk);
|
|
436
|
+
if (sumWidth + visibleWidth <= width) {
|
|
437
|
+
sumChunks.push(chunk);
|
|
438
|
+
sumWidth += visibleWidth;
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
wrappedLines.push(sumChunks.join(""));
|
|
442
|
+
const nextChunk = chunk.trimStart();
|
|
443
|
+
sumChunks = [nextChunk];
|
|
444
|
+
sumWidth = this.displayWidth(nextChunk);
|
|
445
|
+
});
|
|
446
|
+
wrappedLines.push(sumChunks.join(""));
|
|
447
|
+
});
|
|
448
|
+
return wrappedLines.join(`
|
|
449
|
+
`);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// ../../node_modules/.bun/commander@15.0.0/node_modules/commander/lib/option.js
|
|
454
|
+
class Option {
|
|
455
|
+
constructor(flags, description) {
|
|
456
|
+
this.flags = flags;
|
|
457
|
+
this.description = description || "";
|
|
458
|
+
this.required = flags.includes("<");
|
|
459
|
+
this.optional = flags.includes("[");
|
|
460
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
461
|
+
this.mandatory = false;
|
|
462
|
+
const optionFlags = splitOptionFlags(flags);
|
|
463
|
+
this.short = optionFlags.shortFlag;
|
|
464
|
+
this.long = optionFlags.longFlag;
|
|
465
|
+
this.negate = false;
|
|
466
|
+
if (this.long) {
|
|
467
|
+
this.negate = this.long.startsWith("--no-");
|
|
468
|
+
}
|
|
469
|
+
this.defaultValue = undefined;
|
|
470
|
+
this.defaultValueDescription = undefined;
|
|
471
|
+
this.presetArg = undefined;
|
|
472
|
+
this.envVar = undefined;
|
|
473
|
+
this.parseArg = undefined;
|
|
474
|
+
this.hidden = false;
|
|
475
|
+
this.argChoices = undefined;
|
|
476
|
+
this.conflictsWith = [];
|
|
477
|
+
this.implied = undefined;
|
|
478
|
+
this.helpGroupHeading = undefined;
|
|
479
|
+
}
|
|
480
|
+
default(value, description) {
|
|
481
|
+
this.defaultValue = value;
|
|
482
|
+
this.defaultValueDescription = description;
|
|
483
|
+
return this;
|
|
484
|
+
}
|
|
485
|
+
preset(arg) {
|
|
486
|
+
this.presetArg = arg;
|
|
487
|
+
return this;
|
|
488
|
+
}
|
|
489
|
+
conflicts(names) {
|
|
490
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
491
|
+
return this;
|
|
492
|
+
}
|
|
493
|
+
implies(impliedOptionValues) {
|
|
494
|
+
let newImplied = impliedOptionValues;
|
|
495
|
+
if (typeof impliedOptionValues === "string") {
|
|
496
|
+
newImplied = { [impliedOptionValues]: true };
|
|
497
|
+
}
|
|
498
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
499
|
+
return this;
|
|
500
|
+
}
|
|
501
|
+
env(name) {
|
|
502
|
+
this.envVar = name;
|
|
503
|
+
return this;
|
|
504
|
+
}
|
|
505
|
+
argParser(fn) {
|
|
506
|
+
this.parseArg = fn;
|
|
507
|
+
return this;
|
|
508
|
+
}
|
|
509
|
+
makeOptionMandatory(mandatory = true) {
|
|
510
|
+
this.mandatory = !!mandatory;
|
|
511
|
+
return this;
|
|
512
|
+
}
|
|
513
|
+
hideHelp(hide = true) {
|
|
514
|
+
this.hidden = !!hide;
|
|
515
|
+
return this;
|
|
516
|
+
}
|
|
517
|
+
_collectValue(value, previous) {
|
|
518
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
519
|
+
return [value];
|
|
520
|
+
}
|
|
521
|
+
previous.push(value);
|
|
522
|
+
return previous;
|
|
523
|
+
}
|
|
524
|
+
choices(values) {
|
|
525
|
+
this.argChoices = values.slice();
|
|
526
|
+
this.parseArg = (arg, previous) => {
|
|
527
|
+
if (!this.argChoices.includes(arg)) {
|
|
528
|
+
throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
|
|
529
|
+
}
|
|
530
|
+
if (this.variadic) {
|
|
531
|
+
return this._collectValue(arg, previous);
|
|
532
|
+
}
|
|
533
|
+
return arg;
|
|
534
|
+
};
|
|
535
|
+
return this;
|
|
536
|
+
}
|
|
537
|
+
name() {
|
|
538
|
+
if (this.long) {
|
|
539
|
+
return this.long.replace(/^--/, "");
|
|
540
|
+
}
|
|
541
|
+
return this.short.replace(/^-/, "");
|
|
542
|
+
}
|
|
543
|
+
attributeName() {
|
|
544
|
+
if (this.negate) {
|
|
545
|
+
return camelcase(this.name().replace(/^no-/, ""));
|
|
546
|
+
}
|
|
547
|
+
return camelcase(this.name());
|
|
548
|
+
}
|
|
549
|
+
helpGroup(heading) {
|
|
550
|
+
this.helpGroupHeading = heading;
|
|
551
|
+
return this;
|
|
552
|
+
}
|
|
553
|
+
is(arg) {
|
|
554
|
+
return this.short === arg || this.long === arg;
|
|
555
|
+
}
|
|
556
|
+
isBoolean() {
|
|
557
|
+
return !this.required && !this.optional && !this.negate;
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
class DualOptions {
|
|
562
|
+
constructor(options) {
|
|
563
|
+
this.positiveOptions = new Map;
|
|
564
|
+
this.negativeOptions = new Map;
|
|
565
|
+
this.dualOptions = new Set;
|
|
566
|
+
options.forEach((option) => {
|
|
567
|
+
if (option.negate) {
|
|
568
|
+
this.negativeOptions.set(option.attributeName(), option);
|
|
569
|
+
} else {
|
|
570
|
+
this.positiveOptions.set(option.attributeName(), option);
|
|
571
|
+
}
|
|
572
|
+
});
|
|
573
|
+
this.negativeOptions.forEach((value, key) => {
|
|
574
|
+
if (this.positiveOptions.has(key)) {
|
|
575
|
+
this.dualOptions.add(key);
|
|
576
|
+
}
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
valueFromOption(value, option) {
|
|
580
|
+
const optionKey = option.attributeName();
|
|
581
|
+
if (!this.dualOptions.has(optionKey))
|
|
582
|
+
return true;
|
|
583
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
584
|
+
const negativeValue = preset !== undefined ? preset : false;
|
|
585
|
+
return option.negate === (negativeValue === value);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
function camelcase(str) {
|
|
589
|
+
return str.split("-").reduce((str, word) => {
|
|
590
|
+
return str + word[0].toUpperCase() + word.slice(1);
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
function splitOptionFlags(flags) {
|
|
594
|
+
let shortFlag;
|
|
595
|
+
let longFlag;
|
|
596
|
+
const shortFlagExp = /^-[^-]$/;
|
|
597
|
+
const longFlagExp = /^--[^-]/;
|
|
598
|
+
const flagParts = flags.split(/[ |,]+/).concat("guard");
|
|
599
|
+
if (shortFlagExp.test(flagParts[0]))
|
|
600
|
+
shortFlag = flagParts.shift();
|
|
601
|
+
if (longFlagExp.test(flagParts[0]))
|
|
602
|
+
longFlag = flagParts.shift();
|
|
603
|
+
if (!shortFlag && shortFlagExp.test(flagParts[0]))
|
|
604
|
+
shortFlag = flagParts.shift();
|
|
605
|
+
if (!shortFlag && longFlagExp.test(flagParts[0])) {
|
|
606
|
+
shortFlag = longFlag;
|
|
607
|
+
longFlag = flagParts.shift();
|
|
608
|
+
}
|
|
609
|
+
if (flagParts[0].startsWith("-")) {
|
|
610
|
+
const unsupportedFlag = flagParts[0];
|
|
611
|
+
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
|
|
612
|
+
if (/^-[^-][^-]/.test(unsupportedFlag))
|
|
613
|
+
throw new Error(`${baseError}
|
|
614
|
+
- a short flag is a single dash and a single character
|
|
615
|
+
- either use a single dash and a single character (for a short flag)
|
|
616
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
|
|
617
|
+
if (shortFlagExp.test(unsupportedFlag))
|
|
618
|
+
throw new Error(`${baseError}
|
|
619
|
+
- too many short flags`);
|
|
620
|
+
if (longFlagExp.test(unsupportedFlag))
|
|
621
|
+
throw new Error(`${baseError}
|
|
622
|
+
- too many long flags`);
|
|
623
|
+
throw new Error(`${baseError}
|
|
624
|
+
- unrecognised flag format`);
|
|
625
|
+
}
|
|
626
|
+
if (shortFlag === undefined && longFlag === undefined)
|
|
627
|
+
throw new Error(`option creation failed due to no flags found in '${flags}'.`);
|
|
628
|
+
return { shortFlag, longFlag };
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
// ../../node_modules/.bun/commander@15.0.0/node_modules/commander/lib/suggestSimilar.js
|
|
632
|
+
var maxDistance = 3;
|
|
633
|
+
function editDistance(a, b) {
|
|
634
|
+
if (Math.abs(a.length - b.length) > maxDistance)
|
|
635
|
+
return Math.max(a.length, b.length);
|
|
636
|
+
const d = [];
|
|
637
|
+
for (let i = 0;i <= a.length; i++) {
|
|
638
|
+
d[i] = [i];
|
|
639
|
+
}
|
|
640
|
+
for (let j = 0;j <= b.length; j++) {
|
|
641
|
+
d[0][j] = j;
|
|
642
|
+
}
|
|
643
|
+
for (let j = 1;j <= b.length; j++) {
|
|
644
|
+
for (let i = 1;i <= a.length; i++) {
|
|
645
|
+
let cost;
|
|
646
|
+
if (a[i - 1] === b[j - 1]) {
|
|
647
|
+
cost = 0;
|
|
648
|
+
} else {
|
|
649
|
+
cost = 1;
|
|
650
|
+
}
|
|
651
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
652
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
653
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
return d[a.length][b.length];
|
|
658
|
+
}
|
|
659
|
+
function suggestSimilar(word, candidates) {
|
|
660
|
+
if (!candidates || candidates.length === 0)
|
|
661
|
+
return "";
|
|
662
|
+
candidates = Array.from(new Set(candidates));
|
|
663
|
+
const searchingOptions = word.startsWith("--");
|
|
664
|
+
if (searchingOptions) {
|
|
665
|
+
word = word.slice(2);
|
|
666
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
667
|
+
}
|
|
668
|
+
let similar = [];
|
|
669
|
+
let bestDistance = maxDistance;
|
|
670
|
+
const minSimilarity = 0.4;
|
|
671
|
+
candidates.forEach((candidate) => {
|
|
672
|
+
if (candidate.length <= 1)
|
|
673
|
+
return;
|
|
674
|
+
const distance = editDistance(word, candidate);
|
|
675
|
+
const length = Math.max(word.length, candidate.length);
|
|
676
|
+
const similarity = (length - distance) / length;
|
|
677
|
+
if (similarity > minSimilarity) {
|
|
678
|
+
if (distance < bestDistance) {
|
|
679
|
+
bestDistance = distance;
|
|
680
|
+
similar = [candidate];
|
|
681
|
+
} else if (distance === bestDistance) {
|
|
682
|
+
similar.push(candidate);
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
});
|
|
686
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
687
|
+
if (searchingOptions) {
|
|
688
|
+
similar = similar.map((candidate) => `--${candidate}`);
|
|
689
|
+
}
|
|
690
|
+
if (similar.length > 1) {
|
|
691
|
+
return `
|
|
692
|
+
(Did you mean one of ${similar.join(", ")}?)`;
|
|
693
|
+
}
|
|
694
|
+
if (similar.length === 1) {
|
|
695
|
+
return `
|
|
696
|
+
(Did you mean ${similar[0]}?)`;
|
|
697
|
+
}
|
|
698
|
+
return "";
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
// ../../node_modules/.bun/commander@15.0.0/node_modules/commander/lib/command.js
|
|
702
|
+
class Command extends EventEmitter {
|
|
703
|
+
constructor(name) {
|
|
704
|
+
super();
|
|
705
|
+
this.commands = [];
|
|
706
|
+
this.options = [];
|
|
707
|
+
this.parent = null;
|
|
708
|
+
this._allowUnknownOption = false;
|
|
709
|
+
this._allowExcessArguments = false;
|
|
710
|
+
this.registeredArguments = [];
|
|
711
|
+
this._args = this.registeredArguments;
|
|
712
|
+
this.args = [];
|
|
713
|
+
this.rawArgs = [];
|
|
714
|
+
this.processedArgs = [];
|
|
715
|
+
this._scriptPath = null;
|
|
716
|
+
this._name = name || "";
|
|
717
|
+
this._optionValues = {};
|
|
718
|
+
this._optionValueSources = {};
|
|
719
|
+
this._storeOptionsAsProperties = false;
|
|
720
|
+
this._actionHandler = null;
|
|
721
|
+
this._executableHandler = false;
|
|
722
|
+
this._executableFile = null;
|
|
723
|
+
this._executableDir = null;
|
|
724
|
+
this._defaultCommandName = null;
|
|
725
|
+
this._exitCallback = null;
|
|
726
|
+
this._aliases = [];
|
|
727
|
+
this._combineFlagAndOptionalValue = true;
|
|
728
|
+
this._description = "";
|
|
729
|
+
this._summary = "";
|
|
730
|
+
this._argsDescription = undefined;
|
|
731
|
+
this._enablePositionalOptions = false;
|
|
732
|
+
this._passThroughOptions = false;
|
|
733
|
+
this._lifeCycleHooks = {};
|
|
734
|
+
this._showHelpAfterError = false;
|
|
735
|
+
this._showSuggestionAfterError = true;
|
|
736
|
+
this._savedState = null;
|
|
737
|
+
this._outputConfiguration = {
|
|
738
|
+
writeOut: (str) => process2.stdout.write(str),
|
|
739
|
+
writeErr: (str) => process2.stderr.write(str),
|
|
740
|
+
outputError: (str, write) => write(str),
|
|
741
|
+
getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
|
|
742
|
+
getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
|
|
743
|
+
getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
|
|
744
|
+
getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
|
|
745
|
+
stripColor: (str) => stripVTControlCharacters2(str)
|
|
746
|
+
};
|
|
747
|
+
this._hidden = false;
|
|
748
|
+
this._helpOption = undefined;
|
|
749
|
+
this._addImplicitHelpCommand = undefined;
|
|
750
|
+
this._helpCommand = undefined;
|
|
751
|
+
this._helpConfiguration = {};
|
|
752
|
+
this._helpGroupHeading = undefined;
|
|
753
|
+
this._defaultCommandGroup = undefined;
|
|
754
|
+
this._defaultOptionGroup = undefined;
|
|
755
|
+
}
|
|
756
|
+
copyInheritedSettings(sourceCommand) {
|
|
757
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
758
|
+
this._helpOption = sourceCommand._helpOption;
|
|
759
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
760
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
761
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
762
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
763
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
764
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
765
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
766
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
767
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
768
|
+
return this;
|
|
769
|
+
}
|
|
770
|
+
_getCommandAndAncestors() {
|
|
771
|
+
const result = [];
|
|
772
|
+
for (let command = this;command; command = command.parent) {
|
|
773
|
+
result.push(command);
|
|
774
|
+
}
|
|
775
|
+
return result;
|
|
776
|
+
}
|
|
777
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
778
|
+
let desc = actionOptsOrExecDesc;
|
|
779
|
+
let opts = execOpts;
|
|
780
|
+
if (typeof desc === "object" && desc !== null) {
|
|
781
|
+
opts = desc;
|
|
782
|
+
desc = null;
|
|
783
|
+
}
|
|
784
|
+
opts = opts || {};
|
|
785
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
786
|
+
const cmd = this.createCommand(name);
|
|
787
|
+
if (desc) {
|
|
788
|
+
cmd.description(desc);
|
|
789
|
+
cmd._executableHandler = true;
|
|
790
|
+
}
|
|
791
|
+
if (opts.isDefault)
|
|
792
|
+
this._defaultCommandName = cmd._name;
|
|
793
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
794
|
+
cmd._executableFile = opts.executableFile || null;
|
|
795
|
+
if (args)
|
|
796
|
+
cmd.arguments(args);
|
|
797
|
+
this._registerCommand(cmd);
|
|
798
|
+
cmd.parent = this;
|
|
799
|
+
cmd.copyInheritedSettings(this);
|
|
800
|
+
if (desc)
|
|
801
|
+
return this;
|
|
802
|
+
return cmd;
|
|
803
|
+
}
|
|
804
|
+
createCommand(name) {
|
|
805
|
+
return new Command(name);
|
|
806
|
+
}
|
|
807
|
+
createHelp() {
|
|
808
|
+
return Object.assign(new Help, this.configureHelp());
|
|
809
|
+
}
|
|
810
|
+
configureHelp(configuration) {
|
|
811
|
+
if (configuration === undefined)
|
|
812
|
+
return this._helpConfiguration;
|
|
813
|
+
this._helpConfiguration = configuration;
|
|
814
|
+
return this;
|
|
815
|
+
}
|
|
816
|
+
configureOutput(configuration) {
|
|
817
|
+
if (configuration === undefined)
|
|
818
|
+
return this._outputConfiguration;
|
|
819
|
+
this._outputConfiguration = {
|
|
820
|
+
...this._outputConfiguration,
|
|
821
|
+
...configuration
|
|
822
|
+
};
|
|
823
|
+
return this;
|
|
824
|
+
}
|
|
825
|
+
showHelpAfterError(displayHelp = true) {
|
|
826
|
+
if (typeof displayHelp !== "string")
|
|
827
|
+
displayHelp = !!displayHelp;
|
|
828
|
+
this._showHelpAfterError = displayHelp;
|
|
829
|
+
return this;
|
|
830
|
+
}
|
|
831
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
832
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
833
|
+
return this;
|
|
834
|
+
}
|
|
835
|
+
addCommand(cmd, opts) {
|
|
836
|
+
if (!cmd._name) {
|
|
837
|
+
throw new Error(`Command passed to .addCommand() must have a name
|
|
838
|
+
- specify the name in Command constructor or using .name()`);
|
|
839
|
+
}
|
|
840
|
+
opts = opts || {};
|
|
841
|
+
if (opts.isDefault)
|
|
842
|
+
this._defaultCommandName = cmd._name;
|
|
843
|
+
if (opts.noHelp || opts.hidden)
|
|
844
|
+
cmd._hidden = true;
|
|
845
|
+
this._registerCommand(cmd);
|
|
846
|
+
cmd.parent = this;
|
|
847
|
+
cmd._checkForBrokenPassThrough();
|
|
848
|
+
return this;
|
|
849
|
+
}
|
|
850
|
+
createArgument(name, description) {
|
|
851
|
+
return new Argument(name, description);
|
|
852
|
+
}
|
|
853
|
+
argument(name, description, parseArg, defaultValue) {
|
|
854
|
+
const argument = this.createArgument(name, description);
|
|
855
|
+
if (typeof parseArg === "function") {
|
|
856
|
+
argument.default(defaultValue).argParser(parseArg);
|
|
857
|
+
} else {
|
|
858
|
+
argument.default(parseArg);
|
|
859
|
+
}
|
|
860
|
+
this.addArgument(argument);
|
|
861
|
+
return this;
|
|
862
|
+
}
|
|
863
|
+
arguments(names) {
|
|
864
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
865
|
+
this.argument(detail);
|
|
866
|
+
});
|
|
867
|
+
return this;
|
|
868
|
+
}
|
|
869
|
+
addArgument(argument) {
|
|
870
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
871
|
+
if (previousArgument?.variadic) {
|
|
872
|
+
throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
|
|
873
|
+
}
|
|
874
|
+
if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
|
|
875
|
+
throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
|
|
876
|
+
}
|
|
877
|
+
this.registeredArguments.push(argument);
|
|
878
|
+
return this;
|
|
879
|
+
}
|
|
880
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
881
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
882
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
883
|
+
if (enableOrNameAndArgs && this._defaultCommandGroup) {
|
|
884
|
+
this._initCommandGroup(this._getHelpCommand());
|
|
885
|
+
}
|
|
886
|
+
return this;
|
|
887
|
+
}
|
|
888
|
+
const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
|
|
889
|
+
const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
890
|
+
const helpDescription = description ?? "display help for command";
|
|
891
|
+
const helpCommand = this.createCommand(helpName);
|
|
892
|
+
helpCommand.helpOption(false);
|
|
893
|
+
if (helpArgs)
|
|
894
|
+
helpCommand.arguments(helpArgs);
|
|
895
|
+
if (helpDescription)
|
|
896
|
+
helpCommand.description(helpDescription);
|
|
897
|
+
this._addImplicitHelpCommand = true;
|
|
898
|
+
this._helpCommand = helpCommand;
|
|
899
|
+
if (enableOrNameAndArgs || description)
|
|
900
|
+
this._initCommandGroup(helpCommand);
|
|
901
|
+
return this;
|
|
902
|
+
}
|
|
903
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
904
|
+
if (typeof helpCommand !== "object") {
|
|
905
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
906
|
+
return this;
|
|
907
|
+
}
|
|
908
|
+
this._addImplicitHelpCommand = true;
|
|
909
|
+
this._helpCommand = helpCommand;
|
|
910
|
+
this._initCommandGroup(helpCommand);
|
|
911
|
+
return this;
|
|
912
|
+
}
|
|
913
|
+
_getHelpCommand() {
|
|
914
|
+
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
|
|
915
|
+
if (hasImplicitHelpCommand) {
|
|
916
|
+
if (this._helpCommand === undefined) {
|
|
917
|
+
this.helpCommand(undefined, undefined);
|
|
918
|
+
}
|
|
919
|
+
return this._helpCommand;
|
|
920
|
+
}
|
|
921
|
+
return null;
|
|
922
|
+
}
|
|
923
|
+
hook(event, listener) {
|
|
924
|
+
const allowedValues = ["preSubcommand", "preAction", "postAction"];
|
|
925
|
+
if (!allowedValues.includes(event)) {
|
|
926
|
+
throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
927
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
928
|
+
}
|
|
929
|
+
if (this._lifeCycleHooks[event]) {
|
|
930
|
+
this._lifeCycleHooks[event].push(listener);
|
|
931
|
+
} else {
|
|
932
|
+
this._lifeCycleHooks[event] = [listener];
|
|
933
|
+
}
|
|
934
|
+
return this;
|
|
935
|
+
}
|
|
936
|
+
exitOverride(fn) {
|
|
937
|
+
if (fn) {
|
|
938
|
+
this._exitCallback = fn;
|
|
939
|
+
} else {
|
|
940
|
+
this._exitCallback = (err) => {
|
|
941
|
+
if (err.code !== "commander.executeSubCommandAsync") {
|
|
942
|
+
throw err;
|
|
943
|
+
}
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
return this;
|
|
947
|
+
}
|
|
948
|
+
_exit(exitCode, code, message) {
|
|
949
|
+
if (this._exitCallback) {
|
|
950
|
+
this._exitCallback(new CommanderError(exitCode, code, message));
|
|
951
|
+
}
|
|
952
|
+
process2.exit(exitCode);
|
|
953
|
+
}
|
|
954
|
+
action(fn) {
|
|
955
|
+
const listener = (args) => {
|
|
956
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
957
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
958
|
+
if (this._storeOptionsAsProperties) {
|
|
959
|
+
actionArgs[expectedArgsCount] = this;
|
|
960
|
+
} else {
|
|
961
|
+
actionArgs[expectedArgsCount] = this.opts();
|
|
962
|
+
}
|
|
963
|
+
actionArgs.push(this);
|
|
964
|
+
return fn.apply(this, actionArgs);
|
|
965
|
+
};
|
|
966
|
+
this._actionHandler = listener;
|
|
967
|
+
return this;
|
|
968
|
+
}
|
|
969
|
+
createOption(flags, description) {
|
|
970
|
+
return new Option(flags, description);
|
|
971
|
+
}
|
|
972
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
973
|
+
try {
|
|
974
|
+
return target.parseArg(value, previous);
|
|
975
|
+
} catch (err) {
|
|
976
|
+
if (err.code === "commander.invalidArgument") {
|
|
977
|
+
const message = `${invalidArgumentMessage} ${err.message}`;
|
|
978
|
+
this.error(message, { exitCode: err.exitCode, code: err.code });
|
|
979
|
+
}
|
|
980
|
+
throw err;
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
_registerOption(option) {
|
|
984
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
985
|
+
if (matchingOption) {
|
|
986
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
987
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
988
|
+
- already used by option '${matchingOption.flags}'`);
|
|
989
|
+
}
|
|
990
|
+
this._initOptionGroup(option);
|
|
991
|
+
this.options.push(option);
|
|
992
|
+
}
|
|
993
|
+
_registerCommand(command) {
|
|
994
|
+
const knownBy = (cmd) => {
|
|
995
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
996
|
+
};
|
|
997
|
+
const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
|
|
998
|
+
if (alreadyUsed) {
|
|
999
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
1000
|
+
const newCmd = knownBy(command).join("|");
|
|
1001
|
+
throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
|
|
1002
|
+
}
|
|
1003
|
+
this._initCommandGroup(command);
|
|
1004
|
+
this.commands.push(command);
|
|
1005
|
+
}
|
|
1006
|
+
addOption(option) {
|
|
1007
|
+
this._registerOption(option);
|
|
1008
|
+
const oname = option.name();
|
|
1009
|
+
const name = option.attributeName();
|
|
1010
|
+
if (option.defaultValue !== undefined) {
|
|
1011
|
+
this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
1012
|
+
}
|
|
1013
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
1014
|
+
if (val == null && option.presetArg !== undefined) {
|
|
1015
|
+
val = option.presetArg;
|
|
1016
|
+
}
|
|
1017
|
+
const oldValue = this.getOptionValue(name);
|
|
1018
|
+
if (val !== null && option.parseArg) {
|
|
1019
|
+
val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
1020
|
+
} else if (val !== null && option.variadic) {
|
|
1021
|
+
val = option._collectValue(val, oldValue);
|
|
1022
|
+
}
|
|
1023
|
+
if (val == null) {
|
|
1024
|
+
if (option.negate) {
|
|
1025
|
+
val = false;
|
|
1026
|
+
} else if (option.isBoolean() || option.optional) {
|
|
1027
|
+
val = true;
|
|
1028
|
+
} else {
|
|
1029
|
+
val = "";
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
1033
|
+
};
|
|
1034
|
+
this.on("option:" + oname, (val) => {
|
|
1035
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
1036
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
1037
|
+
});
|
|
1038
|
+
if (option.envVar) {
|
|
1039
|
+
this.on("optionEnv:" + oname, (val) => {
|
|
1040
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
1041
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
1042
|
+
});
|
|
1043
|
+
}
|
|
1044
|
+
return this;
|
|
1045
|
+
}
|
|
1046
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
1047
|
+
if (typeof flags === "object" && flags instanceof Option) {
|
|
1048
|
+
throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
|
|
1049
|
+
}
|
|
1050
|
+
const option = this.createOption(flags, description);
|
|
1051
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
1052
|
+
if (typeof fn === "function") {
|
|
1053
|
+
option.default(defaultValue).argParser(fn);
|
|
1054
|
+
} else if (fn instanceof RegExp) {
|
|
1055
|
+
const regex = fn;
|
|
1056
|
+
fn = (val, def) => {
|
|
1057
|
+
const m = regex.exec(val);
|
|
1058
|
+
return m ? m[0] : def;
|
|
1059
|
+
};
|
|
1060
|
+
option.default(defaultValue).argParser(fn);
|
|
1061
|
+
} else {
|
|
1062
|
+
option.default(fn);
|
|
1063
|
+
}
|
|
1064
|
+
return this.addOption(option);
|
|
1065
|
+
}
|
|
1066
|
+
option(flags, description, parseArg, defaultValue) {
|
|
1067
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
1068
|
+
}
|
|
1069
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
1070
|
+
return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
|
|
1071
|
+
}
|
|
1072
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
1073
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
1074
|
+
return this;
|
|
1075
|
+
}
|
|
1076
|
+
allowUnknownOption(allowUnknown = true) {
|
|
1077
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
1078
|
+
return this;
|
|
1079
|
+
}
|
|
1080
|
+
allowExcessArguments(allowExcess = true) {
|
|
1081
|
+
this._allowExcessArguments = !!allowExcess;
|
|
1082
|
+
return this;
|
|
1083
|
+
}
|
|
1084
|
+
enablePositionalOptions(positional = true) {
|
|
1085
|
+
this._enablePositionalOptions = !!positional;
|
|
1086
|
+
return this;
|
|
1087
|
+
}
|
|
1088
|
+
passThroughOptions(passThrough = true) {
|
|
1089
|
+
this._passThroughOptions = !!passThrough;
|
|
1090
|
+
this._checkForBrokenPassThrough();
|
|
1091
|
+
return this;
|
|
1092
|
+
}
|
|
1093
|
+
_checkForBrokenPassThrough() {
|
|
1094
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
|
|
1095
|
+
throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
1099
|
+
if (this.options.length) {
|
|
1100
|
+
throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
1101
|
+
}
|
|
1102
|
+
if (Object.keys(this._optionValues).length) {
|
|
1103
|
+
throw new Error("call .storeOptionsAsProperties() before setting option values");
|
|
1104
|
+
}
|
|
1105
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1106
|
+
return this;
|
|
1107
|
+
}
|
|
1108
|
+
getOptionValue(key) {
|
|
1109
|
+
if (this._storeOptionsAsProperties) {
|
|
1110
|
+
return this[key];
|
|
1111
|
+
}
|
|
1112
|
+
return this._optionValues[key];
|
|
1113
|
+
}
|
|
1114
|
+
setOptionValue(key, value) {
|
|
1115
|
+
return this.setOptionValueWithSource(key, value, undefined);
|
|
1116
|
+
}
|
|
1117
|
+
setOptionValueWithSource(key, value, source) {
|
|
1118
|
+
if (this._storeOptionsAsProperties) {
|
|
1119
|
+
this[key] = value;
|
|
1120
|
+
} else {
|
|
1121
|
+
this._optionValues[key] = value;
|
|
1122
|
+
}
|
|
1123
|
+
this._optionValueSources[key] = source;
|
|
1124
|
+
return this;
|
|
1125
|
+
}
|
|
1126
|
+
getOptionValueSource(key) {
|
|
1127
|
+
return this._optionValueSources[key];
|
|
1128
|
+
}
|
|
1129
|
+
getOptionValueSourceWithGlobals(key) {
|
|
1130
|
+
let source;
|
|
1131
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1132
|
+
if (cmd.getOptionValueSource(key) !== undefined) {
|
|
1133
|
+
source = cmd.getOptionValueSource(key);
|
|
1134
|
+
}
|
|
1135
|
+
});
|
|
1136
|
+
return source;
|
|
1137
|
+
}
|
|
1138
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
1139
|
+
if (argv !== undefined && !Array.isArray(argv)) {
|
|
1140
|
+
throw new Error("first parameter to parse must be array or undefined");
|
|
1141
|
+
}
|
|
1142
|
+
parseOptions = parseOptions || {};
|
|
1143
|
+
if (argv === undefined && parseOptions.from === undefined) {
|
|
1144
|
+
if (process2.versions?.electron) {
|
|
1145
|
+
parseOptions.from = "electron";
|
|
1146
|
+
}
|
|
1147
|
+
const execArgv = process2.execArgv ?? [];
|
|
1148
|
+
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
|
|
1149
|
+
parseOptions.from = "eval";
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
if (argv === undefined) {
|
|
1153
|
+
argv = process2.argv;
|
|
1154
|
+
}
|
|
1155
|
+
this.rawArgs = argv.slice();
|
|
1156
|
+
let userArgs;
|
|
1157
|
+
switch (parseOptions.from) {
|
|
1158
|
+
case undefined:
|
|
1159
|
+
case "node":
|
|
1160
|
+
this._scriptPath = argv[1];
|
|
1161
|
+
userArgs = argv.slice(2);
|
|
1162
|
+
break;
|
|
1163
|
+
case "electron":
|
|
1164
|
+
if (process2.defaultApp) {
|
|
1165
|
+
this._scriptPath = argv[1];
|
|
1166
|
+
userArgs = argv.slice(2);
|
|
1167
|
+
} else {
|
|
1168
|
+
userArgs = argv.slice(1);
|
|
1169
|
+
}
|
|
1170
|
+
break;
|
|
1171
|
+
case "user":
|
|
1172
|
+
userArgs = argv.slice(0);
|
|
1173
|
+
break;
|
|
1174
|
+
case "eval":
|
|
1175
|
+
userArgs = argv.slice(1);
|
|
1176
|
+
break;
|
|
1177
|
+
default:
|
|
1178
|
+
throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
|
|
1179
|
+
}
|
|
1180
|
+
if (!this._name && this._scriptPath)
|
|
1181
|
+
this.nameFromFilename(this._scriptPath);
|
|
1182
|
+
this._name = this._name || "program";
|
|
1183
|
+
return userArgs;
|
|
1184
|
+
}
|
|
1185
|
+
parse(argv, parseOptions) {
|
|
1186
|
+
this._prepareForParse();
|
|
1187
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1188
|
+
this._parseCommand([], userArgs);
|
|
1189
|
+
return this;
|
|
1190
|
+
}
|
|
1191
|
+
async parseAsync(argv, parseOptions) {
|
|
1192
|
+
this._prepareForParse();
|
|
1193
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
1194
|
+
await this._parseCommand([], userArgs);
|
|
1195
|
+
return this;
|
|
1196
|
+
}
|
|
1197
|
+
_prepareForParse() {
|
|
1198
|
+
if (this._savedState === null) {
|
|
1199
|
+
this.options.filter((option) => option.negate && option.defaultValue === undefined && this.getOptionValue(option.attributeName()) === undefined).forEach((option) => {
|
|
1200
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
1201
|
+
if (!this._findOption(positiveLongFlag)) {
|
|
1202
|
+
this.setOptionValueWithSource(option.attributeName(), true, "default");
|
|
1203
|
+
}
|
|
1204
|
+
});
|
|
1205
|
+
this.saveStateBeforeParse();
|
|
1206
|
+
} else {
|
|
1207
|
+
this.restoreStateBeforeParse();
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
saveStateBeforeParse() {
|
|
1211
|
+
this._savedState = {
|
|
1212
|
+
_name: this._name,
|
|
1213
|
+
_optionValues: { ...this._optionValues },
|
|
1214
|
+
_optionValueSources: { ...this._optionValueSources }
|
|
1215
|
+
};
|
|
1216
|
+
}
|
|
1217
|
+
restoreStateBeforeParse() {
|
|
1218
|
+
if (this._storeOptionsAsProperties)
|
|
1219
|
+
throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
1220
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);
|
|
1221
|
+
this._name = this._savedState._name;
|
|
1222
|
+
this._scriptPath = null;
|
|
1223
|
+
this.rawArgs = [];
|
|
1224
|
+
this._optionValues = { ...this._savedState._optionValues };
|
|
1225
|
+
this._optionValueSources = { ...this._savedState._optionValueSources };
|
|
1226
|
+
this.args = [];
|
|
1227
|
+
this.processedArgs = [];
|
|
1228
|
+
}
|
|
1229
|
+
_checkForMissingExecutable(executableFile, executableDir, subcommandName) {
|
|
1230
|
+
if (fs.existsSync(executableFile))
|
|
1231
|
+
return;
|
|
1232
|
+
const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
|
|
1233
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
1234
|
+
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
1235
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
1236
|
+
- ${executableDirMessage}`;
|
|
1237
|
+
throw new Error(executableMissing);
|
|
1238
|
+
}
|
|
1239
|
+
_executeSubCommand(subcommand, args) {
|
|
1240
|
+
args = args.slice();
|
|
1241
|
+
const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
|
|
1242
|
+
function findFile(baseDir, baseName) {
|
|
1243
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
1244
|
+
if (fs.existsSync(localBin))
|
|
1245
|
+
return localBin;
|
|
1246
|
+
if (sourceExt.includes(path.extname(baseName)))
|
|
1247
|
+
return;
|
|
1248
|
+
const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
|
|
1249
|
+
if (foundExt)
|
|
1250
|
+
return `${localBin}${foundExt}`;
|
|
1251
|
+
return;
|
|
1252
|
+
}
|
|
1253
|
+
this._checkForMissingMandatoryOptions();
|
|
1254
|
+
this._checkForConflictingOptions();
|
|
1255
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
1256
|
+
let executableDir = this._executableDir || "";
|
|
1257
|
+
if (this._scriptPath) {
|
|
1258
|
+
let resolvedScriptPath;
|
|
1259
|
+
try {
|
|
1260
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
1261
|
+
} catch {
|
|
1262
|
+
resolvedScriptPath = this._scriptPath;
|
|
1263
|
+
}
|
|
1264
|
+
executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
|
|
1265
|
+
}
|
|
1266
|
+
if (executableDir) {
|
|
1267
|
+
let localFile = findFile(executableDir, executableFile);
|
|
1268
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
1269
|
+
const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
|
|
1270
|
+
if (legacyName !== this._name) {
|
|
1271
|
+
localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
executableFile = localFile || executableFile;
|
|
1275
|
+
}
|
|
1276
|
+
const launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
1277
|
+
let proc;
|
|
1278
|
+
if (process2.platform !== "win32") {
|
|
1279
|
+
if (launchWithNode) {
|
|
1280
|
+
args.unshift(executableFile);
|
|
1281
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
1282
|
+
proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
|
|
1283
|
+
} else {
|
|
1284
|
+
proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
1285
|
+
}
|
|
1286
|
+
} else {
|
|
1287
|
+
this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
|
|
1288
|
+
args.unshift(executableFile);
|
|
1289
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
1290
|
+
proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
|
|
1291
|
+
}
|
|
1292
|
+
if (!proc.killed) {
|
|
1293
|
+
const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
|
|
1294
|
+
signals.forEach((signal) => {
|
|
1295
|
+
process2.on(signal, () => {
|
|
1296
|
+
if (proc.killed === false && proc.exitCode === null) {
|
|
1297
|
+
proc.kill(signal);
|
|
1298
|
+
}
|
|
1299
|
+
});
|
|
1300
|
+
});
|
|
1301
|
+
}
|
|
1302
|
+
const exitCallback = this._exitCallback;
|
|
1303
|
+
proc.on("close", (code) => {
|
|
1304
|
+
code = code ?? 1;
|
|
1305
|
+
if (!exitCallback) {
|
|
1306
|
+
process2.exit(code);
|
|
1307
|
+
} else {
|
|
1308
|
+
exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
|
|
1309
|
+
}
|
|
1310
|
+
});
|
|
1311
|
+
proc.on("error", (err) => {
|
|
1312
|
+
if (err.code === "ENOENT") {
|
|
1313
|
+
this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
|
|
1314
|
+
} else if (err.code === "EACCES") {
|
|
1315
|
+
throw new Error(`'${executableFile}' not executable`);
|
|
1316
|
+
}
|
|
1317
|
+
if (!exitCallback) {
|
|
1318
|
+
process2.exit(1);
|
|
1319
|
+
} else {
|
|
1320
|
+
const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
|
|
1321
|
+
wrappedError.nestedError = err;
|
|
1322
|
+
exitCallback(wrappedError);
|
|
1323
|
+
}
|
|
1324
|
+
});
|
|
1325
|
+
this.runningCommand = proc;
|
|
1326
|
+
}
|
|
1327
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
1328
|
+
const subCommand = this._findCommand(commandName);
|
|
1329
|
+
if (!subCommand)
|
|
1330
|
+
this.help({ error: true });
|
|
1331
|
+
subCommand._prepareForParse();
|
|
1332
|
+
let promiseChain;
|
|
1333
|
+
promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
|
|
1334
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
1335
|
+
if (subCommand._executableHandler) {
|
|
1336
|
+
this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
1337
|
+
} else {
|
|
1338
|
+
return subCommand._parseCommand(operands, unknown);
|
|
1339
|
+
}
|
|
1340
|
+
});
|
|
1341
|
+
return promiseChain;
|
|
1342
|
+
}
|
|
1343
|
+
_dispatchHelpCommand(subcommandName) {
|
|
1344
|
+
if (!subcommandName) {
|
|
1345
|
+
this.help();
|
|
1346
|
+
}
|
|
1347
|
+
const subCommand = this._findCommand(subcommandName);
|
|
1348
|
+
if (subCommand && !subCommand._executableHandler) {
|
|
1349
|
+
subCommand.help();
|
|
1350
|
+
}
|
|
1351
|
+
return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
|
|
1352
|
+
}
|
|
1353
|
+
_checkNumberOfArguments() {
|
|
1354
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
1355
|
+
if (arg.required && this.args[i] == null) {
|
|
1356
|
+
this.missingArgument(arg.name());
|
|
1357
|
+
}
|
|
1358
|
+
});
|
|
1359
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
|
|
1360
|
+
return;
|
|
1361
|
+
}
|
|
1362
|
+
if (this.args.length > this.registeredArguments.length) {
|
|
1363
|
+
this._excessArguments(this.args);
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
_processArguments() {
|
|
1367
|
+
const myParseArg = (argument, value, previous) => {
|
|
1368
|
+
let parsedValue = value;
|
|
1369
|
+
if (value !== null && argument.parseArg) {
|
|
1370
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
1371
|
+
parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
|
|
1372
|
+
}
|
|
1373
|
+
return parsedValue;
|
|
1374
|
+
};
|
|
1375
|
+
this._checkNumberOfArguments();
|
|
1376
|
+
const processedArgs = [];
|
|
1377
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
1378
|
+
let value = declaredArg.defaultValue;
|
|
1379
|
+
if (declaredArg.variadic) {
|
|
1380
|
+
if (index < this.args.length) {
|
|
1381
|
+
value = this.args.slice(index);
|
|
1382
|
+
if (declaredArg.parseArg) {
|
|
1383
|
+
value = value.reduce((processed, v) => {
|
|
1384
|
+
return myParseArg(declaredArg, v, processed);
|
|
1385
|
+
}, declaredArg.defaultValue);
|
|
1386
|
+
}
|
|
1387
|
+
} else if (value === undefined) {
|
|
1388
|
+
value = [];
|
|
1389
|
+
}
|
|
1390
|
+
} else if (index < this.args.length) {
|
|
1391
|
+
value = this.args[index];
|
|
1392
|
+
if (declaredArg.parseArg) {
|
|
1393
|
+
value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
processedArgs[index] = value;
|
|
1397
|
+
});
|
|
1398
|
+
this.processedArgs = processedArgs;
|
|
1399
|
+
}
|
|
1400
|
+
_chainOrCall(promise, fn) {
|
|
1401
|
+
if (promise?.then && typeof promise.then === "function") {
|
|
1402
|
+
return promise.then(() => fn());
|
|
1403
|
+
}
|
|
1404
|
+
return fn();
|
|
1405
|
+
}
|
|
1406
|
+
_chainOrCallHooks(promise, event) {
|
|
1407
|
+
let result = promise;
|
|
1408
|
+
const hooks = [];
|
|
1409
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
|
|
1410
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
1411
|
+
hooks.push({ hookedCommand, callback });
|
|
1412
|
+
});
|
|
1413
|
+
});
|
|
1414
|
+
if (event === "postAction") {
|
|
1415
|
+
hooks.reverse();
|
|
1416
|
+
}
|
|
1417
|
+
hooks.forEach((hookDetail) => {
|
|
1418
|
+
result = this._chainOrCall(result, () => {
|
|
1419
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
1420
|
+
});
|
|
1421
|
+
});
|
|
1422
|
+
return result;
|
|
1423
|
+
}
|
|
1424
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
1425
|
+
let result = promise;
|
|
1426
|
+
if (this._lifeCycleHooks[event] !== undefined) {
|
|
1427
|
+
this._lifeCycleHooks[event].forEach((hook) => {
|
|
1428
|
+
result = this._chainOrCall(result, () => {
|
|
1429
|
+
return hook(this, subCommand);
|
|
1430
|
+
});
|
|
1431
|
+
});
|
|
1432
|
+
}
|
|
1433
|
+
return result;
|
|
1434
|
+
}
|
|
1435
|
+
_parseCommand(operands, unknown) {
|
|
1436
|
+
const parsed = this.parseOptions(unknown);
|
|
1437
|
+
this._parseOptionsEnv();
|
|
1438
|
+
this._parseOptionsImplied();
|
|
1439
|
+
operands = operands.concat(parsed.operands);
|
|
1440
|
+
unknown = parsed.unknown;
|
|
1441
|
+
this.args = operands.concat(unknown);
|
|
1442
|
+
if (operands && this._findCommand(operands[0])) {
|
|
1443
|
+
return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
1444
|
+
}
|
|
1445
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
|
|
1446
|
+
return this._dispatchHelpCommand(operands[1]);
|
|
1447
|
+
}
|
|
1448
|
+
if (this._defaultCommandName) {
|
|
1449
|
+
this._outputHelpIfRequested(unknown);
|
|
1450
|
+
return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
|
|
1451
|
+
}
|
|
1452
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
|
|
1453
|
+
this.help({ error: true });
|
|
1454
|
+
}
|
|
1455
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
1456
|
+
this._checkForMissingMandatoryOptions();
|
|
1457
|
+
this._checkForConflictingOptions();
|
|
1458
|
+
const checkForUnknownOptions = () => {
|
|
1459
|
+
if (parsed.unknown.length > 0) {
|
|
1460
|
+
this.unknownOption(parsed.unknown[0]);
|
|
1461
|
+
}
|
|
1462
|
+
};
|
|
1463
|
+
const commandEvent = `command:${this.name()}`;
|
|
1464
|
+
if (this._actionHandler) {
|
|
1465
|
+
checkForUnknownOptions();
|
|
1466
|
+
this._processArguments();
|
|
1467
|
+
let promiseChain;
|
|
1468
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
1469
|
+
promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
|
|
1470
|
+
if (this.parent) {
|
|
1471
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
1472
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
1473
|
+
});
|
|
1474
|
+
}
|
|
1475
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
1476
|
+
return promiseChain;
|
|
1477
|
+
}
|
|
1478
|
+
if (this.parent?.listenerCount(commandEvent)) {
|
|
1479
|
+
checkForUnknownOptions();
|
|
1480
|
+
this._processArguments();
|
|
1481
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
1482
|
+
} else if (operands.length) {
|
|
1483
|
+
if (this._findCommand("*")) {
|
|
1484
|
+
return this._dispatchSubcommand("*", operands, unknown);
|
|
1485
|
+
}
|
|
1486
|
+
if (this.listenerCount("command:*")) {
|
|
1487
|
+
this.emit("command:*", operands, unknown);
|
|
1488
|
+
} else if (this.commands.length) {
|
|
1489
|
+
this.unknownCommand();
|
|
1490
|
+
} else {
|
|
1491
|
+
checkForUnknownOptions();
|
|
1492
|
+
this._processArguments();
|
|
1493
|
+
}
|
|
1494
|
+
} else if (this.commands.length) {
|
|
1495
|
+
checkForUnknownOptions();
|
|
1496
|
+
this.help({ error: true });
|
|
1497
|
+
} else {
|
|
1498
|
+
checkForUnknownOptions();
|
|
1499
|
+
this._processArguments();
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
_findCommand(name) {
|
|
1503
|
+
if (!name)
|
|
1504
|
+
return;
|
|
1505
|
+
return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
|
|
1506
|
+
}
|
|
1507
|
+
_findOption(arg) {
|
|
1508
|
+
return this.options.find((option) => option.is(arg));
|
|
1509
|
+
}
|
|
1510
|
+
_checkForMissingMandatoryOptions() {
|
|
1511
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1512
|
+
cmd.options.forEach((anOption) => {
|
|
1513
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
|
|
1514
|
+
cmd.missingMandatoryOptionValue(anOption);
|
|
1515
|
+
}
|
|
1516
|
+
});
|
|
1517
|
+
});
|
|
1518
|
+
}
|
|
1519
|
+
_checkForConflictingLocalOptions() {
|
|
1520
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
1521
|
+
const optionKey = option.attributeName();
|
|
1522
|
+
if (this.getOptionValue(optionKey) === undefined) {
|
|
1523
|
+
return false;
|
|
1524
|
+
}
|
|
1525
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
1526
|
+
});
|
|
1527
|
+
const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
|
|
1528
|
+
optionsWithConflicting.forEach((option) => {
|
|
1529
|
+
const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
|
|
1530
|
+
if (conflictingAndDefined) {
|
|
1531
|
+
this._conflictingOption(option, conflictingAndDefined);
|
|
1532
|
+
}
|
|
1533
|
+
});
|
|
1534
|
+
}
|
|
1535
|
+
_checkForConflictingOptions() {
|
|
1536
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1537
|
+
cmd._checkForConflictingLocalOptions();
|
|
1538
|
+
});
|
|
1539
|
+
}
|
|
1540
|
+
parseOptions(args) {
|
|
1541
|
+
const operands = [];
|
|
1542
|
+
const unknown = [];
|
|
1543
|
+
let dest = operands;
|
|
1544
|
+
function maybeOption(arg) {
|
|
1545
|
+
return arg.length > 1 && arg[0] === "-";
|
|
1546
|
+
}
|
|
1547
|
+
const negativeNumberArg = (arg) => {
|
|
1548
|
+
if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg))
|
|
1549
|
+
return false;
|
|
1550
|
+
return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
|
|
1551
|
+
};
|
|
1552
|
+
let activeVariadicOption = null;
|
|
1553
|
+
let activeGroup = null;
|
|
1554
|
+
let i = 0;
|
|
1555
|
+
while (i < args.length || activeGroup) {
|
|
1556
|
+
const arg = activeGroup ?? args[i++];
|
|
1557
|
+
activeGroup = null;
|
|
1558
|
+
if (arg === "--") {
|
|
1559
|
+
if (dest === unknown)
|
|
1560
|
+
dest.push(arg);
|
|
1561
|
+
dest.push(...args.slice(i));
|
|
1562
|
+
break;
|
|
1563
|
+
}
|
|
1564
|
+
if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
|
|
1565
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
1566
|
+
continue;
|
|
1567
|
+
}
|
|
1568
|
+
activeVariadicOption = null;
|
|
1569
|
+
if (maybeOption(arg)) {
|
|
1570
|
+
const option = this._findOption(arg);
|
|
1571
|
+
if (option) {
|
|
1572
|
+
if (option.required) {
|
|
1573
|
+
const value = args[i++];
|
|
1574
|
+
if (value === undefined)
|
|
1575
|
+
this.optionMissingArgument(option);
|
|
1576
|
+
this.emit(`option:${option.name()}`, value);
|
|
1577
|
+
} else if (option.optional) {
|
|
1578
|
+
let value = null;
|
|
1579
|
+
if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
|
|
1580
|
+
value = args[i++];
|
|
1581
|
+
}
|
|
1582
|
+
this.emit(`option:${option.name()}`, value);
|
|
1583
|
+
} else {
|
|
1584
|
+
this.emit(`option:${option.name()}`);
|
|
1585
|
+
}
|
|
1586
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
1587
|
+
continue;
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
1591
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
1592
|
+
if (option) {
|
|
1593
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) {
|
|
1594
|
+
this.emit(`option:${option.name()}`, arg.slice(2));
|
|
1595
|
+
} else {
|
|
1596
|
+
this.emit(`option:${option.name()}`);
|
|
1597
|
+
activeGroup = `-${arg.slice(2)}`;
|
|
1598
|
+
}
|
|
1599
|
+
continue;
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
1603
|
+
const index = arg.indexOf("=");
|
|
1604
|
+
const option = this._findOption(arg.slice(0, index));
|
|
1605
|
+
if (option && (option.required || option.optional)) {
|
|
1606
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
1607
|
+
continue;
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
|
|
1611
|
+
dest = unknown;
|
|
1612
|
+
}
|
|
1613
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
1614
|
+
if (this._findCommand(arg)) {
|
|
1615
|
+
operands.push(arg);
|
|
1616
|
+
unknown.push(...args.slice(i));
|
|
1617
|
+
break;
|
|
1618
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
1619
|
+
operands.push(arg, ...args.slice(i));
|
|
1620
|
+
break;
|
|
1621
|
+
} else if (this._defaultCommandName) {
|
|
1622
|
+
unknown.push(arg, ...args.slice(i));
|
|
1623
|
+
break;
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
if (this._passThroughOptions) {
|
|
1627
|
+
dest.push(arg, ...args.slice(i));
|
|
1628
|
+
break;
|
|
1629
|
+
}
|
|
1630
|
+
dest.push(arg);
|
|
1631
|
+
}
|
|
1632
|
+
return { operands, unknown };
|
|
1633
|
+
}
|
|
1634
|
+
opts() {
|
|
1635
|
+
if (this._storeOptionsAsProperties) {
|
|
1636
|
+
const result = {};
|
|
1637
|
+
const len = this.options.length;
|
|
1638
|
+
for (let i = 0;i < len; i++) {
|
|
1639
|
+
const key = this.options[i].attributeName();
|
|
1640
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
1641
|
+
}
|
|
1642
|
+
return result;
|
|
1643
|
+
}
|
|
1644
|
+
return this._optionValues;
|
|
1645
|
+
}
|
|
1646
|
+
optsWithGlobals() {
|
|
1647
|
+
return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
|
|
1648
|
+
}
|
|
1649
|
+
error(message, errorOptions) {
|
|
1650
|
+
this._outputConfiguration.outputError(`${message}
|
|
1651
|
+
`, this._outputConfiguration.writeErr);
|
|
1652
|
+
if (typeof this._showHelpAfterError === "string") {
|
|
1653
|
+
this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
1654
|
+
`);
|
|
1655
|
+
} else if (this._showHelpAfterError) {
|
|
1656
|
+
this._outputConfiguration.writeErr(`
|
|
1657
|
+
`);
|
|
1658
|
+
this.outputHelp({ error: true });
|
|
1659
|
+
}
|
|
1660
|
+
const config = errorOptions || {};
|
|
1661
|
+
const exitCode = config.exitCode || 1;
|
|
1662
|
+
const code = config.code || "commander.error";
|
|
1663
|
+
this._exit(exitCode, code, message);
|
|
1664
|
+
}
|
|
1665
|
+
_parseOptionsEnv() {
|
|
1666
|
+
this.options.forEach((option) => {
|
|
1667
|
+
if (option.envVar && option.envVar in process2.env) {
|
|
1668
|
+
const optionKey = option.attributeName();
|
|
1669
|
+
if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
|
|
1670
|
+
if (option.required || option.optional) {
|
|
1671
|
+
this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
|
|
1672
|
+
} else {
|
|
1673
|
+
this.emit(`optionEnv:${option.name()}`);
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
});
|
|
1678
|
+
}
|
|
1679
|
+
_parseOptionsImplied() {
|
|
1680
|
+
const dualHelper = new DualOptions(this.options);
|
|
1681
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
1682
|
+
return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
1683
|
+
};
|
|
1684
|
+
this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
|
|
1685
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
1686
|
+
this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
|
|
1687
|
+
});
|
|
1688
|
+
});
|
|
1689
|
+
}
|
|
1690
|
+
missingArgument(name) {
|
|
1691
|
+
const message = `error: missing required argument '${name}'`;
|
|
1692
|
+
this.error(message, { code: "commander.missingArgument" });
|
|
1693
|
+
}
|
|
1694
|
+
optionMissingArgument(option) {
|
|
1695
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
1696
|
+
this.error(message, { code: "commander.optionMissingArgument" });
|
|
1697
|
+
}
|
|
1698
|
+
missingMandatoryOptionValue(option) {
|
|
1699
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
1700
|
+
this.error(message, { code: "commander.missingMandatoryOptionValue" });
|
|
1701
|
+
}
|
|
1702
|
+
_conflictingOption(option, conflictingOption) {
|
|
1703
|
+
const findBestOptionFromValue = (option) => {
|
|
1704
|
+
const optionKey = option.attributeName();
|
|
1705
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
1706
|
+
const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
|
|
1707
|
+
const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
|
|
1708
|
+
if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
|
|
1709
|
+
return negativeOption;
|
|
1710
|
+
}
|
|
1711
|
+
return positiveOption || option;
|
|
1712
|
+
};
|
|
1713
|
+
const getErrorMessage = (option) => {
|
|
1714
|
+
const bestOption = findBestOptionFromValue(option);
|
|
1715
|
+
const optionKey = bestOption.attributeName();
|
|
1716
|
+
const source = this.getOptionValueSource(optionKey);
|
|
1717
|
+
if (source === "env") {
|
|
1718
|
+
return `environment variable '${bestOption.envVar}'`;
|
|
1719
|
+
}
|
|
1720
|
+
return `option '${bestOption.flags}'`;
|
|
1721
|
+
};
|
|
1722
|
+
const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
1723
|
+
this.error(message, { code: "commander.conflictingOption" });
|
|
1724
|
+
}
|
|
1725
|
+
unknownOption(flag) {
|
|
1726
|
+
if (this._allowUnknownOption)
|
|
1727
|
+
return;
|
|
1728
|
+
let suggestion = "";
|
|
1729
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
1730
|
+
let candidateFlags = [];
|
|
1731
|
+
let command = this;
|
|
1732
|
+
do {
|
|
1733
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
1734
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
1735
|
+
command = command.parent;
|
|
1736
|
+
} while (command && !command._enablePositionalOptions);
|
|
1737
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
1738
|
+
}
|
|
1739
|
+
const message = `error: unknown option '${flag}'${suggestion}`;
|
|
1740
|
+
this.error(message, { code: "commander.unknownOption" });
|
|
1741
|
+
}
|
|
1742
|
+
_excessArguments(receivedArgs) {
|
|
1743
|
+
if (this._allowExcessArguments)
|
|
1744
|
+
return;
|
|
1745
|
+
const expected = this.registeredArguments.length;
|
|
1746
|
+
const s = expected === 1 ? "" : "s";
|
|
1747
|
+
const received = receivedArgs.length;
|
|
1748
|
+
const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
|
|
1749
|
+
const details = receivedArgs.join(", ");
|
|
1750
|
+
const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;
|
|
1751
|
+
this.error(message, { code: "commander.excessArguments" });
|
|
1752
|
+
}
|
|
1753
|
+
unknownCommand() {
|
|
1754
|
+
const unknownName = this.args[0];
|
|
1755
|
+
let suggestion = "";
|
|
1756
|
+
if (this._showSuggestionAfterError) {
|
|
1757
|
+
const candidateNames = [];
|
|
1758
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
1759
|
+
candidateNames.push(command.name());
|
|
1760
|
+
if (command.alias())
|
|
1761
|
+
candidateNames.push(command.alias());
|
|
1762
|
+
});
|
|
1763
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
1764
|
+
}
|
|
1765
|
+
const message = `error: unknown command '${unknownName}'${suggestion}`;
|
|
1766
|
+
this.error(message, { code: "commander.unknownCommand" });
|
|
1767
|
+
}
|
|
1768
|
+
version(str, flags, description) {
|
|
1769
|
+
if (str === undefined)
|
|
1770
|
+
return this._version;
|
|
1771
|
+
this._version = str;
|
|
1772
|
+
flags = flags || "-V, --version";
|
|
1773
|
+
description = description || "output the version number";
|
|
1774
|
+
const versionOption = this.createOption(flags, description);
|
|
1775
|
+
this._versionOptionName = versionOption.attributeName();
|
|
1776
|
+
this._registerOption(versionOption);
|
|
1777
|
+
this.on("option:" + versionOption.name(), () => {
|
|
1778
|
+
this._outputConfiguration.writeOut(`${str}
|
|
1779
|
+
`);
|
|
1780
|
+
this._exit(0, "commander.version", str);
|
|
1781
|
+
});
|
|
1782
|
+
return this;
|
|
1783
|
+
}
|
|
1784
|
+
description(str, argsDescription) {
|
|
1785
|
+
if (str === undefined && argsDescription === undefined)
|
|
1786
|
+
return this._description;
|
|
1787
|
+
this._description = str;
|
|
1788
|
+
if (argsDescription) {
|
|
1789
|
+
this._argsDescription = argsDescription;
|
|
1790
|
+
}
|
|
1791
|
+
return this;
|
|
1792
|
+
}
|
|
1793
|
+
summary(str) {
|
|
1794
|
+
if (str === undefined)
|
|
1795
|
+
return this._summary;
|
|
1796
|
+
this._summary = str;
|
|
1797
|
+
return this;
|
|
1798
|
+
}
|
|
1799
|
+
alias(alias) {
|
|
1800
|
+
if (alias === undefined)
|
|
1801
|
+
return this._aliases[0];
|
|
1802
|
+
let command = this;
|
|
1803
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
|
|
1804
|
+
command = this.commands[this.commands.length - 1];
|
|
1805
|
+
}
|
|
1806
|
+
if (alias === command._name)
|
|
1807
|
+
throw new Error("Command alias can't be the same as its name");
|
|
1808
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
1809
|
+
if (matchingCommand) {
|
|
1810
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
1811
|
+
throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
|
|
1812
|
+
}
|
|
1813
|
+
command._aliases.push(alias);
|
|
1814
|
+
return this;
|
|
1815
|
+
}
|
|
1816
|
+
aliases(aliases) {
|
|
1817
|
+
if (aliases === undefined)
|
|
1818
|
+
return this._aliases;
|
|
1819
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
1820
|
+
return this;
|
|
1821
|
+
}
|
|
1822
|
+
usage(str) {
|
|
1823
|
+
if (str === undefined) {
|
|
1824
|
+
if (this._usage)
|
|
1825
|
+
return this._usage;
|
|
1826
|
+
const args = this.registeredArguments.map((arg) => {
|
|
1827
|
+
return humanReadableArgName(arg);
|
|
1828
|
+
});
|
|
1829
|
+
return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
|
|
1830
|
+
}
|
|
1831
|
+
this._usage = str;
|
|
1832
|
+
return this;
|
|
1833
|
+
}
|
|
1834
|
+
name(str) {
|
|
1835
|
+
if (str === undefined)
|
|
1836
|
+
return this._name;
|
|
1837
|
+
this._name = str;
|
|
1838
|
+
return this;
|
|
1839
|
+
}
|
|
1840
|
+
helpGroup(heading) {
|
|
1841
|
+
if (heading === undefined)
|
|
1842
|
+
return this._helpGroupHeading ?? "";
|
|
1843
|
+
this._helpGroupHeading = heading;
|
|
1844
|
+
return this;
|
|
1845
|
+
}
|
|
1846
|
+
commandsGroup(heading) {
|
|
1847
|
+
if (heading === undefined)
|
|
1848
|
+
return this._defaultCommandGroup ?? "";
|
|
1849
|
+
this._defaultCommandGroup = heading;
|
|
1850
|
+
return this;
|
|
1851
|
+
}
|
|
1852
|
+
optionsGroup(heading) {
|
|
1853
|
+
if (heading === undefined)
|
|
1854
|
+
return this._defaultOptionGroup ?? "";
|
|
1855
|
+
this._defaultOptionGroup = heading;
|
|
1856
|
+
return this;
|
|
1857
|
+
}
|
|
1858
|
+
_initOptionGroup(option) {
|
|
1859
|
+
if (this._defaultOptionGroup && !option.helpGroupHeading)
|
|
1860
|
+
option.helpGroup(this._defaultOptionGroup);
|
|
1861
|
+
}
|
|
1862
|
+
_initCommandGroup(cmd) {
|
|
1863
|
+
if (this._defaultCommandGroup && !cmd.helpGroup())
|
|
1864
|
+
cmd.helpGroup(this._defaultCommandGroup);
|
|
1865
|
+
}
|
|
1866
|
+
nameFromFilename(filename) {
|
|
1867
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
1868
|
+
return this;
|
|
1869
|
+
}
|
|
1870
|
+
executableDir(path2) {
|
|
1871
|
+
if (path2 === undefined)
|
|
1872
|
+
return this._executableDir;
|
|
1873
|
+
this._executableDir = path2;
|
|
1874
|
+
return this;
|
|
1875
|
+
}
|
|
1876
|
+
helpInformation(contextOptions) {
|
|
1877
|
+
const helper = this.createHelp();
|
|
1878
|
+
const context = this._getOutputContext(contextOptions);
|
|
1879
|
+
helper.prepareContext({
|
|
1880
|
+
error: context.error,
|
|
1881
|
+
helpWidth: context.helpWidth,
|
|
1882
|
+
outputHasColors: context.hasColors
|
|
1883
|
+
});
|
|
1884
|
+
const text = helper.formatHelp(this, helper);
|
|
1885
|
+
if (context.hasColors)
|
|
1886
|
+
return text;
|
|
1887
|
+
return this._outputConfiguration.stripColor(text);
|
|
1888
|
+
}
|
|
1889
|
+
_getOutputContext(contextOptions) {
|
|
1890
|
+
contextOptions = contextOptions || {};
|
|
1891
|
+
const error = !!contextOptions.error;
|
|
1892
|
+
let baseWrite;
|
|
1893
|
+
let hasColors;
|
|
1894
|
+
let helpWidth;
|
|
1895
|
+
if (error) {
|
|
1896
|
+
baseWrite = (str) => this._outputConfiguration.writeErr(str);
|
|
1897
|
+
hasColors = this._outputConfiguration.getErrHasColors();
|
|
1898
|
+
helpWidth = this._outputConfiguration.getErrHelpWidth();
|
|
1899
|
+
} else {
|
|
1900
|
+
baseWrite = (str) => this._outputConfiguration.writeOut(str);
|
|
1901
|
+
hasColors = this._outputConfiguration.getOutHasColors();
|
|
1902
|
+
helpWidth = this._outputConfiguration.getOutHelpWidth();
|
|
1903
|
+
}
|
|
1904
|
+
const write = (str) => {
|
|
1905
|
+
if (!hasColors)
|
|
1906
|
+
str = this._outputConfiguration.stripColor(str);
|
|
1907
|
+
return baseWrite(str);
|
|
1908
|
+
};
|
|
1909
|
+
return { error, write, hasColors, helpWidth };
|
|
1910
|
+
}
|
|
1911
|
+
outputHelp(contextOptions) {
|
|
1912
|
+
let deprecatedCallback;
|
|
1913
|
+
if (typeof contextOptions === "function") {
|
|
1914
|
+
deprecatedCallback = contextOptions;
|
|
1915
|
+
contextOptions = undefined;
|
|
1916
|
+
}
|
|
1917
|
+
const outputContext = this._getOutputContext(contextOptions);
|
|
1918
|
+
const eventContext = {
|
|
1919
|
+
error: outputContext.error,
|
|
1920
|
+
write: outputContext.write,
|
|
1921
|
+
command: this
|
|
1922
|
+
};
|
|
1923
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
|
|
1924
|
+
this.emit("beforeHelp", eventContext);
|
|
1925
|
+
let helpInformation = this.helpInformation({ error: outputContext.error });
|
|
1926
|
+
if (deprecatedCallback) {
|
|
1927
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
1928
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
|
|
1929
|
+
throw new Error("outputHelp callback must return a string or a Buffer");
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1932
|
+
outputContext.write(helpInformation);
|
|
1933
|
+
if (this._getHelpOption()?.long) {
|
|
1934
|
+
this.emit(this._getHelpOption().long);
|
|
1935
|
+
}
|
|
1936
|
+
this.emit("afterHelp", eventContext);
|
|
1937
|
+
this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
|
|
1938
|
+
}
|
|
1939
|
+
helpOption(flags, description) {
|
|
1940
|
+
if (typeof flags === "boolean") {
|
|
1941
|
+
if (flags) {
|
|
1942
|
+
if (this._helpOption === null)
|
|
1943
|
+
this._helpOption = undefined;
|
|
1944
|
+
if (this._defaultOptionGroup) {
|
|
1945
|
+
this._initOptionGroup(this._getHelpOption());
|
|
1946
|
+
}
|
|
1947
|
+
} else {
|
|
1948
|
+
this._helpOption = null;
|
|
1949
|
+
}
|
|
1950
|
+
return this;
|
|
1951
|
+
}
|
|
1952
|
+
this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
|
|
1953
|
+
if (flags || description)
|
|
1954
|
+
this._initOptionGroup(this._helpOption);
|
|
1955
|
+
return this;
|
|
1956
|
+
}
|
|
1957
|
+
_getHelpOption() {
|
|
1958
|
+
if (this._helpOption === undefined) {
|
|
1959
|
+
this.helpOption(undefined, undefined);
|
|
1960
|
+
}
|
|
1961
|
+
return this._helpOption;
|
|
1962
|
+
}
|
|
1963
|
+
addHelpOption(option) {
|
|
1964
|
+
this._helpOption = option;
|
|
1965
|
+
this._initOptionGroup(option);
|
|
1966
|
+
return this;
|
|
1967
|
+
}
|
|
1968
|
+
help(contextOptions) {
|
|
1969
|
+
this.outputHelp(contextOptions);
|
|
1970
|
+
let exitCode = Number(process2.exitCode ?? 0);
|
|
1971
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
|
|
1972
|
+
exitCode = 1;
|
|
1973
|
+
}
|
|
1974
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
1975
|
+
}
|
|
1976
|
+
addHelpText(position, text) {
|
|
1977
|
+
const allowedValues = ["beforeAll", "before", "after", "afterAll"];
|
|
1978
|
+
if (!allowedValues.includes(position)) {
|
|
1979
|
+
throw new Error(`Unexpected value for position to addHelpText.
|
|
1980
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1981
|
+
}
|
|
1982
|
+
const helpEvent = `${position}Help`;
|
|
1983
|
+
this.on(helpEvent, (context) => {
|
|
1984
|
+
let helpStr;
|
|
1985
|
+
if (typeof text === "function") {
|
|
1986
|
+
helpStr = text({ error: context.error, command: context.command });
|
|
1987
|
+
} else {
|
|
1988
|
+
helpStr = text;
|
|
1989
|
+
}
|
|
1990
|
+
if (helpStr) {
|
|
1991
|
+
context.write(`${helpStr}
|
|
1992
|
+
`);
|
|
1993
|
+
}
|
|
1994
|
+
});
|
|
1995
|
+
return this;
|
|
1996
|
+
}
|
|
1997
|
+
_outputHelpIfRequested(args) {
|
|
1998
|
+
const helpOption = this._getHelpOption();
|
|
1999
|
+
const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
|
|
2000
|
+
if (helpRequested) {
|
|
2001
|
+
this.outputHelp();
|
|
2002
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
2003
|
+
}
|
|
2004
|
+
}
|
|
2005
|
+
}
|
|
2006
|
+
function incrementNodeInspectorPort(args) {
|
|
2007
|
+
return args.map((arg) => {
|
|
2008
|
+
if (!arg.startsWith("--inspect")) {
|
|
2009
|
+
return arg;
|
|
2010
|
+
}
|
|
2011
|
+
let debugOption;
|
|
2012
|
+
let debugHost = "127.0.0.1";
|
|
2013
|
+
let debugPort = "9229";
|
|
2014
|
+
let match;
|
|
2015
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
|
|
2016
|
+
debugOption = match[1];
|
|
2017
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
2018
|
+
debugOption = match[1];
|
|
2019
|
+
if (/^\d+$/.test(match[3])) {
|
|
2020
|
+
debugPort = match[3];
|
|
2021
|
+
} else {
|
|
2022
|
+
debugHost = match[3];
|
|
2023
|
+
}
|
|
2024
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
2025
|
+
debugOption = match[1];
|
|
2026
|
+
debugHost = match[3];
|
|
2027
|
+
debugPort = match[4];
|
|
2028
|
+
}
|
|
2029
|
+
if (debugOption && debugPort !== "0") {
|
|
2030
|
+
return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
2031
|
+
}
|
|
2032
|
+
return arg;
|
|
2033
|
+
});
|
|
2034
|
+
}
|
|
2035
|
+
function useColor() {
|
|
2036
|
+
if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
|
|
2037
|
+
return false;
|
|
2038
|
+
if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== undefined)
|
|
2039
|
+
return true;
|
|
2040
|
+
return;
|
|
2041
|
+
}
|
|
4
2042
|
|
|
5
|
-
//
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
2043
|
+
// ../../node_modules/.bun/commander@15.0.0/node_modules/commander/index.js
|
|
2044
|
+
var program = new Command;
|
|
2045
|
+
|
|
2046
|
+
// src/commands/create.ts
|
|
2047
|
+
import { execFile as execFileCallback, spawn } from "node:child_process";
|
|
2048
|
+
import { mkdir as mkdir2, readdir as readdir3, writeFile as writeFile3 } from "node:fs/promises";
|
|
2049
|
+
import { dirname as dirname2, join as join9, relative, resolve as resolve5 } from "node:path";
|
|
2050
|
+
import { promisify } from "node:util";
|
|
2051
|
+
|
|
2052
|
+
// src/lib/cli-output.ts
|
|
2053
|
+
async function withStdoutRedirected(redirect, work) {
|
|
2054
|
+
if (!redirect)
|
|
2055
|
+
return work();
|
|
2056
|
+
const original = { log: console.log, info: console.info, debug: console.debug };
|
|
2057
|
+
const toStderr = (...args) => console.error(...args);
|
|
2058
|
+
console.log = toStderr;
|
|
2059
|
+
console.info = toStderr;
|
|
2060
|
+
console.debug = toStderr;
|
|
2061
|
+
try {
|
|
2062
|
+
return await work();
|
|
2063
|
+
} finally {
|
|
2064
|
+
console.log = original.log;
|
|
2065
|
+
console.info = original.info;
|
|
2066
|
+
console.debug = original.debug;
|
|
2067
|
+
}
|
|
2068
|
+
}
|
|
2069
|
+
function fail(json, message, field) {
|
|
2070
|
+
if (json) {
|
|
2071
|
+
console.log(JSON.stringify({ ok: false, error: message, ...field ? { field } : {} }));
|
|
2072
|
+
} else {
|
|
2073
|
+
console.error(`Error: ${message}${field ? ` (field: ${field})` : ""}`);
|
|
2074
|
+
}
|
|
2075
|
+
process.exit(1);
|
|
2076
|
+
}
|
|
2077
|
+
|
|
2078
|
+
// src/lib/package-manager.ts
|
|
2079
|
+
var PACKAGE_MANAGERS = ["bun", "npm", "pnpm", "yarn"];
|
|
2080
|
+
function isPackageManager(value) {
|
|
2081
|
+
return PACKAGE_MANAGERS.includes(value);
|
|
2082
|
+
}
|
|
2083
|
+
function detectPackageManager(input) {
|
|
2084
|
+
if (input.flag !== undefined) {
|
|
2085
|
+
if (!isPackageManager(input.flag)) {
|
|
2086
|
+
throw new Error(`unknown package manager '${input.flag}' — use one of ${PACKAGE_MANAGERS.join(", ")}`);
|
|
2087
|
+
}
|
|
2088
|
+
return input.flag;
|
|
2089
|
+
}
|
|
2090
|
+
const agent = input.userAgent?.split("/")[0];
|
|
2091
|
+
return agent !== undefined && isPackageManager(agent) ? agent : "npm";
|
|
2092
|
+
}
|
|
2093
|
+
var COMMANDS = {
|
|
2094
|
+
bun: { install: "bun install", frozenInstall: "bun install --frozen-lockfile", run: "bun run" },
|
|
2095
|
+
npm: { install: "npm install", frozenInstall: "npm ci", run: "npm run" },
|
|
2096
|
+
pnpm: { install: "pnpm install", frozenInstall: "pnpm install --frozen-lockfile", run: "pnpm run" },
|
|
2097
|
+
yarn: { install: "yarn install", frozenInstall: "yarn install --frozen-lockfile", run: "yarn" }
|
|
2098
|
+
};
|
|
2099
|
+
function packageManagerCommands(pm) {
|
|
2100
|
+
return COMMANDS[pm];
|
|
2101
|
+
}
|
|
2102
|
+
|
|
2103
|
+
// src/lib/page-write.ts
|
|
2104
|
+
import { join } from "node:path";
|
|
2105
|
+
import { FileSystemContentAPI, normalizeAndValidatePathname, readSitesConfig } from "@conloca/content-api/node";
|
|
2106
|
+
var EMPTY_PUCK_DATA = { root: {}, content: [], zones: {} };
|
|
2107
|
+
|
|
2108
|
+
class PageWriteError extends Error {
|
|
2109
|
+
reason;
|
|
2110
|
+
field;
|
|
2111
|
+
constructor(reason, message, field) {
|
|
2112
|
+
super(message);
|
|
2113
|
+
this.reason = reason;
|
|
2114
|
+
this.field = field;
|
|
2115
|
+
this.name = "PageWriteError";
|
|
2116
|
+
}
|
|
2117
|
+
}
|
|
2118
|
+
async function writePage(input) {
|
|
2119
|
+
if (!input.pathname.startsWith("/")) {
|
|
2120
|
+
throw new PageWriteError("missing_leading_slash", `pathname must start with '/' (got '${input.pathname}')`, "pathname");
|
|
2121
|
+
}
|
|
2122
|
+
const pathnameCheck = normalizeAndValidatePathname(input.pathname);
|
|
2123
|
+
if (!pathnameCheck.valid) {
|
|
2124
|
+
throw new PageWriteError("invalid_pathname", `Invalid pathname '${input.pathname}': ${pathnameCheck.message}`, "pathname");
|
|
2125
|
+
}
|
|
2126
|
+
const pathname = pathnameCheck.value;
|
|
2127
|
+
const sitesConfig = await readSitesConfig(input.contentRoot);
|
|
2128
|
+
const siteConfig = Object.hasOwn(sitesConfig.sites, input.site) ? sitesConfig.sites[input.site] : undefined;
|
|
2129
|
+
if (!siteConfig) {
|
|
2130
|
+
const existing = Object.keys(sitesConfig.sites);
|
|
2131
|
+
if (existing.length === 0) {
|
|
2132
|
+
throw new PageWriteError("no_sites_configured", `Site '${input.site}' is not in sites.json and no sites are configured`, "site");
|
|
2133
|
+
}
|
|
2134
|
+
throw new PageWriteError("unknown_site", `Site '${input.site}' is not in sites.json. Existing sites: ${existing.join(", ")}`, "site");
|
|
2135
|
+
}
|
|
2136
|
+
const locale = siteConfig.defaultLocale;
|
|
2137
|
+
if (!locale) {
|
|
2138
|
+
throw new PageWriteError("no_default_locale", `Site '${input.site}' has no defaultLocale in sites.json — add one before creating pages`, "site");
|
|
2139
|
+
}
|
|
2140
|
+
const api = await FileSystemContentAPI.create({ contentRoot: input.contentRoot });
|
|
2141
|
+
const result = await api.createContent({
|
|
2142
|
+
kind: "page",
|
|
2143
|
+
site: input.site,
|
|
2144
|
+
collection: input.collection,
|
|
2145
|
+
type: "puck",
|
|
2146
|
+
locales: {
|
|
2147
|
+
[locale]: {
|
|
2148
|
+
pathname,
|
|
2149
|
+
meta: { title: input.title },
|
|
2150
|
+
content: { puckData: input.puckData ?? EMPTY_PUCK_DATA }
|
|
2151
|
+
}
|
|
2152
|
+
}
|
|
2153
|
+
});
|
|
2154
|
+
if (!result.success || !result.id) {
|
|
2155
|
+
throw new PageWriteError("write_failed", result.error?.message ?? `Create failed (${result.reason ?? "unknown reason"})`, result.field);
|
|
2156
|
+
}
|
|
2157
|
+
const basePath = pathname === "/" ? "index" : pathname.slice(1);
|
|
2158
|
+
const filePath = join(input.contentRoot, input.site, input.collection, `${basePath}.${locale}.vxjson`);
|
|
2159
|
+
return { id: result.id, pathname, filePath };
|
|
2160
|
+
}
|
|
2161
|
+
|
|
2162
|
+
// src/lib/project-template.ts
|
|
2163
|
+
import { readFile } from "node:fs/promises";
|
|
2164
|
+
import { basename } from "node:path";
|
|
2165
|
+
var THIRD_PARTY_VERSIONS = {
|
|
2166
|
+
astro: "^7.3.1",
|
|
2167
|
+
"@astrojs/node": "^11.1.5",
|
|
2168
|
+
"@astrojs/react": "^6.0.5",
|
|
2169
|
+
"@puckeditor/core": "^0.23.0",
|
|
2170
|
+
"@vitejs/plugin-react": "^5.2.0",
|
|
2171
|
+
react: "19.2.8",
|
|
2172
|
+
"react-dom": "19.2.8",
|
|
2173
|
+
zod: "^4.5.4",
|
|
2174
|
+
"@astrojs/check": "^0.9.10"
|
|
2175
|
+
};
|
|
2176
|
+
var DEV_ONLY = new Set(["@astrojs/check"]);
|
|
2177
|
+
var MANIFEST_CANDIDATES = ["../package.json", "../../package.json"];
|
|
2178
|
+
async function readCliManifest() {
|
|
2179
|
+
for (const candidate of MANIFEST_CANDIDATES) {
|
|
2180
|
+
let manifest;
|
|
2181
|
+
try {
|
|
2182
|
+
manifest = JSON.parse(await readFile(new URL(candidate, import.meta.url), "utf-8"));
|
|
2183
|
+
} catch {
|
|
2184
|
+
continue;
|
|
2185
|
+
}
|
|
2186
|
+
if (typeof manifest.version === "string") {
|
|
2187
|
+
return { version: manifest.version, dependencies: manifest.dependencies };
|
|
2188
|
+
}
|
|
2189
|
+
}
|
|
2190
|
+
throw new Error("could not read the version of @conloca/cli from its own package.json");
|
|
2191
|
+
}
|
|
2192
|
+
function packageNameOf(directory) {
|
|
2193
|
+
const name = basename(directory).toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[._-]+|[._-]+$/g, "");
|
|
2194
|
+
return name === "" ? "conloca-site" : name;
|
|
2195
|
+
}
|
|
2196
|
+
var SCAFFOLD_CONLOCA_PACKAGES = ["@conloca/astro-cms", "@conloca/content-api"];
|
|
2197
|
+
function conlocaRange(manifest, name) {
|
|
2198
|
+
const declared = manifest.dependencies?.[name];
|
|
2199
|
+
return declared === undefined || declared.startsWith("workspace:") ? manifest.version : declared;
|
|
2200
|
+
}
|
|
2201
|
+
function renderPackageJson(input) {
|
|
2202
|
+
const dependencies = {};
|
|
2203
|
+
for (const name of SCAFFOLD_CONLOCA_PACKAGES) {
|
|
2204
|
+
dependencies[name] = conlocaRange(input.manifest, name);
|
|
2205
|
+
}
|
|
2206
|
+
const devDependencies = { "@conloca/cli": input.manifest.version };
|
|
2207
|
+
for (const [name, range] of Object.entries(THIRD_PARTY_VERSIONS)) {
|
|
2208
|
+
(DEV_ONLY.has(name) ? devDependencies : dependencies)[name] = range;
|
|
2209
|
+
}
|
|
2210
|
+
const sorted = (record) => Object.fromEntries(Object.entries(record).sort(([a], [b]) => a.localeCompare(b)));
|
|
2211
|
+
return `${JSON.stringify({
|
|
2212
|
+
name: input.name,
|
|
2213
|
+
version: "0.0.1",
|
|
2214
|
+
private: true,
|
|
2215
|
+
type: "module",
|
|
2216
|
+
scripts: { dev: "astro dev", build: "astro build", preview: "astro preview", doctor: "conloca doctor" },
|
|
2217
|
+
dependencies: sorted(dependencies),
|
|
2218
|
+
devDependencies: sorted(devDependencies)
|
|
2219
|
+
}, null, 2)}
|
|
2220
|
+
`;
|
|
2221
|
+
}
|
|
2222
|
+
var SETUP_STEPS = {
|
|
2223
|
+
bun: ` - uses: oven-sh/setup-bun@v2
|
|
2224
|
+
`,
|
|
2225
|
+
npm: ` - uses: actions/setup-node@v4
|
|
2226
|
+
with:
|
|
2227
|
+
node-version: 22
|
|
2228
|
+
cache: npm
|
|
2229
|
+
`,
|
|
2230
|
+
pnpm: ` - uses: pnpm/action-setup@v4
|
|
2231
|
+
with:
|
|
2232
|
+
version: 10
|
|
2233
|
+
- uses: actions/setup-node@v4
|
|
2234
|
+
with:
|
|
2235
|
+
node-version: 22
|
|
2236
|
+
cache: pnpm
|
|
2237
|
+
`,
|
|
2238
|
+
yarn: ` - uses: actions/setup-node@v4
|
|
2239
|
+
with:
|
|
2240
|
+
node-version: 22
|
|
2241
|
+
cache: yarn
|
|
2242
|
+
`
|
|
2243
|
+
};
|
|
2244
|
+
function renderWorkflow(pm) {
|
|
2245
|
+
const commands = packageManagerCommands(pm);
|
|
2246
|
+
return `name: Conloca
|
|
2247
|
+
|
|
2248
|
+
on: [push, pull_request]
|
|
2249
|
+
|
|
2250
|
+
jobs:
|
|
2251
|
+
build:
|
|
2252
|
+
runs-on: ubuntu-latest
|
|
2253
|
+
steps:
|
|
2254
|
+
- uses: actions/checkout@v4
|
|
2255
|
+
with:
|
|
2256
|
+
# On a pull request, build the branch's own commit rather than GitHub's
|
|
2257
|
+
# temporary merge commit, so a build that reports its commit names a real one.
|
|
2258
|
+
ref: \${{ github.event.pull_request.head.sha || github.sha }}
|
|
2259
|
+
${SETUP_STEPS[pm]} - run: ${commands.frozenInstall}
|
|
2260
|
+
# Slot for a build integration that is not part of this scaffold; nothing reads
|
|
2261
|
+
# this secret until you add one. Given to doctor and the build only, never to
|
|
2262
|
+
# dependency install scripts.
|
|
2263
|
+
- run: ${commands.run} doctor
|
|
2264
|
+
env:
|
|
2265
|
+
CONLOCA_BUILD_TOKEN: \${{ secrets.CONLOCA_BUILD_TOKEN }}
|
|
2266
|
+
- run: ${commands.run} build
|
|
2267
|
+
env:
|
|
2268
|
+
CONLOCA_BUILD_TOKEN: \${{ secrets.CONLOCA_BUILD_TOKEN }}
|
|
2269
|
+
`;
|
|
2270
|
+
}
|
|
2271
|
+
|
|
2272
|
+
// src/templates/project-files.ts
|
|
2273
|
+
function renderAstroConfig(siteName) {
|
|
2274
|
+
const literal = siteName.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
|
|
2275
|
+
return `// @ts-check
|
|
2276
|
+
import node from '@astrojs/node';
|
|
2277
|
+
import react from '@astrojs/react';
|
|
2278
|
+
import { conlocaCMS } from '@conloca/astro-cms/node';
|
|
2279
|
+
import { defineConfig } from 'astro/config';
|
|
2280
|
+
|
|
2281
|
+
export default defineConfig({
|
|
2282
|
+
output: 'server',
|
|
2283
|
+
adapter: node({ mode: 'standalone' }),
|
|
2284
|
+
integrations: [
|
|
2285
|
+
// react() must come before conlocaCMS(): the visual editor is a React app.
|
|
2286
|
+
react(),
|
|
2287
|
+
conlocaCMS({
|
|
2288
|
+
contentRoot: './content',
|
|
2289
|
+
puckConfigPath: './src/puck.config.tsx',
|
|
2290
|
+
schemasPath: './src/schemas/data.ts',
|
|
2291
|
+
routing: {
|
|
2292
|
+
routes: {
|
|
2293
|
+
pages: {
|
|
2294
|
+
pattern: '/[...slug]',
|
|
2295
|
+
collection: 'pages',
|
|
2296
|
+
layout: './src/layouts/Layout.astro',
|
|
2297
|
+
},
|
|
2298
|
+
},
|
|
2299
|
+
fallback: '404',
|
|
2300
|
+
siteName: '${literal}',
|
|
2301
|
+
locale: 'en',
|
|
2302
|
+
},
|
|
2303
|
+
}),
|
|
2304
|
+
],
|
|
2305
|
+
});
|
|
2306
|
+
`;
|
|
2307
|
+
}
|
|
2308
|
+
var TSCONFIG_TEMPLATE = `{
|
|
2309
|
+
"extends": "astro/tsconfigs/strict",
|
|
2310
|
+
"compilerOptions": {
|
|
2311
|
+
"jsx": "react-jsx",
|
|
2312
|
+
"jsxImportSource": "react"
|
|
2313
|
+
},
|
|
2314
|
+
"include": [".astro/types.d.ts", "**/*"],
|
|
2315
|
+
"exclude": ["dist"]
|
|
2316
|
+
}
|
|
2317
|
+
`;
|
|
2318
|
+
var CONTENT_CONFIG_TEMPLATE = `import { conlocaData, conlocaFragments, conlocaPages } from '@conloca/astro-cms/node/content';
|
|
2319
|
+
import { dataSchemas } from './schemas/data';
|
|
2320
|
+
|
|
2321
|
+
export const collections = {
|
|
2322
|
+
pages: conlocaPages(),
|
|
2323
|
+
...conlocaData({ dataSchemas }),
|
|
2324
|
+
...conlocaFragments(),
|
|
2325
|
+
};
|
|
2326
|
+
`;
|
|
2327
|
+
var GITIGNORE_TEMPLATE = `# build output
|
|
2328
|
+
dist/
|
|
2329
|
+
# generated types
|
|
2330
|
+
.astro/
|
|
2331
|
+
# dependencies
|
|
2332
|
+
node_modules/
|
|
2333
|
+
# environment variables
|
|
2334
|
+
.env
|
|
2335
|
+
.env.production
|
|
2336
|
+
# Conloca build output
|
|
2337
|
+
.conloca/
|
|
2338
|
+
# OS files
|
|
2339
|
+
.DS_Store
|
|
2340
|
+
`;
|
|
2341
|
+
function renderReadme(name, runPrefix) {
|
|
2342
|
+
return `# ${name}
|
|
2343
|
+
|
|
2344
|
+
An Astro site edited with [Conloca CMS](https://conloca.com).
|
|
2345
|
+
|
|
2346
|
+
- \`${runPrefix} dev\` — start the site, then open http://localhost:4321/__cms to edit pages.
|
|
2347
|
+
- \`${runPrefix} build\` — production build.
|
|
2348
|
+
- \`${runPrefix} doctor\` — check the Conloca setup; run it first whenever something looks wrong.
|
|
2349
|
+
|
|
2350
|
+
CI installs from the lockfile, so commit it.
|
|
2351
|
+
|
|
2352
|
+
Pages live in \`content/\` as \`.vxjson\` files built from the components in \`src/components/puck/\`.
|
|
2353
|
+
Working with a coding agent? \`.claude/skills/conloca/SKILL.md\` teaches it Conloca.
|
|
2354
|
+
`;
|
|
2355
|
+
}
|
|
2356
|
+
|
|
2357
|
+
// src/commands/doctor.ts
|
|
2358
|
+
import { readdir as readdir2, readFile as readFile5, stat } from "node:fs/promises";
|
|
2359
|
+
import { join as join6, resolve as resolve3 } from "node:path";
|
|
2360
|
+
import { ContentIndex, FileSystemReaderBackend } from "@conloca/content-api/node";
|
|
2361
|
+
|
|
2362
|
+
// src/lib/content-root.ts
|
|
2363
|
+
import { existsSync } from "node:fs";
|
|
2364
|
+
import { basename as basename2, join as join2, resolve } from "node:path";
|
|
2365
|
+
function contentRootOf(directory) {
|
|
9
2366
|
const resolvedPath = resolve(directory);
|
|
10
|
-
const
|
|
2367
|
+
const nested = join2(resolvedPath, "content");
|
|
2368
|
+
if (basename2(resolvedPath) === "content" && !existsSync(join2(nested, "sites.json"))) {
|
|
2369
|
+
return resolvedPath;
|
|
2370
|
+
}
|
|
2371
|
+
return nested;
|
|
2372
|
+
}
|
|
2373
|
+
|
|
2374
|
+
// src/lib/is-record.ts
|
|
2375
|
+
function isRecord(value) {
|
|
2376
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2377
|
+
}
|
|
2378
|
+
|
|
2379
|
+
// src/lib/message-of.ts
|
|
2380
|
+
function messageOf(error) {
|
|
2381
|
+
return error instanceof Error ? error.message : String(error);
|
|
2382
|
+
}
|
|
2383
|
+
|
|
2384
|
+
// src/commands/doctor-astro.ts
|
|
2385
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
2386
|
+
import { readdir, readFile as readFile3 } from "node:fs/promises";
|
|
2387
|
+
import { join as join4 } from "node:path";
|
|
2388
|
+
|
|
2389
|
+
// src/lib/project-dependencies.ts
|
|
2390
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
2391
|
+
import { join as join3 } from "node:path";
|
|
2392
|
+
async function readProjectDependencies(projectDir) {
|
|
2393
|
+
let raw;
|
|
2394
|
+
try {
|
|
2395
|
+
raw = await readFile2(join3(projectDir, "package.json"), "utf-8");
|
|
2396
|
+
} catch {
|
|
2397
|
+
return "missing";
|
|
2398
|
+
}
|
|
2399
|
+
let parsed;
|
|
2400
|
+
try {
|
|
2401
|
+
parsed = JSON.parse(raw);
|
|
2402
|
+
} catch {
|
|
2403
|
+
return "unreadable";
|
|
2404
|
+
}
|
|
2405
|
+
if (!isRecord(parsed))
|
|
2406
|
+
return "unreadable";
|
|
2407
|
+
const deps = new Set;
|
|
2408
|
+
for (const field of ["dependencies", "devDependencies"]) {
|
|
2409
|
+
const section = parsed[field];
|
|
2410
|
+
if (isRecord(section)) {
|
|
2411
|
+
for (const name of Object.keys(section))
|
|
2412
|
+
deps.add(name);
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
return { deps };
|
|
2416
|
+
}
|
|
2417
|
+
|
|
2418
|
+
// src/commands/doctor-astro.ts
|
|
2419
|
+
var ASTRO_CONFIG_NAMES = ["astro.config.mjs", "astro.config.ts", "astro.config.js"];
|
|
2420
|
+
var CMS_PEERS = ["zod", "@vitejs/plugin-react"];
|
|
2421
|
+
var PAGE_FILE_RE = /\.(?:astro|ts|md|mdx)$/;
|
|
2422
|
+
var OPENERS = { "(": ")", "{": "}", "[": "]" };
|
|
2423
|
+
var CLOSERS = new Set([")", "}", "]"]);
|
|
2424
|
+
var QUOTES = new Set(["'", '"', "`"]);
|
|
2425
|
+
function skipString(text, index) {
|
|
2426
|
+
const quote = text[index];
|
|
2427
|
+
let i = index + 1;
|
|
2428
|
+
while (i < text.length) {
|
|
2429
|
+
if (text[i] === "\\")
|
|
2430
|
+
i += 2;
|
|
2431
|
+
else if (text[i] === quote)
|
|
2432
|
+
return i + 1;
|
|
2433
|
+
else
|
|
2434
|
+
i += 1;
|
|
2435
|
+
}
|
|
2436
|
+
return i;
|
|
2437
|
+
}
|
|
2438
|
+
function stripComments(source) {
|
|
2439
|
+
const chars = source.split("");
|
|
2440
|
+
let i = 0;
|
|
2441
|
+
while (i < chars.length) {
|
|
2442
|
+
if (QUOTES.has(chars[i])) {
|
|
2443
|
+
i = skipString(source, i);
|
|
2444
|
+
} else if (chars[i] === "/" && chars[i + 1] === "/") {
|
|
2445
|
+
while (i < chars.length && chars[i] !== `
|
|
2446
|
+
`)
|
|
2447
|
+
chars[i++] = " ";
|
|
2448
|
+
} else if (chars[i] === "/" && chars[i + 1] === "*") {
|
|
2449
|
+
while (i < chars.length && !(chars[i] === "*" && chars[i + 1] === "/")) {
|
|
2450
|
+
if (chars[i] !== `
|
|
2451
|
+
`)
|
|
2452
|
+
chars[i] = " ";
|
|
2453
|
+
i += 1;
|
|
2454
|
+
}
|
|
2455
|
+
if (i < chars.length) {
|
|
2456
|
+
chars[i] = " ";
|
|
2457
|
+
chars[i + 1] = " ";
|
|
2458
|
+
i += 2;
|
|
2459
|
+
}
|
|
2460
|
+
} else {
|
|
2461
|
+
i += 1;
|
|
2462
|
+
}
|
|
2463
|
+
}
|
|
2464
|
+
return chars.join("");
|
|
2465
|
+
}
|
|
2466
|
+
function balancedSlice(text, openIndex) {
|
|
2467
|
+
const closer = OPENERS[text[openIndex]];
|
|
2468
|
+
let depth = 0;
|
|
2469
|
+
let i = openIndex;
|
|
2470
|
+
while (i < text.length) {
|
|
2471
|
+
const ch = text[i];
|
|
2472
|
+
if (QUOTES.has(ch)) {
|
|
2473
|
+
i = skipString(text, i);
|
|
2474
|
+
continue;
|
|
2475
|
+
}
|
|
2476
|
+
if (OPENERS[ch]) {
|
|
2477
|
+
depth += 1;
|
|
2478
|
+
} else if (CLOSERS.has(ch)) {
|
|
2479
|
+
depth -= 1;
|
|
2480
|
+
if (depth === 0)
|
|
2481
|
+
return ch === closer ? text.slice(openIndex, i + 1) : null;
|
|
2482
|
+
}
|
|
2483
|
+
i += 1;
|
|
2484
|
+
}
|
|
2485
|
+
return null;
|
|
2486
|
+
}
|
|
2487
|
+
function skipValue(text, start) {
|
|
2488
|
+
let depth = 0;
|
|
2489
|
+
let i = start;
|
|
2490
|
+
while (i < text.length) {
|
|
2491
|
+
const ch = text[i];
|
|
2492
|
+
if (QUOTES.has(ch)) {
|
|
2493
|
+
i = skipString(text, i);
|
|
2494
|
+
continue;
|
|
2495
|
+
}
|
|
2496
|
+
if (OPENERS[ch])
|
|
2497
|
+
depth += 1;
|
|
2498
|
+
else if (CLOSERS.has(ch))
|
|
2499
|
+
depth -= 1;
|
|
2500
|
+
else if (ch === "," && depth === 0)
|
|
2501
|
+
return i;
|
|
2502
|
+
i += 1;
|
|
2503
|
+
}
|
|
2504
|
+
return i;
|
|
2505
|
+
}
|
|
2506
|
+
function containsOutsideStrings(text, needle) {
|
|
2507
|
+
let i = 0;
|
|
2508
|
+
while (i < text.length) {
|
|
2509
|
+
if (QUOTES.has(text[i])) {
|
|
2510
|
+
i = skipString(text, i);
|
|
2511
|
+
continue;
|
|
2512
|
+
}
|
|
2513
|
+
if (text.startsWith(needle, i))
|
|
2514
|
+
return true;
|
|
2515
|
+
i += 1;
|
|
2516
|
+
}
|
|
2517
|
+
return false;
|
|
2518
|
+
}
|
|
2519
|
+
function parseObjectEntries(objectText) {
|
|
2520
|
+
if (!objectText.startsWith("{") || !objectText.endsWith("}"))
|
|
2521
|
+
return null;
|
|
2522
|
+
const body = objectText.slice(1, -1);
|
|
2523
|
+
const entries = new Map;
|
|
2524
|
+
let hasSpread = false;
|
|
2525
|
+
let i = 0;
|
|
2526
|
+
while (i < body.length) {
|
|
2527
|
+
if (/[\s,]/.test(body[i])) {
|
|
2528
|
+
i += 1;
|
|
2529
|
+
continue;
|
|
2530
|
+
}
|
|
2531
|
+
if (body.startsWith("...", i)) {
|
|
2532
|
+
hasSpread = true;
|
|
2533
|
+
i = skipValue(body, i + 3);
|
|
2534
|
+
continue;
|
|
2535
|
+
}
|
|
2536
|
+
const keyMatch = /^(?:([$A-Za-z_][$\w]*)|'([^']*)'|"([^"]*)")\s*:/.exec(body.slice(i));
|
|
2537
|
+
if (!keyMatch) {
|
|
2538
|
+
i = skipValue(body, i);
|
|
2539
|
+
continue;
|
|
2540
|
+
}
|
|
2541
|
+
const valueStart = i + keyMatch[0].length;
|
|
2542
|
+
const valueEnd = skipValue(body, valueStart);
|
|
2543
|
+
entries.set(keyMatch[1] ?? keyMatch[2] ?? keyMatch[3] ?? "", body.slice(valueStart, valueEnd).trim());
|
|
2544
|
+
i = valueEnd;
|
|
2545
|
+
}
|
|
2546
|
+
return { entries, hasSpread };
|
|
2547
|
+
}
|
|
2548
|
+
function stringLiteral(raw) {
|
|
2549
|
+
const match = /^(?:'([^'\\]*)'|"([^"\\]*)")$/.exec(raw.trim());
|
|
2550
|
+
return match === null ? null : match[1] ?? match[2] ?? "";
|
|
2551
|
+
}
|
|
2552
|
+
function extractCmsOptions(configText) {
|
|
2553
|
+
const call = /\bconlocaCMS\s*\(/.exec(configText);
|
|
2554
|
+
if (!call)
|
|
2555
|
+
return { state: "no-call" };
|
|
2556
|
+
const args = balancedSlice(configText, call.index + call[0].length - 1);
|
|
2557
|
+
if (args === null)
|
|
2558
|
+
return { state: "dynamic" };
|
|
2559
|
+
const inner = args.slice(1, -1).trim();
|
|
2560
|
+
if (inner === "")
|
|
2561
|
+
return { state: "literal", entries: new Map, hasSpread: false };
|
|
2562
|
+
if (!inner.startsWith("{"))
|
|
2563
|
+
return { state: "dynamic" };
|
|
2564
|
+
const objectText = balancedSlice(inner, 0);
|
|
2565
|
+
const parsed = objectText === null ? null : parseObjectEntries(objectText);
|
|
2566
|
+
return parsed === null ? { state: "dynamic" } : { state: "literal", ...parsed };
|
|
2567
|
+
}
|
|
2568
|
+
var ASTRO_CHECK_LABELS = {
|
|
2569
|
+
C1: "content config registers Conloca collections",
|
|
2570
|
+
C2: "siteName matches a sites.json entry",
|
|
2571
|
+
C5: "conlocaCMS is imported from @conloca/astro-cms/node",
|
|
2572
|
+
C6: "conlocaCMS options are complete",
|
|
2573
|
+
C7: "react() is wired before conlocaCMS()",
|
|
2574
|
+
C8: "CMS peer dependencies are declared",
|
|
2575
|
+
C9: "tsconfig compilerOptions.jsx suits Puck components",
|
|
2576
|
+
C10: "server-output pages declare prerender",
|
|
2577
|
+
C11: "no static page shadows the CMS home"
|
|
2578
|
+
};
|
|
2579
|
+
function outcomeOf(id) {
|
|
2580
|
+
return { id, label: ASTRO_CHECK_LABELS[id], problems: [] };
|
|
2581
|
+
}
|
|
2582
|
+
async function checkContentConfig(projectDir) {
|
|
2583
|
+
const outcome = outcomeOf("C1");
|
|
2584
|
+
const { CONTENT_CONFIG_SNIPPET, findContentConfigProblem } = await import("@conloca/astro-cms/checks");
|
|
2585
|
+
const problem = findContentConfigProblem(projectDir);
|
|
2586
|
+
if (problem === "missing") {
|
|
2587
|
+
outcome.problems.push({
|
|
2588
|
+
check: "C1",
|
|
2589
|
+
level: "error",
|
|
2590
|
+
message: `no content config found — without it every CMS page 404s; create src/content.config.ts:
|
|
2591
|
+
${CONTENT_CONFIG_SNIPPET}`,
|
|
2592
|
+
path: join4(projectDir, "src", "content.config.ts")
|
|
2593
|
+
});
|
|
2594
|
+
} else if (problem === "not-wired") {
|
|
2595
|
+
outcome.problems.push({
|
|
2596
|
+
check: "C1",
|
|
2597
|
+
level: "error",
|
|
2598
|
+
message: `the content config never registers Conloca's collections, so every CMS page 404s — wire it like:
|
|
2599
|
+
${CONTENT_CONFIG_SNIPPET}`
|
|
2600
|
+
});
|
|
2601
|
+
}
|
|
2602
|
+
return outcome;
|
|
2603
|
+
}
|
|
2604
|
+
function resolveSiteNameText(options) {
|
|
2605
|
+
const candidates = [];
|
|
2606
|
+
let undeterminable = options.hasSpread;
|
|
2607
|
+
const routingRaw = options.entries.get("routing");
|
|
2608
|
+
if (routingRaw !== undefined && routingRaw !== "true" && routingRaw !== "false") {
|
|
2609
|
+
const routing = routingRaw.startsWith("{") ? parseObjectEntries(balancedSlice(routingRaw, 0) ?? "") : null;
|
|
2610
|
+
if (routing === null) {
|
|
2611
|
+
undeterminable = true;
|
|
2612
|
+
} else {
|
|
2613
|
+
if (routing.hasSpread)
|
|
2614
|
+
undeterminable = true;
|
|
2615
|
+
const nested = routing.entries.get("siteName");
|
|
2616
|
+
if (nested !== undefined)
|
|
2617
|
+
candidates.push(nested);
|
|
2618
|
+
}
|
|
2619
|
+
}
|
|
2620
|
+
const topLevel = options.entries.get("siteName");
|
|
2621
|
+
if (topLevel !== undefined)
|
|
2622
|
+
candidates.push(topLevel);
|
|
2623
|
+
if (candidates.length === 0)
|
|
2624
|
+
return undeterminable ? { kind: "undeterminable" } : { kind: "absent" };
|
|
2625
|
+
const name = stringLiteral(candidates[0]);
|
|
2626
|
+
return name === null ? { kind: "undeterminable" } : { kind: "literal", name };
|
|
2627
|
+
}
|
|
2628
|
+
function checkSiteName(options, siteNames) {
|
|
2629
|
+
const outcome = outcomeOf("C2");
|
|
2630
|
+
if (siteNames === null) {
|
|
2631
|
+
outcome.skipped = "sites.json is unusable";
|
|
2632
|
+
return outcome;
|
|
2633
|
+
}
|
|
2634
|
+
if (options.state === "no-call") {
|
|
2635
|
+
outcome.skipped = "conlocaCMS is not called in the astro config";
|
|
2636
|
+
return outcome;
|
|
2637
|
+
}
|
|
2638
|
+
if (options.state === "dynamic") {
|
|
2639
|
+
outcome.problems.push({
|
|
2640
|
+
check: "C2",
|
|
2641
|
+
level: "warn",
|
|
2642
|
+
message: "doctor could not determine siteName — the conlocaCMS options are not a plain object literal; check manually that siteName matches a sites.json entry"
|
|
2643
|
+
});
|
|
2644
|
+
return outcome;
|
|
2645
|
+
}
|
|
2646
|
+
const resolution = resolveSiteNameText(options);
|
|
2647
|
+
if (resolution.kind === "undeterminable") {
|
|
2648
|
+
outcome.problems.push({
|
|
2649
|
+
check: "C2",
|
|
2650
|
+
level: "warn",
|
|
2651
|
+
message: "doctor could not determine siteName (not a plain string literal) — check manually that it matches a sites.json entry"
|
|
2652
|
+
});
|
|
2653
|
+
} else if (resolution.kind === "absent") {
|
|
2654
|
+
if (siteNames.length === 0) {
|
|
2655
|
+
outcome.problems.push({
|
|
2656
|
+
check: "C2",
|
|
2657
|
+
level: "error",
|
|
2658
|
+
message: "sites.json declares no sites — add a site entry so the CMS has a site to serve"
|
|
2659
|
+
});
|
|
2660
|
+
} else {
|
|
2661
|
+
outcome.detail = `defaults to first site "${siteNames[0]}"`;
|
|
2662
|
+
}
|
|
2663
|
+
} else if (siteNames.includes(resolution.name)) {
|
|
2664
|
+
outcome.detail = `siteName "${resolution.name}"`;
|
|
2665
|
+
} else {
|
|
2666
|
+
outcome.problems.push({
|
|
2667
|
+
check: "C2",
|
|
2668
|
+
level: "error",
|
|
2669
|
+
message: `siteName "${resolution.name}" has no sites.json entry — add it to sites.json or set siteName to one of: ${siteNames.join(", ")}`
|
|
2670
|
+
});
|
|
2671
|
+
}
|
|
2672
|
+
return outcome;
|
|
2673
|
+
}
|
|
2674
|
+
function checkImportSource(configText) {
|
|
2675
|
+
const outcome = outcomeOf("C5");
|
|
2676
|
+
const importRe = /import\s+([^;]*?)\s+from\s*(['"])([^'"]+)\2/g;
|
|
2677
|
+
for (const match of configText.matchAll(importRe)) {
|
|
2678
|
+
if (!/\bconlocaCMS\b/.test(match[1]))
|
|
2679
|
+
continue;
|
|
2680
|
+
const specifier = match[3];
|
|
2681
|
+
if (specifier === "@conloca/astro-cms/node")
|
|
2682
|
+
return outcome;
|
|
2683
|
+
if (specifier === "@conloca/astro-cms") {
|
|
2684
|
+
outcome.problems.push({
|
|
2685
|
+
check: "C5",
|
|
2686
|
+
level: "error",
|
|
2687
|
+
message: "conlocaCMS is imported from '@conloca/astro-cms' (the package root, which throws at runtime) — import it from '@conloca/astro-cms/node' instead"
|
|
2688
|
+
});
|
|
2689
|
+
} else {
|
|
2690
|
+
outcome.problems.push({
|
|
2691
|
+
check: "C5",
|
|
2692
|
+
level: "warn",
|
|
2693
|
+
message: `conlocaCMS is imported from '${specifier}' — doctor expects '@conloca/astro-cms/node' and cannot verify indirect imports`
|
|
2694
|
+
});
|
|
2695
|
+
}
|
|
2696
|
+
return outcome;
|
|
2697
|
+
}
|
|
2698
|
+
if (/\bconlocaCMS\b/.test(configText)) {
|
|
2699
|
+
outcome.problems.push({
|
|
2700
|
+
check: "C5",
|
|
2701
|
+
level: "warn",
|
|
2702
|
+
message: "conlocaCMS is referenced but doctor could not find its import — make sure it comes from '@conloca/astro-cms/node'"
|
|
2703
|
+
});
|
|
2704
|
+
} else {
|
|
2705
|
+
outcome.problems.push({
|
|
2706
|
+
check: "C5",
|
|
2707
|
+
level: "error",
|
|
2708
|
+
message: `conlocaCMS is not imported in the astro config — add "import { conlocaCMS } from '@conloca/astro-cms/node'" and call it in integrations`
|
|
2709
|
+
});
|
|
2710
|
+
}
|
|
2711
|
+
return outcome;
|
|
2712
|
+
}
|
|
2713
|
+
function checkCmsOptions(options) {
|
|
2714
|
+
const outcome = outcomeOf("C6");
|
|
2715
|
+
if (options.state === "no-call") {
|
|
2716
|
+
outcome.problems.push({
|
|
2717
|
+
check: "C6",
|
|
2718
|
+
level: "error",
|
|
2719
|
+
message: "conlocaCMS(...) is never called in the astro config — add it to the integrations array with contentRoot and puckConfigPath"
|
|
2720
|
+
});
|
|
2721
|
+
return outcome;
|
|
2722
|
+
}
|
|
2723
|
+
if (options.state === "dynamic") {
|
|
2724
|
+
outcome.problems.push({
|
|
2725
|
+
check: "C6",
|
|
2726
|
+
level: "warn",
|
|
2727
|
+
message: "doctor could not determine the conlocaCMS options (not a plain object literal) — check manually that contentRoot and puckConfigPath are set and a routing block or layout is present"
|
|
2728
|
+
});
|
|
2729
|
+
return outcome;
|
|
2730
|
+
}
|
|
2731
|
+
const hints = {
|
|
2732
|
+
contentRoot: "add contentRoot: './content' so the CMS knows where the content lives",
|
|
2733
|
+
puckConfigPath: "add puckConfigPath: './src/puck.config.tsx' so the editor knows the component config"
|
|
2734
|
+
};
|
|
2735
|
+
for (const [key, hint] of Object.entries(hints)) {
|
|
2736
|
+
if (options.entries.has(key))
|
|
2737
|
+
continue;
|
|
2738
|
+
outcome.problems.push({
|
|
2739
|
+
check: "C6",
|
|
2740
|
+
level: options.hasSpread ? "warn" : "error",
|
|
2741
|
+
message: options.hasSpread ? `doctor could not confirm the ${key} option (the options object uses a spread) — check that it is set` : `the conlocaCMS options are missing ${key} — ${hint}`
|
|
2742
|
+
});
|
|
2743
|
+
}
|
|
2744
|
+
if (!options.entries.has("routing") && !options.entries.has("layout")) {
|
|
2745
|
+
outcome.problems.push({
|
|
2746
|
+
check: "C6",
|
|
2747
|
+
level: options.hasSpread ? "warn" : "error",
|
|
2748
|
+
message: options.hasSpread ? "doctor could not confirm a routing block or layout option (the options object uses a spread) — check that one is set" : "the conlocaCMS options set neither routing nor layout — add a routing block (or a top-level layout) so CMS pages get rendered routes"
|
|
2749
|
+
});
|
|
2750
|
+
}
|
|
2751
|
+
return outcome;
|
|
2752
|
+
}
|
|
2753
|
+
function checkReactIntegration(projectDir, configText, pkg) {
|
|
2754
|
+
const outcome = outcomeOf("C7");
|
|
2755
|
+
if (pkg === "missing") {
|
|
2756
|
+
outcome.problems.push({
|
|
2757
|
+
check: "C7",
|
|
2758
|
+
level: "error",
|
|
2759
|
+
message: `@astrojs/react is not declared — no package.json found at ${join4(projectDir, "package.json")}; add @astrojs/react to the project's dependencies`
|
|
2760
|
+
});
|
|
2761
|
+
} else if (pkg === "unreadable") {
|
|
2762
|
+
outcome.problems.push({
|
|
2763
|
+
check: "C7",
|
|
2764
|
+
level: "warn",
|
|
2765
|
+
message: "doctor could not parse package.json — check manually that @astrojs/react is a dependency"
|
|
2766
|
+
});
|
|
2767
|
+
} else if (!pkg.deps.has("@astrojs/react")) {
|
|
2768
|
+
outcome.problems.push({
|
|
2769
|
+
check: "C7",
|
|
2770
|
+
level: "error",
|
|
2771
|
+
message: "@astrojs/react is missing from package.json — add it to dependencies; conlocaCMS renders components through the react integration"
|
|
2772
|
+
});
|
|
2773
|
+
}
|
|
2774
|
+
const integrationsKey = /\bintegrations\s*:/.exec(configText);
|
|
2775
|
+
if (!integrationsKey) {
|
|
2776
|
+
outcome.problems.push({
|
|
2777
|
+
check: "C7",
|
|
2778
|
+
level: "error",
|
|
2779
|
+
message: "react() is missing — the astro config has no integrations array; add integrations: [react(), conlocaCMS({...})]"
|
|
2780
|
+
});
|
|
2781
|
+
return outcome;
|
|
2782
|
+
}
|
|
2783
|
+
const valueText = configText.slice(integrationsKey.index + integrationsKey[0].length).trimStart();
|
|
2784
|
+
const arrayText = valueText.startsWith("[") ? balancedSlice(valueText, 0) : null;
|
|
2785
|
+
if (arrayText === null) {
|
|
2786
|
+
outcome.problems.push({
|
|
2787
|
+
check: "C7",
|
|
2788
|
+
level: "warn",
|
|
2789
|
+
message: "doctor could not read the integrations array (not a plain array literal) — check manually that react() comes before conlocaCMS()"
|
|
2790
|
+
});
|
|
2791
|
+
return outcome;
|
|
2792
|
+
}
|
|
2793
|
+
const reactIndex = arrayText.search(/\breact\s*\(/);
|
|
2794
|
+
const cmsIndex = arrayText.search(/\bconlocaCMS\s*\(/);
|
|
2795
|
+
if (reactIndex === -1) {
|
|
2796
|
+
if (containsOutsideStrings(arrayText, "...")) {
|
|
2797
|
+
outcome.problems.push({
|
|
2798
|
+
check: "C7",
|
|
2799
|
+
level: "warn",
|
|
2800
|
+
message: "doctor could not confirm react() in the integrations array (it uses a spread) — check that react() comes before conlocaCMS()"
|
|
2801
|
+
});
|
|
2802
|
+
} else {
|
|
2803
|
+
outcome.problems.push({
|
|
2804
|
+
check: "C7",
|
|
2805
|
+
level: "error",
|
|
2806
|
+
message: "react() is missing from the integrations array — add react() (from @astrojs/react) before conlocaCMS(); the CMS needs it to render React components"
|
|
2807
|
+
});
|
|
2808
|
+
}
|
|
2809
|
+
} else if (cmsIndex !== -1 && reactIndex > cmsIndex) {
|
|
2810
|
+
outcome.problems.push({
|
|
2811
|
+
check: "C7",
|
|
2812
|
+
level: "error",
|
|
2813
|
+
message: "react() comes after conlocaCMS() in the integrations array — move react() before conlocaCMS() so the react integration registers first"
|
|
2814
|
+
});
|
|
2815
|
+
}
|
|
2816
|
+
return outcome;
|
|
2817
|
+
}
|
|
2818
|
+
function checkPeers(pkg) {
|
|
2819
|
+
const outcome = outcomeOf("C8");
|
|
2820
|
+
if (pkg === "unreadable") {
|
|
2821
|
+
outcome.problems.push({
|
|
2822
|
+
check: "C8",
|
|
2823
|
+
level: "warn",
|
|
2824
|
+
message: `doctor could not parse package.json — check manually that ${CMS_PEERS.join(" and ")} are installed`
|
|
2825
|
+
});
|
|
2826
|
+
return outcome;
|
|
2827
|
+
}
|
|
2828
|
+
const deps = pkg === "missing" ? new Set : pkg.deps;
|
|
2829
|
+
for (const peer of CMS_PEERS) {
|
|
2830
|
+
if (!deps.has(peer)) {
|
|
2831
|
+
outcome.problems.push({
|
|
2832
|
+
check: "C8",
|
|
2833
|
+
level: "error",
|
|
2834
|
+
message: `${peer} is missing from package.json — add it to dependencies or devDependencies; @conloca/astro-cms requires it as a peer`
|
|
2835
|
+
});
|
|
2836
|
+
}
|
|
2837
|
+
}
|
|
2838
|
+
return outcome;
|
|
2839
|
+
}
|
|
2840
|
+
async function checkTsconfigJsx(projectDir) {
|
|
2841
|
+
const outcome = outcomeOf("C9");
|
|
2842
|
+
const path = join4(projectDir, "tsconfig.json");
|
|
2843
|
+
let raw;
|
|
11
2844
|
try {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
2845
|
+
raw = await readFile3(path, "utf-8");
|
|
2846
|
+
} catch {
|
|
2847
|
+
outcome.problems.push({
|
|
2848
|
+
check: "C9",
|
|
2849
|
+
level: "warn",
|
|
2850
|
+
message: "tsconfig.json not found — if Puck .tsx components misrender or fail typecheck, create it with compilerOptions.jsx set to react-jsx",
|
|
2851
|
+
path
|
|
2852
|
+
});
|
|
2853
|
+
return outcome;
|
|
2854
|
+
}
|
|
2855
|
+
let parsed;
|
|
2856
|
+
try {
|
|
2857
|
+
parsed = JSON.parse(stripComments(raw).replace(/,(\s*[}\]])/g, "$1"));
|
|
2858
|
+
} catch {
|
|
2859
|
+
outcome.problems.push({
|
|
2860
|
+
check: "C9",
|
|
2861
|
+
level: "warn",
|
|
2862
|
+
message: "doctor could not parse tsconfig.json — check manually that compilerOptions.jsx is react-jsx",
|
|
2863
|
+
path
|
|
2864
|
+
});
|
|
2865
|
+
return outcome;
|
|
2866
|
+
}
|
|
2867
|
+
const compilerOptions = isRecord(parsed) && isRecord(parsed.compilerOptions) ? parsed.compilerOptions : undefined;
|
|
2868
|
+
const jsx = compilerOptions?.jsx;
|
|
2869
|
+
if (jsx === "react-jsx")
|
|
2870
|
+
return outcome;
|
|
2871
|
+
outcome.problems.push({
|
|
2872
|
+
check: "C9",
|
|
2873
|
+
level: "warn",
|
|
2874
|
+
message: jsx === undefined ? "compilerOptions.jsx is not set (Astro presets use preserve) — if Puck .tsx components misrender or fail typecheck, set it to react-jsx" : `compilerOptions.jsx is ${JSON.stringify(jsx)} — if Puck .tsx components misrender or fail typecheck, set it to react-jsx`,
|
|
2875
|
+
path
|
|
2876
|
+
});
|
|
2877
|
+
return outcome;
|
|
2878
|
+
}
|
|
2879
|
+
async function checkPrerender(projectDir, configText) {
|
|
2880
|
+
const outcome = outcomeOf("C10");
|
|
2881
|
+
const keyMatch = /\boutput\s*:/.exec(configText);
|
|
2882
|
+
if (!keyMatch) {
|
|
2883
|
+
outcome.skipped = "output is not 'server'";
|
|
2884
|
+
return outcome;
|
|
2885
|
+
}
|
|
2886
|
+
const valueText = configText.slice(keyMatch.index + keyMatch[0].length).trimStart();
|
|
2887
|
+
const literal = /^(['"])([^'"]*)\1/.exec(valueText);
|
|
2888
|
+
if (!literal) {
|
|
2889
|
+
outcome.problems.push({
|
|
2890
|
+
check: "C10",
|
|
2891
|
+
level: "warn",
|
|
2892
|
+
message: "the astro config sets output but doctor could not read its value — if it is 'server', every file under src/pages must set prerender"
|
|
2893
|
+
});
|
|
2894
|
+
return outcome;
|
|
2895
|
+
}
|
|
2896
|
+
if (literal[2] !== "server") {
|
|
2897
|
+
outcome.skipped = "output is not 'server'";
|
|
2898
|
+
return outcome;
|
|
2899
|
+
}
|
|
2900
|
+
const pagesDir = join4(projectDir, "src", "pages");
|
|
2901
|
+
const names = await readdir(pagesDir, { recursive: true }).catch(() => []);
|
|
2902
|
+
for (const name of names.filter((entry) => PAGE_FILE_RE.test(entry)).sort()) {
|
|
2903
|
+
const filePath = join4(pagesDir, name);
|
|
2904
|
+
const text = await readFile3(filePath, "utf-8").catch(() => null);
|
|
2905
|
+
if (text === null) {
|
|
2906
|
+
outcome.problems.push({
|
|
2907
|
+
check: "C10",
|
|
2908
|
+
level: "warn",
|
|
2909
|
+
message: `doctor could not read src/pages/${name} — check its prerender setting manually`,
|
|
2910
|
+
path: filePath
|
|
2911
|
+
});
|
|
2912
|
+
} else if (!text.includes("prerender")) {
|
|
2913
|
+
outcome.problems.push({
|
|
2914
|
+
check: "C10",
|
|
2915
|
+
level: "error",
|
|
2916
|
+
message: `src/pages/${name} does not set prerender — with output: 'server' add "export const prerender = true" (or false on purpose) so its render mode is explicit`,
|
|
2917
|
+
path: filePath
|
|
2918
|
+
});
|
|
16
2919
|
}
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
2920
|
+
}
|
|
2921
|
+
return outcome;
|
|
2922
|
+
}
|
|
2923
|
+
function homeRouteVerdict(options) {
|
|
2924
|
+
if (options.state !== "literal")
|
|
2925
|
+
return { kind: "undeterminable" };
|
|
2926
|
+
const routingRaw = options.entries.get("routing");
|
|
2927
|
+
if (routingRaw === undefined) {
|
|
2928
|
+
if (options.entries.has("layout"))
|
|
2929
|
+
return { kind: "catch-all", pattern: "/[...slug]" };
|
|
2930
|
+
return options.hasSpread ? { kind: "undeterminable" } : { kind: "clear" };
|
|
2931
|
+
}
|
|
2932
|
+
if (routingRaw === "false")
|
|
2933
|
+
return { kind: "clear" };
|
|
2934
|
+
if (routingRaw === "true")
|
|
2935
|
+
return { kind: "catch-all", pattern: "/[...slug]" };
|
|
2936
|
+
if (!routingRaw.startsWith("{"))
|
|
2937
|
+
return { kind: "undeterminable" };
|
|
2938
|
+
const patternValues = [...routingRaw.matchAll(/\bpattern\s*:\s*(['"])([^'"]*)\1/g)].map((match) => match[2]);
|
|
2939
|
+
const catchAll = patternValues.find((pattern) => pattern === "/" || pattern.startsWith("/[..."));
|
|
2940
|
+
if (catchAll !== undefined)
|
|
2941
|
+
return { kind: "catch-all", pattern: catchAll };
|
|
2942
|
+
const patternKeyCount = (routingRaw.match(/\bpattern\s*:/g) ?? []).length;
|
|
2943
|
+
if (patternKeyCount > patternValues.length || containsOutsideStrings(routingRaw, "...")) {
|
|
2944
|
+
return { kind: "undeterminable" };
|
|
2945
|
+
}
|
|
2946
|
+
return { kind: "clear" };
|
|
2947
|
+
}
|
|
2948
|
+
function checkHomeShadow(projectDir, options) {
|
|
2949
|
+
const outcome = outcomeOf("C11");
|
|
2950
|
+
const indexPath = join4(projectDir, "src", "pages", "index.astro");
|
|
2951
|
+
if (!existsSync2(indexPath))
|
|
2952
|
+
return outcome;
|
|
2953
|
+
if (options.state === "no-call") {
|
|
2954
|
+
outcome.skipped = "conlocaCMS is not called in the astro config";
|
|
2955
|
+
return outcome;
|
|
2956
|
+
}
|
|
2957
|
+
const verdict = homeRouteVerdict(options);
|
|
2958
|
+
if (verdict.kind === "catch-all") {
|
|
2959
|
+
outcome.problems.push({
|
|
2960
|
+
check: "C11",
|
|
2961
|
+
level: "warn",
|
|
2962
|
+
message: `src/pages/index.astro shadows the CMS home page — the conlocaCMS pattern '${verdict.pattern}' also serves '/' and the static file wins; delete src/pages/index.astro or manage the home page in the CMS`,
|
|
2963
|
+
path: indexPath
|
|
2964
|
+
});
|
|
2965
|
+
} else if (verdict.kind === "undeterminable") {
|
|
2966
|
+
outcome.problems.push({
|
|
2967
|
+
check: "C11",
|
|
2968
|
+
level: "warn",
|
|
2969
|
+
message: "src/pages/index.astro exists but doctor could not determine the conlocaCMS routing pattern — if it is a catch-all like '/[...slug]', the static file shadows the CMS home page",
|
|
2970
|
+
path: indexPath
|
|
2971
|
+
});
|
|
2972
|
+
}
|
|
2973
|
+
return outcome;
|
|
2974
|
+
}
|
|
2975
|
+
async function runAstroChecks(projectDir, siteNames) {
|
|
2976
|
+
const configPath = ASTRO_CONFIG_NAMES.map((name) => join4(projectDir, name)).find((path) => existsSync2(path));
|
|
2977
|
+
if (configPath === undefined) {
|
|
2978
|
+
return Object.keys(ASTRO_CHECK_LABELS).map((id) => ({ ...outcomeOf(id), skipped: "no astro.config found" }));
|
|
2979
|
+
}
|
|
2980
|
+
const source = await readFile3(configPath, "utf-8").catch(() => null);
|
|
2981
|
+
if (source === null) {
|
|
2982
|
+
const problem = {
|
|
2983
|
+
check: "C5",
|
|
2984
|
+
level: "warn",
|
|
2985
|
+
message: `doctor could not read ${configPath} — check its file permissions`,
|
|
2986
|
+
path: configPath
|
|
21
2987
|
};
|
|
2988
|
+
return Object.keys(ASTRO_CHECK_LABELS).map((id) => id === "C5" ? { ...outcomeOf(id), problems: [problem] } : { ...outcomeOf(id), skipped: "astro config could not be read" });
|
|
2989
|
+
}
|
|
2990
|
+
const configText = stripComments(source);
|
|
2991
|
+
const options = extractCmsOptions(configText);
|
|
2992
|
+
const pkg = await readProjectDependencies(projectDir);
|
|
2993
|
+
return [
|
|
2994
|
+
await checkContentConfig(projectDir),
|
|
2995
|
+
checkSiteName(options, siteNames),
|
|
2996
|
+
checkImportSource(configText),
|
|
2997
|
+
checkCmsOptions(options),
|
|
2998
|
+
checkReactIntegration(projectDir, configText, pkg),
|
|
2999
|
+
checkPeers(pkg),
|
|
3000
|
+
await checkTsconfigJsx(projectDir),
|
|
3001
|
+
await checkPrerender(projectDir, configText),
|
|
3002
|
+
checkHomeShadow(projectDir, options)
|
|
3003
|
+
];
|
|
3004
|
+
}
|
|
3005
|
+
|
|
3006
|
+
// src/commands/doctor-extensions.ts
|
|
3007
|
+
import { existsSync as existsSync3 } from "node:fs";
|
|
3008
|
+
import { readFile as readFile4 } from "node:fs/promises";
|
|
3009
|
+
import { createRequire } from "node:module";
|
|
3010
|
+
import { dirname, join as join5, resolve as resolve2 } from "node:path";
|
|
3011
|
+
import { pathToFileURL } from "node:url";
|
|
3012
|
+
var DOCTOR_CONTRACT_VERSION = 1;
|
|
3013
|
+
var SEAM_CHECK_ID = "EXT";
|
|
3014
|
+
function seamWarning(name, message) {
|
|
3015
|
+
return {
|
|
3016
|
+
id: SEAM_CHECK_ID,
|
|
3017
|
+
label: `doctor extension ${name}`,
|
|
3018
|
+
problems: [{ check: SEAM_CHECK_ID, level: "warn", message }]
|
|
3019
|
+
};
|
|
3020
|
+
}
|
|
3021
|
+
function unexpectedShape(name) {
|
|
3022
|
+
return seamWarning(name, `${name}'s doctor extension returned an unexpected shape — update the package`);
|
|
3023
|
+
}
|
|
3024
|
+
function resolveManifestPath(require2, projectDir, name) {
|
|
3025
|
+
try {
|
|
3026
|
+
return require2.resolve(`${name}/package.json`);
|
|
3027
|
+
} catch {
|
|
3028
|
+
let dir = projectDir;
|
|
3029
|
+
for (;; ) {
|
|
3030
|
+
const candidate = join5(dir, "node_modules", name, "package.json");
|
|
3031
|
+
if (existsSync3(candidate))
|
|
3032
|
+
return candidate;
|
|
3033
|
+
const parent = dirname(dir);
|
|
3034
|
+
if (parent === dir)
|
|
3035
|
+
return null;
|
|
3036
|
+
dir = parent;
|
|
3037
|
+
}
|
|
3038
|
+
}
|
|
3039
|
+
}
|
|
3040
|
+
async function discoverExtensions(projectDir) {
|
|
3041
|
+
const pkg = await readProjectDependencies(projectDir);
|
|
3042
|
+
if (pkg === "missing" || pkg === "unreadable")
|
|
3043
|
+
return [];
|
|
3044
|
+
const require2 = createRequire(join5(projectDir, "package.json"));
|
|
3045
|
+
const manifests = [];
|
|
3046
|
+
for (const name of [...pkg.deps].sort()) {
|
|
3047
|
+
const manifestPath = resolveManifestPath(require2, projectDir, name);
|
|
3048
|
+
if (manifestPath === null)
|
|
3049
|
+
continue;
|
|
3050
|
+
let manifest;
|
|
22
3051
|
try {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
sitesConfig = parsed;
|
|
27
|
-
} else {
|
|
28
|
-
sitesConfig.sites = parsed;
|
|
29
|
-
}
|
|
30
|
-
console.log(" Found existing sites.json");
|
|
31
|
-
} catch (error) {}
|
|
32
|
-
if (!sitesConfig.sites[siteName]) {
|
|
33
|
-
sitesConfig.sites[siteName] = {
|
|
34
|
-
locales: ["en", "nl", "de", "fr"],
|
|
35
|
-
defaultLocale: "en"
|
|
36
|
-
};
|
|
37
|
-
await writeFile(sitesJsonPath, JSON.stringify(sitesConfig, null, 2) + `
|
|
38
|
-
`, "utf-8");
|
|
39
|
-
console.log(` Updated: ${sitesJsonPath} (added site: ${siteName})`);
|
|
40
|
-
} else {
|
|
41
|
-
console.log(` Site '${siteName}' already exists in sites.json`);
|
|
3052
|
+
manifest = JSON.parse(await readFile4(manifestPath, "utf-8"));
|
|
3053
|
+
} catch {
|
|
3054
|
+
continue;
|
|
42
3055
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
3056
|
+
const entry = isRecord(manifest) && isRecord(manifest.conloca) ? manifest.conloca.doctor : undefined;
|
|
3057
|
+
if (typeof entry !== "string" || entry === "")
|
|
3058
|
+
continue;
|
|
3059
|
+
manifests.push({ name, dir: dirname(manifestPath), entry });
|
|
3060
|
+
}
|
|
3061
|
+
return manifests;
|
|
3062
|
+
}
|
|
3063
|
+
function isProblem(value) {
|
|
3064
|
+
return isRecord(value) && typeof value.check === "string" && (value.level === "error" || value.level === "warn") && typeof value.message === "string" && (value.path === undefined || typeof value.path === "string");
|
|
3065
|
+
}
|
|
3066
|
+
function isCheckOutcome(value) {
|
|
3067
|
+
return isRecord(value) && typeof value.id === "string" && typeof value.label === "string" && Array.isArray(value.problems) && value.problems.every(isProblem) && (value.detail === undefined || typeof value.detail === "string") && (value.skipped === undefined || typeof value.skipped === "string");
|
|
3068
|
+
}
|
|
3069
|
+
async function runExtension(manifest, context) {
|
|
3070
|
+
let loaded;
|
|
3071
|
+
try {
|
|
3072
|
+
loaded = await import(pathToFileURL(resolve2(manifest.dir, manifest.entry)).href);
|
|
50
3073
|
} catch (error) {
|
|
51
|
-
|
|
52
|
-
|
|
3074
|
+
return [
|
|
3075
|
+
seamWarning(manifest.name, `${manifest.name} declares a doctor extension at ${manifest.entry} that could not be loaded — reinstall or update the package (${messageOf(error)})`)
|
|
3076
|
+
];
|
|
3077
|
+
}
|
|
3078
|
+
const run = isRecord(loaded) ? loaded.default : undefined;
|
|
3079
|
+
if (typeof run !== "function") {
|
|
3080
|
+
return [
|
|
3081
|
+
seamWarning(manifest.name, `${manifest.name}'s doctor extension has no default export function — update the package`)
|
|
3082
|
+
];
|
|
3083
|
+
}
|
|
3084
|
+
let result;
|
|
3085
|
+
try {
|
|
3086
|
+
result = await run(context);
|
|
3087
|
+
} catch (error) {
|
|
3088
|
+
return [seamWarning(manifest.name, `${manifest.name}'s doctor extension failed: ${messageOf(error)}`)];
|
|
3089
|
+
}
|
|
3090
|
+
if (!isRecord(result))
|
|
3091
|
+
return [unexpectedShape(manifest.name)];
|
|
3092
|
+
if (result.contractVersion !== DOCTOR_CONTRACT_VERSION) {
|
|
3093
|
+
return [
|
|
3094
|
+
seamWarning(manifest.name, `extension ${manifest.name} speaks doctor contract ${JSON.stringify(result.contractVersion)}, this CLI speaks ${DOCTOR_CONTRACT_VERSION} — update the older side`)
|
|
3095
|
+
];
|
|
3096
|
+
}
|
|
3097
|
+
if (!Array.isArray(result.checks))
|
|
3098
|
+
return [unexpectedShape(manifest.name)];
|
|
3099
|
+
const checks = result.checks.filter(isCheckOutcome);
|
|
3100
|
+
const dropped = result.checks.length - checks.length;
|
|
3101
|
+
return dropped === 0 ? checks : [
|
|
3102
|
+
...checks,
|
|
3103
|
+
seamWarning(manifest.name, `${dropped} result(s) from ${manifest.name}'s doctor extension were malformed and ignored — update the package`)
|
|
3104
|
+
];
|
|
3105
|
+
}
|
|
3106
|
+
async function runExtensionChecks(projectDir, contentRoot, live) {
|
|
3107
|
+
const context = { contractVersion: DOCTOR_CONTRACT_VERSION, projectDir, contentRoot, live };
|
|
3108
|
+
const outcomes = [];
|
|
3109
|
+
for (const manifest of await discoverExtensions(projectDir)) {
|
|
3110
|
+
outcomes.push(...await runExtension(manifest, context));
|
|
3111
|
+
}
|
|
3112
|
+
return outcomes;
|
|
3113
|
+
}
|
|
3114
|
+
|
|
3115
|
+
// src/commands/doctor.ts
|
|
3116
|
+
var RESERVED_CONTENT_DIRS = new Set(["fragments", "data"]);
|
|
3117
|
+
var CONTENT_GLOB = "{**/*.{vxjson,mdx},data/**/*.json}";
|
|
3118
|
+
function isLocaleList(value) {
|
|
3119
|
+
return Array.isArray(value) && value.length > 0 && value.every((locale) => typeof locale === "string" && locale.trim() !== "");
|
|
3120
|
+
}
|
|
3121
|
+
function counted(count, noun) {
|
|
3122
|
+
return count === 1 ? `1 ${noun}` : `${count} ${noun}s`;
|
|
3123
|
+
}
|
|
3124
|
+
async function checkSitesFile(contentRoot) {
|
|
3125
|
+
const path = join6(contentRoot, "sites.json");
|
|
3126
|
+
const problems = [];
|
|
3127
|
+
const outcome = { id: "C3", label: "sites.json is present and complete", problems };
|
|
3128
|
+
let raw;
|
|
3129
|
+
try {
|
|
3130
|
+
raw = await readFile5(path, "utf-8");
|
|
3131
|
+
} catch {
|
|
3132
|
+
problems.push({
|
|
3133
|
+
check: "C3",
|
|
3134
|
+
level: "error",
|
|
3135
|
+
message: `sites.json not found — expected it at ${path} (conloca init creates it)`,
|
|
3136
|
+
path
|
|
3137
|
+
});
|
|
3138
|
+
return { outcome, config: null };
|
|
3139
|
+
}
|
|
3140
|
+
let parsed;
|
|
3141
|
+
try {
|
|
3142
|
+
parsed = JSON.parse(raw);
|
|
3143
|
+
} catch (error) {
|
|
3144
|
+
problems.push({ check: "C3", level: "error", message: `sites.json is not valid JSON: ${messageOf(error)}`, path });
|
|
3145
|
+
return { outcome, config: null };
|
|
3146
|
+
}
|
|
3147
|
+
if (!isRecord(parsed) || !isRecord(parsed.sites)) {
|
|
3148
|
+
problems.push({ check: "C3", level: "error", message: 'sites.json has no "sites" object', path });
|
|
3149
|
+
return { outcome, config: null };
|
|
3150
|
+
}
|
|
3151
|
+
for (const [siteName, site] of Object.entries(parsed.sites)) {
|
|
3152
|
+
if (!isRecord(site)) {
|
|
3153
|
+
problems.push({ check: "C3", level: "error", message: `site "${siteName}" entry is not an object`, path });
|
|
3154
|
+
continue;
|
|
3155
|
+
}
|
|
3156
|
+
if (typeof site.defaultLocale !== "string" || site.defaultLocale === "") {
|
|
3157
|
+
problems.push({ check: "C3", level: "error", message: `site "${siteName}" is missing "defaultLocale"`, path });
|
|
3158
|
+
}
|
|
3159
|
+
if (!isLocaleList(site.locales)) {
|
|
3160
|
+
problems.push({
|
|
3161
|
+
check: "C3",
|
|
3162
|
+
level: "error",
|
|
3163
|
+
message: `site "${siteName}" must declare a non-empty "locales" array of non-empty strings`,
|
|
3164
|
+
path
|
|
3165
|
+
});
|
|
3166
|
+
} else if (typeof site.defaultLocale === "string" && !site.locales.includes(site.defaultLocale)) {
|
|
3167
|
+
problems.push({
|
|
3168
|
+
check: "C3",
|
|
3169
|
+
level: "error",
|
|
3170
|
+
message: `site "${siteName}" defaultLocale must appear in its locales array`,
|
|
3171
|
+
path
|
|
3172
|
+
});
|
|
3173
|
+
}
|
|
3174
|
+
}
|
|
3175
|
+
if (!Array.isArray(parsed.globalLocales) || parsed.globalLocales.length === 0) {
|
|
3176
|
+
problems.push({
|
|
3177
|
+
check: "C3",
|
|
3178
|
+
level: "warn",
|
|
3179
|
+
message: 'sites.json is missing a non-empty "globalLocales" array; the CMS falls back to ["en"]',
|
|
3180
|
+
path
|
|
3181
|
+
});
|
|
3182
|
+
}
|
|
3183
|
+
if (Array.isArray(parsed.globalLocales) && parsed.globalLocales.length > 0 && !isLocaleList(parsed.globalLocales)) {
|
|
3184
|
+
problems.push({ check: "C3", level: "error", message: "globalLocales must contain only non-empty strings", path });
|
|
3185
|
+
}
|
|
3186
|
+
if (problems.some((problem) => problem.level === "error")) {
|
|
3187
|
+
return { outcome, config: null };
|
|
3188
|
+
}
|
|
3189
|
+
const globalLocales = Array.isArray(parsed.globalLocales) && parsed.globalLocales.length > 0 ? parsed.globalLocales : ["en"];
|
|
3190
|
+
return { outcome, config: { sites: parsed.sites, globalLocales } };
|
|
3191
|
+
}
|
|
3192
|
+
async function checkSiteDirs(contentRoot, config) {
|
|
3193
|
+
const problems = [];
|
|
3194
|
+
const outcome = { id: "C4", label: "site directories match sites.json", problems };
|
|
3195
|
+
if (!config) {
|
|
3196
|
+
outcome.skipped = "sites.json is unusable";
|
|
3197
|
+
return outcome;
|
|
3198
|
+
}
|
|
3199
|
+
for (const site of Object.keys(config.sites)) {
|
|
3200
|
+
const pagesPath = join6(contentRoot, site, "pages");
|
|
3201
|
+
const stats = await stat(pagesPath).catch(() => null);
|
|
3202
|
+
if (!stats?.isDirectory()) {
|
|
3203
|
+
problems.push({
|
|
3204
|
+
check: "C4",
|
|
3205
|
+
level: "error",
|
|
3206
|
+
message: `site "${site}" has no pages directory — expected ${pagesPath}`,
|
|
3207
|
+
path: pagesPath
|
|
3208
|
+
});
|
|
3209
|
+
}
|
|
3210
|
+
}
|
|
3211
|
+
const entries = await readdir2(contentRoot, { withFileTypes: true }).catch(() => []);
|
|
3212
|
+
for (const entry of entries) {
|
|
3213
|
+
if (!entry.isDirectory() || RESERVED_CONTENT_DIRS.has(entry.name) || Object.hasOwn(config.sites, entry.name))
|
|
3214
|
+
continue;
|
|
3215
|
+
problems.push({
|
|
3216
|
+
check: "C4",
|
|
3217
|
+
level: "warn",
|
|
3218
|
+
message: `directory "${entry.name}" has no sites.json entry — any pages inside are invisible to the CMS`,
|
|
3219
|
+
path: join6(contentRoot, entry.name)
|
|
3220
|
+
});
|
|
3221
|
+
}
|
|
3222
|
+
return outcome;
|
|
3223
|
+
}
|
|
3224
|
+
async function checkContentIndex(contentRoot, config) {
|
|
3225
|
+
const problems = [];
|
|
3226
|
+
const outcome = { id: "C12", label: "content files index cleanly", problems };
|
|
3227
|
+
const sitesConfig = config ?? { sites: {}, globalLocales: ["en"] };
|
|
3228
|
+
try {
|
|
3229
|
+
const index = ContentIndex.createUncached(sitesConfig);
|
|
3230
|
+
const backend = new FileSystemReaderBackend({ contentRoot });
|
|
3231
|
+
const { indexed } = await index.indexAll(backend, {
|
|
3232
|
+
glob: CONTENT_GLOB,
|
|
3233
|
+
onError: (path, reason, message) => {
|
|
3234
|
+
problems.push({
|
|
3235
|
+
check: "C12",
|
|
3236
|
+
level: "error",
|
|
3237
|
+
message: `${message} (${reason})`,
|
|
3238
|
+
path: join6(contentRoot, path)
|
|
3239
|
+
});
|
|
3240
|
+
}
|
|
3241
|
+
});
|
|
3242
|
+
outcome.detail = counted(indexed, "file");
|
|
3243
|
+
} catch (error) {
|
|
3244
|
+
problems.push({ check: "C12", level: "error", message: `content scan failed: ${messageOf(error)}` });
|
|
3245
|
+
}
|
|
3246
|
+
return outcome;
|
|
3247
|
+
}
|
|
3248
|
+
async function runDoctor(projectDir, contentRoot, options) {
|
|
3249
|
+
const sitesFile = await checkSitesFile(contentRoot);
|
|
3250
|
+
const checks = [sitesFile.outcome];
|
|
3251
|
+
checks.push(await checkSiteDirs(contentRoot, sitesFile.config));
|
|
3252
|
+
checks.push(await checkContentIndex(contentRoot, sitesFile.config));
|
|
3253
|
+
checks.push(...await runAstroChecks(projectDir, sitesFile.config ? Object.keys(sitesFile.config.sites) : null));
|
|
3254
|
+
checks.push(...await runExtensionChecks(projectDir, contentRoot, options.live));
|
|
3255
|
+
const problems = checks.flatMap((check) => check.problems);
|
|
3256
|
+
return { ok: !problems.some((problem) => problem.level === "error"), checks, problems };
|
|
3257
|
+
}
|
|
3258
|
+
function printReport(contentRoot, report) {
|
|
3259
|
+
console.log(`Checking ${contentRoot}`);
|
|
3260
|
+
for (const check of report.checks) {
|
|
3261
|
+
if (check.skipped) {
|
|
3262
|
+
console.log(`- ${check.id} ${check.label} (skipped: ${check.skipped})`);
|
|
3263
|
+
continue;
|
|
3264
|
+
}
|
|
3265
|
+
const hasErrors = check.problems.some((problem) => problem.level === "error");
|
|
3266
|
+
const mark = hasErrors ? "✗" : check.problems.length > 0 ? "!" : "✓";
|
|
3267
|
+
console.log(`${mark} ${check.id} ${check.label}${check.detail ? ` (${check.detail})` : ""}`);
|
|
3268
|
+
for (const problem of check.problems) {
|
|
3269
|
+
console.log(` ${problem.level}: ${problem.message}`);
|
|
3270
|
+
}
|
|
3271
|
+
}
|
|
3272
|
+
const errorCount = report.problems.filter((problem) => problem.level === "error").length;
|
|
3273
|
+
const warnCount = report.problems.length - errorCount;
|
|
3274
|
+
console.log("");
|
|
3275
|
+
if (report.problems.length === 0) {
|
|
3276
|
+
console.log("✓ No problems found");
|
|
3277
|
+
} else {
|
|
3278
|
+
console.log(`Found ${counted(errorCount, "error")}, ${counted(warnCount, "warning")}`);
|
|
3279
|
+
}
|
|
3280
|
+
}
|
|
3281
|
+
async function doctor(directory, options) {
|
|
3282
|
+
const projectDir = resolve3(directory);
|
|
3283
|
+
const contentRoot = contentRootOf(directory);
|
|
3284
|
+
const report = await runDoctor(projectDir, contentRoot, { live: options.live });
|
|
3285
|
+
if (options.json) {
|
|
3286
|
+
console.log(JSON.stringify({ ok: report.ok, problems: report.problems }));
|
|
3287
|
+
} else {
|
|
3288
|
+
printReport(contentRoot, report);
|
|
3289
|
+
}
|
|
3290
|
+
if (!report.ok) {
|
|
53
3291
|
process.exit(1);
|
|
54
3292
|
}
|
|
55
3293
|
}
|
|
56
3294
|
|
|
57
3295
|
// src/commands/setup.ts
|
|
58
|
-
import { mkdir
|
|
59
|
-
import { join as
|
|
60
|
-
|
|
3296
|
+
import { mkdir, readFile as readFile7, writeFile as writeFile2 } from "node:fs/promises";
|
|
3297
|
+
import { join as join8, resolve as resolve4 } from "node:path";
|
|
3298
|
+
|
|
3299
|
+
// src/lib/sites-config.ts
|
|
3300
|
+
import { readFile as readFile6, writeFile } from "node:fs/promises";
|
|
3301
|
+
import { join as join7 } from "node:path";
|
|
3302
|
+
var DEFAULT_LOCALES = ["en", "nl", "de", "fr"];
|
|
3303
|
+
async function ensureSiteInSitesConfig(contentPath, siteName) {
|
|
3304
|
+
const path = join7(contentPath, "sites.json");
|
|
3305
|
+
let sitesConfig = { sites: {}, globalLocales: [...DEFAULT_LOCALES] };
|
|
3306
|
+
let existed = false;
|
|
3307
|
+
try {
|
|
3308
|
+
const parsed = JSON.parse(await readFile6(path, "utf-8"));
|
|
3309
|
+
if (parsed.sites) {
|
|
3310
|
+
sitesConfig = parsed;
|
|
3311
|
+
} else {
|
|
3312
|
+
sitesConfig.sites = parsed;
|
|
3313
|
+
}
|
|
3314
|
+
existed = true;
|
|
3315
|
+
} catch {}
|
|
3316
|
+
if (Object.hasOwn(sitesConfig.sites, siteName)) {
|
|
3317
|
+
return { path, existed, added: false };
|
|
3318
|
+
}
|
|
3319
|
+
sitesConfig.sites[siteName] = { locales: [...DEFAULT_LOCALES], defaultLocale: "en" };
|
|
3320
|
+
await writeFile(path, `${JSON.stringify(sitesConfig, null, 2)}
|
|
3321
|
+
`, "utf-8");
|
|
3322
|
+
return { path, existed, added: true };
|
|
3323
|
+
}
|
|
3324
|
+
|
|
3325
|
+
// src/templates/conloca-skill.md
|
|
3326
|
+
var conloca_skill_default = "---\nname: conloca\ndescription: Load when working on an Astro site using Conloca CMS — @conloca/* packages, .vxjson content, sites.json.\n---\n\n# Conloca CMS\n\nConloca stores pages as `.vxjson` files (visual pages built from Puck components) and `.mdx` files under `content/`, and\nrenders them through the `@conloca/astro-cms` Astro integration. The visual editor lives at `/__cms` on the dev server\nonly.\n\n## First move: `conloca doctor`\n\nFor any Conloca problem — blank page, 404 on a content page, editor not loading, build failure — run this before reading\nsource:\n\n```bash\nconloca doctor # human-readable report\nconloca doctor --json # single {ok, problems} object on stdout\n```\n\nThe `conloca` command ships in `@conloca/cli` — run it as `npx @conloca/cli doctor` (or `bunx`) when it is not\ninstalled.\n\nIt checks the content directory (sites.json complete, site directories present, every content file indexes cleanly) and,\nwhen an astro.config is present, the Astro wiring: content config, conlocaCMS import and options, react() order, peer\ndependencies, tsconfig jsx, prerender under server output, and home-page shadowing. Each problem names the broken file\nand the fix. It is read-only and exits 1 on errors; warnings alone exit 0.\n\nNew project from an empty directory? `conloca create <dir>` writes and installs the whole wired site;\n`conloca astro setup` is for adding Conloca to an existing Astro site.\n\n## The files a working site needs\n\n- `astro.config.mjs` — registers `react()` and `conlocaCMS(...)`\n- `src/content.config.ts` — declares the content collections (without it every content page 404s)\n- `content/sites.json` — sites with their `locales` and `defaultLocale`, plus `globalLocales`\n- `src/puck.config.tsx` — registers the Puck components pages are built from\n- `src/layouts/Layout.astro` — the page layout content pages render into\n- `src/components/puck/*` and `src/schemas/data.ts` — starter components and data-collection schemas\n\nRun `conloca astro setup` inside an existing Astro project. It scaffolds the content config, components, schemas, page\nlayout, and content directories, preserving existing generated files. It adds the default site to `sites.json` when\nmissing. It prints the `astro.config` wiring rather than writing that file: merge the printed options into the existing\nconfig, then run `conloca doctor` to verify the result. `conloca init . <site-name>` adds another site to sites.json.\n\n## Install: the exact package set\n\n```bash\nnpm install @conloca/astro-cms @conloca/content-api @conloca/mdx @puckeditor/core @astrojs/react @vitejs/plugin-react zod\n```\n\n`@puckeditor/core` is what the generated components import — there is no other Puck package to install.\n\n## Canonical astro.config.mjs\n\nThe minimal working config, matching what `conloca astro setup` prints:\n\n```js\nimport react from '@astrojs/react';\nimport { conlocaCMS } from '@conloca/astro-cms/node';\nimport { defineConfig } from 'astro/config';\n\nexport default defineConfig({\n integrations: [\n react(),\n conlocaCMS({\n contentRoot: './content',\n puckConfigPath: './src/puck.config.tsx',\n schemasPath: './src/schemas/data.ts',\n layout: './src/layouts/Layout.astro',\n }),\n ],\n});\n```\n\n`react()` must come before `conlocaCMS()` — doctor checks the order. And `src/content.config.ts`:\n\n```ts\nimport { conlocaData, conlocaFragments, conlocaPages } from '@conloca/astro-cms/node/content';\nimport { dataSchemas } from './schemas/data';\n\nexport const collections = {\n pages: conlocaPages(),\n ...conlocaData({ dataSchemas }),\n ...conlocaFragments(),\n};\n```\n\nEvery collection is declared here by name — content the config does not name fails the build instead of silently not\nbuilding.\n\n## Where errors appear\n\n- `astro dev` runs in the foreground: config and integration errors print to the terminal running it, and page errors\n also show in the browser error overlay. There is no separate log command — read that terminal.\n- A page referencing a Puck component type missing from puck.config.tsx serves HTTP 200 with a blank region and a clean\n browser console. The only signal is `[Conloca] Page references N component type(s) missing from your Puck config: ...`\n in the dev-server or build terminal.\n- The editor at `/__cms` exists only on the dev server. A production build without it is not a bug.\n\n## Creating a page\n\n```bash\nconloca page create --site default --collection pages --pathname /about --title 'About us'\n```\n\nWrites the `.vxjson` file with the same empty Puck payload the CMS writes for a new page, in the site's default locale;\nthe page is immediately editable at `/__cms`. `--json` prints `{ok, id, path}`. Do not hand-craft `.vxjson` files and do\nnot reach for HTTP endpoints — this command is the supported path.\n\n## Routing\n\n- `layout: './src/layouts/Layout.astro'` alone injects a catch-all `/[...slug]` route over the `pages` collection, with\n `prerender: true` and `fallback: '404'`.\n- Passing `routing` replaces that default route entirely and the top-level `layout` is then ignored — name it per route\n instead: `routing: { routes: { pages: { pattern: '/[...slug]', layout: './src/layouts/Layout.astro' } } }`.\n- `routing: true` is the same default catch-all with no layout.\n- `fallback: '404'` returns a bare 404 when no content matches the pattern; `'passthrough'` hands the miss back to Astro\n so the site's own `/404` page renders, with a real 404 status.\n- Trap: a static `src/pages/index.astro` shadows the CMS home page — the file wins over the catch-all and Astro says\n nothing. Doctor flags it; delete the file or manage the home page in the CMS.\n\n## Adding Conloca to an existing Astro site\n\n- Switching to `output: 'server'`: first add `export const prerender = true` to every existing file under `src/pages/`,\n then flip the output — otherwise those pages silently stop being static. Doctor errors on files that miss it.\n- Existing `.mdx` content: set the site's `mdxPages` path in `content/sites.json` (relative to the project root, e.g.\n `./src/content/docs`). `.mdx` files under it surface in the CMS as pages of that site; the default locale lives at\n `<mdxPages>/<slug>.mdx`, other locales at `<mdxPages>/<locale>/<slug>.mdx`.\n- Plain `.md` files are never adopted — only `.mdx` and `.vxjson` are recognized as pages. Rename `.md` to `.mdx` to\n bring a file under management.\n\n## Custom Puck components\n\nFollow the generated examples in `src/components/puck/` — that is the one proven path:\n\n1. Write a render component plus a `ComponentConfig` wrapped in `withLayout` from `src/components/ComponentLayout.tsx`,\n mirroring the generated `HeadingComponent.tsx` / `Heading.tsx` pair.\n2. Register the component and its Props type in `src/puck.config.tsx`: add it to the `Components` type and the\n `components` map (and optionally a `categories` entry).\n3. Types come from `@puckeditor/core`. If `.tsx` components misrender or fail typecheck, set tsconfig\n `\"jsx\": \"react-jsx\"` — doctor's advisory warning covers this.\n\nA component referenced by stored content but not registered renders blank — see \"Where errors appear\".\n\n## Known limits — by design, do not fight them\n\n- MDX fragments render prose only.\n `Unknown component <X>: fragments render as plain content and cannot use React components.` is intentional: fragment\n content is treated as untrusted, so `{...}` expressions and `import`/`export` statements are rejected too. Do not try\n to sneak components in.\n- Unknown Puck component types render as nothing; the dev-server or build console names them. The fix is registering the\n type in `puck.config.tsx`, not editing the stored content.\n";
|
|
3327
|
+
|
|
3328
|
+
// src/commands/setup.ts
|
|
3329
|
+
var DEFAULT_SITE_NAME = "default";
|
|
3330
|
+
var COMPONENT_LAYOUT_TEMPLATE = `import type { ComponentConfig, DefaultComponentProps, ObjectField } from '@puckeditor/core';
|
|
61
3331
|
import type { CSSProperties } from 'react';
|
|
62
3332
|
import { forwardRef, type ReactNode } from 'react';
|
|
63
3333
|
|
|
@@ -72,7 +3342,7 @@ export type WithLayout<Props extends DefaultComponentProps> = Props & {
|
|
|
72
3342
|
layout?: LayoutFieldProps;
|
|
73
3343
|
};
|
|
74
3344
|
|
|
75
|
-
type
|
|
3345
|
+
type ComponentLayoutProps = WithLayout<{
|
|
76
3346
|
children: ReactNode;
|
|
77
3347
|
className?: string;
|
|
78
3348
|
style?: CSSProperties;
|
|
@@ -127,28 +3397,30 @@ export const layoutField: ObjectField<LayoutFieldProps> = {
|
|
|
127
3397
|
},
|
|
128
3398
|
};
|
|
129
3399
|
|
|
130
|
-
const
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
3400
|
+
const ComponentLayout = forwardRef<HTMLDivElement, ComponentLayoutProps>(
|
|
3401
|
+
({ children, className, layout, style }, ref) => {
|
|
3402
|
+
return (
|
|
3403
|
+
<div
|
|
3404
|
+
className={className}
|
|
3405
|
+
ref={ref}
|
|
3406
|
+
style={{
|
|
3407
|
+
gridColumn: layout?.spanCol ? \`span \${Math.max(Math.min(layout.spanCol, 12), 1)}\` : undefined,
|
|
3408
|
+
gridRow: layout?.spanRow ? \`span \${Math.max(Math.min(layout.spanRow, 12), 1)}\` : undefined,
|
|
3409
|
+
paddingTop: layout?.padding,
|
|
3410
|
+
paddingBottom: layout?.padding,
|
|
3411
|
+
flex: layout?.grow ? '1 1 0' : undefined,
|
|
3412
|
+
...style,
|
|
3413
|
+
}}
|
|
3414
|
+
>
|
|
3415
|
+
{children}
|
|
3416
|
+
</div>
|
|
3417
|
+
);
|
|
3418
|
+
},
|
|
3419
|
+
);
|
|
148
3420
|
|
|
149
|
-
|
|
3421
|
+
ComponentLayout.displayName = 'ComponentLayout';
|
|
150
3422
|
|
|
151
|
-
export {
|
|
3423
|
+
export { ComponentLayout };
|
|
152
3424
|
|
|
153
3425
|
export function withLayout<ThisComponentConfig extends ComponentConfig<any> = ComponentConfig<any>>(
|
|
154
3426
|
componentConfig: ThisComponentConfig,
|
|
@@ -208,9 +3480,9 @@ export function withLayout<ThisComponentConfig extends ComponentConfig<any> = Co
|
|
|
208
3480
|
},
|
|
209
3481
|
inline: true,
|
|
210
3482
|
render: (props) => (
|
|
211
|
-
<
|
|
3483
|
+
<ComponentLayout className="puck-layout" layout={props.layout as LayoutFieldProps} ref={props.puck.dragRef}>
|
|
212
3484
|
{componentConfig.render(props)}
|
|
213
|
-
</
|
|
3485
|
+
</ComponentLayout>
|
|
214
3486
|
),
|
|
215
3487
|
};
|
|
216
3488
|
}
|
|
@@ -290,8 +3562,8 @@ export function HeadingComponent({ text, level = '2', size = 'm', align = 'left'
|
|
|
290
3562
|
`;
|
|
291
3563
|
var HEADING_TEMPLATE = `import type { ComponentConfig } from '@puckeditor/core';
|
|
292
3564
|
import React from 'react';
|
|
293
|
-
import type { WithLayout } from '../
|
|
294
|
-
import { withLayout } from '../
|
|
3565
|
+
import type { WithLayout } from '../ComponentLayout';
|
|
3566
|
+
import { withLayout } from '../ComponentLayout';
|
|
295
3567
|
import { Section } from '../Section';
|
|
296
3568
|
import { HeadingComponent } from './HeadingComponent';
|
|
297
3569
|
|
|
@@ -394,8 +3666,8 @@ export function TextComponent({ text, size = 'm', color = 'default', align = 'le
|
|
|
394
3666
|
`;
|
|
395
3667
|
var TEXT_TEMPLATE = `import type { ComponentConfig } from '@puckeditor/core';
|
|
396
3668
|
import React from 'react';
|
|
397
|
-
import type { WithLayout } from '../
|
|
398
|
-
import { withLayout } from '../
|
|
3669
|
+
import type { WithLayout } from '../ComponentLayout';
|
|
3670
|
+
import { withLayout } from '../ComponentLayout';
|
|
399
3671
|
import { Section } from '../Section';
|
|
400
3672
|
import { TextComponent } from './TextComponent';
|
|
401
3673
|
|
|
@@ -459,8 +3731,8 @@ export const Text = withLayout(TextInner);
|
|
|
459
3731
|
`;
|
|
460
3732
|
var FLEX_TEMPLATE = `import type { ComponentConfig, Slot } from '@puckeditor/core';
|
|
461
3733
|
import React from 'react';
|
|
462
|
-
import type { WithLayout } from '../
|
|
463
|
-
import { withLayout } from '../
|
|
3734
|
+
import type { WithLayout } from '../ComponentLayout';
|
|
3735
|
+
import { withLayout } from '../ComponentLayout';
|
|
464
3736
|
import { Section } from '../Section';
|
|
465
3737
|
|
|
466
3738
|
export type FlexProps = WithLayout<{
|
|
@@ -546,7 +3818,7 @@ export const Flex = withLayout(FlexInternal);
|
|
|
546
3818
|
`;
|
|
547
3819
|
var GRID_TEMPLATE = `import type { ComponentConfig, Slot } from '@puckeditor/core';
|
|
548
3820
|
import React from 'react';
|
|
549
|
-
import { withLayout } from '../
|
|
3821
|
+
import { withLayout } from '../ComponentLayout';
|
|
550
3822
|
import { Section } from '../Section';
|
|
551
3823
|
|
|
552
3824
|
export type GridProps = {
|
|
@@ -595,6 +3867,28 @@ export const GridInternal: ComponentConfig<GridProps> = {
|
|
|
595
3867
|
|
|
596
3868
|
export const Grid = withLayout(GridInternal);
|
|
597
3869
|
`;
|
|
3870
|
+
var PAGE_LAYOUT_TEMPLATE = `---
|
|
3871
|
+
interface Props {
|
|
3872
|
+
title?: string;
|
|
3873
|
+
description?: string;
|
|
3874
|
+
}
|
|
3875
|
+
|
|
3876
|
+
const { title, description } = Astro.props;
|
|
3877
|
+
---
|
|
3878
|
+
|
|
3879
|
+
<!doctype html>
|
|
3880
|
+
<html lang="en">
|
|
3881
|
+
<head>
|
|
3882
|
+
<meta charset="utf-8" />
|
|
3883
|
+
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
|
3884
|
+
<title>{title ?? 'My site'}</title>
|
|
3885
|
+
{description && <meta name="description" content={description} />}
|
|
3886
|
+
</head>
|
|
3887
|
+
<body>
|
|
3888
|
+
<slot />
|
|
3889
|
+
</body>
|
|
3890
|
+
</html>
|
|
3891
|
+
`;
|
|
598
3892
|
var PUCK_CONFIG_TEMPLATE = `import type { Config } from '@puckeditor/core';
|
|
599
3893
|
import type { FlexProps } from './components/puck/Flex';
|
|
600
3894
|
import { Flex } from './components/puck/Flex';
|
|
@@ -667,37 +3961,54 @@ export const dataSchemas = {
|
|
|
667
3961
|
}),
|
|
668
3962
|
};
|
|
669
3963
|
`;
|
|
670
|
-
async function setup(projectPath = ".") {
|
|
3964
|
+
async function setup(projectPath = ".", siteName = DEFAULT_SITE_NAME) {
|
|
671
3965
|
try {
|
|
672
|
-
const absolutePath =
|
|
673
|
-
const srcDir =
|
|
3966
|
+
const absolutePath = resolve4(projectPath);
|
|
3967
|
+
const srcDir = join8(absolutePath, "src");
|
|
674
3968
|
console.log(`Setting up Conloca for Astro...
|
|
675
3969
|
`);
|
|
676
|
-
const
|
|
3970
|
+
const contentDir = join8(absolutePath, "content");
|
|
3971
|
+
const dirs = [
|
|
3972
|
+
contentDir,
|
|
3973
|
+
join8(contentDir, siteName, "pages"),
|
|
3974
|
+
join8(srcDir, "components"),
|
|
3975
|
+
join8(srcDir, "components", "puck"),
|
|
3976
|
+
join8(srcDir, "layouts"),
|
|
3977
|
+
join8(srcDir, "schemas"),
|
|
3978
|
+
join8(absolutePath, ".claude", "skills", "conloca")
|
|
3979
|
+
];
|
|
677
3980
|
for (const dir of dirs) {
|
|
678
|
-
await
|
|
3981
|
+
await mkdir(dir, { recursive: true });
|
|
679
3982
|
}
|
|
680
3983
|
const created = [];
|
|
681
3984
|
const skipped = [];
|
|
682
3985
|
async function writeIfNotExists(filePath, content, description) {
|
|
683
3986
|
try {
|
|
684
|
-
await
|
|
3987
|
+
await readFile7(filePath);
|
|
685
3988
|
skipped.push(description);
|
|
686
3989
|
} catch {
|
|
687
3990
|
await writeFile2(filePath, content, "utf-8");
|
|
688
3991
|
created.push(description);
|
|
689
3992
|
}
|
|
690
3993
|
}
|
|
691
|
-
await writeIfNotExists(
|
|
692
|
-
await writeIfNotExists(
|
|
693
|
-
await writeIfNotExists(
|
|
694
|
-
await writeIfNotExists(
|
|
695
|
-
await writeIfNotExists(
|
|
696
|
-
await writeIfNotExists(
|
|
697
|
-
await writeIfNotExists(
|
|
698
|
-
await writeIfNotExists(
|
|
699
|
-
await writeIfNotExists(
|
|
700
|
-
await writeIfNotExists(
|
|
3994
|
+
await writeIfNotExists(join8(srcDir, "components", "ComponentLayout.tsx"), COMPONENT_LAYOUT_TEMPLATE, "src/components/ComponentLayout.tsx");
|
|
3995
|
+
await writeIfNotExists(join8(srcDir, "components", "Section.tsx"), SECTION_TEMPLATE, "src/components/Section.tsx");
|
|
3996
|
+
await writeIfNotExists(join8(srcDir, "components", "puck", "HeadingComponent.tsx"), HEADING_COMPONENT_TEMPLATE, "src/components/puck/HeadingComponent.tsx");
|
|
3997
|
+
await writeIfNotExists(join8(srcDir, "components", "puck", "Heading.tsx"), HEADING_TEMPLATE, "src/components/puck/Heading.tsx");
|
|
3998
|
+
await writeIfNotExists(join8(srcDir, "components", "puck", "TextComponent.tsx"), TEXT_COMPONENT_TEMPLATE, "src/components/puck/TextComponent.tsx");
|
|
3999
|
+
await writeIfNotExists(join8(srcDir, "components", "puck", "Text.tsx"), TEXT_TEMPLATE, "src/components/puck/Text.tsx");
|
|
4000
|
+
await writeIfNotExists(join8(srcDir, "components", "puck", "Flex.tsx"), FLEX_TEMPLATE, "src/components/puck/Flex.tsx");
|
|
4001
|
+
await writeIfNotExists(join8(srcDir, "components", "puck", "Grid.tsx"), GRID_TEMPLATE, "src/components/puck/Grid.tsx");
|
|
4002
|
+
await writeIfNotExists(join8(srcDir, "puck.config.tsx"), PUCK_CONFIG_TEMPLATE, "src/puck.config.tsx");
|
|
4003
|
+
await writeIfNotExists(join8(srcDir, "schemas", "data.ts"), DATA_SCHEMAS_TEMPLATE, "src/schemas/data.ts");
|
|
4004
|
+
await writeIfNotExists(join8(srcDir, "layouts", "Layout.astro"), PAGE_LAYOUT_TEMPLATE, "src/layouts/Layout.astro");
|
|
4005
|
+
await writeIfNotExists(join8(absolutePath, ".claude", "skills", "conloca", "SKILL.md"), conloca_skill_default, ".claude/skills/conloca/SKILL.md");
|
|
4006
|
+
const sites = await ensureSiteInSitesConfig(contentDir, siteName);
|
|
4007
|
+
if (sites.added) {
|
|
4008
|
+
created.push(sites.existed ? `content/sites.json (added site: ${siteName})` : "content/sites.json");
|
|
4009
|
+
} else {
|
|
4010
|
+
skipped.push("content/sites.json");
|
|
4011
|
+
}
|
|
701
4012
|
console.log("Created:");
|
|
702
4013
|
for (const file of created) {
|
|
703
4014
|
console.log(` ✅ ${file}`);
|
|
@@ -711,153 +4022,368 @@ Skipped (already exist):`);
|
|
|
711
4022
|
}
|
|
712
4023
|
console.log(`
|
|
713
4024
|
✨ Astro setup complete!`);
|
|
714
|
-
|
|
715
|
-
Next steps:`);
|
|
716
|
-
console.log("1. Run `conloca init . <site-name>` to create content directory");
|
|
717
|
-
console.log("2. Configure routing in astro.config: conlocaCMS({ routing: true })");
|
|
718
|
-
console.log("3. Start your dev server and visit /__cms to edit pages");
|
|
719
|
-
console.log("4. Add more Puck components in src/components/puck/");
|
|
4025
|
+
return created;
|
|
720
4026
|
} catch (error) {
|
|
721
4027
|
console.error("❌ Error during setup:", error);
|
|
722
4028
|
throw error;
|
|
723
4029
|
}
|
|
724
4030
|
}
|
|
4031
|
+
function printSetupNextSteps() {
|
|
4032
|
+
console.log(`
|
|
4033
|
+
Next steps:`);
|
|
4034
|
+
console.log(`1. content/sites.json now lists the site '${DEFAULT_SITE_NAME}'. To add a second site,`);
|
|
4035
|
+
console.log(" run `conloca init . <site-name>`.");
|
|
4036
|
+
console.log(`
|
|
4037
|
+
2. Name the generated files in astro.config.mjs. Nothing loads them until`);
|
|
4038
|
+
console.log(` they are listed here, and react() must come before conlocaCMS():
|
|
4039
|
+
`);
|
|
4040
|
+
console.log(` import react from '@astrojs/react';
|
|
4041
|
+
import { conlocaCMS } from '@conloca/astro-cms/node';
|
|
725
4042
|
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
4043
|
+
export default defineConfig({
|
|
4044
|
+
integrations: [
|
|
4045
|
+
react(),
|
|
4046
|
+
conlocaCMS({
|
|
4047
|
+
contentRoot: './content',
|
|
4048
|
+
puckConfigPath: './src/puck.config.tsx',
|
|
4049
|
+
schemasPath: './src/schemas/data.ts',
|
|
4050
|
+
layout: './src/layouts/Layout.astro',
|
|
4051
|
+
}),
|
|
4052
|
+
],
|
|
4053
|
+
});`);
|
|
4054
|
+
console.log("\n `layout` on its own turns on a catch-all /[...slug] route over the pages");
|
|
4055
|
+
console.log(" collection. Adding `routing` replaces that route, and the top-level `layout`");
|
|
4056
|
+
console.log(" is then ignored — name it under routing.routes.<name>.layout instead.");
|
|
4057
|
+
console.log(`
|
|
4058
|
+
3. Create src/content.config.ts. Without it every content page returns 404:
|
|
4059
|
+
`);
|
|
4060
|
+
console.log(` import { conlocaData, conlocaFragments, conlocaPages } from '@conloca/astro-cms/node/content';
|
|
4061
|
+
import { dataSchemas } from './schemas/data';
|
|
4062
|
+
|
|
4063
|
+
export const collections = {
|
|
4064
|
+
pages: conlocaPages(),
|
|
4065
|
+
...conlocaData({ dataSchemas }),
|
|
4066
|
+
...conlocaFragments(),
|
|
4067
|
+
};`);
|
|
4068
|
+
console.log(`
|
|
4069
|
+
Every collection is declared here by name — content the config does not name`);
|
|
4070
|
+
console.log(" fails the build instead of silently not building. The generated schemas file");
|
|
4071
|
+
console.log(" already declares its data collections, so they are covered before the first");
|
|
4072
|
+
console.log(" entry is saved.");
|
|
4073
|
+
console.log(`
|
|
4074
|
+
4. Start your dev server and visit /__cms to edit pages`);
|
|
4075
|
+
console.log("5. Add more Puck components in src/components/puck/");
|
|
4076
|
+
console.log("6. Working with a coding agent? .claude/skills/conloca/SKILL.md teaches it Conloca");
|
|
4077
|
+
}
|
|
4078
|
+
|
|
4079
|
+
// src/commands/create.ts
|
|
4080
|
+
var execFile = promisify(execFileCallback);
|
|
4081
|
+
var SITE_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
|
|
4082
|
+
async function assertEmptyDirectory(directory) {
|
|
4083
|
+
const entries = await readdir3(directory).catch((error) => {
|
|
4084
|
+
if (error.code === "ENOENT")
|
|
4085
|
+
return [];
|
|
4086
|
+
throw error;
|
|
4087
|
+
});
|
|
4088
|
+
if (entries.some((entry) => entry !== ".git")) {
|
|
4089
|
+
throw new Error(`${directory} is not empty — for an existing Astro site run 'conloca astro setup' instead`);
|
|
741
4090
|
}
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
})
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
4091
|
+
}
|
|
4092
|
+
async function writeTemplate(directory, name, pm, siteName) {
|
|
4093
|
+
const files = [
|
|
4094
|
+
["package.json", renderPackageJson({ name, manifest: await readCliManifest() })],
|
|
4095
|
+
["astro.config.mjs", renderAstroConfig(siteName)],
|
|
4096
|
+
["tsconfig.json", TSCONFIG_TEMPLATE],
|
|
4097
|
+
["src/content.config.ts", CONTENT_CONFIG_TEMPLATE],
|
|
4098
|
+
[".gitignore", GITIGNORE_TEMPLATE],
|
|
4099
|
+
["README.md", renderReadme(name, packageManagerCommands(pm).run)],
|
|
4100
|
+
[".github/workflows/conloca.yml", renderWorkflow(pm)]
|
|
4101
|
+
];
|
|
4102
|
+
for (const [file, content] of files) {
|
|
4103
|
+
const path = join9(directory, file);
|
|
4104
|
+
await mkdir2(dirname2(path), { recursive: true });
|
|
4105
|
+
await writeFile3(path, content, "utf-8");
|
|
4106
|
+
}
|
|
4107
|
+
return files.map(([file]) => file);
|
|
4108
|
+
}
|
|
4109
|
+
async function writeHomePage(directory, contentRoot, siteName, name) {
|
|
4110
|
+
const written = await writePage({
|
|
4111
|
+
contentRoot,
|
|
4112
|
+
site: siteName,
|
|
4113
|
+
collection: "pages",
|
|
4114
|
+
pathname: "/",
|
|
4115
|
+
title: "Home",
|
|
4116
|
+
puckData: {
|
|
4117
|
+
root: {},
|
|
4118
|
+
content: [
|
|
4119
|
+
{
|
|
4120
|
+
type: "Heading",
|
|
4121
|
+
props: {
|
|
4122
|
+
id: "Heading-welcome",
|
|
4123
|
+
text: `Welcome to ${name}`,
|
|
4124
|
+
level: "1",
|
|
4125
|
+
size: "xxl",
|
|
4126
|
+
align: "left",
|
|
4127
|
+
layout: { padding: "8px" }
|
|
759
4128
|
}
|
|
760
|
-
} catch (error) {
|
|
761
|
-
errorCount++;
|
|
762
|
-
errors.push(`Error loading ${manifest.id} (${locale}): ${error}`);
|
|
763
4129
|
}
|
|
764
|
-
|
|
4130
|
+
],
|
|
4131
|
+
zones: {}
|
|
765
4132
|
}
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
4133
|
+
});
|
|
4134
|
+
return relative(directory, written.filePath);
|
|
4135
|
+
}
|
|
4136
|
+
function runInstall(pm, directory, quiet) {
|
|
4137
|
+
const [command, ...args] = packageManagerCommands(pm).install.split(" ");
|
|
4138
|
+
return new Promise((resolveInstall) => {
|
|
4139
|
+
const child = spawn(command, args, {
|
|
4140
|
+
cwd: directory,
|
|
4141
|
+
stdio: ["ignore", quiet ? process.stderr : "inherit", "inherit"],
|
|
4142
|
+
shell: process.platform === "win32"
|
|
4143
|
+
});
|
|
4144
|
+
child.on("error", (error) => {
|
|
4145
|
+
console.error(`${command}: ${error.message}`);
|
|
4146
|
+
resolveInstall(false);
|
|
4147
|
+
});
|
|
4148
|
+
child.on("exit", (code) => resolveInstall(code === 0));
|
|
4149
|
+
});
|
|
4150
|
+
}
|
|
4151
|
+
async function initGit(directory) {
|
|
4152
|
+
const inside = await execFile("git", ["rev-parse", "--is-inside-work-tree"], { cwd: directory }).then(() => true, () => false);
|
|
4153
|
+
if (inside)
|
|
4154
|
+
return "already-in-repo";
|
|
4155
|
+
return execFile("git", ["init", "-q"], { cwd: directory }).then(() => "initialized", () => "failed");
|
|
4156
|
+
}
|
|
4157
|
+
async function buildProject(directory, name, pm, options) {
|
|
4158
|
+
const { json } = options;
|
|
4159
|
+
await assertEmptyDirectory(directory);
|
|
4160
|
+
await mkdir2(directory, { recursive: true });
|
|
4161
|
+
const contentRoot = join9(directory, "content");
|
|
4162
|
+
const created = await withStdoutRedirected(json, async () => {
|
|
4163
|
+
const files = await writeTemplate(directory, name, pm, options.site);
|
|
4164
|
+
files.push(...await setup(directory, options.site));
|
|
4165
|
+
files.push(await writeHomePage(directory, contentRoot, options.site, name));
|
|
4166
|
+
return files;
|
|
4167
|
+
});
|
|
4168
|
+
const install = options.install ? await runInstall(pm, directory, json) ? "done" : "failed" : "skipped";
|
|
4169
|
+
const git = options.git ? await initGit(directory) : "skipped";
|
|
4170
|
+
const report = await runDoctor(directory, contentRoot, { live: false });
|
|
4171
|
+
return {
|
|
4172
|
+
result: {
|
|
4173
|
+
ok: install !== "failed" && report.ok,
|
|
4174
|
+
directory,
|
|
4175
|
+
packageManager: pm,
|
|
4176
|
+
created,
|
|
4177
|
+
install,
|
|
4178
|
+
git,
|
|
4179
|
+
doctor: { ok: report.ok, problems: report.problems }
|
|
4180
|
+
},
|
|
4181
|
+
report,
|
|
4182
|
+
contentRoot
|
|
4183
|
+
};
|
|
4184
|
+
}
|
|
4185
|
+
function printCreateReport(result, report, contentRoot, name) {
|
|
4186
|
+
console.log(`
|
|
4187
|
+
Created ${name} in ${result.directory} (${result.created.length} files)`);
|
|
4188
|
+
printReport(contentRoot, report);
|
|
4189
|
+
const commands = packageManagerCommands(result.packageManager);
|
|
4190
|
+
console.log(`
|
|
4191
|
+
Next:`);
|
|
4192
|
+
const step = relative(process.cwd(), result.directory) || ".";
|
|
4193
|
+
const target = step.startsWith("..") ? result.directory : step;
|
|
4194
|
+
console.log(` cd ${/\s/.test(target) ? `'${target}'` : target}`);
|
|
4195
|
+
if (result.install !== "done")
|
|
4196
|
+
console.log(` ${commands.install}`);
|
|
4197
|
+
console.log(` ${commands.run} dev # then open http://localhost:4321/__cms`);
|
|
4198
|
+
}
|
|
4199
|
+
async function create(target, options) {
|
|
4200
|
+
const { json } = options;
|
|
4201
|
+
const directory = resolve5(target);
|
|
4202
|
+
let pm;
|
|
4203
|
+
try {
|
|
4204
|
+
pm = detectPackageManager({ flag: options.pm, userAgent: process.env.npm_config_user_agent });
|
|
4205
|
+
} catch (error) {
|
|
4206
|
+
fail(json, error instanceof Error ? error.message : String(error), "pm");
|
|
4207
|
+
}
|
|
4208
|
+
if (!SITE_NAME_RE.test(options.site)) {
|
|
4209
|
+
fail(json, `--site must be letters, digits, '-' or '_' (got '${options.site}')`, "site");
|
|
4210
|
+
}
|
|
4211
|
+
if (RESERVED_CONTENT_DIRS.has(options.site)) {
|
|
4212
|
+
fail(json, `--site cannot be '${options.site}' — that is a reserved content directory`, "site");
|
|
4213
|
+
}
|
|
4214
|
+
const name = packageNameOf(directory);
|
|
4215
|
+
let built;
|
|
4216
|
+
try {
|
|
4217
|
+
built = await buildProject(directory, name, pm, options);
|
|
4218
|
+
} catch (error) {
|
|
4219
|
+
fail(json, error instanceof Error ? error.message : String(error));
|
|
4220
|
+
}
|
|
4221
|
+
const { result, report, contentRoot } = built;
|
|
4222
|
+
if (json) {
|
|
4223
|
+
console.log(JSON.stringify(result));
|
|
4224
|
+
} else {
|
|
4225
|
+
printCreateReport(result, report, contentRoot, name);
|
|
4226
|
+
}
|
|
4227
|
+
if (result.install === "failed") {
|
|
4228
|
+
console.error(`install failed — rerun: ${packageManagerCommands(pm).install} (in ${directory})`);
|
|
4229
|
+
}
|
|
4230
|
+
if (result.git === "failed") {
|
|
4231
|
+
console.error(`git init failed — rerun: git init (in ${directory})`);
|
|
4232
|
+
}
|
|
4233
|
+
if (!result.ok)
|
|
4234
|
+
process.exit(1);
|
|
4235
|
+
}
|
|
4236
|
+
|
|
4237
|
+
// src/commands/init.ts
|
|
4238
|
+
import { mkdir as mkdir3 } from "node:fs/promises";
|
|
4239
|
+
import { join as join10 } from "node:path";
|
|
4240
|
+
async function init(directory, siteName) {
|
|
4241
|
+
const contentPath = contentRootOf(directory);
|
|
4242
|
+
try {
|
|
4243
|
+
const contentDirs = [contentPath, join10(contentPath, siteName, "pages"), join10(contentPath, "fragments", "shared")];
|
|
4244
|
+
for (const dir of contentDirs) {
|
|
4245
|
+
await mkdir3(dir, { recursive: true });
|
|
4246
|
+
console.log(` Created: ${dir}`);
|
|
4247
|
+
}
|
|
4248
|
+
const sites = await ensureSiteInSitesConfig(contentPath, siteName);
|
|
4249
|
+
if (sites.existed) {
|
|
4250
|
+
console.log(" Found existing sites.json");
|
|
772
4251
|
}
|
|
773
|
-
|
|
774
|
-
|
|
4252
|
+
if (sites.added) {
|
|
4253
|
+
console.log(` Updated: ${sites.path} (added site: ${siteName})`);
|
|
4254
|
+
} else {
|
|
4255
|
+
console.log(` Site '${siteName}' already exists in sites.json`);
|
|
4256
|
+
}
|
|
4257
|
+
console.log(`
|
|
4258
|
+
✓ Initialized Conloca content structure for site '${siteName}' in ${contentPath}`);
|
|
775
4259
|
console.log(`
|
|
776
|
-
|
|
4260
|
+
Next steps:`);
|
|
4261
|
+
console.log(` 1. Create your first page in ${join10(contentPath, siteName, "pages")}`);
|
|
4262
|
+
console.log(` 2. Run 'conloca doctor' to check the setup`);
|
|
4263
|
+
console.log(` 3. Point the conlocaCMS() contentRoot option at ${contentPath}`);
|
|
777
4264
|
} catch (error) {
|
|
778
|
-
console.error("
|
|
4265
|
+
console.error("Failed to initialize content structure");
|
|
779
4266
|
console.error(` ${error}`);
|
|
780
4267
|
process.exit(1);
|
|
781
4268
|
}
|
|
782
4269
|
}
|
|
783
4270
|
|
|
4271
|
+
// src/commands/page-create.ts
|
|
4272
|
+
import { relative as relative2 } from "node:path";
|
|
4273
|
+
function toCliMessage(error, directory, options) {
|
|
4274
|
+
switch (error.reason) {
|
|
4275
|
+
case "missing_leading_slash":
|
|
4276
|
+
return `--pathname must start with '/' (got '${options.pathname}')`;
|
|
4277
|
+
case "no_sites_configured":
|
|
4278
|
+
return `${error.message} — run 'conloca init ${directory} ${options.site}' first`;
|
|
4279
|
+
default:
|
|
4280
|
+
return error.message;
|
|
4281
|
+
}
|
|
4282
|
+
}
|
|
4283
|
+
async function pageCreate(directory, options) {
|
|
4284
|
+
try {
|
|
4285
|
+
await createPage(directory, options);
|
|
4286
|
+
} catch (error) {
|
|
4287
|
+
fail(options.json, error instanceof Error ? error.message : String(error));
|
|
4288
|
+
}
|
|
4289
|
+
}
|
|
4290
|
+
async function createPage(directory, options) {
|
|
4291
|
+
const contentRoot = contentRootOf(directory);
|
|
4292
|
+
const { json } = options;
|
|
4293
|
+
let written;
|
|
4294
|
+
try {
|
|
4295
|
+
written = await withStdoutRedirected(json, () => writePage({
|
|
4296
|
+
contentRoot,
|
|
4297
|
+
site: options.site,
|
|
4298
|
+
collection: options.collection,
|
|
4299
|
+
pathname: options.pathname,
|
|
4300
|
+
title: options.title
|
|
4301
|
+
}));
|
|
4302
|
+
} catch (error) {
|
|
4303
|
+
if (error instanceof PageWriteError) {
|
|
4304
|
+
fail(json, toCliMessage(error, directory, options), error.field);
|
|
4305
|
+
}
|
|
4306
|
+
throw error;
|
|
4307
|
+
}
|
|
4308
|
+
const relPath = relative2(process.cwd(), written.filePath);
|
|
4309
|
+
if (json) {
|
|
4310
|
+
console.log(JSON.stringify({ ok: true, id: written.id, path: relPath }));
|
|
4311
|
+
return;
|
|
4312
|
+
}
|
|
4313
|
+
console.log(`✓ Created page ${written.pathname} (${written.id})`);
|
|
4314
|
+
console.log(` File: ${relPath}`);
|
|
4315
|
+
console.log("The page is now editable in the CMS.");
|
|
4316
|
+
}
|
|
4317
|
+
|
|
784
4318
|
// src/cli.ts
|
|
4319
|
+
var program2 = new Command;
|
|
4320
|
+
program2.name("conloca").usage("<command> [options]").helpOption("-h, --help", "Show this help message").addHelpText("after", `
|
|
4321
|
+
Run 'conloca <command> --help' for help on a single command.`);
|
|
4322
|
+
program2.command("init").argument("<directory>", "Where the content root is created").argument("<site>", "Site name recorded in sites.json").description("Initialize a new Conloca content structure").addHelpText("after", `
|
|
4323
|
+
Creates the content structure: <directory>/content with a pages folder for
|
|
4324
|
+
<site>, a shared fragments folder, and sites.json. Pointing it at a directory
|
|
4325
|
+
already named 'content' uses that directory as the content root, unless it
|
|
4326
|
+
holds a content/ directory of its own.`).action(async (directory, site) => {
|
|
4327
|
+
await init(directory, site);
|
|
4328
|
+
});
|
|
4329
|
+
program2.command("create").argument("<directory>", "Empty directory for the new site (created if missing)").option("--site <site>", "Site name recorded in sites.json", DEFAULT_SITE_NAME).option("--pm <manager>", `Package manager: ${PACKAGE_MANAGERS.join(", ")} (default: the one that launched the CLI)`).option("--no-install", "Skip installing dependencies").option("--no-git", "Skip git init").option("--json", "Report as a single JSON object on stdout").description("Create a new Astro site with Conloca CMS wired in").addHelpText("after", `
|
|
4330
|
+
Writes a complete Astro project into <directory>: package.json, astro.config
|
|
4331
|
+
with conlocaCMS wired, tsconfig, content config, starter components, a first
|
|
4332
|
+
page, the agent skill and a CI workflow with an inert build-token slot.
|
|
4333
|
+
Then installs dependencies, initialises git, and runs the doctor on the result.
|
|
4334
|
+
Refuses a non-empty directory — for an existing site use 'conloca astro setup'.`).action(async (directory, options) => {
|
|
4335
|
+
await create(directory, {
|
|
4336
|
+
site: options.site,
|
|
4337
|
+
pm: options.pm,
|
|
4338
|
+
install: options.install,
|
|
4339
|
+
git: options.git,
|
|
4340
|
+
json: options.json === true
|
|
4341
|
+
});
|
|
4342
|
+
});
|
|
4343
|
+
program2.command("doctor").argument("[path]", "Project directory to check", ".").option("--json", "Report as a single JSON object on stdout").option("--live", "Let doctor extensions contact the services the project configures").description("Check the content directory for problems").addHelpText("after", `
|
|
4344
|
+
Runs read-only health checks over the project in [path]: sites.json is present
|
|
4345
|
+
and complete, every site has its pages directory, and every content file
|
|
4346
|
+
indexes cleanly. When an astro.config is present it also checks the Astro
|
|
4347
|
+
wiring: content config, conlocaCMS import and options, react() order, peer
|
|
4348
|
+
dependencies, tsconfig jsx, prerender under server output, and home-page
|
|
4349
|
+
shadowing. Dependencies that ship a doctor extension (a conloca.doctor field
|
|
4350
|
+
in their package.json) add their own checks; --live lets those extensions
|
|
4351
|
+
reach the services the project configures, otherwise they stay offline.
|
|
4352
|
+
Never modifies any file. Exits 1 when an error is found; warnings alone exit
|
|
4353
|
+
0. Pointing it at a directory already named 'content' uses that directory as
|
|
4354
|
+
the content root, unless it holds a content/ directory of its own. Replaces
|
|
4355
|
+
the retired verify command.`).action(async (path, options) => {
|
|
4356
|
+
await doctor(path, { json: options.json === true, live: options.live === true });
|
|
4357
|
+
});
|
|
4358
|
+
var page = program2.command("page").usage("<subcommand>").description("Page management commands");
|
|
4359
|
+
page.command("create").argument("[path]", "Project directory holding the content root", ".").requiredOption("--site <site>", "Site the page belongs to (a key in sites.json)").requiredOption("--collection <collection>", "Collection directory under the site, e.g. 'pages'").requiredOption("--pathname <pathname>", "Page route, starting with '/'").requiredOption("--title <title>", "Page title (meta.title)").option("--json", "Report as a single JSON object on stdout").description("Create an empty Puck page in the site's default locale").addHelpText("after", `
|
|
4360
|
+
Writes a new .vxjson page file under <content root>/<site>/<collection>, with
|
|
4361
|
+
the same empty Puck payload the CMS writes for a new page, in the site's
|
|
4362
|
+
default locale from sites.json. Prints the created file path and page id;
|
|
4363
|
+
--json prints {ok, id, path} instead. Exits 1 when the site is unknown, the
|
|
4364
|
+
pathname is invalid or already taken, or the write fails.`).action(async (path, options) => {
|
|
4365
|
+
await pageCreate(path, {
|
|
4366
|
+
site: options.site,
|
|
4367
|
+
collection: options.collection,
|
|
4368
|
+
pathname: options.pathname,
|
|
4369
|
+
title: options.title,
|
|
4370
|
+
json: options.json === true
|
|
4371
|
+
});
|
|
4372
|
+
});
|
|
4373
|
+
var astro = program2.command("astro").usage("<subcommand>").description("Astro framework integration commands");
|
|
4374
|
+
astro.command("setup").argument("[path]", "Project directory to set up", ".").description("Set up Astro integration (components, Puck config)").addHelpText("after", `
|
|
4375
|
+
Writes the starter components, Puck config and data schemas into [path], then
|
|
4376
|
+
prints the astro.config options that load them.`).action(async (path) => {
|
|
4377
|
+
await setup(path);
|
|
4378
|
+
printSetupNextSteps();
|
|
4379
|
+
});
|
|
785
4380
|
async function main() {
|
|
786
4381
|
try {
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
options: {
|
|
790
|
-
help: {
|
|
791
|
-
type: "boolean",
|
|
792
|
-
short: "h"
|
|
793
|
-
},
|
|
794
|
-
site: {
|
|
795
|
-
type: "string",
|
|
796
|
-
short: "s"
|
|
797
|
-
}
|
|
798
|
-
},
|
|
799
|
-
allowPositionals: true
|
|
800
|
-
});
|
|
801
|
-
if (values.help || positionals.length === 0) {
|
|
802
|
-
console.log(`Usage: conloca <command> [options]
|
|
803
|
-
|
|
804
|
-
Commands:
|
|
805
|
-
init <directory> <site> Initialize a new Conloca content structure
|
|
806
|
-
verify <directory> Verify content in the specified directory
|
|
807
|
-
astro <subcommand> [options] Astro framework integration commands
|
|
808
|
-
|
|
809
|
-
Astro Subcommands:
|
|
810
|
-
astro setup [path] Set up Astro integration (components, Puck config)
|
|
811
|
-
|
|
812
|
-
Options:
|
|
813
|
-
-h, --help Show this help message
|
|
814
|
-
-s, --site <name> Site name to target (default: default)`);
|
|
4382
|
+
if (process.argv.length <= 2) {
|
|
4383
|
+
program2.outputHelp();
|
|
815
4384
|
process.exit(0);
|
|
816
4385
|
}
|
|
817
|
-
|
|
818
|
-
switch (command) {
|
|
819
|
-
case "init":
|
|
820
|
-
if (positionals.length < 2) {
|
|
821
|
-
console.error("Error: init command requires a directory argument");
|
|
822
|
-
process.exit(1);
|
|
823
|
-
}
|
|
824
|
-
if (positionals.length < 3) {
|
|
825
|
-
console.error("Error: init command requires a site name argument");
|
|
826
|
-
process.exit(1);
|
|
827
|
-
}
|
|
828
|
-
await init(positionals[1], positionals[2]);
|
|
829
|
-
break;
|
|
830
|
-
case "verify":
|
|
831
|
-
if (positionals.length < 2) {
|
|
832
|
-
console.error("Error: verify command requires a directory argument");
|
|
833
|
-
process.exit(1);
|
|
834
|
-
}
|
|
835
|
-
await verify(positionals[1]);
|
|
836
|
-
break;
|
|
837
|
-
case "astro": {
|
|
838
|
-
const subcommand = positionals[1];
|
|
839
|
-
if (!subcommand) {
|
|
840
|
-
console.error(`Error: astro command requires a subcommand
|
|
841
|
-
Available subcommands:
|
|
842
|
-
setup [path] Set up Astro integration (components, Puck config)`);
|
|
843
|
-
process.exit(1);
|
|
844
|
-
}
|
|
845
|
-
switch (subcommand) {
|
|
846
|
-
case "setup": {
|
|
847
|
-
const projectPath = positionals[2] || ".";
|
|
848
|
-
await setup(projectPath);
|
|
849
|
-
break;
|
|
850
|
-
}
|
|
851
|
-
default:
|
|
852
|
-
console.error(`Error: Unknown astro subcommand '${subcommand}'`);
|
|
853
|
-
process.exit(1);
|
|
854
|
-
}
|
|
855
|
-
break;
|
|
856
|
-
}
|
|
857
|
-
default:
|
|
858
|
-
console.error(`Error: Unknown command '${command}'`);
|
|
859
|
-
process.exit(1);
|
|
860
|
-
}
|
|
4386
|
+
await program2.parseAsync(process.argv);
|
|
861
4387
|
} catch (error) {
|
|
862
4388
|
console.error("Error:", error);
|
|
863
4389
|
process.exit(1);
|