@tanstack/cli 0.0.7 → 0.48.2

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.
Files changed (83) hide show
  1. package/dist/bin.js +7 -0
  2. package/dist/cli.js +481 -0
  3. package/dist/command-line.js +174 -0
  4. package/dist/dev-watch.js +290 -0
  5. package/dist/file-syncer.js +148 -0
  6. package/dist/index.js +1 -0
  7. package/dist/mcp/api.js +31 -0
  8. package/dist/mcp/tools.js +250 -0
  9. package/dist/mcp/types.js +37 -0
  10. package/dist/mcp.js +121 -0
  11. package/dist/options.js +162 -0
  12. package/dist/types/bin.d.ts +2 -0
  13. package/dist/types/cli.d.ts +16 -0
  14. package/dist/types/command-line.d.ts +10 -0
  15. package/dist/types/dev-watch.d.ts +27 -0
  16. package/dist/types/file-syncer.d.ts +18 -0
  17. package/dist/types/index.d.ts +1 -0
  18. package/dist/types/mcp/api.d.ts +4 -0
  19. package/dist/types/mcp/tools.d.ts +2 -0
  20. package/dist/types/mcp/types.d.ts +217 -0
  21. package/dist/types/mcp.d.ts +6 -0
  22. package/dist/types/options.d.ts +8 -0
  23. package/dist/types/types.d.ts +25 -0
  24. package/dist/types/ui-environment.d.ts +2 -0
  25. package/dist/types/ui-prompts.d.ts +12 -0
  26. package/dist/types/utils.d.ts +8 -0
  27. package/dist/types.js +1 -0
  28. package/dist/ui-environment.js +52 -0
  29. package/dist/ui-prompts.js +244 -0
  30. package/dist/utils.js +30 -0
  31. package/package.json +46 -46
  32. package/src/bin.ts +6 -93
  33. package/src/cli.ts +692 -0
  34. package/src/command-line.ts +236 -0
  35. package/src/dev-watch.ts +430 -0
  36. package/src/file-syncer.ts +205 -0
  37. package/src/index.ts +1 -85
  38. package/src/mcp.ts +190 -0
  39. package/src/options.ts +260 -0
  40. package/src/types.ts +27 -0
  41. package/src/ui-environment.ts +74 -0
  42. package/src/ui-prompts.ts +322 -0
  43. package/src/utils.ts +38 -0
  44. package/tests/command-line.test.ts +304 -0
  45. package/tests/index.test.ts +9 -0
  46. package/tests/mcp.test.ts +225 -0
  47. package/tests/options.test.ts +304 -0
  48. package/tests/setupVitest.ts +6 -0
  49. package/tests/ui-environment.test.ts +97 -0
  50. package/tests/ui-prompts.test.ts +238 -0
  51. package/tsconfig.json +17 -0
  52. package/vitest.config.js +7 -0
  53. package/dist/bin.cjs +0 -761
  54. package/dist/bin.d.cts +0 -1
  55. package/dist/bin.d.mts +0 -1
  56. package/dist/bin.mjs +0 -760
  57. package/dist/index.cjs +0 -36
  58. package/dist/index.d.cts +0 -1172
  59. package/dist/index.d.mts +0 -1172
  60. package/dist/index.mjs +0 -3
  61. package/dist/template-CkAkdP8n.mjs +0 -2545
  62. package/dist/template-Cup47s9h.cjs +0 -2783
  63. package/src/api/fetch.test.ts +0 -114
  64. package/src/api/fetch.ts +0 -249
  65. package/src/cache/index.ts +0 -89
  66. package/src/commands/create.ts +0 -463
  67. package/src/commands/mcp.test.ts +0 -152
  68. package/src/commands/mcp.ts +0 -203
  69. package/src/engine/compile-with-addons.test.ts +0 -302
  70. package/src/engine/compile.test.ts +0 -404
  71. package/src/engine/compile.ts +0 -551
  72. package/src/engine/config-file.test.ts +0 -118
  73. package/src/engine/config-file.ts +0 -61
  74. package/src/engine/custom-addons/integration.ts +0 -323
  75. package/src/engine/custom-addons/shared.test.ts +0 -98
  76. package/src/engine/custom-addons/shared.ts +0 -281
  77. package/src/engine/custom-addons/template.test.ts +0 -288
  78. package/src/engine/custom-addons/template.ts +0 -124
  79. package/src/engine/template.test.ts +0 -256
  80. package/src/engine/template.ts +0 -269
  81. package/src/engine/types.ts +0 -336
  82. package/src/parse-gitignore.d.ts +0 -5
  83. package/src/templates/base.ts +0 -891
