alchemy 0.2.5 → 0.3.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.
Files changed (151) hide show
  1. package/README.md +3 -3
  2. package/lib/ai/astro-file.d.ts +137 -0
  3. package/lib/ai/astro-file.js +173 -0
  4. package/lib/ai/client.d.ts +2 -10
  5. package/lib/ai/client.js +8 -24
  6. package/lib/ai/css-file.d.ts +131 -0
  7. package/lib/ai/css-file.js +158 -0
  8. package/lib/ai/data.d.ts +45 -5
  9. package/lib/ai/data.js +45 -10
  10. package/lib/ai/document.d.ts +44 -20
  11. package/lib/ai/document.js +95 -28
  12. package/lib/ai/html-file.d.ts +128 -0
  13. package/lib/ai/html-file.js +155 -0
  14. package/lib/ai/index.d.ts +7 -0
  15. package/lib/ai/index.js +7 -0
  16. package/lib/ai/json-file.d.ts +160 -0
  17. package/lib/ai/json-file.js +208 -0
  18. package/lib/ai/typescript-file.d.ts +140 -0
  19. package/lib/ai/typescript-file.js +176 -0
  20. package/lib/ai/vue-file.d.ts +126 -0
  21. package/lib/ai/vue-file.js +153 -0
  22. package/lib/ai/yaml-file.d.ts +169 -0
  23. package/lib/ai/yaml-file.js +236 -0
  24. package/lib/cloudflare/dns.d.ts +88 -0
  25. package/lib/cloudflare/dns.js +192 -0
  26. package/lib/cloudflare/index.d.ts +2 -1
  27. package/lib/cloudflare/index.js +2 -1
  28. package/lib/cloudflare/r2-rest-state-store.d.ts +125 -0
  29. package/lib/cloudflare/r2-rest-state-store.js +254 -0
  30. package/lib/cloudflare/response.d.ts +12 -0
  31. package/lib/cloudflare/response.js +0 -0
  32. package/lib/cloudflare/zone.d.ts +18 -0
  33. package/lib/cloudflare/zone.js +17 -4
  34. package/lib/dns/godaddy.d.ts +7 -0
  35. package/lib/dns/godaddy.js +21 -0
  36. package/lib/dns/import-dns.d.ts +82 -0
  37. package/lib/dns/import-dns.js +114 -0
  38. package/lib/dns/index.d.ts +2 -0
  39. package/lib/dns/index.js +2 -0
  40. package/lib/dns/record.d.ts +88 -0
  41. package/lib/dns/record.js +13 -0
  42. package/lib/fs/file-system-state-store.d.ts +17 -0
  43. package/lib/fs/file-system-state-store.js +87 -0
  44. package/lib/fs/folder.d.ts +10 -0
  45. package/lib/fs/folder.js +2 -2
  46. package/lib/fs/index.d.ts +4 -4
  47. package/lib/fs/index.js +4 -4
  48. package/lib/fs/{json-file.d.ts → static-json-file.d.ts} +2 -2
  49. package/lib/fs/static-json-file.js +14 -0
  50. package/lib/fs/{text-file.d.ts → static-text-file.d.ts} +2 -2
  51. package/lib/fs/{text-file.js → static-text-file.js} +1 -1
  52. package/lib/fs/{typescript-file.d.ts → static-typescript-file.d.ts} +2 -2
  53. package/lib/fs/{typescript-file.js → static-typescript-file.js} +1 -1
  54. package/lib/fs/{yaml-file.d.ts → static-yaml-file.d.ts} +2 -2
  55. package/lib/fs/{yaml-file.js → static-yaml-file.js} +1 -1
  56. package/lib/internal/getting-started.d.ts +10 -0
  57. package/lib/internal/getting-started.js +94 -0
  58. package/lib/internal/project.d.ts +13 -0
  59. package/lib/internal/project.js +101 -0
  60. package/lib/internal/providers.d.ts +23 -0
  61. package/lib/internal/providers.js +148 -0
  62. package/lib/resource.js +8 -1
  63. package/lib/scope.d.ts +1 -1
  64. package/lib/scope.js +4 -2
  65. package/lib/state.d.ts +1 -16
  66. package/lib/state.js +0 -87
  67. package/lib/test/bun.d.ts +11 -0
  68. package/lib/test/bun.js +36 -8
  69. package/lib/web/astro.d.ts +147 -0
  70. package/lib/web/astro.js +414 -0
  71. package/lib/{shadcn/component.js → web/shadcn-component.js} +2 -9
  72. package/lib/web/shadcn.d.ts +97 -0
  73. package/lib/web/shadcn.js +99 -0
  74. package/lib/web/tailwind.d.ts +64 -0
  75. package/lib/web/tailwind.js +97 -0
  76. package/lib/{vite → web}/vite.d.ts +5 -0
  77. package/lib/{vite → web}/vite.js +44 -44
  78. package/lib/web/vitepress/custom-theme.d.ts +173 -0
  79. package/lib/web/vitepress/custom-theme.js +336 -0
  80. package/lib/{vitepress → web/vitepress}/dependencies.d.ts +2 -2
  81. package/lib/{vitepress → web/vitepress}/dependencies.js +1 -1
  82. package/lib/web/vitepress/home-page.d.ts +244 -0
  83. package/lib/web/vitepress/home-page.js +134 -0
  84. package/lib/{vitepress → web/vitepress}/index.d.ts +1 -0
  85. package/lib/{vitepress → web/vitepress}/index.js +1 -0
  86. package/lib/{vitepress → web/vitepress}/vitepress.d.ts +10 -8
  87. package/lib/{vitepress → web/vitepress}/vitepress.js +11 -12
  88. package/package.json +6 -2
  89. package/src/ai/astro-file.ts +288 -0
  90. package/src/ai/client.ts +8 -28
  91. package/src/ai/css-file.ts +266 -0
  92. package/src/ai/data.ts +53 -16
  93. package/src/ai/document.ts +130 -33
  94. package/src/ai/html-file.ts +263 -0
  95. package/src/ai/index.ts +7 -0
  96. package/src/ai/json-file.ts +349 -0
  97. package/src/ai/typescript-file.ts +293 -0
  98. package/src/ai/vue-file.ts +261 -0
  99. package/src/ai/yaml-file.ts +368 -0
  100. package/src/apply.ts +0 -1
  101. package/src/cloudflare/dns.ts +344 -0
  102. package/src/cloudflare/index.ts +2 -1
  103. package/src/cloudflare/r2-rest-state-store.ts +353 -0
  104. package/src/cloudflare/response.ts +9 -0
  105. package/src/cloudflare/zone.ts +39 -23
  106. package/src/dns/godaddy.ts +29 -0
  107. package/src/dns/import-dns.ts +213 -0
  108. package/src/dns/index.ts +2 -0
  109. package/src/dns/record.ts +121 -0
  110. package/src/fs/file-system-state-store.ts +109 -0
  111. package/src/fs/folder.ts +14 -2
  112. package/src/fs/index.ts +4 -4
  113. package/src/fs/{json-file.ts → static-json-file.ts} +13 -3
  114. package/src/fs/{text-file.ts → static-text-file.ts} +5 -2
  115. package/src/fs/{typescript-file.ts → static-typescript-file.ts} +3 -3
  116. package/src/fs/{yaml-file.ts → static-yaml-file.ts} +5 -2
  117. package/src/internal/getting-started.ts +107 -0
  118. package/src/internal/project.ts +119 -0
  119. package/src/internal/providers.ts +209 -0
  120. package/src/resource.ts +10 -1
  121. package/src/scope.ts +5 -6
  122. package/src/state.ts +1 -111
  123. package/src/test/bun.ts +60 -10
  124. package/src/web/astro.ts +644 -0
  125. package/src/{shadcn/component.ts → web/shadcn-component.ts} +5 -13
  126. package/src/web/shadcn.ts +219 -0
  127. package/src/web/tailwind.ts +167 -0
  128. package/src/{vite → web}/vite.ts +54 -56
  129. package/src/web/vitepress/custom-theme.ts +514 -0
  130. package/src/{vitepress → web/vitepress}/dependencies.ts +2 -2
  131. package/src/web/vitepress/home-page.ts +363 -0
  132. package/src/{vitepress → web/vitepress}/index.ts +1 -0
  133. package/src/{vitepress → web/vitepress}/vitepress.ts +34 -27
  134. package/lib/cloudflare/state.d.ts +0 -82
  135. package/lib/cloudflare/state.js +0 -108
  136. package/lib/fs/json-file.js +0 -7
  137. package/lib/internal/docs.d.ts +0 -5
  138. package/lib/internal/docs.js +0 -287
  139. package/lib/shadcn/index.d.ts +0 -1
  140. package/lib/shadcn/index.js +0 -1
  141. package/lib/vite/index.d.ts +0 -1
  142. package/lib/vite/index.js +0 -1
  143. package/lib/vitepress/home-page.d.ts +0 -133
  144. package/lib/vitepress/home-page.js +0 -11
  145. package/src/cloudflare/state.ts +0 -138
  146. package/src/internal/docs.ts +0 -338
  147. package/src/shadcn/index.ts +0 -1
  148. package/src/vite/index.ts +0 -1
  149. package/src/vitepress/home-page.ts +0 -166
  150. /package/lib/{shadcn/component.d.ts → web/shadcn-component.d.ts} +0 -0
  151. /package/src/{vitepress → web/vitepress}/index.md +0 -0
