ai-props 2.0.2 → 2.1.3

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.
package/src/ai.js ADDED
@@ -0,0 +1,198 @@
1
+ /**
2
+ * AI() wrapper for components with intelligent prop generation
3
+ *
4
+ * The AI() function wraps a component definition and automatically
5
+ * generates missing props using AI when the component is rendered.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ import { mergeWithGenerated } from './generate.js';
10
+ /**
11
+ * Create an AI-powered component wrapper
12
+ *
13
+ * The returned function accepts partial props and generates
14
+ * any missing props using AI based on the schema.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * const UserCard = AI({
19
+ * schema: {
20
+ * name: 'Full name of the user',
21
+ * bio: 'A short biography',
22
+ * avatar: 'URL to avatar image',
23
+ * },
24
+ * defaults: {
25
+ * avatar: 'https://example.com/default-avatar.png',
26
+ * },
27
+ * })
28
+ *
29
+ * // Generate all props
30
+ * const props = await UserCard({})
31
+ *
32
+ * // Generate only missing props
33
+ * const props2 = await UserCard({ name: 'John Doe' })
34
+ * ```
35
+ */
36
+ export function AI(options) {
37
+ const { schema, defaults = {}, required = [], exclude = [], config = {} } = options;
38
+ // Build filtered schema (exclude specified props)
39
+ const filteredSchema = filterSchema(schema, exclude);
40
+ /**
41
+ * The AI component function
42
+ */
43
+ const aiComponent = async (partialProps) => {
44
+ // Merge with defaults
45
+ const propsWithDefaults = { ...defaults, ...partialProps };
46
+ // Check if all required props are provided
47
+ const missingRequired = required.filter(key => propsWithDefaults[key] === undefined);
48
+ if (missingRequired.length > 0) {
49
+ throw new Error(`Missing required props: ${missingRequired.join(', ')}`);
50
+ }
51
+ // Generate missing props
52
+ const fullProps = await mergeWithGenerated(filteredSchema, propsWithDefaults, {
53
+ model: config.model,
54
+ system: config.system,
55
+ });
56
+ return fullProps;
57
+ };
58
+ // Attach metadata
59
+ aiComponent.schema = schema;
60
+ aiComponent.config = config;
61
+ // Attach helper method
62
+ aiComponent.generateProps = async (context) => {
63
+ return aiComponent(context || {});
64
+ };
65
+ return aiComponent;
66
+ }
67
+ /**
68
+ * Filter schema to exclude certain keys
69
+ */
70
+ function filterSchema(schema, exclude) {
71
+ if (typeof schema === 'string') {
72
+ return schema;
73
+ }
74
+ const filtered = {};
75
+ for (const [key, value] of Object.entries(schema)) {
76
+ if (!exclude.includes(key)) {
77
+ filtered[key] = value;
78
+ }
79
+ }
80
+ return filtered;
81
+ }
82
+ /**
83
+ * Create a typed AI component with inference
84
+ *
85
+ * @example
86
+ * ```ts
87
+ * const ProductCard = createAIComponent<{
88
+ * title: string
89
+ * price: number
90
+ * description: string
91
+ * }>({
92
+ * schema: {
93
+ * title: 'Product title',
94
+ * price: 'Price in USD (number)',
95
+ * description: 'Product description',
96
+ * },
97
+ * })
98
+ * ```
99
+ */
100
+ export function createAIComponent(options) {
101
+ return AI(options);
102
+ }
103
+ /**
104
+ * Define props schema with type inference
105
+ *
106
+ * @example
107
+ * ```ts
108
+ * const userSchema = definePropsSchema({
109
+ * name: 'User name',
110
+ * email: 'Email address',
111
+ * age: 'Age (number)',
112
+ * })
113
+ * ```
114
+ */
115
+ export function definePropsSchema(schema) {
116
+ return schema;
117
+ }
118
+ /**
119
+ * Create a component factory for generating multiple instances
120
+ *
121
+ * @example
122
+ * ```ts
123
+ * const factory = createComponentFactory({
124
+ * schema: { name: 'Product name', price: 'Price (number)' },
125
+ * })
126
+ *
127
+ * const products = await factory.generateMany([
128
+ * { category: 'electronics' },
129
+ * { category: 'clothing' },
130
+ * { category: 'food' },
131
+ * ])
132
+ * ```
133
+ */
134
+ export function createComponentFactory(options) {
135
+ const component = AI(options);
136
+ return {
137
+ component,
138
+ schema: options.schema,
139
+ /**
140
+ * Generate a single instance
141
+ */
142
+ generate: (context) => component(context || {}),
143
+ /**
144
+ * Generate multiple instances
145
+ */
146
+ generateMany: async (contexts) => {
147
+ return Promise.all(contexts.map(ctx => component(ctx)));
148
+ },
149
+ /**
150
+ * Generate with specific overrides
151
+ */
152
+ generateWith: async (context, overrides) => {
153
+ const generated = await component(context);
154
+ return { ...generated, ...overrides };
155
+ },
156
+ };
157
+ }
158
+ /**
159
+ * Compose multiple AI components
160
+ *
161
+ * Creates a component that combines props from multiple schemas.
162
+ *
163
+ * @example
164
+ * ```ts
165
+ * const FullProfile = composeAIComponents({
166
+ * user: userSchema,
167
+ * settings: settingsSchema,
168
+ * preferences: preferencesSchema,
169
+ * })
170
+ *
171
+ * const profile = await FullProfile({
172
+ * user: { name: 'John' },
173
+ * settings: {},
174
+ * preferences: { theme: 'dark' },
175
+ * })
176
+ * ```
177
+ */
178
+ export function composeAIComponents(components) {
179
+ const aiComponent = async (partialProps) => {
180
+ const results = {};
181
+ // Generate each component's props
182
+ await Promise.all(Object.entries(components).map(async ([key, options]) => {
183
+ const component = AI(options);
184
+ const partial = partialProps[key] || {};
185
+ results[key] = await component(partial);
186
+ }));
187
+ return results;
188
+ };
189
+ // Compose schemas
190
+ const composedSchema = {};
191
+ for (const [key, options] of Object.entries(components)) {
192
+ composedSchema[key] = options.schema;
193
+ }
194
+ aiComponent.schema = composedSchema;
195
+ aiComponent.config = {};
196
+ aiComponent.generateProps = (context) => aiComponent(context || {});
197
+ return aiComponent;
198
+ }
package/src/cache.js ADDED
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Props caching for ai-props
3
+ *
4
+ * Provides in-memory caching for generated props to avoid
5
+ * redundant AI calls with the same context.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ /**
10
+ * Default cache TTL (5 minutes)
11
+ */
12
+ export const DEFAULT_CACHE_TTL = 5 * 60 * 1000;
13
+ /**
14
+ * Create a cache key from schema and context
15
+ */
16
+ export function createCacheKey(schema, context) {
17
+ const schemaStr = typeof schema === 'string' ? schema : JSON.stringify(schema);
18
+ const contextStr = context ? JSON.stringify(sortObject(context)) : '';
19
+ return `${hashString(schemaStr)}:${hashString(contextStr)}`;
20
+ }
21
+ /**
22
+ * Simple string hash function
23
+ */
24
+ function hashString(str) {
25
+ let hash = 0;
26
+ for (let i = 0; i < str.length; i++) {
27
+ const char = str.charCodeAt(i);
28
+ hash = ((hash << 5) - hash) + char;
29
+ hash = hash & hash; // Convert to 32-bit integer
30
+ }
31
+ return hash.toString(36);
32
+ }
33
+ /**
34
+ * Sort object keys for consistent hashing
35
+ */
36
+ function sortObject(obj) {
37
+ const sorted = {};
38
+ for (const key of Object.keys(obj).sort()) {
39
+ const value = obj[key];
40
+ sorted[key] = value && typeof value === 'object' && !Array.isArray(value)
41
+ ? sortObject(value)
42
+ : value;
43
+ }
44
+ return sorted;
45
+ }
46
+ /**
47
+ * In-memory props cache implementation
48
+ */
49
+ export class MemoryPropsCache {
50
+ cache = new Map();
51
+ ttl;
52
+ constructor(ttl = DEFAULT_CACHE_TTL) {
53
+ this.ttl = ttl;
54
+ }
55
+ get(key) {
56
+ const entry = this.cache.get(key);
57
+ if (!entry)
58
+ return undefined;
59
+ // Check if expired
60
+ if (Date.now() - entry.timestamp > this.ttl) {
61
+ this.cache.delete(key);
62
+ return undefined;
63
+ }
64
+ return entry;
65
+ }
66
+ set(key, props) {
67
+ this.cache.set(key, {
68
+ props,
69
+ timestamp: Date.now(),
70
+ key
71
+ });
72
+ }
73
+ delete(key) {
74
+ return this.cache.delete(key);
75
+ }
76
+ clear() {
77
+ this.cache.clear();
78
+ }
79
+ get size() {
80
+ return this.cache.size;
81
+ }
82
+ /**
83
+ * Remove expired entries
84
+ */
85
+ cleanup() {
86
+ const now = Date.now();
87
+ let removed = 0;
88
+ for (const [key, entry] of this.cache) {
89
+ if (now - entry.timestamp > this.ttl) {
90
+ this.cache.delete(key);
91
+ removed++;
92
+ }
93
+ }
94
+ return removed;
95
+ }
96
+ /**
97
+ * Get all entries (for debugging)
98
+ */
99
+ entries() {
100
+ return this.cache.entries();
101
+ }
102
+ }
103
+ /**
104
+ * Global default cache instance
105
+ */
106
+ let defaultCache = null;
107
+ /**
108
+ * Get or create the default cache
109
+ */
110
+ export function getDefaultCache() {
111
+ if (!defaultCache) {
112
+ defaultCache = new MemoryPropsCache();
113
+ }
114
+ return defaultCache;
115
+ }
116
+ /**
117
+ * Configure the default cache
118
+ */
119
+ export function configureCache(ttl) {
120
+ defaultCache = new MemoryPropsCache(ttl);
121
+ }
122
+ /**
123
+ * Clear the default cache
124
+ */
125
+ export function clearCache() {
126
+ if (defaultCache) {
127
+ defaultCache.clear();
128
+ }
129
+ }
130
+ /**
131
+ * LRU (Least Recently Used) cache implementation
132
+ * For scenarios where memory usage needs to be bounded
133
+ */
134
+ export class LRUPropsCache {
135
+ cache = new Map();
136
+ maxSize;
137
+ ttl;
138
+ constructor(maxSize = 100, ttl = DEFAULT_CACHE_TTL) {
139
+ this.maxSize = maxSize;
140
+ this.ttl = ttl;
141
+ }
142
+ get(key) {
143
+ const entry = this.cache.get(key);
144
+ if (!entry)
145
+ return undefined;
146
+ // Check if expired
147
+ if (Date.now() - entry.timestamp > this.ttl) {
148
+ this.cache.delete(key);
149
+ return undefined;
150
+ }
151
+ // Move to end (most recently used)
152
+ this.cache.delete(key);
153
+ this.cache.set(key, entry);
154
+ return entry;
155
+ }
156
+ set(key, props) {
157
+ // Remove oldest entries if at capacity
158
+ while (this.cache.size >= this.maxSize) {
159
+ const oldest = this.cache.keys().next().value;
160
+ if (oldest) {
161
+ this.cache.delete(oldest);
162
+ }
163
+ else {
164
+ break;
165
+ }
166
+ }
167
+ this.cache.set(key, {
168
+ props,
169
+ timestamp: Date.now(),
170
+ key
171
+ });
172
+ }
173
+ delete(key) {
174
+ return this.cache.delete(key);
175
+ }
176
+ clear() {
177
+ this.cache.clear();
178
+ }
179
+ get size() {
180
+ return this.cache.size;
181
+ }
182
+ }
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Props generation for ai-props
3
+ *
4
+ * Core functionality for generating component props using AI.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ import { generateObject } from 'ai-functions';
9
+ import { createCacheKey, getDefaultCache } from './cache.js';
10
+ /**
11
+ * Default configuration
12
+ */
13
+ const DEFAULT_CONFIG = {
14
+ model: 'sonnet',
15
+ cache: true,
16
+ cacheTTL: 5 * 60 * 1000, // 5 minutes
17
+ };
18
+ /**
19
+ * Global configuration
20
+ */
21
+ let globalConfig = { ...DEFAULT_CONFIG };
22
+ /**
23
+ * Configure global AI props settings
24
+ */
25
+ export function configureAIProps(config) {
26
+ globalConfig = { ...globalConfig, ...config };
27
+ }
28
+ /**
29
+ * Get current configuration
30
+ */
31
+ export function getConfig() {
32
+ return { ...globalConfig };
33
+ }
34
+ /**
35
+ * Reset configuration to defaults
36
+ */
37
+ export function resetConfig() {
38
+ globalConfig = { ...DEFAULT_CONFIG };
39
+ }
40
+ /**
41
+ * Resolve a prop schema to a SimpleSchema
42
+ *
43
+ * If the schema is a string, it's treated as a named type
44
+ * that generates a single property or description.
45
+ */
46
+ function resolveSchema(schema) {
47
+ if (typeof schema === 'string') {
48
+ // Named type or description string
49
+ return { value: schema };
50
+ }
51
+ return schema;
52
+ }
53
+ /**
54
+ * Build a prompt from context and schema
55
+ */
56
+ function buildPrompt(schema, context, additionalPrompt) {
57
+ const parts = [];
58
+ // Add context information
59
+ if (context && Object.keys(context).length > 0) {
60
+ parts.push('Given the following context:');
61
+ parts.push(JSON.stringify(context, null, 2));
62
+ parts.push('');
63
+ }
64
+ // Add schema information
65
+ if (typeof schema === 'string') {
66
+ parts.push(`Generate a value for: ${schema}`);
67
+ }
68
+ else {
69
+ parts.push('Generate props matching the schema.');
70
+ }
71
+ // Add additional prompt
72
+ if (additionalPrompt) {
73
+ parts.push('');
74
+ parts.push(additionalPrompt);
75
+ }
76
+ return parts.join('\n');
77
+ }
78
+ /**
79
+ * Generate props using AI
80
+ *
81
+ * @example
82
+ * ```ts
83
+ * const result = await generateProps({
84
+ * schema: {
85
+ * title: 'A compelling page title',
86
+ * description: 'A brief description',
87
+ * keywords: ['Relevant SEO keywords'],
88
+ * },
89
+ * context: { topic: 'AI-powered applications' },
90
+ * })
91
+ *
92
+ * console.log(result.props)
93
+ * // { title: '...', description: '...', keywords: [...] }
94
+ * ```
95
+ */
96
+ export async function generateProps(options) {
97
+ const { schema, context, prompt, model, system } = options;
98
+ const config = getConfig();
99
+ const startTime = Date.now();
100
+ // Check cache
101
+ if (config.cache) {
102
+ const cache = getDefaultCache();
103
+ const cacheKey = createCacheKey(schema, context);
104
+ const cached = cache.get(cacheKey);
105
+ if (cached) {
106
+ return {
107
+ props: cached.props,
108
+ cached: true,
109
+ metadata: {
110
+ model: config.model || 'cached',
111
+ },
112
+ };
113
+ }
114
+ }
115
+ // Resolve schema
116
+ const resolvedSchema = resolveSchema(schema);
117
+ // Build prompt
118
+ const fullPrompt = buildPrompt(schema, context, prompt);
119
+ // Use custom generator if provided
120
+ if (config.generate) {
121
+ const props = await config.generate(resolvedSchema, context || {});
122
+ return {
123
+ props,
124
+ cached: false,
125
+ metadata: {
126
+ model: 'custom',
127
+ duration: Date.now() - startTime,
128
+ },
129
+ };
130
+ }
131
+ // Generate using AI
132
+ const result = await generateObject({
133
+ model: model || config.model || 'sonnet',
134
+ schema: resolvedSchema,
135
+ prompt: fullPrompt,
136
+ system: system || config.system,
137
+ });
138
+ const props = result.object;
139
+ // Cache result
140
+ if (config.cache) {
141
+ const cache = getDefaultCache();
142
+ const cacheKey = createCacheKey(schema, context);
143
+ cache.set(cacheKey, props);
144
+ }
145
+ return {
146
+ props,
147
+ cached: false,
148
+ metadata: {
149
+ model: model || config.model || 'sonnet',
150
+ duration: Date.now() - startTime,
151
+ },
152
+ };
153
+ }
154
+ /**
155
+ * Generate props synchronously from cache or throw
156
+ *
157
+ * Useful for SSR scenarios where async isn't available.
158
+ * Throws if props aren't in cache.
159
+ */
160
+ export function getPropsSync(schema, context) {
161
+ const cache = getDefaultCache();
162
+ const cacheKey = createCacheKey(schema, context);
163
+ const cached = cache.get(cacheKey);
164
+ if (!cached) {
165
+ throw new Error('Props not in cache. Use generateProps() first or ensure caching is enabled.');
166
+ }
167
+ return cached.props;
168
+ }
169
+ /**
170
+ * Pre-generate props for warming the cache
171
+ *
172
+ * @example
173
+ * ```ts
174
+ * await prefetchProps([
175
+ * { schema: userProfileSchema, context: { userId: '123' } },
176
+ * { schema: productSchema, context: { category: 'electronics' } },
177
+ * ])
178
+ * ```
179
+ */
180
+ export async function prefetchProps(requests) {
181
+ await Promise.all(requests.map(generateProps));
182
+ }
183
+ /**
184
+ * Generate multiple prop sets in parallel
185
+ */
186
+ export async function generatePropsMany(requests) {
187
+ return Promise.all(requests.map(req => generateProps(req)));
188
+ }
189
+ /**
190
+ * Merge partial props with generated props
191
+ *
192
+ * Generates only the missing props, keeping provided ones.
193
+ */
194
+ export async function mergeWithGenerated(schema, partialProps, options) {
195
+ // Get list of missing keys
196
+ const schemaObj = typeof schema === 'string' ? { value: schema } : schema;
197
+ const schemaKeys = Object.keys(schemaObj);
198
+ const providedKeys = Object.keys(partialProps);
199
+ const missingKeys = schemaKeys.filter(k => !providedKeys.includes(k));
200
+ // If all props are provided, return as-is
201
+ if (missingKeys.length === 0) {
202
+ return partialProps;
203
+ }
204
+ // Build partial schema for missing props only
205
+ const partialSchema = {};
206
+ for (const key of missingKeys) {
207
+ partialSchema[key] = schemaObj[key];
208
+ }
209
+ // Generate missing props
210
+ const result = await generateProps({
211
+ schema: partialSchema,
212
+ context: partialProps,
213
+ ...options,
214
+ });
215
+ // Merge
216
+ return {
217
+ ...result.props,
218
+ ...partialProps,
219
+ };
220
+ }