alchemy 0.2.1 → 0.2.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.
@@ -0,0 +1,228 @@
1
+ import { exec } from "child_process";
2
+ import fs from "fs/promises";
3
+ import path from "path";
4
+ import { promisify } from "util";
5
+ import { Resource } from "../resource";
6
+ import { ShadcnComponent } from "../shadcn/component";
7
+ import { rm } from "../util/rm";
8
+ const execAsync = promisify(exec);
9
+ export const ViteProject = Resource("project::ViteProject", {
10
+ alwaysUpdate: true,
11
+ }, async function (id, props) {
12
+ const phase = this.phase;
13
+ if (this.phase === "delete") {
14
+ try {
15
+ if (await fs.exists(props.name)) {
16
+ // TODO: OS agnostic - fs.rm is slow to delete node_modules/
17
+ await execAsync("rm -rf " + props.name);
18
+ }
19
+ }
20
+ catch (error) {
21
+ console.error(`Error deleting project ${id}:`, error);
22
+ }
23
+ return this.destroy();
24
+ }
25
+ if (this.phase === "update") {
26
+ if (props.overwrite) {
27
+ await modifyConfig(props);
28
+ }
29
+ else {
30
+ console.warn("ViteProject does not support updates - the project must be recreated to change the template");
31
+ }
32
+ }
33
+ else {
34
+ await execAsync(`bun create vite ${id} --template ${props.template}`);
35
+ await modifyConfig(props);
36
+ }
37
+ return this(props);
38
+ async function modifyConfig(props) {
39
+ const tailwind = props.tailwind ?? false;
40
+ const tanstack = props.tanstack ?? false;
41
+ const plugins = [
42
+ tailwind && "tailwindcss()",
43
+ tanstack &&
44
+ "TanStackRouterVite({ target: 'react', autoCodeSplitting: true })",
45
+ "react()",
46
+ ].filter((s) => typeof s === "string");
47
+ const cwd = path.resolve(process.cwd(), props.name);
48
+ const exec = (command) => execAsync(command, { cwd });
49
+ if (phase === "create" || props.overwrite) {
50
+ await removeUnnecessaryFiles();
51
+ }
52
+ await patchTsConfig();
53
+ if (props.tailwind) {
54
+ await installTailwind();
55
+ }
56
+ if (props.tanstack) {
57
+ await installTanstack();
58
+ }
59
+ if (props.shadcn !== undefined) {
60
+ await installShadcn();
61
+ }
62
+ await build();
63
+ async function build() {
64
+ // tsc -b will fail if we have not invoked tan stacks' code gen
65
+ await execAsync(`bun vite build`, { cwd: props.name });
66
+ }
67
+ async function installTailwind() {
68
+ await exec(`bun add tailwindcss @tailwindcss/vite`);
69
+ await fs.writeFile(path.join(props.name, "vite.config.ts"), `import path from "path";
70
+ import react from "@vitejs/plugin-react";
71
+ import { defineConfig } from "vite";
72
+ ${tailwind ? "import tailwindcss from '@tailwindcss/vite';" : ""}
73
+ ${tanstack ? 'import { TanStackRouterVite } from "@tanstack/router-plugin/vite";' : ""}
74
+
75
+ // https://vite.dev/config/
76
+ export default defineConfig({
77
+ plugins: [${plugins.join(", ")}],
78
+ resolve: {
79
+ alias: {
80
+ "@": path.resolve(__dirname, "./src"),
81
+ },
82
+ },
83
+ });`);
84
+ // Add Tailwind CSS import to index.css
85
+ const indexCssPath = path.join(props.name, "src", "index.css");
86
+ const currentCss = await fs.readFile(indexCssPath, "utf-8");
87
+ if (!currentCss.includes('@import "tailwindcss";')) {
88
+ await fs.writeFile(indexCssPath, '@import "tailwindcss";\n\n' + currentCss);
89
+ }
90
+ }
91
+ async function installShadcn() {
92
+ await exec("bun add -D @types/node");
93
+ // Build the shadcn init command with all options
94
+ const shadcnOptions = props.shadcn;
95
+ const initCommand = [
96
+ "bunx --bun shadcn@latest init",
97
+ shadcnOptions?.baseColor && `-b ${shadcnOptions.baseColor}`,
98
+ shadcnOptions?.defaults && "-d",
99
+ shadcnOptions?.force && "-f",
100
+ shadcnOptions?.cwd && `-c ${shadcnOptions.cwd}`,
101
+ shadcnOptions?.silent && "-s",
102
+ shadcnOptions?.srcDir && "--src-dir",
103
+ shadcnOptions?.cssVariables === false && "--no-css-variables",
104
+ ]
105
+ .filter(Boolean)
106
+ .join(" ");
107
+ await exec(initCommand);
108
+ // Install requested components using the ShadcnComponent resource
109
+ for (const componentName of props.shadcn?.components ?? []) {
110
+ await ShadcnComponent(`shadcn-component-${componentName}`, {
111
+ name: componentName,
112
+ cwd: props.name,
113
+ force: props.shadcn?.force,
114
+ silent: props.shadcn?.silent,
115
+ });
116
+ }
117
+ }
118
+ async function installTanstack() {
119
+ await exec(`bun add @tanstack/react-router`);
120
+ await exec(`bun add -D @tanstack/router-plugin @tanstack/react-router-devtools`);
121
+ const src = path.join(props.name, "src");
122
+ const routes = path.join(src, "routes");
123
+ await fs.mkdir(routes, { recursive: true });
124
+ await fs.writeFile(path.join(routes, "__root.tsx"), `import { Link, Outlet, createRootRoute } from "@tanstack/react-router";
125
+ import { TanStackRouterDevtools } from "@tanstack/react-router-devtools";
126
+
127
+ export const Route = createRootRoute({
128
+ component: () => (
129
+ <div className="w-full min-h-screen flex flex-col">
130
+ <div className="p-2 flex gap-2">
131
+ <Link to="/" className="[&.active]:font-bold">
132
+ Home
133
+ </Link>{" "}
134
+ <Link to="/about" className="[&.active]:font-bold">
135
+ About
136
+ </Link>
137
+ </div>
138
+ <hr />
139
+ <Outlet />
140
+ <TanStackRouterDevtools />
141
+ </div>
142
+ ),
143
+ });
144
+ `);
145
+ await fs.writeFile(path.join(routes, "index.tsx"), `import { createLazyFileRoute } from '@tanstack/react-router'
146
+
147
+ export const Route = createLazyFileRoute('/')({
148
+ component: Index,
149
+ })
150
+
151
+ function Index() {
152
+ return (
153
+ <div className="p-2">
154
+ <h3>Welcome Home!</h3>
155
+ </div>
156
+ )
157
+ }`);
158
+ await fs.writeFile(path.join(routes, "about.tsx"), `import { createLazyFileRoute } from '@tanstack/react-router'
159
+
160
+ export const Route = createLazyFileRoute('/about')({
161
+ component: About,
162
+ })
163
+
164
+ function About() {
165
+ return <div className="p-2">Hello from About!</div>
166
+ }`);
167
+ await fs.writeFile(path.join(src, "main.tsx"), `import { StrictMode } from 'react'
168
+ import ReactDOM from 'react-dom/client'
169
+ import { RouterProvider, createRouter } from '@tanstack/react-router'
170
+ import './index.css'
171
+
172
+ // Import the generated route tree
173
+ import { routeTree } from './routeTree.gen'
174
+
175
+ // Create a new router instance
176
+ const router = createRouter({ routeTree })
177
+
178
+ // Register the router instance for type safety
179
+ declare module '@tanstack/react-router' {
180
+ interface Register {
181
+ router: typeof router
182
+ }
183
+ }
184
+
185
+ // Render the app
186
+ const rootElement = document.getElementById('root')!
187
+ if (!rootElement.innerHTML) {
188
+ const root = ReactDOM.createRoot(rootElement)
189
+ root.render(
190
+ <StrictMode>
191
+ <RouterProvider router={router} />
192
+ </StrictMode>,
193
+ )
194
+ }`);
195
+ }
196
+ async function removeUnnecessaryFiles() {
197
+ await Promise.all([
198
+ rm(path.join(props.name, "src", "App.tsx")),
199
+ rm(path.join(props.name, "src", "App.css")),
200
+ ]);
201
+ }
202
+ async function patchTsConfig() {
203
+ await Promise.all([
204
+ rm(path.join(props.name, "tsconfig.app.json")),
205
+ rm(path.join(props.name, "tsconfig.node.json")),
206
+ fs.writeFile(path.join(props.name, "tsconfig.json"), JSON.stringify({
207
+ extends: props.extends,
208
+ compilerOptions: {
209
+ baseUrl: ".",
210
+ paths: {
211
+ "@/*": ["./src/*"],
212
+ },
213
+ types: ["@cloudflare/workers-types"],
214
+ allowImportingTsExtensions: true,
215
+ jsx: "react-jsx",
216
+ },
217
+ include: [
218
+ "vite/*.ts",
219
+ "src/**/*.ts",
220
+ "src/**/*.tsx",
221
+ "src/env.d.ts",
222
+ ],
223
+ references: props.references?.map((path) => ({ path })),
224
+ }, null, 2)),
225
+ ]);
226
+ }
227
+ }
228
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "alchemy",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "type": "module",
5
5
  "module": "./lib/index.js",
6
6
  "scripts": {
@@ -15,9 +15,10 @@
15
15
  "./esbuild": "./lib/esbuild/index.js",
16
16
  "./fs": "./lib/fs/index.js",
17
17
  "./github": "./lib/github/index.js",
18
- "./project": "./lib/project/index.js",
18
+ "./shadcn": "./lib/shadcn/index.js",
19
19
  "./stripe": "./lib/stripe/index.js",
20
- "./test/bun": "./lib/test/bun.js"
20
+ "./test/bun": "./lib/test/bun.js",
21
+ "./vite": "./lib/vite/index.js"
21
22
  },
22
23
  "peerDependencies": {
23
24
  "@ai-sdk/openai": "^1.1.9",
@@ -4,7 +4,9 @@ import path from "path";
4
4
  import { promisify } from "util";
5
5
  import type { Context } from "../context";
6
6
  import { Resource } from "../resource";
7
+ import { ShadcnComponent } from "../shadcn/component";
7
8
  import { rm } from "../util/rm";
9
+
8
10
  const execAsync = promisify(exec);
9
11
 
10
12
  type ViteTemplate =
@@ -45,11 +47,68 @@ export interface ViteProjectProps {
45
47
  */
46
48
  references?: string[];
47
49
  /**
50
+ * Add Tailwind CSS to the project
48
51
  * @default false
49
52
  */
50
53
  tailwind?: boolean;
51
54
  /**
52
- * Force overwrite the project config tfiles during the update phase
55
+ * Add Tanstack Router to the project
56
+ * @default false
57
+ */
58
+ tanstack?: boolean;
59
+ /**
60
+ * Add Shadcn UI to the project
61
+ * @default false
62
+ */
63
+ shadcn?: {
64
+ /**
65
+ * The base color to use
66
+ * @default "neutral"
67
+ */
68
+ baseColor?: "neutral" | "gray" | "zinc" | "stone" | "slate";
69
+ /**
70
+ * Use default configuration
71
+ * @default false
72
+ */
73
+ defaults?: boolean;
74
+
75
+ /**
76
+ * Force overwrite of existing configuration
77
+ * @default false
78
+ */
79
+ force?: boolean;
80
+
81
+ /**
82
+ * The working directory
83
+ * @default current directory
84
+ */
85
+ cwd?: string;
86
+
87
+ /**
88
+ * Mute output
89
+ * @default false
90
+ */
91
+ silent?: boolean;
92
+
93
+ /**
94
+ * Use the src directory when creating a new project
95
+ * @default false
96
+ */
97
+ srcDir?: boolean;
98
+
99
+ /**
100
+ * Use css variables for theming
101
+ * @default true
102
+ */
103
+ cssVariables?: boolean;
104
+
105
+ /**
106
+ * The components to add
107
+ */
108
+ components?: string[];
109
+ };
110
+ /**
111
+ * Force overwrite the project config files during the update phase
53
112
  *
54
113
  * @default false
55
114
  */
@@ -65,11 +124,15 @@ export interface ViteProject extends ViteProjectProps, Resource {
65
124
 
66
125
  export const ViteProject = Resource(
67
126
  "project::ViteProject",
127
+ {
128
+ alwaysUpdate: true,
129
+ },
68
130
  async function (
69
131
  this: Context<ViteProject>,
70
132
  id: string,
71
133
  props: ViteProjectProps,
72
134
  ): Promise<ViteProject> {
135
+ const phase = this.phase;
73
136
  if (this.phase === "delete") {
74
137
  try {
75
138
  if (await fs.exists(props.name)) {
@@ -91,62 +154,253 @@ export const ViteProject = Resource(
91
154
  );
92
155
  }
93
156
  } else {
94
- // Create phase
95
157
  await execAsync(`bun create vite ${id} --template ${props.template}`);
96
158
 
97
159
  await modifyConfig(props);
98
160
  }
99
161
 
100
162
  return this(props);
101
- },
102
- );
103
163
 
104
- async function modifyConfig(props: ViteProjectProps) {
105
- if (props.tailwind) {
106
- await execAsync(`bun add tailwindcss @tailwindcss/vite`);
164
+ async function modifyConfig(props: ViteProjectProps) {
165
+ const tailwind = props.tailwind ?? false;
166
+ const tanstack = props.tanstack ?? false;
167
+
168
+ const plugins = [
169
+ tailwind && "tailwindcss()",
170
+ tanstack &&
171
+ "TanStackRouterVite({ target: 'react', autoCodeSplitting: true })",
172
+ "react()",
173
+ ].filter((s) => typeof s === "string");
174
+
175
+ const cwd = path.resolve(process.cwd(), props.name);
107
176
 
108
- await fs.writeFile(
109
- path.join(props.name, "vite.config.ts"),
110
- `import tailwindcss from "@tailwindcss/vite";
177
+ const exec = (command: string) => execAsync(command, { cwd });
178
+
179
+ if (phase === "create" || props.overwrite) {
180
+ await removeUnnecessaryFiles();
181
+ }
182
+
183
+ await patchTsConfig();
184
+
185
+ if (props.tailwind) {
186
+ await installTailwind();
187
+ }
188
+
189
+ if (props.tanstack) {
190
+ await installTanstack();
191
+ }
192
+
193
+ if (props.shadcn !== undefined) {
194
+ await installShadcn();
195
+ }
196
+
197
+ await build();
198
+
199
+ async function build() {
200
+ // tsc -b will fail if we have not invoked tan stacks' code gen
201
+ await execAsync(`bun vite build`, { cwd: props.name });
202
+ }
203
+
204
+ async function installTailwind() {
205
+ await exec(`bun add tailwindcss @tailwindcss/vite`);
206
+
207
+ await fs.writeFile(
208
+ path.join(props.name, "vite.config.ts"),
209
+ `import path from "path";
111
210
  import react from "@vitejs/plugin-react";
112
211
  import { defineConfig } from "vite";
212
+ ${tailwind ? "import tailwindcss from '@tailwindcss/vite';" : ""}
213
+ ${tanstack ? 'import { TanStackRouterVite } from "@tanstack/router-plugin/vite";' : ""}
113
214
 
114
215
  // https://vite.dev/config/
115
216
  export default defineConfig({
116
- plugins: [react(), tailwindcss()],
217
+ plugins: [${plugins.join(", ")}],
218
+ resolve: {
219
+ alias: {
220
+ "@": path.resolve(__dirname, "./src"),
221
+ },
222
+ },
117
223
  });`,
118
- );
119
-
120
- // Add Tailwind CSS import to index.css
121
- const indexCssPath = path.join(props.name, "src", "index.css");
122
- const currentCss = await fs.readFile(indexCssPath, "utf-8");
123
- if (!currentCss.includes('@import "tailwindcss";')) {
124
- await fs.writeFile(
125
- indexCssPath,
126
- '@import "tailwindcss";\n\n' + currentCss,
127
- );
128
- }
129
- }
224
+ );
130
225
 
131
- await Promise.all([
132
- rm(path.join(props.name, "tsconfig.app.json")),
133
- rm(path.join(props.name, "tsconfig.node.json")),
134
- fs.writeFile(
135
- path.join(props.name, "tsconfig.json"),
136
- JSON.stringify(
137
- {
138
- extends: props.extends,
139
- compilerOptions: {
140
- types: ["@cloudflare/workers-types"],
141
- allowImportingTsExtensions: true,
142
- jsx: "react-jsx",
143
- },
144
- include: ["vite/*.ts", "src/**/*.ts", "src/**/*.tsx", "src/env.d.ts"],
145
- references: props.references?.map((path) => ({ path })),
146
- },
147
- null,
148
- 2,
149
- ),
150
- ),
151
- ]);
226
+ // Add Tailwind CSS import to index.css
227
+ const indexCssPath = path.join(props.name, "src", "index.css");
228
+ const currentCss = await fs.readFile(indexCssPath, "utf-8");
229
+ if (!currentCss.includes('@import "tailwindcss";')) {
230
+ await fs.writeFile(
231
+ indexCssPath,
232
+ '@import "tailwindcss";\n\n' + currentCss,
233
+ );
234
+ }
235
+ }
236
+
237
+ async function installShadcn() {
238
+ await exec("bun add -D @types/node");
239
+
240
+ // Build the shadcn init command with all options
241
+ const shadcnOptions = props.shadcn;
242
+ const initCommand = [
243
+ "bunx --bun shadcn@latest init",
244
+ shadcnOptions?.baseColor && `-b ${shadcnOptions.baseColor}`,
245
+ shadcnOptions?.defaults && "-d",
246
+ shadcnOptions?.force && "-f",
247
+ shadcnOptions?.cwd && `-c ${shadcnOptions.cwd}`,
248
+ shadcnOptions?.silent && "-s",
249
+ shadcnOptions?.srcDir && "--src-dir",
250
+ shadcnOptions?.cssVariables === false && "--no-css-variables",
251
+ ]
252
+ .filter(Boolean)
253
+ .join(" ");
254
+
255
+ await exec(initCommand);
256
+
257
+ // Install requested components using the ShadcnComponent resource
258
+ for (const componentName of props.shadcn?.components ?? []) {
259
+ await ShadcnComponent(`shadcn-component-${componentName}`, {
260
+ name: componentName,
261
+ cwd: props.name,
262
+ force: props.shadcn?.force,
263
+ silent: props.shadcn?.silent,
264
+ });
265
+ }
266
+ }
267
+
268
+ async function installTanstack() {
269
+ await exec(`bun add @tanstack/react-router`);
270
+ await exec(
271
+ `bun add -D @tanstack/router-plugin @tanstack/react-router-devtools`,
272
+ );
273
+
274
+ const src = path.join(props.name, "src");
275
+ const routes = path.join(src, "routes");
276
+ await fs.mkdir(routes, { recursive: true });
277
+ await fs.writeFile(
278
+ path.join(routes, "__root.tsx"),
279
+ `import { Link, Outlet, createRootRoute } from "@tanstack/react-router";
280
+ import { TanStackRouterDevtools } from "@tanstack/react-router-devtools";
281
+
282
+ export const Route = createRootRoute({
283
+ component: () => (
284
+ <div className="w-full min-h-screen flex flex-col">
285
+ <div className="p-2 flex gap-2">
286
+ <Link to="/" className="[&.active]:font-bold">
287
+ Home
288
+ </Link>{" "}
289
+ <Link to="/about" className="[&.active]:font-bold">
290
+ About
291
+ </Link>
292
+ </div>
293
+ <hr />
294
+ <Outlet />
295
+ <TanStackRouterDevtools />
296
+ </div>
297
+ ),
298
+ });
299
+ `,
300
+ );
301
+
302
+ await fs.writeFile(
303
+ path.join(routes, "index.tsx"),
304
+ `import { createLazyFileRoute } from '@tanstack/react-router'
305
+
306
+ export const Route = createLazyFileRoute('/')({
307
+ component: Index,
308
+ })
309
+
310
+ function Index() {
311
+ return (
312
+ <div className="p-2">
313
+ <h3>Welcome Home!</h3>
314
+ </div>
315
+ )
316
+ }`,
317
+ );
318
+
319
+ await fs.writeFile(
320
+ path.join(routes, "about.tsx"),
321
+ `import { createLazyFileRoute } from '@tanstack/react-router'
322
+
323
+ export const Route = createLazyFileRoute('/about')({
324
+ component: About,
325
+ })
326
+
327
+ function About() {
328
+ return <div className="p-2">Hello from About!</div>
329
+ }`,
330
+ );
331
+
332
+ await fs.writeFile(
333
+ path.join(src, "main.tsx"),
334
+ `import { StrictMode } from 'react'
335
+ import ReactDOM from 'react-dom/client'
336
+ import { RouterProvider, createRouter } from '@tanstack/react-router'
337
+ import './index.css'
338
+
339
+ // Import the generated route tree
340
+ import { routeTree } from './routeTree.gen'
341
+
342
+ // Create a new router instance
343
+ const router = createRouter({ routeTree })
344
+
345
+ // Register the router instance for type safety
346
+ declare module '@tanstack/react-router' {
347
+ interface Register {
348
+ router: typeof router
349
+ }
152
350
  }
351
+
352
+ // Render the app
353
+ const rootElement = document.getElementById('root')!
354
+ if (!rootElement.innerHTML) {
355
+ const root = ReactDOM.createRoot(rootElement)
356
+ root.render(
357
+ <StrictMode>
358
+ <RouterProvider router={router} />
359
+ </StrictMode>,
360
+ )
361
+ }`,
362
+ );
363
+ }
364
+
365
+ async function removeUnnecessaryFiles() {
366
+ await Promise.all([
367
+ rm(path.join(props.name, "src", "App.tsx")),
368
+ rm(path.join(props.name, "src", "App.css")),
369
+ ]);
370
+ }
371
+
372
+ async function patchTsConfig() {
373
+ await Promise.all([
374
+ rm(path.join(props.name, "tsconfig.app.json")),
375
+ rm(path.join(props.name, "tsconfig.node.json")),
376
+ fs.writeFile(
377
+ path.join(props.name, "tsconfig.json"),
378
+ JSON.stringify(
379
+ {
380
+ extends: props.extends,
381
+ compilerOptions: {
382
+ baseUrl: ".",
383
+ paths: {
384
+ "@/*": ["./src/*"],
385
+ },
386
+ types: ["@cloudflare/workers-types"],
387
+ allowImportingTsExtensions: true,
388
+ jsx: "react-jsx",
389
+ },
390
+ include: [
391
+ "vite/*.ts",
392
+ "src/**/*.ts",
393
+ "src/**/*.tsx",
394
+ "src/env.d.ts",
395
+ ],
396
+ references: props.references?.map((path) => ({ path })),
397
+ },
398
+ null,
399
+ 2,
400
+ ),
401
+ ),
402
+ ]);
403
+ }
404
+ }
405
+ },
406
+ );