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
package/lib/scope.d.ts CHANGED
@@ -20,11 +20,13 @@ export declare class Scope {
20
20
  readonly password: string | undefined;
21
21
  readonly state: StateStore;
22
22
  readonly quiet: boolean;
23
+ private isErrored;
23
24
  constructor(options: ScopeOptions);
24
25
  delete(resourceID: ResourceID): Promise<void>;
25
26
  private _seq;
26
27
  seq(): number;
27
28
  get chain(): string[];
29
+ fail(): void;
28
30
  enter(): void;
29
31
  init(): Promise<void>;
30
32
  deinit(): Promise<void>;
package/lib/scope.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { destroy } from "./destroy";
2
3
  import { FileSystemStateStore, } from "./state";
3
4
  const scopeStorage = new AsyncLocalStorage();
4
5
  export class Scope {
@@ -20,6 +21,7 @@ export class Scope {
20
21
  password;
21
22
  state;
22
23
  quiet;
24
+ isErrored = false;
23
25
  constructor(options) {
24
26
  this.appName = options.appName;
25
27
  this.stage = options.stage;
@@ -50,6 +52,10 @@ export class Scope {
50
52
  return [...app, this.stage, ...thisScope];
51
53
  }
52
54
  }
55
+ fail() {
56
+ console.error("Scope failed", this.chain.join("/"));
57
+ this.isErrored = true;
58
+ }
53
59
  enter() {
54
60
  scopeStorage.enterWith(this);
55
61
  }
@@ -63,7 +69,20 @@ export class Scope {
63
69
  return [...this.chain, resourceID].join("/");
64
70
  }
65
71
  async finalize() {
66
- // TODO
72
+ if (!this.isErrored) {
73
+ // TODO: need to detect if it is in error
74
+ const resourceIds = await this.state.list();
75
+ const aliveIds = new Set(this.resources.keys());
76
+ const orphanIds = Array.from(resourceIds.filter((id) => !aliveIds.has(id)));
77
+ const orphans = await Promise.all(orphanIds.map(async (id) => (await this.state.get(id)).output));
78
+ await destroy.all(orphans, {
79
+ quiet: this.quiet,
80
+ strategy: "sequential",
81
+ });
82
+ }
83
+ else {
84
+ console.warn("Scope is in error, skipping finalize");
85
+ }
67
86
  }
68
87
  async run(fn) {
69
88
  return scopeStorage.run(this, () => fn(this));
@@ -0,0 +1,29 @@
1
+ import type { Context } from "../context";
2
+ import { Resource } from "../resource";
3
+ export interface ShadcnComponentProps {
4
+ /**
5
+ * The name of the component to install
6
+ */
7
+ name: string;
8
+ /**
9
+ * The working directory where the component should be installed
10
+ */
11
+ cwd: string;
12
+ /**
13
+ * Force overwrite of existing component
14
+ * @default false
15
+ */
16
+ force?: boolean;
17
+ /**
18
+ * Mute output
19
+ * @default false
20
+ */
21
+ silent?: boolean;
22
+ }
23
+ export interface ShadcnComponent extends ShadcnComponentProps, Resource {
24
+ /**
25
+ * The name of the installed component
26
+ */
27
+ name: string;
28
+ }
29
+ export declare const ShadcnComponent: ((this: Context<ShadcnComponent>, id: string, props: ShadcnComponentProps) => Promise<ShadcnComponent>) | (((this: any, id: string, props: ShadcnComponentProps) => never) & (new (_: never) => never));
@@ -0,0 +1,31 @@
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
+ const execAsync = promisify(exec);
7
+ export const ShadcnComponent = Resource("project::ShadcnComponent", async function (id, props) {
8
+ if (this.phase === "delete") {
9
+ const componentPath = path.join(props.cwd, "src", "components", "ui", `${props.name}.tsx`);
10
+ try {
11
+ await fs.unlink(componentPath);
12
+ }
13
+ catch (error) {
14
+ if (error.code !== "ENOENT") {
15
+ throw error;
16
+ }
17
+ }
18
+ return this.destroy();
19
+ }
20
+ // Build the shadcn add command with options
21
+ const addCommand = [
22
+ "bunx --bun shadcn@latest add",
23
+ props.name,
24
+ props.silent && "-s",
25
+ ]
26
+ .filter(Boolean)
27
+ .join(" ");
28
+ // Execute the command in the specified directory
29
+ await execAsync(addCommand, { cwd: props.cwd });
30
+ return this(props);
31
+ });
@@ -0,0 +1 @@
1
+ export * from "./component";
@@ -0,0 +1 @@
1
+ export * from "./component";
package/lib/state.js CHANGED
@@ -39,7 +39,12 @@ export class FileSystemStateStore {
39
39
  async get(key) {
40
40
  try {
41
41
  const content = await fs.promises.readFile(await this.getPath(key), "utf8");
42
- return (await deserialize(this.scope, JSON.parse(content)));
42
+ const state = (await deserialize(this.scope, JSON.parse(content)));
43
+ if (state.output === undefined) {
44
+ state.output = {};
45
+ }
46
+ state.output.Scope = this.scope;
47
+ return state;
43
48
  }
44
49
  catch (error) {
45
50
  if (error.code === "ENOENT") {
@@ -0,0 +1 @@
1
+ export declare function rm(path: string): Promise<void>;
package/lib/util/rm.js ADDED
@@ -0,0 +1,11 @@
1
+ import fs from "fs/promises";
2
+ export async function rm(path) {
3
+ try {
4
+ await fs.rm(path, { recursive: true, force: true });
5
+ }
6
+ catch (error) {
7
+ if (error.code !== "ENOENT") {
8
+ throw error;
9
+ }
10
+ }
11
+ }
@@ -0,0 +1 @@
1
+ export * from "./vite";
@@ -0,0 +1 @@
1
+ export * from "./vite";
@@ -0,0 +1,90 @@
1
+ import type { Context } from "../context";
2
+ import { Resource } from "../resource";
3
+ type ViteTemplate = "vanilla" | "vanilla-ts" | "vue" | "vue-ts" | "react" | "react-ts" | "react-swc" | "react-swc-ts" | "preact" | "preact-ts" | "lit" | "lit-ts" | "svelte" | "svelte-ts" | "solid" | "solid-ts" | "qwik" | "qwik-ts";
4
+ export interface ViteProjectProps {
5
+ /**
6
+ * The name/path of the project
7
+ */
8
+ name: string;
9
+ /**
10
+ * The Vite template to use
11
+ */
12
+ template: ViteTemplate;
13
+ /**
14
+ * The extends to add to the tsconfig.json file
15
+ */
16
+ extends?: string;
17
+ /**
18
+ * The references to add to the tsconfig.json file
19
+ */
20
+ references?: string[];
21
+ /**
22
+ * Add Tailwind CSS to the project
23
+ * @default false
24
+ */
25
+ tailwind?: boolean;
26
+ /**
27
+ * Add Tanstack Router to the project
28
+ * @default false
29
+ */
30
+ tanstack?: boolean;
31
+ /**
32
+ * Add Shadcn UI to the project
33
+ * @default false
34
+ */
35
+ shadcn?: {
36
+ /**
37
+ * The base color to use
38
+ * @default "neutral"
39
+ */
40
+ baseColor?: "neutral" | "gray" | "zinc" | "stone" | "slate";
41
+ /**
42
+ * Use default configuration
43
+ * @default false
44
+ */
45
+ defaults?: boolean;
46
+ /**
47
+ * Force overwrite of existing configuration
48
+ * @default false
49
+ */
50
+ force?: boolean;
51
+ /**
52
+ * The working directory
53
+ * @default current directory
54
+ */
55
+ cwd?: string;
56
+ /**
57
+ * Mute output
58
+ * @default false
59
+ */
60
+ silent?: boolean;
61
+ /**
62
+ * Use the src directory when creating a new project
63
+ * @default false
64
+ */
65
+ srcDir?: boolean;
66
+ /**
67
+ * Use css variables for theming
68
+ * @default true
69
+ */
70
+ cssVariables?: boolean;
71
+ /**
72
+ * The components to add
73
+ */
74
+ components?: string[];
75
+ };
76
+ /**
77
+ * Force overwrite the project config files during the update phase
78
+ *
79
+ * @default false
80
+ */
81
+ overwrite?: boolean;
82
+ }
83
+ export interface ViteProject extends ViteProjectProps, Resource {
84
+ /**
85
+ * The name/path of the project
86
+ */
87
+ name: string;
88
+ }
89
+ export declare const ViteProject: ((this: Context<ViteProject>, id: string, props: ViteProjectProps) => Promise<ViteProject>) | (((this: any, id: string, props: ViteProjectProps) => never) & (new (_: never) => never));
90
+ export {};
@@ -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,10 +1,10 @@
1
1
  {
2
2
  "name": "alchemy",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "type": "module",
5
5
  "module": "./lib/index.js",
6
6
  "scripts": {
7
- "publish:npm": "rm -rf ./*.tsbuildinfo && rm -rf ./lib && tsc -b && npm publish"
7
+ "publish:npm": "cp ../README.md . && rm -rf ./*.tsbuildinfo && rm -rf ./lib && tsc -b && npm publish && rm README.md"
8
8
  },
9
9
  "files": ["lib", "src"],
10
10
  "exports": {
@@ -15,8 +15,10 @@
15
15
  "./esbuild": "./lib/esbuild/index.js",
16
16
  "./fs": "./lib/fs/index.js",
17
17
  "./github": "./lib/github/index.js",
18
+ "./shadcn": "./lib/shadcn/index.js",
18
19
  "./stripe": "./lib/stripe/index.js",
19
- "./test/bun": "./lib/test/bun.js"
20
+ "./test/bun": "./lib/test/bun.js",
21
+ "./vite": "./lib/vite/index.js"
20
22
  },
21
23
  "peerDependencies": {
22
24
  "@ai-sdk/openai": "^1.1.9",
package/src/alchemy.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { destroy } from "./destroy";
1
+ import { DestroyedSignal, destroy } from "./destroy";
2
2
  import { Scope } from "./scope";
3
3
  import { secret } from "./secret";
4
4
  import type { StateStoreType } from "./state";
@@ -116,5 +116,12 @@ async function run<T>(
116
116
  (this: Scope, scope: Scope) => Promise<T>,
117
117
  ]);
118
118
  await using scope = alchemy.scope(id, options);
119
- return await fn.bind(scope)(scope);
119
+ try {
120
+ return await fn.bind(scope)(scope);
121
+ } catch (error) {
122
+ if (!(error instanceof DestroyedSignal)) {
123
+ scope.fail();
124
+ }
125
+ throw error;
126
+ }
120
127
  }