package/dist/bin.mjs DELETED
@@ -1,760 +0,0 @@
1
- #!/usr/bin/env node
2
- import { A as writeConfigFile, a as initIntegration, d as fetchManifest, i as compileIntegration, j as compile, n as initTemplate, r as loadTemplate, t as compileTemplate, u as fetchIntegrations } from "./template-CkAkdP8n.mjs";
3
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
4
- import { resolve } from "node:path";
5
- import { z } from "zod";
6
- import { Command } from "commander";
7
- import { cancel, confirm, intro, isCancel, log, multiselect, note, outro, select, spinner, text } from "@clack/prompts";
8
- import chalk from "chalk";
9
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
10
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
11
- import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
12
- import express from "express";
13
-
14
- //#region src/commands/create.ts
15
- const PACKAGE_MANAGERS = [
16
- "pnpm",
17
- "npm",
18
- "yarn",
19
- "bun",
20
- "deno"
21
- ];
22
- function detectPackageManager() {
23
- const userAgent = process.env.npm_config_user_agent;
24
- if (userAgent) {
25
- if (userAgent.includes("pnpm")) return "pnpm";
26
- if (userAgent.includes("yarn")) return "yarn";
27
- if (userAgent.includes("bun")) return "bun";
28
- if (userAgent.includes("deno")) return "deno";
29
- }
30
- return "npm";
31
- }
32
- function validateProjectName(name) {
33
- if (!name) return {
34
- valid: false,
35
- error: "Project name is required"
36
- };
37
- if (!/^[a-z0-9-_]+$/.test(name)) return {
38
- valid: false,
39
- error: "Project name can only contain lowercase letters, numbers, hyphens, and underscores"
40
- };
41
- return { valid: true };
42
- }
43
- function groupIntegrationsByCategory(integrations) {
44
- const groups = {};
45
- for (const integration of integrations) {
46
- const category = integration.category ?? "other";
47
- groups[category] ??= [];
48
- groups[category].push(integration);
49
- }
50
- return groups;
51
- }
52
- const CATEGORY_LABELS = {
53
- tanstack: "TanStack",
54
- database: "Database",
55
- orm: "ORM",
56
- auth: "Authentication",
57
- deploy: "Deployment",
58
- tooling: "Tooling",
59
- monitoring: "Monitoring",
60
- api: "API",
61
- i18n: "Internationalization",
62
- cms: "CMS",
63
- other: "Other"
64
- };
65
- const CATEGORY_ORDER = [
66
- "tanstack",
67
- "database",
68
- "orm",
69
- "auth",
70
- "deploy",
71
- "api",
72
- "monitoring",
73
- "tooling",
74
- "i18n",
75
- "cms",
76
- "other"
77
- ];
78
- async function runCreate(projectName, options) {
79
- intro(chalk.bgCyan(chalk.black(" TanStack Start ")));
80
- const s = spinner();
81
- const integrationsPath = options.integrationsPath;
82
- s.start("Fetching available integrations...");
83
- let manifest;
84
- try {
85
- manifest = await fetchManifest(integrationsPath);
86
- s.stop("Integrations loaded");
87
- } catch (error$1) {
88
- s.stop("Failed to fetch integrations");
89
- log.error("Could not fetch integration manifest. Check your internet connection.");
90
- process.exit(1);
91
- }
92
- let name = projectName;
93
- if (!name && !options.yes) {
94
- const nameInput = await text({
95
- message: "Project name:",
96
- placeholder: "my-tanstack-app",
97
- defaultValue: "my-tanstack-app",
98
- validate: (value) => {
99
- const result = validateProjectName(value);
100
- return result.valid ? void 0 : result.error;
101
- }
102
- });
103
- if (isCancel(nameInput)) {
104
- cancel("Operation cancelled.");
105
- process.exit(0);
106
- }
107
- name = nameInput;
108
- }
109
- name = name ?? "my-tanstack-app";
110
- const { valid, error } = validateProjectName(name);
111
- if (!valid) {
112
- log.error(error ?? "Invalid project name");
113
- process.exit(1);
114
- }
115
- const targetDir = options.targetDir ? resolve(options.targetDir) : resolve(process.cwd(), name);
116
- if (existsSync(targetDir)) {
117
- if (!options.yes) {
118
- const overwrite = await confirm({
119
- message: `Directory ${chalk.cyan(name)} already exists. Overwrite?`,
120
- initialValue: false
121
- });
122
- if (isCancel(overwrite) || !overwrite) {
123
- cancel("Operation cancelled.");
124
- process.exit(0);
125
- }
126
- }
127
- }
128
- let packageManager = options.packageManager ?? detectPackageManager();
129
- if (!options.packageManager && !options.yes) {
130
- const pmChoice = await select({
131
- message: "Package manager:",
132
- options: PACKAGE_MANAGERS.map((pm) => ({
133
- value: pm,
134
- label: pm
135
- })),
136
- initialValue: packageManager
137
- });
138
- if (isCancel(pmChoice)) {
139
- cancel("Operation cancelled.");
140
- process.exit(0);
141
- }
142
- packageManager = pmChoice;
143
- }
144
- let tailwind = options.tailwind ?? true;
145
- if (options.tailwind === void 0 && !options.yes) {
146
- const twChoice = await confirm({
147
- message: "Include Tailwind CSS?",
148
- initialValue: true
149
- });
150
- if (isCancel(twChoice)) {
151
- cancel("Operation cancelled.");
152
- process.exit(0);
153
- }
154
- tailwind = twChoice;
155
- }
156
- let selectedIntegrationIds = [];
157
- if (options.integrations) selectedIntegrationIds = options.integrations.split(",").map((s$1) => s$1.trim());
158
- else if (!options.yes) {
159
- const grouped = groupIntegrationsByCategory(manifest.integrations.filter((a) => a.type === "integration" && a.modes.includes("file-router")));
160
- const categoryOptions = CATEGORY_ORDER.filter((cat) => grouped[cat]?.length).map((cat) => ({
161
- value: cat,
162
- label: CATEGORY_LABELS[cat] ?? cat,
163
- hint: `${grouped[cat].length} integrations`
164
- }));
165
- note("Use arrow keys to navigate, space to select/deselect, enter to confirm.", "Integration Selection");
166
- const selectedCategories = await multiselect({
167
- message: "Which categories would you like to explore?",
168
- options: categoryOptions,
169
- required: false
170
- });
171
- if (isCancel(selectedCategories)) {
172
- cancel("Operation cancelled.");
173
- process.exit(0);
174
- }
175
- for (const category of selectedCategories) {
176
- const categoryIntegrations = grouped[category];
177
- if (!categoryIntegrations?.length) continue;
178
- const integrationChoices = await multiselect({
179
- message: `Select ${CATEGORY_LABELS[category]} integrations:`,
180
- options: categoryIntegrations.map((integration) => ({
181
- value: integration.id,
182
- label: integration.name,
183
- hint: integration.description
184
- })),
185
- required: false
186
- });
187
- if (isCancel(integrationChoices)) {
188
- cancel("Operation cancelled.");
189
- process.exit(0);
190
- }
191
- selectedIntegrationIds.push(...integrationChoices);
192
- }
193
- }
194
- const integrationMap = new Map(manifest.integrations.map((a) => [a.id, a]));
195
- const resolvedIds = new Set(selectedIntegrationIds);
196
- for (const id of selectedIntegrationIds) {
197
- const integration = integrationMap.get(id);
198
- if (integration?.dependsOn) for (const dep of integration.dependsOn) resolvedIds.add(dep);
199
- }
200
- if (resolvedIds.size > 0) note(Array.from(resolvedIds).map((id) => {
201
- const integration = integrationMap.get(id);
202
- return ` ${!selectedIntegrationIds.includes(id) && resolvedIds.has(id) ? chalk.dim("(auto)") : chalk.green("+")} ${integration?.name ?? id}`;
203
- }).join("\n"), "Selected Integrations");
204
- if (!options.yes) {
205
- const proceed = await confirm({
206
- message: "Create project?",
207
- initialValue: true
208
- });
209
- if (isCancel(proceed) || !proceed) {
210
- cancel("Operation cancelled.");
211
- process.exit(0);
212
- }
213
- }
214
- s.start("Preparing project...");
215
- let customTemplate;
216
- if (options.template) try {
217
- customTemplate = await loadTemplate(options.template);
218
- for (const integrationId of customTemplate.integrations) resolvedIds.add(integrationId);
219
- tailwind = customTemplate.tailwind;
220
- } catch (error$1) {
221
- s.stop("Failed to load template");
222
- log.error(error$1 instanceof Error ? error$1.message : "Could not load template from URL.");
223
- process.exit(1);
224
- }
225
- let chosenIntegrations = [];
226
- if (resolvedIds.size > 0) try {
227
- chosenIntegrations = await fetchIntegrations(Array.from(resolvedIds), integrationsPath);
228
- } catch (error$1) {
229
- s.stop("Failed to fetch integration details");
230
- log.error("Could not fetch integration definitions.");
231
- process.exit(1);
232
- }
233
- const compileOptions = {
234
- projectName: name,
235
- framework: customTemplate?.framework ?? "react",
236
- mode: customTemplate?.mode ?? "file-router",
237
- typescript: customTemplate?.typescript ?? true,
238
- tailwind,
239
- packageManager,
240
- chosenIntegrations,
241
- integrationOptions: customTemplate?.integrationOptions ?? {},
242
- customTemplate
243
- };
244
- const output = compile(compileOptions);
245
- s.stop("Project prepared");
246
- s.start("Writing files...");
247
- mkdirSync(targetDir, { recursive: true });
248
- for (const [filePath, content] of Object.entries(output.files)) {
249
- const fullPath = resolve(targetDir, filePath);
250
- mkdirSync(resolve(fullPath, ".."), { recursive: true });
251
- writeFileSync(fullPath, content, "utf-8");
252
- }
253
- await writeConfigFile(targetDir, compileOptions);
254
- s.stop("Files written");
255
- if (options.git !== false) {
256
- s.start("Initializing git repository...");
257
- try {
258
- const { execSync } = await import("node:child_process");
259
- execSync("git init", {
260
- cwd: targetDir,
261
- stdio: "ignore"
262
- });
263
- s.stop("Git initialized");
264
- } catch {
265
- s.stop("Git initialization skipped");
266
- }
267
- }
268
- if (options.install !== false) {
269
- s.start(`Installing dependencies with ${packageManager}...`);
270
- const startTime = Date.now();
271
- const interval = setInterval(() => {
272
- const elapsed = Math.floor((Date.now() - startTime) / 1e3);
273
- s.message(`Installing dependencies with ${packageManager}... (${elapsed}s)`);
274
- }, 1e3);
275
- try {
276
- const { execSync } = await import("node:child_process");
277
- execSync(packageManager === "yarn" ? "yarn" : `${packageManager} install`, {
278
- cwd: targetDir,
279
- stdio: "ignore"
280
- });
281
- clearInterval(interval);
282
- const total = Math.floor((Date.now() - startTime) / 1e3);
283
- s.stop(`Dependencies installed (${total}s)`);
284
- } catch {
285
- clearInterval(interval);
286
- s.stop("Dependency installation failed");
287
- log.warning(`Run "${packageManager} install" manually to install dependencies.`);
288
- }
289
- }
290
- const relativePath = resolve(process.cwd()) === targetDir ? "." : name;
291
- outro(chalk.green("Project created successfully!"));
292
- console.log();
293
- console.log("Next steps:");
294
- console.log();
295
- if (relativePath !== ".") console.log(` ${chalk.cyan("cd")} ${relativePath}`);
296
- if (options.install === false) console.log(` ${chalk.cyan(packageManager)} install`);
297
- console.log(` ${chalk.cyan(packageManager)} ${packageManager === "npm" ? "run " : ""}dev`);
298
- console.log();
299
- if (output.envVars.length > 0) {
300
- console.log(chalk.yellow("Environment variables needed:"));
301
- console.log();
302
- for (const envVar of output.envVars) console.log(` ${chalk.cyan(envVar.name)} - ${envVar.description}`);
303
- console.log();
304
- console.log(` Add these to your ${chalk.cyan(".env.local")} file.`);
305
- console.log();
306
- }
307
- for (const warning of output.warnings) log.warning(warning);
308
- }
309
-
310
- //#endregion
311
- //#region src/mcp/types.ts
312
- const LibrarySchema = z.object({
313
- id: z.string(),
314
- name: z.string(),
315
- tagline: z.string(),
316
- description: z.string().optional(),
317
- frameworks: z.array(z.string()),
318
- latestVersion: z.string(),
319
- latestBranch: z.string().optional(),
320
- availableVersions: z.array(z.string()),
321
- repo: z.string(),
322
- docsRoot: z.string().optional(),
323
- defaultDocs: z.string().optional(),
324
- docsUrl: z.string().optional(),
325
- githubUrl: z.string().optional()
326
- });
327
- const LibrariesResponseSchema = z.object({
328
- libraries: z.array(LibrarySchema),
329
- groups: z.record(z.array(z.string())),
330
- groupNames: z.record(z.string())
331
- });
332
- const PartnerSchema = z.object({
333
- id: z.string(),
334
- name: z.string(),
335
- tagline: z.string().optional(),
336
- description: z.string(),
337
- category: z.string(),
338
- categoryLabel: z.string(),
339
- libraries: z.array(z.string()),
340
- url: z.string()
341
- });
342
- const PartnersResponseSchema = z.object({
343
- partners: z.array(PartnerSchema),
344
- categories: z.array(z.string()),
345
- categoryLabels: z.record(z.string())
346
- });
347
-
348
- //#endregion
349
- //#region src/mcp/api.ts
350
- const TANSTACK_API_BASE = "https://tanstack.com/api/data";
351
- async function fetchLibraries() {
352
- const response = await fetch(`${TANSTACK_API_BASE}/libraries`);
353
- if (!response.ok) throw new Error(`Failed to fetch libraries: ${response.statusText}`);
354
- const data = await response.json();
355
- return LibrariesResponseSchema.parse(data);
356
- }
357
- async function fetchPartners() {
358
- const response = await fetch(`${TANSTACK_API_BASE}/partners`);
359
- if (!response.ok) throw new Error(`Failed to fetch partners: ${response.statusText}`);
360
- const data = await response.json();
361
- return PartnersResponseSchema.parse(data);
362
- }
363
- async function fetchDocContent(repo, branch, filePath) {
364
- const url = `https://raw.githubusercontent.com/${repo}/${branch}/${filePath}`;
365
- const response = await fetch(url, { headers: { "User-Agent": "tanstack-cli" } });
366
- if (!response.ok) {
367
- if (response.status === 404) return null;
368
- throw new Error(`Failed to fetch doc: ${response.statusText}`);
369
- }
370
- return response.text();
371
- }
372
-
373
- //#endregion
374
- //#region src/mcp/tools.ts
375
- const ALGOLIA_APP_ID = "FQ0DQ6MA3C";
376
- const ALGOLIA_API_KEY = "10c34d6a5c89f6048cf644d601e65172";
377
- const ALGOLIA_INDEX = "tanstack-test";
378
- const GROUP_KEYS = [
379
- "state",
380
- "headlessUI",
381
- "performance",
382
- "tooling"
383
- ];
384
- function jsonResult(data) {
385
- return { content: [{
386
- type: "text",
387
- text: JSON.stringify(data, null, 2)
388
- }] };
389
- }
390
- function errorResult(error) {
391
- return {
392
- content: [{
393
- type: "text",
394
- text: `Error: ${error}`
395
- }],
396
- isError: true
397
- };
398
- }
399
- function registerDocTools(server) {
400
- server.tool("tanstack_list_libraries", "List TanStack libraries with metadata, frameworks, and docs URLs.", { group: z.enum(GROUP_KEYS).optional().describe("Filter libraries by group. Options: state, headlessUI, performance, tooling") }, async ({ group }) => {
401
- try {
402
- const data = await fetchLibraries();
403
- let libraries = data.libraries;
404
- if (group && data.groups[group]) {
405
- const groupIds = data.groups[group];
406
- libraries = libraries.filter((lib) => groupIds.includes(lib.id));
407
- }
408
- return jsonResult({
409
- group: group ? data.groupNames[group] || group : "All Libraries",
410
- count: libraries.length,
411
- libraries: libraries.map((lib) => ({
412
- id: lib.id,
413
- name: lib.name,
414
- tagline: lib.tagline,
415
- description: lib.description,
416
- frameworks: lib.frameworks,
417
- latestVersion: lib.latestVersion,
418
- docsUrl: lib.docsUrl,
419
- githubUrl: lib.githubUrl
420
- }))
421
- });
422
- } catch (error) {
423
- return errorResult(String(error));
424
- }
425
- });
426
- server.tool("tanstack_doc", "Fetch a TanStack documentation page by library and path.", {
427
- library: z.string().describe("Library ID (e.g., query, router, table, form)"),
428
- path: z.string().describe("Documentation path (e.g., framework/react/overview)"),
429
- version: z.string().optional().describe("Version (e.g., v5, v1). Defaults to latest")
430
- }, async ({ library: libraryId, path, version = "latest" }) => {
431
- try {
432
- const library = (await fetchLibraries()).libraries.find((l) => l.id === libraryId);
433
- if (!library) return errorResult(`Library "${libraryId}" not found. Use tanstack_list_libraries to see available libraries.`);
434
- if (version !== "latest" && !library.availableVersions.includes(version)) return errorResult(`Version "${version}" not found for ${library.name}. Available: ${library.availableVersions.join(", ")}`);
435
- const branch = version === "latest" || version === library.latestVersion ? library.latestBranch || "main" : version;
436
- const filePath = `${library.docsRoot || "docs"}/${path}.md`;
437
- const content = await fetchDocContent(library.repo, branch, filePath);
438
- if (!content) return errorResult(`Document not found: ${library.name} / ${path} (version: ${version})`);
439
- const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---/);
440
- let title = path.split("/").pop() || "Untitled";
441
- let docContent = content;
442
- if (frontmatterMatch && frontmatterMatch[1]) {
443
- const titleMatch = frontmatterMatch[1].match(/title:\s*['"]?([^'"\n]+)['"]?/);
444
- if (titleMatch && titleMatch[1]) title = titleMatch[1];
445
- docContent = content.slice(frontmatterMatch[0].length).trim();
446
- }
447
- return jsonResult({
448
- title,
449
- content: docContent,
450
- url: `https://tanstack.com/${libraryId}/${version}/docs/${path}`,
451
- library: library.name,
452
- version: version === "latest" ? library.latestVersion : version
453
- });
454
- } catch (error) {
455
- return errorResult(String(error));
456
- }
457
- });
458
- server.tool("tanstack_search_docs", "Search TanStack documentation. Returns matching pages with snippets.", {
459
- query: z.string().describe("Search query"),
460
- library: z.string().optional().describe("Filter to specific library (e.g., query, router)"),
461
- framework: z.string().optional().describe("Filter to specific framework (e.g., react, vue, solid)"),
462
- limit: z.number().min(1).max(50).optional().describe("Maximum number of results (default: 10, max: 50)")
463
- }, async ({ query, library, framework, limit = 10 }) => {
464
- try {
465
- const ALL_LIBRARIES = [
466
- "config",
467
- "form",
468
- "optimistic",
469
- "pacer",
470
- "query",
471
- "ranger",
472
- "react-charts",
473
- "router",
474
- "start",
475
- "store",
476
- "table",
477
- "virtual",
478
- "db",
479
- "devtools"
480
- ];
481
- const ALL_FRAMEWORKS = [
482
- "react",
483
- "vue",
484
- "solid",
485
- "svelte",
486
- "angular"
487
- ];
488
- const filterParts = ["version:latest"];
489
- if (library) {
490
- const exclusions = ALL_LIBRARIES.filter((l) => l !== library).map((l) => `NOT library:${l}`).join(" AND ");
491
- if (exclusions) filterParts.push(`(${exclusions})`);
492
- }
493
- if (framework) {
494
- const exclusions = ALL_FRAMEWORKS.filter((f) => f !== framework).map((f) => `NOT framework:${f}`).join(" AND ");
495
- if (exclusions) filterParts.push(`(${exclusions})`);
496
- }
497
- const searchParams = { requests: [{
498
- indexName: ALGOLIA_INDEX,
499
- query,
500
- hitsPerPage: Math.min(limit, 50),
501
- filters: filterParts.join(" AND "),
502
- attributesToRetrieve: [
503
- "hierarchy",
504
- "url",
505
- "content",
506
- "library"
507
- ],
508
- attributesToSnippet: ["content:80"]
509
- }] };
510
- const response = await fetch(`https://${ALGOLIA_APP_ID}-dsn.algolia.net/1/indexes/*/queries`, {
511
- method: "POST",
512
- headers: {
513
- "Content-Type": "application/json",
514
- "X-Algolia-Application-Id": ALGOLIA_APP_ID,
515
- "X-Algolia-API-Key": ALGOLIA_API_KEY
516
- },
517
- body: JSON.stringify(searchParams)
518
- });
519
- if (!response.ok) return errorResult(`Algolia search failed: ${response.statusText}`);
520
- const searchResult = (await response.json()).results[0];
521
- if (!searchResult) return jsonResult({
522
- query,
523
- totalHits: 0,
524
- results: []
525
- });
526
- const results = searchResult.hits.map((hit) => {
527
- const breadcrumb = Object.values(hit.hierarchy).filter((v) => Boolean(v));
528
- return {
529
- title: hit.hierarchy.lvl1 || hit.hierarchy.lvl0 || "Untitled",
530
- url: hit.url,
531
- snippet: hit._snippetResult?.content?.value || hit.content || "",
532
- library: hit.library || "unknown",
533
- breadcrumb
534
- };
535
- });
536
- return jsonResult({
537
- query,
538
- totalHits: searchResult.nbHits || results.length,
539
- results
540
- });
541
- } catch (error) {
542
- return errorResult(String(error));
543
- }
544
- });
545
- server.tool("tanstack_ecosystem", "Ecosystem partner recommendations. Filter by category (database, auth, deployment, monitoring, cms, api, data-grid) or library.", {
546
- category: z.string().optional().describe("Filter by category: database, auth, deployment, monitoring, cms, api, data-grid, code-review, learning"),
547
- library: z.string().optional().describe("Filter by TanStack library (e.g., start, router, query, table)")
548
- }, async ({ category, library }) => {
549
- try {
550
- const data = await fetchPartners();
551
- const categoryAliases = {
552
- db: "database",
553
- postgres: "database",
554
- sql: "database",
555
- login: "auth",
556
- authentication: "auth",
557
- hosting: "deployment",
558
- deploy: "deployment",
559
- serverless: "deployment",
560
- errors: "monitoring",
561
- logging: "monitoring",
562
- content: "cms",
563
- "api-keys": "api",
564
- grid: "data-grid",
565
- review: "code-review",
566
- courses: "learning"
567
- };
568
- let resolvedCategory;
569
- if (category) {
570
- const normalized = category.toLowerCase().trim();
571
- resolvedCategory = categoryAliases[normalized] || normalized;
572
- if (!data.categories.includes(resolvedCategory)) resolvedCategory = void 0;
573
- }
574
- const lib = library?.toLowerCase().trim();
575
- const partners = data.partners.filter((p) => !resolvedCategory || p.category === resolvedCategory).filter((p) => !lib || p.libraries.some((l) => l === lib)).map((p) => ({
576
- id: p.id,
577
- name: p.name,
578
- tagline: p.tagline,
579
- description: p.description,
580
- category: p.category,
581
- categoryLabel: p.categoryLabel,
582
- url: p.url,
583
- libraries: p.libraries
584
- }));
585
- return jsonResult({
586
- query: {
587
- category,
588
- categoryResolved: resolvedCategory,
589
- library
590
- },
591
- count: partners.length,
592
- partners
593
- });
594
- } catch (error) {
595
- return errorResult(String(error));
596
- }
597
- });
598
- }
599
-
600
- //#endregion
601
- //#region src/commands/mcp.ts
602
- function createServer() {
603
- const server = new McpServer({
604
- name: "TanStack CLI",
605
- version: "0.0.1"
606
- });
607
- server.tool("listTanStackIntegrations", "List available integrations for creating TanStack applications", {}, async () => {
608
- try {
609
- const integrations = (await fetchManifest()).integrations.filter((a) => a.modes.includes("file-router")).map((integration) => ({
610
- id: integration.id,
611
- name: integration.name,
612
- description: integration.description,
613
- category: integration.category,
614
- dependsOn: integration.dependsOn,
615
- exclusive: integration.exclusive,
616
- hasOptions: integration.hasOptions
617
- }));
618
- return { content: [{
619
- type: "text",
620
- text: JSON.stringify(integrations, null, 2)
621
- }] };
622
- } catch (error) {
623
- return { content: [{
624
- type: "text",
625
- text: `Error fetching integrations: ${error}`
626
- }] };
627
- }
628
- });
629
- registerDocTools(server);
630
- server.tool("createTanStackApplication", "Create a new TanStack Start application", {
631
- projectName: z.string().describe("The name of the project (will be the directory name)"),
632
- targetDir: z.string().describe("Absolute path where the project should be created"),
633
- integrations: z.array(z.string()).optional().describe("Array of integration IDs to include. Use listTanStackIntegrations to see available options."),
634
- integrationOptions: z.record(z.record(z.unknown())).optional().describe("Configuration for integrations. Format: {\"integrationId\": {\"optionName\": \"value\"}}"),
635
- tailwind: z.boolean().optional().describe("Include Tailwind CSS (default: true)"),
636
- packageManager: z.enum([
637
- "npm",
638
- "pnpm",
639
- "yarn",
640
- "bun",
641
- "deno"
642
- ]).optional().describe("Package manager to use (default: pnpm)")
643
- }, async ({ projectName, targetDir, integrations, integrationOptions, tailwind, packageManager }) => {
644
- try {
645
- const { mkdirSync: mkdirSync$1, writeFileSync: writeFileSync$1 } = await import("node:fs");
646
- const { resolve: resolve$1 } = await import("node:path");
647
- const { execSync } = await import("node:child_process");
648
- let chosenIntegrations = [];
649
- if (integrations?.length) chosenIntegrations = await fetchIntegrations(integrations);
650
- const output = compile({
651
- projectName,
652
- framework: "react",
653
- mode: "file-router",
654
- typescript: true,
655
- tailwind: tailwind ?? true,
656
- packageManager: packageManager ?? "pnpm",
657
- chosenIntegrations,
658
- integrationOptions: integrationOptions ?? {}
659
- });
660
- mkdirSync$1(targetDir, { recursive: true });
661
- for (const [filePath, content] of Object.entries(output.files)) {
662
- const fullPath = resolve$1(targetDir, filePath);
663
- mkdirSync$1(resolve$1(fullPath, ".."), { recursive: true });
664
- writeFileSync$1(fullPath, content, "utf-8");
665
- }
666
- try {
667
- execSync("git init", {
668
- cwd: targetDir,
669
- stdio: "ignore"
670
- });
671
- } catch {}
672
- const envVarList = output.envVars.length > 0 ? `\n\nRequired environment variables:\n${output.envVars.map((e) => `- ${e.name}: ${e.description}`).join("\n")}` : "";
673
- const warnings = output.warnings.length > 0 ? `\n\nWarnings:\n${output.warnings.map((w) => `- ${w}`).join("\n")}` : "";
674
- return { content: [{
675
- type: "text",
676
- text: `Project "${projectName}" created successfully at ${targetDir}
677
-
678
- Files created: ${Object.keys(output.files).length}
679
- Integrations included: ${chosenIntegrations.map((a) => a.name).join(", ") || "none"}${envVarList}${warnings}
680
-
681
- Next steps:
682
- 1. cd ${targetDir}
683
- 2. ${packageManager ?? "pnpm"} install
684
- 3. ${packageManager ?? "pnpm"} dev`
685
- }] };
686
- } catch (error) {
687
- return { content: [{
688
- type: "text",
689
- text: `Error creating application: ${error}`
690
- }] };
691
- }
692
- });
693
- return server;
694
- }
695
- async function runMcp(options) {
696
- const server = createServer();
697
- if (options.sse) {
698
- const app = express();
699
- let transport = null;
700
- app.get("/sse", (_req, res) => {
701
- transport = new SSEServerTransport("/messages", res);
702
- server.connect(transport);
703
- });
704
- app.post("/messages", (req, res) => {
705
- if (transport) transport.handlePostMessage(req, res);
706
- });
707
- const port = parseInt(options.port ?? "8080", 10);
708
- app.listen(port, () => {
709
- console.log(`MCP server running at http://localhost:${port}/sse`);
710
- });
711
- } else {
712
- const transport = new StdioServerTransport();
713
- await server.connect(transport);
714
- }
715
- }
716
-
717
- //#endregion
718
- //#region src/bin.ts
719
- const program = new Command();
720
- program.name("tanstack").description("TanStack CLI for scaffolding and tooling").version("0.0.1");
721
- program.command("create").argument("[project-name]", "name of the project").option("--template <template>", "URL to a custom template JSON file").option("--package-manager <pm>", "package manager (npm, pnpm, yarn, bun)").option("--integrations <integrations>", "comma-separated list of integration IDs").option("--no-install", "skip installing dependencies").option("--no-git", "skip initializing git repository").option("--no-tailwind", "skip tailwind CSS").option("-y, --yes", "skip prompts and use defaults").option("--target-dir <path>", "target directory for the project").option("--integrations-path <path>", "local path to integrations directory (for development)").description("Create a new TanStack Start project").action(runCreate);
722
- program.command("mcp").option("--sse", "run in SSE mode (for HTTP transport)").option("--port <port>", "port for SSE server", "8080").description("Start the MCP server for AI agents").action(runMcp);
723
- const integrationCommand = program.command("integration");
724
- integrationCommand.command("init").option("--integrations-path <path>", "local path to integrations directory (for development)").description("Initialize an integration from the current project").action(async (options) => {
725
- try {
726
- await initIntegration(resolve(process.cwd()), options.integrationsPath);
727
- } catch (error) {
728
- console.error(error instanceof Error ? error.message : "An error occurred");
729
- process.exit(1);
730
- }
731
- });
732
- integrationCommand.command("compile").option("--integrations-path <path>", "local path to integrations directory (for development)").description("Compile/update the integration from the current project").action(async (options) => {
733
- try {
734
- await compileIntegration(resolve(process.cwd()), options.integrationsPath);
735
- } catch (error) {
736
- console.error(error instanceof Error ? error.message : "An error occurred");
737
- process.exit(1);
738
- }
739
- });
740
- const templateCommand = program.command("template");
741
- templateCommand.command("init").description("Initialize a custom template from the current project").action(async () => {
742
- try {
743
- await initTemplate(resolve(process.cwd()));
744
- } catch (error) {
745
- console.error(error instanceof Error ? error.message : "An error occurred");
746
- process.exit(1);
747
- }
748
- });
749
- templateCommand.command("compile").description("Compile/update the custom template from the current project").action(async () => {
750
- try {
751
- await compileTemplate(resolve(process.cwd()));
752
- } catch (error) {
753
- console.error(error instanceof Error ? error.message : "An error occurred");
754
- process.exit(1);
755
- }
756
- });
757
- program.parse();
758
-
759
- //#endregion
760
- export { };