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