@darkrymit/crunes-cli 0.5.10 → 0.7.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.
Files changed (70) hide show
  1. package/README.md +5 -5
  2. package/dist/chunks/add-OWYVF3IE.js +22 -0
  3. package/dist/chunks/apply-OMEVXCHC.js +183 -0
  4. package/dist/chunks/args-32BVYW77.js +42 -0
  5. package/dist/chunks/benchmark-CLUBISCR.js +164 -0
  6. package/dist/chunks/browse-COH6IJEX.js +34 -0
  7. package/dist/chunks/check-BS6TZGRR.js +144 -0
  8. package/dist/chunks/chunk-2Q24YPGL.js +369 -0
  9. package/dist/chunks/chunk-3TM6B4E5.js +70 -0
  10. package/dist/chunks/chunk-67I2J474.js +153 -0
  11. package/dist/chunks/chunk-6XLT25GS.js +50 -0
  12. package/dist/chunks/chunk-BVY5LN7X.js +25091 -0
  13. package/dist/chunks/chunk-CGZL5SSH.js +926 -0
  14. package/dist/chunks/chunk-DMMC4X27.js +1836 -0
  15. package/dist/chunks/chunk-G3U4V32O.js +46 -0
  16. package/dist/chunks/chunk-GHQOK4L7.js +59 -0
  17. package/dist/chunks/chunk-H3BVJCIL.js +105 -0
  18. package/dist/chunks/chunk-HMU2J25D.js +63 -0
  19. package/dist/chunks/chunk-HOH7WZX4.js +95 -0
  20. package/dist/chunks/chunk-L72BG6DS.js +225 -0
  21. package/dist/chunks/chunk-NXSDVVTW.js +181 -0
  22. package/dist/chunks/chunk-QLDB3FO2.js +73059 -0
  23. package/dist/chunks/chunk-QMWGQXEZ.js +26 -0
  24. package/dist/chunks/chunk-TPK5AGRA.js +54 -0
  25. package/dist/chunks/chunk-UGN3FFEF.js +8379 -0
  26. package/dist/chunks/chunk-WCODTMDN.js +508 -0
  27. package/dist/chunks/chunk-XIXND2M4.js +296 -0
  28. package/dist/chunks/chunk-XXUNHQIB.js +129 -0
  29. package/dist/chunks/chunk-ZXIP4Z5V.js +281 -0
  30. package/dist/chunks/clear-Y5POLIMF.js +32 -0
  31. package/dist/chunks/completions-2MSEWWTG.js +232 -0
  32. package/dist/chunks/create-5FXQYCGM.js +165 -0
  33. package/dist/chunks/create-I6BNYZ5Q.js +247 -0
  34. package/dist/chunks/create-O3HMODSL.js +130 -0
  35. package/dist/chunks/delete-7CQFYIXS.js +40 -0
  36. package/dist/chunks/delete-UB5SXO5I.js +40 -0
  37. package/dist/chunks/disable-FCBW7WVG.js +47 -0
  38. package/dist/chunks/doctor-DS57HDLJ.js +53 -0
  39. package/dist/chunks/enable-IXRVUXJM.js +47 -0
  40. package/dist/chunks/esm-7MEWZCHY.js +5162 -0
  41. package/dist/chunks/globals-YCJ2DGWC.js +60 -0
  42. package/dist/chunks/init-WGKQVAZE.js +59 -0
  43. package/dist/chunks/install-BCTBOPBS.js +57 -0
  44. package/dist/chunks/intro-2UDWF6D4.js +1482 -0
  45. package/dist/chunks/kill-LWRXZVM5.js +37 -0
  46. package/dist/chunks/list-5DVVP7HX.js +50 -0
  47. package/dist/chunks/list-6WL5LGIZ.js +80 -0
  48. package/dist/chunks/list-NGOCMJXE.js +104 -0
  49. package/dist/chunks/list-TTKLNJKI.js +28 -0
  50. package/dist/chunks/list-WUAOSO3M.js +110 -0
  51. package/dist/chunks/list-YPI7YDKK.js +80 -0
  52. package/dist/chunks/list-ZBYPMUID.js +23 -0
  53. package/dist/chunks/manifest-7RVNKBOH.js +9 -0
  54. package/dist/chunks/output-RJ6JSNY7.js +12 -0
  55. package/dist/chunks/promise-DUSIQMA2.js +19400 -0
  56. package/dist/chunks/query-NY4SCO77.js +41 -0
  57. package/dist/chunks/registry-W5XFI5T6.js +16 -0
  58. package/dist/chunks/remove-WEAZFZCO.js +22 -0
  59. package/dist/chunks/run-I6TZX347.js +23 -0
  60. package/dist/chunks/run-MVIZQVJ6.js +36 -0
  61. package/dist/chunks/rune-TAX26NH2.js +76 -0
  62. package/dist/chunks/search-XENXL3GC.js +25 -0
  63. package/dist/chunks/uninstall-MX5PLGDI.js +49 -0
  64. package/dist/chunks/unset-KQOZYVTE.js +28 -0
  65. package/dist/chunks/update-7XDTVFZ3.js +39 -0
  66. package/dist/chunks/update-IEE54GPY.js +79 -0
  67. package/dist/chunks/utils-PO3ZK53L.js +50 -0
  68. package/dist/chunks/version-DIEA5FVV.js +145 -0
  69. package/dist/cli.js +3360 -125840
  70. package/package.json +23 -15
