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