@makoojs/cli 0.1.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/LICENSE +21 -0
- package/README.CN.md +373 -0
- package/README.md +373 -0
- package/dist/bin.js +1506 -0
- package/dist/command/_util.d.ts +16 -0
- package/dist/command/add.d.ts +1 -0
- package/dist/command/bin.d.ts +2 -0
- package/dist/command/build.d.ts +1 -0
- package/dist/command/dev.d.ts +1 -0
- package/dist/command/inspect.d.ts +1 -0
- package/dist/config/config.d.ts +3 -0
- package/dist/config/defaults.d.ts +26 -0
- package/dist/config/resolve.d.ts +17 -0
- package/dist/config/types.d.ts +140 -0
- package/dist/config/validation.d.ts +15 -0
- package/dist/error/error.d.ts +46 -0
- package/dist/generator/generator.d.ts +3 -0
- package/dist/generator/render/import/importAdapter.d.ts +3 -0
- package/dist/generator/render/import/importComp.d.ts +3 -0
- package/dist/generator/render/import/importInjector.d.ts +1 -0
- package/dist/generator/render/import/importRuntimeSetup.d.ts +1 -0
- package/dist/generator/render/init/initInjector.d.ts +3 -0
- package/dist/generator/render/init/registerComp.d.ts +2 -0
- package/dist/generator/render/run/renderInjectorRun.d.ts +1 -0
- package/dist/generator/render/util/value.d.ts +1 -0
- package/dist/generator/types.d.ts +21 -0
- package/dist/index.cjs +86 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5090 -0
- package/dist/monkey/clipboard.d.ts +3 -0
- package/dist/monkey/download.d.ts +3 -0
- package/dist/monkey/index.cjs +1 -0
- package/dist/monkey/index.d.ts +60 -0
- package/dist/monkey/index.js +60 -0
- package/dist/monkey/info.d.ts +5 -0
- package/dist/monkey/menu.d.ts +4 -0
- package/dist/monkey/notification.d.ts +3 -0
- package/dist/monkey/request.d.ts +7 -0
- package/dist/monkey/resource.d.ts +4 -0
- package/dist/monkey/storage.d.ts +11 -0
- package/dist/monkey/style.d.ts +4 -0
- package/dist/monkey/tab.d.ts +6 -0
- package/dist/scanner/collectDependenics.d.ts +2 -0
- package/dist/scanner/load/loadManifes.d.ts +3 -0
- package/dist/scanner/load/loadMeta.d.ts +2 -0
- package/dist/scanner/scanner.d.ts +3 -0
- package/dist/scanner/types.d.ts +23 -0
- package/dist/scanner/util.d.ts +2 -0
- package/dist/scanner/validation.d.ts +121 -0
- package/dist/vitePlugin/hmrController.d.ts +4 -0
- package/dist/vitePlugin/makoo.d.ts +3 -0
- package/dist/vitePlugin/makooMonkey.d.ts +3 -0
- package/dist/vitePlugin/types.d.ts +12 -0
- package/dist/vitePlugin/virtualModule.d.ts +2 -0
- package/dist/vitePlugin/watchList.d.ts +4 -0
- package/package.json +54 -0
package/dist/bin.js
ADDED
|
@@ -0,0 +1,1506 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/command/bin.ts
|
|
4
|
+
import { MakooError as MakooError2 } from "@makoojs/core";
|
|
5
|
+
|
|
6
|
+
// ../../node_modules/.pnpm/cac@7.0.0/node_modules/cac/dist/index.js
|
|
7
|
+
function toArr(any) {
|
|
8
|
+
return any == null ? [] : Array.isArray(any) ? any : [any];
|
|
9
|
+
}
|
|
10
|
+
function toVal(out, key, val, opts) {
|
|
11
|
+
var x, old = out[key], nxt = !!~opts.string.indexOf(key) ? val == null || val === true ? "" : String(val) : typeof val === "boolean" ? val : !!~opts.boolean.indexOf(key) ? val === "false" ? false : val === "true" || (out._.push((x = +val, x * 0 === 0) ? x : val), !!val) : (x = +val, x * 0 === 0) ? x : val;
|
|
12
|
+
out[key] = old == null ? nxt : Array.isArray(old) ? old.concat(nxt) : [old, nxt];
|
|
13
|
+
}
|
|
14
|
+
function lib_default(args, opts) {
|
|
15
|
+
args = args || [];
|
|
16
|
+
opts = opts || {};
|
|
17
|
+
var k, arr, arg, name, val, out = { _: [] };
|
|
18
|
+
var i = 0, j = 0, idx = 0, len = args.length;
|
|
19
|
+
const alibi = opts.alias !== void 0;
|
|
20
|
+
const strict = opts.unknown !== void 0;
|
|
21
|
+
const defaults = opts.default !== void 0;
|
|
22
|
+
opts.alias = opts.alias || {};
|
|
23
|
+
opts.string = toArr(opts.string);
|
|
24
|
+
opts.boolean = toArr(opts.boolean);
|
|
25
|
+
if (alibi) for (k in opts.alias) {
|
|
26
|
+
arr = opts.alias[k] = toArr(opts.alias[k]);
|
|
27
|
+
for (i = 0; i < arr.length; i++) (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
|
|
28
|
+
}
|
|
29
|
+
for (i = opts.boolean.length; i-- > 0; ) {
|
|
30
|
+
arr = opts.alias[opts.boolean[i]] || [];
|
|
31
|
+
for (j = arr.length; j-- > 0; ) opts.boolean.push(arr[j]);
|
|
32
|
+
}
|
|
33
|
+
for (i = opts.string.length; i-- > 0; ) {
|
|
34
|
+
arr = opts.alias[opts.string[i]] || [];
|
|
35
|
+
for (j = arr.length; j-- > 0; ) opts.string.push(arr[j]);
|
|
36
|
+
}
|
|
37
|
+
if (defaults) for (k in opts.default) {
|
|
38
|
+
name = typeof opts.default[k];
|
|
39
|
+
arr = opts.alias[k] = opts.alias[k] || [];
|
|
40
|
+
if (opts[name] !== void 0) {
|
|
41
|
+
opts[name].push(k);
|
|
42
|
+
for (i = 0; i < arr.length; i++) opts[name].push(arr[i]);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const keys = strict ? Object.keys(opts.alias) : [];
|
|
46
|
+
for (i = 0; i < len; i++) {
|
|
47
|
+
arg = args[i];
|
|
48
|
+
if (arg === "--") {
|
|
49
|
+
out._ = out._.concat(args.slice(++i));
|
|
50
|
+
break;
|
|
51
|
+
}
|
|
52
|
+
for (j = 0; j < arg.length; j++) if (arg.charCodeAt(j) !== 45) break;
|
|
53
|
+
if (j === 0) out._.push(arg);
|
|
54
|
+
else if (arg.substring(j, j + 3) === "no-") {
|
|
55
|
+
name = arg.substring(j + 3);
|
|
56
|
+
if (strict && !~keys.indexOf(name)) return opts.unknown(arg);
|
|
57
|
+
out[name] = false;
|
|
58
|
+
} else {
|
|
59
|
+
for (idx = j + 1; idx < arg.length; idx++) if (arg.charCodeAt(idx) === 61) break;
|
|
60
|
+
name = arg.substring(j, idx);
|
|
61
|
+
val = arg.substring(++idx) || i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i];
|
|
62
|
+
arr = j === 2 ? [name] : name;
|
|
63
|
+
for (idx = 0; idx < arr.length; idx++) {
|
|
64
|
+
name = arr[idx];
|
|
65
|
+
if (strict && !~keys.indexOf(name)) return opts.unknown("-".repeat(j) + name);
|
|
66
|
+
toVal(out, name, idx + 1 < arr.length || val, opts);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (defaults) {
|
|
71
|
+
for (k in opts.default) if (out[k] === void 0) out[k] = opts.default[k];
|
|
72
|
+
}
|
|
73
|
+
if (alibi) for (k in out) {
|
|
74
|
+
arr = opts.alias[k] || [];
|
|
75
|
+
while (arr.length > 0) out[arr.shift()] = out[k];
|
|
76
|
+
}
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
function removeBrackets(v) {
|
|
80
|
+
return v.replace(/[<[].+/, "").trim();
|
|
81
|
+
}
|
|
82
|
+
function findAllBrackets(v) {
|
|
83
|
+
const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
|
|
84
|
+
const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
|
|
85
|
+
const res = [];
|
|
86
|
+
const parse = (match) => {
|
|
87
|
+
let variadic = false;
|
|
88
|
+
let value = match[1];
|
|
89
|
+
if (value.startsWith("...")) {
|
|
90
|
+
value = value.slice(3);
|
|
91
|
+
variadic = true;
|
|
92
|
+
}
|
|
93
|
+
return {
|
|
94
|
+
required: match[0].startsWith("<"),
|
|
95
|
+
value,
|
|
96
|
+
variadic
|
|
97
|
+
};
|
|
98
|
+
};
|
|
99
|
+
let angledMatch;
|
|
100
|
+
while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) res.push(parse(angledMatch));
|
|
101
|
+
let squareMatch;
|
|
102
|
+
while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) res.push(parse(squareMatch));
|
|
103
|
+
return res;
|
|
104
|
+
}
|
|
105
|
+
function getMriOptions(options) {
|
|
106
|
+
const result = {
|
|
107
|
+
alias: {},
|
|
108
|
+
boolean: []
|
|
109
|
+
};
|
|
110
|
+
for (const [index, option] of options.entries()) {
|
|
111
|
+
if (option.names.length > 1) result.alias[option.names[0]] = option.names.slice(1);
|
|
112
|
+
if (option.isBoolean) if (option.negated) {
|
|
113
|
+
if (!options.some((o, i) => {
|
|
114
|
+
return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
|
|
115
|
+
})) result.boolean.push(option.names[0]);
|
|
116
|
+
} else result.boolean.push(option.names[0]);
|
|
117
|
+
}
|
|
118
|
+
return result;
|
|
119
|
+
}
|
|
120
|
+
function findLongest(arr) {
|
|
121
|
+
return arr.sort((a, b) => {
|
|
122
|
+
return a.length > b.length ? -1 : 1;
|
|
123
|
+
})[0];
|
|
124
|
+
}
|
|
125
|
+
function padRight(str, length) {
|
|
126
|
+
return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
|
|
127
|
+
}
|
|
128
|
+
function camelcase(input) {
|
|
129
|
+
return input.replaceAll(/([a-z])-([a-z])/g, (_, p1, p2) => {
|
|
130
|
+
return p1 + p2.toUpperCase();
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
function setDotProp(obj, keys, val) {
|
|
134
|
+
let current = obj;
|
|
135
|
+
for (let i = 0; i < keys.length; i++) {
|
|
136
|
+
const key = keys[i];
|
|
137
|
+
if (i === keys.length - 1) {
|
|
138
|
+
current[key] = val;
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (current[key] == null) {
|
|
142
|
+
const nextKeyIsArrayIndex = +keys[i + 1] > -1;
|
|
143
|
+
current[key] = nextKeyIsArrayIndex ? [] : {};
|
|
144
|
+
}
|
|
145
|
+
current = current[key];
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
function setByType(obj, transforms) {
|
|
149
|
+
for (const key of Object.keys(transforms)) {
|
|
150
|
+
const transform = transforms[key];
|
|
151
|
+
if (transform.shouldTransform) {
|
|
152
|
+
obj[key] = [obj[key]].flat();
|
|
153
|
+
if (typeof transform.transformFunction === "function") obj[key] = obj[key].map(transform.transformFunction);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
function getFileName(input) {
|
|
158
|
+
const m = /([^\\/]+)$/.exec(input);
|
|
159
|
+
return m ? m[1] : "";
|
|
160
|
+
}
|
|
161
|
+
function camelcaseOptionName(name) {
|
|
162
|
+
return name.split(".").map((v, i) => {
|
|
163
|
+
return i === 0 ? camelcase(v) : v;
|
|
164
|
+
}).join(".");
|
|
165
|
+
}
|
|
166
|
+
var CACError = class extends Error {
|
|
167
|
+
constructor(message) {
|
|
168
|
+
super(message);
|
|
169
|
+
this.name = "CACError";
|
|
170
|
+
if (typeof Error.captureStackTrace !== "function") this.stack = new Error(message).stack;
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
var Option = class {
|
|
174
|
+
rawName;
|
|
175
|
+
description;
|
|
176
|
+
/** Option name */
|
|
177
|
+
name;
|
|
178
|
+
/** Option name and aliases */
|
|
179
|
+
names;
|
|
180
|
+
isBoolean;
|
|
181
|
+
required;
|
|
182
|
+
config;
|
|
183
|
+
negated;
|
|
184
|
+
constructor(rawName, description, config) {
|
|
185
|
+
this.rawName = rawName;
|
|
186
|
+
this.description = description;
|
|
187
|
+
this.config = Object.assign({}, config);
|
|
188
|
+
rawName = rawName.replaceAll(".*", "");
|
|
189
|
+
this.negated = false;
|
|
190
|
+
this.names = removeBrackets(rawName).split(",").map((v) => {
|
|
191
|
+
let name = v.trim().replace(/^-{1,2}/, "");
|
|
192
|
+
if (name.startsWith("no-")) {
|
|
193
|
+
this.negated = true;
|
|
194
|
+
name = name.replace(/^no-/, "");
|
|
195
|
+
}
|
|
196
|
+
return camelcaseOptionName(name);
|
|
197
|
+
}).sort((a, b) => a.length > b.length ? 1 : -1);
|
|
198
|
+
this.name = this.names.at(-1);
|
|
199
|
+
if (this.negated && this.config.default == null) this.config.default = true;
|
|
200
|
+
if (rawName.includes("<")) this.required = true;
|
|
201
|
+
else if (rawName.includes("[")) this.required = false;
|
|
202
|
+
else this.isBoolean = true;
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
var runtimeProcessArgs;
|
|
206
|
+
var runtimeInfo;
|
|
207
|
+
if (typeof process !== "undefined") {
|
|
208
|
+
let runtimeName;
|
|
209
|
+
if (typeof Deno !== "undefined" && typeof Deno.version?.deno === "string") runtimeName = "deno";
|
|
210
|
+
else if (typeof Bun !== "undefined" && typeof Bun.version === "string") runtimeName = "bun";
|
|
211
|
+
else runtimeName = "node";
|
|
212
|
+
runtimeInfo = `${process.platform}-${process.arch} ${runtimeName}-${process.version}`;
|
|
213
|
+
runtimeProcessArgs = process.argv;
|
|
214
|
+
} else if (typeof navigator === "undefined") runtimeInfo = `unknown`;
|
|
215
|
+
else runtimeInfo = `${navigator.platform} ${navigator.userAgent}`;
|
|
216
|
+
var Command = class {
|
|
217
|
+
rawName;
|
|
218
|
+
description;
|
|
219
|
+
config;
|
|
220
|
+
cli;
|
|
221
|
+
options;
|
|
222
|
+
aliasNames;
|
|
223
|
+
name;
|
|
224
|
+
args;
|
|
225
|
+
commandAction;
|
|
226
|
+
usageText;
|
|
227
|
+
versionNumber;
|
|
228
|
+
examples;
|
|
229
|
+
helpCallback;
|
|
230
|
+
globalCommand;
|
|
231
|
+
constructor(rawName, description, config = {}, cli2) {
|
|
232
|
+
this.rawName = rawName;
|
|
233
|
+
this.description = description;
|
|
234
|
+
this.config = config;
|
|
235
|
+
this.cli = cli2;
|
|
236
|
+
this.options = [];
|
|
237
|
+
this.aliasNames = [];
|
|
238
|
+
this.name = removeBrackets(rawName);
|
|
239
|
+
this.args = findAllBrackets(rawName);
|
|
240
|
+
this.examples = [];
|
|
241
|
+
}
|
|
242
|
+
usage(text) {
|
|
243
|
+
this.usageText = text;
|
|
244
|
+
return this;
|
|
245
|
+
}
|
|
246
|
+
allowUnknownOptions() {
|
|
247
|
+
this.config.allowUnknownOptions = true;
|
|
248
|
+
return this;
|
|
249
|
+
}
|
|
250
|
+
ignoreOptionDefaultValue() {
|
|
251
|
+
this.config.ignoreOptionDefaultValue = true;
|
|
252
|
+
return this;
|
|
253
|
+
}
|
|
254
|
+
version(version, customFlags = "-v, --version") {
|
|
255
|
+
this.versionNumber = version;
|
|
256
|
+
this.option(customFlags, "Display version number");
|
|
257
|
+
return this;
|
|
258
|
+
}
|
|
259
|
+
example(example) {
|
|
260
|
+
this.examples.push(example);
|
|
261
|
+
return this;
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Add a option for this command
|
|
265
|
+
* @param rawName Raw option name(s)
|
|
266
|
+
* @param description Option description
|
|
267
|
+
* @param config Option config
|
|
268
|
+
*/
|
|
269
|
+
option(rawName, description, config) {
|
|
270
|
+
const option = new Option(rawName, description, config);
|
|
271
|
+
this.options.push(option);
|
|
272
|
+
return this;
|
|
273
|
+
}
|
|
274
|
+
alias(name) {
|
|
275
|
+
this.aliasNames.push(name);
|
|
276
|
+
return this;
|
|
277
|
+
}
|
|
278
|
+
action(callback) {
|
|
279
|
+
this.commandAction = callback;
|
|
280
|
+
return this;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Check if a command name is matched by this command
|
|
284
|
+
* @param name Command name
|
|
285
|
+
*/
|
|
286
|
+
isMatched(name) {
|
|
287
|
+
return this.name === name || this.aliasNames.includes(name);
|
|
288
|
+
}
|
|
289
|
+
get isDefaultCommand() {
|
|
290
|
+
return this.name === "" || this.aliasNames.includes("!");
|
|
291
|
+
}
|
|
292
|
+
get isGlobalCommand() {
|
|
293
|
+
return this instanceof GlobalCommand;
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Check if an option is registered in this command
|
|
297
|
+
* @param name Option name
|
|
298
|
+
*/
|
|
299
|
+
hasOption(name) {
|
|
300
|
+
name = name.split(".")[0];
|
|
301
|
+
return this.options.find((option) => {
|
|
302
|
+
return option.names.includes(name);
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
outputHelp() {
|
|
306
|
+
const { name, commands } = this.cli;
|
|
307
|
+
const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand;
|
|
308
|
+
let sections = [{ body: `${name}${versionNumber ? `/${versionNumber}` : ""}` }];
|
|
309
|
+
sections.push({
|
|
310
|
+
title: "Usage",
|
|
311
|
+
body: ` $ ${name} ${this.usageText || this.rawName}`
|
|
312
|
+
});
|
|
313
|
+
if ((this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0) {
|
|
314
|
+
const longestCommandName = findLongest(commands.map((command) => command.rawName));
|
|
315
|
+
sections.push({
|
|
316
|
+
title: "Commands",
|
|
317
|
+
body: commands.map((command) => {
|
|
318
|
+
return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
|
|
319
|
+
}).join("\n")
|
|
320
|
+
}, {
|
|
321
|
+
title: `For more info, run any command with the \`--help\` flag`,
|
|
322
|
+
body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
|
|
326
|
+
if (!this.isGlobalCommand && !this.isDefaultCommand) options = options.filter((option) => option.name !== "version");
|
|
327
|
+
if (options.length > 0) {
|
|
328
|
+
const longestOptionName = findLongest(options.map((option) => option.rawName));
|
|
329
|
+
sections.push({
|
|
330
|
+
title: "Options",
|
|
331
|
+
body: options.map((option) => {
|
|
332
|
+
return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
|
|
333
|
+
}).join("\n")
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
if (this.examples.length > 0) sections.push({
|
|
337
|
+
title: "Examples",
|
|
338
|
+
body: this.examples.map((example) => {
|
|
339
|
+
if (typeof example === "function") return example(name);
|
|
340
|
+
return example;
|
|
341
|
+
}).join("\n")
|
|
342
|
+
});
|
|
343
|
+
if (helpCallback) sections = helpCallback(sections) || sections;
|
|
344
|
+
console.info(sections.map((section) => {
|
|
345
|
+
return section.title ? `${section.title}:
|
|
346
|
+
${section.body}` : section.body;
|
|
347
|
+
}).join("\n\n"));
|
|
348
|
+
}
|
|
349
|
+
outputVersion() {
|
|
350
|
+
const { name } = this.cli;
|
|
351
|
+
const { versionNumber } = this.cli.globalCommand;
|
|
352
|
+
if (versionNumber) console.info(`${name}/${versionNumber} ${runtimeInfo}`);
|
|
353
|
+
}
|
|
354
|
+
checkRequiredArgs() {
|
|
355
|
+
const minimalArgsCount = this.args.filter((arg) => arg.required).length;
|
|
356
|
+
if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``);
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Check if the parsed options contain any unknown options
|
|
360
|
+
*
|
|
361
|
+
* Exit and output error when true
|
|
362
|
+
*/
|
|
363
|
+
checkUnknownOptions() {
|
|
364
|
+
const { options, globalCommand } = this.cli;
|
|
365
|
+
if (!this.config.allowUnknownOptions) {
|
|
366
|
+
for (const name of Object.keys(options)) if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Check if the required string-type options exist
|
|
371
|
+
*/
|
|
372
|
+
checkOptionValue() {
|
|
373
|
+
const { options: parsedOptions, globalCommand } = this.cli;
|
|
374
|
+
const options = [...globalCommand.options, ...this.options];
|
|
375
|
+
for (const option of options) {
|
|
376
|
+
const value = parsedOptions[option.name.split(".")[0]];
|
|
377
|
+
if (option.required) {
|
|
378
|
+
const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
|
|
379
|
+
if (value === true || value === false && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Check if the number of args is more than expected
|
|
385
|
+
*/
|
|
386
|
+
checkUnusedArgs() {
|
|
387
|
+
const maximumArgsCount = this.args.some((arg) => arg.variadic) ? Infinity : this.args.length;
|
|
388
|
+
if (maximumArgsCount < this.cli.args.length) throw new CACError(`Unused args: ${this.cli.args.slice(maximumArgsCount).map((arg) => `\`${arg}\``).join(", ")}`);
|
|
389
|
+
}
|
|
390
|
+
};
|
|
391
|
+
var GlobalCommand = class extends Command {
|
|
392
|
+
constructor(cli2) {
|
|
393
|
+
super("@@global@@", "", {}, cli2);
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
var CAC = class extends EventTarget {
|
|
397
|
+
/** The program name to display in help and version message */
|
|
398
|
+
name;
|
|
399
|
+
commands;
|
|
400
|
+
globalCommand;
|
|
401
|
+
matchedCommand;
|
|
402
|
+
matchedCommandName;
|
|
403
|
+
/**
|
|
404
|
+
* Raw CLI arguments
|
|
405
|
+
*/
|
|
406
|
+
rawArgs;
|
|
407
|
+
/**
|
|
408
|
+
* Parsed CLI arguments
|
|
409
|
+
*/
|
|
410
|
+
args;
|
|
411
|
+
/**
|
|
412
|
+
* Parsed CLI options, camelCased
|
|
413
|
+
*/
|
|
414
|
+
options;
|
|
415
|
+
showHelpOnExit;
|
|
416
|
+
showVersionOnExit;
|
|
417
|
+
/**
|
|
418
|
+
* @param name The program name to display in help and version message
|
|
419
|
+
*/
|
|
420
|
+
constructor(name = "") {
|
|
421
|
+
super();
|
|
422
|
+
this.name = name;
|
|
423
|
+
this.commands = [];
|
|
424
|
+
this.rawArgs = [];
|
|
425
|
+
this.args = [];
|
|
426
|
+
this.options = {};
|
|
427
|
+
this.globalCommand = new GlobalCommand(this);
|
|
428
|
+
this.globalCommand.usage("<command> [options]");
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* Add a global usage text.
|
|
432
|
+
*
|
|
433
|
+
* This is not used by sub-commands.
|
|
434
|
+
*/
|
|
435
|
+
usage(text) {
|
|
436
|
+
this.globalCommand.usage(text);
|
|
437
|
+
return this;
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Add a sub-command
|
|
441
|
+
*/
|
|
442
|
+
command(rawName, description, config) {
|
|
443
|
+
const command = new Command(rawName, description || "", config, this);
|
|
444
|
+
command.globalCommand = this.globalCommand;
|
|
445
|
+
this.commands.push(command);
|
|
446
|
+
return command;
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* Add a global CLI option.
|
|
450
|
+
*
|
|
451
|
+
* Which is also applied to sub-commands.
|
|
452
|
+
*/
|
|
453
|
+
option(rawName, description, config) {
|
|
454
|
+
this.globalCommand.option(rawName, description, config);
|
|
455
|
+
return this;
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Show help message when `-h, --help` flags appear.
|
|
459
|
+
*
|
|
460
|
+
*/
|
|
461
|
+
help(callback) {
|
|
462
|
+
this.globalCommand.option("-h, --help", "Display this message");
|
|
463
|
+
this.globalCommand.helpCallback = callback;
|
|
464
|
+
this.showHelpOnExit = true;
|
|
465
|
+
return this;
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* Show version number when `-v, --version` flags appear.
|
|
469
|
+
*
|
|
470
|
+
*/
|
|
471
|
+
version(version, customFlags = "-v, --version") {
|
|
472
|
+
this.globalCommand.version(version, customFlags);
|
|
473
|
+
this.showVersionOnExit = true;
|
|
474
|
+
return this;
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Add a global example.
|
|
478
|
+
*
|
|
479
|
+
* This example added here will not be used by sub-commands.
|
|
480
|
+
*/
|
|
481
|
+
example(example) {
|
|
482
|
+
this.globalCommand.example(example);
|
|
483
|
+
return this;
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* Output the corresponding help message
|
|
487
|
+
* When a sub-command is matched, output the help message for the command
|
|
488
|
+
* Otherwise output the global one.
|
|
489
|
+
*
|
|
490
|
+
*/
|
|
491
|
+
outputHelp() {
|
|
492
|
+
if (this.matchedCommand) this.matchedCommand.outputHelp();
|
|
493
|
+
else this.globalCommand.outputHelp();
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Output the version number.
|
|
497
|
+
*
|
|
498
|
+
*/
|
|
499
|
+
outputVersion() {
|
|
500
|
+
this.globalCommand.outputVersion();
|
|
501
|
+
}
|
|
502
|
+
setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
|
|
503
|
+
this.args = args;
|
|
504
|
+
this.options = options;
|
|
505
|
+
if (matchedCommand) this.matchedCommand = matchedCommand;
|
|
506
|
+
if (matchedCommandName) this.matchedCommandName = matchedCommandName;
|
|
507
|
+
return this;
|
|
508
|
+
}
|
|
509
|
+
unsetMatchedCommand() {
|
|
510
|
+
this.matchedCommand = void 0;
|
|
511
|
+
this.matchedCommandName = void 0;
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Parse argv
|
|
515
|
+
*/
|
|
516
|
+
parse(argv, { run = true } = {}) {
|
|
517
|
+
if (!argv) {
|
|
518
|
+
if (!runtimeProcessArgs) throw new Error("No argv provided and runtime process argv is not available.");
|
|
519
|
+
argv = runtimeProcessArgs;
|
|
520
|
+
}
|
|
521
|
+
this.rawArgs = argv;
|
|
522
|
+
if (!this.name) this.name = argv[1] ? getFileName(argv[1]) : "cli";
|
|
523
|
+
let shouldParse = true;
|
|
524
|
+
for (const command of this.commands) {
|
|
525
|
+
const parsed = this.mri(argv.slice(2), command);
|
|
526
|
+
const commandName = parsed.args[0];
|
|
527
|
+
if (command.isMatched(commandName)) {
|
|
528
|
+
shouldParse = false;
|
|
529
|
+
const parsedInfo = {
|
|
530
|
+
...parsed,
|
|
531
|
+
args: parsed.args.slice(1)
|
|
532
|
+
};
|
|
533
|
+
this.setParsedInfo(parsedInfo, command, commandName);
|
|
534
|
+
this.dispatchEvent(new CustomEvent(`command:${commandName}`, { detail: command }));
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
if (shouldParse) {
|
|
538
|
+
for (const command of this.commands) if (command.isDefaultCommand) {
|
|
539
|
+
shouldParse = false;
|
|
540
|
+
const parsed = this.mri(argv.slice(2), command);
|
|
541
|
+
this.setParsedInfo(parsed, command);
|
|
542
|
+
this.dispatchEvent(new CustomEvent("command:!", { detail: command }));
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
if (shouldParse) {
|
|
546
|
+
const parsed = this.mri(argv.slice(2));
|
|
547
|
+
this.setParsedInfo(parsed);
|
|
548
|
+
}
|
|
549
|
+
if (this.options.help && this.showHelpOnExit) {
|
|
550
|
+
this.outputHelp();
|
|
551
|
+
run = false;
|
|
552
|
+
this.unsetMatchedCommand();
|
|
553
|
+
}
|
|
554
|
+
if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
|
|
555
|
+
this.outputVersion();
|
|
556
|
+
run = false;
|
|
557
|
+
this.unsetMatchedCommand();
|
|
558
|
+
}
|
|
559
|
+
const parsedArgv = {
|
|
560
|
+
args: this.args,
|
|
561
|
+
options: this.options
|
|
562
|
+
};
|
|
563
|
+
if (run) this.runMatchedCommand();
|
|
564
|
+
if (!this.matchedCommand && this.args[0]) this.dispatchEvent(new CustomEvent("command:*", { detail: this.args[0] }));
|
|
565
|
+
return parsedArgv;
|
|
566
|
+
}
|
|
567
|
+
mri(argv, command) {
|
|
568
|
+
const cliOptions = [...this.globalCommand.options, ...command ? command.options : []];
|
|
569
|
+
const mriOptions = getMriOptions(cliOptions);
|
|
570
|
+
let argsAfterDoubleDashes = [];
|
|
571
|
+
const doubleDashesIndex = argv.indexOf("--");
|
|
572
|
+
if (doubleDashesIndex !== -1) {
|
|
573
|
+
argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
|
|
574
|
+
argv = argv.slice(0, doubleDashesIndex);
|
|
575
|
+
}
|
|
576
|
+
let parsed = lib_default(argv, mriOptions);
|
|
577
|
+
parsed = Object.keys(parsed).reduce((res, name) => {
|
|
578
|
+
return {
|
|
579
|
+
...res,
|
|
580
|
+
[camelcaseOptionName(name)]: parsed[name]
|
|
581
|
+
};
|
|
582
|
+
}, { _: [] });
|
|
583
|
+
const args = parsed._;
|
|
584
|
+
const options = { "--": argsAfterDoubleDashes };
|
|
585
|
+
const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
|
|
586
|
+
const transforms = /* @__PURE__ */ Object.create(null);
|
|
587
|
+
for (const cliOption of cliOptions) {
|
|
588
|
+
if (!ignoreDefault && cliOption.config.default !== void 0) for (const name of cliOption.names) options[name] = cliOption.config.default;
|
|
589
|
+
if (Array.isArray(cliOption.config.type) && transforms[cliOption.name] === void 0) {
|
|
590
|
+
transforms[cliOption.name] = /* @__PURE__ */ Object.create(null);
|
|
591
|
+
transforms[cliOption.name].shouldTransform = true;
|
|
592
|
+
transforms[cliOption.name].transformFunction = cliOption.config.type[0];
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
for (const key of Object.keys(parsed)) if (key !== "_") {
|
|
596
|
+
setDotProp(options, key.split("."), parsed[key]);
|
|
597
|
+
setByType(options, transforms);
|
|
598
|
+
}
|
|
599
|
+
return {
|
|
600
|
+
args,
|
|
601
|
+
options
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
runMatchedCommand() {
|
|
605
|
+
const { args, options, matchedCommand: command } = this;
|
|
606
|
+
if (!command || !command.commandAction) return;
|
|
607
|
+
command.checkUnknownOptions();
|
|
608
|
+
command.checkOptionValue();
|
|
609
|
+
command.checkRequiredArgs();
|
|
610
|
+
command.checkUnusedArgs();
|
|
611
|
+
const actionArgs = [];
|
|
612
|
+
command.args.forEach((arg, index) => {
|
|
613
|
+
if (arg.variadic) actionArgs.push(args.slice(index));
|
|
614
|
+
else actionArgs.push(args[index]);
|
|
615
|
+
});
|
|
616
|
+
actionArgs.push(options);
|
|
617
|
+
return command.commandAction.apply(this, actionArgs);
|
|
618
|
+
}
|
|
619
|
+
};
|
|
620
|
+
var cac = (name = "") => new CAC(name);
|
|
621
|
+
|
|
622
|
+
// src/command/add.ts
|
|
623
|
+
import { existsSync as existsSync2 } from "fs";
|
|
624
|
+
import { mkdir, writeFile as writeFile2 } from "fs/promises";
|
|
625
|
+
import { join as join2 } from "path";
|
|
626
|
+
|
|
627
|
+
// src/config/defaults.ts
|
|
628
|
+
import process2 from "process";
|
|
629
|
+
var SOURCE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs", ".cjs"];
|
|
630
|
+
var ESM_IMPORT_RE = /\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]|\bexport\s+(?:type\s+)?(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]/g;
|
|
631
|
+
var CJS_IMPORT_RE = /\brequire\s*\(['"]([^'"]+)['"]\)/g;
|
|
632
|
+
var REACT_EXTENSIONS = /* @__PURE__ */ new Set([".tsx", ".jsx"]);
|
|
633
|
+
var VUE_EXTENSIONS = /* @__PURE__ */ new Set([".vue"]);
|
|
634
|
+
var DEFAULT_SOURCE_DIR = "injections";
|
|
635
|
+
var DEFAULT_MANIFEST_FILE_NAME = "manifest";
|
|
636
|
+
var DEFAULT_SOURCE_CONFIG = {
|
|
637
|
+
dir: DEFAULT_SOURCE_DIR,
|
|
638
|
+
// '*' matches any single path segment (bare directory name).
|
|
639
|
+
// '**/*' would require a '/' and never match top-level folder names via picomatch.
|
|
640
|
+
include: ["*"],
|
|
641
|
+
exclude: [],
|
|
642
|
+
manifest: DEFAULT_MANIFEST_FILE_NAME
|
|
643
|
+
};
|
|
644
|
+
var DEFAULT_INJECTOR_CONFIG = {
|
|
645
|
+
alive: false,
|
|
646
|
+
scope: "local",
|
|
647
|
+
timeout: 5e3,
|
|
648
|
+
hooks: {}
|
|
649
|
+
};
|
|
650
|
+
var DEFAULT_MONKEY_SERVER_CONFIG = {
|
|
651
|
+
open: process2.platform === "win32" || process2.platform === "darwin",
|
|
652
|
+
prefix: "server:"
|
|
653
|
+
};
|
|
654
|
+
|
|
655
|
+
// src/error/error.ts
|
|
656
|
+
import { relative } from "path";
|
|
657
|
+
import process3 from "process";
|
|
658
|
+
import { ErrorCode, MakooError } from "@makoojs/core";
|
|
659
|
+
var ModuleAlreadyExistsError = class extends MakooError {
|
|
660
|
+
constructor(message, code = ErrorCode.CLI_MODULE_ALREADY_EXISTS, cause) {
|
|
661
|
+
super(message, void 0, code, cause);
|
|
662
|
+
this.name = "ModuleAlreadyExistsError";
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
var LoadViteMakooConfigError = class extends MakooError {
|
|
666
|
+
constructor(message, code, cause) {
|
|
667
|
+
super(message, void 0, code, cause);
|
|
668
|
+
this.name = "LoadViteMakooConfigError";
|
|
669
|
+
}
|
|
670
|
+
};
|
|
671
|
+
var RuntimeSetupNotFoundError = class extends MakooError {
|
|
672
|
+
constructor(file, code = ErrorCode.CLI_RUNTIME_SETUP_NOT_FOUND, cause) {
|
|
673
|
+
super(
|
|
674
|
+
`Runtime setup file not found at ${file}`,
|
|
675
|
+
[{ path: "runtime.setup", message: file }],
|
|
676
|
+
code,
|
|
677
|
+
cause
|
|
678
|
+
);
|
|
679
|
+
this.name = "RuntimeSetupNotFoundError";
|
|
680
|
+
}
|
|
681
|
+
};
|
|
682
|
+
var ManifestValidationError = class extends MakooError {
|
|
683
|
+
constructor(file, zodIssues, code = ErrorCode.CLI_MANIFEST_VALIDATION_FAIL, cause) {
|
|
684
|
+
const issues = zodIssues.map(toMakooIssue);
|
|
685
|
+
const rel = relative(process3.cwd(), file);
|
|
686
|
+
super(`Invalid manifest at ${rel}`, issues, code, cause);
|
|
687
|
+
this.name = "ManifestValidationError";
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
var UnknownFrameworkError = class extends MakooError {
|
|
691
|
+
constructor(componentPath, code = ErrorCode.CLI_UNKNOWN_FRAMEWORK, cause) {
|
|
692
|
+
super(
|
|
693
|
+
`Cannot infer framework from "${componentPath}". Set "framework" explicitly ("Vue" or "React") in the module manifest.`,
|
|
694
|
+
[{ path: "framework", message: `cannot infer from "${componentPath}"` }],
|
|
695
|
+
code,
|
|
696
|
+
cause
|
|
697
|
+
);
|
|
698
|
+
this.name = "UnknownFrameworkError";
|
|
699
|
+
}
|
|
700
|
+
};
|
|
701
|
+
var ComponentNotFoundError = class extends MakooError {
|
|
702
|
+
constructor(injectionName, code = ErrorCode.CLI_COMPONENT_NOT_FOUND, cause) {
|
|
703
|
+
super(
|
|
704
|
+
`Missing component path for injection "${injectionName}"`,
|
|
705
|
+
[{ path: "component", message: "could not resolve component path" }],
|
|
706
|
+
code,
|
|
707
|
+
cause
|
|
708
|
+
);
|
|
709
|
+
this.name = "ComponentNotFoundError";
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
var UnsupportedFrameworkGenerationError = class extends MakooError {
|
|
713
|
+
constructor(ext, code = ErrorCode.CLI_UNSUPPORTED_FRAMEWORK, cause) {
|
|
714
|
+
super(`Unsupported framework for template generation: ${ext}`, void 0, code, cause);
|
|
715
|
+
this.name = "UnsupportedFrameworkError";
|
|
716
|
+
}
|
|
717
|
+
};
|
|
718
|
+
var SourceDirNotFoundError = class extends MakooError {
|
|
719
|
+
constructor(dir, code = ErrorCode.CLI_SOURCE_DIR_NOT_FOUND, cause) {
|
|
720
|
+
super(`Source directory not found at ${dir}`, void 0, code, cause);
|
|
721
|
+
this.name = "SourceDirNotFoundError";
|
|
722
|
+
}
|
|
723
|
+
};
|
|
724
|
+
var ManifestNotFoundError = class extends MakooError {
|
|
725
|
+
constructor(dir, code = ErrorCode.CLI_MANIFEST_NOT_FOUND, cause) {
|
|
726
|
+
super(`No manifest found in source directory at ${dir}`, void 0, code, cause);
|
|
727
|
+
this.name = "ManifestNotFoundError";
|
|
728
|
+
}
|
|
729
|
+
};
|
|
730
|
+
var ManifestLoadError = class extends MakooError {
|
|
731
|
+
constructor(path5, code = ErrorCode.CLI_MANIFEST_LOAD_FAIL, cause) {
|
|
732
|
+
super(
|
|
733
|
+
`Failed to load manifest at ${path5}`,
|
|
734
|
+
[{ path: "(load)", message: cause instanceof Error ? cause.message : String(cause) }],
|
|
735
|
+
code,
|
|
736
|
+
cause
|
|
737
|
+
);
|
|
738
|
+
this.name = "ManifestLoadError";
|
|
739
|
+
}
|
|
740
|
+
};
|
|
741
|
+
var ModuleManifestLoadError = class extends MakooError {
|
|
742
|
+
constructor(path5, code = ErrorCode.CLI_MODULE_MANIFEST_LOAD_FAIL, cause) {
|
|
743
|
+
super(
|
|
744
|
+
`Failed to load module manifest at ${path5}`,
|
|
745
|
+
[{ path: "(load)", message: cause instanceof Error ? cause.message : String(cause) }],
|
|
746
|
+
code,
|
|
747
|
+
cause
|
|
748
|
+
);
|
|
749
|
+
this.name = "ModuleManifestLoadError";
|
|
750
|
+
}
|
|
751
|
+
};
|
|
752
|
+
var NoEnabledInjectionsError = class extends MakooError {
|
|
753
|
+
constructor(code = ErrorCode.CLI_NO_ENABLED_INJECTIONS, cause) {
|
|
754
|
+
super(
|
|
755
|
+
"No enabled injections \u2014 all injections are disabled or filtered out",
|
|
756
|
+
void 0,
|
|
757
|
+
code,
|
|
758
|
+
cause
|
|
759
|
+
);
|
|
760
|
+
this.name = "NoEnabledInjectionsError";
|
|
761
|
+
}
|
|
762
|
+
};
|
|
763
|
+
function formatZodPath(path5) {
|
|
764
|
+
if (path5.length === 0) return "(root)";
|
|
765
|
+
return path5.filter((p) => typeof p !== "symbol").map((p) => typeof p === "number" ? `[${p}]` : p).join(".");
|
|
766
|
+
}
|
|
767
|
+
function formatZodMessage(issue) {
|
|
768
|
+
if (issue.code === "invalid_type" && issue.message.endsWith("received undefined")) {
|
|
769
|
+
return "is required";
|
|
770
|
+
}
|
|
771
|
+
return issue.message;
|
|
772
|
+
}
|
|
773
|
+
function toMakooIssue(issue) {
|
|
774
|
+
return {
|
|
775
|
+
path: formatZodPath(issue.path),
|
|
776
|
+
message: formatZodMessage(issue)
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
// src/command/_util.ts
|
|
781
|
+
import { existsSync } from "fs";
|
|
782
|
+
import { readdir, readFile, writeFile } from "fs/promises";
|
|
783
|
+
import { dirname, join } from "path";
|
|
784
|
+
import { fileURLToPath } from "url";
|
|
785
|
+
import { ErrorCode as ErrorCode2 } from "@makoojs/core";
|
|
786
|
+
import { createJiti } from "jiti";
|
|
787
|
+
import { loadConfigFromFile } from "vite";
|
|
788
|
+
var ansi = {
|
|
789
|
+
reset: "\x1B[0m",
|
|
790
|
+
bold: "\x1B[1m",
|
|
791
|
+
cyan: "\x1B[36m",
|
|
792
|
+
green: "\x1B[32m",
|
|
793
|
+
dim: "\x1B[2m"
|
|
794
|
+
};
|
|
795
|
+
var colorize = (value, ...codes) => `${codes.join("")}${value}${ansi.reset}`;
|
|
796
|
+
async function loadCliVersion(cliVersionCache2) {
|
|
797
|
+
if (cliVersionCache2) {
|
|
798
|
+
return cliVersionCache2;
|
|
799
|
+
}
|
|
800
|
+
let currentDir = dirname(fileURLToPath(import.meta.url));
|
|
801
|
+
while (true) {
|
|
802
|
+
const packagePath = join(currentDir, "package.json");
|
|
803
|
+
try {
|
|
804
|
+
const content = await readFile(packagePath, "utf-8");
|
|
805
|
+
const packageJson = JSON.parse(content);
|
|
806
|
+
if (packageJson.name === "@makoojs/cli" && packageJson.version) {
|
|
807
|
+
cliVersionCache2 = packageJson.version;
|
|
808
|
+
return cliVersionCache2;
|
|
809
|
+
}
|
|
810
|
+
} catch {
|
|
811
|
+
}
|
|
812
|
+
const parentDir = dirname(currentDir);
|
|
813
|
+
if (parentDir === currentDir) {
|
|
814
|
+
break;
|
|
815
|
+
}
|
|
816
|
+
currentDir = parentDir;
|
|
817
|
+
}
|
|
818
|
+
return "0.0.0";
|
|
819
|
+
}
|
|
820
|
+
async function loadMakooConfig() {
|
|
821
|
+
const root = process.cwd();
|
|
822
|
+
const result = await loadConfigFromFile(
|
|
823
|
+
{ command: "build", mode: "production" },
|
|
824
|
+
void 0,
|
|
825
|
+
root
|
|
826
|
+
);
|
|
827
|
+
if (!result) {
|
|
828
|
+
throw new LoadViteMakooConfigError(
|
|
829
|
+
`No vite config file found in "${root}". Make sure a vite.config.ts (or .js/.mts) exists.`,
|
|
830
|
+
ErrorCode2.CLI_VITE_CONFIG_NOT_FOUND
|
|
831
|
+
);
|
|
832
|
+
}
|
|
833
|
+
const plugins = (result.config.plugins ?? []).flat().filter((p) => p != null && p !== false);
|
|
834
|
+
const makooPlugin = plugins.find(
|
|
835
|
+
(p) => p.name === "vite-plugin-makoo"
|
|
836
|
+
);
|
|
837
|
+
if (!makooPlugin) {
|
|
838
|
+
throw new LoadViteMakooConfigError(
|
|
839
|
+
`makoo plugin not found in vite config at "${result.path}". Make sure makoo() is included in your plugins array.`,
|
|
840
|
+
ErrorCode2.CLI_PLUGIN_NOT_FOUND
|
|
841
|
+
);
|
|
842
|
+
}
|
|
843
|
+
return makooPlugin.__makoo;
|
|
844
|
+
}
|
|
845
|
+
function getExtName(framework) {
|
|
846
|
+
const lowerFramework = framework.toLowerCase();
|
|
847
|
+
if (lowerFramework === "vue") {
|
|
848
|
+
return ".vue";
|
|
849
|
+
}
|
|
850
|
+
if (lowerFramework === "react") {
|
|
851
|
+
if (existsSync(join(process.cwd(), "tsconfig.json"))) {
|
|
852
|
+
return ".tsx";
|
|
853
|
+
}
|
|
854
|
+
return ".jsx";
|
|
855
|
+
}
|
|
856
|
+
return null;
|
|
857
|
+
}
|
|
858
|
+
async function updateManifest(moduleName, updateData) {
|
|
859
|
+
const sourcePath = join(process.cwd(), DEFAULT_SOURCE_DIR);
|
|
860
|
+
const sourceFiles = await readdir(sourcePath);
|
|
861
|
+
let manifestName = null;
|
|
862
|
+
for (const file of sourceFiles) {
|
|
863
|
+
if ("manifest" === file.split(".")[0]) {
|
|
864
|
+
manifestName = file;
|
|
865
|
+
break;
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
const merged = { injections: { [moduleName]: updateData } };
|
|
869
|
+
if (!manifestName) {
|
|
870
|
+
const newManifestPath = join(sourcePath, "manifest.ts");
|
|
871
|
+
await writeFile(
|
|
872
|
+
newManifestPath,
|
|
873
|
+
`import { defineInjections } from "@makoojs/cli";
|
|
874
|
+
export default defineInjections(${JSON.stringify(merged, null, 2)})
|
|
875
|
+
`,
|
|
876
|
+
"utf-8"
|
|
877
|
+
);
|
|
878
|
+
return;
|
|
879
|
+
}
|
|
880
|
+
const manifestPath = join(sourcePath, manifestName);
|
|
881
|
+
const manifestContent = await readFile(manifestPath, "utf-8");
|
|
882
|
+
const jiti = createJiti(sourcePath, { moduleCache: false });
|
|
883
|
+
const existing = await jiti.import(manifestPath, { default: true });
|
|
884
|
+
const injections = existing.injections;
|
|
885
|
+
let updatedInjections;
|
|
886
|
+
if (Array.isArray(injections)) {
|
|
887
|
+
updatedInjections = [...injections, { name: moduleName, ...updateData }];
|
|
888
|
+
} else if (injections && typeof injections === "object") {
|
|
889
|
+
updatedInjections = {
|
|
890
|
+
...injections,
|
|
891
|
+
[moduleName]: updateData
|
|
892
|
+
};
|
|
893
|
+
} else {
|
|
894
|
+
updatedInjections = { [moduleName]: updateData };
|
|
895
|
+
}
|
|
896
|
+
Object.assign(merged, { ...existing, injections: updatedInjections });
|
|
897
|
+
const updated = manifestContent.replace(
|
|
898
|
+
/defineInjections\s*\(\s*([\s\S]*?)\s*\)\s*;?\s*$/,
|
|
899
|
+
`defineInjections(${JSON.stringify(merged, null, 2)})`
|
|
900
|
+
);
|
|
901
|
+
await writeFile(manifestPath, updated, "utf-8");
|
|
902
|
+
}
|
|
903
|
+
function moduleTemplate(framework) {
|
|
904
|
+
switch (framework) {
|
|
905
|
+
case "Vue":
|
|
906
|
+
return vueTemplate();
|
|
907
|
+
case "React":
|
|
908
|
+
return reactTemplate();
|
|
909
|
+
default:
|
|
910
|
+
throw new UnsupportedFrameworkGenerationError(framework);
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
function vueTemplate() {
|
|
914
|
+
return `<template>
|
|
915
|
+
<div>hello-Vue !!</div>
|
|
916
|
+
</template>
|
|
917
|
+
`;
|
|
918
|
+
}
|
|
919
|
+
function reactTemplate() {
|
|
920
|
+
return `export default function App() {
|
|
921
|
+
return <div>hello-React !!</div>;
|
|
922
|
+
}
|
|
923
|
+
`;
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
// src/command/add.ts
|
|
927
|
+
async function addCommand(moduleName, framework) {
|
|
928
|
+
const cwd = process.cwd();
|
|
929
|
+
const sourceDir = join2(cwd, DEFAULT_SOURCE_DIR);
|
|
930
|
+
const moduleDir = join2(sourceDir, moduleName);
|
|
931
|
+
const extName = getExtName(framework);
|
|
932
|
+
if (!extName) throw new UnsupportedFrameworkGenerationError(framework);
|
|
933
|
+
const appPath = join2(moduleDir, `App${extName}`);
|
|
934
|
+
if (existsSync2(moduleDir)) {
|
|
935
|
+
throw new ModuleAlreadyExistsError(`Module "${moduleName}" already exists`);
|
|
936
|
+
}
|
|
937
|
+
await mkdir(moduleDir, { recursive: true });
|
|
938
|
+
await writeFile2(appPath, moduleTemplate(framework));
|
|
939
|
+
await updateManifest(moduleName, {
|
|
940
|
+
injectAt: "body",
|
|
941
|
+
component: `./${moduleName}/app${extName}`
|
|
942
|
+
});
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
// src/command/build.ts
|
|
946
|
+
import { build } from "vite";
|
|
947
|
+
async function buildCommand() {
|
|
948
|
+
await build();
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
// src/command/dev.ts
|
|
952
|
+
import { createServer } from "vite";
|
|
953
|
+
var cliVersionCache = null;
|
|
954
|
+
async function printDevBanner(server) {
|
|
955
|
+
const cliVersion = await loadCliVersion(cliVersionCache);
|
|
956
|
+
const title = `Makoo v${cliVersion}`;
|
|
957
|
+
const urls = server.resolvedUrls;
|
|
958
|
+
const localUrl = urls?.local[0];
|
|
959
|
+
const networkUrl = urls?.network[0];
|
|
960
|
+
console.log(`
|
|
961
|
+
${colorize(title, ansi.bold, ansi.cyan)}
|
|
962
|
+
`);
|
|
963
|
+
console.log(
|
|
964
|
+
` ${colorize("\u279C", ansi.green)} ${colorize("Local:", ansi.bold)} ${colorize(localUrl ?? "unavailable", ansi.cyan)}`
|
|
965
|
+
);
|
|
966
|
+
console.log(
|
|
967
|
+
` ${colorize("\u279C", ansi.green)} ${colorize("Network:", ansi.bold)} ${networkUrl ?? colorize("use --host to expose", ansi.dim)}`
|
|
968
|
+
);
|
|
969
|
+
}
|
|
970
|
+
async function devCommand() {
|
|
971
|
+
const server = await createServer();
|
|
972
|
+
await server.listen();
|
|
973
|
+
await printDevBanner(server);
|
|
974
|
+
server.bindCLIShortcuts({ print: true });
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
// src/scanner/scanner.ts
|
|
978
|
+
import { existsSync as existsSync5, readdirSync as readdirSync2 } from "fs";
|
|
979
|
+
import path4 from "path";
|
|
980
|
+
import picomatch from "picomatch";
|
|
981
|
+
|
|
982
|
+
// src/config/resolve.ts
|
|
983
|
+
import {
|
|
984
|
+
basename,
|
|
985
|
+
dirname as dirname2,
|
|
986
|
+
extname,
|
|
987
|
+
isAbsolute,
|
|
988
|
+
normalize,
|
|
989
|
+
resolve as resolvePath
|
|
990
|
+
} from "path";
|
|
991
|
+
import process4 from "process";
|
|
992
|
+
|
|
993
|
+
// src/config/validation.ts
|
|
994
|
+
import { z } from "zod";
|
|
995
|
+
var AppConfigSchema = z.object({
|
|
996
|
+
name: z.string().min(1, "app.name is required"),
|
|
997
|
+
version: z.string().min(1, "app.version is required"),
|
|
998
|
+
description: z.string().optional()
|
|
999
|
+
});
|
|
1000
|
+
var MonkeyConfigSchema = z.object({
|
|
1001
|
+
server: z.object({}).passthrough().optional()
|
|
1002
|
+
}).passthrough().superRefine((value, context) => {
|
|
1003
|
+
if ("clientAlias" in value) {
|
|
1004
|
+
context.addIssue({
|
|
1005
|
+
code: z.ZodIssueCode.custom,
|
|
1006
|
+
path: ["clientAlias"],
|
|
1007
|
+
message: "monkey.clientAlias is not supported by makoo"
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
if (value.server && typeof value.server === "object" && "mountGmApi" in value.server) {
|
|
1011
|
+
context.addIssue({
|
|
1012
|
+
code: z.ZodIssueCode.custom,
|
|
1013
|
+
path: ["server", "mountGmApi"],
|
|
1014
|
+
message: "monkey.server.mountGmApi is not supported by makoo"
|
|
1015
|
+
});
|
|
1016
|
+
}
|
|
1017
|
+
});
|
|
1018
|
+
var CliConfigSchema = z.object({
|
|
1019
|
+
app: AppConfigSchema,
|
|
1020
|
+
monkey: MonkeyConfigSchema.optional(),
|
|
1021
|
+
source: z.object({}).passthrough().optional(),
|
|
1022
|
+
injector: z.object({}).passthrough().optional(),
|
|
1023
|
+
runtime: z.object({}).passthrough().optional()
|
|
1024
|
+
});
|
|
1025
|
+
|
|
1026
|
+
// src/config/resolve.ts
|
|
1027
|
+
var toStringArray = (value, fallback) => {
|
|
1028
|
+
if (Array.isArray(value)) {
|
|
1029
|
+
return value;
|
|
1030
|
+
}
|
|
1031
|
+
if (typeof value === "undefined") {
|
|
1032
|
+
return fallback;
|
|
1033
|
+
}
|
|
1034
|
+
return [value];
|
|
1035
|
+
};
|
|
1036
|
+
var resolveFileSystemPath = (root, value) => {
|
|
1037
|
+
if (isAbsolute(value)) {
|
|
1038
|
+
return normalize(value);
|
|
1039
|
+
}
|
|
1040
|
+
return normalize(resolvePath(root, value));
|
|
1041
|
+
};
|
|
1042
|
+
var resolveProjectRoot = (root) => {
|
|
1043
|
+
return normalize(root ? resolvePath(root) : process4.cwd());
|
|
1044
|
+
};
|
|
1045
|
+
var inferFrameworkFromPath = (componentPath) => {
|
|
1046
|
+
const extension = extname(componentPath).toLowerCase();
|
|
1047
|
+
if (REACT_EXTENSIONS.has(extension)) {
|
|
1048
|
+
return "React";
|
|
1049
|
+
}
|
|
1050
|
+
if (VUE_EXTENSIONS.has(extension)) {
|
|
1051
|
+
return "Vue";
|
|
1052
|
+
}
|
|
1053
|
+
throw new UnknownFrameworkError(componentPath);
|
|
1054
|
+
};
|
|
1055
|
+
var resolveFramework = (framework, componentPath) => {
|
|
1056
|
+
if (framework && framework !== "auto") {
|
|
1057
|
+
return framework;
|
|
1058
|
+
}
|
|
1059
|
+
return inferFrameworkFromPath(componentPath);
|
|
1060
|
+
};
|
|
1061
|
+
var resolveMatchConfig = (match) => {
|
|
1062
|
+
if (!match) {
|
|
1063
|
+
return void 0;
|
|
1064
|
+
}
|
|
1065
|
+
if (Array.isArray(match)) {
|
|
1066
|
+
return {
|
|
1067
|
+
include: match
|
|
1068
|
+
};
|
|
1069
|
+
}
|
|
1070
|
+
return {
|
|
1071
|
+
include: match.include,
|
|
1072
|
+
exclude: match.exclude
|
|
1073
|
+
};
|
|
1074
|
+
};
|
|
1075
|
+
var deriveInjectionModuleId = (config, moduleDir, componentPath, fallbackName, index) => {
|
|
1076
|
+
if (config.name) {
|
|
1077
|
+
return config.name;
|
|
1078
|
+
}
|
|
1079
|
+
if (fallbackName) {
|
|
1080
|
+
return fallbackName;
|
|
1081
|
+
}
|
|
1082
|
+
const moduleName = basename(moduleDir);
|
|
1083
|
+
if (moduleName) {
|
|
1084
|
+
return moduleName;
|
|
1085
|
+
}
|
|
1086
|
+
const componentName = basename(componentPath, extname(componentPath));
|
|
1087
|
+
if (componentName) {
|
|
1088
|
+
return componentName;
|
|
1089
|
+
}
|
|
1090
|
+
return `injection-${typeof index === "number" ? index + 1 : 1}`;
|
|
1091
|
+
};
|
|
1092
|
+
var normalizeInjectionManifest = (injections) => {
|
|
1093
|
+
const items = injections?.injections;
|
|
1094
|
+
if (!items) {
|
|
1095
|
+
return [];
|
|
1096
|
+
}
|
|
1097
|
+
if (Array.isArray(items)) {
|
|
1098
|
+
return items;
|
|
1099
|
+
}
|
|
1100
|
+
return Object.entries(items).map(([name, config]) => ({
|
|
1101
|
+
name,
|
|
1102
|
+
...config
|
|
1103
|
+
}));
|
|
1104
|
+
};
|
|
1105
|
+
var resolveSourceConfig = (config, root) => {
|
|
1106
|
+
return {
|
|
1107
|
+
dir: resolveFileSystemPath(root, DEFAULT_SOURCE_CONFIG.dir),
|
|
1108
|
+
include: toStringArray(config?.include, DEFAULT_SOURCE_CONFIG.include),
|
|
1109
|
+
exclude: toStringArray(config?.exclude, DEFAULT_SOURCE_CONFIG.exclude),
|
|
1110
|
+
manifest: DEFAULT_MANIFEST_FILE_NAME
|
|
1111
|
+
};
|
|
1112
|
+
};
|
|
1113
|
+
var resolveInjectorConfig = (config) => {
|
|
1114
|
+
return {
|
|
1115
|
+
alive: config?.alive ?? DEFAULT_INJECTOR_CONFIG.alive,
|
|
1116
|
+
scope: config?.scope ?? DEFAULT_INJECTOR_CONFIG.scope,
|
|
1117
|
+
timeout: config?.timeout ?? DEFAULT_INJECTOR_CONFIG.timeout,
|
|
1118
|
+
hooks: config?.hooks
|
|
1119
|
+
};
|
|
1120
|
+
};
|
|
1121
|
+
var resolveInjection = (config, options) => {
|
|
1122
|
+
const root = resolveProjectRoot(options.root);
|
|
1123
|
+
const source = options.source ?? resolveSourceConfig(void 0, root);
|
|
1124
|
+
const injector = options.injector ?? resolveInjectorConfig(void 0);
|
|
1125
|
+
const componentBaseDir = options.moduleDir ? resolveFileSystemPath(root, options.moduleDir) : source.dir;
|
|
1126
|
+
if (!options.componentPath) {
|
|
1127
|
+
throw new ComponentNotFoundError(config.name ?? config.injectAt);
|
|
1128
|
+
}
|
|
1129
|
+
const componentPath = resolveFileSystemPath(root, options.componentPath);
|
|
1130
|
+
const moduleDir = options.moduleDir ? componentBaseDir : componentPath ? dirname2(componentPath) : source.dir;
|
|
1131
|
+
const {
|
|
1132
|
+
component,
|
|
1133
|
+
framework: _framework,
|
|
1134
|
+
enabled: _enabled,
|
|
1135
|
+
alive: _alive,
|
|
1136
|
+
scope: _scope,
|
|
1137
|
+
timeout: _timeout,
|
|
1138
|
+
...rest
|
|
1139
|
+
} = config;
|
|
1140
|
+
void component;
|
|
1141
|
+
void _framework;
|
|
1142
|
+
void _enabled;
|
|
1143
|
+
void _alive;
|
|
1144
|
+
void _scope;
|
|
1145
|
+
void _timeout;
|
|
1146
|
+
const moduleId = options.moduleId ?? deriveInjectionModuleId(
|
|
1147
|
+
config,
|
|
1148
|
+
moduleDir,
|
|
1149
|
+
componentPath,
|
|
1150
|
+
options.fallbackName,
|
|
1151
|
+
options.index
|
|
1152
|
+
);
|
|
1153
|
+
const framework = resolveFramework(config.framework, componentPath);
|
|
1154
|
+
const overridePath = options.overridePath ? resolveFileSystemPath(root, options.overridePath) : void 0;
|
|
1155
|
+
return {
|
|
1156
|
+
...rest,
|
|
1157
|
+
moduleId,
|
|
1158
|
+
componentPath,
|
|
1159
|
+
framework,
|
|
1160
|
+
moduleDir,
|
|
1161
|
+
overridePath,
|
|
1162
|
+
enabled: config.enabled ?? true,
|
|
1163
|
+
alive: config.alive ?? injector.alive,
|
|
1164
|
+
scope: config.scope ?? injector.scope,
|
|
1165
|
+
timeout: config.timeout ?? injector.timeout,
|
|
1166
|
+
match: resolveMatchConfig(config.match)
|
|
1167
|
+
};
|
|
1168
|
+
};
|
|
1169
|
+
var resolveInjections = (injections, options) => {
|
|
1170
|
+
const root = resolveProjectRoot(options.root);
|
|
1171
|
+
const normalizedInjections = normalizeInjectionManifest(injections);
|
|
1172
|
+
return normalizedInjections.map(
|
|
1173
|
+
(injection, index) => resolveInjection(injection, {
|
|
1174
|
+
root,
|
|
1175
|
+
source: options.source,
|
|
1176
|
+
injector: options.injector,
|
|
1177
|
+
componentPath: resolvePath(options.source.dir, injection.component),
|
|
1178
|
+
// `index` was a name of element
|
|
1179
|
+
index
|
|
1180
|
+
})
|
|
1181
|
+
);
|
|
1182
|
+
};
|
|
1183
|
+
|
|
1184
|
+
// src/scanner/collectDependenics.ts
|
|
1185
|
+
import { existsSync as existsSync3, readFileSync, statSync } from "fs";
|
|
1186
|
+
import path from "path";
|
|
1187
|
+
function isInsideRoot(file, root) {
|
|
1188
|
+
const rel = path.relative(root, file);
|
|
1189
|
+
return rel === "" || !rel.startsWith("..") && !path.isAbsolute(rel);
|
|
1190
|
+
}
|
|
1191
|
+
function isNodeModulesFile(file) {
|
|
1192
|
+
return file.split(path.sep).includes("node_modules");
|
|
1193
|
+
}
|
|
1194
|
+
function isRelativeSpecifier(specifier) {
|
|
1195
|
+
return specifier.startsWith("./") || specifier.startsWith("../");
|
|
1196
|
+
}
|
|
1197
|
+
function extractLocalSpecifiers(code) {
|
|
1198
|
+
const specifiers = [];
|
|
1199
|
+
for (const match of code.matchAll(ESM_IMPORT_RE)) {
|
|
1200
|
+
const specifier = match[1] ?? match[2];
|
|
1201
|
+
if (!specifier) continue;
|
|
1202
|
+
if (!isRelativeSpecifier(specifier)) continue;
|
|
1203
|
+
specifiers.push(specifier);
|
|
1204
|
+
}
|
|
1205
|
+
for (const match of code.matchAll(CJS_IMPORT_RE)) {
|
|
1206
|
+
const specifier = match[1];
|
|
1207
|
+
if (!specifier) continue;
|
|
1208
|
+
if (!isRelativeSpecifier(specifier)) continue;
|
|
1209
|
+
specifiers.push(specifier);
|
|
1210
|
+
}
|
|
1211
|
+
return specifiers;
|
|
1212
|
+
}
|
|
1213
|
+
function tryFile(filePath) {
|
|
1214
|
+
if (!existsSync3(filePath)) return null;
|
|
1215
|
+
if (!statSync(filePath).isFile()) return null;
|
|
1216
|
+
return path.resolve(filePath);
|
|
1217
|
+
}
|
|
1218
|
+
function resolveLocalImport(fromDir, specifier) {
|
|
1219
|
+
const base = path.resolve(fromDir, specifier);
|
|
1220
|
+
const direct = tryFile(base);
|
|
1221
|
+
if (direct) return direct;
|
|
1222
|
+
for (const ext of SOURCE_EXTENSIONS) {
|
|
1223
|
+
const withExt = tryFile(base + ext);
|
|
1224
|
+
if (withExt) return withExt;
|
|
1225
|
+
}
|
|
1226
|
+
for (const ext of SOURCE_EXTENSIONS) {
|
|
1227
|
+
const asIndex = tryFile(path.join(base, `index${ext}`));
|
|
1228
|
+
if (asIndex) return asIndex;
|
|
1229
|
+
}
|
|
1230
|
+
return null;
|
|
1231
|
+
}
|
|
1232
|
+
function collectDependencies(entryFile, options) {
|
|
1233
|
+
const root = path.resolve(options.root);
|
|
1234
|
+
const visited = /* @__PURE__ */ new Set();
|
|
1235
|
+
const result = /* @__PURE__ */ new Set();
|
|
1236
|
+
const walk = (file) => {
|
|
1237
|
+
const resolveFile = path.resolve(file);
|
|
1238
|
+
if (visited.has(resolveFile)) return;
|
|
1239
|
+
visited.add(resolveFile);
|
|
1240
|
+
if (!isInsideRoot(resolveFile, root)) return;
|
|
1241
|
+
if (isNodeModulesFile(resolveFile)) return;
|
|
1242
|
+
if (!existsSync3(resolveFile)) return;
|
|
1243
|
+
if (!statSync(resolveFile).isFile()) return;
|
|
1244
|
+
if (options.includeEntry || resolveFile !== path.resolve(entryFile))
|
|
1245
|
+
result.add(resolveFile);
|
|
1246
|
+
const code = readFileSync(resolveFile, "utf8");
|
|
1247
|
+
const dir = path.dirname(resolveFile);
|
|
1248
|
+
for (const specifier of extractLocalSpecifiers(code)) {
|
|
1249
|
+
const dep = resolveLocalImport(dir, specifier);
|
|
1250
|
+
if (!dep) continue;
|
|
1251
|
+
walk(dep);
|
|
1252
|
+
}
|
|
1253
|
+
};
|
|
1254
|
+
walk(entryFile);
|
|
1255
|
+
return Array.from(result);
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
// src/scanner/load/loadManifes.ts
|
|
1259
|
+
import { existsSync as existsSync4, readdirSync, statSync as statSync2 } from "fs";
|
|
1260
|
+
import path2 from "path";
|
|
1261
|
+
import { createJiti as createJiti2 } from "jiti";
|
|
1262
|
+
|
|
1263
|
+
// src/scanner/validation.ts
|
|
1264
|
+
import { OBSERVE_EVENT_NAMES } from "@makoojs/core";
|
|
1265
|
+
import { z as z2 } from "zod";
|
|
1266
|
+
var ObserveEventNameSchema = z2.enum(OBSERVE_EVENT_NAMES);
|
|
1267
|
+
var HookSchema = z2.union([z2.function(), z2.array(z2.function())]);
|
|
1268
|
+
var LifecycleHookMapSchema = z2.record(z2.string(), HookSchema).refine((obj) => Object.keys(obj).every((k) => ObserveEventNameSchema.safeParse(k).success), {
|
|
1269
|
+
message: "Invalid hook event name"
|
|
1270
|
+
});
|
|
1271
|
+
var InjectorConfigSchema = z2.object({
|
|
1272
|
+
alive: z2.boolean().optional(),
|
|
1273
|
+
scope: z2.enum(["local", "global"]).optional(),
|
|
1274
|
+
timeout: z2.number().optional(),
|
|
1275
|
+
hooks: LifecycleHookMapSchema.optional()
|
|
1276
|
+
});
|
|
1277
|
+
var InjectionMatchSchema = z2.union([
|
|
1278
|
+
z2.array(z2.string()),
|
|
1279
|
+
z2.object({
|
|
1280
|
+
include: z2.array(z2.string()).optional(),
|
|
1281
|
+
exclude: z2.array(z2.string()).optional()
|
|
1282
|
+
})
|
|
1283
|
+
]);
|
|
1284
|
+
var InjectionModuleSchema = z2.object({
|
|
1285
|
+
name: z2.string().optional(),
|
|
1286
|
+
injectAt: z2.string(),
|
|
1287
|
+
component: z2.string(),
|
|
1288
|
+
framework: z2.enum(["auto", "Vue", "React"]).optional(),
|
|
1289
|
+
enabled: z2.boolean().optional(),
|
|
1290
|
+
match: InjectionMatchSchema.optional(),
|
|
1291
|
+
alive: z2.boolean().optional(),
|
|
1292
|
+
scope: z2.enum(["local", "global"]).optional(),
|
|
1293
|
+
timeout: z2.number().optional()
|
|
1294
|
+
});
|
|
1295
|
+
var InjectionManifestSchema = z2.object({
|
|
1296
|
+
globalInjector: InjectorConfigSchema.optional(),
|
|
1297
|
+
injections: z2.union([
|
|
1298
|
+
z2.array(InjectionModuleSchema),
|
|
1299
|
+
z2.record(z2.string(), InjectionModuleSchema.omit({ name: true }))
|
|
1300
|
+
])
|
|
1301
|
+
});
|
|
1302
|
+
function validateManifest(data, file) {
|
|
1303
|
+
const result = InjectionManifestSchema.safeParse(data);
|
|
1304
|
+
if (!result.success) {
|
|
1305
|
+
throw new ManifestValidationError(file, result.error.issues);
|
|
1306
|
+
}
|
|
1307
|
+
return result.data;
|
|
1308
|
+
}
|
|
1309
|
+
function validateModuleMeta(data, file) {
|
|
1310
|
+
const result = InjectionModuleSchema.safeParse(data);
|
|
1311
|
+
if (!result.success) {
|
|
1312
|
+
throw new ManifestValidationError(file, result.error.issues);
|
|
1313
|
+
}
|
|
1314
|
+
return result.data;
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
// src/scanner/load/loadManifes.ts
|
|
1318
|
+
async function loadManifest(source) {
|
|
1319
|
+
if (!existsSync4(source.dir)) {
|
|
1320
|
+
throw new SourceDirNotFoundError(source.dir);
|
|
1321
|
+
}
|
|
1322
|
+
const manifestName = source.manifest;
|
|
1323
|
+
const jiti = createJiti2(source.dir, { moduleCache: false });
|
|
1324
|
+
for (const entry of readdirSync(source.dir)) {
|
|
1325
|
+
const fullPath = path2.join(source.dir, entry);
|
|
1326
|
+
if (statSync2(fullPath).isFile() && path2.basename(entry, path2.extname(entry)) === manifestName) {
|
|
1327
|
+
let raw;
|
|
1328
|
+
try {
|
|
1329
|
+
raw = await jiti.import(fullPath, { default: true });
|
|
1330
|
+
} catch (err) {
|
|
1331
|
+
throw new ManifestLoadError(
|
|
1332
|
+
fullPath,
|
|
1333
|
+
void 0,
|
|
1334
|
+
err instanceof Error ? err : void 0
|
|
1335
|
+
);
|
|
1336
|
+
}
|
|
1337
|
+
return {
|
|
1338
|
+
manifest: validateManifest(raw, fullPath),
|
|
1339
|
+
manifestFile: fullPath,
|
|
1340
|
+
dependencies: collectDependencies(fullPath, {
|
|
1341
|
+
root: path2.resolve(source.dir, "..")
|
|
1342
|
+
})
|
|
1343
|
+
};
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
return null;
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
// src/scanner/load/loadMeta.ts
|
|
1350
|
+
import fs from "fs";
|
|
1351
|
+
import path3 from "path";
|
|
1352
|
+
import { createJiti as createJiti3 } from "jiti";
|
|
1353
|
+
async function loadMeta(root) {
|
|
1354
|
+
const files = fs.readdirSync(root).filter((name) => {
|
|
1355
|
+
const fullPath = path3.join(root, name);
|
|
1356
|
+
return fs.statSync(fullPath).isFile();
|
|
1357
|
+
});
|
|
1358
|
+
if (files.length === 0) {
|
|
1359
|
+
return null;
|
|
1360
|
+
}
|
|
1361
|
+
const jiti = createJiti3(root, { moduleCache: false });
|
|
1362
|
+
for (const f of files) {
|
|
1363
|
+
const fileName = path3.basename(f, path3.extname(f));
|
|
1364
|
+
if (fileName === DEFAULT_MANIFEST_FILE_NAME) {
|
|
1365
|
+
const fullPath = path3.join(root, f);
|
|
1366
|
+
let raw;
|
|
1367
|
+
try {
|
|
1368
|
+
raw = await jiti.import(fullPath, { default: true });
|
|
1369
|
+
} catch (err) {
|
|
1370
|
+
throw new ModuleManifestLoadError(
|
|
1371
|
+
fullPath,
|
|
1372
|
+
void 0,
|
|
1373
|
+
err instanceof Error ? err : void 0
|
|
1374
|
+
);
|
|
1375
|
+
}
|
|
1376
|
+
return {
|
|
1377
|
+
overridePath: fullPath,
|
|
1378
|
+
moduleConfig: validateModuleMeta(raw, fullPath),
|
|
1379
|
+
dependencies: collectDependencies(fullPath, {
|
|
1380
|
+
root: path3.resolve(root, "..", "..")
|
|
1381
|
+
})
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
return null;
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
// src/scanner/util.ts
|
|
1389
|
+
function mergeMeta(source, target) {
|
|
1390
|
+
const targetMap = new Map(target.map((m) => [m.moduleId, m]));
|
|
1391
|
+
const result = source.map((s) => targetMap.get(s.moduleId) ?? s);
|
|
1392
|
+
for (const t of target) {
|
|
1393
|
+
if (!source.some((s) => s.moduleId === t.moduleId)) {
|
|
1394
|
+
result.push(t);
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
return result;
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
// src/scanner/scanner.ts
|
|
1401
|
+
async function scanner(config) {
|
|
1402
|
+
const loadedManifest = await loadManifest(config.source);
|
|
1403
|
+
if (!loadedManifest) {
|
|
1404
|
+
throw new ManifestNotFoundError(config.source.dir);
|
|
1405
|
+
}
|
|
1406
|
+
const manifestDependencies = new Set(loadedManifest.dependencies);
|
|
1407
|
+
const runtimeDependencies = /* @__PURE__ */ new Set();
|
|
1408
|
+
for (const setupFile of config.runtime.setup) {
|
|
1409
|
+
if (!existsSync5(setupFile)) {
|
|
1410
|
+
throw new RuntimeSetupNotFoundError(setupFile);
|
|
1411
|
+
}
|
|
1412
|
+
runtimeDependencies.add(setupFile);
|
|
1413
|
+
for (const dependency of collectDependencies(setupFile, { root: config.root })) {
|
|
1414
|
+
runtimeDependencies.add(dependency);
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
const resolveInjector = resolveInjectorConfig(loadedManifest.manifest.globalInjector);
|
|
1418
|
+
const resolveManifest = resolveInjections(loadedManifest.manifest, {
|
|
1419
|
+
root: config.root,
|
|
1420
|
+
source: config.source,
|
|
1421
|
+
injector: resolveInjector
|
|
1422
|
+
});
|
|
1423
|
+
const folder = readdirSync2(config.source.dir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
|
|
1424
|
+
const isIncluded = picomatch(config.source.include);
|
|
1425
|
+
const isExcluded = picomatch(config.source.exclude);
|
|
1426
|
+
const filteredFolders = folder.filter((name) => isIncluded(name) && !isExcluded(name));
|
|
1427
|
+
const injectionsMeta = [];
|
|
1428
|
+
for (const module of filteredFolders) {
|
|
1429
|
+
const modulePath = path4.join(config.source.dir, module);
|
|
1430
|
+
const meta = await loadMeta(modulePath);
|
|
1431
|
+
if (!meta) {
|
|
1432
|
+
continue;
|
|
1433
|
+
}
|
|
1434
|
+
for (const dependency of meta.dependencies) {
|
|
1435
|
+
manifestDependencies.add(dependency);
|
|
1436
|
+
}
|
|
1437
|
+
const resolveMeta = resolveInjection(meta.moduleConfig, {
|
|
1438
|
+
root: config.root,
|
|
1439
|
+
source: config.source,
|
|
1440
|
+
injector: resolveInjector,
|
|
1441
|
+
moduleDir: modulePath,
|
|
1442
|
+
componentPath: path4.join(modulePath, meta.moduleConfig.component),
|
|
1443
|
+
fallbackName: module,
|
|
1444
|
+
overridePath: meta.overridePath
|
|
1445
|
+
});
|
|
1446
|
+
injectionsMeta.push(resolveMeta);
|
|
1447
|
+
}
|
|
1448
|
+
const injections = mergeMeta(resolveManifest, injectionsMeta).filter(
|
|
1449
|
+
(injection) => injection.enabled
|
|
1450
|
+
);
|
|
1451
|
+
if (injections.length === 0) {
|
|
1452
|
+
throw new NoEnabledInjectionsError();
|
|
1453
|
+
}
|
|
1454
|
+
injections.sort((a, b) => a.moduleId.localeCompare(b.moduleId));
|
|
1455
|
+
const frameworks = [...new Set(injections.map((m) => m.framework))];
|
|
1456
|
+
return {
|
|
1457
|
+
config: { ...config, injector: resolveInjector },
|
|
1458
|
+
manifestFile: loadedManifest.manifestFile,
|
|
1459
|
+
manifestDependencies: [...manifestDependencies].sort(),
|
|
1460
|
+
runtimeDependencies: [...runtimeDependencies].sort(),
|
|
1461
|
+
injections,
|
|
1462
|
+
frameworks
|
|
1463
|
+
};
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
// src/command/inspect.ts
|
|
1467
|
+
async function inspectCommand() {
|
|
1468
|
+
const resolveViteMakooConfig = await loadMakooConfig();
|
|
1469
|
+
const resolveManifest = await scanner(resolveViteMakooConfig);
|
|
1470
|
+
console.log(colorize("Manifest:", ansi.green));
|
|
1471
|
+
console.dir(resolveManifest, {
|
|
1472
|
+
depth: null,
|
|
1473
|
+
colors: true
|
|
1474
|
+
});
|
|
1475
|
+
console.log(colorize("Vite Makoo Config:", ansi.cyan));
|
|
1476
|
+
console.dir(resolveViteMakooConfig, {
|
|
1477
|
+
depth: null,
|
|
1478
|
+
colors: true
|
|
1479
|
+
});
|
|
1480
|
+
}
|
|
1481
|
+
|
|
1482
|
+
// src/command/bin.ts
|
|
1483
|
+
var cli = cac("makoo");
|
|
1484
|
+
cli.command("build", "Build the userscript").action(async () => {
|
|
1485
|
+
await buildCommand();
|
|
1486
|
+
});
|
|
1487
|
+
cli.command("dev", "Start the dev server").action(async () => {
|
|
1488
|
+
await devCommand();
|
|
1489
|
+
});
|
|
1490
|
+
cli.command("add <name>", "Add a new injection module").option("--framework <framework>", "Framework to use", { default: "React" }).action(async (name, options) => {
|
|
1491
|
+
await addCommand(name, options.framework);
|
|
1492
|
+
});
|
|
1493
|
+
cli.command("inspect", "Inspect resolved makoo config").action(async () => {
|
|
1494
|
+
await inspectCommand();
|
|
1495
|
+
});
|
|
1496
|
+
cli.help();
|
|
1497
|
+
cli.version("1.3.1");
|
|
1498
|
+
process.on("unhandledRejection", (err) => {
|
|
1499
|
+
if (err instanceof MakooError2) {
|
|
1500
|
+
console.error(err);
|
|
1501
|
+
} else {
|
|
1502
|
+
console.error("[makoo]", err);
|
|
1503
|
+
}
|
|
1504
|
+
process.exit(1);
|
|
1505
|
+
});
|
|
1506
|
+
cli.parse();
|