create-krispya 0.6.0 → 0.7.0

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