@@ -0,0 +1,32 @@
1
+ import {
2
+ clearCacheBucket
3
+ } from "./chunk-NXSDVVTW.js";
4
+ import "./chunk-QMWGQXEZ.js";
5
+ import {
6
+ ensureProjectIdentity
7
+ } from "./chunk-3TM6B4E5.js";
8
+ import "./chunk-HMU2J25D.js";
9
+ import {
10
+ init_require_shim
11
+ } from "./chunk-TPK5AGRA.js";
12
+
13
+ // src/cache/commands/clear.js
14
+ init_require_shim();
15
+ async function handler({ id, projectDir, global: isGlobal }) {
16
+ const key = isGlobal ? void 0 : (await ensureProjectIdentity(projectDir)).id;
17
+ let result;
18
+ try {
19
+ result = await clearCacheBucket(id, key);
20
+ } catch (err) {
21
+ console.error(`Error: ${err.message}`);
22
+ process.exit(1);
23
+ }
24
+ if (result.removed === 0) {
25
+ console.log(`No expired keys in "${result.name}".`);
26
+ } else {
27
+ console.log(`Removed ${result.removed} expired key${result.removed === 1 ? "" : "s"} from "${result.name}".`);
28
+ }
29
+ }
30
+ export {
31
+ handler
32
+ };
@@ -0,0 +1,232 @@
1
+ import {
2
+ init_require_shim
3
+ } from "./chunk-TPK5AGRA.js";
4
+
5
+ // src/cli/commands/completions.js
6
+ init_require_shim();
7
+ import fs from "node:fs";
8
+ import fsPromises from "node:fs/promises";
9
+ import os from "node:os";
10
+ import path from "node:path";
11
+ function extractCwd(tokens) {
12
+ const idx = tokens.indexOf("--cwd");
13
+ if (idx !== -1 && idx + 1 < tokens.length) return path.resolve(tokens[idx + 1]);
14
+ return process.cwd();
15
+ }
16
+ function loadRuneKeys(dir) {
17
+ try {
18
+ const configPath = path.join(dir, ".crunes", "config.json");
19
+ const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
20
+ return Object.keys(config.runes ?? {});
21
+ } catch {
22
+ return [];
23
+ }
24
+ }
25
+ function loadPluginNames() {
26
+ try {
27
+ const pluginsPath = path.join(os.homedir(), ".crunes", "plugins.json");
28
+ const registry = JSON.parse(fs.readFileSync(pluginsPath, "utf8"));
29
+ return Object.keys(registry.plugins ?? {});
30
+ } catch {
31
+ return [];
32
+ }
33
+ }
34
+ function logDebug(err) {
35
+ if (process.env.CRUNES_COMPLETION_DEBUG !== "1") return;
36
+ try {
37
+ const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${err?.stack ?? err}
38
+ `;
39
+ fs.appendFileSync(path.join(os.tmpdir(), "crunes-completion.log"), line);
40
+ } catch {
41
+ }
42
+ }
43
+ function resolveCompletions(tokens, program, { cwd } = {}) {
44
+ const resolvedCwd = cwd ?? extractCwd(tokens);
45
+ const args = tokens.slice(1);
46
+ const partialWord = args.length > 0 ? args[args.length - 1] : "";
47
+ const prevWord = args.length > 1 ? args[args.length - 2] : "";
48
+ let currentCmd = program;
49
+ const positionalArgs = [];
50
+ let skipNext = false;
51
+ const getOpt = (cmd, word) => cmd.options.find((o) => o.short === word || o.long === word) ?? program.options.find((o) => o.short === word || o.long === word);
52
+ for (let i = 0; i < args.length - 1; i++) {
53
+ if (skipNext) {
54
+ skipNext = false;
55
+ continue;
56
+ }
57
+ const arg = args[i];
58
+ if (arg.startsWith("-")) {
59
+ const hasEquals = arg.includes("=");
60
+ const flagName = hasEquals ? arg.split("=")[0] : arg;
61
+ const opt = getOpt(currentCmd, flagName);
62
+ if (opt && (opt.required || opt.optional) && !hasEquals) skipNext = true;
63
+ continue;
64
+ }
65
+ const nextCmd = currentCmd.commands.find((c) => c.name() === arg || c.aliases().includes(arg));
66
+ if (nextCmd) {
67
+ currentCmd = nextCmd;
68
+ positionalArgs.length = 0;
69
+ } else {
70
+ positionalArgs.push(arg);
71
+ }
72
+ }
73
+ const candidates = /* @__PURE__ */ new Set();
74
+ let activeOpt = null;
75
+ let matchTarget = partialWord;
76
+ let prefix = "";
77
+ if (partialWord.startsWith("-") && partialWord.includes("=")) {
78
+ const idx = partialWord.indexOf("=");
79
+ const flagName = partialWord.slice(0, idx);
80
+ activeOpt = getOpt(currentCmd, flagName);
81
+ matchTarget = partialWord.slice(idx + 1);
82
+ prefix = flagName + "=";
83
+ } else if (!prevWord.includes("=")) {
84
+ activeOpt = getOpt(currentCmd, prevWord);
85
+ }
86
+ if (!activeOpt && prevWord === "--format" && ["run", "check", "bench"].includes(currentCmd.name())) {
87
+ return ["text", "jsonl"].filter((c) => c.startsWith(matchTarget));
88
+ }
89
+ if (activeOpt) {
90
+ let optCandidates = [];
91
+ if (activeOpt.argChoices?.length) optCandidates = [...activeOpt.argChoices];
92
+ else if (activeOpt.flags.includes("<rune>")) optCandidates = loadRuneKeys(resolvedCwd);
93
+ if (optCandidates.length > 0) {
94
+ return optCandidates.filter((c) => c.startsWith(matchTarget)).map((c) => prefix + c);
95
+ }
96
+ if (activeOpt.required || activeOpt.optional) return [];
97
+ }
98
+ if (partialWord.startsWith("-") && !partialWord.includes("=")) {
99
+ const addOpts = (cmd) => cmd.options.forEach((opt) => {
100
+ if (opt.long) candidates.add(opt.long);
101
+ if (opt.short) candidates.add(opt.short);
102
+ });
103
+ addOpts(currentCmd);
104
+ if (currentCmd !== program) addOpts(program);
105
+ return Array.from(candidates).filter((c) => c.startsWith(partialWord));
106
+ }
107
+ const argDefs = currentCmd.registeredArguments;
108
+ let targetArgIndex = positionalArgs.length;
109
+ if (argDefs.length > 0 && targetArgIndex >= argDefs.length && argDefs[argDefs.length - 1].variadic) {
110
+ targetArgIndex = argDefs.length - 1;
111
+ }
112
+ const argDef = argDefs[targetArgIndex];
113
+ if (argDef) {
114
+ const argName = argDef.name();
115
+ if (argName === "rune") loadRuneKeys(resolvedCwd).forEach((k) => candidates.add(k));
116
+ else if (argName === "args" && positionalArgs.length === 0 && ["run", "check", "bench"].includes(currentCmd.name())) {
117
+ loadRuneKeys(resolvedCwd).forEach((k) => candidates.add(k));
118
+ } else if (argName === "plugin") loadPluginNames().forEach((p) => candidates.add(p));
119
+ else if (argName === "template-source") {
120
+ candidates.add("local");
121
+ loadPluginNames().forEach((p) => candidates.add(p));
122
+ } else if (argName === "shell") {
123
+ ["bash", "zsh", "fish", "powershell"].forEach((s) => candidates.add(s));
124
+ }
125
+ }
126
+ if (!argDef || currentCmd.commands.length > 0) {
127
+ currentCmd.commands.forEach((cmd) => candidates.add(cmd.name()));
128
+ }
129
+ return Array.from(candidates).filter((c) => c.startsWith(partialWord));
130
+ }
131
+ function outputCandidates(candidates) {
132
+ if (candidates.length > 0) process.stdout.write(candidates.join("\n") + "\n");
133
+ }
134
+ function zshHandler(words, program) {
135
+ try {
136
+ const tokens = Array.isArray(words) ? words : [];
137
+ outputCandidates(resolveCompletions(tokens, program));
138
+ } catch (err) {
139
+ logDebug(err);
140
+ }
141
+ }
142
+ function fishHandler(words, program) {
143
+ try {
144
+ const tokens = Array.isArray(words) ? words : [];
145
+ outputCandidates(resolveCompletions(tokens, program));
146
+ } catch (err) {
147
+ logDebug(err);
148
+ }
149
+ }
150
+ function powershellHandler(elements, program) {
151
+ try {
152
+ const line = process.env.CRUNES_COMP_LINE ?? elements[0] ?? "";
153
+ const point = parseInt(process.env.CRUNES_COMP_POINT ?? elements[1] ?? String(line.length), 10);
154
+ const partial = line.slice(0, point);
155
+ const tokens = partial.split(/\s+/).filter((t, i, arr) => i < arr.length - 1 || t !== "");
156
+ if (partial.endsWith(" ")) tokens.push("");
157
+ outputCandidates(resolveCompletions(tokens, program));
158
+ } catch (err) {
159
+ logDebug(err);
160
+ }
161
+ }
162
+ function bashHandler(program) {
163
+ try {
164
+ const compLine = process.env.COMP_LINE ?? "";
165
+ const compPoint = parseInt(process.env.COMP_POINT ?? String(compLine.length), 10);
166
+ const partial = compLine.slice(0, compPoint);
167
+ const tokens = partial.split(/\s+/).filter((t, i, arr) => i < arr.length - 1 || t !== "");
168
+ if (partial.endsWith(" ")) tokens.push("");
169
+ const candidates = resolveCompletions(tokens, program);
170
+ const lastToken = tokens[tokens.length - 1] ?? "";
171
+ const eqIdx = lastToken.indexOf("=");
172
+ if (eqIdx !== -1) {
173
+ const bashPrefix = lastToken.slice(0, eqIdx + 1);
174
+ outputCandidates(candidates.filter((c) => c.startsWith(bashPrefix)).map((c) => c.slice(bashPrefix.length)));
175
+ } else {
176
+ outputCandidates(candidates);
177
+ }
178
+ } catch (err) {
179
+ logDebug(err);
180
+ }
181
+ }
182
+ var HOOKS = {
183
+ bash: "complete -C 'crunes completions bash' crunes\n",
184
+ zsh: 'compdef \'_comps=("${(@f)$(crunes completions zsh "${(@)words}")}"); compadd -a _comps\' crunes\n',
185
+ fish: 'complete -c crunes -f -a "(crunes completions fish (commandline -opc))"\n',
186
+ powershell: `Register-ArgumentCompleter -Native -CommandName crunes -ScriptBlock { param($w,$ast,$pos); $line = $ast.Extent.Text; if ([string]::IsNullOrEmpty($w)) { $line += ' ' }; $env:CRUNES_COMP_LINE = $line; $env:CRUNES_COMP_POINT = $pos; $res = & crunes completions powershell; if ($res) { $res | Where-Object { $_ -like "$w*" } | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) } } }
187
+ `
188
+ };
189
+ function defaultProfilePath(shell) {
190
+ const home = os.homedir();
191
+ if (shell === "bash") return path.join(home, ".bashrc");
192
+ if (shell === "zsh") return path.join(home, ".zshrc");
193
+ if (shell === "fish") return path.join(home, ".config", "fish", "config.fish");
194
+ if (shell === "powershell") {
195
+ if (process.platform === "win32") {
196
+ const pwshCorePath = path.join(home, "Documents", "PowerShell", "Microsoft.PowerShell_profile.ps1");
197
+ const winPwshPath = path.join(home, "Documents", "WindowsPowerShell", "Microsoft.PowerShell_profile.ps1");
198
+ if (fs.existsSync(path.dirname(pwshCorePath))) return pwshCorePath;
199
+ return winPwshPath;
200
+ } else {
201
+ return path.join(home, ".config", "powershell", "Microsoft.PowerShell_profile.ps1");
202
+ }
203
+ }
204
+ }
205
+ async function installHandler(shell, { profilePath } = {}) {
206
+ const hook = HOOKS[shell];
207
+ if (!hook) throw new Error(`Unknown shell: ${shell}. Supported: bash, zsh, fish, powershell`);
208
+ const target = profilePath ?? defaultProfilePath(shell);
209
+ await fsPromises.mkdir(path.dirname(target), { recursive: true });
210
+ let existing = "";
211
+ try {
212
+ existing = await fsPromises.readFile(target, "utf8");
213
+ } catch (err) {
214
+ if (err.code !== "ENOENT") throw err;
215
+ }
216
+ const hookLine = hook.trim();
217
+ if (existing.includes(hookLine)) {
218
+ console.log(`crunes completions already present in ${target}`);
219
+ return;
220
+ }
221
+ await fsPromises.appendFile(target, (existing.length ? "\n" : "") + hook);
222
+ console.log(`crunes completions installed in ${target}`);
223
+ console.log(`Restart your shell or run: source ${target}`);
224
+ }
225
+ export {
226
+ bashHandler,
227
+ fishHandler,
228
+ installHandler,
229
+ powershellHandler,
230
+ resolveCompletions,
231
+ zshHandler
232
+ };
@@ -0,0 +1,165 @@
1
+ import {
2
+ Ee,
3
+ Re,
4
+ fe,
5
+ ge,
6
+ ye
7
+ } from "./chunk-CGZL5SSH.js";
8
+ import {
9
+ output
10
+ } from "./chunk-6XLT25GS.js";
11
+ import "./chunk-WCODTMDN.js";
12
+ import {
13
+ init_require_shim
14
+ } from "./chunk-TPK5AGRA.js";
15
+
16
+ // src/rune/commands/create.js
17
+ init_require_shim();
18
+ import { mkdir, writeFile, readFile, rename } from "node:fs/promises";
19
+ import { join, dirname } from "node:path";
20
+ var VALID_FORMATS = ["tree", "markdown"];
21
+ function template(key, format) {
22
+ const imports = format === "tree" ? `import { md, section, tree } from '@utils'` : `import { md, section } from '@utils'`;
23
+ const header = [
24
+ `// permissions:`,
25
+ `// run:`,
26
+ `// allow: [] \u2014 add patterns like fs.read:./** if you use utils.fs`,
27
+ `// deny: []`,
28
+ ``,
29
+ imports,
30
+ ``,
31
+ `// export async function args(b) {`,
32
+ `// return b`,
33
+ `// .option('-v, --verbose', 'Verbose output', false)`,
34
+ `// .build()`,
35
+ `// }`,
36
+ ``,
37
+ `export async function run(args) {`,
38
+ ` // args._ \u2014 data positionals (command tokens stripped)`,
39
+ ` // args.verbose \u2014 named flag (if args export is defined above)`,
40
+ ` // utils.fs.cwd() \u2014 absolute path to the project root`
41
+ ].join("\n");
42
+ if (format === "tree") {
43
+ return header + "\n" + [
44
+ ``,
45
+ ` const root = tree.node('${key}', 'Root description', [`,
46
+ ` tree.node('child', 'Child description'),`,
47
+ ` ]);`,
48
+ ` return section.create('example-tree', { type: 'tree', root });`,
49
+ `}`,
50
+ ``
51
+ ].join("\n");
52
+ }
53
+ return header + "\n" + [
54
+ ``,
55
+ ` const content = [`,
56
+ ` md.h3('${key}'),`,
57
+ ` md.ul(['Replace with real data']),`,
58
+ ` ].join('\\n');`,
59
+ ` return section.create('example-md', { type: 'markdown', content });`,
60
+ `}`,
61
+ ``
62
+ ].join("\n");
63
+ }
64
+ async function handler({
65
+ key,
66
+ format,
67
+ path: runeRelPath,
68
+ name,
69
+ description,
70
+ yes = false,
71
+ projectRoot = process.cwd(),
72
+ configRoot = projectRoot
73
+ } = {}) {
74
+ const isNonInteractive = yes || !process.stdout.isTTY;
75
+ if (isNonInteractive) {
76
+ if (!key) {
77
+ output.error("Missing required argument: <key>");
78
+ process.exit(1);
79
+ }
80
+ if (!format || !VALID_FORMATS.includes(format)) {
81
+ output.error(`Missing or invalid --format. Must be one of: ${VALID_FORMATS.join(", ")}`);
82
+ process.exit(1);
83
+ }
84
+ } else {
85
+ ye("crunes create");
86
+ if (!key) {
87
+ const result = await Re({ message: "Rune key?", validate: (v) => v ? void 0 : "Required" });
88
+ if (result === /* @__PURE__ */ Symbol.for("clack:cancel")) {
89
+ ge("Cancelled.");
90
+ return;
91
+ }
92
+ key = result;
93
+ }
94
+ if (!format) {
95
+ const result = await Ee({
96
+ message: "Output format?",
97
+ options: [
98
+ { value: "tree", label: "tree", hint: "hierarchical ASCII tree structure" },
99
+ { value: "markdown", label: "markdown", hint: "freeform markdown content" }
100
+ ]
101
+ });
102
+ if (result === /* @__PURE__ */ Symbol.for("clack:cancel")) {
103
+ ge("Cancelled.");
104
+ return;
105
+ }
106
+ format = result;
107
+ }
108
+ if (!runeRelPath) {
109
+ const defaultPath = `.crunes/runes/${key}.js`;
110
+ const result = await Re({ message: "File path?", initialValue: defaultPath });
111
+ if (result === /* @__PURE__ */ Symbol.for("clack:cancel")) {
112
+ ge("Cancelled.");
113
+ return;
114
+ }
115
+ runeRelPath = result;
116
+ }
117
+ if (!name) {
118
+ const result = await Re({ message: "Name? (optional)", placeholder: "Human-readable label for crunes list" });
119
+ if (result === /* @__PURE__ */ Symbol.for("clack:cancel")) {
120
+ ge("Cancelled.");
121
+ return;
122
+ }
123
+ name = result || void 0;
124
+ }
125
+ if (!description) {
126
+ const result = await Re({ message: "Description? (optional)", placeholder: "What context does this rune provide?" });
127
+ if (result === /* @__PURE__ */ Symbol.for("clack:cancel")) {
128
+ ge("Cancelled.");
129
+ return;
130
+ }
131
+ description = result || void 0;
132
+ }
133
+ }
134
+ runeRelPath = runeRelPath ?? `.crunes/runes/${key}.js`;
135
+ const runeAbsPath = join(configRoot, runeRelPath);
136
+ await mkdir(dirname(runeAbsPath), { recursive: true });
137
+ await writeFile(runeAbsPath, template(key, format));
138
+ const configPath = join(configRoot, ".crunes", "config.json");
139
+ await mkdir(dirname(configPath), { recursive: true });
140
+ let config = { runes: {} };
141
+ try {
142
+ config = JSON.parse(await readFile(configPath, "utf8"));
143
+ } catch {
144
+ }
145
+ const entry = {
146
+ path: runeRelPath,
147
+ ...name && { name },
148
+ ...description && { description }
149
+ };
150
+ config.runes = { ...config.runes ?? {}, [key]: entry };
151
+ const tmpPath = configPath + ".tmp";
152
+ await writeFile(tmpPath, JSON.stringify(config, null, 2) + "\n", "utf8");
153
+ await rename(tmpPath, configPath);
154
+ if (!isNonInteractive) {
155
+ fe(`Created ${runeRelPath}
156
+ Run: crunes run ${key}`);
157
+ } else {
158
+ output.success(`Created ${runeRelPath}`);
159
+ output.info(`Run: crunes run ${key}`);
160
+ }
161
+ }
162
+ export {
163
+ handler,
164
+ template
165
+ };
@@ -0,0 +1,247 @@
1
+ import {
2
+ Re,
3
+ fe,
4
+ ge,
5
+ le,
6
+ ye
7
+ } from "./chunk-CGZL5SSH.js";
8
+ import {
9
+ output
10
+ } from "./chunk-6XLT25GS.js";
11
+ import "./chunk-WCODTMDN.js";
12
+ import {
13
+ init_require_shim
14
+ } from "./chunk-TPK5AGRA.js";
15
+
16
+ // src/plugin/commands/create.js
17
+ init_require_shim();
18
+ import { mkdir, writeFile, readdir } from "node:fs/promises";
19
+ import { join, resolve, dirname } from "node:path";
20
+ import { spawnSync } from "node:child_process";
21
+ function pluginJson({ name, description, author, license }) {
22
+ return JSON.stringify({
23
+ format: "1",
24
+ runes: {
25
+ example: {
26
+ name: "Example Rune",
27
+ description: "Replace with your rune description",
28
+ permissions: {
29
+ use: {
30
+ allow: [],
31
+ deny: []
32
+ }
33
+ }
34
+ }
35
+ },
36
+ templates: {
37
+ "example-template": {
38
+ name: "Example Template",
39
+ description: "Replace with your template description"
40
+ }
41
+ }
42
+ }, null, 2) + "\n";
43
+ }
44
+ function marketplaceJson({ name, description, author, license }) {
45
+ return JSON.stringify({
46
+ format: "1",
47
+ name,
48
+ description,
49
+ owner: { name: author },
50
+ plugins: [{
51
+ name,
52
+ description,
53
+ version: "1.0.0",
54
+ author: { name: author },
55
+ source: "./",
56
+ category: "runes",
57
+ license
58
+ }]
59
+ }, null, 2) + "\n";
60
+ }
61
+ function exampleRune() {
62
+ return `// Ready-to-run rune \u2014 runs directly from the plugin install location.
63
+ // Users activate it by adding your plugin to their project config.
64
+ //
65
+ // permissions (plugin.json):
66
+ // run:
67
+ // allow: [] \u2014 add patterns like fs.read:./** if you use utils.fs
68
+ // deny: []
69
+
70
+ import { md, section } from '@utils'
71
+
72
+ // export async function args(b) {
73
+ // return b
74
+ // .option('-v, --verbose', 'Verbose output', false)
75
+ // .build()
76
+ // }
77
+
78
+ export async function run(args) {
79
+ // args._ \u2014 data positionals (command tokens stripped)
80
+ // args.verbose \u2014 named flag (if args export is defined above)
81
+ // utils.fs.cwd() \u2014 absolute path to the user's project root
82
+
83
+ return section.create('example', {
84
+ type: 'markdown',
85
+ content: md.h3('Example') + '\\n' + md.ul(['Replace with real output']),
86
+ });
87
+ }
88
+ `;
89
+ }
90
+ function exampleTemplate() {
91
+ return `// Template rune \u2014 copied into the user's project by \`crunes template apply\`.
92
+ // Edit this file to define what a new rune looks like when scaffolded from your plugin.
93
+ //
94
+ // permissions (plugin.json):
95
+ // run:
96
+ // allow: [] \u2014 add patterns like fs.read:./** if you use utils.fs
97
+ // deny: []
98
+
99
+ import { md, section } from '@utils'
100
+
101
+ // export async function args(b) {
102
+ // return b
103
+ // .option('-v, --verbose', 'Verbose output', false)
104
+ // .build()
105
+ // }
106
+
107
+ export async function run(args) {
108
+ // args._ \u2014 data positionals (command tokens stripped)
109
+ // args.verbose \u2014 named flag (if args export is defined above)
110
+ // utils.fs.cwd() \u2014 absolute path to the user's project root
111
+
112
+ return section.create('example', {
113
+ type: 'markdown',
114
+ content: md.h3('Example') + '\\n' + md.ul(['Replace with real output']),
115
+ });
116
+ }
117
+ `;
118
+ }
119
+ function readmeMd({ name, description }) {
120
+ return `# ${name}
121
+
122
+ ${description}
123
+
124
+ ## Installation
125
+
126
+ Add this plugin via the crunes marketplace.
127
+ `;
128
+ }
129
+ function changelogMd() {
130
+ return `# Changelog
131
+
132
+ ## 1.0.0
133
+
134
+ - Initial release
135
+ `;
136
+ }
137
+ function getGitAuthor() {
138
+ const result = spawnSync("git", ["config", "user.name"], { encoding: "utf8" });
139
+ return result.status === 0 ? result.stdout.trim() : "";
140
+ }
141
+ async function handler({
142
+ name,
143
+ description,
144
+ author,
145
+ license,
146
+ out,
147
+ yes = false,
148
+ projectRoot = process.cwd()
149
+ } = {}) {
150
+ const isNonInteractive = yes || !process.stdout.isTTY;
151
+ if (isNonInteractive) {
152
+ if (!name) {
153
+ output.error("Missing required argument: <name>");
154
+ process.exit(1);
155
+ }
156
+ if (!description) {
157
+ output.error("Missing required option: --description");
158
+ process.exit(1);
159
+ }
160
+ author = author ?? getGitAuthor();
161
+ license = license ?? "MIT";
162
+ } else {
163
+ ye("crunes plugin create");
164
+ if (!name) {
165
+ const r = await Re({ message: "Plugin name?", validate: (v) => v ? void 0 : "Required" });
166
+ if (r === /* @__PURE__ */ Symbol.for("clack:cancel")) {
167
+ ge("Cancelled.");
168
+ return;
169
+ }
170
+ name = r;
171
+ }
172
+ if (!description) {
173
+ const r = await Re({ message: "Description?", validate: (v) => v ? void 0 : "Required" });
174
+ if (r === /* @__PURE__ */ Symbol.for("clack:cancel")) {
175
+ ge("Cancelled.");
176
+ return;
177
+ }
178
+ description = r;
179
+ }
180
+ if (author === void 0) {
181
+ const r = await Re({ message: "Author?", initialValue: getGitAuthor() });
182
+ if (r === /* @__PURE__ */ Symbol.for("clack:cancel")) {
183
+ ge("Cancelled.");
184
+ return;
185
+ }
186
+ author = r;
187
+ }
188
+ if (license === void 0) {
189
+ const r = await Re({ message: "License?", initialValue: "MIT" });
190
+ if (r === /* @__PURE__ */ Symbol.for("clack:cancel")) {
191
+ ge("Cancelled.");
192
+ return;
193
+ }
194
+ license = r;
195
+ }
196
+ }
197
+ const outDir = resolve(projectRoot, out ?? name);
198
+ let entries = [];
199
+ try {
200
+ entries = await readdir(outDir);
201
+ } catch {
202
+ }
203
+ if (entries.length > 0) {
204
+ if (isNonInteractive) {
205
+ output.error(`Output directory "${outDir}" already exists and is not empty. Provide --out pointing to an empty location.`);
206
+ process.exit(1);
207
+ }
208
+ const ok = await le({ message: `"${outDir}" already exists and is not empty. Overwrite?` });
209
+ if (!ok || ok === /* @__PURE__ */ Symbol.for("clack:cancel")) {
210
+ ge("Cancelled.");
211
+ return;
212
+ }
213
+ }
214
+ const opts = { name, description, author, license };
215
+ const files = [
216
+ [join(outDir, ".crunes-plugin", "plugin.json"), pluginJson(opts)],
217
+ [join(outDir, ".crunes-plugin", "marketplace.json"), marketplaceJson(opts)],
218
+ [join(outDir, "runes", "example.js"), exampleRune()],
219
+ [join(outDir, "templates", "example-template.js"), exampleTemplate()],
220
+ [join(outDir, "README.md"), readmeMd(opts)],
221
+ [join(outDir, "CHANGELOG.md"), changelogMd()]
222
+ ];
223
+ for (const [filePath, content] of files) {
224
+ await mkdir(dirname(filePath), { recursive: true });
225
+ await writeFile(filePath, content);
226
+ }
227
+ const successMsg = `Created ${outDir}`;
228
+ const hintMsg = `Run the following to test locally:
229
+ 1. crunes marketplace add ./${name}
230
+ 2. crunes plugin install ${name}@${name}`;
231
+ if (isNonInteractive) {
232
+ output.success(successMsg);
233
+ output.info(`Run: crunes marketplace add ./${name} && crunes plugin install ${name}@${name}`);
234
+ } else {
235
+ fe(`${successMsg}
236
+ ${hintMsg}`);
237
+ }
238
+ }
239
+ export {
240
+ changelogMd,
241
+ exampleRune,
242
+ exampleTemplate,
243
+ handler,
244
+ marketplaceJson,
245
+ pluginJson,
246
+ readmeMd
247
+ };