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.
@@ -0,0 +1,3226 @@
1
+ import { readFile, access } from 'fs/promises';
2
+ import { constants } from 'fs';
3
+ import { join } from 'path';
4
+ import color from 'chalk';
5
+
6
+ const HtmlContent = `<!DOCTYPE html>
7
+ <html lang="en">
8
+ <head>
9
+ <meta charset="UTF-8">
10
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
11
+ <title>$title</title>
12
+ </head>
13
+ <body style="margin: 0; overscroll-behavior: none; user-select: none; touch-action: none;">
14
+ <script type="module" src="$indexPath"><\/script>
15
+ <div style="width: 100dvw; height: 100dvh; overflow: hidden;" id="root"></div>
16
+ </body>
17
+ </html>`;
18
+ const ViteHtmlContent = `<!DOCTYPE html>
19
+ <html lang="en">
20
+ <head>
21
+ <meta charset="UTF-8">
22
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
23
+ <title>$title</title>
24
+ </head>
25
+ <body>
26
+ <div id="app"></div>
27
+ <script type="module" src="$indexPath"><\/script>
28
+ </body>
29
+ </html>`;
30
+ const IndexContent = `import { StrictMode } from 'react'
31
+ import { createRoot } from 'react-dom/client'
32
+ import { App } from './app.js'
33
+
34
+ createRoot(document.getElementById('root')!).render(
35
+ <StrictMode>
36
+ <App />
37
+ </StrictMode>,
38
+ )`;
39
+ const ViteIndexContent = `import './style.css'
40
+
41
+ document.querySelector('#app')!.innerHTML = \`
42
+ <h1>Hello Vite!</h1>
43
+ <p>Edit src/main.ts and save to see HMR in action.</p>
44
+ \``;
45
+ const ViteStyleContent = `body {
46
+ font-family: system-ui, -apple-system, sans-serif;
47
+ margin: 0;
48
+ padding: 2rem;
49
+ min-height: 100vh;
50
+ background: #1a1a1a;
51
+ color: #fff;
52
+ }
53
+
54
+ h1 {
55
+ color: #646cff;
56
+ }
57
+
58
+ a {
59
+ color: #646cff;
60
+ }`;
61
+ const GitAttributes = [
62
+ "* text eol=lf",
63
+ "*.png binary",
64
+ "*.jpg binary",
65
+ "*.jpeg binary",
66
+ "*.gif binary",
67
+ "*.ico binary",
68
+ "*.mov binary",
69
+ "*.mp4 binary",
70
+ "*.mp3 binary",
71
+ "*.flv binary",
72
+ "*.fla binary",
73
+ "*.wav binary",
74
+ "*.swf binary",
75
+ "*.gz binary",
76
+ "*.zip binary",
77
+ "*.7z binary",
78
+ "*.ttf binary",
79
+ "*.eot binary",
80
+ "*.woff binary",
81
+ "*.pyc binary",
82
+ "*.pdf binary",
83
+ "*.glb binary",
84
+ "*.gltf binary"
85
+ ].join("\n");
86
+ const defaultFormatterConfig = {
87
+ printWidth: 102,
88
+ tabWidth: 2,
89
+ useTabs: false,
90
+ semi: true,
91
+ singleQuote: true,
92
+ trailingComma: "es5",
93
+ bracketSpacing: true,
94
+ arrowParens: "always"
95
+ };
96
+ const defaultPrettierConfig = {
97
+ $schema: "https://json.schemastore.org/prettierrc",
98
+ ...defaultFormatterConfig,
99
+ overrides: [
100
+ {
101
+ files: ["*.md", "**/*.md"],
102
+ options: { semi: false }
103
+ },
104
+ {
105
+ files: ["*.yml", "*.yaml", "**/*.yml", "**/*.yaml"],
106
+ options: { semi: false }
107
+ }
108
+ ]
109
+ };
110
+ const defaultOxfmtConfig = {
111
+ printWidth: defaultFormatterConfig.printWidth,
112
+ tabWidth: defaultFormatterConfig.tabWidth,
113
+ useTabs: defaultFormatterConfig.useTabs,
114
+ semi: defaultFormatterConfig.semi,
115
+ singleQuote: defaultFormatterConfig.singleQuote,
116
+ trailingComma: defaultFormatterConfig.trailingComma,
117
+ bracketSpacing: defaultFormatterConfig.bracketSpacing,
118
+ arrowParens: defaultFormatterConfig.arrowParens
119
+ };
120
+ const defaultLinterConfig = {
121
+ ignorePatterns: ["dist"],
122
+ rules: {
123
+ noUnusedVars: {
124
+ level: "warn",
125
+ argsIgnorePattern: "^_",
126
+ varsIgnorePattern: "^_",
127
+ caughtErrorsIgnorePattern: "^_"
128
+ },
129
+ noUnusedExpressions: {
130
+ level: "warn",
131
+ allowShortCircuit: true
132
+ }
133
+ }
134
+ };
135
+
136
+ const ALL_AI_PLATFORMS = ["agents", "claude"];
137
+ const AI_PLATFORM_LABELS = {
138
+ agents: "AGENTS.md",
139
+ claude: "CLAUDE.md"
140
+ };
141
+ const AI_PLATFORM_HINTS = {
142
+ agents: "OpenAI, Cursor, Windsurf, etc.",
143
+ claude: "Claude Code"
144
+ };
145
+ function generateAiFiles(files, params) {
146
+ const { platforms, isMonorepo, configStrategy, ...rest } = params;
147
+ if (platforms.length === 0) return;
148
+ const content = generateWorkspace({
149
+ ...rest,
150
+ isMonorepo: !!isMonorepo});
151
+ const pointer = "See [`AGENTS.md`](./Agents.md) for agent context.\n";
152
+ const hasAgents = platforms.includes("agents");
153
+ const hasClaude = platforms.includes("claude");
154
+ const isSingleton = platforms.length === 1;
155
+ if (hasAgents) files["AGENTS.md"] = { type: "text", content };
156
+ if (hasClaude) {
157
+ if (isSingleton) {
158
+ files["CLAUDE.md"] = { type: "text", content };
159
+ } else {
160
+ files["CLAUDE.md"] = { type: "text", content: pointer };
161
+ }
162
+ }
163
+ }
164
+ function generateWorkspace(ctx) {
165
+ const { name, packageManager, linter, formatter, isMonorepo} = ctx;
166
+ const sections = [
167
+ `# ${name}`,
168
+ "",
169
+ `- **Type:** ${isMonorepo ? "pnpm monorepo" : "standalone project"}`,
170
+ `- **Package Manager:** ${packageManager}`,
171
+ `- **Linter:** ${linter}`,
172
+ `- **Formatter:** ${formatter}`,
173
+ "",
174
+ "## Commands",
175
+ "",
176
+ `- \`${packageManager} test\` \u2014 run tests`,
177
+ `- \`${packageManager} build\` \u2014 build`,
178
+ `- \`${packageManager} lint\` and \`${packageManager} format\` \u2014 run before committing`
179
+ ];
180
+ if (isMonorepo) {
181
+ sections.push(
182
+ "",
183
+ "- Use `workspace:*` for internal dependencies",
184
+ `- New packages: \`${packageManager} create krispya <name> --workspace\``
185
+ );
186
+ }
187
+ sections.push("");
188
+ return sections.join("\n");
189
+ }
190
+
191
+ function getLanguageFromTemplate(template) {
192
+ return template.endsWith("-js") ? "javascript" : "typescript";
193
+ }
194
+ function getBaseTemplate(template) {
195
+ return template.replace("-js", "");
196
+ }
197
+
198
+ async function getLatestNpmVersion(packageName, fallback) {
199
+ try {
200
+ const response = await fetch(`https://registry.npmjs.org/${packageName}/latest`);
201
+ const data = await response.json();
202
+ return data.version;
203
+ } catch {
204
+ return fallback;
205
+ }
206
+ }
207
+ async function getLatestPnpmVersion() {
208
+ return getLatestNpmVersion("pnpm", "10.11.0");
209
+ }
210
+ async function getLatestYarnVersion() {
211
+ return getLatestNpmVersion("yarn", "4.6.0");
212
+ }
213
+ async function getLatestNpmCliVersion() {
214
+ return getLatestNpmVersion("npm", "11.0.0");
215
+ }
216
+ async function getLatestNodeVersion() {
217
+ try {
218
+ const response = await fetch("https://nodejs.org/dist/index.json");
219
+ const data = await response.json();
220
+ const latestVersion = data[0];
221
+ if (latestVersion) {
222
+ return latestVersion.version.replace(/^v/, "");
223
+ }
224
+ return "25.0.0";
225
+ } catch {
226
+ return "25.0.0";
227
+ }
228
+ }
229
+ function validateNameSegment(segment, label) {
230
+ if (!segment.length) {
231
+ return `${label} is required`;
232
+ }
233
+ if (!/^[a-z0-9-]+$/.test(segment)) {
234
+ return `${label} must be lowercase and contain only letters, numbers, and hyphens`;
235
+ }
236
+ if (segment.startsWith("-") || segment.endsWith("-")) {
237
+ return `${label} cannot start or end with a hyphen`;
238
+ }
239
+ if (segment.includes("--")) {
240
+ return `${label} cannot contain consecutive hyphens`;
241
+ }
242
+ return void 0;
243
+ }
244
+ function validatePackageName(name) {
245
+ if (!name.length) {
246
+ return "Package name is required";
247
+ }
248
+ if (name.includes("..") || name.includes("\\")) {
249
+ return "Package name cannot contain path traversal sequences";
250
+ }
251
+ if (name.startsWith("@")) {
252
+ const slashIndex = name.indexOf("/");
253
+ if (slashIndex === -1) {
254
+ return "Scoped package name must include a package name after the scope (e.g., @scope/name)";
255
+ }
256
+ if (name.indexOf("/", slashIndex + 1) !== -1) {
257
+ return "Package name can only have one slash for scoped packages";
258
+ }
259
+ const scope = name.slice(1, slashIndex);
260
+ const packageName = name.slice(slashIndex + 1);
261
+ const scopeError = validateNameSegment(scope, "Scope");
262
+ if (scopeError) return scopeError;
263
+ const nameError = validateNameSegment(packageName, "Package name");
264
+ if (nameError) return nameError;
265
+ return void 0;
266
+ }
267
+ if (name.includes("/")) {
268
+ return "Unscoped package name cannot contain slashes. Use @scope/name format for scoped packages";
269
+ }
270
+ return validateNameSegment(name, "Package name");
271
+ }
272
+ function parseWorkspaceYamlContent(content) {
273
+ const directories = [];
274
+ let inPackagesSection = false;
275
+ for (const line of content.split("\n")) {
276
+ const trimmed = line.trim();
277
+ if (trimmed === "packages:") {
278
+ inPackagesSection = true;
279
+ continue;
280
+ }
281
+ if (inPackagesSection && trimmed && !line.startsWith(" ") && !line.startsWith(" ") && !trimmed.startsWith("-")) {
282
+ break;
283
+ }
284
+ if (inPackagesSection && trimmed.startsWith("-")) {
285
+ const entry = trimmed.slice(1).trim().replace(/^["']|["']$/g, "").replace(/^\.\//, "").replace(/\/\*.*$/, "");
286
+ if (entry && !entry.startsWith(".")) {
287
+ directories.push(entry);
288
+ }
289
+ }
290
+ }
291
+ return directories;
292
+ }
293
+ async function pathExists(path) {
294
+ try {
295
+ await access(path, constants.F_OK);
296
+ return true;
297
+ } catch {
298
+ return false;
299
+ }
300
+ }
301
+ function detectLinterFromScript(script) {
302
+ if (!script) return void 0;
303
+ if (script.includes("oxlint")) return "oxlint";
304
+ if (script.includes("eslint")) return "eslint";
305
+ if (script.includes("biome check") || script.includes("biome lint")) return "biome";
306
+ return void 0;
307
+ }
308
+ function detectFormatterFromScript(script) {
309
+ if (!script) return void 0;
310
+ if (script.includes("prettier")) return "prettier";
311
+ if (script.includes("oxfmt")) return "oxfmt";
312
+ if (script.includes("biome format")) return "biome";
313
+ return void 0;
314
+ }
315
+ async function detectLinterFromConfig(root) {
316
+ if (await pathExists(join(root, ".config/oxlint"))) return "oxlint";
317
+ if (await pathExists(join(root, ".config/eslint"))) return "eslint";
318
+ if (await pathExists(join(root, "biome.json"))) {
319
+ try {
320
+ const content = await readFile(join(root, "biome.json"), "utf-8");
321
+ const config = JSON.parse(content);
322
+ if (config.linter?.enabled !== false) return "biome";
323
+ } catch {
324
+ return "biome";
325
+ }
326
+ }
327
+ return void 0;
328
+ }
329
+ async function detectFormatterFromConfig(root) {
330
+ if (await pathExists(join(root, ".config/prettier"))) return "prettier";
331
+ if (await pathExists(join(root, ".config/oxfmt"))) return "oxfmt";
332
+ if (await pathExists(join(root, "biome.json"))) {
333
+ try {
334
+ const content = await readFile(join(root, "biome.json"), "utf-8");
335
+ const config = JSON.parse(content);
336
+ if (config.formatter?.enabled !== false) return "biome";
337
+ } catch {
338
+ return "biome";
339
+ }
340
+ }
341
+ return void 0;
342
+ }
343
+ function detectLinterFromDeps(devDeps) {
344
+ if (!devDeps) return void 0;
345
+ if (devDeps["@biomejs/biome"]) return "biome";
346
+ if (devDeps.eslint) return "eslint";
347
+ if (devDeps.oxlint) return "oxlint";
348
+ return void 0;
349
+ }
350
+ function detectFormatterFromDeps(devDeps) {
351
+ if (!devDeps) return void 0;
352
+ if (devDeps["@biomejs/biome"]) return "biome";
353
+ if (devDeps.prettier) return "prettier";
354
+ if (devDeps.oxfmt) return "oxfmt";
355
+ return void 0;
356
+ }
357
+ async function detectTooling(root) {
358
+ try {
359
+ const pkgPath = join(root, "package.json");
360
+ const content = await readFile(pkgPath, "utf-8");
361
+ const pkg = JSON.parse(content);
362
+ const linter = detectLinterFromScript(pkg.scripts?.lint) ?? await detectLinterFromConfig(root) ?? detectLinterFromDeps(pkg.devDependencies);
363
+ const formatter = detectFormatterFromScript(pkg.scripts?.format) ?? await detectFormatterFromConfig(root) ?? detectFormatterFromDeps(pkg.devDependencies);
364
+ return { linter, formatter };
365
+ } catch {
366
+ return { linter: void 0, formatter: void 0 };
367
+ }
368
+ }
369
+ function generateRandomName() {
370
+ const adjectives = [
371
+ "red",
372
+ "blue",
373
+ "green",
374
+ "yellow",
375
+ "purple",
376
+ "orange",
377
+ "pink",
378
+ "black",
379
+ "white",
380
+ "tiny",
381
+ "big",
382
+ "small",
383
+ "large",
384
+ "huge",
385
+ "giant",
386
+ "mini",
387
+ "mega",
388
+ "super",
389
+ "happy",
390
+ "sad",
391
+ "angry",
392
+ "calm",
393
+ "quiet",
394
+ "loud",
395
+ "silent",
396
+ "noisy",
397
+ "shiny",
398
+ "dull",
399
+ "bright",
400
+ "dark",
401
+ "fuzzy",
402
+ "smooth",
403
+ "rough",
404
+ "soft"
405
+ ];
406
+ const nouns = [
407
+ "apple",
408
+ "banana",
409
+ "cherry",
410
+ "date",
411
+ "elderberry",
412
+ "fig",
413
+ "grape",
414
+ "honeydew",
415
+ "cat",
416
+ "dog",
417
+ "elephant",
418
+ "fox",
419
+ "giraffe",
420
+ "horse",
421
+ "iguana",
422
+ "jaguar",
423
+ "mountain",
424
+ "river",
425
+ "ocean",
426
+ "desert",
427
+ "forest",
428
+ "jungle",
429
+ "meadow",
430
+ "valley",
431
+ "star",
432
+ "moon",
433
+ "sun",
434
+ "planet",
435
+ "comet",
436
+ "asteroid",
437
+ "galaxy",
438
+ "universe"
439
+ ];
440
+ const randomAdjective = adjectives[Math.floor(Math.random() * adjectives.length)];
441
+ const randomNoun = nouns[Math.floor(Math.random() * nouns.length)];
442
+ return `${randomAdjective}-${randomNoun}`;
443
+ }
444
+
445
+ const PACKAGE_VERSION_DEFINITIONS = {
446
+ "@biomejs/biome": { fallbackVersion: "2.0.0" },
447
+ "@react-three/drei": { fallbackVersion: "10.0.0" },
448
+ "@react-three/fiber": { fallbackVersion: "9.0.0" },
449
+ "@react-three/handle": { fallbackVersion: "6.6.16" },
450
+ "@react-three/offscreen": { fallbackVersion: "0.0.8" },
451
+ "@react-three/postprocessing": { fallbackVersion: "3.0.4" },
452
+ "@react-three/rapier": { fallbackVersion: "2.1.0" },
453
+ "@react-three/uikit": { fallbackVersion: "0.8.15" },
454
+ "@react-three/xr": { fallbackVersion: "6.6.16" },
455
+ "@testing-library/dom": { fallbackVersion: "10.4.0" },
456
+ "@testing-library/react": { fallbackVersion: "16.2.0" },
457
+ "@types/react": { fallbackVersion: "19.0.0" },
458
+ "@types/react-dom": { fallbackVersion: "19.0.0" },
459
+ "@types/three": { fallbackVersion: "0.175.0", prefix: "~" },
460
+ "@vitejs/plugin-basic-ssl": { fallbackVersion: "2.0.0" },
461
+ "@vitejs/plugin-react": { fallbackVersion: "4.4.1" },
462
+ "@viverse/cli": { fallbackVersion: "0.9.5-beta.8" },
463
+ eslint: { fallbackVersion: "9.17.0" },
464
+ "eslint-plugin-react-hooks": { fallbackVersion: "5.1.0" },
465
+ jsdom: { fallbackVersion: "26.0.0" },
466
+ koota: { fallbackVersion: "0.4.0" },
467
+ leva: { fallbackVersion: "0.10.0" },
468
+ oxfmt: { fallbackVersion: "0.21.0" },
469
+ oxlint: { fallbackVersion: "1.36.0" },
470
+ prettier: { fallbackVersion: "3.4.2" },
471
+ react: { fallbackVersion: "19.0.0" },
472
+ "react-dom": { fallbackVersion: "19.0.0" },
473
+ three: { fallbackVersion: "0.175.0", prefix: "~" },
474
+ tsdown: { fallbackVersion: "0.12.0" },
475
+ "typescript-eslint": { fallbackVersion: "8.18.0" },
476
+ unbuild: { fallbackVersion: "3.5.0" },
477
+ vite: { fallbackVersion: "6.3.4" },
478
+ vitest: { fallbackVersion: "4.0.0" },
479
+ zustand: { fallbackVersion: "5.0.3" }
480
+ };
481
+ function addPackageName(packageNames, explicitVersions, packageName) {
482
+ if (!explicitVersions.has(packageName)) {
483
+ packageNames.add(packageName);
484
+ }
485
+ }
486
+ function getExplicitVersionPackages(options) {
487
+ return /* @__PURE__ */ new Set([
488
+ ...Object.keys(options.dependencies ?? {}),
489
+ ...Object.keys(options.versions ?? {})
490
+ ]);
491
+ }
492
+ function getPackageFallbackVersion(packageName) {
493
+ const definition = PACKAGE_VERSION_DEFINITIONS[packageName];
494
+ if (definition == null) {
495
+ throw new Error(`Missing package version definition for ${packageName}`);
496
+ }
497
+ return definition.fallbackVersion;
498
+ }
499
+ function getResolvedPackageVersion(versions, packageName) {
500
+ return versions[packageName] ?? getPackageFallbackVersion(packageName);
501
+ }
502
+ function formatResolvedPackageVersion(versions, packageName, prefix) {
503
+ const resolvedPrefix = prefix ?? PACKAGE_VERSION_DEFINITIONS[packageName]?.prefix ?? "^";
504
+ return `${resolvedPrefix}${getResolvedPackageVersion(versions, packageName)}`;
505
+ }
506
+ function assignResolvedPackageVersion(target, versions, packageName, prefix) {
507
+ target[packageName] = formatResolvedPackageVersion(versions, packageName, prefix);
508
+ }
509
+ function getPackageManagerSpec(packageManager) {
510
+ return packageManager ?? { name: "pnpm" };
511
+ }
512
+ function getPackageManagerName(packageManager) {
513
+ return getPackageManagerSpec(packageManager).name;
514
+ }
515
+ function formatPackageManager(packageManager) {
516
+ const spec = getPackageManagerSpec(packageManager);
517
+ return spec.version ? `${spec.name}@${spec.version}` : spec.name;
518
+ }
519
+ function parsePackageManager(packageManager) {
520
+ if (packageManager == null || packageManager.length === 0) {
521
+ return void 0;
522
+ }
523
+ const atIndex = packageManager.indexOf("@");
524
+ if (atIndex === -1) {
525
+ return { name: packageManager };
526
+ }
527
+ return {
528
+ name: packageManager.slice(0, atIndex),
529
+ version: packageManager.slice(atIndex + 1)
530
+ };
531
+ }
532
+ function getEngineSpec(engine) {
533
+ return engine ?? { name: "node" };
534
+ }
535
+ function getEngineName(engine) {
536
+ return getEngineSpec(engine).name;
537
+ }
538
+ function parseEngine(engines) {
539
+ if (engines == null) {
540
+ return void 0;
541
+ }
542
+ const [name, range] = Object.entries(engines).find(
543
+ ([engineName]) => engineName !== "npm" && engineName !== "pnpm" && engineName !== "yarn"
544
+ ) ?? [];
545
+ if (name == null) {
546
+ return void 0;
547
+ }
548
+ const version = range?.match(/(\d+(?:\.\d+(?:\.\d+)?)?)/)?.[1];
549
+ return { name, version };
550
+ }
551
+ async function resolvePackageManager(options) {
552
+ const packageManager = getPackageManagerSpec(options.packageManager);
553
+ if (packageManager.version == null) {
554
+ if (packageManager.name === "pnpm") {
555
+ packageManager.version = await getLatestPnpmVersion();
556
+ } else if (packageManager.name === "yarn") {
557
+ packageManager.version = await getLatestYarnVersion();
558
+ } else if (packageManager.name === "npm") {
559
+ packageManager.version = await getLatestNpmCliVersion();
560
+ }
561
+ }
562
+ return packageManager;
563
+ }
564
+ async function resolveEngine(options) {
565
+ const engine = getEngineSpec(options.engine);
566
+ if (engine.version == null && engine.name === "node") {
567
+ engine.version = await getLatestNodeVersion();
568
+ }
569
+ return engine;
570
+ }
571
+ async function resolvePackageVersions(packageNames, existingVersions = {}) {
572
+ const versions = { ...existingVersions };
573
+ const uniquePackageNames = [...new Set(packageNames)];
574
+ await Promise.all(
575
+ uniquePackageNames.map(async (packageName) => {
576
+ if (versions[packageName] != null) return;
577
+ versions[packageName] = await getLatestNpmVersion(
578
+ packageName,
579
+ getPackageFallbackVersion(packageName)
580
+ );
581
+ })
582
+ );
583
+ return versions;
584
+ }
585
+ async function resolveProjectPackageVersions(options) {
586
+ return resolvePackageVersions(collectProjectPackageNames(options), options.versions);
587
+ }
588
+ async function resolveMonorepoRootPackageVersions(params) {
589
+ const packageNames = /* @__PURE__ */ new Set();
590
+ const explicitVersions = new Set(Object.keys(params.versions ?? {}));
591
+ addPackageName(packageNames, explicitVersions, getLinterPackage(params.linter));
592
+ if (params.formatter !== "biome" || params.linter !== "biome") {
593
+ addPackageName(packageNames, explicitVersions, getFormatterPackage(params.formatter));
594
+ }
595
+ return resolvePackageVersions(packageNames, params.versions);
596
+ }
597
+ function collectProjectPackageNames(options) {
598
+ const packageNames = /* @__PURE__ */ new Set();
599
+ const explicitVersions = getExplicitVersionPackages(options);
600
+ const template = options.template ?? "vanilla";
601
+ const baseTemplate = getBaseTemplate(template);
602
+ const language = getLanguageFromTemplate(template);
603
+ const isLibrary = options.projectType === "library";
604
+ const isReact = baseTemplate === "react" || baseTemplate === "r3f";
605
+ const isR3f = baseTemplate === "r3f";
606
+ const isTypescript = language === "typescript";
607
+ const inWorkspace = options.workspaceRoot != null;
608
+ const testing = options.testing ?? (isLibrary ? "vitest" : "none");
609
+ const linter = options.linter ?? "oxlint";
610
+ const formatter = options.formatter ?? "prettier";
611
+ const bundler = options.libraryBundler ?? "unbuild";
612
+ const packageManager = getPackageManagerName(options.packageManager);
613
+ if (!isLibrary) {
614
+ addPackageName(packageNames, explicitVersions, "vite");
615
+ }
616
+ if (isReact) {
617
+ if (!isLibrary) {
618
+ addPackageName(packageNames, explicitVersions, "react");
619
+ addPackageName(packageNames, explicitVersions, "react-dom");
620
+ addPackageName(packageNames, explicitVersions, "@vitejs/plugin-react");
621
+ }
622
+ if (isTypescript) {
623
+ addPackageName(packageNames, explicitVersions, "@types/react");
624
+ addPackageName(packageNames, explicitVersions, "@types/react-dom");
625
+ }
626
+ }
627
+ if (isR3f) {
628
+ if (!isLibrary) {
629
+ addPackageName(packageNames, explicitVersions, "three");
630
+ addPackageName(packageNames, explicitVersions, "@react-three/fiber");
631
+ }
632
+ if (isTypescript) {
633
+ addPackageName(packageNames, explicitVersions, "@types/three");
634
+ }
635
+ if (isEnabledOption(options.drei)) {
636
+ addPackageName(packageNames, explicitVersions, "@react-three/drei");
637
+ }
638
+ if (isEnabledOption(options.handle)) {
639
+ addPackageName(packageNames, explicitVersions, "@react-three/handle");
640
+ }
641
+ if (isEnabledOption(options.koota)) {
642
+ addPackageName(packageNames, explicitVersions, "koota");
643
+ }
644
+ if (isEnabledOption(options.leva)) {
645
+ addPackageName(packageNames, explicitVersions, "leva");
646
+ }
647
+ if (isEnabledOption(options.rapier)) {
648
+ addPackageName(packageNames, explicitVersions, "@react-three/rapier");
649
+ }
650
+ if (isEnabledOption(options.uikit)) {
651
+ addPackageName(packageNames, explicitVersions, "@react-three/uikit");
652
+ }
653
+ if (isEnabledOption(options.zustand)) {
654
+ addPackageName(packageNames, explicitVersions, "zustand");
655
+ }
656
+ if (isEnabledOption(options.xr)) {
657
+ addPackageName(packageNames, explicitVersions, "@react-three/xr");
658
+ addPackageName(packageNames, explicitVersions, "@vitejs/plugin-basic-ssl");
659
+ }
660
+ if (!isEnabledOption(options.xr) && isEnabledOption(options.offscreen)) {
661
+ addPackageName(packageNames, explicitVersions, "@react-three/offscreen");
662
+ }
663
+ if (!isEnabledOption(options.xr) && isEnabledOption(options.postprocessing)) {
664
+ addPackageName(packageNames, explicitVersions, "@react-three/postprocessing");
665
+ }
666
+ if (isEnabledOption(options.viverse) && packageManager === "npm") {
667
+ addPackageName(packageNames, explicitVersions, "@viverse/cli");
668
+ }
669
+ }
670
+ if (testing === "vitest") {
671
+ addPackageName(packageNames, explicitVersions, "vitest");
672
+ if (isReact) {
673
+ addPackageName(packageNames, explicitVersions, "@testing-library/react");
674
+ addPackageName(packageNames, explicitVersions, "@testing-library/dom");
675
+ addPackageName(packageNames, explicitVersions, "jsdom");
676
+ }
677
+ }
678
+ if (linter === "eslint") {
679
+ addPackageName(packageNames, explicitVersions, "eslint");
680
+ if (isTypescript) {
681
+ addPackageName(packageNames, explicitVersions, "typescript-eslint");
682
+ }
683
+ if (isReact) {
684
+ addPackageName(packageNames, explicitVersions, "eslint-plugin-react-hooks");
685
+ }
686
+ } else if (linter === "oxlint") {
687
+ if (!inWorkspace) {
688
+ addPackageName(packageNames, explicitVersions, "oxlint");
689
+ }
690
+ } else if (linter === "biome") {
691
+ addPackageName(packageNames, explicitVersions, "@biomejs/biome");
692
+ }
693
+ if (formatter === "prettier") {
694
+ addPackageName(packageNames, explicitVersions, "prettier");
695
+ } else if (formatter === "oxfmt") {
696
+ if (!inWorkspace) {
697
+ addPackageName(packageNames, explicitVersions, "oxfmt");
698
+ }
699
+ } else if (formatter === "biome") {
700
+ addPackageName(packageNames, explicitVersions, "@biomejs/biome");
701
+ }
702
+ if (isLibrary) {
703
+ addPackageName(packageNames, explicitVersions, bundler === "unbuild" ? "unbuild" : "tsdown");
704
+ }
705
+ return [...packageNames];
706
+ }
707
+ function getLinterPackage(linter) {
708
+ if (linter === "biome") {
709
+ return "@biomejs/biome";
710
+ }
711
+ return linter;
712
+ }
713
+ function getFormatterPackage(formatter) {
714
+ if (formatter === "biome") {
715
+ return "@biomejs/biome";
716
+ }
717
+ return formatter;
718
+ }
719
+ function isEnabledOption(option) {
720
+ return option != null && option !== false;
721
+ }
722
+
723
+ function generateTypescriptConfig(baseTemplateOrParams) {
724
+ const params = typeof baseTemplateOrParams === "string" ? { baseTemplate: baseTemplateOrParams } : baseTemplateOrParams;
725
+ const {
726
+ baseTemplate,
727
+ useConfigPackage,
728
+ configStrategy = "stealth",
729
+ engine,
730
+ versions = {}
731
+ } = params;
732
+ const isReact = baseTemplate === "react";
733
+ const isR3f = baseTemplate === "r3f";
734
+ const files = {};
735
+ const devDependencies = {};
736
+ if (getEngineName(engine) === "node" && getEngineSpec(engine).version) {
737
+ const majorVersion = getEngineSpec(engine).version.split(".")[0];
738
+ devDependencies["@types/node"] = `^${majorVersion}.0.0`;
739
+ } else {
740
+ devDependencies["@types/node"] = "^22.0.0";
741
+ }
742
+ if (isReact || isR3f) {
743
+ assignResolvedPackageVersion(devDependencies, versions, "@types/react");
744
+ assignResolvedPackageVersion(devDependencies, versions, "@types/react-dom");
745
+ }
746
+ if (isR3f) {
747
+ assignResolvedPackageVersion(devDependencies, versions, "@types/three", "~");
748
+ }
749
+ if (useConfigPackage) {
750
+ devDependencies["@config/typescript"] = "workspace:*";
751
+ const baseConfig = isReact || isR3f ? "@config/typescript/react.json" : "@config/typescript/app.json";
752
+ files["tsconfig.json"] = {
753
+ type: "text",
754
+ content: JSON.stringify(
755
+ {
756
+ $schema: "https://json.schemastore.org/tsconfig",
757
+ extends: baseConfig,
758
+ include: ["src/**/*", "tests/**/*"]
759
+ },
760
+ null,
761
+ 2
762
+ )
763
+ };
764
+ return { files, devDependencies };
765
+ }
766
+ if (configStrategy === "stealth") {
767
+ const tsConfig = {
768
+ $schema: "https://json.schemastore.org/tsconfig",
769
+ files: [],
770
+ references: [
771
+ { path: "./.config/tsconfig.app.json" },
772
+ { path: "./.config/tsconfig.node.json" }
773
+ ]
774
+ };
775
+ files["tsconfig.json"] = {
776
+ type: "text",
777
+ content: JSON.stringify(tsConfig, null, 2)
778
+ };
779
+ const tsConfigApp = {
780
+ $schema: "https://json.schemastore.org/tsconfig",
781
+ compilerOptions: {
782
+ target: "ESNext",
783
+ module: "ESNext",
784
+ moduleResolution: "bundler",
785
+ lib: ["DOM", "DOM.Iterable", "ESNext"],
786
+ esModuleInterop: true,
787
+ allowSyntheticDefaultImports: true,
788
+ strict: true,
789
+ skipLibCheck: true,
790
+ composite: true,
791
+ rewriteRelativeImportExtensions: true,
792
+ erasableSyntaxOnly: true,
793
+ ...isReact || isR3f ? { jsx: "react-jsx" } : {}
794
+ },
795
+ include: ["../src", "../tests"]
796
+ };
797
+ files[".config/tsconfig.app.json"] = {
798
+ type: "text",
799
+ content: JSON.stringify(tsConfigApp, null, 2)
800
+ };
801
+ const tsConfigNode = {
802
+ $schema: "https://json.schemastore.org/tsconfig",
803
+ compilerOptions: {
804
+ target: "ESNext",
805
+ module: "ESNext",
806
+ moduleResolution: "bundler",
807
+ lib: ["ESNext"],
808
+ esModuleInterop: true,
809
+ allowSyntheticDefaultImports: true,
810
+ strict: true,
811
+ skipLibCheck: true,
812
+ composite: true,
813
+ rewriteRelativeImportExtensions: true,
814
+ erasableSyntaxOnly: true
815
+ },
816
+ include: ["../*.config.ts", "./*.ts"]
817
+ };
818
+ files[".config/tsconfig.node.json"] = {
819
+ type: "text",
820
+ content: JSON.stringify(tsConfigNode, null, 2)
821
+ };
822
+ } else {
823
+ const tsConfig = {
824
+ $schema: "https://json.schemastore.org/tsconfig",
825
+ files: [],
826
+ references: [{ path: "./tsconfig.app.json" }, { path: "./tsconfig.node.json" }]
827
+ };
828
+ files["tsconfig.json"] = {
829
+ type: "text",
830
+ content: JSON.stringify(tsConfig, null, 2)
831
+ };
832
+ const tsConfigApp = {
833
+ $schema: "https://json.schemastore.org/tsconfig",
834
+ compilerOptions: {
835
+ target: "ESNext",
836
+ module: "ESNext",
837
+ moduleResolution: "bundler",
838
+ lib: ["DOM", "DOM.Iterable", "ESNext"],
839
+ esModuleInterop: true,
840
+ allowSyntheticDefaultImports: true,
841
+ strict: true,
842
+ skipLibCheck: true,
843
+ composite: true,
844
+ rewriteRelativeImportExtensions: true,
845
+ erasableSyntaxOnly: true,
846
+ ...isReact || isR3f ? { jsx: "react-jsx" } : {}
847
+ },
848
+ include: ["src", "tests"]
849
+ };
850
+ files["tsconfig.app.json"] = {
851
+ type: "text",
852
+ content: JSON.stringify(tsConfigApp, null, 2)
853
+ };
854
+ const tsConfigNode = {
855
+ $schema: "https://json.schemastore.org/tsconfig",
856
+ compilerOptions: {
857
+ target: "ESNext",
858
+ module: "ESNext",
859
+ moduleResolution: "bundler",
860
+ lib: ["ESNext"],
861
+ esModuleInterop: true,
862
+ allowSyntheticDefaultImports: true,
863
+ strict: true,
864
+ skipLibCheck: true,
865
+ composite: true,
866
+ rewriteRelativeImportExtensions: true,
867
+ erasableSyntaxOnly: true
868
+ },
869
+ include: ["*.config.ts"]
870
+ };
871
+ files["tsconfig.node.json"] = {
872
+ type: "text",
873
+ content: JSON.stringify(tsConfigNode, null, 2)
874
+ };
875
+ }
876
+ return { files, devDependencies };
877
+ }
878
+
879
+ const DEFAULT_LIBRARY_VERSION = "0.1.0";
880
+ function generatePackageJson(params) {
881
+ const {
882
+ name,
883
+ language,
884
+ isLibrary,
885
+ dependencies,
886
+ devDependencies,
887
+ peerDependencies,
888
+ scripts,
889
+ options,
890
+ workspaceDependencies
891
+ } = params;
892
+ const files = {};
893
+ const packageManager = getPackageManagerSpec(options.packageManager);
894
+ const isPnpm = packageManager.name === "pnpm";
895
+ const packageJson = {
896
+ name,
897
+ description: "Built with \u{1F339} create-krispya",
898
+ type: "module"
899
+ };
900
+ if (isLibrary) {
901
+ packageJson.version = DEFAULT_LIBRARY_VERSION;
902
+ packageJson.main = "./dist/index.mjs";
903
+ packageJson.module = "./dist/index.mjs";
904
+ if (language === "typescript") {
905
+ packageJson.types = "./dist/index.d.ts";
906
+ }
907
+ packageJson.exports = {
908
+ ".": {
909
+ ...language === "typescript" && { types: "./dist/index.d.ts" },
910
+ import: "./dist/index.mjs",
911
+ require: "./dist/index.cjs"
912
+ }
913
+ };
914
+ packageJson.files = ["dist"];
915
+ }
916
+ const sortKeys = (obj) => Object.fromEntries(Object.entries(obj).sort(([a], [b]) => a.localeCompare(b)));
917
+ const allDependencies = { ...dependencies };
918
+ if (workspaceDependencies && workspaceDependencies.length > 0) {
919
+ for (const pkgName of workspaceDependencies) {
920
+ allDependencies[pkgName] = "workspace:*";
921
+ }
922
+ }
923
+ const allDevDependencies = { ...devDependencies };
924
+ const engine = getEngineSpec(options.engine);
925
+ if (getEngineName(engine) === "node" && engine.version) {
926
+ const majorVersion = engine.version.split(".")[0];
927
+ allDevDependencies["@types/node"] ??= `^${majorVersion}.0.0`;
928
+ }
929
+ packageJson.scripts = scripts;
930
+ packageJson.dependencies = sortKeys(allDependencies);
931
+ if (Object.keys(allDevDependencies).length > 0) {
932
+ packageJson.devDependencies = sortKeys(allDevDependencies);
933
+ }
934
+ if (isLibrary && Object.keys(peerDependencies).length > 0) {
935
+ packageJson.peerDependencies = sortKeys(peerDependencies);
936
+ }
937
+ const isMonorepoPackage = options.workspaceRoot != null;
938
+ if (!isMonorepoPackage) {
939
+ const engines = {};
940
+ if (packageManager.version != null) {
941
+ const majorVersion = packageManager.version.split(".")[0];
942
+ engines[packageManager.name] = `>=${majorVersion}.0.0`;
943
+ packageJson.packageManager = formatPackageManager(packageManager);
944
+ }
945
+ if (engine.version != null) {
946
+ const majorVersion = engine.version.split(".")[0];
947
+ engines[engine.name] = `>=${majorVersion}.0.0`;
948
+ }
949
+ if (Object.keys(engines).length > 0) {
950
+ packageJson.engines = engines;
951
+ }
952
+ }
953
+ files["package.json"] = {
954
+ type: "text",
955
+ content: JSON.stringify(packageJson, null, 2)
956
+ };
957
+ if (isPnpm && !options.workspaceRoot) {
958
+ const manageVersions = options.pnpmManageVersions ?? true;
959
+ const workspaceLines = [];
960
+ if (manageVersions) {
961
+ workspaceLines.push("manage-package-manager-versions: true", "");
962
+ }
963
+ workspaceLines.push("onlyBuiltDependencies:", " - esbuild");
964
+ files["pnpm-workspace.yaml"] = {
965
+ type: "text",
966
+ content: workspaceLines.join("\n")
967
+ };
968
+ }
969
+ return { files };
970
+ }
971
+
972
+ function generateReadme(params) {
973
+ const { name, baseTemplate, isLibrary, libraryBundler, packageManager, codeSnippets } = params;
974
+ const isVanilla = baseTemplate === "vanilla";
975
+ const isReact = baseTemplate === "react";
976
+ const isR3f = baseTemplate === "r3f";
977
+ const ext = "ts";
978
+ const jsxExt = "tsx";
979
+ codeSnippets["readme-libraries"] ??= [];
980
+ codeSnippets["readme-commands"] ??= [];
981
+ if (isLibrary) ; else if (isVanilla) {
982
+ codeSnippets["readme-libraries"].unshift(
983
+ `[Vite](https://vitejs.dev/) - Next generation frontend tooling`
984
+ );
985
+ } else if (isReact) {
986
+ codeSnippets["readme-libraries"].unshift(
987
+ `[React](https://react.dev/) - A JavaScript library for building user interfaces`,
988
+ `[Vite](https://vitejs.dev/) - Next generation frontend tooling`
989
+ );
990
+ } else {
991
+ codeSnippets["readme-libraries"].unshift(
992
+ `[React](https://react.dev/) - A JavaScript library for building user interfaces`,
993
+ `[Three.js](https://threejs.org/) - JavaScript 3D library`,
994
+ `[@react-three/fiber](https://docs.pmnd.rs/react-three-fiber) - lets you create Three.js scenes using React components`
995
+ );
996
+ }
997
+ if (isLibrary) {
998
+ codeSnippets["readme-commands"].unshift(
999
+ `\`${packageManager} install\` to install the dependencies`,
1000
+ `\`${packageManager} run build\` to build the library into the \`dist\` folder`,
1001
+ `\`${packageManager} run test\` to run the tests`,
1002
+ `\`${packageManager} run release\` to build and publish to npm`
1003
+ );
1004
+ } else {
1005
+ codeSnippets["readme-commands"].unshift(
1006
+ `\`${packageManager} install\` to install the dependencies`,
1007
+ `\`${packageManager} run dev\` to run the development server and preview the app with live updates`,
1008
+ `\`${packageManager} run build\` to build the app into the \`dist\` folder`,
1009
+ `\`${packageManager} run test\` to run the tests`
1010
+ );
1011
+ }
1012
+ let architectureDesc;
1013
+ if (isLibrary) {
1014
+ architectureDesc = [
1015
+ `- \`src/index.${isReact || isR3f ? jsxExt : ext}\` is the main entry point for your library exports`,
1016
+ `- Add your library code in the \`src\` folder`,
1017
+ `- \`tests/\` contains your test files`
1018
+ ];
1019
+ } else if (isVanilla) {
1020
+ architectureDesc = [
1021
+ `- \`src/main.${ext}\` is the entry point for your application`,
1022
+ `- \`tests/\` contains your test files`,
1023
+ `- Static assets can be placed in the \`public\` folder`
1024
+ ];
1025
+ } else if (isReact) {
1026
+ architectureDesc = [
1027
+ `- \`src/app.${jsxExt}\` defines the main application component`,
1028
+ `- \`src/index.${jsxExt}\` renders the React app into the DOM`,
1029
+ `- \`tests/\` contains your test files`,
1030
+ `- Static assets can be placed in the \`public\` folder`
1031
+ ];
1032
+ } else {
1033
+ architectureDesc = [
1034
+ `- \`app.${jsxExt}\` defines the main application component containing your 3D content`,
1035
+ `- Modify the content inside the \`<Canvas>\` component to change what is visible on screen`,
1036
+ `- \`tests/\` contains your test files`,
1037
+ `- Static assets can be placed in the \`public\` folder`
1038
+ ];
1039
+ }
1040
+ const bundlerDescription = isLibrary ? libraryBundler === "unbuild" ? `This library uses [unbuild](https://github.com/unjs/unbuild) for building.` : `This library uses [tsdown](https://github.com/nicepkg/tsdown) for building.` : `This project uses [Vite](https://vitejs.dev/) as the bundler for fast development and optimized production builds.`;
1041
+ const content = [
1042
+ `# ${name}`,
1043
+ `This ${isLibrary ? "library" : "project"} was generated with create-krispya`,
1044
+ ...codeSnippets["readme-start"] ?? [],
1045
+ "\n",
1046
+ `## Project Architecture`,
1047
+ bundlerDescription,
1048
+ ...architectureDesc,
1049
+ "\n",
1050
+ `## Libraries`,
1051
+ `The following libraries are used - checkout the linked docs to learn more`,
1052
+ ...(codeSnippets["readme-libraries"] ?? []).map((library) => `- ${library}`),
1053
+ "\n",
1054
+ codeSnippets["readme-tools"] && `## Tools`,
1055
+ ...(codeSnippets["readme-tools"] ?? []).map((tool) => `- ${tool}`),
1056
+ codeSnippets["readme-tools"] && `
1057
+ `,
1058
+ `## Development Commands`,
1059
+ ...(codeSnippets["readme-commands"] ?? []).map((command) => `- ${command}`),
1060
+ ...codeSnippets["readme-end"] ?? []
1061
+ ].filter(Boolean).join("\n");
1062
+ return { type: "text", content };
1063
+ }
1064
+
1065
+ function generateSourceFiles(params) {
1066
+ const { name, baseTemplate, language, isLibrary, codeSnippets, replacements } = params;
1067
+ const files = {};
1068
+ const ext = language === "typescript" ? "ts" : "js";
1069
+ const jsxExt = language === "typescript" ? "tsx" : "jsx";
1070
+ const isVanilla = baseTemplate === "vanilla";
1071
+ const isReact = baseTemplate === "react";
1072
+ const isR3f = baseTemplate === "r3f";
1073
+ if (isLibrary) {
1074
+ const libExt = isReact || isR3f ? jsxExt : ext;
1075
+ let libContent;
1076
+ if (isVanilla) {
1077
+ libContent = [
1078
+ `// Library entry point`,
1079
+ `export function hello(name: string = "world"): string {`,
1080
+ ` return \`Hello, \${name}!\``,
1081
+ `}`
1082
+ ].join("\n");
1083
+ } else if (isReact) {
1084
+ libContent = [
1085
+ `// Library entry point`,
1086
+ `export function MyComponent({ message = "Hello from library!" }: { message?: string }) {`,
1087
+ ` return <div>{message}</div>`,
1088
+ `}`
1089
+ ].join("\n");
1090
+ } else {
1091
+ libContent = [
1092
+ `// Library entry point`,
1093
+ `export function MyMesh({ color = "orange" }: { color?: string }) {`,
1094
+ ` return (`,
1095
+ ` <mesh>`,
1096
+ ` <boxGeometry />`,
1097
+ ` <meshStandardMaterial color={color} />`,
1098
+ ` </mesh>`,
1099
+ ` )`,
1100
+ `}`
1101
+ ].join("\n");
1102
+ }
1103
+ files[`src/index.${libExt}`] = { type: "text", content: libContent };
1104
+ } else if (isVanilla) {
1105
+ files[`src/main.${ext}`] = { type: "text", content: ViteIndexContent };
1106
+ files["src/style.css"] = { type: "text", content: ViteStyleContent };
1107
+ const indexHtml = ViteHtmlContent.replace("$indexPath", `./src/main.${ext}`).replace(
1108
+ "$title",
1109
+ name
1110
+ );
1111
+ files["index.html"] = { type: "text", content: indexHtml };
1112
+ } else {
1113
+ files[`src/index.tsx`] = { type: "text", content: IndexContent };
1114
+ const indexHtml = HtmlContent.replace(
1115
+ "$indexPath",
1116
+ language === "javascript" ? "./src/index.jsx" : "./src/index.tsx"
1117
+ ).replace("$title", name);
1118
+ files["index.html"] = { type: "text", content: indexHtml };
1119
+ codeSnippets["dom-end"]?.reverse();
1120
+ codeSnippets["global-end"]?.reverse();
1121
+ codeSnippets["scene-end"]?.reverse();
1122
+ let appCode;
1123
+ if (isReact) {
1124
+ appCode = [
1125
+ ...codeSnippets["import"] ?? [],
1126
+ ...codeSnippets["global-start"] ?? [],
1127
+ `export function App() {`,
1128
+ " return (",
1129
+ ' <div style={{ padding: "2rem" }}>',
1130
+ " <h1>Hello React!</h1>",
1131
+ " <p>Edit src/app.tsx and save to see changes.</p>",
1132
+ " </div>",
1133
+ " )",
1134
+ "}",
1135
+ ...codeSnippets["global-end"] ?? []
1136
+ ].join("\n");
1137
+ } else {
1138
+ appCode = [
1139
+ ...codeSnippets["import"] ?? [],
1140
+ ...codeSnippets["global-start"] ?? [],
1141
+ `export function App() {`,
1142
+ " return <>",
1143
+ ...codeSnippets["dom-start"] ?? [],
1144
+ ...codeSnippets["dom"] ?? [],
1145
+ " <Canvas>",
1146
+ ...codeSnippets["scene-start"] ?? [],
1147
+ ...codeSnippets["scene"] ?? [],
1148
+ ...codeSnippets["scene-end"] ?? [],
1149
+ " </Canvas>",
1150
+ ...codeSnippets["dom-end"] ?? [],
1151
+ " </>",
1152
+ "}",
1153
+ ...codeSnippets["global-end"] ?? []
1154
+ ].join("\n");
1155
+ }
1156
+ for (const { search, replace } of replacements) {
1157
+ appCode = appCode.replace(search, replace);
1158
+ }
1159
+ files[`src/app.tsx`] = { type: "text", content: appCode };
1160
+ }
1161
+ return files;
1162
+ }
1163
+
1164
+ function generateTestFiles(params) {
1165
+ const { baseTemplate, language, isLibrary } = params;
1166
+ const files = {};
1167
+ const ext = language === "typescript" ? "ts" : "js";
1168
+ const jsxExt = language === "typescript" ? "tsx" : "jsx";
1169
+ const isVanilla = baseTemplate === "vanilla";
1170
+ const isReact = baseTemplate === "react";
1171
+ const isR3f = baseTemplate === "r3f";
1172
+ if (isLibrary) {
1173
+ const testExt = isReact || isR3f ? jsxExt : ext;
1174
+ let testContent;
1175
+ if (isVanilla) {
1176
+ testContent = [
1177
+ `import { describe, it, expect } from "vitest"`,
1178
+ `import { hello } from "../src/index.js"`,
1179
+ ``,
1180
+ `describe("hello", () => {`,
1181
+ ` it("returns greeting with default name", () => {`,
1182
+ ` expect(hello()).toBe("Hello, world!")`,
1183
+ ` })`,
1184
+ ``,
1185
+ ` it("returns greeting with custom name", () => {`,
1186
+ ` expect(hello("vitest")).toBe("Hello, vitest!")`,
1187
+ ` })`,
1188
+ `})`
1189
+ ].join("\n");
1190
+ } else if (isReact) {
1191
+ testContent = [
1192
+ `import { describe, it, expect } from "vitest"`,
1193
+ `import { render, screen } from "@testing-library/react"`,
1194
+ `import { MyComponent } from "../src/index.js"`,
1195
+ ``,
1196
+ `describe("MyComponent", () => {`,
1197
+ ` it("renders with default message", () => {`,
1198
+ ` render(<MyComponent />)`,
1199
+ ` expect(screen.getByText("Hello from library!")).toBeDefined()`,
1200
+ ` })`,
1201
+ ``,
1202
+ ` it("renders with custom message", () => {`,
1203
+ ` render(<MyComponent message="Custom message" />)`,
1204
+ ` expect(screen.getByText("Custom message")).toBeDefined()`,
1205
+ ` })`,
1206
+ `})`
1207
+ ].join("\n");
1208
+ } else {
1209
+ testContent = [
1210
+ `import { describe, it, expect } from "vitest"`,
1211
+ `import { MyMesh } from "../src/index.js"`,
1212
+ ``,
1213
+ `describe("MyMesh", () => {`,
1214
+ ` it("is defined", () => {`,
1215
+ ` expect(MyMesh).toBeDefined()`,
1216
+ ` })`,
1217
+ `})`
1218
+ ].join("\n");
1219
+ }
1220
+ files[`tests/index.test.${testExt}`] = {
1221
+ type: "text",
1222
+ content: testContent
1223
+ };
1224
+ } else if (isVanilla) {
1225
+ const testContent = [
1226
+ `import { describe, it, expect } from "vitest"`,
1227
+ ``,
1228
+ `describe("example", () => {`,
1229
+ ` it("works", () => {`,
1230
+ ` expect(1 + 1).toBe(2)`,
1231
+ ` })`,
1232
+ `})`
1233
+ ].join("\n");
1234
+ files[`tests/main.test.${ext}`] = { type: "text", content: testContent };
1235
+ } else if (isReact) {
1236
+ const testContent = [
1237
+ `import { describe, it, expect } from "vitest"`,
1238
+ `import { render, screen } from "@testing-library/react"`,
1239
+ `import { App } from "../src/app.js"`,
1240
+ ``,
1241
+ `describe("App", () => {`,
1242
+ ` it("renders heading", () => {`,
1243
+ ` render(<App />)`,
1244
+ ` expect(screen.getByText("Hello React!")).toBeDefined()`,
1245
+ ` })`,
1246
+ `})`
1247
+ ].join("\n");
1248
+ files[`tests/app.test.${jsxExt}`] = { type: "text", content: testContent };
1249
+ } else {
1250
+ const testContent = [
1251
+ `import { describe, it, expect } from "vitest"`,
1252
+ `import { App } from "../src/app.js"`,
1253
+ ``,
1254
+ `describe("App", () => {`,
1255
+ ` it("is defined", () => {`,
1256
+ ` expect(App).toBeDefined()`,
1257
+ ` })`,
1258
+ `})`
1259
+ ].join("\n");
1260
+ files[`tests/app.test.${jsxExt}`] = { type: "text", content: testContent };
1261
+ }
1262
+ return files;
1263
+ }
1264
+
1265
+ const COMMON_GITIGNORE_LINES = [
1266
+ "node_modules",
1267
+ "dist",
1268
+ "*.tsbuildinfo",
1269
+ ".env",
1270
+ ".env.*",
1271
+ "!.env.example"
1272
+ ];
1273
+ function generateGitignore(variant) {
1274
+ const lines = variant === "workspace-root" ? [...COMMON_GITIGNORE_LINES, ".DS_Store"] : COMMON_GITIGNORE_LINES;
1275
+ return {
1276
+ type: "text",
1277
+ content: lines.join("\n")
1278
+ };
1279
+ }
1280
+
1281
+ function generateVscodeFiles$1(params) {
1282
+ const { codeSnippets, vscodeSettings } = params;
1283
+ const files = {};
1284
+ if (codeSnippets["vscode-extension-suggestion"]?.length) {
1285
+ const uniqueRecommendations = [...new Set(codeSnippets["vscode-extension-suggestion"])];
1286
+ files[".vscode/extensions.json"] = {
1287
+ type: "text",
1288
+ content: JSON.stringify(
1289
+ {
1290
+ recommendations: uniqueRecommendations
1291
+ },
1292
+ null,
1293
+ 2
1294
+ )
1295
+ };
1296
+ }
1297
+ if (Object.keys(vscodeSettings).length > 0) {
1298
+ const sortedSettings = Object.fromEntries(
1299
+ Object.entries(vscodeSettings).sort(([a], [b]) => a.localeCompare(b))
1300
+ );
1301
+ files[".vscode/settings.json"] = {
1302
+ type: "text",
1303
+ content: JSON.stringify(sortedSettings, null, 2)
1304
+ };
1305
+ }
1306
+ return files;
1307
+ }
1308
+
1309
+ function formatValue(value, indent) {
1310
+ const spaces = " ".repeat(indent);
1311
+ const innerSpaces = " ".repeat(indent + 1);
1312
+ if (typeof value === "string") {
1313
+ if (value.startsWith("$raw:")) {
1314
+ return value.slice(5);
1315
+ }
1316
+ return JSON.stringify(value);
1317
+ }
1318
+ if (typeof value === "number" || typeof value === "boolean") {
1319
+ return String(value);
1320
+ }
1321
+ if (value === null) {
1322
+ return "null";
1323
+ }
1324
+ if (Array.isArray(value)) {
1325
+ if (value.length === 0) return "[]";
1326
+ const items = value.map((v) => `${innerSpaces}${formatValue(v, indent + 1)}`);
1327
+ return `[
1328
+ ${items.join(",\n")}
1329
+ ${spaces}]`;
1330
+ }
1331
+ if (typeof value === "object") {
1332
+ const entries = Object.entries(value);
1333
+ if (entries.length === 0) return "{}";
1334
+ const props = entries.map(
1335
+ ([key, val]) => `${innerSpaces}${key}: ${formatValue(val, indent + 1)}`
1336
+ );
1337
+ return `{
1338
+ ${props.join(",\n")}
1339
+ ${spaces}}`;
1340
+ }
1341
+ return String(value);
1342
+ }
1343
+ function generateViteConfig(params) {
1344
+ const { viteConfig, codeSnippets } = params;
1345
+ const configBody = formatValue(viteConfig, 0);
1346
+ const viteConfigContent = [
1347
+ `import { defineConfig } from "vite"`,
1348
+ ...codeSnippets["vite-config-import"] ?? [],
1349
+ ``,
1350
+ `export default defineConfig(${configBody})`,
1351
+ ``
1352
+ ].join("\n");
1353
+ return { type: "text", content: viteConfigContent };
1354
+ }
1355
+
1356
+ function generateTypescriptConfigPackage(files) {
1357
+ const basePath = ".config/typescript";
1358
+ files[`${basePath}/package.json`] = {
1359
+ type: "text",
1360
+ content: JSON.stringify(
1361
+ {
1362
+ name: "@config/typescript",
1363
+ version: "0.1.0",
1364
+ private: true,
1365
+ files: ["base.json", "app.json", "node.json", "react.json"]
1366
+ },
1367
+ null,
1368
+ 2
1369
+ )
1370
+ };
1371
+ files[`${basePath}/README.md`] = {
1372
+ type: "text",
1373
+ content: `# \`@config/typescript\`
1374
+
1375
+ These are base shared \`tsconfig.json\`s from which all other \`tsconfig.json\`s inherit.
1376
+
1377
+ ## Usage
1378
+
1379
+ In your package's \`tsconfig.json\`:
1380
+
1381
+ \`\`\`json
1382
+ {
1383
+ "extends": "@config/typescript/app.json",
1384
+ "include": ["src/**/*", "tests"]
1385
+ }
1386
+ \`\`\`
1387
+
1388
+ ## Available Configs
1389
+
1390
+ - \`base.json\` - Common TypeScript compiler options
1391
+ - \`app.json\` - For browser/DOM code (extends base)
1392
+ - \`node.json\` - For Node.js code (extends base)
1393
+ - \`react.json\` - For React projects with JSX (extends app)
1394
+ `
1395
+ };
1396
+ files[`${basePath}/base.json`] = {
1397
+ type: "text",
1398
+ content: JSON.stringify(
1399
+ {
1400
+ $schema: "https://json.schemastore.org/tsconfig",
1401
+ compilerOptions: {
1402
+ target: "ESNext",
1403
+ module: "ESNext",
1404
+ moduleResolution: "bundler",
1405
+ esModuleInterop: true,
1406
+ allowSyntheticDefaultImports: true,
1407
+ strict: true,
1408
+ skipLibCheck: true,
1409
+ composite: true,
1410
+ rewriteRelativeImportExtensions: true,
1411
+ erasableSyntaxOnly: true
1412
+ }
1413
+ },
1414
+ null,
1415
+ 2
1416
+ )
1417
+ };
1418
+ files[`${basePath}/app.json`] = {
1419
+ type: "text",
1420
+ content: JSON.stringify(
1421
+ {
1422
+ $schema: "https://json.schemastore.org/tsconfig",
1423
+ extends: "./base.json",
1424
+ compilerOptions: {
1425
+ lib: ["DOM", "DOM.Iterable", "ESNext"]
1426
+ }
1427
+ },
1428
+ null,
1429
+ 2
1430
+ )
1431
+ };
1432
+ files[`${basePath}/node.json`] = {
1433
+ type: "text",
1434
+ content: JSON.stringify(
1435
+ {
1436
+ $schema: "https://json.schemastore.org/tsconfig",
1437
+ extends: "./base.json",
1438
+ compilerOptions: {
1439
+ lib: ["ESNext"]
1440
+ }
1441
+ },
1442
+ null,
1443
+ 2
1444
+ )
1445
+ };
1446
+ files[`${basePath}/react.json`] = {
1447
+ type: "text",
1448
+ content: JSON.stringify(
1449
+ {
1450
+ $schema: "https://json.schemastore.org/tsconfig",
1451
+ extends: "./app.json",
1452
+ compilerOptions: {
1453
+ jsx: "react-jsx"
1454
+ }
1455
+ },
1456
+ null,
1457
+ 2
1458
+ )
1459
+ };
1460
+ }
1461
+ function generateOxlintConfigPackage(files) {
1462
+ const basePath = ".config/oxlint";
1463
+ const { rules } = defaultLinterConfig;
1464
+ files[`${basePath}/package.json`] = {
1465
+ type: "text",
1466
+ content: JSON.stringify(
1467
+ {
1468
+ name: "@config/oxlint",
1469
+ version: "0.1.0",
1470
+ private: true,
1471
+ files: ["base.json", "react.json"]
1472
+ },
1473
+ null,
1474
+ 2
1475
+ )
1476
+ };
1477
+ files[`${basePath}/README.md`] = {
1478
+ type: "text",
1479
+ content: `# \`@config/oxlint\`
1480
+
1481
+ Shared oxlint configurations for the monorepo.
1482
+
1483
+ ## Usage
1484
+
1485
+ Run oxlint with a config:
1486
+
1487
+ \`\`\`bash
1488
+ oxlint -c node_modules/@config/oxlint/base.json
1489
+ \`\`\`
1490
+
1491
+ ## Available Configs
1492
+
1493
+ - \`base.json\` - Base linting rules for TypeScript projects
1494
+ - \`react.json\` - Extends base with React-specific rules
1495
+ `
1496
+ };
1497
+ files[`${basePath}/base.json`] = {
1498
+ type: "text",
1499
+ content: JSON.stringify(
1500
+ {
1501
+ $schema: "./node_modules/oxlint/configuration_schema.json",
1502
+ plugins: ["unicorn", "typescript", "oxc"],
1503
+ rules: {
1504
+ "no-unused-vars": [
1505
+ rules.noUnusedVars.level,
1506
+ {
1507
+ argsIgnorePattern: rules.noUnusedVars.argsIgnorePattern,
1508
+ varsIgnorePattern: rules.noUnusedVars.varsIgnorePattern,
1509
+ caughtErrorsIgnorePattern: rules.noUnusedVars.caughtErrorsIgnorePattern
1510
+ }
1511
+ ],
1512
+ "no-useless-escape": "off",
1513
+ "no-unused-expressions": [
1514
+ rules.noUnusedExpressions.level,
1515
+ { allowShortCircuit: rules.noUnusedExpressions.allowShortCircuit }
1516
+ ]
1517
+ },
1518
+ ignorePatterns: defaultLinterConfig.ignorePatterns
1519
+ },
1520
+ null,
1521
+ 2
1522
+ )
1523
+ };
1524
+ files[`${basePath}/react.json`] = {
1525
+ type: "text",
1526
+ content: JSON.stringify(
1527
+ {
1528
+ $schema: "./node_modules/oxlint/configuration_schema.json",
1529
+ plugins: ["unicorn", "typescript", "oxc", "react"],
1530
+ rules: {
1531
+ "no-unused-vars": [
1532
+ rules.noUnusedVars.level,
1533
+ {
1534
+ argsIgnorePattern: rules.noUnusedVars.argsIgnorePattern,
1535
+ varsIgnorePattern: rules.noUnusedVars.varsIgnorePattern,
1536
+ caughtErrorsIgnorePattern: rules.noUnusedVars.caughtErrorsIgnorePattern
1537
+ }
1538
+ ],
1539
+ "no-useless-escape": "off",
1540
+ "no-unused-expressions": [
1541
+ rules.noUnusedExpressions.level,
1542
+ { allowShortCircuit: rules.noUnusedExpressions.allowShortCircuit }
1543
+ ]
1544
+ },
1545
+ ignorePatterns: defaultLinterConfig.ignorePatterns
1546
+ },
1547
+ null,
1548
+ 2
1549
+ )
1550
+ };
1551
+ }
1552
+ function generateEslintConfigPackage(files) {
1553
+ const basePath = ".config/eslint";
1554
+ files[`${basePath}/package.json`] = {
1555
+ type: "text",
1556
+ content: JSON.stringify(
1557
+ {
1558
+ name: "@config/eslint",
1559
+ version: "0.1.0",
1560
+ private: true,
1561
+ type: "module",
1562
+ exports: {
1563
+ "./base": "./base.js",
1564
+ "./react": "./react.js"
1565
+ },
1566
+ files: ["base.js", "react.js"],
1567
+ devDependencies: {
1568
+ "@eslint/js": "^9.17.0",
1569
+ "typescript-eslint": "^8.18.0"
1570
+ }
1571
+ },
1572
+ null,
1573
+ 2
1574
+ )
1575
+ };
1576
+ files[`${basePath}/README.md`] = {
1577
+ type: "text",
1578
+ content: `# \`@config/eslint\`
1579
+
1580
+ Shared ESLint configurations for the monorepo.
1581
+
1582
+ ## Usage
1583
+
1584
+ In your package's \`eslint.config.js\`:
1585
+
1586
+ \`\`\`js
1587
+ import base from "@config/eslint/base";
1588
+
1589
+ export default [...base];
1590
+ \`\`\`
1591
+
1592
+ Or for React projects:
1593
+
1594
+ \`\`\`js
1595
+ import react from "@config/eslint/react";
1596
+
1597
+ export default [...react];
1598
+ \`\`\`
1599
+
1600
+ ## Available Configs
1601
+
1602
+ - \`base\` - Base linting rules for TypeScript projects
1603
+ - \`react\` - Extends base with React-specific rules
1604
+ `
1605
+ };
1606
+ files[`${basePath}/base.js`] = {
1607
+ type: "text",
1608
+ content: `import js from "@eslint/js";
1609
+ import tseslint from "typescript-eslint";
1610
+
1611
+ export default tseslint.config(
1612
+ js.configs.recommended,
1613
+ ...tseslint.configs.recommended,
1614
+ {
1615
+ rules: {
1616
+ "@typescript-eslint/no-unused-vars": [
1617
+ "error",
1618
+ {
1619
+ argsIgnorePattern: "^_",
1620
+ varsIgnorePattern: "^_",
1621
+ caughtErrorsIgnorePattern: "^_",
1622
+ },
1623
+ ],
1624
+ },
1625
+ },
1626
+ {
1627
+ ignores: ["dist/**", "node_modules/**"],
1628
+ }
1629
+ );
1630
+ `
1631
+ };
1632
+ files[`${basePath}/react.js`] = {
1633
+ type: "text",
1634
+ content: `import js from "@eslint/js";
1635
+ import tseslint from "typescript-eslint";
1636
+
1637
+ export default tseslint.config(
1638
+ js.configs.recommended,
1639
+ ...tseslint.configs.recommended,
1640
+ {
1641
+ rules: {
1642
+ "@typescript-eslint/no-unused-vars": [
1643
+ "error",
1644
+ {
1645
+ argsIgnorePattern: "^_",
1646
+ varsIgnorePattern: "^_",
1647
+ caughtErrorsIgnorePattern: "^_",
1648
+ },
1649
+ ],
1650
+ },
1651
+ },
1652
+ {
1653
+ ignores: ["dist/**", "node_modules/**"],
1654
+ }
1655
+ );
1656
+ `
1657
+ };
1658
+ }
1659
+ function generatePrettierConfigPackage(files) {
1660
+ const basePath = ".config/prettier";
1661
+ files[`${basePath}/package.json`] = {
1662
+ type: "text",
1663
+ content: JSON.stringify(
1664
+ {
1665
+ name: "@config/prettier",
1666
+ version: "0.1.0",
1667
+ private: true,
1668
+ type: "module",
1669
+ exports: {
1670
+ ".": "./base.json"
1671
+ },
1672
+ files: ["base.json"]
1673
+ },
1674
+ null,
1675
+ 2
1676
+ )
1677
+ };
1678
+ files[`${basePath}/README.md`] = {
1679
+ type: "text",
1680
+ content: `# \`@config/prettier\`
1681
+
1682
+ Shared Prettier configuration for the monorepo.
1683
+
1684
+ ## Usage
1685
+
1686
+ In your package's \`package.json\`:
1687
+
1688
+ \`\`\`json
1689
+ {
1690
+ "prettier": "@config/prettier"
1691
+ }
1692
+ \`\`\`
1693
+
1694
+ Or in \`.prettierrc.json\`:
1695
+
1696
+ \`\`\`json
1697
+ "@config/prettier"
1698
+ \`\`\`
1699
+
1700
+ ## Available Configs
1701
+
1702
+ - Default export - Base formatter settings
1703
+ `
1704
+ };
1705
+ files[`${basePath}/base.json`] = {
1706
+ type: "text",
1707
+ content: JSON.stringify(defaultPrettierConfig, null, 2)
1708
+ };
1709
+ }
1710
+ function generateOxfmtConfigPackage(files) {
1711
+ const basePath = ".config/oxfmt";
1712
+ files[`${basePath}/package.json`] = {
1713
+ type: "text",
1714
+ content: JSON.stringify(
1715
+ {
1716
+ name: "@config/oxfmt",
1717
+ version: "0.1.0",
1718
+ private: true,
1719
+ files: ["base.json"]
1720
+ },
1721
+ null,
1722
+ 2
1723
+ )
1724
+ };
1725
+ files[`${basePath}/README.md`] = {
1726
+ type: "text",
1727
+ content: `# \`@config/oxfmt\`
1728
+
1729
+ Shared oxfmt (formatter) configuration for the monorepo.
1730
+
1731
+ ## Usage
1732
+
1733
+ Run oxfmt with the config:
1734
+
1735
+ \`\`\`bash
1736
+ oxfmt -c node_modules/@config/oxfmt/base.json --write .
1737
+ \`\`\`
1738
+
1739
+ ## Available Configs
1740
+
1741
+ - \`base.json\` - Base formatter settings (Prettier-compatible)
1742
+ `
1743
+ };
1744
+ files[`${basePath}/base.json`] = {
1745
+ type: "text",
1746
+ content: JSON.stringify(defaultOxfmtConfig, null, 2)
1747
+ };
1748
+ }
1749
+
1750
+ function generateMonorepo(params) {
1751
+ const {
1752
+ name,
1753
+ linter,
1754
+ formatter,
1755
+ packageManager,
1756
+ pnpmManageVersions,
1757
+ engine,
1758
+ versions = {},
1759
+ aiPlatforms
1760
+ } = params;
1761
+ const files = {};
1762
+ const isPnpm = packageManager.name === "pnpm";
1763
+ const devDependencies = {};
1764
+ if (engine?.name === "node" && engine.version) {
1765
+ const majorVersion = engine.version.split(".")[0];
1766
+ devDependencies["@types/node"] = `^${majorVersion}.0.0`;
1767
+ } else {
1768
+ devDependencies["@types/node"] = "^22.0.0";
1769
+ }
1770
+ if (linter === "oxlint") {
1771
+ assignResolvedPackageVersion(devDependencies, versions, "oxlint");
1772
+ } else if (linter === "eslint") {
1773
+ assignResolvedPackageVersion(devDependencies, versions, "eslint");
1774
+ } else if (linter === "biome") {
1775
+ assignResolvedPackageVersion(devDependencies, versions, "@biomejs/biome");
1776
+ }
1777
+ if (formatter === "oxfmt") {
1778
+ assignResolvedPackageVersion(devDependencies, versions, "oxfmt");
1779
+ } else if (formatter === "prettier") {
1780
+ assignResolvedPackageVersion(devDependencies, versions, "prettier");
1781
+ }
1782
+ const rootPackageJson = {
1783
+ name: "root",
1784
+ version: "0.0.0",
1785
+ private: true,
1786
+ type: "module",
1787
+ scripts: {
1788
+ dev: "pnpm --filter './apps/*' run dev",
1789
+ build: "pnpm --filter './packages/*' run build && pnpm --filter './apps/*' run build",
1790
+ test: "pnpm -r run test",
1791
+ lint: linter === "oxlint" ? "oxlint ." : linter === "biome" ? "biome check ." : "eslint .",
1792
+ format: formatter === "oxfmt" ? "oxfmt -c .config/oxfmt/base.json ." : formatter === "biome" ? "biome format . --write" : "prettier --config .config/prettier/base.json --write ."
1793
+ },
1794
+ devDependencies
1795
+ };
1796
+ const engines = {};
1797
+ if (isPnpm && packageManager.version) {
1798
+ const majorVersion = packageManager.version.split(".")[0];
1799
+ engines.pnpm = `>=${majorVersion}.0.0`;
1800
+ rootPackageJson.packageManager = formatPackageManager(packageManager);
1801
+ }
1802
+ if (engine?.version) {
1803
+ const majorVersion = engine.version.split(".")[0];
1804
+ engines[engine.name] = `>=${majorVersion}.0.0`;
1805
+ }
1806
+ if (Object.keys(engines).length > 0) {
1807
+ rootPackageJson.engines = engines;
1808
+ }
1809
+ files["package.json"] = {
1810
+ type: "text",
1811
+ content: JSON.stringify(rootPackageJson, null, 2)
1812
+ };
1813
+ if (isPnpm) {
1814
+ const workspaceLines = [];
1815
+ if (pnpmManageVersions) {
1816
+ workspaceLines.push("manage-package-manager-versions: true", "");
1817
+ }
1818
+ workspaceLines.push("packages:", ' - ".config/*"', ' - "apps/*"', ' - "packages/*"', "");
1819
+ workspaceLines.push("onlyBuiltDependencies:", " - esbuild");
1820
+ files["pnpm-workspace.yaml"] = {
1821
+ type: "text",
1822
+ content: workspaceLines.join("\n")
1823
+ };
1824
+ }
1825
+ files["tsconfig.json"] = {
1826
+ type: "text",
1827
+ content: JSON.stringify(
1828
+ {
1829
+ extends: "@config/typescript/base.json",
1830
+ compilerOptions: {
1831
+ noEmit: true
1832
+ },
1833
+ references: []
1834
+ },
1835
+ null,
1836
+ 2
1837
+ )
1838
+ };
1839
+ generateTypescriptConfigPackage(files);
1840
+ if (linter === "oxlint") {
1841
+ generateOxlintConfigPackage(files);
1842
+ files["oxlint.json"] = {
1843
+ type: "text",
1844
+ content: JSON.stringify(
1845
+ {
1846
+ $schema: "./node_modules/oxlint/configuration_schema.json",
1847
+ extends: ["@config/oxlint/base.json"]
1848
+ },
1849
+ null,
1850
+ 2
1851
+ )
1852
+ };
1853
+ } else if (linter === "eslint") {
1854
+ generateEslintConfigPackage(files);
1855
+ files["eslint.config.js"] = {
1856
+ type: "text",
1857
+ content: `import base from "@config/eslint/base";
1858
+
1859
+ export default [...base];
1860
+ `
1861
+ };
1862
+ } else if (linter === "biome") {
1863
+ const biomeVersion = getResolvedPackageVersion(versions, "@biomejs/biome");
1864
+ const biomeConfig = {
1865
+ $schema: `https://biomejs.dev/schemas/${biomeVersion}/schema.json`,
1866
+ vcs: {
1867
+ enabled: true,
1868
+ clientKind: "git",
1869
+ useIgnoreFile: true
1870
+ },
1871
+ linter: {
1872
+ enabled: true,
1873
+ rules: {
1874
+ recommended: true
1875
+ }
1876
+ },
1877
+ formatter: {
1878
+ enabled: formatter === "biome"
1879
+ }
1880
+ };
1881
+ files["biome.json"] = {
1882
+ type: "text",
1883
+ content: JSON.stringify(biomeConfig, null, 2)
1884
+ };
1885
+ }
1886
+ if (formatter === "oxfmt") {
1887
+ generateOxfmtConfigPackage(files);
1888
+ } else if (formatter === "prettier") {
1889
+ generatePrettierConfigPackage(files);
1890
+ }
1891
+ files[".gitignore"] = generateGitignore("workspace-root");
1892
+ files[".gitattributes"] = {
1893
+ type: "text",
1894
+ content: `* text=auto eol=lf
1895
+ *.{cmd,[cC][mM][dD]} text eol=crlf
1896
+ *.{bat,[bB][aA][tT]} text eol=crlf
1897
+ `
1898
+ };
1899
+ generateVscodeFiles(files, linter, formatter);
1900
+ files["README.md"] = {
1901
+ type: "text",
1902
+ content: `# ${name}
1903
+
1904
+ This monorepo workspace was generated with create-krispya.
1905
+
1906
+ ## Structure
1907
+
1908
+ - \`apps/\` - Applications
1909
+ - \`packages/\` - Shared packages and libraries
1910
+ - \`.config/\` - Shared configuration packages
1911
+
1912
+ ## Development Commands
1913
+
1914
+ - \`${packageManager.name} install\` to install all dependencies
1915
+ - \`${packageManager.name} run dev\` to run all applications in development mode
1916
+ - \`${packageManager.name} run build\` to build all packages and applications
1917
+ - \`${packageManager.name} run test\` to run tests across the workspace
1918
+ - \`${packageManager.name} run lint\` to lint all code
1919
+ - \`${packageManager.name} run format\` to format all code
1920
+
1921
+ ## Adding Packages
1922
+
1923
+ To add a new package to this workspace, run create-krispya from this directory and it will detect the monorepo.
1924
+ `
1925
+ };
1926
+ if (aiPlatforms && aiPlatforms.length > 0) {
1927
+ generateAiFiles(files, {
1928
+ name,
1929
+ packageManager: packageManager.name,
1930
+ linter,
1931
+ formatter,
1932
+ isMonorepo: true,
1933
+ platforms: aiPlatforms
1934
+ });
1935
+ }
1936
+ return { files };
1937
+ }
1938
+ function generateVscodeFiles(files, linter, formatter) {
1939
+ const recommendations = [];
1940
+ const settings = {};
1941
+ if (linter === "oxlint") {
1942
+ recommendations.push("oxc.oxc-vscode");
1943
+ settings["oxc.enable"] = true;
1944
+ settings["eslint.enable"] = false;
1945
+ settings["biome.enabled"] = false;
1946
+ } else if (linter === "eslint") {
1947
+ recommendations.push("dbaeumer.vscode-eslint");
1948
+ settings["eslint.enable"] = true;
1949
+ settings["oxc.enable"] = false;
1950
+ settings["biome.enabled"] = false;
1951
+ } else if (linter === "biome") {
1952
+ recommendations.push("biomejs.biome");
1953
+ settings["biome.enabled"] = true;
1954
+ settings["eslint.enable"] = false;
1955
+ settings["oxc.enable"] = false;
1956
+ }
1957
+ if (formatter === "oxfmt") {
1958
+ if (!recommendations.includes("oxc.oxc-vscode")) {
1959
+ recommendations.push("oxc.oxc-vscode");
1960
+ }
1961
+ settings["editor.defaultFormatter"] = "oxc.oxc-vscode";
1962
+ settings["[json]"] = {
1963
+ "editor.defaultFormatter": "vscode.json-language-features"
1964
+ };
1965
+ settings["[jsonc]"] = {
1966
+ "editor.defaultFormatter": "vscode.json-language-features"
1967
+ };
1968
+ } else if (formatter === "prettier") {
1969
+ recommendations.push("esbenp.prettier-vscode");
1970
+ settings["editor.defaultFormatter"] = "esbenp.prettier-vscode";
1971
+ } else if (formatter === "biome") {
1972
+ if (!recommendations.includes("biomejs.biome")) {
1973
+ recommendations.push("biomejs.biome");
1974
+ }
1975
+ settings["editor.defaultFormatter"] = "biomejs.biome";
1976
+ }
1977
+ files[".vscode/extensions.json"] = {
1978
+ type: "text",
1979
+ content: JSON.stringify({ recommendations }, null, 2)
1980
+ };
1981
+ const codeSnippets = {};
1982
+ if (recommendations.length > 0) {
1983
+ codeSnippets["vscode-extension-suggestion"] = recommendations;
1984
+ }
1985
+ Object.assign(
1986
+ files,
1987
+ generateVscodeFiles$1({
1988
+ codeSnippets,
1989
+ vscodeSettings: settings
1990
+ })
1991
+ );
1992
+ }
1993
+
1994
+ const monorepo = {
1995
+ __proto__: null,
1996
+ generateEslintConfigPackage: generateEslintConfigPackage,
1997
+ generateMonorepo: generateMonorepo,
1998
+ generateOxfmtConfigPackage: generateOxfmtConfigPackage,
1999
+ generateOxlintConfigPackage: generateOxlintConfigPackage,
2000
+ generatePrettierConfigPackage: generatePrettierConfigPackage,
2001
+ generateTypescriptConfigPackage: generateTypescriptConfigPackage,
2002
+ generateVscodeFiles: generateVscodeFiles
2003
+ };
2004
+
2005
+ function toBiomeLevel(level) {
2006
+ return level;
2007
+ }
2008
+ function generateBiome(generator, options) {
2009
+ if (options == null || !options.linter && !options.formatter) {
2010
+ return;
2011
+ }
2012
+ const version = generator.getVersion("@biomejs/biome");
2013
+ generator.addDevDependency("@biomejs/biome");
2014
+ const { rules } = defaultLinterConfig;
2015
+ const biomeConfig = {
2016
+ $schema: `https://biomejs.dev/schemas/${version}/schema.json`
2017
+ };
2018
+ if (options.linter) {
2019
+ biomeConfig.linter = {
2020
+ enabled: true,
2021
+ rules: {
2022
+ recommended: true,
2023
+ correctness: {
2024
+ noUnusedVariables: toBiomeLevel(rules.noUnusedVars.level)
2025
+ }
2026
+ }
2027
+ };
2028
+ } else {
2029
+ biomeConfig.linter = {
2030
+ enabled: false
2031
+ };
2032
+ }
2033
+ if (options.formatter) {
2034
+ biomeConfig.formatter = {
2035
+ enabled: true,
2036
+ lineWidth: defaultFormatterConfig.printWidth,
2037
+ indentWidth: defaultFormatterConfig.tabWidth,
2038
+ indentStyle: "space"
2039
+ };
2040
+ biomeConfig.javascript = {
2041
+ formatter: {
2042
+ semicolons: "always" ,
2043
+ quoteStyle: "single" ,
2044
+ trailingCommas: defaultFormatterConfig.trailingComma,
2045
+ bracketSpacing: defaultFormatterConfig.bracketSpacing,
2046
+ arrowParentheses: "always"
2047
+ }
2048
+ };
2049
+ biomeConfig.json = {
2050
+ formatter: {
2051
+ indentWidth: 2
2052
+ }
2053
+ };
2054
+ } else {
2055
+ biomeConfig.formatter = {
2056
+ enabled: false
2057
+ };
2058
+ }
2059
+ const isStealth = generator.isStealthConfig();
2060
+ if (isStealth) {
2061
+ generator.addFile(".config/biome.json", {
2062
+ type: "text",
2063
+ content: JSON.stringify(biomeConfig, null, 2)
2064
+ });
2065
+ if (options.linter) {
2066
+ generator.addScript("lint", "biome lint --config-path .config .");
2067
+ }
2068
+ if (options.formatter) {
2069
+ generator.addScript("format", "biome format --config-path .config --write .");
2070
+ }
2071
+ generator.addVscodeSetting("biome.linter.configPath", ".config/biome.json");
2072
+ } else {
2073
+ generator.addFile("biome.json", {
2074
+ type: "text",
2075
+ content: JSON.stringify(biomeConfig, null, 2)
2076
+ });
2077
+ if (options.linter) {
2078
+ generator.addScript("lint", "biome lint .");
2079
+ }
2080
+ if (options.formatter) {
2081
+ generator.addScript("format", "biome format --write .");
2082
+ }
2083
+ }
2084
+ const roles = [];
2085
+ if (options.linter) roles.push("linter");
2086
+ if (options.formatter) roles.push("formatter");
2087
+ generator.inject(
2088
+ "readme-tools",
2089
+ `[Biome](https://biomejs.dev/) - Fast ${roles.join(" and ")} for JavaScript and TypeScript`
2090
+ );
2091
+ generator.inject("vscode-extension-suggestion", "biomejs.biome");
2092
+ generator.addVscodeSetting("biome.enabled", true);
2093
+ if (options.formatter) {
2094
+ generator.addVscodeSetting("editor.defaultFormatter", "biomejs.biome");
2095
+ }
2096
+ }
2097
+
2098
+ function generateDrei(generator, options) {
2099
+ if (options == null) {
2100
+ return;
2101
+ }
2102
+ generator.addDependency("@react-three/drei");
2103
+ generator.inject("import", `import { Environment } from "@react-three/drei"`);
2104
+ generator.inject("scene", '<Environment background preset="city" />');
2105
+ generator.inject(
2106
+ "readme-libraries",
2107
+ `[@react-three/drei](https://drei.docs.pmnd.rs/) - Useful helpers for @react-three/fiber`
2108
+ );
2109
+ }
2110
+
2111
+ function toEslintLevel(level) {
2112
+ return level;
2113
+ }
2114
+ function generateEslint(generator, options) {
2115
+ generator.addDevDependency("eslint");
2116
+ const template = generator.options.template ?? "vanilla";
2117
+ const baseTemplate = getBaseTemplate(template);
2118
+ const isTypescript = getLanguageFromTemplate(template) === "typescript";
2119
+ const isReact = baseTemplate === "react" || baseTemplate === "r3f";
2120
+ const { rules } = defaultLinterConfig;
2121
+ const imports = ['import js from "@eslint/js"'];
2122
+ const configs = ["js.configs.recommended"];
2123
+ if (isTypescript) {
2124
+ generator.addDevDependency("typescript-eslint");
2125
+ imports.push('import tseslint from "typescript-eslint"');
2126
+ configs.push("...tseslint.configs.recommended");
2127
+ }
2128
+ if (isReact) {
2129
+ generator.addDevDependency("eslint-plugin-react-hooks");
2130
+ imports.push('import reactHooks from "eslint-plugin-react-hooks"');
2131
+ }
2132
+ const ignoresArray = JSON.stringify(defaultLinterConfig.ignorePatterns);
2133
+ const unusedVarsRule = isTypescript ? "@typescript-eslint/no-unused-vars" : "no-unused-vars";
2134
+ const rulesConfig = {
2135
+ [unusedVarsRule]: [
2136
+ toEslintLevel(rules.noUnusedVars.level),
2137
+ {
2138
+ argsIgnorePattern: rules.noUnusedVars.argsIgnorePattern,
2139
+ varsIgnorePattern: rules.noUnusedVars.varsIgnorePattern,
2140
+ caughtErrorsIgnorePattern: rules.noUnusedVars.caughtErrorsIgnorePattern
2141
+ }
2142
+ ],
2143
+ "no-unused-expressions": [
2144
+ toEslintLevel(rules.noUnusedExpressions.level),
2145
+ { allowShortCircuit: rules.noUnusedExpressions.allowShortCircuit }
2146
+ ]
2147
+ };
2148
+ const rulesString = JSON.stringify(rulesConfig, null, 4).replace(/\n/g, "\n ");
2149
+ const configContent = [
2150
+ ...imports,
2151
+ "",
2152
+ "export default [",
2153
+ ` { ignores: ${ignoresArray} },`,
2154
+ ` ${configs.join(",\n ")},`,
2155
+ isReact ? ` {
2156
+ plugins: {
2157
+ "react-hooks": reactHooks,
2158
+ },
2159
+ rules: reactHooks.configs.recommended.rules,
2160
+ },` : "",
2161
+ ` {
2162
+ rules: ${rulesString},
2163
+ },`,
2164
+ "]"
2165
+ ].filter(Boolean).join("\n");
2166
+ const isStealth = generator.isStealthConfig();
2167
+ if (isStealth) {
2168
+ generator.addFile(".config/eslint.config.js", {
2169
+ type: "text",
2170
+ content: configContent
2171
+ });
2172
+ generator.addScript("lint", "eslint --config .config/eslint.config.js .");
2173
+ generator.addVscodeSetting("eslint.options", {
2174
+ overrideConfigFile: ".config/eslint.config.js"
2175
+ });
2176
+ } else {
2177
+ generator.addFile("eslint.config.js", {
2178
+ type: "text",
2179
+ content: configContent
2180
+ });
2181
+ generator.addScript("lint", "eslint .");
2182
+ }
2183
+ generator.inject(
2184
+ "readme-tools",
2185
+ "[ESLint](https://eslint.org/) - Linter for JavaScript and TypeScript"
2186
+ );
2187
+ generator.inject("vscode-extension-suggestion", "dbaeumer.vscode-eslint");
2188
+ generator.addVscodeSetting("eslint.enable", true);
2189
+ }
2190
+
2191
+ function generateFiber(generator, _options) {
2192
+ generator.inject("import", `import { Box } from "./box.js"`);
2193
+ generator.inject(
2194
+ "scene",
2195
+ [
2196
+ `<ambientLight intensity={Math.PI / 2} />`,
2197
+ `<spotLight position={[10, 10, 10]} angle={0.15} penumbra={1} decay={0} intensity={Math.PI} />`,
2198
+ `<pointLight position={[-10, -10, -10]} decay={0} intensity={Math.PI} />`,
2199
+ `<Box position={[-1.2, 0, 0]} />`,
2200
+ `<Box position={[1.2, 0, 0]} />`
2201
+ ].join("\n")
2202
+ );
2203
+ generator.addFile("src/box.tsx", {
2204
+ type: "text",
2205
+ content: `import type { Mesh } from 'three'
2206
+ import { useRef, useState } from 'react'
2207
+ import { useFrame, ThreeElements } from '@react-three/fiber'
2208
+
2209
+ export function Box(props: ThreeElements['mesh']) {
2210
+ const meshRef = useRef<Mesh>(null!)
2211
+ const [hovered, setHover] = useState(false)
2212
+ const [active, setActive] = useState(false)
2213
+ useFrame((state, delta) => (meshRef.current.rotation.x += delta))
2214
+ return (
2215
+ <mesh
2216
+ {...props}
2217
+ ref={meshRef}
2218
+ scale={active ? 1.5 : 1}
2219
+ onClick={(event) => setActive(!active)}
2220
+ onPointerOver={(event) => setHover(true)}
2221
+ onPointerOut={(event) => setHover(false)}>
2222
+ <boxGeometry args={[1, 1, 1]} />
2223
+ <meshStandardMaterial color={hovered ? 'hotpink' : '#2f74c0'} />
2224
+ </mesh>
2225
+ )
2226
+ }`
2227
+ });
2228
+ }
2229
+
2230
+ function generateGithubPages(generator, options) {
2231
+ if (options === false || getPackageManagerName(generator.options.packageManager) !== "npm") {
2232
+ return;
2233
+ }
2234
+ generator.addFile(".github/workflows/gh-pages.yml", {
2235
+ type: "text",
2236
+ content: `name: Deploy to Github Pages
2237
+
2238
+ on:
2239
+ push:
2240
+ branches:
2241
+ - main
2242
+
2243
+ jobs:
2244
+ build-and-deploy:
2245
+ runs-on: ubuntu-latest
2246
+ permissions:
2247
+ pages: write
2248
+ contents: read
2249
+ id-token: write
2250
+
2251
+ environment:
2252
+ name: github-pages
2253
+ url: \${{ steps.deployment.outputs.page_url }}
2254
+
2255
+ steps:
2256
+ - name: Checkout code
2257
+ uses: actions/checkout@v3
2258
+
2259
+ - name: Setup Node
2260
+ uses: actions/setup-node@v3
2261
+ with:
2262
+ node-version: 20
2263
+
2264
+ - name: Install dependencies
2265
+ run: npm install
2266
+
2267
+ - name: Build project
2268
+ run: npm run build
2269
+
2270
+ - name: Upload artifact
2271
+ uses: actions/upload-pages-artifact@v3
2272
+ with:
2273
+ path: './dist'
2274
+
2275
+ - name: Deploy to GitHub Pages
2276
+ id: deployment
2277
+ uses: actions/deploy-pages@v4
2278
+ `
2279
+ });
2280
+ generator.inject("readme-start", `A github pages deployment action is configurd.`);
2281
+ if (generator.options.githubUserName != null && generator.options.githubRepoName != null) {
2282
+ const address = `${generator.options.githubUserName}.github.io/${generator.options.githubRepoName}`;
2283
+ generator.inject(
2284
+ "readme-start",
2285
+ `Your app will be publish at [${address}](https://${address}) once the github action is finished.
2286
+ `
2287
+ );
2288
+ }
2289
+ }
2290
+
2291
+ function generateHandle(generator, options) {
2292
+ if (options == null) {
2293
+ return;
2294
+ }
2295
+ generator.addDependency("@react-three/handle");
2296
+ generator.inject(
2297
+ "readme-libraries",
2298
+ `[@react-three/handle](https://pmndrs.github.io/xr/docs/handles/introduction) - interactive controls and handles for your 3D objects`
2299
+ );
2300
+ }
2301
+
2302
+ function generateKoota(generator, options) {
2303
+ if (options == null) {
2304
+ return;
2305
+ }
2306
+ generator.addDependency("koota");
2307
+ generator.inject(
2308
+ "readme-libraries",
2309
+ `[koota](https://github.com/pmndrs/koota) - ECS-based state management library optimized for real-time apps, games, and XR experiences`
2310
+ );
2311
+ }
2312
+
2313
+ function generateLeva(generator, options) {
2314
+ if (options == null) {
2315
+ return;
2316
+ }
2317
+ generator.addDependency("leva");
2318
+ generator.inject(
2319
+ "readme-libraries",
2320
+ `[leva](https://github.com/pmndrs/leva) - HTML GUI panel for React with lightweight, beautiful and extensible controls`
2321
+ );
2322
+ }
2323
+
2324
+ function generateOffscreen(generator, options) {
2325
+ if (options == null) {
2326
+ return;
2327
+ }
2328
+ if (generator.options.xr != null) {
2329
+ console.info(
2330
+ color.blue("Info:"),
2331
+ "@react-three/offscreen is disabled because it is not supported with XR"
2332
+ );
2333
+ return;
2334
+ }
2335
+ generator.addDependency("@react-three/offscreen");
2336
+ generator.inject(
2337
+ "readme-libraries",
2338
+ `[@react-three/offscreen](https://github.com/pmndrs/offscreen) - Offload your scene to a worker thread for better performance`
2339
+ );
2340
+ }
2341
+
2342
+ function generateOxfmt(generator, options) {
2343
+ const isMonorepo = generator.options.workspaceRoot != null;
2344
+ if (isMonorepo) {
2345
+ generator.addDevDependency("@config/oxfmt", { version: "workspace:*" });
2346
+ const configPath = "node_modules/@config/oxfmt/base.json";
2347
+ generator.addScript("format", `oxfmt -c ${configPath} --write .`);
2348
+ generator.addVscodeSetting("oxc.fmt.configPath", configPath);
2349
+ } else {
2350
+ generator.addDevDependency("oxfmt");
2351
+ const isStealth = generator.isStealthConfig();
2352
+ if (isStealth) {
2353
+ generator.addFile(".config/oxfmt.json", {
2354
+ type: "text",
2355
+ content: JSON.stringify(defaultOxfmtConfig, null, 2)
2356
+ });
2357
+ generator.addScript("format", "oxfmt -c .config/oxfmt.json --write .");
2358
+ generator.addVscodeSetting("oxc.fmt.configPath", ".config/oxfmt.json");
2359
+ } else {
2360
+ generator.addFile("oxfmt.json", {
2361
+ type: "text",
2362
+ content: JSON.stringify(defaultOxfmtConfig, null, 2)
2363
+ });
2364
+ generator.addScript("format", "oxfmt -c oxfmt.json --write .");
2365
+ }
2366
+ }
2367
+ generator.inject(
2368
+ "readme-tools",
2369
+ "[Oxfmt](https://oxc.rs/docs/guide/usage/formatter) - Fast Prettier-compatible code formatter"
2370
+ );
2371
+ generator.inject("vscode-extension-suggestion", "oxc.oxc-vscode");
2372
+ generator.addVscodeSetting("editor.defaultFormatter", "oxc.oxc-vscode");
2373
+ generator.addVscodeSetting("[json]", {
2374
+ "editor.defaultFormatter": "vscode.json-language-features"
2375
+ });
2376
+ generator.addVscodeSetting("[jsonc]", {
2377
+ "editor.defaultFormatter": "vscode.json-language-features"
2378
+ });
2379
+ generator.addVscodeSetting("[markdown]", {
2380
+ "editor.defaultFormatter": "vscode.markdown-language-features"
2381
+ });
2382
+ generator.addVscodeSetting("[yaml]", {
2383
+ "editor.defaultFormatter": "redhat.vscode-yaml"
2384
+ });
2385
+ }
2386
+
2387
+ function toOxlintLevel(level) {
2388
+ return level;
2389
+ }
2390
+ function generateOxlint(generator, options) {
2391
+ const template = generator.options.template ?? "vanilla";
2392
+ const baseTemplate = getBaseTemplate(template);
2393
+ const isReact = baseTemplate === "react" || baseTemplate === "r3f";
2394
+ const isMonorepo = generator.options.workspaceRoot != null;
2395
+ if (isMonorepo) {
2396
+ generator.addDevDependency("@config/oxlint", { version: "workspace:*" });
2397
+ const configPath = isReact ? "node_modules/@config/oxlint/react.json" : "node_modules/@config/oxlint/base.json";
2398
+ generator.addScript("lint", `oxlint -c ${configPath}`);
2399
+ generator.addVscodeSetting("oxc.configPath", configPath);
2400
+ } else {
2401
+ generator.addDevDependency("oxlint");
2402
+ const isStealth = generator.isStealthConfig();
2403
+ const { rules } = defaultLinterConfig;
2404
+ const plugins = ["unicorn", "typescript", "oxc"];
2405
+ if (isReact) {
2406
+ plugins.push("react");
2407
+ }
2408
+ const oxlintConfig = {
2409
+ $schema: isStealth ? "../node_modules/oxlint/configuration_schema.json" : "./node_modules/oxlint/configuration_schema.json",
2410
+ plugins,
2411
+ rules: {
2412
+ "no-unused-vars": [
2413
+ toOxlintLevel(rules.noUnusedVars.level),
2414
+ {
2415
+ argsIgnorePattern: rules.noUnusedVars.argsIgnorePattern,
2416
+ varsIgnorePattern: rules.noUnusedVars.varsIgnorePattern,
2417
+ caughtErrorsIgnorePattern: rules.noUnusedVars.caughtErrorsIgnorePattern
2418
+ }
2419
+ ],
2420
+ "no-useless-escape": "off",
2421
+ "no-unused-expressions": [
2422
+ toOxlintLevel(rules.noUnusedExpressions.level),
2423
+ { allowShortCircuit: rules.noUnusedExpressions.allowShortCircuit }
2424
+ ]
2425
+ },
2426
+ ignorePatterns: defaultLinterConfig.ignorePatterns
2427
+ };
2428
+ if (isStealth) {
2429
+ generator.addFile(".config/oxlint.json", {
2430
+ type: "text",
2431
+ content: JSON.stringify(oxlintConfig, null, 2)
2432
+ });
2433
+ generator.addScript("lint", "oxlint -c .config/oxlint.json");
2434
+ generator.addVscodeSetting("oxc.configPath", ".config/oxlint.json");
2435
+ } else {
2436
+ generator.addFile("oxlint.json", {
2437
+ type: "text",
2438
+ content: JSON.stringify(oxlintConfig, null, 2)
2439
+ });
2440
+ generator.addScript("lint", "oxlint");
2441
+ }
2442
+ }
2443
+ generator.inject(
2444
+ "readme-tools",
2445
+ "[Oxlint](https://oxc.rs/docs/guide/usage/linter) - A fast linter for JavaScript and TypeScript"
2446
+ );
2447
+ generator.inject("vscode-extension-suggestion", "oxc.oxc-vscode");
2448
+ generator.addVscodeSetting("oxc.enable", true);
2449
+ }
2450
+
2451
+ function generatePostprocessing(generator, options) {
2452
+ if (options == null) {
2453
+ return;
2454
+ }
2455
+ if (generator.options.xr != null) {
2456
+ console.info(
2457
+ color.blue("Info:"),
2458
+ "@react-three/postprocessing is disabled because it is not supported with XR"
2459
+ );
2460
+ return;
2461
+ }
2462
+ generator.addDependency("@react-three/postprocessing");
2463
+ generator.inject(
2464
+ "readme-libraries",
2465
+ `[@react-three/postprocessing](https://react-postprocessing.docs.pmnd.rs/) - Post-processing effects for @react-three/fiber`
2466
+ );
2467
+ }
2468
+
2469
+ function generatePrettier(generator, options) {
2470
+ generator.addDevDependency("prettier");
2471
+ const isStealth = generator.isStealthConfig();
2472
+ if (isStealth) {
2473
+ generator.addFile(".config/prettier.json", {
2474
+ type: "text",
2475
+ content: JSON.stringify(defaultPrettierConfig, null, 2)
2476
+ });
2477
+ generator.addScript("format", "prettier --config .config/prettier.json --write .");
2478
+ generator.addVscodeSetting("prettier.configPath", ".config/prettier.json");
2479
+ } else {
2480
+ generator.addFile(".prettierrc", {
2481
+ type: "text",
2482
+ content: JSON.stringify(defaultPrettierConfig, null, 2)
2483
+ });
2484
+ generator.addScript("format", "prettier --write .");
2485
+ }
2486
+ generator.inject("readme-tools", "[Prettier](https://prettier.io/) - Opinionated code formatter");
2487
+ generator.inject("vscode-extension-suggestion", "esbenp.prettier-vscode");
2488
+ generator.addVscodeSetting("editor.defaultFormatter", "esbenp.prettier-vscode");
2489
+ }
2490
+
2491
+ function generateRapier(generator, options) {
2492
+ if (options == null) {
2493
+ return;
2494
+ }
2495
+ generator.addDependency("@react-three/rapier");
2496
+ generator.inject(
2497
+ "readme-libraries",
2498
+ `[@react-three/rapier](https://github.com/pmndrs/react-three-rapier) - Physics based on Rapier for your @react-three/fiber scene`
2499
+ );
2500
+ }
2501
+
2502
+ function unique(...array) {
2503
+ const set = /* @__PURE__ */ new Set();
2504
+ for (const arr of array) {
2505
+ for (const item of arr) {
2506
+ set.add(item);
2507
+ }
2508
+ }
2509
+ return Array.from(set);
2510
+ }
2511
+
2512
+ function generateProvidersModule(generator) {
2513
+ const canvasProviders = [];
2514
+ const globalProviders = [];
2515
+ const providerDefs = {
2516
+ uikit: {
2517
+ type: "layout-effect",
2518
+ props: [
2519
+ {
2520
+ declaredPropDefaultValue: '"light"',
2521
+ declaredPropName: "colorMode",
2522
+ propName: "colorMode",
2523
+ propValue: "colorMode",
2524
+ declaredPropType: '"light" | "dark"'
2525
+ }
2526
+ ],
2527
+ code: `
2528
+ setPreferredColorScheme(colorMode);
2529
+ `,
2530
+ import: 'import { setPreferredColorScheme } from "@react-three/uikit"'
2531
+ },
2532
+ rapier: {
2533
+ component: "Physics",
2534
+ type: "wrapped-jsx",
2535
+ import: 'import { Physics } from "@react-three/rapier";',
2536
+ props: [
2537
+ {
2538
+ declaredPropDefaultValue: false,
2539
+ declaredPropName: "physicsEnabled",
2540
+ propName: "paused",
2541
+ propValue: "!physicsEnabled",
2542
+ declaredPropType: "boolean"
2543
+ },
2544
+ {
2545
+ declaredPropDefaultValue: true,
2546
+ declaredPropName: "debugPhysics",
2547
+ propName: "debug",
2548
+ propValue: "debugPhysics",
2549
+ declaredPropType: "boolean"
2550
+ }
2551
+ ]
2552
+ },
2553
+ postprocessing: {
2554
+ type: "inline-jsx",
2555
+ code: `
2556
+ <EffectComposer enabled={postProcessingEnabled}>
2557
+ <DepthOfField
2558
+ focusDistance={0}
2559
+ focalLength={0.02}
2560
+ bokehScale={2}
2561
+ height={480}
2562
+ />
2563
+ <Bloom luminanceThreshold={0} luminanceSmoothing={0.9} height={300} />
2564
+ </EffectComposer>
2565
+ `,
2566
+ import: 'import { Bloom, DepthOfField, EffectComposer } from "@react-three/postprocessing";',
2567
+ props: [
2568
+ {
2569
+ declaredPropDefaultValue: true,
2570
+ declaredPropName: "postProcessingEnabled",
2571
+ propName: "enabled",
2572
+ propValue: "postProcessingEnabled",
2573
+ declaredPropType: "boolean"
2574
+ }
2575
+ ]
2576
+ }
2577
+ };
2578
+ if (generator.options.rapier) {
2579
+ canvasProviders.push("rapier");
2580
+ }
2581
+ if (!!generator.options.postprocessing && !generator.options.xr) {
2582
+ canvasProviders.push("postprocessing");
2583
+ }
2584
+ if (generator.options.uikit) {
2585
+ globalProviders.push("uikit");
2586
+ }
2587
+ function generateProviderFunction(name, { jsdoc, providers }) {
2588
+ const resolvedProviders = providers.map((provider) => providerDefs[provider]);
2589
+ const providerProps = resolvedProviders.flatMap((provider) => provider.props || []);
2590
+ const providerImports = resolvedProviders.flatMap((provider) => provider.import);
2591
+ const wrappedComponents = resolvedProviders.filter(
2592
+ (provider) => provider.type === "wrapped-jsx"
2593
+ );
2594
+ const inlineComponents = resolvedProviders.filter(
2595
+ (provider) => provider.type === "inline-jsx"
2596
+ );
2597
+ const layoutEffects = resolvedProviders.filter(
2598
+ (provider) => provider.type === "layout-effect"
2599
+ );
2600
+ const declaredProps = providerProps.map((prop) => `${prop.declaredPropName} = ${prop.declaredPropDefaultValue}`).join(", ");
2601
+ const declaredTypes = providerProps.map((prop) => `${prop.declaredPropName}?: ${prop.declaredPropType}`).join("; ");
2602
+ const reactImports = ["type ReactNode"];
2603
+ if (layoutEffects.length) {
2604
+ reactImports.push("useLayoutEffect");
2605
+ }
2606
+ return {
2607
+ reactImports,
2608
+ imports: providerImports,
2609
+ code: `
2610
+ /**
2611
+ ${jsdoc.split("\n").map((line) => ` * ${line}`).join("\n")}
2612
+ */
2613
+ export function ${name}({ children, ${declaredProps} }: { children: ReactNode; ${declaredTypes} }) {
2614
+ ${layoutEffects.length ? `
2615
+ useLayoutEffect(() => {
2616
+ ${layoutEffects.map((effect) => effect.code).join("\n")}
2617
+ }, [${layoutEffects.map((effect) => effect.props?.[0]?.propValue)}]);
2618
+ ` : ""}
2619
+ return (
2620
+ <>
2621
+ ${inlineComponents.map((provider) => provider.code)}
2622
+ ${wrappedComponents.reduce((acc, provider) => {
2623
+ const props = provider.props?.map((prop) => `${prop.propName}={${prop.propValue}}`).join(" ");
2624
+ return `<${provider.component} ${props}>${acc}</${provider.component}>`;
2625
+ }, "{children}")}
2626
+ </>
2627
+ );
2628
+ }`
2629
+ };
2630
+ }
2631
+ const global = generateProviderFunction("GlobalProvider", {
2632
+ jsdoc: "The global provider is rendered at the root of your application,\nuse it to set up global configuration like themes.\nProps defined on this component appear as controls inside Triplex.\n\nSee: https://triplex.dev/docs/building-your-scene/providers#global-provider",
2633
+ providers: globalProviders
2634
+ });
2635
+ const canvas = generateProviderFunction("CanvasProvider", {
2636
+ jsdoc: "The canvas provider is rendered as a child inside the React Three Fiber canvas,\nuse it to set up canvas specific configuration like post-processing and physics.\nProps defined on this component appear as controls inside Triplex.\n\nSee: https://triplex.dev/docs/building-your-scene/providers#canvas-provider",
2637
+ providers: canvasProviders
2638
+ });
2639
+ return `
2640
+ import { ${unique(global.reactImports, canvas.reactImports).sort().join(", ")} } from "react";
2641
+ ${unique(global.imports, canvas.imports).sort().join("\n")}
2642
+
2643
+ ${global.code}
2644
+ ${canvas.code}
2645
+ `;
2646
+ }
2647
+ function generateTriplex(generator, options) {
2648
+ if (options == null) {
2649
+ return;
2650
+ }
2651
+ generator.inject("vscode-extension-suggestion", "trytriplex.triplex-vsce");
2652
+ generator.inject(
2653
+ "readme-tools",
2654
+ `[Triplex](https://triplex.dev) - Your visual workspace for React / Three Fiber. Get started by installing [Triplex for VS Code](https://triplex.dev/docs/get-started/vscode). Don't use Visual Studio Code? Download [Triplex Standalone](https://triplex.dev/docs/get-started/standalone).`
2655
+ );
2656
+ generator.addFile(".triplex/providers.tsx", {
2657
+ content: generateProvidersModule(generator),
2658
+ type: "text"
2659
+ });
2660
+ generator.addFile(".triplex/config.json", {
2661
+ content: JSON.stringify(
2662
+ {
2663
+ $schema: "https://triplex.dev/config.schema.json",
2664
+ provider: "./providers.tsx"
2665
+ },
2666
+ null,
2667
+ 2
2668
+ ),
2669
+ type: "text"
2670
+ });
2671
+ }
2672
+
2673
+ function generateTsdown(generator) {
2674
+ generator.addDevDependency("tsdown");
2675
+ const template = generator.options.template ?? "vanilla";
2676
+ const baseTemplate = getBaseTemplate(template);
2677
+ const language = getLanguageFromTemplate(template);
2678
+ const isReact = baseTemplate === "react" || baseTemplate === "r3f";
2679
+ const ext = language === "typescript" ? "ts" : "js";
2680
+ const configLines = [
2681
+ `import { defineConfig } from "tsdown"`,
2682
+ ``,
2683
+ `export default defineConfig({`,
2684
+ ` entry: ["./src/index.${ext}${isReact ? "x" : ""}"],`,
2685
+ ` format: ["esm", "cjs"],`,
2686
+ ` dts: ${language === "typescript"},`,
2687
+ ` clean: true,`
2688
+ ];
2689
+ if (isReact) {
2690
+ configLines.push(` esbuild: {`);
2691
+ configLines.push(` jsx: "automatic",`);
2692
+ configLines.push(` },`);
2693
+ }
2694
+ configLines.push(`})`);
2695
+ generator.addFile(`tsdown.config.${ext}`, {
2696
+ type: "text",
2697
+ content: configLines.join("\n")
2698
+ });
2699
+ generator.addScript("build", "tsdown");
2700
+ generator.inject(
2701
+ "readme-libraries",
2702
+ "[tsdown](https://github.com/nicepkg/tsdown) - Fast TypeScript bundler powered by esbuild"
2703
+ );
2704
+ }
2705
+
2706
+ function generateUikit(generator, options) {
2707
+ if (options == null) {
2708
+ return;
2709
+ }
2710
+ generator.addDependency("@react-three/uikit");
2711
+ generator.inject(
2712
+ "readme-libraries",
2713
+ `[@react-three/uikit](https://pmndrs.github.io/uikit/docs/) - UI primitives for React Three Fiber`
2714
+ );
2715
+ }
2716
+
2717
+ function generateUnbuild(generator) {
2718
+ generator.addDevDependency("unbuild");
2719
+ const template = generator.options.template ?? "vanilla";
2720
+ const baseTemplate = getBaseTemplate(template);
2721
+ const language = getLanguageFromTemplate(template);
2722
+ const isReact = baseTemplate === "react" || baseTemplate === "r3f";
2723
+ const ext = language === "typescript" ? "ts" : "js";
2724
+ const isMonorepo = generator.options.workspaceRoot != null;
2725
+ const buildConfigLines = [
2726
+ `import { defineBuildConfig } from "unbuild"`,
2727
+ ``,
2728
+ `export default defineBuildConfig({`,
2729
+ ` entries: ["./src/index"],`,
2730
+ ` declaration: ${language === "typescript"},`,
2731
+ ` clean: true,`,
2732
+ ` rollup: {`,
2733
+ ` emitCJS: true,`
2734
+ ];
2735
+ if (isReact) {
2736
+ buildConfigLines.push(` esbuild: {`);
2737
+ buildConfigLines.push(` jsx: "automatic",`);
2738
+ buildConfigLines.push(` },`);
2739
+ }
2740
+ buildConfigLines.push(` },`);
2741
+ buildConfigLines.push(`})`);
2742
+ const isStealth = generator.isStealthConfig() && !isMonorepo;
2743
+ if (isStealth) {
2744
+ generator.addFile(`.config/build.config.${ext}`, {
2745
+ type: "text",
2746
+ content: buildConfigLines.join("\n")
2747
+ });
2748
+ generator.addScript("build", `unbuild --config .config/build.config.${ext}`);
2749
+ } else {
2750
+ generator.addFile(`build.config.${ext}`, {
2751
+ type: "text",
2752
+ content: buildConfigLines.join("\n")
2753
+ });
2754
+ generator.addScript("build", "unbuild");
2755
+ }
2756
+ generator.inject(
2757
+ "readme-libraries",
2758
+ "[unbuild](https://github.com/unjs/unbuild) - Unified JavaScript build system"
2759
+ );
2760
+ }
2761
+
2762
+ function generateVitest(generator) {
2763
+ generator.addDevDependency("vitest");
2764
+ const template = generator.options.template ?? "vanilla";
2765
+ const baseTemplate = getBaseTemplate(template);
2766
+ const isReact = baseTemplate === "react" || baseTemplate === "r3f";
2767
+ if (isReact) {
2768
+ generator.addDevDependency("@testing-library/react");
2769
+ generator.addDevDependency("@testing-library/dom");
2770
+ generator.addDevDependency("jsdom");
2771
+ }
2772
+ if (isReact) {
2773
+ generator.configureVite({ test: { environment: "jsdom" } });
2774
+ }
2775
+ generator.addScript("test", "vitest");
2776
+ generator.inject(
2777
+ "readme-tools",
2778
+ "[Vitest](https://vitest.dev/) - Fast unit test framework powered by Vite"
2779
+ );
2780
+ }
2781
+
2782
+ function generateViverse(generator, options) {
2783
+ if (options == null || getPackageManagerName(generator.options.packageManager) !== "npm") {
2784
+ return;
2785
+ }
2786
+ generator.addFile(".github/workflows/viverse.yml", {
2787
+ type: "text",
2788
+ content: `name: Deploy to Viverse
2789
+
2790
+ on:
2791
+ push:
2792
+ branches:
2793
+ - main
2794
+ workflow_dispatch:
2795
+
2796
+ jobs:
2797
+ check-secrets:
2798
+ runs-on: ubuntu-latest
2799
+ outputs:
2800
+ secrets-available: \${{ steps.check.outputs.secrets-available }}
2801
+ steps:
2802
+ - id: check
2803
+ run: |
2804
+ if [[ -n "\${{ secrets.VIVERSE_EMAIL }}" && -n "\${{ secrets.VIVERSE_PASSWORD }}" ]]; then
2805
+ echo "secrets-available=true" >> $GITHUB_OUTPUT
2806
+ else
2807
+ echo "secrets-available=false" >> $GITHUB_OUTPUT
2808
+ fi
2809
+
2810
+ build-and-deploy:
2811
+ runs-on: ubuntu-latest
2812
+ needs: check-secrets
2813
+ # Only run if secrets are present
2814
+ if: needs.check-secrets.outputs.secrets-available == 'true'
2815
+ permissions:
2816
+ contents: read
2817
+
2818
+ steps:
2819
+ - name: Checkout code
2820
+ uses: actions/checkout@v3
2821
+
2822
+ - name: Setup Node
2823
+ uses: actions/setup-node@v3
2824
+ with:
2825
+ node-version: 22
2826
+
2827
+ - name: Install dependencies
2828
+ run: npm install
2829
+
2830
+ - name: Build project
2831
+ run: npm run build
2832
+
2833
+ - name: Viverse Login
2834
+ run: npx viverse-cli auth login -e \${{ secrets.VIVERSE_EMAIL }} -p \${{ secrets.VIVERSE_PASSWORD }}
2835
+
2836
+ - name: Deploy to Viverse
2837
+ run: npx viverse-cli app publish ./dist --auto-create-app --name ${generator.options.name}
2838
+
2839
+ `
2840
+ });
2841
+ generator.addDependency("@viverse/cli");
2842
+ generator.inject(
2843
+ "readme-start",
2844
+ `A GitHub CI/CD workflow for publishing to Viverse is configured.
2845
+
2846
+ To use publish to viverse via the CI/CD workflow:
2847
+ 1. Set \`VIVERSE_EMAIL\` and \`VIVERSE_PASSWORD\` secrets in your repository settings under \`Secrets and Variables\` > \`Actions\` > \`New repository secret\`
2848
+ 2. Manually trigger the "Deploy to Viverse" workflow or push to the main branch
2849
+
2850
+ **Manual CLI Upload:**
2851
+ You can also upload your project manually using the Viverse CLI:
2852
+ \`\`\`bash
2853
+ viverse-cli auth login -e <email> -p <password>
2854
+ npm run build
2855
+ viverse-cli app publish ./dist --auto-create-app --name ${generator.options.name}
2856
+ \`\`\`
2857
+ `
2858
+ );
2859
+ }
2860
+
2861
+ function generateXr(generator, options) {
2862
+ if (options == null || options === false) {
2863
+ return;
2864
+ }
2865
+ if (options === true) {
2866
+ options = {};
2867
+ }
2868
+ generator.addDependency("@react-three/xr");
2869
+ generator.addDependency("@vitejs/plugin-basic-ssl");
2870
+ generator.inject("import", "import { XR, createXRStore } from '@react-three/xr'");
2871
+ generator.inject(
2872
+ `global-start`,
2873
+ `const store = createXRStore(${JSON.stringify(options.storeOptions ?? {})})`
2874
+ );
2875
+ generator.inject("scene-start", "<XR store={store}>");
2876
+ generator.inject("scene-end", "</XR>");
2877
+ generator.inject("vite-config-import", "import basicSsl from '@vitejs/plugin-basic-ssl'");
2878
+ generator.configureVite({
2879
+ server: {
2880
+ host: true
2881
+ },
2882
+ plugins: ["$raw:basicSsl()"]
2883
+ });
2884
+ generator.inject(
2885
+ "dom-start",
2886
+ `<div style={{
2887
+ display: "flex",
2888
+ flexDirection: "row",
2889
+ gap: "1rem",
2890
+ position: 'absolute',
2891
+ zIndex: 10000,
2892
+ background: 'black',
2893
+ borderRadius: '0.5rem',
2894
+ border: 'none',
2895
+ fontWeight: 'bold',
2896
+ color: 'white',
2897
+ cursor: 'pointer',
2898
+ fontSize: '1.5rem',
2899
+ bottom: '1rem',
2900
+ left: '50%',
2901
+ boxShadow: '0px 0px 20px rgba(0,0,0,1)',
2902
+ transform: 'translate(-50%, 0)',
2903
+ }}><button
2904
+ style={{ cursor: "pointer", padding: '1rem 2rem', fontSize: "1rem", background: "none", color: "white", border: "none" }}
2905
+ onClick={() => store.enterAR()}
2906
+ >
2907
+ Enter AR
2908
+ </button>
2909
+ <button
2910
+ style={{ cursor: "pointer", padding: '1rem 2rem', fontSize: "1rem", background: "none", color: "white", border: "none" }}
2911
+ onClick={() => store.enterVR()}
2912
+ >
2913
+ Enter VR
2914
+ </button></div>`
2915
+ );
2916
+ generator.inject(
2917
+ "readme-libraries",
2918
+ `[@react-three/xr](https://pmndrs.github.io/xr/docs/) - VR/AR support for @react-three/fiber`
2919
+ );
2920
+ }
2921
+
2922
+ function generateZustand(generator, options) {
2923
+ if (options == null) {
2924
+ return;
2925
+ }
2926
+ generator.addDependency("zustand");
2927
+ generator.inject(
2928
+ "readme-libraries",
2929
+ `[zustand](https://zustand.docs.pmnd.rs/) - small, fast and scalable state-management solution`
2930
+ );
2931
+ }
2932
+
2933
+ function merge(target, modification) {
2934
+ if (modification == null) {
2935
+ throw new Error(`Cannot merge "${modification}" modification into target "${target}"`);
2936
+ }
2937
+ if (target == null) {
2938
+ return modification;
2939
+ }
2940
+ if (Array.isArray(target)) {
2941
+ if (!Array.isArray(modification)) {
2942
+ throw new Error(
2943
+ `Cannot merge non-array modification "${modification}" into array target "${target}"`
2944
+ );
2945
+ }
2946
+ return [...target, ...modification];
2947
+ }
2948
+ if (typeof target === "object") {
2949
+ if (typeof modification != "object") {
2950
+ throw new Error(
2951
+ `Cannot merge non-object modification "${modification}" into object target "${target}"`
2952
+ );
2953
+ }
2954
+ const result = { ...target };
2955
+ for (const modificationKey in modification) {
2956
+ result[modificationKey] = merge(target[modificationKey], modification[modificationKey]);
2957
+ }
2958
+ return result;
2959
+ }
2960
+ console.warn(`target "${target}" is overwritten with modification "${modification}"`);
2961
+ return modification;
2962
+ }
2963
+
2964
+ function generate(options) {
2965
+ const clonedOptions = structuredClone(options);
2966
+ const template = clonedOptions.template ?? "vanilla";
2967
+ const baseTemplate = getBaseTemplate(template);
2968
+ const language = getLanguageFromTemplate(template);
2969
+ const isVanilla = baseTemplate === "vanilla";
2970
+ const isReact = baseTemplate === "react";
2971
+ const isR3f = baseTemplate === "r3f";
2972
+ const isLibrary = clonedOptions.projectType === "library";
2973
+ const libraryBundler = clonedOptions.libraryBundler ?? "unbuild";
2974
+ const files = {
2975
+ ...clonedOptions.files
2976
+ };
2977
+ const replacements = clonedOptions.replacements ?? [];
2978
+ const versions = clonedOptions.versions ?? {};
2979
+ const dependencies = {
2980
+ ...clonedOptions.dependencies
2981
+ };
2982
+ const devDependencies = {};
2983
+ const peerDependencies = {};
2984
+ if (!isLibrary) {
2985
+ assignResolvedPackageVersion(devDependencies, versions, "vite");
2986
+ }
2987
+ if (isReact || isR3f) {
2988
+ if (isLibrary) {
2989
+ peerDependencies["react"] = "^18.0.0 || ^19.0.0";
2990
+ peerDependencies["react-dom"] = "^18.0.0 || ^19.0.0";
2991
+ } else {
2992
+ assignResolvedPackageVersion(dependencies, versions, "react");
2993
+ assignResolvedPackageVersion(dependencies, versions, "react-dom");
2994
+ assignResolvedPackageVersion(devDependencies, versions, "@vitejs/plugin-react");
2995
+ }
2996
+ }
2997
+ if (isR3f) {
2998
+ if (isLibrary) {
2999
+ peerDependencies["three"] = ">=0.150.0";
3000
+ peerDependencies["@react-three/fiber"] = "^8.0.0 || ^9.0.0";
3001
+ } else {
3002
+ assignResolvedPackageVersion(dependencies, versions, "three", "~");
3003
+ assignResolvedPackageVersion(dependencies, versions, "@react-three/fiber");
3004
+ }
3005
+ }
3006
+ if (language === "typescript") {
3007
+ const tsResult = generateTypescriptConfig({
3008
+ baseTemplate,
3009
+ useConfigPackage: clonedOptions.workspaceRoot != null,
3010
+ configStrategy: clonedOptions.configStrategy,
3011
+ engine: clonedOptions.engine,
3012
+ versions
3013
+ });
3014
+ Object.assign(files, tsResult.files);
3015
+ Object.assign(devDependencies, tsResult.devDependencies);
3016
+ }
3017
+ const codeSnippets = {};
3018
+ const vscodeSettings = {};
3019
+ const scripts = isLibrary ? {} : {
3020
+ dev: "vite",
3021
+ build: "vite build"
3022
+ };
3023
+ if (!isLibrary && (isReact || isR3f)) {
3024
+ codeSnippets["vite-config-import"] = ["import react from '@vitejs/plugin-react'"];
3025
+ }
3026
+ if (!isLibrary && isR3f) {
3027
+ codeSnippets["import"] = [`import { Canvas } from "@react-three/fiber"`];
3028
+ }
3029
+ const defaultName = isVanilla ? "vanilla-app" : isReact ? "react-app" : "react-three-app";
3030
+ const name = clonedOptions.name ?? defaultName;
3031
+ let viteConfig = {
3032
+ base: "./"
3033
+ };
3034
+ if (!isLibrary && (isReact || isR3f)) {
3035
+ viteConfig.plugins = ["$raw:react()"];
3036
+ }
3037
+ if (!isLibrary && isR3f) {
3038
+ viteConfig.resolve = { dedupe: ["three"] };
3039
+ }
3040
+ const isMonorepoPackage = clonedOptions.workspaceRoot != null;
3041
+ const generator = {
3042
+ options: clonedOptions,
3043
+ versions,
3044
+ getVersion(name2) {
3045
+ return getResolvedPackageVersion(versions, name2);
3046
+ },
3047
+ isStealthConfig() {
3048
+ return (clonedOptions.configStrategy ?? "stealth") === "stealth";
3049
+ },
3050
+ addDependency(name2, options2) {
3051
+ if (dependencies[name2] != null) {
3052
+ return;
3053
+ }
3054
+ dependencies[name2] = resolveDependencySemver(name2, versions, options2);
3055
+ },
3056
+ addDevDependency(name2, options2) {
3057
+ if (devDependencies[name2] != null) {
3058
+ return;
3059
+ }
3060
+ devDependencies[name2] = resolveDependencySemver(name2, versions, options2);
3061
+ },
3062
+ addPeerDependency(name2, semver) {
3063
+ if (peerDependencies[name2] != null) {
3064
+ return;
3065
+ }
3066
+ peerDependencies[name2] = semver;
3067
+ },
3068
+ addFile(path, content) {
3069
+ files[path] = content;
3070
+ },
3071
+ addScript(name2, command) {
3072
+ scripts[name2] = command;
3073
+ },
3074
+ inject(location, code) {
3075
+ let entries = codeSnippets[location];
3076
+ if (entries == null) {
3077
+ codeSnippets[location] = entries = [];
3078
+ }
3079
+ entries.push(code);
3080
+ },
3081
+ replace(search, replace) {
3082
+ replacements.push({ search, replace });
3083
+ },
3084
+ configureVite(config) {
3085
+ viteConfig = merge(viteConfig, config);
3086
+ },
3087
+ addVscodeSetting(key, value) {
3088
+ vscodeSettings[key] = value;
3089
+ }
3090
+ };
3091
+ if (isR3f) {
3092
+ generateDrei(generator, clonedOptions.drei);
3093
+ generateHandle(generator, clonedOptions.handle);
3094
+ generateKoota(generator, clonedOptions.koota);
3095
+ generateLeva(generator, clonedOptions.leva);
3096
+ generateOffscreen(generator, clonedOptions.offscreen);
3097
+ generatePostprocessing(generator, clonedOptions.postprocessing);
3098
+ generateRapier(generator, clonedOptions.rapier);
3099
+ generateUikit(generator, clonedOptions.uikit);
3100
+ generateXr(generator, clonedOptions.xr);
3101
+ generateZustand(generator, clonedOptions.zustand);
3102
+ generateFiber(generator, clonedOptions.fiber);
3103
+ generateTriplex(generator, clonedOptions.triplex);
3104
+ generateViverse(generator, clonedOptions.viverse);
3105
+ }
3106
+ if (!isLibrary) {
3107
+ generateGithubPages(generator, clonedOptions.githubPages);
3108
+ }
3109
+ if (isLibrary) {
3110
+ if (libraryBundler === "unbuild") {
3111
+ generateUnbuild(generator);
3112
+ } else if (libraryBundler === "tsdown") {
3113
+ generateTsdown(generator);
3114
+ }
3115
+ const packageManager2 = getPackageManagerName(clonedOptions.packageManager);
3116
+ generator.addScript("release", `${packageManager2} run build && ${packageManager2} publish`);
3117
+ }
3118
+ const testing = clonedOptions.testing ?? (isLibrary ? "vitest" : "none");
3119
+ if (testing === "vitest") {
3120
+ generateVitest(generator);
3121
+ }
3122
+ const linter = clonedOptions.linter;
3123
+ const formatter = clonedOptions.formatter;
3124
+ if (linter === "eslint") {
3125
+ generateEslint(generator);
3126
+ generator.addVscodeSetting("biome.enabled", false);
3127
+ generator.addVscodeSetting("oxc.enable", false);
3128
+ } else if (linter === "oxlint") {
3129
+ generateOxlint(generator);
3130
+ generator.addVscodeSetting("eslint.enable", false);
3131
+ generator.addVscodeSetting("biome.enabled", false);
3132
+ } else if (linter === "biome") {
3133
+ generateBiome(generator, {
3134
+ linter: true,
3135
+ formatter: formatter === "biome"
3136
+ });
3137
+ generator.addVscodeSetting("eslint.enable", false);
3138
+ generator.addVscodeSetting("oxc.enable", false);
3139
+ }
3140
+ if (formatter === "prettier") {
3141
+ generatePrettier(generator);
3142
+ } else if (formatter === "oxfmt") {
3143
+ generateOxfmt(generator);
3144
+ } else if (formatter === "biome" && linter !== "biome") {
3145
+ generateBiome(generator, { linter: false, formatter: true });
3146
+ generator.addVscodeSetting("eslint.enable", false);
3147
+ generator.addVscodeSetting("oxc.enable", false);
3148
+ }
3149
+ for (const { code, location } of clonedOptions.injections ?? []) {
3150
+ generator.inject(location, code);
3151
+ }
3152
+ if (!isLibrary) {
3153
+ files["vite.config.ts"] = generateViteConfig({ viteConfig, codeSnippets });
3154
+ }
3155
+ const packageManager = getPackageManagerName(options.packageManager);
3156
+ files["README.md"] = generateReadme({
3157
+ name,
3158
+ baseTemplate,
3159
+ isLibrary,
3160
+ libraryBundler,
3161
+ packageManager,
3162
+ codeSnippets
3163
+ });
3164
+ Object.assign(
3165
+ files,
3166
+ generateSourceFiles({
3167
+ name,
3168
+ baseTemplate,
3169
+ language,
3170
+ isLibrary,
3171
+ codeSnippets,
3172
+ replacements
3173
+ })
3174
+ );
3175
+ if (testing === "vitest") {
3176
+ Object.assign(
3177
+ files,
3178
+ generateTestFiles({
3179
+ baseTemplate,
3180
+ language,
3181
+ isLibrary
3182
+ })
3183
+ );
3184
+ }
3185
+ Object.assign(
3186
+ files,
3187
+ generatePackageJson({
3188
+ name,
3189
+ language,
3190
+ isLibrary,
3191
+ dependencies,
3192
+ devDependencies,
3193
+ peerDependencies,
3194
+ scripts,
3195
+ options: clonedOptions,
3196
+ workspaceDependencies: clonedOptions.workspaceDependencies
3197
+ }).files
3198
+ );
3199
+ if (!isMonorepoPackage) {
3200
+ Object.assign(files, generateVscodeFiles$1({ codeSnippets, vscodeSettings }));
3201
+ }
3202
+ if (!isMonorepoPackage) {
3203
+ files[".gitignore"] = generateGitignore("standalone");
3204
+ files[".gitattributes"] = { type: "text", content: GitAttributes };
3205
+ }
3206
+ if (!isMonorepoPackage && clonedOptions.aiPlatforms?.length) {
3207
+ generateAiFiles(files, {
3208
+ name,
3209
+ packageManager: getPackageManagerName(clonedOptions.packageManager),
3210
+ linter: clonedOptions.linter ?? "oxlint",
3211
+ formatter: clonedOptions.formatter ?? "prettier",
3212
+ isMonorepo: false,
3213
+ configStrategy: clonedOptions.configStrategy,
3214
+ platforms: clonedOptions.aiPlatforms
3215
+ });
3216
+ }
3217
+ return files;
3218
+ }
3219
+ function resolveDependencySemver(name, versions, options = {}) {
3220
+ if (options.version != null) {
3221
+ return options.version;
3222
+ }
3223
+ return formatResolvedPackageVersion(versions, name, options.prefix);
3224
+ }
3225
+
3226
+ export { ALL_AI_PLATFORMS as A, validatePackageName as B, generateMonorepo as C, getLatestNodeVersion as D, getLatestNpmCliVersion as E, getLatestNpmVersion as F, getLatestPnpmVersion as G, getLatestYarnVersion as H, monorepo as I, getBaseTemplate as a, getLanguageFromTemplate as b, getPackageManagerName as c, generateRandomName as d, detectTooling as e, generateAiFiles as f, getEngineName as g, generateVscodeFiles as h, generateTypescriptConfigPackage as i, generateOxlintConfigPackage as j, generateEslintConfigPackage as k, generateOxfmtConfigPackage as l, generatePrettierConfigPackage as m, generateGitignore as n, getResolvedPackageVersion as o, parseWorkspaceYamlContent as p, formatResolvedPackageVersion as q, resolveMonorepoRootPackageVersions as r, resolvePackageManager as s, resolveEngine as t, resolveProjectPackageVersions as u, generate as v, parsePackageManager as w, parseEngine as x, AI_PLATFORM_LABELS as y, AI_PLATFORM_HINTS as z };