alchemy 0.2.0 → 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.
Files changed (47) hide show
  1. package/README.md +506 -0
  2. package/lib/alchemy.js +10 -2
  3. package/lib/apply.js +86 -77
  4. package/lib/cloudflare/index.d.ts +2 -0
  5. package/lib/cloudflare/index.js +2 -0
  6. package/lib/cloudflare/static-site.js +9 -9
  7. package/lib/cloudflare/worker.js +1 -1
  8. package/lib/cloudflare/wrangler.json.d.ts +243 -0
  9. package/lib/cloudflare/wrangler.json.js +35 -0
  10. package/lib/cloudflare/zone-settings.d.ts +301 -0
  11. package/lib/cloudflare/zone-settings.js +1 -0
  12. package/lib/cloudflare/zone.d.ts +196 -0
  13. package/lib/cloudflare/zone.js +175 -0
  14. package/lib/destroy.js +1 -1
  15. package/lib/project/vite.d.ts +90 -0
  16. package/lib/project/vite.js +228 -0
  17. package/lib/scope.d.ts +2 -0
  18. package/lib/scope.js +20 -1
  19. package/lib/shadcn/component.d.ts +29 -0
  20. package/lib/shadcn/component.js +31 -0
  21. package/lib/shadcn/index.d.ts +1 -0
  22. package/lib/shadcn/index.js +1 -0
  23. package/lib/state.js +6 -1
  24. package/lib/util/rm.d.ts +1 -0
  25. package/lib/util/rm.js +11 -0
  26. package/lib/vite/index.d.ts +1 -0
  27. package/lib/vite/index.js +1 -0
  28. package/lib/vite/vite.d.ts +90 -0
  29. package/lib/vite/vite.js +228 -0
  30. package/package.json +5 -3
  31. package/src/alchemy.ts +9 -2
  32. package/src/apply.ts +100 -94
  33. package/src/cloudflare/index.ts +2 -0
  34. package/src/cloudflare/static-site.ts +11 -11
  35. package/src/cloudflare/worker.ts +1 -1
  36. package/src/cloudflare/wrangler.json.ts +309 -0
  37. package/src/cloudflare/zone-settings.ts +368 -0
  38. package/src/cloudflare/zone.ts +491 -0
  39. package/src/destroy.ts +1 -1
  40. package/src/project/vite.ts +406 -0
  41. package/src/scope.ts +25 -1
  42. package/src/shadcn/component.ts +80 -0
  43. package/src/shadcn/index.ts +1 -0
  44. package/src/state.ts +9 -1
  45. package/src/util/rm.ts +11 -0
  46. package/src/vite/index.ts +1 -0
  47. package/src/vite/vite.ts +406 -0
