create-krispya 0.6.0 → 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.
package/dist/cli.cjs DELETED
@@ -1,3025 +0,0 @@
1
- #!/usr/bin/env node
2
- 'use strict';
3
-
4
- const module$1 = require('module');
5
- const process$1 = require('process');
6
- const path = require('path');
7
- const promises = require('fs/promises');
8
- const fs = require('fs');
9
- const commander = require('commander');
10
- const p = require('@clack/prompts');
11
- const color = require('chalk');
12
- const undici = require('undici');
13
- const child_process = require('child_process');
14
- const index = require('./chunks/index.cjs');
15
- const Conf = require('conf');
16
-
17
- var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
18
- function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
19
-
20
- function _interopNamespaceCompat(e) {
21
- if (e && typeof e === 'object' && 'default' in e) return e;
22
- const n = Object.create(null);
23
- if (e) {
24
- for (const k in e) {
25
- n[k] = e[k];
26
- }
27
- }
28
- n.default = e;
29
- return n;
30
- }
31
-
32
- const p__namespace = /*#__PURE__*/_interopNamespaceCompat(p);
33
- const color__default = /*#__PURE__*/_interopDefaultCompat(color);
34
- const Conf__default = /*#__PURE__*/_interopDefaultCompat(Conf);
35
-
36
- const editorNames = {
37
- cursor: "Cursor",
38
- code: "VS Code",
39
- webstorm: "WebStorm",
40
- skip: "Skip"
41
- };
42
- function openInEditor(editor, path, reuseWindow) {
43
- return new Promise((resolve, reject) => {
44
- const isWindows = process.platform === "win32";
45
- const useReuseFlag = reuseWindow && (editor === "cursor" || editor === "code");
46
- const args = useReuseFlag ? ["-r", path] : [path];
47
- const child = isWindows ? child_process.spawn(`${editor} ${useReuseFlag ? "-r " : ""}"${path}"`, {
48
- detached: true,
49
- stdio: "ignore",
50
- shell: true
51
- }) : child_process.spawn(editor, args, {
52
- detached: true,
53
- stdio: "ignore"
54
- });
55
- child.on("error", reject);
56
- child.unref();
57
- setTimeout(resolve, 100);
58
- });
59
- }
60
-
61
- function formatConfigSummary(options, inherited) {
62
- const lines = [];
63
- const VALUE_COL = 27;
64
- const formatRow = (label, value, isInherited = false, indent = "") => {
65
- const fullLabel = indent + label;
66
- const dotCount = Math.max(1, VALUE_COL - fullLabel.length - 1);
67
- const dots = color__default.gray(".".repeat(dotCount));
68
- const displayValue = isInherited ? `${value} \u{1F512}` : value;
69
- return `${indent}${label} ${dots} ${displayValue}`;
70
- };
71
- const formatLanguage = (lang) => {
72
- return lang === "typescript" ? "TypeScript" : lang === "javascript" ? "JavaScript" : lang;
73
- };
74
- const projectType = options.projectType ?? "app";
75
- const baseTemplate = options.template ? index.getBaseTemplate(options.template) : "vanilla";
76
- if (baseTemplate === "react") {
77
- lines.push(formatRow("Framework", "React"));
78
- } else if (baseTemplate === "r3f") {
79
- lines.push(formatRow("Framework", "React Three Fiber"));
80
- }
81
- const language = options.template ? index.getLanguageFromTemplate(options.template) : "typescript";
82
- lines.push(formatRow("Language", formatLanguage(language)));
83
- if (projectType === "library") {
84
- lines.push(formatRow("Bundler", options.libraryBundler ?? "unbuild"));
85
- } else {
86
- lines.push(formatRow("Bundler", "vite"));
87
- }
88
- const nodeVersionInherited = inherited?.nodeVersion !== void 0;
89
- lines.push(formatRow("Node version", options.nodeVersion || "latest", nodeVersionInherited));
90
- const pmInherited = inherited?.packageManager !== void 0;
91
- lines.push(formatRow("Package manager", options.packageManager || "pnpm", pmInherited));
92
- if (options.packageManager === "pnpm") {
93
- const versionManaged = options.pnpmManageVersions ? "yes" : "no";
94
- const pnpmVersionInherited = inherited?.pnpmManageVersions !== void 0;
95
- lines.push(formatRow("\u21B3 Version managed", versionManaged, pnpmVersionInherited, ""));
96
- }
97
- if (options.linter) {
98
- const linterInherited = inherited?.linter !== void 0;
99
- lines.push(formatRow("Linter", options.linter, linterInherited));
100
- }
101
- if (options.formatter) {
102
- const formatterInherited = inherited?.formatter !== void 0;
103
- lines.push(formatRow("Formatter", options.formatter, formatterInherited));
104
- }
105
- const testing = options.testing ?? (projectType === "library" ? "vitest" : "none");
106
- lines.push(formatRow("Testing", testing));
107
- if (!inherited) {
108
- const configStrategy = options.configStrategy ?? "stealth";
109
- lines.push(formatRow("Config strategy", configStrategy));
110
- }
111
- if (options.template && index.getBaseTemplate(options.template) === "r3f") {
112
- const integrationNames = [
113
- options.drei && "drei",
114
- options.handle && "handle",
115
- options.leva && "leva",
116
- options.postprocessing && "postproc",
117
- options.rapier && "rapier",
118
- options.xr && "xr",
119
- options.uikit && "uikit",
120
- options.offscreen && "offscreen",
121
- options.zustand && "zustand",
122
- options.koota && "koota",
123
- options.triplex && "triplex",
124
- options.viverse && "viverse"
125
- ].filter(Boolean);
126
- lines.push("");
127
- lines.push(color__default.dim("Integrations"));
128
- for (let i = 0; i < integrationNames.length; i += 2) {
129
- const left = `${color__default.green("\u25CF")} ${integrationNames[i]}`;
130
- const right = integrationNames[i + 1] ? `${color__default.green("\u25CF")} ${integrationNames[i + 1]}` : "";
131
- const spacing = " ".repeat(Math.max(1, 16 - integrationNames[i].length));
132
- lines.push(` ${left}${spacing}${right}`);
133
- }
134
- }
135
- return lines.join("\n");
136
- }
137
- function formatMonorepoConfigSummary(options) {
138
- const lines = [];
139
- const VALUE_COL = 27;
140
- const formatRow = (label, value, indent = "") => {
141
- const fullLabel = indent + label;
142
- const dotCount = Math.max(1, VALUE_COL - fullLabel.length - 1);
143
- const dots = color__default.gray(".".repeat(dotCount));
144
- return `${indent}${label} ${dots} ${value}`;
145
- };
146
- lines.push(formatRow("Node version", options.nodeVersion || "latest"));
147
- lines.push(formatRow("Package manager", options.packageManager || "pnpm"));
148
- if (options.packageManager === "pnpm") {
149
- const versionManaged = options.pnpmManageVersions ? "yes" : "no";
150
- lines.push(formatRow("\u21B3 Version managed", versionManaged, ""));
151
- }
152
- lines.push(formatRow("Linter", options.linter));
153
- lines.push(formatRow("Formatter", options.formatter));
154
- return lines.join("\n");
155
- }
156
-
157
- const config = new Conf__default({
158
- projectName: "create-krispya"
159
- });
160
- function getPreferredEditor() {
161
- return config.get("preferredEditor");
162
- }
163
- function setPreferredEditor(editor) {
164
- config.set("preferredEditor", editor);
165
- }
166
- function getReuseWindow() {
167
- return config.get("reuseWindow") ?? false;
168
- }
169
- function setReuseWindow(reuse) {
170
- config.set("reuseWindow", reuse);
171
- }
172
- function getAiPlatforms() {
173
- return config.get("aiPlatforms");
174
- }
175
- function setAiPlatforms(platforms) {
176
- config.set("aiPlatforms", platforms);
177
- }
178
- function getConfigStrategy() {
179
- return config.get("configStrategy") ?? "stealth";
180
- }
181
- function clearConfig() {
182
- config.clear();
183
- }
184
- function getConfigPath() {
185
- return config.path;
186
- }
187
- function getCustomTemplates() {
188
- return config.get("customTemplates") ?? {};
189
- }
190
-
191
- function getDefaultOptions(template, name, projectType = "app", libraryBundler, integrations, inheritedSettings) {
192
- const baseTemplate = index.getBaseTemplate(template);
193
- const base = {
194
- name,
195
- template,
196
- projectType,
197
- libraryBundler: projectType === "library" ? libraryBundler ?? "unbuild" : void 0,
198
- packageManager: inheritedSettings?.packageManager ?? "pnpm",
199
- pnpmManageVersions: inheritedSettings?.pnpmManageVersions ?? true,
200
- nodeVersion: inheritedSettings?.nodeVersion ?? "latest",
201
- linter: inheritedSettings?.linter ?? "oxlint",
202
- formatter: inheritedSettings?.formatter ?? "prettier",
203
- // Libraries get vitest by default, apps don't
204
- testing: projectType === "library" ? "vitest" : "none",
205
- configStrategy: getConfigStrategy()
206
- };
207
- if (baseTemplate === "r3f" && integrations) {
208
- return {
209
- ...base,
210
- drei: integrations.includes("drei") ? {} : void 0,
211
- handle: integrations.includes("handle") ? {} : void 0,
212
- leva: integrations.includes("leva") ? {} : void 0,
213
- postprocessing: integrations.includes("postprocessing") ? {} : void 0,
214
- rapier: integrations.includes("rapier") ? {} : void 0,
215
- xr: integrations.includes("xr") ? {} : void 0,
216
- uikit: integrations.includes("uikit") ? {} : void 0,
217
- offscreen: integrations.includes("offscreen") ? {} : void 0,
218
- zustand: integrations.includes("zustand") ? {} : void 0,
219
- koota: integrations.includes("koota") ? {} : void 0,
220
- triplex: integrations.includes("triplex") ? {} : void 0,
221
- viverse: integrations.includes("viverse") ? {} : void 0
222
- };
223
- }
224
- return base;
225
- }
226
- function getDefaultProjectName(template) {
227
- const base = index.getBaseTemplate(template);
228
- switch (base) {
229
- case "vanilla":
230
- return `vanilla-${index.generateRandomName()}`;
231
- case "react":
232
- return `react-${index.generateRandomName()}`;
233
- case "r3f":
234
- return `react-three-${index.generateRandomName()}`;
235
- }
236
- }
237
- async function promptForR3fIntegrations(presets) {
238
- const initialValues = [];
239
- if (presets) {
240
- if (presets.drei) initialValues.push("drei");
241
- if (presets.handle) initialValues.push("handle");
242
- if (presets.leva) initialValues.push("leva");
243
- if (presets.postprocessing) initialValues.push("postprocessing");
244
- if (presets.rapier) initialValues.push("rapier");
245
- if (presets.xr) initialValues.push("xr");
246
- if (presets.uikit) initialValues.push("uikit");
247
- if (presets.offscreen) initialValues.push("offscreen");
248
- if (presets.zustand) initialValues.push("zustand");
249
- if (presets.koota) initialValues.push("koota");
250
- if (presets.triplex) initialValues.push("triplex");
251
- if (presets.viverse) initialValues.push("viverse");
252
- }
253
- const selected = await p__namespace.multiselect({
254
- message: "R3F integrations",
255
- options: [
256
- { value: "drei", label: "Drei" },
257
- { value: "handle", label: "Handle" },
258
- { value: "leva", label: "Leva" },
259
- { value: "postprocessing", label: "Postprocessing" },
260
- { value: "rapier", label: "Rapier" },
261
- { value: "xr", label: "XR" },
262
- { value: "uikit", label: "UIKit" },
263
- { value: "offscreen", label: "Offscreen" },
264
- { value: "zustand", label: "Zustand" },
265
- { value: "koota", label: "Koota" },
266
- { value: "triplex", label: "Triplex" },
267
- { value: "viverse", label: "Viverse" }
268
- ],
269
- initialValues: initialValues.length > 0 ? initialValues : ["drei"],
270
- required: false
271
- });
272
- if (p__namespace.isCancel(selected)) {
273
- p__namespace.cancel("Operation cancelled.");
274
- process.exit(0);
275
- }
276
- return selected;
277
- }
278
- async function promptForCustomization(template, name, projectType, integrations, inheritedSettings, presets) {
279
- let libraryBundler;
280
- if (projectType === "library") {
281
- const bundler = await p__namespace.select({
282
- message: "Library bundler",
283
- options: [
284
- { value: "unbuild", label: "unbuild", hint: "unjs, simple config" },
285
- { value: "tsdown", label: "tsdown", hint: "fast, esbuild-based" }
286
- ],
287
- initialValue: presets?.bundler ?? "unbuild"
288
- });
289
- if (p__namespace.isCancel(bundler)) {
290
- p__namespace.cancel("Operation cancelled.");
291
- process.exit(0);
292
- }
293
- libraryBundler = bundler;
294
- }
295
- let nodeVersion = inheritedSettings?.nodeVersion ?? presets?.nodeVersion ?? "latest";
296
- let finalPackageManager = inheritedSettings?.packageManager ?? presets?.packageManager ?? "pnpm";
297
- let pnpmManageVersions = inheritedSettings?.pnpmManageVersions ?? presets?.pnpmManageVersions ?? true;
298
- if (!inheritedSettings?.nodeVersion) {
299
- const nodeVersionInput = await p__namespace.text({
300
- message: "Node.js version",
301
- placeholder: presets?.nodeVersion ?? "latest",
302
- defaultValue: presets?.nodeVersion ?? "latest",
303
- validate: (value) => {
304
- if (!value.length) return "Required";
305
- if (value !== "latest" && !/^\d+(\.\d+(\.\d+)?)?$/.test(value)) {
306
- return 'Must be "latest" or a valid semver (e.g., "22" or "22.13.0")';
307
- }
308
- }
309
- });
310
- if (p__namespace.isCancel(nodeVersionInput)) {
311
- p__namespace.cancel("Operation cancelled.");
312
- process.exit(0);
313
- }
314
- nodeVersion = nodeVersionInput;
315
- }
316
- if (!inheritedSettings?.packageManager) {
317
- const packageManager = await p__namespace.select({
318
- message: "Package manager",
319
- options: [
320
- { value: "pnpm", label: "pnpm" },
321
- { value: "npm", label: "npm" },
322
- { value: "yarn", label: "yarn" }
323
- ],
324
- initialValue: presets?.packageManager ?? "pnpm"
325
- });
326
- if (p__namespace.isCancel(packageManager)) {
327
- p__namespace.cancel("Operation cancelled.");
328
- process.exit(0);
329
- }
330
- finalPackageManager = packageManager;
331
- if (packageManager === "pnpm") {
332
- const managePnpm = await p__namespace.confirm({
333
- message: "Enable manage-package-manager-versions?",
334
- initialValue: presets?.pnpmManageVersions ?? true
335
- });
336
- if (p__namespace.isCancel(managePnpm)) {
337
- p__namespace.cancel("Operation cancelled.");
338
- process.exit(0);
339
- }
340
- pnpmManageVersions = managePnpm;
341
- }
342
- }
343
- let linter = inheritedSettings?.linter ?? presets?.linter ?? "oxlint";
344
- let formatter = inheritedSettings?.formatter ?? presets?.formatter ?? "prettier";
345
- if (!inheritedSettings?.linter) {
346
- const linterChoice = await p__namespace.select({
347
- message: "Linter",
348
- options: [
349
- { value: "oxlint", label: "Oxlint", hint: "fast, from OXC" },
350
- { value: "eslint", label: "ESLint", hint: "classic" },
351
- { value: "biome", label: "Biome", hint: "all-in-one" }
352
- ],
353
- initialValue: presets?.linter ?? "oxlint"
354
- });
355
- if (p__namespace.isCancel(linterChoice)) {
356
- p__namespace.cancel("Operation cancelled.");
357
- process.exit(0);
358
- }
359
- linter = linterChoice;
360
- }
361
- if (!inheritedSettings?.formatter) {
362
- const formatterChoice = await p__namespace.select({
363
- message: "Formatter",
364
- options: [
365
- { value: "prettier", label: "Prettier", hint: "widely adopted" },
366
- { value: "oxfmt", label: "Oxfmt", hint: "fast, Prettier-compatible" },
367
- { value: "biome", label: "Biome", hint: "all-in-one" }
368
- ],
369
- initialValue: presets?.formatter ?? "prettier"
370
- });
371
- if (p__namespace.isCancel(formatterChoice)) {
372
- p__namespace.cancel("Operation cancelled.");
373
- process.exit(0);
374
- }
375
- formatter = formatterChoice;
376
- }
377
- const testing = await p__namespace.select({
378
- message: "Testing",
379
- options: [
380
- { value: "vitest", label: "Vitest", hint: "fast, Vite-native" },
381
- { value: "none", label: "None" }
382
- ],
383
- initialValue: projectType === "library" ? "vitest" : "none"
384
- });
385
- if (p__namespace.isCancel(testing)) {
386
- p__namespace.cancel("Operation cancelled.");
387
- process.exit(0);
388
- }
389
- const language = await p__namespace.select({
390
- message: "Language",
391
- options: [
392
- { value: "typescript", label: "TypeScript" },
393
- { value: "javascript", label: "JavaScript" }
394
- ],
395
- initialValue: "typescript"
396
- });
397
- if (p__namespace.isCancel(language)) {
398
- p__namespace.cancel("Operation cancelled.");
399
- process.exit(0);
400
- }
401
- const configStrategyChoice = await p__namespace.select({
402
- message: "Config strategy",
403
- options: [
404
- { value: "stealth", label: "stealth", hint: "configs in .config/" },
405
- { value: "root", label: "root", hint: "configs at project root" }
406
- ],
407
- initialValue: getConfigStrategy()
408
- });
409
- if (p__namespace.isCancel(configStrategyChoice)) {
410
- p__namespace.cancel("Operation cancelled.");
411
- process.exit(0);
412
- }
413
- const baseTemplate = index.getBaseTemplate(template);
414
- const finalTemplate = language === "javascript" ? `${baseTemplate}-js` : baseTemplate;
415
- const base = {
416
- name,
417
- template: finalTemplate,
418
- projectType,
419
- libraryBundler: projectType === "library" ? libraryBundler : void 0,
420
- nodeVersion,
421
- packageManager: finalPackageManager,
422
- pnpmManageVersions,
423
- linter,
424
- formatter,
425
- testing,
426
- configStrategy: configStrategyChoice
427
- };
428
- if (baseTemplate === "r3f" && integrations) {
429
- return {
430
- ...base,
431
- drei: integrations.includes("drei") ? {} : void 0,
432
- handle: integrations.includes("handle") ? {} : void 0,
433
- leva: integrations.includes("leva") ? {} : void 0,
434
- postprocessing: integrations.includes("postprocessing") ? {} : void 0,
435
- rapier: integrations.includes("rapier") ? {} : void 0,
436
- xr: integrations.includes("xr") ? {} : void 0,
437
- uikit: integrations.includes("uikit") ? {} : void 0,
438
- offscreen: integrations.includes("offscreen") ? {} : void 0,
439
- zustand: integrations.includes("zustand") ? {} : void 0,
440
- koota: integrations.includes("koota") ? {} : void 0,
441
- triplex: integrations.includes("triplex") ? {} : void 0,
442
- viverse: integrations.includes("viverse") ? {} : void 0
443
- };
444
- }
445
- return base;
446
- }
447
- async function promptForInitialPackage() {
448
- const choice = await p__namespace.select({
449
- message: "Add an initial package?",
450
- options: [
451
- { value: "app", label: "Application" },
452
- { value: "library", label: "Library" },
453
- { value: "skip", label: "Skip" }
454
- ],
455
- initialValue: "app"
456
- });
457
- if (p__namespace.isCancel(choice)) {
458
- p__namespace.cancel("Operation cancelled.");
459
- process.exit(0);
460
- }
461
- return choice;
462
- }
463
- function getDefaultMonorepoOptions(name) {
464
- return {
465
- name,
466
- projectType: "monorepo",
467
- packageManager: "pnpm",
468
- pnpmManageVersions: true,
469
- nodeVersion: "latest",
470
- linter: "oxlint",
471
- formatter: "prettier"
472
- };
473
- }
474
- async function promptForMonorepoCustomization(name, presets) {
475
- const nodeVersion = await p__namespace.text({
476
- message: "Node.js version",
477
- placeholder: presets?.nodeVersion ?? "latest",
478
- defaultValue: presets?.nodeVersion ?? "latest",
479
- validate: (value) => {
480
- if (!value.length) return "Required";
481
- if (value !== "latest" && !/^\d+(\.\d+(\.\d+)?)?$/.test(value)) {
482
- return 'Must be "latest" or a valid semver (e.g., "22" or "22.13.0")';
483
- }
484
- }
485
- });
486
- if (p__namespace.isCancel(nodeVersion)) {
487
- p__namespace.cancel("Operation cancelled.");
488
- process.exit(0);
489
- }
490
- const managePnpm = await p__namespace.confirm({
491
- message: "Enable manage-package-manager-versions?",
492
- initialValue: presets?.pnpmManageVersions ?? true
493
- });
494
- if (p__namespace.isCancel(managePnpm)) {
495
- p__namespace.cancel("Operation cancelled.");
496
- process.exit(0);
497
- }
498
- const linter = await p__namespace.select({
499
- message: "Linter",
500
- options: [
501
- { value: "oxlint", label: "Oxlint", hint: "fast, from OXC" },
502
- { value: "eslint", label: "ESLint", hint: "classic" },
503
- { value: "biome", label: "Biome", hint: "all-in-one" }
504
- ],
505
- initialValue: presets?.linter ?? "oxlint"
506
- });
507
- if (p__namespace.isCancel(linter)) {
508
- p__namespace.cancel("Operation cancelled.");
509
- process.exit(0);
510
- }
511
- const formatter = await p__namespace.select({
512
- message: "Formatter",
513
- options: [
514
- { value: "prettier", label: "Prettier", hint: "widely adopted" },
515
- { value: "oxfmt", label: "Oxfmt", hint: "fast, Prettier-compatible" },
516
- { value: "biome", label: "Biome", hint: "all-in-one" }
517
- ],
518
- initialValue: presets?.formatter ?? "prettier"
519
- });
520
- if (p__namespace.isCancel(formatter)) {
521
- p__namespace.cancel("Operation cancelled.");
522
- process.exit(0);
523
- }
524
- return {
525
- name,
526
- projectType: "monorepo",
527
- nodeVersion,
528
- packageManager: "pnpm",
529
- pnpmManageVersions: managePnpm,
530
- linter,
531
- formatter
532
- };
533
- }
534
- async function promptForMonorepo(workspaceName, presets) {
535
- const defaultOptions = getDefaultMonorepoOptions(workspaceName);
536
- if (presets) {
537
- if (presets.linter) defaultOptions.linter = presets.linter;
538
- if (presets.formatter) defaultOptions.formatter = presets.formatter;
539
- if (presets.nodeVersion) defaultOptions.nodeVersion = presets.nodeVersion;
540
- if (presets.pnpmManageVersions !== void 0)
541
- defaultOptions.pnpmManageVersions = presets.pnpmManageVersions;
542
- }
543
- p__namespace.note(
544
- formatMonorepoConfigSummary({
545
- name: defaultOptions.name,
546
- nodeVersion: defaultOptions.nodeVersion ?? "latest",
547
- packageManager: defaultOptions.packageManager ?? "pnpm",
548
- pnpmManageVersions: defaultOptions.pnpmManageVersions,
549
- linter: defaultOptions.linter ?? "oxlint",
550
- formatter: defaultOptions.formatter ?? "prettier"
551
- }),
552
- "Workspace Configuration"
553
- );
554
- const proceed = await p__namespace.select({
555
- message: "Proceed with these settings?",
556
- options: [
557
- { value: "continue", label: "Yes, continue" },
558
- { value: "customize", label: "No, customize settings" }
559
- ],
560
- initialValue: "continue"
561
- });
562
- if (p__namespace.isCancel(proceed)) {
563
- p__namespace.cancel("Operation cancelled.");
564
- process.exit(0);
565
- }
566
- if (proceed === "continue") {
567
- return defaultOptions;
568
- }
569
- return promptForMonorepoCustomization(workspaceName, presets);
570
- }
571
- async function promptForOptions(name, presets) {
572
- let projectName = name;
573
- if (!projectName) {
574
- const nameResult = await p__namespace.text({
575
- message: "What is your project named?",
576
- placeholder: index.generateRandomName(),
577
- defaultValue: index.generateRandomName(),
578
- validate: (value) => {
579
- if (!value.length) return "Project name is required";
580
- }
581
- });
582
- if (p__namespace.isCancel(nameResult)) {
583
- p__namespace.cancel("Operation cancelled.");
584
- process.exit(0);
585
- }
586
- projectName = nameResult;
587
- }
588
- const projectType = await p__namespace.select({
589
- message: "Project type",
590
- options: [
591
- { value: "app", label: "Application" },
592
- { value: "library", label: "Library" },
593
- { value: "monorepo", label: "Monorepo" }
594
- ],
595
- initialValue: presets?.type ?? "app"
596
- });
597
- if (p__namespace.isCancel(projectType)) {
598
- p__namespace.cancel("Operation cancelled.");
599
- process.exit(0);
600
- }
601
- if (projectType === "monorepo") {
602
- return promptForMonorepo(projectName, presets);
603
- }
604
- return promptForPackageOptions(
605
- projectName,
606
- projectType,
607
- void 0,
608
- presets
609
- );
610
- }
611
- function customTemplateToOptions(customTemplate, name, projectType, inheritedSettings) {
612
- const baseTemplate = customTemplate.baseTemplate;
613
- const template = baseTemplate;
614
- const base = {
615
- name,
616
- template,
617
- projectType,
618
- packageManager: inheritedSettings?.packageManager ?? "pnpm",
619
- pnpmManageVersions: inheritedSettings?.pnpmManageVersions ?? true,
620
- nodeVersion: inheritedSettings?.nodeVersion ?? "latest",
621
- linter: inheritedSettings?.linter ?? customTemplate.linter,
622
- formatter: inheritedSettings?.formatter ?? customTemplate.formatter,
623
- testing: customTemplate.testing,
624
- configStrategy: customTemplate.configStrategy ?? getConfigStrategy()
625
- };
626
- if (baseTemplate === "r3f" && customTemplate.integrations) {
627
- const integrations = customTemplate.integrations;
628
- return {
629
- ...base,
630
- drei: integrations.includes("drei") ? {} : void 0,
631
- handle: integrations.includes("handle") ? {} : void 0,
632
- leva: integrations.includes("leva") ? {} : void 0,
633
- postprocessing: integrations.includes("postprocessing") ? {} : void 0,
634
- rapier: integrations.includes("rapier") ? {} : void 0,
635
- xr: integrations.includes("xr") ? {} : void 0,
636
- uikit: integrations.includes("uikit") ? {} : void 0,
637
- offscreen: integrations.includes("offscreen") ? {} : void 0,
638
- zustand: integrations.includes("zustand") ? {} : void 0,
639
- koota: integrations.includes("koota") ? {} : void 0,
640
- triplex: integrations.includes("triplex") ? {} : void 0,
641
- viverse: integrations.includes("viverse") ? {} : void 0
642
- };
643
- }
644
- return base;
645
- }
646
- function presetsToInheritedSettings(presets) {
647
- if (!presets) return void 0;
648
- return {
649
- linter: presets.linter,
650
- formatter: presets.formatter,
651
- packageManager: presets.packageManager,
652
- nodeVersion: presets.nodeVersion,
653
- pnpmManageVersions: presets.pnpmManageVersions
654
- };
655
- }
656
- async function promptForPackageOptions(projectName, projectType, inheritedSettings, presets) {
657
- const builtInOptions = [
658
- { value: "vanilla", label: "Vanilla" },
659
- { value: "react", label: "React" },
660
- { value: "r3f", label: "React Three Fiber" }
661
- ];
662
- const customTemplates = getCustomTemplates();
663
- const customOptions = Object.keys(customTemplates).map((name) => ({
664
- value: `custom:${name}`,
665
- label: name,
666
- hint: "saved template"
667
- }));
668
- const allOptions = [...builtInOptions, ...customOptions];
669
- const templateSelection = await p__namespace.select({
670
- message: "Select a template",
671
- options: allOptions,
672
- initialValue: presets?.template ?? "vanilla"
673
- });
674
- if (p__namespace.isCancel(templateSelection)) {
675
- p__namespace.cancel("Operation cancelled.");
676
- process.exit(0);
677
- }
678
- const selection = templateSelection;
679
- if (selection.startsWith("custom:")) {
680
- const customName = selection.slice(7);
681
- const customTemplate = customTemplates[customName];
682
- const defaultOptions2 = customTemplateToOptions(
683
- customTemplate,
684
- projectName,
685
- projectType,
686
- inheritedSettings
687
- );
688
- const configTitle2 = inheritedSettings ? `Template: ${customName} (using workspace settings)` : `Template: ${customName}`;
689
- p__namespace.note(formatConfigSummary(defaultOptions2, inheritedSettings), configTitle2);
690
- const proceed2 = await p__namespace.select({
691
- message: "Proceed with these settings?",
692
- options: [
693
- { value: "continue", label: "Yes, continue" },
694
- { value: "customize", label: "No, customize settings" }
695
- ],
696
- initialValue: "continue"
697
- });
698
- if (p__namespace.isCancel(proceed2)) {
699
- p__namespace.cancel("Operation cancelled.");
700
- process.exit(0);
701
- }
702
- if (proceed2 === "continue") {
703
- return defaultOptions2;
704
- }
705
- return promptForCustomization(
706
- customTemplate.baseTemplate,
707
- projectName,
708
- projectType,
709
- customTemplate.integrations,
710
- inheritedSettings
711
- );
712
- }
713
- const template = selection;
714
- const baseTemplate = index.getBaseTemplate(template);
715
- let integrations;
716
- if (baseTemplate === "r3f") {
717
- integrations = await promptForR3fIntegrations(presets);
718
- }
719
- const defaultOptions = getDefaultOptions(
720
- template,
721
- projectName,
722
- projectType,
723
- presets?.bundler,
724
- integrations,
725
- inheritedSettings ?? presetsToInheritedSettings(presets)
726
- );
727
- const configTitle = inheritedSettings ? "Template Configuration (using workspace settings)" : "Template Configuration";
728
- p__namespace.note(formatConfigSummary(defaultOptions, inheritedSettings), configTitle);
729
- const proceed = await p__namespace.select({
730
- message: "Proceed with these settings?",
731
- options: [
732
- { value: "continue", label: "Yes, continue" },
733
- { value: "customize", label: "No, customize settings" }
734
- ],
735
- initialValue: "continue"
736
- });
737
- if (p__namespace.isCancel(proceed)) {
738
- p__namespace.cancel("Operation cancelled.");
739
- process.exit(0);
740
- }
741
- if (proceed === "continue") {
742
- return defaultOptions;
743
- }
744
- return promptForCustomization(
745
- template,
746
- projectName,
747
- projectType,
748
- integrations,
749
- inheritedSettings,
750
- presets
751
- );
752
- }
753
-
754
- async function checkAnyExists(paths) {
755
- for (const path of paths) {
756
- try {
757
- await promises.access(path, promises.constants.F_OK);
758
- return true;
759
- } catch {
760
- }
761
- }
762
- return false;
763
- }
764
- async function validateWorkspace(monorepoRoot) {
765
- const errors = [];
766
- const tsConfigPath = path.join(monorepoRoot, ".config/typescript/package.json");
767
- try {
768
- await promises.access(tsConfigPath, promises.constants.F_OK);
769
- } catch {
770
- errors.push("Missing .config/typescript package");
771
- }
772
- const linterPaths = [
773
- path.join(monorepoRoot, ".config/oxlint/package.json"),
774
- path.join(monorepoRoot, ".config/eslint/package.json"),
775
- path.join(monorepoRoot, "eslint.config.js"),
776
- path.join(monorepoRoot, "biome.json")
777
- ];
778
- const hasLinter = await checkAnyExists(linterPaths);
779
- if (!hasLinter) {
780
- errors.push(
781
- "Missing linter config (.config/oxlint, .config/eslint, eslint.config.js, or biome.json)"
782
- );
783
- }
784
- const formatterPaths = [
785
- path.join(monorepoRoot, ".config/oxfmt/package.json"),
786
- path.join(monorepoRoot, ".config/prettier/package.json"),
787
- path.join(monorepoRoot, ".prettierrc.json"),
788
- path.join(monorepoRoot, "biome.json")
789
- ];
790
- const hasFormatter = await checkAnyExists(formatterPaths);
791
- if (!hasFormatter) {
792
- errors.push(
793
- "Missing formatter config (.config/oxfmt, .config/prettier, .prettierrc.json, or biome.json)"
794
- );
795
- }
796
- return { valid: errors.length === 0, errors };
797
- }
798
-
799
- async function detectCurrentConfig(root) {
800
- let name = root.split(/[/\\]/).pop() ?? "workspace";
801
- try {
802
- const pkgPath = path.join(root, "package.json");
803
- const content = await promises.readFile(pkgPath, "utf-8");
804
- const pkgJson = JSON.parse(content);
805
- if (pkgJson.name) {
806
- name = pkgJson.name.replace(/^@/, "").replace(/\/.*$/, "");
807
- }
808
- } catch {
809
- }
810
- const tooling = await index.detectTooling(root);
811
- return {
812
- name,
813
- linter: tooling.linter ?? "oxlint",
814
- formatter: tooling.formatter ?? "prettier",
815
- packageManager: "pnpm"
816
- };
817
- }
818
- function generateExpectedFiles(config) {
819
- const { name, linter, formatter, packageManager } = config;
820
- const aiFilesMap = {};
821
- index.generateAiFiles(aiFilesMap, {
822
- name,
823
- packageManager,
824
- linter,
825
- formatter,
826
- isMonorepo: true,
827
- platforms: index.ALL_AI_PLATFORMS
828
- });
829
- const vscodeFiles = {};
830
- index.generateVscodeFiles(vscodeFiles, linter, formatter);
831
- const configPackages = {};
832
- index.generateTypescriptConfigPackage(configPackages);
833
- if (linter === "oxlint") {
834
- index.generateOxlintConfigPackage(configPackages);
835
- } else if (linter === "eslint") {
836
- index.generateEslintConfigPackage(configPackages);
837
- }
838
- if (formatter === "oxfmt") {
839
- index.generateOxfmtConfigPackage(configPackages);
840
- } else if (formatter === "prettier") {
841
- index.generatePrettierConfigPackage(configPackages);
842
- }
843
- const workspaceConfig = {};
844
- const rootConfig = {};
845
- rootConfig[".gitignore"] = {
846
- type: "text",
847
- content: ["node_modules", "dist", "*.tsbuildinfo", ".DS_Store"].join("\n")
848
- };
849
- rootConfig[".gitattributes"] = {
850
- type: "text",
851
- content: `* text=auto eol=lf
852
- *.{cmd,[cC][mM][dD]} text eol=crlf
853
- *.{bat,[bB][aA][tT]} text eol=crlf
854
- `
855
- };
856
- if (linter === "biome" || formatter === "biome") {
857
- const biomeConfig = {
858
- $schema: "https://biomejs.dev/schemas/1.9.4/schema.json",
859
- vcs: {
860
- enabled: true,
861
- clientKind: "git",
862
- useIgnoreFile: true
863
- },
864
- linter: {
865
- enabled: linter === "biome",
866
- rules: {
867
- recommended: true
868
- }
869
- },
870
- formatter: {
871
- enabled: formatter === "biome"
872
- }
873
- };
874
- rootConfig["biome.json"] = {
875
- type: "text",
876
- content: JSON.stringify(biomeConfig, null, 2)
877
- };
878
- }
879
- return {
880
- "ai-files": aiFilesMap,
881
- vscode: vscodeFiles,
882
- "config-packages": configPackages,
883
- "workspace-config": workspaceConfig,
884
- "root-config": rootConfig
885
- };
886
- }
887
- async function fileExists$1(path) {
888
- try {
889
- await promises.access(path, fs.constants.F_OK);
890
- return true;
891
- } catch {
892
- return false;
893
- }
894
- }
895
- async function compareWithDisk(expected, root) {
896
- const categoryLabels = {
897
- "ai-files": "AI Files",
898
- vscode: "VS Code",
899
- "config-packages": "Config Packages",
900
- "workspace-config": "Workspace Config",
901
- "root-config": "Root Config"
902
- };
903
- const categories = [];
904
- for (const [category, files] of Object.entries(expected)) {
905
- const changes = [];
906
- for (const [filePath, file] of Object.entries(files)) {
907
- if (file.type !== "text") continue;
908
- const fullPath = path.join(root, filePath);
909
- const newContent = file.content;
910
- if (await fileExists$1(fullPath)) {
911
- const currentContent = await promises.readFile(fullPath, "utf-8");
912
- if (currentContent === newContent) {
913
- changes.push({
914
- path: filePath,
915
- status: "unchanged",
916
- currentContent,
917
- newContent
918
- });
919
- } else {
920
- changes.push({
921
- path: filePath,
922
- status: "modified",
923
- currentContent,
924
- newContent
925
- });
926
- }
927
- } else {
928
- changes.push({
929
- path: filePath,
930
- status: "added",
931
- newContent
932
- });
933
- }
934
- }
935
- if (changes.length === 0) continue;
936
- const hasUserModifications = changes.some((c) => c.status === "modified");
937
- categories.push({
938
- category,
939
- label: categoryLabels[category],
940
- changes,
941
- hasUserModifications
942
- });
943
- }
944
- return categories;
945
- }
946
- async function getWorkspaceConfigUpdates(root) {
947
- const workspacePath = path.join(root, "pnpm-workspace.yaml");
948
- const changes = [];
949
- let currentContent = "";
950
- let exists = false;
951
- try {
952
- currentContent = await promises.readFile(workspacePath, "utf-8");
953
- exists = true;
954
- } catch {
955
- }
956
- if (!exists) {
957
- const newContent = `manage-package-manager-versions: true
958
-
959
- packages:
960
- - ".config/*"
961
- - "apps/*"
962
- - "packages/*"
963
-
964
- onlyBuiltDependencies:
965
- - esbuild
966
- `;
967
- changes.push({
968
- path: "pnpm-workspace.yaml",
969
- status: "added",
970
- newContent
971
- });
972
- return changes;
973
- }
974
- let updatedContent = currentContent;
975
- let needsUpdate = false;
976
- if (!currentContent.includes("manage-package-manager-versions")) {
977
- updatedContent = `manage-package-manager-versions: true
978
-
979
- ${updatedContent}`;
980
- needsUpdate = true;
981
- }
982
- if (!currentContent.includes("onlyBuiltDependencies")) {
983
- updatedContent = `${updatedContent.trimEnd()}
984
-
985
- onlyBuiltDependencies:
986
- - esbuild
987
- `;
988
- needsUpdate = true;
989
- }
990
- if (!currentContent.includes(".config/*") && !currentContent.includes('".config/*"')) {
991
- const lines = updatedContent.split("\n");
992
- const packagesIndex = lines.findIndex(
993
- (line) => line.trim().startsWith("packages:")
994
- );
995
- if (packagesIndex !== -1) {
996
- lines.splice(packagesIndex + 1, 0, ' - ".config/*"');
997
- updatedContent = lines.join("\n");
998
- needsUpdate = true;
999
- }
1000
- }
1001
- if (needsUpdate) {
1002
- changes.push({
1003
- path: "pnpm-workspace.yaml",
1004
- status: "modified",
1005
- currentContent,
1006
- newContent: updatedContent
1007
- });
1008
- } else {
1009
- changes.push({
1010
- path: "pnpm-workspace.yaml",
1011
- status: "unchanged",
1012
- currentContent,
1013
- newContent: currentContent
1014
- });
1015
- }
1016
- return changes;
1017
- }
1018
- async function applyUpdates(changes, root) {
1019
- for (const change of changes) {
1020
- if (change.status === "unchanged") continue;
1021
- const fullPath = path.join(root, change.path);
1022
- await promises.mkdir(path.dirname(fullPath), { recursive: true });
1023
- await promises.writeFile(fullPath, change.newContent);
1024
- }
1025
- }
1026
- function formatFileChange(change) {
1027
- const icon = change.status === "added" ? "+" : change.status === "modified" ? "~" : "=";
1028
- return ` ${icon} ${change.path}`;
1029
- }
1030
- const LINTER_DEPS = {
1031
- oxlint: "oxlint",
1032
- eslint: "eslint",
1033
- biome: "@biomejs/biome"
1034
- };
1035
- const FORMATTER_DEPS = {
1036
- oxfmt: "oxfmt",
1037
- prettier: "prettier",
1038
- biome: "@biomejs/biome"
1039
- };
1040
- const LINTER_CONFIG_PACKAGES = {
1041
- oxlint: "@config/oxlint",
1042
- eslint: "@config/eslint",
1043
- biome: null
1044
- // biome uses root biome.json
1045
- };
1046
- const FORMATTER_CONFIG_PACKAGES = {
1047
- oxfmt: "@config/oxfmt",
1048
- prettier: "@config/prettier",
1049
- biome: null
1050
- // biome uses root biome.json
1051
- };
1052
- function needsMigration(current, target) {
1053
- const linterChange = target.linter && target.linter !== current.linter;
1054
- const formatterChange = target.formatter && target.formatter !== current.formatter;
1055
- return linterChange || formatterChange || false;
1056
- }
1057
- async function getMigrationPlan(current, target, root) {
1058
- const toLinter = target.linter ?? current.linter;
1059
- const toFormatter = target.formatter ?? current.formatter;
1060
- const changes = [];
1061
- if (toLinter !== current.linter) {
1062
- if (current.linter !== "biome") {
1063
- changes.push({
1064
- type: "remove-dir",
1065
- path: `.config/${current.linter}`,
1066
- description: `Remove @config/${current.linter} package`
1067
- });
1068
- }
1069
- if (toLinter !== "biome") {
1070
- const files = {};
1071
- if (toLinter === "oxlint") {
1072
- index.generateOxlintConfigPackage(files);
1073
- } else if (toLinter === "eslint") {
1074
- index.generateEslintConfigPackage(files);
1075
- }
1076
- for (const [path, file] of Object.entries(files)) {
1077
- if (file.type === "text") {
1078
- changes.push({
1079
- type: "add-file",
1080
- path,
1081
- description: `Add ${path}`,
1082
- content: file.content
1083
- });
1084
- }
1085
- }
1086
- }
1087
- if (toLinter === "biome" && toFormatter === "biome") {
1088
- changes.push({
1089
- type: "add-file",
1090
- path: "biome.json",
1091
- description: "Add biome.json config",
1092
- content: JSON.stringify(
1093
- {
1094
- $schema: "https://biomejs.dev/schemas/1.9.4/schema.json",
1095
- vcs: { enabled: true, clientKind: "git", useIgnoreFile: true },
1096
- linter: { enabled: true, rules: { recommended: true } },
1097
- formatter: { enabled: true }
1098
- },
1099
- null,
1100
- 2
1101
- )
1102
- });
1103
- } else if (toLinter === "biome" && toFormatter !== "biome") {
1104
- changes.push({
1105
- type: "add-file",
1106
- path: "biome.json",
1107
- description: "Add biome.json config (linter only)",
1108
- content: JSON.stringify(
1109
- {
1110
- $schema: "https://biomejs.dev/schemas/1.9.4/schema.json",
1111
- vcs: { enabled: true, clientKind: "git", useIgnoreFile: true },
1112
- linter: { enabled: true, rules: { recommended: true } },
1113
- formatter: { enabled: false }
1114
- },
1115
- null,
1116
- 2
1117
- )
1118
- });
1119
- }
1120
- if (current.linter === "biome" && toLinter !== "biome" && current.formatter !== "biome" && toFormatter !== "biome") {
1121
- changes.push({
1122
- type: "remove-file",
1123
- path: "biome.json",
1124
- description: "Remove biome.json"
1125
- });
1126
- }
1127
- }
1128
- if (toFormatter !== current.formatter) {
1129
- const formatterSameAsLinter = current.formatter === current.linter;
1130
- if (current.formatter !== "biome" && !formatterSameAsLinter) {
1131
- changes.push({
1132
- type: "remove-dir",
1133
- path: `.config/${current.formatter}`,
1134
- description: `Remove @config/${current.formatter} package`
1135
- });
1136
- }
1137
- const newFormatterSameAsLinter = toFormatter === toLinter;
1138
- if (toFormatter !== "biome" && !newFormatterSameAsLinter) {
1139
- const files = {};
1140
- if (toFormatter === "oxfmt") {
1141
- index.generateOxfmtConfigPackage(files);
1142
- } else if (toFormatter === "prettier") {
1143
- index.generatePrettierConfigPackage(files);
1144
- }
1145
- for (const [path, file] of Object.entries(files)) {
1146
- if (file.type === "text") {
1147
- changes.push({
1148
- type: "add-file",
1149
- path,
1150
- description: `Add ${path}`,
1151
- content: file.content
1152
- });
1153
- }
1154
- }
1155
- }
1156
- if (toFormatter === "biome" && toLinter !== "biome") {
1157
- changes.push({
1158
- type: "add-file",
1159
- path: "biome.json",
1160
- description: "Add biome.json config (formatter only)",
1161
- content: JSON.stringify(
1162
- {
1163
- $schema: "https://biomejs.dev/schemas/1.9.4/schema.json",
1164
- vcs: { enabled: true, clientKind: "git", useIgnoreFile: true },
1165
- linter: { enabled: false },
1166
- formatter: { enabled: true }
1167
- },
1168
- null,
1169
- 2
1170
- )
1171
- });
1172
- }
1173
- if (current.formatter === "biome" && toFormatter !== "biome" && current.linter !== "biome" && toLinter !== "biome") {
1174
- changes.push({
1175
- type: "remove-file",
1176
- path: "biome.json",
1177
- description: "Remove biome.json"
1178
- });
1179
- }
1180
- }
1181
- changes.push({
1182
- type: "update-package-json",
1183
- path: "package.json",
1184
- description: "Update root package.json (devDependencies, scripts)"
1185
- });
1186
- const subPackageUpdates = await getSubPackageUpdates(
1187
- root,
1188
- current,
1189
- toLinter,
1190
- toFormatter
1191
- );
1192
- return {
1193
- fromLinter: current.linter,
1194
- toLinter,
1195
- fromFormatter: current.formatter,
1196
- toFormatter,
1197
- changes,
1198
- subPackageUpdates
1199
- };
1200
- }
1201
- async function getSubPackageUpdates(root, current, toLinter, toFormatter) {
1202
- const updates = [];
1203
- const workspacePath = path.join(root, "pnpm-workspace.yaml");
1204
- let workspaceContent;
1205
- try {
1206
- workspaceContent = await promises.readFile(workspacePath, "utf-8");
1207
- } catch {
1208
- return updates;
1209
- }
1210
- const packageGlobs = index.parseWorkspaceYamlContent(workspaceContent);
1211
- for (const glob of packageGlobs) {
1212
- if (glob.includes(".config")) continue;
1213
- const baseDir = glob.replace(/\/\*$/, "").replace(/^["']|["']$/g, "");
1214
- const basePath = path.join(root, baseDir);
1215
- try {
1216
- const entries = await promises.readdir(basePath, { withFileTypes: true });
1217
- for (const entry of entries) {
1218
- if (!entry.isDirectory()) continue;
1219
- const pkgJsonPath = path.join(basePath, entry.name, "package.json");
1220
- try {
1221
- const content = await promises.readFile(pkgJsonPath, "utf-8");
1222
- const pkg = JSON.parse(content);
1223
- const devDeps = pkg.devDependencies ?? {};
1224
- const remove = [];
1225
- const add = [];
1226
- const oldLinterPkg = LINTER_CONFIG_PACKAGES[current.linter];
1227
- const newLinterPkg = LINTER_CONFIG_PACKAGES[toLinter];
1228
- if (oldLinterPkg && oldLinterPkg !== newLinterPkg && devDeps[oldLinterPkg]) {
1229
- remove.push(oldLinterPkg);
1230
- }
1231
- if (newLinterPkg && newLinterPkg !== oldLinterPkg && oldLinterPkg && devDeps[oldLinterPkg]) {
1232
- add.push(newLinterPkg);
1233
- }
1234
- if (current.formatter !== current.linter) {
1235
- const oldFormatterPkg = FORMATTER_CONFIG_PACKAGES[current.formatter];
1236
- const newFormatterPkg = FORMATTER_CONFIG_PACKAGES[toFormatter];
1237
- if (oldFormatterPkg && oldFormatterPkg !== newFormatterPkg && devDeps[oldFormatterPkg]) {
1238
- remove.push(oldFormatterPkg);
1239
- }
1240
- if (newFormatterPkg && newFormatterPkg !== oldFormatterPkg && oldFormatterPkg && devDeps[oldFormatterPkg]) {
1241
- add.push(newFormatterPkg);
1242
- }
1243
- }
1244
- if (remove.length > 0 || add.length > 0) {
1245
- updates.push({
1246
- path: path.join(baseDir, entry.name, "package.json"),
1247
- remove,
1248
- add
1249
- });
1250
- }
1251
- } catch {
1252
- }
1253
- }
1254
- } catch {
1255
- }
1256
- }
1257
- return updates;
1258
- }
1259
- async function applyMigration(plan, root) {
1260
- for (const change of plan.changes) {
1261
- if (change.type === "remove-dir") {
1262
- const fullPath = path.join(root, change.path);
1263
- try {
1264
- await promises.rm(fullPath, { recursive: true });
1265
- } catch {
1266
- }
1267
- }
1268
- }
1269
- for (const change of plan.changes) {
1270
- if (change.type === "remove-file") {
1271
- const fullPath = path.join(root, change.path);
1272
- try {
1273
- await promises.rm(fullPath);
1274
- } catch {
1275
- }
1276
- }
1277
- }
1278
- for (const change of plan.changes) {
1279
- if (change.type === "add-file" && change.content) {
1280
- const fullPath = path.join(root, change.path);
1281
- await promises.mkdir(path.dirname(fullPath), { recursive: true });
1282
- await promises.writeFile(fullPath, change.content);
1283
- }
1284
- }
1285
- await updateRootPackageJson(root, plan);
1286
- for (const update of plan.subPackageUpdates) {
1287
- await updateSubPackageJson(root, update);
1288
- }
1289
- }
1290
- async function updateRootPackageJson(root, plan) {
1291
- const pkgPath = path.join(root, "package.json");
1292
- const content = await promises.readFile(pkgPath, "utf-8");
1293
- const pkg = JSON.parse(content);
1294
- const devDeps = pkg.devDependencies ?? {};
1295
- const oldLinterDep = LINTER_DEPS[plan.fromLinter];
1296
- delete devDeps[oldLinterDep];
1297
- if (plan.fromFormatter !== plan.fromLinter) {
1298
- const oldFormatterDep = FORMATTER_DEPS[plan.fromFormatter];
1299
- delete devDeps[oldFormatterDep];
1300
- }
1301
- const newLinterDep = LINTER_DEPS[plan.toLinter];
1302
- if (plan.toLinter === "oxlint") {
1303
- devDeps[newLinterDep] = "^1.36.0";
1304
- } else if (plan.toLinter === "eslint") {
1305
- devDeps[newLinterDep] = "^9.17.0";
1306
- } else if (plan.toLinter === "biome") {
1307
- devDeps[newLinterDep] = "^1.9.4";
1308
- }
1309
- if (plan.toFormatter !== plan.toLinter) {
1310
- const newFormatterDep = FORMATTER_DEPS[plan.toFormatter];
1311
- if (plan.toFormatter === "oxfmt") {
1312
- devDeps[newFormatterDep] = "^0.21.0";
1313
- } else if (plan.toFormatter === "prettier") {
1314
- devDeps[newFormatterDep] = "^3.4.2";
1315
- } else if (plan.toFormatter === "biome") {
1316
- devDeps[newFormatterDep] = "^1.9.4";
1317
- }
1318
- }
1319
- pkg.devDependencies = Object.fromEntries(
1320
- Object.entries(devDeps).sort(([a], [b]) => a.localeCompare(b))
1321
- );
1322
- const scripts = pkg.scripts ?? {};
1323
- if (plan.toLinter === "oxlint") {
1324
- scripts.lint = "oxlint .";
1325
- } else if (plan.toLinter === "eslint") {
1326
- scripts.lint = "eslint .";
1327
- } else if (plan.toLinter === "biome") {
1328
- scripts.lint = "biome check .";
1329
- }
1330
- if (plan.toFormatter === "oxfmt") {
1331
- scripts.format = "oxfmt .";
1332
- } else if (plan.toFormatter === "prettier") {
1333
- scripts.format = "prettier --write .";
1334
- } else if (plan.toFormatter === "biome") {
1335
- scripts.format = "biome format . --write";
1336
- }
1337
- pkg.scripts = scripts;
1338
- await promises.writeFile(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
1339
- }
1340
- async function updateSubPackageJson(root, update) {
1341
- const pkgPath = path.join(root, update.path);
1342
- const content = await promises.readFile(pkgPath, "utf-8");
1343
- const pkg = JSON.parse(content);
1344
- const devDeps = pkg.devDependencies ?? {};
1345
- for (const dep of update.remove) {
1346
- delete devDeps[dep];
1347
- }
1348
- for (const dep of update.add) {
1349
- devDeps[dep] = "workspace:*";
1350
- }
1351
- pkg.devDependencies = Object.fromEntries(
1352
- Object.entries(devDeps).sort(([a], [b]) => a.localeCompare(b))
1353
- );
1354
- await promises.writeFile(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
1355
- }
1356
- function formatMigrationChange(change) {
1357
- const icon = change.type === "remove-dir" || change.type === "remove-file" ? "-" : change.type === "add-file" ? "+" : "~";
1358
- return ` ${icon} ${change.description}`;
1359
- }
1360
-
1361
- const require$1 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href)));
1362
- const pkg = require$1("../package.json");
1363
- const META_OPTIONS = [
1364
- "clearConfig",
1365
- "configPath",
1366
- "check",
1367
- "fix",
1368
- "update",
1369
- "yes",
1370
- "workspace",
1371
- "path",
1372
- "dir"
1373
- ];
1374
- function hasConfigOptions(options) {
1375
- return Object.keys(options).some(
1376
- (key) => !META_OPTIONS.includes(key)
1377
- );
1378
- }
1379
- async function fileExists(path) {
1380
- try {
1381
- await promises.access(path, fs.constants.F_OK);
1382
- return true;
1383
- } catch {
1384
- return false;
1385
- }
1386
- }
1387
- async function promptForAiPlatforms(isNonInteractive) {
1388
- const savedPlatforms = getAiPlatforms();
1389
- if (isNonInteractive) {
1390
- return savedPlatforms ?? index.ALL_AI_PLATFORMS;
1391
- }
1392
- if (savedPlatforms && savedPlatforms.length > 0) {
1393
- const savedLabels = savedPlatforms.map((plat) => index.AI_PLATFORM_LABELS[plat]).join(", ");
1394
- const useDefault = await p__namespace.confirm({
1395
- message: `Add AI rules? ${color__default.dim(`(${savedLabels})`)}`,
1396
- initialValue: true
1397
- });
1398
- if (p__namespace.isCancel(useDefault)) {
1399
- return [];
1400
- }
1401
- if (useDefault) {
1402
- return savedPlatforms;
1403
- }
1404
- }
1405
- const selected = await p__namespace.multiselect({
1406
- message: "Add AI rules?",
1407
- options: index.ALL_AI_PLATFORMS.map((platform) => ({
1408
- value: platform,
1409
- label: index.AI_PLATFORM_LABELS[platform],
1410
- hint: index.AI_PLATFORM_HINTS[platform]
1411
- })),
1412
- initialValues: [],
1413
- required: false
1414
- });
1415
- if (p__namespace.isCancel(selected)) {
1416
- return [];
1417
- }
1418
- const platforms = selected;
1419
- if (platforms.length === 0) {
1420
- return [];
1421
- }
1422
- const saveChoice = await p__namespace.confirm({
1423
- message: "Save selection for future projects?",
1424
- initialValue: true
1425
- });
1426
- if (!p__namespace.isCancel(saveChoice) && saveChoice) {
1427
- setAiPlatforms(platforms);
1428
- }
1429
- return platforms;
1430
- }
1431
- async function writeGeneratedFiles(basePath, files) {
1432
- const filePaths = Object.keys(files).sort();
1433
- for (const filePath of filePaths) {
1434
- const fullFilePath = path.join(basePath, filePath);
1435
- await promises.mkdir(path.dirname(fullFilePath), { recursive: true });
1436
- const file = files[filePath];
1437
- if (file.type === "text") {
1438
- await promises.writeFile(fullFilePath, file.content);
1439
- } else {
1440
- const response = await undici.fetch(file.url);
1441
- await promises.writeFile(fullFilePath, response.body);
1442
- }
1443
- }
1444
- }
1445
- function calculateWorkspaceRoot(packagePath) {
1446
- const segments = packagePath.split(/[/\\]/).filter(Boolean);
1447
- return segments.map(() => "..").join("/");
1448
- }
1449
- async function detectMonorepoRoot() {
1450
- let currentDir = process$1.cwd();
1451
- const root = path.resolve("/");
1452
- while (currentDir !== root) {
1453
- const workspaceFile = path.join(currentDir, "pnpm-workspace.yaml");
1454
- try {
1455
- await promises.access(workspaceFile, fs.constants.F_OK);
1456
- const content = await promises.readFile(workspaceFile, "utf-8");
1457
- if (content.includes("packages:")) {
1458
- return currentDir;
1459
- }
1460
- } catch {
1461
- }
1462
- currentDir = path.dirname(currentDir);
1463
- }
1464
- return null;
1465
- }
1466
- async function parseWorkspaceDirectories(monorepoRoot) {
1467
- try {
1468
- const workspaceFile = path.join(monorepoRoot, "pnpm-workspace.yaml");
1469
- const content = await promises.readFile(workspaceFile, "utf-8");
1470
- return index.parseWorkspaceYamlContent(content);
1471
- } catch {
1472
- return [];
1473
- }
1474
- }
1475
- async function detectWorkspaceSettings(monorepoRoot) {
1476
- try {
1477
- const tooling = await index.detectTooling(monorepoRoot);
1478
- const pkgPath = path.join(monorepoRoot, "package.json");
1479
- const content = await promises.readFile(pkgPath, "utf-8");
1480
- const pkgJson = JSON.parse(content);
1481
- let packageManager;
1482
- if (pkgJson.packageManager) {
1483
- packageManager = pkgJson.packageManager.split("@")[0];
1484
- }
1485
- let nodeVersion;
1486
- if (pkgJson.engines?.node) {
1487
- const match = pkgJson.engines.node.match(/(\d+)/);
1488
- if (match) {
1489
- nodeVersion = match[1];
1490
- }
1491
- }
1492
- let pnpmManageVersions;
1493
- try {
1494
- const workspaceFile = path.join(monorepoRoot, "pnpm-workspace.yaml");
1495
- const workspaceContent = await promises.readFile(workspaceFile, "utf-8");
1496
- pnpmManageVersions = workspaceContent.includes(
1497
- "manage-package-manager-versions: true"
1498
- );
1499
- } catch {
1500
- }
1501
- return {
1502
- linter: tooling.linter,
1503
- formatter: tooling.formatter,
1504
- packageManager,
1505
- nodeVersion,
1506
- pnpmManageVersions
1507
- };
1508
- } catch {
1509
- return {};
1510
- }
1511
- }
1512
- async function detectExistingConfigs(monorepoRoot) {
1513
- const configs = {};
1514
- const eslintPath = path.join(monorepoRoot, "eslint.config.js");
1515
- if (await fileExists(eslintPath)) {
1516
- configs.linter = "eslint";
1517
- configs.eslintConfigPath = eslintPath;
1518
- }
1519
- const prettierPath = path.join(monorepoRoot, ".prettierrc.json");
1520
- if (await fileExists(prettierPath)) {
1521
- configs.formatter = "prettier";
1522
- configs.prettierConfigPath = prettierPath;
1523
- }
1524
- const biomePath = path.join(monorepoRoot, "biome.json");
1525
- if (await fileExists(biomePath)) {
1526
- configs.biomeConfigPath = biomePath;
1527
- if (!configs.linter) configs.linter = "biome";
1528
- if (!configs.formatter) configs.formatter = "biome";
1529
- }
1530
- return configs;
1531
- }
1532
- async function getMonorepoScope(monorepoRoot) {
1533
- try {
1534
- const pkgPath = path.join(monorepoRoot, "package.json");
1535
- const content = await promises.readFile(pkgPath, "utf-8");
1536
- const pkgJson = JSON.parse(content);
1537
- if (pkgJson.name) {
1538
- return pkgJson.name.replace(/^@/, "").replace(/\/.*$/, "");
1539
- }
1540
- } catch {
1541
- }
1542
- return monorepoRoot.split(/[/\\]/).pop() ?? "workspace";
1543
- }
1544
- async function getWorkspacePackages(monorepoRoot) {
1545
- const packagesDir = path.join(monorepoRoot, "packages");
1546
- try {
1547
- const { readdir } = await import('fs/promises');
1548
- const entries = await readdir(packagesDir, { withFileTypes: true });
1549
- const names = [];
1550
- for (const entry of entries) {
1551
- if (!entry.isDirectory()) continue;
1552
- try {
1553
- const content = await promises.readFile(
1554
- path.join(packagesDir, entry.name, "package.json"),
1555
- "utf-8"
1556
- );
1557
- const pkg2 = JSON.parse(content);
1558
- if (pkg2.name) names.push(pkg2.name);
1559
- } catch {
1560
- }
1561
- }
1562
- return names;
1563
- } catch {
1564
- return [];
1565
- }
1566
- }
1567
- async function ensureConfigInWorkspace(monorepoRoot) {
1568
- const workspacePath = path.join(monorepoRoot, "pnpm-workspace.yaml");
1569
- let content;
1570
- try {
1571
- content = await promises.readFile(workspacePath, "utf-8");
1572
- } catch {
1573
- content = `packages:
1574
- - ".config/*"
1575
- - "packages/*"
1576
- `;
1577
- await promises.writeFile(workspacePath, content);
1578
- return;
1579
- }
1580
- if (content.includes(".config/*") || content.includes('".config/*"')) {
1581
- return;
1582
- }
1583
- const lines = content.split("\n");
1584
- const packagesIndex = lines.findIndex(
1585
- (line) => line.trim().startsWith("packages:")
1586
- );
1587
- if (packagesIndex === -1) {
1588
- content = `packages:
1589
- - ".config/*"
1590
- ${content}`;
1591
- } else {
1592
- lines.splice(packagesIndex + 1, 0, ' - ".config/*"');
1593
- content = lines.join("\n");
1594
- }
1595
- await promises.writeFile(workspacePath, content);
1596
- }
1597
- async function migrateEslintConfig(monorepoRoot, files) {
1598
- const configBasePath = ".config/eslint";
1599
- const existingConfigPath = path.join(monorepoRoot, "eslint.config.js");
1600
- let existingContent;
1601
- try {
1602
- existingContent = await promises.readFile(existingConfigPath, "utf-8");
1603
- } catch {
1604
- index.generateEslintConfigPackage(files);
1605
- return;
1606
- }
1607
- files[`${configBasePath}/package.json`] = {
1608
- type: "text",
1609
- content: JSON.stringify(
1610
- {
1611
- name: "@config/eslint",
1612
- version: "0.1.0",
1613
- private: true,
1614
- type: "module",
1615
- exports: {
1616
- "./base": "./base.js",
1617
- "./react": "./react.js"
1618
- }
1619
- },
1620
- null,
1621
- 2
1622
- )
1623
- };
1624
- files[`${configBasePath}/README.md`] = {
1625
- type: "text",
1626
- content: `# \`@config/eslint\`
1627
-
1628
- Shared ESLint configurations.
1629
-
1630
- ## Usage
1631
-
1632
- In your package's \`eslint.config.js\`:
1633
-
1634
- \`\`\`js
1635
- import base from "@config/eslint/base";
1636
-
1637
- export default [...base];
1638
- \`\`\`
1639
-
1640
- ## Available Configs
1641
-
1642
- - \`base\` - Base ESLint rules (migrated from root)
1643
- - \`react\` - React-specific rules
1644
- `
1645
- };
1646
- files[`${configBasePath}/base.js`] = {
1647
- type: "text",
1648
- content: existingContent
1649
- };
1650
- files[`${configBasePath}/react.js`] = {
1651
- type: "text",
1652
- content: `import react from "eslint-plugin-react";
1653
- import reactHooks from "eslint-plugin-react-hooks";
1654
-
1655
- export default [
1656
- {
1657
- plugins: {
1658
- react,
1659
- "react-hooks": reactHooks,
1660
- },
1661
- rules: {
1662
- ...react.configs.recommended.rules,
1663
- ...reactHooks.configs.recommended.rules,
1664
- "react/react-in-jsx-scope": "off",
1665
- },
1666
- settings: {
1667
- react: {
1668
- version: "detect",
1669
- },
1670
- },
1671
- },
1672
- ];
1673
- `
1674
- };
1675
- }
1676
- async function migratePrettierConfig(monorepoRoot, files) {
1677
- const configBasePath = ".config/prettier";
1678
- const existingConfigPath = path.join(monorepoRoot, ".prettierrc.json");
1679
- let existingContent;
1680
- try {
1681
- existingContent = await promises.readFile(existingConfigPath, "utf-8");
1682
- } catch {
1683
- index.generatePrettierConfigPackage(files);
1684
- return;
1685
- }
1686
- files[`${configBasePath}/package.json`] = {
1687
- type: "text",
1688
- content: JSON.stringify(
1689
- {
1690
- name: "@config/prettier",
1691
- version: "0.1.0",
1692
- private: true,
1693
- exports: {
1694
- "./base": "./base.json"
1695
- }
1696
- },
1697
- null,
1698
- 2
1699
- )
1700
- };
1701
- files[`${configBasePath}/README.md`] = {
1702
- type: "text",
1703
- content: `# \`@config/prettier\`
1704
-
1705
- Shared Prettier configurations.
1706
-
1707
- ## Usage
1708
-
1709
- In your package's \`.prettierrc\`:
1710
-
1711
- \`\`\`json
1712
- "@config/prettier/base"
1713
- \`\`\`
1714
-
1715
- Or in \`package.json\`:
1716
-
1717
- \`\`\`json
1718
- {
1719
- "prettier": "@config/prettier/base"
1720
- }
1721
- \`\`\`
1722
-
1723
- ## Available Configs
1724
-
1725
- - \`base\` - Base Prettier rules (migrated from root)
1726
- `
1727
- };
1728
- files[`${configBasePath}/base.json`] = {
1729
- type: "text",
1730
- content: existingContent
1731
- };
1732
- }
1733
- async function createPackageInWorkspace(monorepoRoot, packageManager, inheritedSettings, scope) {
1734
- const workspaceDirectories = await parseWorkspaceDirectories(monorepoRoot);
1735
- const defaultDirectories = ["apps", "packages"];
1736
- const hasCustomDirectories = workspaceDirectories.length > 0 && !workspaceDirectories.every((dir) => defaultDirectories.includes(dir));
1737
- const packageType = await promptForInitialPackage();
1738
- if (packageType === "skip") {
1739
- return false;
1740
- }
1741
- const defaultDir = packageType === "app" ? "apps" : "packages";
1742
- const packageNameInput = await p__namespace.text({
1743
- message: "Package name?",
1744
- initialValue: `@${scope}/`,
1745
- validate: (value) => {
1746
- const validationError = index.validatePackageName(value);
1747
- if (validationError) return validationError;
1748
- const dirName = value.includes("/") ? value.split("/").pop() : value;
1749
- if (!dirName) return "Package name is required";
1750
- if (!hasCustomDirectories) {
1751
- const targetPath = path.join(monorepoRoot, defaultDir, dirName);
1752
- try {
1753
- const { statSync } = require$1("fs");
1754
- statSync(targetPath);
1755
- return `Directory ${defaultDir}/${dirName} already exists`;
1756
- } catch {
1757
- }
1758
- }
1759
- }
1760
- });
1761
- if (p__namespace.isCancel(packageNameInput)) {
1762
- return false;
1763
- }
1764
- const scopedName = packageNameInput;
1765
- const shortName = scopedName.includes("/") ? scopedName.split("/").pop() : scopedName;
1766
- const packageOptions = await promptForPackageOptions(
1767
- scopedName,
1768
- packageType,
1769
- inheritedSettings
1770
- );
1771
- let targetDir = defaultDir;
1772
- if (hasCustomDirectories && workspaceDirectories.length > 0) {
1773
- const dirChoice = await p__namespace.select({
1774
- message: "Target directory",
1775
- options: workspaceDirectories.map((dir) => ({
1776
- value: dir,
1777
- label: dir
1778
- })),
1779
- initialValue: workspaceDirectories.includes(defaultDir) ? defaultDir : workspaceDirectories[0]
1780
- });
1781
- if (p__namespace.isCancel(dirChoice)) {
1782
- return false;
1783
- }
1784
- targetDir = dirChoice;
1785
- const targetPath = path.join(monorepoRoot, targetDir, shortName);
1786
- try {
1787
- const { statSync } = require$1("fs");
1788
- statSync(targetPath);
1789
- p__namespace.log.error(`Directory ${targetDir}/${shortName} already exists`);
1790
- return false;
1791
- } catch {
1792
- }
1793
- }
1794
- const relativePkgPath = path.join(targetDir, shortName);
1795
- const workspaceRoot = calculateWorkspaceRoot(relativePkgPath);
1796
- packageOptions.workspaceRoot = workspaceRoot;
1797
- packageOptions.name = scopedName;
1798
- if (packageManager === "pnpm") {
1799
- packageOptions.pnpmVersion = await index.getLatestPnpmVersion();
1800
- } else if (packageManager === "yarn") {
1801
- packageOptions.yarnVersion = await index.getLatestYarnVersion();
1802
- } else if (packageManager === "npm") {
1803
- packageOptions.npmVersion = await index.getLatestNpmCliVersion();
1804
- }
1805
- const nodeVersion = packageOptions.nodeVersion ?? "latest";
1806
- if (nodeVersion === "latest") {
1807
- packageOptions.nodeVersion = await index.getLatestNodeVersion();
1808
- }
1809
- const versions = {};
1810
- const versionPromises = [];
1811
- const pkgIsLibrary = packageOptions.projectType === "library";
1812
- const pkgTesting = packageOptions.testing ?? (pkgIsLibrary ? "vitest" : "none");
1813
- if (pkgTesting === "vitest") {
1814
- versionPromises.push(
1815
- index.getLatestNpmVersion("vitest", "4.0.0").then((v) => {
1816
- versions.vitest = v;
1817
- })
1818
- );
1819
- }
1820
- if (!pkgIsLibrary) {
1821
- versionPromises.push(
1822
- index.getLatestNpmVersion("vite", "6.3.4").then((v) => {
1823
- versions.vite = v;
1824
- })
1825
- );
1826
- }
1827
- const linter = packageOptions.linter ?? "oxlint";
1828
- if (linter === "eslint") {
1829
- versionPromises.push(
1830
- index.getLatestNpmVersion("eslint", "9.17.0").then((v) => {
1831
- versions.eslint = v;
1832
- })
1833
- );
1834
- } else if (linter === "oxlint") {
1835
- versionPromises.push(
1836
- index.getLatestNpmVersion("oxlint", "0.16.0").then((v) => {
1837
- versions.oxlint = v;
1838
- })
1839
- );
1840
- } else if (linter === "biome") {
1841
- versionPromises.push(
1842
- index.getLatestNpmVersion("@biomejs/biome", "1.9.4").then((v) => {
1843
- versions.biome = v;
1844
- })
1845
- );
1846
- }
1847
- const formatter = packageOptions.formatter ?? "prettier";
1848
- if (formatter === "prettier") {
1849
- versionPromises.push(
1850
- index.getLatestNpmVersion("prettier", "3.4.2").then((v) => {
1851
- versions.prettier = v;
1852
- })
1853
- );
1854
- } else if (formatter === "oxfmt") {
1855
- versionPromises.push(
1856
- index.getLatestNpmVersion("oxfmt", "0.1.0").then((v) => {
1857
- versions.oxfmt = v;
1858
- })
1859
- );
1860
- } else if (formatter === "biome" && linter !== "biome") {
1861
- versionPromises.push(
1862
- index.getLatestNpmVersion("@biomejs/biome", "1.9.4").then((v) => {
1863
- versions.biome = v;
1864
- })
1865
- );
1866
- }
1867
- await Promise.all(versionPromises);
1868
- packageOptions.versions = versions;
1869
- const workspacePackages = packageType === "app" ? await getWorkspacePackages(monorepoRoot) : [];
1870
- if (workspacePackages.length > 0) {
1871
- const selectedDeps = await p__namespace.multiselect({
1872
- message: "Add workspace dependencies?",
1873
- options: workspacePackages.map((name) => ({ value: name, label: name })),
1874
- required: false
1875
- });
1876
- if (!p__namespace.isCancel(selectedDeps) && selectedDeps.length > 0) {
1877
- packageOptions.workspaceDependencies = selectedDeps;
1878
- }
1879
- }
1880
- const outputPath = path.join(monorepoRoot, relativePkgPath);
1881
- const spinner = p__namespace.spinner();
1882
- spinner.start("Creating package...");
1883
- try {
1884
- const files = index.generate(packageOptions);
1885
- await writeGeneratedFiles(outputPath, files);
1886
- spinner.stop(
1887
- color__default.green.inverse(` \u2713 Package created at ${relativePkgPath}! `)
1888
- );
1889
- const addAnother = await p__namespace.select({
1890
- message: "Add another package?",
1891
- options: [
1892
- { value: "no", label: "No, I'm done" },
1893
- { value: "yes", label: "Yes, add another" }
1894
- ],
1895
- initialValue: "no"
1896
- });
1897
- return !p__namespace.isCancel(addAnother) && addAnother === "yes";
1898
- } catch (error) {
1899
- spinner.stop("Failed to create package");
1900
- p__namespace.log.error(String(error));
1901
- return false;
1902
- }
1903
- }
1904
- async function promptAndOpenEditor(projectPath) {
1905
- const savedEditor = getPreferredEditor();
1906
- let selectedEditor;
1907
- if (savedEditor && savedEditor !== "skip") {
1908
- const useDefault = await p__namespace.confirm({
1909
- message: `Open in editor? ${color__default.dim(`(${editorNames[savedEditor]})`)}`,
1910
- initialValue: true
1911
- });
1912
- if (p__namespace.isCancel(useDefault)) {
1913
- selectedEditor = void 0;
1914
- } else if (useDefault) {
1915
- selectedEditor = savedEditor;
1916
- } else {
1917
- selectedEditor = "skip";
1918
- }
1919
- } else {
1920
- const openEditor = await p__namespace.select({
1921
- message: "Open project in editor?",
1922
- options: [
1923
- { value: "skip", label: "Skip" },
1924
- { value: "cursor", label: "Cursor" },
1925
- { value: "code", label: "VS Code" },
1926
- { value: "webstorm", label: "WebStorm" }
1927
- ],
1928
- initialValue: "skip"
1929
- });
1930
- if (!p__namespace.isCancel(openEditor)) {
1931
- selectedEditor = openEditor;
1932
- const saveChoice = await p__namespace.confirm({
1933
- message: `Save ${editorNames[selectedEditor] ?? "Skip"} as default editor?`,
1934
- initialValue: true
1935
- });
1936
- if (!p__namespace.isCancel(saveChoice) && saveChoice) {
1937
- setPreferredEditor(selectedEditor);
1938
- if (selectedEditor === "cursor" || selectedEditor === "code") {
1939
- const reuseChoice = await p__namespace.confirm({
1940
- message: "Reuse current window when opening projects?",
1941
- initialValue: false
1942
- });
1943
- if (!p__namespace.isCancel(reuseChoice)) {
1944
- setReuseWindow(reuseChoice);
1945
- }
1946
- }
1947
- }
1948
- }
1949
- }
1950
- if (selectedEditor && selectedEditor !== "skip") {
1951
- try {
1952
- await openInEditor(
1953
- selectedEditor,
1954
- projectPath,
1955
- getReuseWindow()
1956
- );
1957
- p__namespace.log.success(`Opening in ${editorNames[selectedEditor]}...`);
1958
- } catch {
1959
- p__namespace.log.warn(
1960
- `Could not open ${editorNames[selectedEditor]}. Make sure the CLI command is in your PATH.`
1961
- );
1962
- }
1963
- }
1964
- }
1965
- async function handleCheckCommand() {
1966
- const monorepoRoot = await detectMonorepoRoot();
1967
- if (!monorepoRoot) {
1968
- console.log(color__default.red("\u2717") + " Not a monorepo workspace");
1969
- process.exit(1);
1970
- }
1971
- const { valid, errors } = await validateWorkspace(monorepoRoot);
1972
- if (valid) {
1973
- console.log(color__default.green("\u2713") + " Valid monorepo workspace");
1974
- console.log(color__default.dim(` ${monorepoRoot}`));
1975
- } else {
1976
- console.log(color__default.red("\u2717") + " Invalid monorepo workspace");
1977
- console.log(color__default.dim(` ${monorepoRoot}`));
1978
- for (const error of errors) {
1979
- console.log(color__default.red(` \u2022 ${error}`));
1980
- }
1981
- }
1982
- process.exit(valid ? 0 : 1);
1983
- }
1984
- async function handleFixCommand(options) {
1985
- const monorepoRoot = await detectMonorepoRoot();
1986
- if (!monorepoRoot) {
1987
- console.log(color__default.red("\u2717") + " Not a monorepo workspace");
1988
- console.log(color__default.dim(" Run this command from within a monorepo"));
1989
- process.exit(1);
1990
- }
1991
- const { valid, errors } = await validateWorkspace(monorepoRoot);
1992
- if (valid) {
1993
- console.log(color__default.green("\u2713") + " Workspace is already valid");
1994
- console.log(color__default.dim(` ${monorepoRoot}`));
1995
- process.exit(0);
1996
- }
1997
- console.log(color__default.yellow("!") + " Invalid monorepo workspace");
1998
- for (const error of errors) {
1999
- console.log(color__default.dim(` \u2022 ${error}`));
2000
- }
2001
- console.log();
2002
- const tooling = await detectWorkspaceSettings(monorepoRoot);
2003
- const existingConfigs = await detectExistingConfigs(monorepoRoot);
2004
- const detectedLinter = tooling.linter ?? existingConfigs.linter ?? "oxlint";
2005
- const detectedFormatter = tooling.formatter ?? existingConfigs.formatter ?? "prettier";
2006
- const isNonInteractive = Boolean(options.linter && options.formatter);
2007
- let linter;
2008
- let formatter;
2009
- if (isNonInteractive) {
2010
- linter = options.linter;
2011
- formatter = options.formatter;
2012
- } else {
2013
- const linterChoice = await p__namespace.select({
2014
- message: "Linter",
2015
- options: [
2016
- {
2017
- value: "oxlint",
2018
- label: "oxlint" + (tooling.linter === "oxlint" ? color__default.dim(" (installed)") : "")
2019
- },
2020
- {
2021
- value: "eslint",
2022
- label: "eslint" + (tooling.linter === "eslint" || existingConfigs.linter === "eslint" ? color__default.dim(" (installed)") : "")
2023
- },
2024
- {
2025
- value: "biome",
2026
- label: "biome" + (tooling.linter === "biome" ? color__default.dim(" (installed)") : "")
2027
- }
2028
- ],
2029
- initialValue: detectedLinter
2030
- });
2031
- if (p__namespace.isCancel(linterChoice)) {
2032
- p__namespace.cancel("Operation cancelled.");
2033
- process.exit(0);
2034
- }
2035
- const formatterChoice = await p__namespace.select({
2036
- message: "Formatter",
2037
- options: [
2038
- {
2039
- value: "oxfmt",
2040
- label: "oxfmt" + (tooling.formatter === "oxfmt" ? color__default.dim(" (installed)") : "")
2041
- },
2042
- {
2043
- value: "prettier",
2044
- label: "prettier" + (tooling.formatter === "prettier" || existingConfigs.formatter === "prettier" ? color__default.dim(" (installed)") : "")
2045
- },
2046
- {
2047
- value: "biome",
2048
- label: "biome" + (tooling.formatter === "biome" ? color__default.dim(" (installed)") : "")
2049
- }
2050
- ],
2051
- initialValue: detectedFormatter
2052
- });
2053
- if (p__namespace.isCancel(formatterChoice)) {
2054
- p__namespace.cancel("Operation cancelled.");
2055
- process.exit(0);
2056
- }
2057
- linter = linterChoice;
2058
- formatter = formatterChoice;
2059
- }
2060
- console.log();
2061
- const spinner = p__namespace.spinner();
2062
- spinner.start("Fixing workspace...");
2063
- try {
2064
- const files = {};
2065
- const tsConfigExists = await fileExists(
2066
- path.join(monorepoRoot, ".config/typescript/package.json")
2067
- );
2068
- if (!tsConfigExists) {
2069
- index.generateTypescriptConfigPackage(files);
2070
- }
2071
- if (linter === "oxlint") {
2072
- const oxlintExists = await fileExists(
2073
- path.join(monorepoRoot, ".config/oxlint/package.json")
2074
- );
2075
- if (!oxlintExists) index.generateOxlintConfigPackage(files);
2076
- } else if (linter === "eslint") {
2077
- const eslintPkgExists = await fileExists(
2078
- path.join(monorepoRoot, ".config/eslint/package.json")
2079
- );
2080
- if (!eslintPkgExists) {
2081
- if (existingConfigs.eslintConfigPath) {
2082
- await migrateEslintConfig(monorepoRoot, files);
2083
- } else {
2084
- index.generateEslintConfigPackage(files);
2085
- }
2086
- }
2087
- }
2088
- if (formatter === "oxfmt") {
2089
- const oxfmtExists = await fileExists(
2090
- path.join(monorepoRoot, ".config/oxfmt/package.json")
2091
- );
2092
- if (!oxfmtExists) index.generateOxfmtConfigPackage(files);
2093
- } else if (formatter === "prettier") {
2094
- const prettierPkgExists = await fileExists(
2095
- path.join(monorepoRoot, ".config/prettier/package.json")
2096
- );
2097
- if (!prettierPkgExists) {
2098
- if (existingConfigs.prettierConfigPath) {
2099
- await migratePrettierConfig(monorepoRoot, files);
2100
- } else {
2101
- index.generatePrettierConfigPackage(files);
2102
- }
2103
- }
2104
- }
2105
- if ((linter === "biome" || formatter === "biome") && !existingConfigs.biomeConfigPath) {
2106
- const biomeConfig = {
2107
- $schema: "https://biomejs.dev/schemas/1.9.4/schema.json",
2108
- vcs: {
2109
- enabled: true,
2110
- clientKind: "git",
2111
- useIgnoreFile: true
2112
- },
2113
- linter: {
2114
- enabled: linter === "biome",
2115
- rules: {
2116
- recommended: true
2117
- }
2118
- },
2119
- formatter: {
2120
- enabled: formatter === "biome"
2121
- }
2122
- };
2123
- files["biome.json"] = {
2124
- type: "text",
2125
- content: JSON.stringify(biomeConfig, null, 2)
2126
- };
2127
- }
2128
- for (const [filePath, file] of Object.entries(files)) {
2129
- const fullPath = path.join(monorepoRoot, filePath);
2130
- await promises.mkdir(path.dirname(fullPath), { recursive: true });
2131
- await promises.writeFile(fullPath, file.content);
2132
- }
2133
- await ensureConfigInWorkspace(monorepoRoot);
2134
- if (existingConfigs.eslintConfigPath && linter === "eslint") {
2135
- try {
2136
- await promises.unlink(existingConfigs.eslintConfigPath);
2137
- } catch {
2138
- }
2139
- }
2140
- if (existingConfigs.prettierConfigPath && formatter === "prettier") {
2141
- try {
2142
- await promises.unlink(existingConfigs.prettierConfigPath);
2143
- } catch {
2144
- }
2145
- }
2146
- spinner.stop(color__default.green("\u2713") + " Workspace fixed!");
2147
- const generated = Object.keys(files).filter(
2148
- (f) => f.endsWith("package.json")
2149
- );
2150
- for (const pkgFile of generated) {
2151
- const pkgName = pkgFile.replace("/package.json", "");
2152
- console.log(color__default.dim(` Generated ${pkgName}`));
2153
- }
2154
- const vscodeSettingsExists = await fileExists(
2155
- path.join(monorepoRoot, ".vscode/settings.json")
2156
- );
2157
- const vscodeExtensionsExists = await fileExists(
2158
- path.join(monorepoRoot, ".vscode/extensions.json")
2159
- );
2160
- const vscodeExists = vscodeSettingsExists && vscodeExtensionsExists;
2161
- if (!vscodeExists) {
2162
- let addVscode = false;
2163
- if (isNonInteractive) {
2164
- addVscode = true;
2165
- } else {
2166
- const vscodeChoice = await p__namespace.confirm({
2167
- message: "Generate VS Code settings?",
2168
- initialValue: true
2169
- });
2170
- addVscode = !p__namespace.isCancel(vscodeChoice) && vscodeChoice;
2171
- }
2172
- if (addVscode) {
2173
- const vscodeFiles = {};
2174
- index.generateVscodeFiles(vscodeFiles, linter, formatter);
2175
- for (const [filePath, file] of Object.entries(vscodeFiles)) {
2176
- const fullPath = path.join(monorepoRoot, filePath);
2177
- await promises.mkdir(path.dirname(fullPath), { recursive: true });
2178
- await promises.writeFile(fullPath, file.content);
2179
- }
2180
- console.log(color__default.dim(" Generated .vscode/settings.json"));
2181
- console.log(color__default.dim(" Generated .vscode/extensions.json"));
2182
- }
2183
- }
2184
- const aiRulesExist = await fileExists(
2185
- path.join(monorepoRoot, ".ai/workspace.md")
2186
- );
2187
- if (!aiRulesExist) {
2188
- const platforms = await promptForAiPlatforms(isNonInteractive);
2189
- if (platforms.length > 0) {
2190
- const scope = await getMonorepoScope(monorepoRoot);
2191
- const aiFilesOutput = {};
2192
- index.generateAiFiles(aiFilesOutput, {
2193
- name: scope,
2194
- packageManager: "pnpm",
2195
- linter,
2196
- formatter,
2197
- isMonorepo: true,
2198
- platforms
2199
- });
2200
- for (const [filePath, file] of Object.entries(aiFilesOutput)) {
2201
- const fullPath = path.join(monorepoRoot, filePath);
2202
- await promises.mkdir(path.dirname(fullPath), { recursive: true });
2203
- await promises.writeFile(fullPath, file.content);
2204
- console.log(color__default.dim(` Generated ${filePath}`));
2205
- }
2206
- }
2207
- }
2208
- process.exit(0);
2209
- } catch (error) {
2210
- spinner.stop(color__default.red("\u2717") + " Failed to fix workspace");
2211
- console.error(error);
2212
- process.exit(1);
2213
- }
2214
- }
2215
- async function handleMigration(config, target, root, options) {
2216
- const plan = await getMigrationPlan(config, target, root);
2217
- console.log(color__default.cyan("Migration:"));
2218
- if (plan.fromLinter !== plan.toLinter) {
2219
- console.log(
2220
- ` Linter: ${color__default.dim(plan.fromLinter)} \u2192 ${color__default.green(plan.toLinter)}`
2221
- );
2222
- }
2223
- if (plan.fromFormatter !== plan.toFormatter) {
2224
- console.log(
2225
- ` Formatter: ${color__default.dim(plan.fromFormatter)} \u2192 ${color__default.green(
2226
- plan.toFormatter
2227
- )}`
2228
- );
2229
- }
2230
- console.log();
2231
- console.log(color__default.cyan("Changes:"));
2232
- for (const change of plan.changes) {
2233
- console.log(formatMigrationChange(change));
2234
- }
2235
- if (plan.subPackageUpdates.length > 0) {
2236
- console.log();
2237
- console.log(color__default.cyan(`Sub-packages (${plan.subPackageUpdates.length}):`));
2238
- for (const update of plan.subPackageUpdates) {
2239
- const changes = [
2240
- ...update.remove.map((d) => `-${d}`),
2241
- ...update.add.map((d) => `+${d}`)
2242
- ].join(", ");
2243
- console.log(` ~ ${update.path} (${changes})`);
2244
- }
2245
- }
2246
- console.log();
2247
- if (!options.yes) {
2248
- const confirm = await p__namespace.confirm({
2249
- message: "Apply migration?",
2250
- initialValue: true
2251
- });
2252
- if (p__namespace.isCancel(confirm) || !confirm) {
2253
- console.log(color__default.dim(" Migration cancelled"));
2254
- process.exit(0);
2255
- }
2256
- }
2257
- await applyMigration(plan, root);
2258
- const aiWorkspacePath = path.join(root, ".ai/workspace.md");
2259
- const aiRulesExist = await fileExists(aiWorkspacePath);
2260
- if (aiRulesExist) {
2261
- console.log();
2262
- console.log(color__default.cyan("Updating AI rules..."));
2263
- const scope = await getMonorepoScope(root);
2264
- const existingPlatforms = [];
2265
- if (await fileExists(path.join(root, "AGENTS.md"))) {
2266
- existingPlatforms.push("agents");
2267
- }
2268
- if (await fileExists(path.join(root, "CLAUDE.md"))) {
2269
- existingPlatforms.push("claude");
2270
- }
2271
- const aiFilesOutput = {};
2272
- index.generateAiFiles(aiFilesOutput, {
2273
- name: scope,
2274
- packageManager: "pnpm",
2275
- linter: plan.toLinter,
2276
- formatter: plan.toFormatter,
2277
- isMonorepo: true,
2278
- platforms: existingPlatforms.length > 0 ? existingPlatforms : ["agents"]
2279
- });
2280
- for (const [filePath, file] of Object.entries(aiFilesOutput)) {
2281
- const fullPath = path.join(root, filePath);
2282
- await promises.mkdir(path.dirname(fullPath), { recursive: true });
2283
- await promises.writeFile(fullPath, file.content);
2284
- console.log(color__default.dim(` ${filePath}`));
2285
- }
2286
- }
2287
- console.log();
2288
- console.log(
2289
- color__default.green("\u2713") + ` Migrated to ${plan.toLinter}/${plan.toFormatter}`
2290
- );
2291
- console.log(color__default.dim(" Run `pnpm install` to update dependencies"));
2292
- process.exit(0);
2293
- }
2294
- async function handleUpdateCommand(options) {
2295
- const monorepoRoot = await detectMonorepoRoot();
2296
- if (!monorepoRoot) {
2297
- console.log(color__default.red("\u2717") + " Not a monorepo workspace");
2298
- console.log(color__default.dim(" --update only supports pnpm monorepos"));
2299
- process.exit(1);
2300
- }
2301
- const { valid, errors } = await validateWorkspace(monorepoRoot);
2302
- if (!valid) {
2303
- console.log(color__default.yellow("!") + " Workspace has issues:");
2304
- for (const error of errors) {
2305
- console.log(color__default.dim(` \u2022 ${error}`));
2306
- }
2307
- console.log();
2308
- const shouldFix = options.yes || await p__namespace.confirm({
2309
- message: "Run fix first to resolve these issues?",
2310
- initialValue: true
2311
- });
2312
- if (p__namespace.isCancel(shouldFix) || !shouldFix) {
2313
- console.log(
2314
- color__default.dim(" Run `pnpm create krispya --fix` to fix manually")
2315
- );
2316
- process.exit(1);
2317
- }
2318
- const preFixConfig = await detectCurrentConfig(monorepoRoot);
2319
- const fixOptions = {
2320
- ...options,
2321
- linter: options.linter ?? preFixConfig.linter,
2322
- formatter: options.formatter ?? preFixConfig.formatter
2323
- };
2324
- await handleFixCommand(fixOptions);
2325
- }
2326
- const config = await detectCurrentConfig(monorepoRoot);
2327
- const targetLinter = options.linter;
2328
- const targetFormatter = options.formatter;
2329
- const migrationTarget = { linter: targetLinter, formatter: targetFormatter };
2330
- if (needsMigration(config, migrationTarget)) {
2331
- await handleMigration(config, migrationTarget, monorepoRoot, options);
2332
- return;
2333
- }
2334
- console.log(
2335
- color__default.cyan("Checking for updates...") + color__default.dim(` (${config.linter}/${config.formatter})`)
2336
- );
2337
- console.log();
2338
- const expected = generateExpectedFiles(config);
2339
- const categories = await compareWithDisk(expected, monorepoRoot);
2340
- const workspaceConfigChanges = await getWorkspaceConfigUpdates(monorepoRoot);
2341
- const workspaceCategory = {
2342
- category: "workspace-config",
2343
- label: "Workspace Config",
2344
- changes: workspaceConfigChanges,
2345
- hasUserModifications: workspaceConfigChanges.some(
2346
- (c) => c.status === "modified"
2347
- )
2348
- };
2349
- const allCategories = categories.filter(
2350
- (c) => c.category !== "workspace-config"
2351
- );
2352
- if (workspaceConfigChanges.length > 0) {
2353
- const configPkgIndex = allCategories.findIndex(
2354
- (c) => c.category === "config-packages"
2355
- );
2356
- if (configPkgIndex !== -1) {
2357
- allCategories.splice(configPkgIndex + 1, 0, workspaceCategory);
2358
- } else {
2359
- allCategories.push(workspaceCategory);
2360
- }
2361
- }
2362
- let updatedCount = 0;
2363
- let skippedCount = 0;
2364
- for (const category of allCategories) {
2365
- const newChanges = category.changes.filter((c) => c.status === "added");
2366
- const modifiedChanges = category.changes.filter(
2367
- (c) => c.status === "modified"
2368
- );
2369
- const hasNew = newChanges.length > 0;
2370
- const hasModified = modifiedChanges.length > 0;
2371
- const hasChanges = hasNew || hasModified;
2372
- if (!hasChanges) {
2373
- console.log(color__default.green("\u2713") + ` ${category.label}: Up to date`);
2374
- continue;
2375
- }
2376
- if (category.category === "ai-files") {
2377
- if (hasNew) {
2378
- console.log(color__default.cyan(category.label + ":"));
2379
- console.log(
2380
- color__default.dim(` ${newChanges.length} AI file(s) can be added`)
2381
- );
2382
- console.log();
2383
- const applyAi = options.yes ? true : await p__namespace.confirm({
2384
- message: "Add AI rules?",
2385
- initialValue: true
2386
- });
2387
- if (!p__namespace.isCancel(applyAi) && applyAi) {
2388
- await applyUpdates(newChanges, monorepoRoot);
2389
- console.log(
2390
- color__default.green("\u2713") + ` Added ${newChanges.length} AI file(s)`
2391
- );
2392
- updatedCount++;
2393
- } else {
2394
- console.log(color__default.dim(` Skipped ${category.label}`));
2395
- skippedCount++;
2396
- }
2397
- }
2398
- if (hasModified) {
2399
- console.log(color__default.cyan("AI Files (existing):"));
2400
- for (const change of modifiedChanges) {
2401
- console.log(formatFileChange(change));
2402
- }
2403
- console.log();
2404
- if (options.yes) {
2405
- console.log(color__default.dim(" (--yes mode: keeping existing AI files)"));
2406
- } else {
2407
- const updateExisting = await p__namespace.confirm({
2408
- message: "Update existing AI files to latest template?",
2409
- initialValue: false
2410
- });
2411
- if (!p__namespace.isCancel(updateExisting) && updateExisting) {
2412
- await applyUpdates(modifiedChanges, monorepoRoot);
2413
- console.log(color__default.green("\u2713") + " Updated existing AI files");
2414
- }
2415
- }
2416
- }
2417
- console.log();
2418
- continue;
2419
- }
2420
- let changesToApply = [];
2421
- if (options.yes) {
2422
- console.log(color__default.cyan(category.label + ":"));
2423
- for (const change of [...newChanges, ...modifiedChanges]) {
2424
- console.log(formatFileChange(change));
2425
- }
2426
- console.log();
2427
- if (category.category === "workspace-config") {
2428
- changesToApply = [...newChanges, ...modifiedChanges];
2429
- if (changesToApply.length > 0) {
2430
- console.log(color__default.dim(" (--yes mode: applying merge updates)"));
2431
- }
2432
- } else {
2433
- changesToApply = newChanges;
2434
- if (newChanges.length > 0) {
2435
- console.log(color__default.dim(" (--yes mode: adding new files only)"));
2436
- }
2437
- }
2438
- } else if (hasNew && hasModified) {
2439
- const allChanges = [...newChanges, ...modifiedChanges];
2440
- const selectedFiles = await p__namespace.multiselect({
2441
- message: `${category.label} (+ new, ~ changed)`,
2442
- options: allChanges.map((change) => ({
2443
- value: change.path,
2444
- label: change.status === "added" ? `+ ${change.path}` : `~ ${change.path}`
2445
- })),
2446
- initialValues: newChanges.map((c) => c.path),
2447
- // Pre-select new files
2448
- required: false
2449
- });
2450
- if (p__namespace.isCancel(selectedFiles)) {
2451
- p__namespace.cancel("Operation cancelled.");
2452
- process.exit(0);
2453
- }
2454
- if (selectedFiles.length > 0) {
2455
- changesToApply = allChanges.filter(
2456
- (c) => selectedFiles.includes(c.path)
2457
- );
2458
- }
2459
- } else if (hasNew) {
2460
- console.log(color__default.cyan(category.label + ":"));
2461
- for (const change of newChanges) {
2462
- console.log(formatFileChange(change));
2463
- }
2464
- console.log();
2465
- const shouldAdd = await p__namespace.confirm({
2466
- message: `Add ${newChanges.length} new file(s)?`,
2467
- initialValue: true
2468
- });
2469
- if (p__namespace.isCancel(shouldAdd)) {
2470
- p__namespace.cancel("Operation cancelled.");
2471
- process.exit(0);
2472
- }
2473
- if (shouldAdd) {
2474
- changesToApply = newChanges;
2475
- }
2476
- } else if (hasModified) {
2477
- console.log(color__default.cyan(category.label + ":"));
2478
- for (const change of modifiedChanges) {
2479
- console.log(formatFileChange(change));
2480
- }
2481
- console.log();
2482
- const shouldUpdate = await p__namespace.confirm({
2483
- message: `Update ${modifiedChanges.length} file(s)? (will overwrite)`,
2484
- initialValue: false
2485
- });
2486
- if (p__namespace.isCancel(shouldUpdate)) {
2487
- p__namespace.cancel("Operation cancelled.");
2488
- process.exit(0);
2489
- }
2490
- if (shouldUpdate) {
2491
- changesToApply = modifiedChanges;
2492
- }
2493
- }
2494
- if (changesToApply.length > 0) {
2495
- await applyUpdates(changesToApply, monorepoRoot);
2496
- const addedCount = changesToApply.filter(
2497
- (c) => c.status === "added"
2498
- ).length;
2499
- const updatedFilesCount = changesToApply.filter(
2500
- (c) => c.status === "modified"
2501
- ).length;
2502
- const parts = [];
2503
- if (addedCount > 0) parts.push(`added ${addedCount}`);
2504
- if (updatedFilesCount > 0) parts.push(`updated ${updatedFilesCount}`);
2505
- console.log(color__default.green("\u2713") + ` ${category.label}: ${parts.join(", ")}`);
2506
- updatedCount++;
2507
- } else {
2508
- console.log(color__default.dim(` Skipped ${category.label}`));
2509
- skippedCount++;
2510
- }
2511
- console.log();
2512
- }
2513
- if (updatedCount === 0 && skippedCount === 0) {
2514
- console.log(color__default.green("\u2713") + " Everything is up to date!");
2515
- } else if (updatedCount > 0) {
2516
- console.log(
2517
- color__default.green("\u2713") + ` Updated ${updatedCount} ${updatedCount === 1 ? "category" : "categories"}`
2518
- );
2519
- if (skippedCount > 0) {
2520
- console.log(color__default.dim(` Skipped ${skippedCount}`));
2521
- }
2522
- }
2523
- process.exit(0);
2524
- }
2525
- async function handleWorkspaceCommand(name, options) {
2526
- const monorepoRoot = await detectMonorepoRoot();
2527
- if (!monorepoRoot) {
2528
- console.error(
2529
- color__default.red("Error:") + " --workspace flag requires being inside a monorepo"
2530
- );
2531
- process.exit(1);
2532
- }
2533
- if (!name) {
2534
- console.error(
2535
- color__default.red("Error:") + " Package name is required with --workspace flag"
2536
- );
2537
- console.log(
2538
- color__default.dim(
2539
- " Example: pnpm create krispya my-lib --workspace --type library"
2540
- )
2541
- );
2542
- process.exit(1);
2543
- }
2544
- const scope = await getMonorepoScope(monorepoRoot);
2545
- const inheritedSettings = await detectWorkspaceSettings(monorepoRoot);
2546
- const projectType = options.type ?? "app";
2547
- const defaultDir = projectType === "library" ? "packages" : "apps";
2548
- const targetDir = options.dir ?? defaultDir;
2549
- const template = options.template ?? "vanilla";
2550
- const baseTemplate = index.getBaseTemplate(template);
2551
- const scopedName = name.startsWith("@") ? name : `@${scope}/${name}`;
2552
- const fullPackagePath = path.join(monorepoRoot, targetDir, name);
2553
- try {
2554
- await promises.access(fullPackagePath, fs.constants.F_OK);
2555
- console.error(
2556
- color__default.red("Error:") + ` Directory ${targetDir}/${name} already exists`
2557
- );
2558
- process.exit(1);
2559
- } catch {
2560
- }
2561
- const versions = {};
2562
- const versionPromises = [];
2563
- const isLibrary = projectType === "library";
2564
- if (!isLibrary) {
2565
- versionPromises.push(
2566
- index.getLatestNpmVersion("vite", "6.3.4").then((v) => {
2567
- versions.vite = v;
2568
- })
2569
- );
2570
- }
2571
- const linter = inheritedSettings.linter ?? options.linter ?? "oxlint";
2572
- const formatter = inheritedSettings.formatter ?? options.formatter ?? "prettier";
2573
- const packageManager = inheritedSettings.packageManager ?? "pnpm";
2574
- const nodeVersion = inheritedSettings.nodeVersion ?? "latest";
2575
- const pnpmManageVersions = inheritedSettings.pnpmManageVersions ?? true;
2576
- await Promise.all(versionPromises);
2577
- const relativePkgPath = path.join(targetDir, name);
2578
- const workspaceRoot = calculateWorkspaceRoot(relativePkgPath);
2579
- const generateOptions = {
2580
- name: scopedName,
2581
- projectType,
2582
- libraryBundler: isLibrary ? options.bundler ?? "unbuild" : void 0,
2583
- template,
2584
- linter,
2585
- formatter,
2586
- packageManager,
2587
- nodeVersion,
2588
- pnpmManageVersions,
2589
- workspaceRoot,
2590
- versions,
2591
- ...baseTemplate === "r3f" && {
2592
- drei: options.drei ? {} : void 0,
2593
- handle: options.handle ? {} : void 0,
2594
- leva: options.leva ? {} : void 0,
2595
- postprocessing: options.postprocessing ? {} : void 0,
2596
- rapier: options.rapier ? {} : void 0,
2597
- xr: options.xr ? {} : void 0,
2598
- uikit: options.uikit ? {} : void 0,
2599
- offscreen: options.offscreen ? {} : void 0,
2600
- zustand: options.zustand ? {} : void 0,
2601
- koota: options.koota ? {} : void 0,
2602
- viverse: options.viverse ? {} : void 0,
2603
- triplex: options.triplex ? {} : void 0
2604
- }
2605
- };
2606
- console.log(
2607
- color__default.cyan("Creating") + ` ${scopedName} in ${targetDir}/${name}...`
2608
- );
2609
- try {
2610
- const files = index.generate(generateOptions);
2611
- await writeGeneratedFiles(fullPackagePath, files);
2612
- console.log(
2613
- color__default.green("\u2713") + ` Created ${scopedName} at ${targetDir}/${name}`
2614
- );
2615
- process.exit(0);
2616
- } catch (error) {
2617
- console.error(color__default.red("Error:") + " Failed to create package");
2618
- console.error(String(error));
2619
- process.exit(1);
2620
- }
2621
- }
2622
- async function handleMonorepoCreation(generateOptions, isNonInteractive) {
2623
- const { generateMonorepo } = await import('./chunks/index.cjs').then(function (n) { return n.monorepo; });
2624
- const packageManager = generateOptions.packageManager || "pnpm";
2625
- if (packageManager === "pnpm") {
2626
- generateOptions.pnpmVersion = await index.getLatestPnpmVersion();
2627
- } else if (packageManager === "yarn") {
2628
- generateOptions.yarnVersion = await index.getLatestYarnVersion();
2629
- } else if (packageManager === "npm") {
2630
- generateOptions.npmVersion = await index.getLatestNpmCliVersion();
2631
- }
2632
- const nodeVersion = generateOptions.nodeVersion ?? "latest";
2633
- if (nodeVersion === "latest") {
2634
- generateOptions.nodeVersion = await index.getLatestNodeVersion();
2635
- }
2636
- const aiPlatforms = await promptForAiPlatforms(isNonInteractive);
2637
- const projectPath = path.join(process$1.cwd(), generateOptions.name);
2638
- const spinner = p__namespace.spinner();
2639
- spinner.start("Creating monorepo workspace...");
2640
- try {
2641
- const { files } = generateMonorepo({
2642
- name: generateOptions.name,
2643
- linter: generateOptions.linter ?? "oxlint",
2644
- formatter: generateOptions.formatter ?? "prettier",
2645
- packageManager,
2646
- pnpmVersion: generateOptions.pnpmVersion,
2647
- pnpmManageVersions: generateOptions.pnpmManageVersions,
2648
- nodeVersion: generateOptions.nodeVersion,
2649
- aiPlatforms: aiPlatforms.length > 0 ? aiPlatforms : void 0
2650
- });
2651
- const filePaths = Object.keys(files).sort();
2652
- for (const filePath of filePaths) {
2653
- const fullFilePath = path.join(projectPath, filePath);
2654
- await promises.mkdir(path.dirname(fullFilePath), { recursive: true });
2655
- const file = files[filePath];
2656
- if (file.type === "text") {
2657
- await promises.writeFile(fullFilePath, file.content);
2658
- }
2659
- }
2660
- spinner.stop(color__default.green.inverse(" \u2713 Monorepo workspace created! "));
2661
- if (isNonInteractive) {
2662
- process.exit(0);
2663
- }
2664
- const newWorkspaceSettings = {
2665
- linter: generateOptions.linter,
2666
- formatter: generateOptions.formatter,
2667
- packageManager,
2668
- nodeVersion: generateOptions.nodeVersion,
2669
- pnpmManageVersions: generateOptions.pnpmManageVersions
2670
- };
2671
- const scope = generateOptions.name;
2672
- let addMore = true;
2673
- while (addMore) {
2674
- addMore = await createPackageInWorkspace(
2675
- projectPath,
2676
- packageManager,
2677
- newWorkspaceSettings,
2678
- scope
2679
- );
2680
- }
2681
- const nextSteps = [
2682
- `cd ${generateOptions.name}`,
2683
- `${packageManager} install`,
2684
- `${packageManager} run dev`
2685
- ].join("\n");
2686
- p__namespace.note(nextSteps, "Next steps");
2687
- await promptAndOpenEditor(projectPath);
2688
- p__namespace.outro(color__default.green("Happy coding! \u2728"));
2689
- process.exit(0);
2690
- } catch (error) {
2691
- spinner.stop("Failed to create monorepo workspace");
2692
- p__namespace.log.error(String(error));
2693
- process.exit(1);
2694
- }
2695
- }
2696
- async function handleStandaloneProjectCreation(generateOptions, isNonInteractive) {
2697
- const base = generateOptions.template ? index.getBaseTemplate(generateOptions.template) : "vanilla";
2698
- const defaultFallbackName = base === "vanilla" ? "vanilla-app" : base === "react" ? "react-app" : "react-three-app";
2699
- generateOptions.name ??= defaultFallbackName;
2700
- const aiPlatforms = await promptForAiPlatforms(isNonInteractive);
2701
- if (aiPlatforms.length > 0) {
2702
- generateOptions.aiPlatforms = aiPlatforms;
2703
- }
2704
- const packageManager = generateOptions.packageManager || "pnpm";
2705
- if (packageManager === "pnpm") {
2706
- generateOptions.pnpmVersion = await index.getLatestPnpmVersion();
2707
- } else if (packageManager === "yarn") {
2708
- generateOptions.yarnVersion = await index.getLatestYarnVersion();
2709
- } else if (packageManager === "npm") {
2710
- generateOptions.npmVersion = await index.getLatestNpmCliVersion();
2711
- }
2712
- const nodeVersion = generateOptions.nodeVersion ?? "latest";
2713
- if (nodeVersion === "latest") {
2714
- generateOptions.nodeVersion = await index.getLatestNodeVersion();
2715
- }
2716
- const versions = {};
2717
- const versionPromises = [];
2718
- const isLibrary = generateOptions.projectType === "library";
2719
- const testing = generateOptions.testing ?? (isLibrary ? "vitest" : "none");
2720
- if (testing === "vitest") {
2721
- versionPromises.push(
2722
- index.getLatestNpmVersion("vitest", "4.0.0").then((v) => {
2723
- versions.vitest = v;
2724
- })
2725
- );
2726
- }
2727
- if (!isLibrary) {
2728
- versionPromises.push(
2729
- index.getLatestNpmVersion("vite", "6.3.4").then((v) => {
2730
- versions.vite = v;
2731
- })
2732
- );
2733
- }
2734
- const linter = generateOptions.linter ?? "oxlint";
2735
- if (linter === "eslint") {
2736
- versionPromises.push(
2737
- index.getLatestNpmVersion("eslint", "9.17.0").then((v) => {
2738
- versions.eslint = v;
2739
- })
2740
- );
2741
- } else if (linter === "oxlint") {
2742
- versionPromises.push(
2743
- index.getLatestNpmVersion("oxlint", "0.16.0").then((v) => {
2744
- versions.oxlint = v;
2745
- })
2746
- );
2747
- } else if (linter === "biome") {
2748
- versionPromises.push(
2749
- index.getLatestNpmVersion("@biomejs/biome", "1.9.4").then((v) => {
2750
- versions.biome = v;
2751
- })
2752
- );
2753
- }
2754
- const formatter = generateOptions.formatter ?? "prettier";
2755
- if (formatter === "prettier") {
2756
- versionPromises.push(
2757
- index.getLatestNpmVersion("prettier", "3.4.2").then((v) => {
2758
- versions.prettier = v;
2759
- })
2760
- );
2761
- } else if (formatter === "oxfmt") {
2762
- versionPromises.push(
2763
- index.getLatestNpmVersion("oxfmt", "0.1.0").then((v) => {
2764
- versions.oxfmt = v;
2765
- })
2766
- );
2767
- } else if (formatter === "biome" && linter !== "biome") {
2768
- versionPromises.push(
2769
- index.getLatestNpmVersion("@biomejs/biome", "1.9.4").then((v) => {
2770
- versions.biome = v;
2771
- })
2772
- );
2773
- }
2774
- await Promise.all(versionPromises);
2775
- generateOptions.versions = versions;
2776
- const projectPath = path.join(process$1.cwd(), generateOptions.name);
2777
- const spinner = p__namespace.spinner();
2778
- spinner.start("Creating project...");
2779
- try {
2780
- const files = index.generate(generateOptions);
2781
- await writeGeneratedFiles(projectPath, files);
2782
- spinner.stop(color__default.green.inverse(" \u2713 Project created! "));
2783
- if (isNonInteractive) {
2784
- process.exit(0);
2785
- }
2786
- const nextSteps = isLibrary ? [
2787
- `cd ${generateOptions.name}`,
2788
- `${packageManager} install`,
2789
- `${packageManager} run build`
2790
- ].join("\n") : [
2791
- `cd ${generateOptions.name}`,
2792
- `${packageManager} install`,
2793
- `${packageManager} run dev`
2794
- ].join("\n");
2795
- p__namespace.note(nextSteps, "Next steps");
2796
- await promptAndOpenEditor(projectPath);
2797
- p__namespace.outro(color__default.green("Happy coding! \u2728"));
2798
- } catch (error) {
2799
- spinner.stop("Failed to create project");
2800
- p__namespace.log.error(String(error));
2801
- process.exit(1);
2802
- }
2803
- }
2804
- async function handleInteractiveMonorepoMode(monorepoRoot) {
2805
- const choice = await p__namespace.select({
2806
- message: "Detected monorepo workspace",
2807
- options: [
2808
- { value: "add", label: "Add new package to this workspace" },
2809
- { value: "standalone", label: "Create standalone project" }
2810
- ],
2811
- initialValue: "add"
2812
- });
2813
- if (p__namespace.isCancel(choice)) {
2814
- p__namespace.cancel("Operation cancelled.");
2815
- process.exit(0);
2816
- }
2817
- if (choice === "add") {
2818
- const inheritedSettings = await detectWorkspaceSettings(monorepoRoot);
2819
- const hasSettings = Object.values(inheritedSettings).some(Boolean);
2820
- if (hasSettings) {
2821
- const settingsInfo = [
2822
- inheritedSettings.linter && `linter: ${inheritedSettings.linter}`,
2823
- inheritedSettings.formatter && `formatter: ${inheritedSettings.formatter}`,
2824
- inheritedSettings.packageManager && `pm: ${inheritedSettings.packageManager}`
2825
- ].filter(Boolean).join(", ");
2826
- p__namespace.log.info(`Using workspace settings (${settingsInfo})`);
2827
- }
2828
- const scope = await getMonorepoScope(monorepoRoot);
2829
- let addMore = true;
2830
- while (addMore) {
2831
- addMore = await createPackageInWorkspace(
2832
- monorepoRoot,
2833
- inheritedSettings.packageManager ?? "pnpm",
2834
- inheritedSettings,
2835
- scope
2836
- );
2837
- }
2838
- p__namespace.note(
2839
- [`cd ${monorepoRoot}`, "pnpm install", "pnpm run dev"].join("\n"),
2840
- "Next steps"
2841
- );
2842
- await promptAndOpenEditor(monorepoRoot);
2843
- p__namespace.outro(color__default.green("Happy coding! \u2728"));
2844
- process.exit(0);
2845
- }
2846
- }
2847
- async function main() {
2848
- const program = new commander.Command().name("create-krispya").description(
2849
- "CLI for creating Vanilla, React, and React Three Fiber projects"
2850
- ).argument("[name]", "name for the project").option("--type <type>", "project type: app or library (default: app)").option(
2851
- "--bundler <bundler>",
2852
- "library bundler: unbuild or tsdown (default: unbuild, only for libraries)"
2853
- ).option(
2854
- "--template <type>",
2855
- "project template: vanilla, vanilla-js, react, react-js, r3f, r3f-js (default: vanilla)"
2856
- ).option(
2857
- "--linter <type>",
2858
- "linter: eslint, oxlint, or biome (default: oxlint)"
2859
- ).option(
2860
- "--formatter <type>",
2861
- "formatter: prettier, oxfmt, or biome (default: prettier)"
2862
- ).option("--drei", "add @react-three/drei (r3f only)").option("--handle", "add @react-three/handle (r3f only)").option("--leva", "add leva (r3f only)").option("--postprocessing", "add @react-three/postprocessing (r3f only)").option("--rapier", "add @react-three/rapier (r3f only)").option("--xr", "add @react-three/xr (r3f only)").option("--uikit", "add @react-three/uikit (r3f only)").option("--offscreen", "add @react-three/offscreen (r3f only)").option("--zustand", "add zustand (r3f only)").option("--koota", "add koota (r3f only)").option("--triplex", "set up triplex development environment (r3f only)").option("--viverse", "set up viverse deployment (r3f only)").option(
2863
- "--package-manager <manager>",
2864
- "specify package manager (e.g. npm, yarn, pnpm)"
2865
- ).option(
2866
- "--pnpm-manage-versions",
2867
- "enable manage-package-manager-versions in pnpm-workspace.yaml (default: true)"
2868
- ).option(
2869
- "--no-pnpm-manage-versions",
2870
- "disable manage-package-manager-versions in pnpm-workspace.yaml"
2871
- ).option(
2872
- "--node-version <version>",
2873
- 'set Node.js version for engines.node field (default: "latest")'
2874
- ).option(
2875
- "--workspace",
2876
- "Add package to current monorepo workspace (non-interactive)"
2877
- ).option(
2878
- "--dir <directory>",
2879
- "Target directory for --workspace (default: apps/ or packages/)"
2880
- ).option("--clear-config", "Clear saved preferences (e.g. editor choice)").option("--config-path", "Print the path to the config file").option(
2881
- "--check",
2882
- "Check if current directory is in a valid monorepo workspace"
2883
- ).option("--fix", "Fix monorepo by generating missing .config packages").option("--update", "Update monorepo workspace to latest configuration").option("-y, --yes", "Non-interactive mode - accept all prompts").option(
2884
- "--path <directory>",
2885
- "Run in specified directory instead of current working directory"
2886
- ).action(async (name, options) => {
2887
- if (options.path) {
2888
- process.chdir(options.path);
2889
- }
2890
- if (options.clearConfig) {
2891
- clearConfig();
2892
- console.log("Configuration cleared.");
2893
- process.exit(0);
2894
- }
2895
- if (options.configPath) {
2896
- console.log(getConfigPath());
2897
- process.exit(0);
2898
- }
2899
- if (name?.startsWith("-")) {
2900
- switch (name) {
2901
- case "--version":
2902
- case "-V":
2903
- console.log(pkg.version);
2904
- process.exit(0);
2905
- case "--help":
2906
- case "-h":
2907
- program.help();
2908
- break;
2909
- case "--clear-config":
2910
- clearConfig();
2911
- console.log("Configuration cleared.");
2912
- process.exit(0);
2913
- case "--config-path":
2914
- console.log(getConfigPath());
2915
- process.exit(0);
2916
- case "--check":
2917
- await handleCheckCommand();
2918
- break;
2919
- case "--fix":
2920
- options.fix = true;
2921
- break;
2922
- case "--update":
2923
- options.update = true;
2924
- break;
2925
- case "--yes":
2926
- options.yes = true;
2927
- break;
2928
- default:
2929
- console.error(color__default.red(`Unknown option: ${name}`));
2930
- process.exit(1);
2931
- }
2932
- }
2933
- if (options.check) {
2934
- await handleCheckCommand();
2935
- }
2936
- if (options.fix) {
2937
- await handleFixCommand(options);
2938
- }
2939
- if (options.update) {
2940
- await handleUpdateCommand(options);
2941
- }
2942
- if (options.dir && !options.workspace) {
2943
- console.error(color__default.red("Error:") + " --dir requires --workspace flag");
2944
- console.log(
2945
- color__default.dim(
2946
- " Example: pnpm create krispya my-lib --workspace --dir examples"
2947
- )
2948
- );
2949
- process.exit(1);
2950
- }
2951
- if (options.workspace) {
2952
- await handleWorkspaceCommand(name, options);
2953
- }
2954
- console.clear();
2955
- p__namespace.intro(color__default.bgCyan(color__default.black(` create-krispya v${pkg.version} `)));
2956
- const monorepoRoot = await detectMonorepoRoot();
2957
- if (monorepoRoot && !hasConfigOptions(options)) {
2958
- await handleInteractiveMonorepoMode(monorepoRoot);
2959
- }
2960
- let generateOptions;
2961
- if (options.yes) {
2962
- const template = options.template ?? "vanilla";
2963
- const baseTemplate = index.getBaseTemplate(template);
2964
- const defaultName = getDefaultProjectName(template);
2965
- const projectType = options.type ?? "app";
2966
- generateOptions = {
2967
- name: name || defaultName,
2968
- projectType,
2969
- libraryBundler: projectType === "library" ? options.bundler ?? "unbuild" : void 0,
2970
- template,
2971
- linter: options.linter ?? "oxlint",
2972
- formatter: options.formatter ?? "prettier",
2973
- ...baseTemplate === "r3f" && {
2974
- drei: options.drei ? {} : void 0,
2975
- handle: options.handle ? {} : void 0,
2976
- leva: options.leva ? {} : void 0,
2977
- postprocessing: options.postprocessing ? {} : void 0,
2978
- rapier: options.rapier ? {} : void 0,
2979
- xr: options.xr ? {} : void 0,
2980
- uikit: options.uikit ? {} : void 0,
2981
- offscreen: options.offscreen ? {} : void 0,
2982
- zustand: options.zustand ? {} : void 0,
2983
- koota: options.koota ? {} : void 0,
2984
- viverse: options.viverse ? {} : void 0,
2985
- triplex: options.triplex ? {} : void 0
2986
- },
2987
- packageManager: options.packageManager,
2988
- pnpmManageVersions: options.pnpmManageVersions,
2989
- nodeVersion: options.nodeVersion ?? "latest"
2990
- };
2991
- } else {
2992
- const presets = hasConfigOptions(options) ? {
2993
- type: options.type,
2994
- template: options.template,
2995
- bundler: options.bundler,
2996
- linter: options.linter,
2997
- formatter: options.formatter,
2998
- packageManager: options.packageManager,
2999
- nodeVersion: options.nodeVersion,
3000
- pnpmManageVersions: options.pnpmManageVersions,
3001
- drei: options.drei,
3002
- handle: options.handle,
3003
- leva: options.leva,
3004
- postprocessing: options.postprocessing,
3005
- rapier: options.rapier,
3006
- xr: options.xr,
3007
- uikit: options.uikit,
3008
- offscreen: options.offscreen,
3009
- zustand: options.zustand,
3010
- koota: options.koota,
3011
- triplex: options.triplex,
3012
- viverse: options.viverse
3013
- } : void 0;
3014
- generateOptions = await promptForOptions(name, presets);
3015
- }
3016
- const isNonInteractive = options.yes ?? false;
3017
- if (generateOptions.projectType === "monorepo") {
3018
- await handleMonorepoCreation(generateOptions, isNonInteractive);
3019
- } else {
3020
- await handleStandaloneProjectCreation(generateOptions, isNonInteractive);
3021
- }
3022
- });
3023
- await program.parseAsync();
3024
- }
3025
- main().catch(console.error);