@@ -0,0 +1,176 @@
1
+ import { generateText } from "ai";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import prettier from "prettier";
5
+ import { Resource } from "../resource";
6
+ import { ignore } from "../util/ignore";
7
+ import { createModel } from "./client";
8
+ /**
9
+ * Default system prompt for TypeScript file generation
10
+ */
11
+ const DEFAULT_TS_SYSTEM_PROMPT = "You are a TypeScript code generator. Create TypeScript code based on the user's requirements. Your response MUST include only TypeScript code inside ```ts fences. Do not include any other text, explanations, or multiple code blocks.";
12
+ /**
13
+ * Resource for generating TypeScript files using AI models.
14
+ * Extracts TypeScript code from between ```ts fences, validates the response,
15
+ * and formats the code with Prettier.
16
+ *
17
+ * @example
18
+ * // Create a utility function
19
+ * const utils = await TypeScriptFile("string-utils", {
20
+ * path: "./src/utils/string-utils.ts",
21
+ * prompt: await alchemy`
22
+ * Generate TypeScript utility functions for string manipulation:
23
+ * - Capitalize first letter
24
+ * - Truncate with ellipsis
25
+ * - Convert to camelCase and kebab-case
26
+ * - Remove special characters
27
+ * `,
28
+ * model: {
29
+ * id: "gpt-4o",
30
+ * provider: "openai"
31
+ * }
32
+ * });
33
+ *
34
+ * @example
35
+ * // Generate a TypeScript class with custom formatting
36
+ * const userService = await TypeScriptFile("user-service", {
37
+ * path: "./src/services/UserService.ts",
38
+ * prompt: await alchemy`
39
+ * Create a UserService class that handles user authentication and profile management.
40
+ * The service should use the User type from:
41
+ * ${alchemy.file("src/types/User.ts")}
42
+ *
43
+ * Include methods for:
44
+ * - login(email, password)
45
+ * - register(user)
46
+ * - updateProfile(userId, profileData)
47
+ * - deleteAccount(userId)
48
+ * `,
49
+ * temperature: 0.2,
50
+ * prettierConfig: {
51
+ * semi: false,
52
+ * singleQuote: true,
53
+ * printWidth: 120
54
+ * }
55
+ * });
56
+ *
57
+ * @example
58
+ * // Generate a React hook with custom system prompt
59
+ * const useFormHook = await TypeScriptFile("use-form", {
60
+ * path: "./src/hooks/useForm.ts",
61
+ * prompt: await alchemy`
62
+ * Create a custom React hook called useForm that handles form state, validation, and submission.
63
+ * It should support:
64
+ * - Initial values
65
+ * - Validation rules
66
+ * - Field errors
67
+ * - Form submission with loading state
68
+ * - Reset functionality
69
+ * `,
70
+ * system: "You are an expert React developer specializing in TypeScript hooks. Create a single TypeScript file inside ```ts fences with no additional text. Follow React best practices and include proper typing.",
71
+ * model: {
72
+ * id: "claude-3-opus-20240229",
73
+ * provider: "anthropic"
74
+ * }
75
+ * });
76
+ */
77
+ export const TypeScriptFile = Resource("ai::TypeScriptFile", async function (id, props) {
78
+ // Ensure directory exists
79
+ await fs.mkdir(path.dirname(props.path), { recursive: true });
80
+ if (this.phase === "delete") {
81
+ try {
82
+ await fs.unlink(props.path);
83
+ }
84
+ catch (error) {
85
+ // Ignore if file doesn't exist
86
+ if (error.code !== "ENOENT") {
87
+ throw error;
88
+ }
89
+ }
90
+ return this.destroy();
91
+ }
92
+ // Use provided system prompt or default
93
+ const system = props.system || DEFAULT_TS_SYSTEM_PROMPT;
94
+ // Generate initial content
95
+ const { text } = await generateText({
96
+ model: createModel(props),
97
+ prompt: props.prompt,
98
+ system,
99
+ providerOptions: props.model?.options,
100
+ ...(props.temperature === undefined
101
+ ? {}
102
+ : { temperature: props.temperature }),
103
+ });
104
+ // Extract and validate TypeScript code
105
+ let { code, error } = await extractTypeScriptCode(text);
106
+ // Re-prompt if there are validation errors
107
+ if (error) {
108
+ const errorSystem = `${system}\n\nERROR: ${error}\n\nPlease try again and ensure your response contains exactly one TypeScript code block inside \`\`\`ts fences.`;
109
+ const { text: retryText } = await generateText({
110
+ model: createModel(props),
111
+ prompt: props.prompt,
112
+ system: errorSystem,
113
+ providerOptions: props.model?.options,
114
+ ...(props.temperature === undefined
115
+ ? {}
116
+ : { temperature: props.temperature }),
117
+ });
118
+ const retryResult = await extractTypeScriptCode(retryText);
119
+ if (retryResult.error) {
120
+ throw new Error(`Failed to generate valid TypeScript code: ${retryResult.error}`);
121
+ }
122
+ code = retryResult.code;
123
+ }
124
+ // Format the code with Prettier
125
+ try {
126
+ // Set default parser to typescript
127
+ const prettierOptions = {
128
+ parser: "typescript",
129
+ ...props.prettierConfig,
130
+ };
131
+ // Format the code
132
+ code = await prettier.format(code, prettierOptions);
133
+ }
134
+ catch (error) {
135
+ // If Prettier formatting fails, just use the unformatted code
136
+ console.warn("Failed to format TypeScript code with Prettier:", error);
137
+ }
138
+ if (this.phase === "update" && props.path !== this.props.path) {
139
+ await ignore("ENOENT", () => fs.unlink(this.props.path));
140
+ }
141
+ // Write content to file
142
+ await fs.writeFile(props.path, code);
143
+ // Get file stats for timestamps
144
+ const stats = await fs.stat(props.path);
145
+ // Return the resource
146
+ return this({
147
+ ...props,
148
+ content: code,
149
+ createdAt: stats.birthtimeMs,
150
+ updatedAt: stats.mtimeMs,
151
+ });
152
+ });
153
+ /**
154
+ * Extracts TypeScript code from between ```ts fences
155
+ * Validates that exactly one TypeScript code block exists
156
+ *
157
+ * @param text The text to extract TypeScript code from
158
+ * @returns The extracted TypeScript code or error message
159
+ */
160
+ async function extractTypeScriptCode(text) {
161
+ const tsCodeRegex = /```ts\s*([\s\S]*?)```/g;
162
+ const matches = Array.from(text.matchAll(tsCodeRegex));
163
+ if (matches.length === 0) {
164
+ return {
165
+ code: "",
166
+ error: "No TypeScript code block found in the response. Please include your code within ```ts fences.",
167
+ };
168
+ }
169
+ if (matches.length > 1) {
170
+ return {
171
+ code: "",
172
+ error: "Multiple TypeScript code blocks found in the response. Please provide exactly one code block within ```ts fences.",
173
+ };
174
+ }
175
+ return { code: matches[0][1].trim() };
176
+ }
@@ -0,0 +1,126 @@
1
+ import type { Context } from "../context";
2
+ import { Resource } from "../resource";
3
+ import type { Secret } from "../secret";
4
+ import { type ModelConfig } from "./client";
5
+ /**
6
+ * Properties for creating or updating a VueFile
7
+ */
8
+ export interface VueFileProps {
9
+ /**
10
+ * Path to the Vue file
11
+ */
12
+ path: string;
13
+ /**
14
+ * Base URL for the OpenAI API
15
+ * @default 'https://api.openai.com/v1'
16
+ */
17
+ baseURL?: string;
18
+ /**
19
+ * Prompt for generating content
20
+ * Use alchemy template literals to include file context:
21
+ * @example
22
+ * prompt: await alchemy`
23
+ * Generate a Vue component using:
24
+ * ${alchemy.file("src/api.ts")}
25
+ * `
26
+ */
27
+ prompt: string;
28
+ /**
29
+ * System prompt for the model
30
+ * This is used to provide instructions to the model about how to format the response
31
+ * The default system prompt instructs the model to return a single Vue component inside ```vue fences
32
+ * @default "You are a Vue component generator. Create a single Vue component based on the user's requirements. Your response MUST include only a single Vue component inside ```vue fences. Do not include any other text, explanations, or multiple code blocks."
33
+ */
34
+ system?: string;
35
+ /**
36
+ * OpenAI API key to use for generating content
37
+ * If not provided, will use OPENAI_API_KEY environment variable
38
+ */
39
+ apiKey?: Secret;
40
+ /**
41
+ * Model configuration
42
+ */
43
+ model?: ModelConfig;
44
+ /**
45
+ * Temperature for controlling randomness in generation.
46
+ * Higher values (e.g., 0.8) make output more random,
47
+ * lower values (e.g., 0.2) make it more deterministic.
48
+ * @default 0.7
49
+ */
50
+ temperature?: number;
51
+ }
52
+ /**
53
+ * A Vue file that can be created, updated, and deleted
54
+ */
55
+ export interface VueFile extends VueFileProps, Resource<"ai::VueFile"> {
56
+ /**
57
+ * Content of the Vue file
58
+ */
59
+ content: string;
60
+ /**
61
+ * Time at which the file was created
62
+ */
63
+ createdAt: number;
64
+ /**
65
+ * Time at which the file was last updated
66
+ */
67
+ updatedAt: number;
68
+ }
69
+ /**
70
+ * Resource for generating Vue files using AI models.
71
+ * Extracts Vue code from between ```vue fences and validates the response.
72
+ *
73
+ * @example
74
+ * // Create a simple Vue component
75
+ * const button = await VueFile("button-component", {
76
+ * path: "./src/components/Button.vue",
77
+ * prompt: await alchemy`
78
+ * Generate a customizable button Vue component with:
79
+ * - Primary, secondary, and outline variants
80
+ * - Small, medium, and large sizes
81
+ * - Loading state with spinner
82
+ * - Disabled state
83
+ * `,
84
+ * model: {
85
+ * id: "gpt-4o",
86
+ * provider: "openai"
87
+ * }
88
+ * });
89
+ *
90
+ * @example
91
+ * // Generate a Vue component using existing files as reference
92
+ * const userCard = await VueFile("user-card", {
93
+ * path: "./src/components/UserCard.vue",
94
+ * prompt: await alchemy`
95
+ * Create a UserCard Vue component that displays user information.
96
+ * Follow the styling patterns from:
97
+ * ${alchemy.file("src/components/Card.vue")}
98
+ *
99
+ * Use the user type from:
100
+ * ${alchemy.file("src/types/User.ts")}
101
+ * `,
102
+ * temperature: 0.2
103
+ * });
104
+ *
105
+ * @example
106
+ * // Generate a complex form component with validation and custom system prompt
107
+ * const form = await VueFile("registration-form", {
108
+ * path: "./src/components/RegistrationForm.vue",
109
+ * prompt: await alchemy`
110
+ * Generate a registration form Vue component with:
111
+ * - Email, password, and confirm password fields
112
+ * - Form validation using Vuelidate or similar
113
+ * - Error messages for each field
114
+ * - Submit handler that emits form data
115
+ *
116
+ * Follow these style guidelines:
117
+ * ${alchemy.file("src/styles/guidelines.md")}
118
+ * `,
119
+ * system: "You are an expert Vue component creator specializing in form components with validation. Create a single Vue component inside ```vue fences with no additional text.",
120
+ * model: {
121
+ * id: "claude-3-opus-20240229",
122
+ * provider: "anthropic"
123
+ * }
124
+ * });
125
+ */
126
+ export declare const VueFile: (((this: any, id: string, props?: {}) => never) & (new (_: never) => never)) | ((this: Context<VueFile>, id: string, props: VueFileProps) => Promise<VueFile>);
@@ -0,0 +1,153 @@
1
+ import { generateText } from "ai";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { Resource } from "../resource";
5
+ import { ignore } from "../util/ignore";
6
+ import { createModel } from "./client";
7
+ /**
8
+ * Default system prompt for Vue file generation
9
+ */
10
+ const DEFAULT_VUE_SYSTEM_PROMPT = "You are a Vue component generator. Create a single Vue component based on the user's requirements. Your response MUST include only a single Vue component inside ```vue fences. Do not include any other text, explanations, or multiple code blocks.";
11
+ /**
12
+ * Resource for generating Vue files using AI models.
13
+ * Extracts Vue code from between ```vue fences and validates the response.
14
+ *
15
+ * @example
16
+ * // Create a simple Vue component
17
+ * const button = await VueFile("button-component", {
18
+ * path: "./src/components/Button.vue",
19
+ * prompt: await alchemy`
20
+ * Generate a customizable button Vue component with:
21
+ * - Primary, secondary, and outline variants
22
+ * - Small, medium, and large sizes
23
+ * - Loading state with spinner
24
+ * - Disabled state
25
+ * `,
26
+ * model: {
27
+ * id: "gpt-4o",
28
+ * provider: "openai"
29
+ * }
30
+ * });
31
+ *
32
+ * @example
33
+ * // Generate a Vue component using existing files as reference
34
+ * const userCard = await VueFile("user-card", {
35
+ * path: "./src/components/UserCard.vue",
36
+ * prompt: await alchemy`
37
+ * Create a UserCard Vue component that displays user information.
38
+ * Follow the styling patterns from:
39
+ * ${alchemy.file("src/components/Card.vue")}
40
+ *
41
+ * Use the user type from:
42
+ * ${alchemy.file("src/types/User.ts")}
43
+ * `,
44
+ * temperature: 0.2
45
+ * });
46
+ *
47
+ * @example
48
+ * // Generate a complex form component with validation and custom system prompt
49
+ * const form = await VueFile("registration-form", {
50
+ * path: "./src/components/RegistrationForm.vue",
51
+ * prompt: await alchemy`
52
+ * Generate a registration form Vue component with:
53
+ * - Email, password, and confirm password fields
54
+ * - Form validation using Vuelidate or similar
55
+ * - Error messages for each field
56
+ * - Submit handler that emits form data
57
+ *
58
+ * Follow these style guidelines:
59
+ * ${alchemy.file("src/styles/guidelines.md")}
60
+ * `,
61
+ * system: "You are an expert Vue component creator specializing in form components with validation. Create a single Vue component inside ```vue fences with no additional text.",
62
+ * model: {
63
+ * id: "claude-3-opus-20240229",
64
+ * provider: "anthropic"
65
+ * }
66
+ * });
67
+ */
68
+ export const VueFile = Resource("ai::VueFile", async function (id, props) {
69
+ // Ensure directory exists
70
+ await fs.mkdir(path.dirname(props.path), { recursive: true });
71
+ if (this.phase === "delete") {
72
+ try {
73
+ await fs.unlink(props.path);
74
+ }
75
+ catch (error) {
76
+ // Ignore if file doesn't exist
77
+ if (error.code !== "ENOENT") {
78
+ throw error;
79
+ }
80
+ }
81
+ return this.destroy();
82
+ }
83
+ // Use provided system prompt or default
84
+ const system = props.system || DEFAULT_VUE_SYSTEM_PROMPT;
85
+ // Generate initial content
86
+ const { text } = await generateText({
87
+ model: createModel(props),
88
+ prompt: props.prompt,
89
+ system,
90
+ providerOptions: props.model?.options,
91
+ ...(props.temperature === undefined
92
+ ? {}
93
+ : { temperature: props.temperature }),
94
+ });
95
+ // Extract and validate Vue code
96
+ let { code, error } = await extractVueCode(text);
97
+ // Re-prompt if there are validation errors
98
+ if (error) {
99
+ const errorSystem = `${system}\n\nERROR: ${error}\n\nPlease try again and ensure your response contains exactly one Vue component inside \`\`\`vue fences.`;
100
+ const { text: retryText } = await generateText({
101
+ model: createModel(props),
102
+ prompt: props.prompt,
103
+ system: errorSystem,
104
+ providerOptions: props.model?.options,
105
+ ...(props.temperature === undefined
106
+ ? {}
107
+ : { temperature: props.temperature }),
108
+ });
109
+ const retryResult = await extractVueCode(retryText);
110
+ if (retryResult.error) {
111
+ throw new Error(`Failed to generate valid Vue code: ${retryResult.error}`);
112
+ }
113
+ code = retryResult.code;
114
+ }
115
+ if (this.phase === "update" && props.path !== this.props.path) {
116
+ await ignore("ENOENT", () => fs.unlink(this.props.path));
117
+ }
118
+ // Write content to file
119
+ await fs.writeFile(props.path, code);
120
+ // Get file stats for timestamps
121
+ const stats = await fs.stat(props.path);
122
+ // Return the resource
123
+ return this({
124
+ ...props,
125
+ content: code,
126
+ createdAt: stats.birthtimeMs,
127
+ updatedAt: stats.mtimeMs,
128
+ });
129
+ });
130
+ /**
131
+ * Extracts Vue code from between ```vue fences
132
+ * Validates that exactly one Vue code block exists
133
+ *
134
+ * @param text The text to extract Vue code from
135
+ * @returns The extracted Vue code or error message
136
+ */
137
+ async function extractVueCode(text) {
138
+ const vueCodeRegex = /```vue\s*([\s\S]*?)```/g;
139
+ const matches = Array.from(text.matchAll(vueCodeRegex));
140
+ if (matches.length === 0) {
141
+ return {
142
+ code: "",
143
+ error: "No Vue code block found in the response. Please include your code within ```vue fences.",
144
+ };
145
+ }
146
+ if (matches.length > 1) {
147
+ return {
148
+ code: "",
149
+ error: "Multiple Vue code blocks found in the response. Please provide exactly one code block within ```vue fences.",
150
+ };
151
+ }
152
+ return { code: matches[0][1].trim() };
153
+ }
@@ -0,0 +1,169 @@
1
+ import type { JsonSchema, Type, type } from "arktype";
2
+ import type { Context } from "../context";
3
+ import { Resource } from "../resource";
4
+ import type { Secret } from "../secret";
5
+ import { type ModelConfig } from "./client";
6
+ /**
7
+ * Properties for creating or updating a YAMLFile
8
+ */
9
+ export interface YAMLFileProps<T extends Type<any, any> | undefined = undefined> {
10
+ /**
11
+ * Path to the YAML file
12
+ */
13
+ path: string;
14
+ /**
15
+ * Optional ArkType schema to validate and structure the generated YAML
16
+ * When provided, the resource will use generateObject with schema validation
17
+ * When not provided, it will extract YAML from between ```yaml fences
18
+ */
19
+ schema?: T;
20
+ /**
21
+ * Base URL for the OpenAI API
22
+ * @default 'https://api.openai.com/v1'
23
+ */
24
+ baseURL?: string;
25
+ /**
26
+ * Prompt for generating content
27
+ * Use alchemy template literals to include file context:
28
+ * @example
29
+ * prompt: await alchemy`
30
+ * Generate a YAML configuration for:
31
+ * ${alchemy.file("src/serverless.js")}
32
+ * `
33
+ */
34
+ prompt: string;
35
+ /**
36
+ * System prompt for the model
37
+ * This is used to provide instructions to the model about how to format the response
38
+ * @default Depends on whether schema is provided
39
+ */
40
+ system?: string;
41
+ /**
42
+ * OpenAI API key to use for generating content
43
+ * If not provided, will use OPENAI_API_KEY environment variable
44
+ */
45
+ apiKey?: Secret;
46
+ /**
47
+ * Model configuration
48
+ */
49
+ model?: ModelConfig;
50
+ /**
51
+ * Temperature for controlling randomness in generation.
52
+ * Higher values (e.g., 0.8) make output more random,
53
+ * lower values (e.g., 0.2) make it more deterministic.
54
+ * @default 0.7
55
+ */
56
+ temperature?: number;
57
+ }
58
+ /**
59
+ * A YAML file that can be created, updated, and deleted
60
+ */
61
+ export interface YAMLFile<T = any> extends Omit<YAMLFileProps, "schema">, Resource<"ai::YAMLFile"> {
62
+ /**
63
+ * Content of the YAML file as a string
64
+ */
65
+ content: string;
66
+ /**
67
+ * Parsed YAML object
68
+ */
69
+ yaml: T;
70
+ /**
71
+ * Schema used to validate the YAML (if provided)
72
+ */
73
+ schema?: JsonSchema;
74
+ /**
75
+ * Time at which the file was created
76
+ */
77
+ createdAt: number;
78
+ /**
79
+ * Time at which the file was last updated
80
+ */
81
+ updatedAt: number;
82
+ }
83
+ /**
84
+ * Resource for generating YAML files using AI models.
85
+ * Can operate in two modes:
86
+ * 1. With schema: Uses generateObject with type validation, then converts to YAML
87
+ * 2. Without schema: Extracts YAML from between ```yaml fences
88
+ *
89
+ * @example
90
+ * // Generate a serverless configuration file
91
+ * const serverlessConfig = await YAMLFile("serverless-config", {
92
+ * path: "./serverless.yml",
93
+ * prompt: await alchemy`
94
+ * Generate a serverless.yml configuration for an AWS Lambda API with:
95
+ * - A service name "user-api"
96
+ * - Node.js 16.x runtime
97
+ * - Three functions: createUser, getUser, and listUsers
98
+ * - API Gateway endpoints for each function
99
+ * - DynamoDB table for users
100
+ * - IAM permissions for DynamoDB access
101
+ * `,
102
+ * model: {
103
+ * id: "gpt-4o",
104
+ * provider: "openai"
105
+ * }
106
+ * });
107
+ *
108
+ * @example
109
+ * // Generate YAML with schema validation
110
+ * import { type } from "arktype";
111
+ *
112
+ * const k8sConfigSchema = type({
113
+ * apiVersion: "string",
114
+ * kind: "string",
115
+ * metadata: {
116
+ * name: "string",
117
+ * namespace: "string?",
118
+ * labels: "Record<string, string>?"
119
+ * },
120
+ * spec: {
121
+ * replicas: "number",
122
+ * selector: {
123
+ * matchLabels: "Record<string, string>"
124
+ * },
125
+ * template: {
126
+ * metadata: {
127
+ * labels: "Record<string, string>"
128
+ * },
129
+ * spec: {
130
+ * containers: [{
131
+ * name: "string",
132
+ * image: "string",
133
+ * ports: [{
134
+ * containerPort: "number"
135
+ * }]
136
+ * }]
137
+ * }
138
+ * }
139
+ * }
140
+ * });
141
+ *
142
+ * const deployment = await YAMLFile("k8s-deployment", {
143
+ * path: "./kubernetes/deployment.yaml",
144
+ * schema: k8sConfigSchema,
145
+ * prompt: "Generate a Kubernetes deployment for a web application named 'frontend' with 3 replicas using the nginx:latest image and exposing port 80",
146
+ * temperature: 0.2
147
+ * });
148
+ *
149
+ * @example
150
+ * // Generate GitHub Actions workflow with custom system prompt
151
+ * const workflow = await YAMLFile("github-workflow", {
152
+ * path: "./.github/workflows/ci.yml",
153
+ * prompt: await alchemy`
154
+ * Create a GitHub Actions workflow for a Node.js project that:
155
+ * - Runs on push to main and pull requests
156
+ * - Sets up Node.js 18
157
+ * - Installs dependencies with npm
158
+ * - Runs linting and tests
159
+ * - Builds the project
160
+ * - Deploys to GitHub Pages on success (main branch only)
161
+ * `,
162
+ * system: "You are a DevOps expert specializing in GitHub Actions workflows. Create a single YAML file inside ```yaml fences with no additional text. Follow GitHub Actions best practices and use proper YAML syntax.",
163
+ * model: {
164
+ * id: "claude-3-opus-20240229",
165
+ * provider: "anthropic"
166
+ * }
167
+ * });
168
+ */
169
+ export declare const YAMLFile: (((this: any, id: string, props?: {}) => never) & (new (_: never) => never)) | (<const T extends Type<any, any> | undefined = undefined>(this: Context<YAMLFile<T extends Type<any, any> ? type.infer<T> : any>>, id: string, props: YAMLFileProps<T>) => Promise<YAMLFile<T extends Type<any, any> ? type.infer<T> : any>>);