@@ -0,0 +1,406 @@
1
+ import { exec } from "child_process";
2
+ import fs from "fs/promises";
3
+ import path from "path";
4
+ import { promisify } from "util";
5
+ import type { Context } from "../context";
6
+ import { Resource } from "../resource";
7
+ import { ShadcnComponent } from "../shadcn/component";
8
+ import { rm } from "../util/rm";
9
+
10
+ const execAsync = promisify(exec);
11
+
12
+ type ViteTemplate =
13
+ | "vanilla"
14
+ | "vanilla-ts"
15
+ | "vue"
16
+ | "vue-ts"
17
+ | "react"
18
+ | "react-ts"
19
+ | "react-swc"
20
+ | "react-swc-ts"
21
+ | "preact"
22
+ | "preact-ts"
23
+ | "lit"
24
+ | "lit-ts"
25
+ | "svelte"
26
+ | "svelte-ts"
27
+ | "solid"
28
+ | "solid-ts"
29
+ | "qwik"
30
+ | "qwik-ts";
31
+
32
+ export interface ViteProjectProps {
33
+ /**
34
+ * The name/path of the project
35
+ */
36
+ name: string;
37
+ /**
38
+ * The Vite template to use
39
+ */
40
+ template: ViteTemplate;
41
+ /**
42
+ * The extends to add to the tsconfig.json file
43
+ */
44
+ extends?: string;
45
+ /**
46
+ * The references to add to the tsconfig.json file
47
+ */
48
+ references?: string[];
49
+ /**
50
+ * Add Tailwind CSS to the project
51
+ * @default false
52
+ */
53
+ tailwind?: boolean;
54
+ /**
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
112
+ *
113
+ * @default false
114
+ */
115
+ overwrite?: boolean;
116
+ }
117
+
118
+ export interface ViteProject extends ViteProjectProps, Resource {
119
+ /**
120
+ * The name/path of the project
121
+ */
122
+ name: string;
123
+ }
124
+
125
+ export const ViteProject = Resource(
126
+ "project::ViteProject",
127
+ {
128
+ alwaysUpdate: true,
129
+ },
130
+ async function (
131
+ this: Context<ViteProject>,
132
+ id: string,
133
+ props: ViteProjectProps,
134
+ ): Promise<ViteProject> {
135
+ const phase = this.phase;
136
+ if (this.phase === "delete") {
137
+ try {
138
+ if (await fs.exists(props.name)) {
139
+ // TODO: OS agnostic - fs.rm is slow to delete node_modules/
140
+ await execAsync("rm -rf " + props.name);
141
+ }
142
+ } catch (error) {
143
+ console.error(`Error deleting project ${id}:`, error);
144
+ }
145
+ return this.destroy();
146
+ }
147
+
148
+ if (this.phase === "update") {
149
+ if (props.overwrite) {
150
+ await modifyConfig(props);
151
+ } else {
152
+ console.warn(
153
+ "ViteProject does not support updates - the project must be recreated to change the template",
154
+ );
155
+ }
156
+ } else {
157
+ await execAsync(`bun create vite ${id} --template ${props.template}`);
158
+
159
+ await modifyConfig(props);
160
+ }
161
+
162
+ return this(props);
163
+
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);
176
+
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";
210
+ import react from "@vitejs/plugin-react";
211
+ import { defineConfig } from "vite";
212
+ ${tailwind ? "import tailwindcss from '@tailwindcss/vite';" : ""}
213
+ ${tanstack ? 'import { TanStackRouterVite } from "@tanstack/router-plugin/vite";' : ""}
214
+
215
+ // https://vite.dev/config/
216
+ export default defineConfig({
217
+ plugins: [${plugins.join(", ")}],
218
+ resolve: {
219
+ alias: {
220
+ "@": path.resolve(__dirname, "./src"),
221
+ },
222
+ },
223
+ });`,
224
+ );
225
+
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
+ }
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
+ );
package/src/scope.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { destroy } from "./destroy";
2
3
  import type { PendingResource, ResourceID } from "./resource";
3
4
  import {
4
5
  FileSystemStateStore,
@@ -40,6 +41,8 @@ export class Scope {
40
41
  public readonly state: StateStore;
41
42
  public readonly quiet: boolean;
42
43
 
44
+ private isErrored = false;
45
+
43
46
  constructor(options: ScopeOptions) {
44
47
  this.appName = options.appName;
45
48
  this.stage = options.stage;
@@ -74,6 +77,11 @@ export class Scope {
74
77
  }
75
78
  }
76
79
 
80
+ public fail() {
81
+ console.error("Scope failed", this.chain.join("/"));
82
+ this.isErrored = true;
83
+ }
84
+
77
85
  public enter() {
78
86
  scopeStorage.enterWith(this);
79
87
  }
@@ -91,7 +99,23 @@ export class Scope {
91
99
  }
92
100
 
93
101
  public async finalize() {
94
- // TODO
102
+ if (!this.isErrored) {
103
+ // TODO: need to detect if it is in error
104
+ const resourceIds = await this.state.list();
105
+ const aliveIds = new Set(this.resources.keys());
106
+ const orphanIds = Array.from(
107
+ resourceIds.filter((id) => !aliveIds.has(id)),
108
+ );
109
+ const orphans = await Promise.all(
110
+ orphanIds.map(async (id) => (await this.state.get(id))!.output),
111
+ );
112
+ await destroy.all(orphans, {
113
+ quiet: this.quiet,
114
+ strategy: "sequential",
115
+ });
116
+ } else {
117
+ console.warn("Scope is in error, skipping finalize");
118
+ }
95
119
  }
96
120
 
97
121
  public async run<T>(fn: (scope: Scope) => Promise<T>): Promise<T> {
@@ -0,0 +1,80 @@
1
+ import { exec } from "child_process";
2
+ import fs from "fs/promises";
3
+ import path from "path";
4
+ import { promisify } from "util";
5
+ import type { Context } from "../context";
6
+ import { Resource } from "../resource";
7
+
8
+ const execAsync = promisify(exec);
9
+
10
+ export interface ShadcnComponentProps {
11
+ /**
12
+ * The name of the component to install
13
+ */
14
+ name: string;
15
+
16
+ /**
17
+ * The working directory where the component should be installed
18
+ */
19
+ cwd: string;
20
+
21
+ /**
22
+ * Force overwrite of existing component
23
+ * @default false
24
+ */
25
+ force?: boolean;
26
+
27
+ /**
28
+ * Mute output
29
+ * @default false
30
+ */
31
+ silent?: boolean;
32
+ }
33
+
34
+ export interface ShadcnComponent extends ShadcnComponentProps, Resource {
35
+ /**
36
+ * The name of the installed component
37
+ */
38
+ name: string;
39
+ }
40
+
41
+ export const ShadcnComponent = Resource(
42
+ "project::ShadcnComponent",
43
+ async function (
44
+ this: Context<ShadcnComponent>,
45
+ id: string,
46
+ props: ShadcnComponentProps,
47
+ ): Promise<ShadcnComponent> {
48
+ if (this.phase === "delete") {
49
+ const componentPath = path.join(
50
+ props.cwd,
51
+ "src",
52
+ "components",
53
+ "ui",
54
+ `${props.name}.tsx`,
55
+ );
56
+ try {
57
+ await fs.unlink(componentPath);
58
+ } catch (error) {
59
+ if ((error as any).code !== "ENOENT") {
60
+ throw error;
61
+ }
62
+ }
63
+ return this.destroy();
64
+ }
65
+
66
+ // Build the shadcn add command with options
67
+ const addCommand = [
68
+ "bunx --bun shadcn@latest add",
69
+ props.name,
70
+ props.silent && "-s",
71
+ ]
72
+ .filter(Boolean)
73
+ .join(" ");
74
+
75
+ // Execute the command in the specified directory
76
+ await execAsync(addCommand, { cwd: props.cwd });
77
+
78
+ return this(props);
79
+ },
80
+ );
@@ -0,0 +1 @@
1
+ export * from "./component";
package/src/state.ts CHANGED
@@ -89,7 +89,15 @@ export class FileSystemStateStore implements StateStore {
89
89
  await this.getPath(key),
90
90
  "utf8",
91
91
  );
92
- return (await deserialize(this.scope, JSON.parse(content))) as State;
92
+ const state = (await deserialize(
93
+ this.scope,
94
+ JSON.parse(content),
95
+ )) as State;
96
+ if (state.output === undefined) {
97
+ state.output = {} as any;
98
+ }
99
+ state.output.Scope = this.scope;
100
+ return state;
93
101
  } catch (error: any) {
94
102
  if (error.code === "ENOENT") {
95
103
  return undefined;
package/src/util/rm.ts ADDED
@@ -0,0 +1,11 @@
1
+ import fs from "fs/promises";
2
+
3
+ export async function rm(path: string) {
4
+ try {
5
+ await fs.rm(path, { recursive: true, force: true });
6
+ } catch (error: any) {
7
+ if (error.code !== "ENOENT") {
8
+ throw error;
9
+ }
10
+ }
11
+ }
@@ -0,0 +1 @@
1
+ export * from "./vite";