@revealui/setup 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 RevealUI Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/README.md ADDED
@@ -0,0 +1,306 @@
1
+ # @revealui/setup
2
+
3
+ Shared setup utilities for RevealUI projects. Provides environment variable management, database initialization, and configuration validation.
4
+
5
+ ## Features
6
+
7
+ - **Environment Setup** - Interactive and automated environment variable configuration
8
+ - **Secret Generation** - Cryptographically secure secret and password generation
9
+ - **Validation** - Type-safe validation for environment variables
10
+ - **Logging** - Consistent, colored console output with log levels
11
+ - **Reusable** - Used by both @revealui/cli and setup scripts
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ pnpm add @revealui/setup
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ### Environment Setup
22
+
23
+ ```typescript
24
+ import { setupEnvironment } from '@revealui/setup/environment'
25
+
26
+ // Interactive setup with prompts
27
+ const result = await setupEnvironment({
28
+ projectRoot: '/path/to/project',
29
+ interactive: true
30
+ })
31
+
32
+ if (result.success) {
33
+ console.log('Environment configured!')
34
+ } else {
35
+ console.log('Missing variables:', result.missing)
36
+ }
37
+ ```
38
+
39
+ ### Generate Secrets
40
+
41
+ ```typescript
42
+ import { generateSecret, generatePassword } from '@revealui/setup/environment'
43
+
44
+ const jwtSecret = generateSecret(32) // 64-char hex string
45
+ const password = generatePassword(16) // 16-char alphanumeric + special
46
+ ```
47
+
48
+ ### Validate Environment
49
+
50
+ ```typescript
51
+ import { validateEnv, REQUIRED_ENV_VARS } from '@revealui/setup/validators'
52
+
53
+ const validation = validateEnv(REQUIRED_ENV_VARS, process.env)
54
+
55
+ if (!validation.valid) {
56
+ console.log('Missing:', validation.missing)
57
+ console.log('Invalid:', validation.invalid)
58
+ }
59
+ ```
60
+
61
+ ### Logging
62
+
63
+ ```typescript
64
+ import { createLogger } from '@revealui/setup/utils'
65
+
66
+ const logger = createLogger({
67
+ prefix: 'MyScript',
68
+ level: 'info',
69
+ timestamps: true
70
+ })
71
+
72
+ logger.info('Starting process')
73
+ logger.success('Completed!')
74
+ logger.error('Failed')
75
+ logger.header('Section Title')
76
+ logger.divider()
77
+ logger.progress(50, 100, 'Processing')
78
+ ```
79
+
80
+ ## API Reference
81
+
82
+ ### Environment
83
+
84
+ #### `setupEnvironment(options)`
85
+
86
+ Sets up environment variables for a project.
87
+
88
+ **Options:**
89
+ - `projectRoot: string` - Project root directory
90
+ - `templatePath?: string` - Path to .env.template (default: `{projectRoot}/.env.template`)
91
+ - `outputPath?: string` - Output path (default: `{projectRoot}/.env.development.local`)
92
+ - `force?: boolean` - Overwrite existing file without prompting
93
+ - `generateOnly?: boolean` - Only generate secrets, skip prompts
94
+ - `interactive?: boolean` - Enable interactive prompts (default: true)
95
+ - `customVariables?: EnvVariable[]` - Custom variable definitions
96
+ - `logger?: Logger` - Custom logger instance
97
+
98
+ **Returns:** `Promise<SetupEnvironmentResult>`
99
+ - `success: boolean` - Whether setup completed successfully
100
+ - `envPath: string` - Path to generated env file
101
+ - `missing: string[]` - Variables still missing
102
+ - `invalid: string[]` - Variables with invalid values
103
+
104
+ #### `generateSecret(length?: number)`
105
+
106
+ Generates cryptographically secure hex string.
107
+
108
+ #### `generatePassword(length?: number)`
109
+
110
+ Generates random password with alphanumeric + special characters.
111
+
112
+ #### `updateEnvValue(content, key, value)`
113
+
114
+ Updates or adds an environment variable in file content.
115
+
116
+ #### `parseEnvContent(content)`
117
+
118
+ Parses environment file content into key-value object.
119
+
120
+ ### Validators
121
+
122
+ #### `validateEnv(required, env)`
123
+
124
+ Validates environment variables against schema.
125
+
126
+ **Parameters:**
127
+ - `required: EnvVariable[]` - Required variable definitions
128
+ - `env: Record<string, string>` - Environment to validate
129
+
130
+ **Returns:** `ValidationResult`
131
+ - `valid: boolean`
132
+ - `missing: string[]`
133
+ - `invalid: string[]`
134
+
135
+ #### `validators`
136
+
137
+ Pre-built validators:
138
+ - `postgresUrl` - PostgreSQL connection string
139
+ - `stripeSecretKey` - Stripe secret key format
140
+ - `stripePublishableKey` - Stripe publishable key format
141
+ - `url` - Valid URL format
142
+ - `email` - Valid email format
143
+ - `minLength(n)` - Minimum string length
144
+
145
+ #### `REQUIRED_ENV_VARS`
146
+
147
+ Default required environment variables for RevealUI:
148
+ - `REVEALUI_SECRET` - JWT secret (min 32 chars)
149
+ - `POSTGRES_URL` - Database connection string
150
+ - `BLOB_READ_WRITE_TOKEN` - Vercel Blob token
151
+ - `STRIPE_SECRET_KEY` - Stripe secret key
152
+ - `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` - Stripe publishable key
153
+
154
+ #### `OPTIONAL_ENV_VARS`
155
+
156
+ Optional environment variables (Supabase, Sentry, admin config, etc.)
157
+
158
+ ### Utilities
159
+
160
+ #### `createLogger(options)`
161
+
162
+ Creates a logger instance with configurable options.
163
+
164
+ **Options:**
165
+ - `level?: 'debug' | 'info' | 'warn' | 'error' | 'silent'`
166
+ - `prefix?: string` - Prefix for all log messages
167
+ - `colors?: boolean` - Enable colors (auto-detected by default)
168
+ - `timestamps?: boolean` - Include timestamps
169
+
170
+ **Methods:**
171
+ - `debug(msg, ...args)` - Debug message
172
+ - `info(msg, ...args)` - Info message
173
+ - `warn(msg, ...args)` - Warning message
174
+ - `error(msg, ...args)` - Error message
175
+ - `success(msg, ...args)` - Success message
176
+ - `header(msg)` - Formatted header
177
+ - `divider()` - Visual divider
178
+ - `table(data)` - Console table
179
+ - `group(label)` - Start group
180
+ - `groupEnd()` - End group
181
+ - `progress(current, total, label?)` - Progress bar
182
+
183
+ ## Examples
184
+
185
+ ### Complete Setup Flow
186
+
187
+ ```typescript
188
+ import { setupEnvironment, createLogger } from '@revealui/setup'
189
+
190
+ const logger = createLogger({ prefix: 'Setup' })
191
+
192
+ logger.header('Project Setup')
193
+
194
+ const result = await setupEnvironment({
195
+ projectRoot: process.cwd(),
196
+ interactive: true,
197
+ logger
198
+ })
199
+
200
+ if (result.success) {
201
+ logger.success('Environment configured successfully!')
202
+ logger.info(`Config file: ${result.envPath}`)
203
+ } else {
204
+ logger.error('Setup failed')
205
+ logger.info('Missing variables:', result.missing.join(', '))
206
+ }
207
+ ```
208
+
209
+ ### Non-Interactive Setup
210
+
211
+ ```typescript
212
+ import { setupEnvironment } from '@revealui/setup'
213
+
214
+ // Generate secrets only, no prompts
215
+ const result = await setupEnvironment({
216
+ projectRoot: '/path/to/project',
217
+ interactive: false,
218
+ generateOnly: true
219
+ })
220
+ ```
221
+
222
+ ### Custom Validation
223
+
224
+ ```typescript
225
+ import { validateEnv, validators, type EnvVariable } from '@revealui/setup/validators'
226
+
227
+ const customVars: EnvVariable[] = [
228
+ {
229
+ name: 'API_KEY',
230
+ description: 'Third-party API key',
231
+ required: true,
232
+ validator: validators.minLength(20)
233
+ },
234
+ {
235
+ name: 'WEBHOOK_URL',
236
+ description: 'Webhook endpoint',
237
+ required: true,
238
+ validator: validators.url
239
+ }
240
+ ]
241
+
242
+ const validation = validateEnv(customVars, process.env)
243
+ ```
244
+
245
+ ## Package Exports
246
+
247
+ ```typescript
248
+ // Main export
249
+ import { setupEnvironment, createLogger } from '@revealui/setup'
250
+
251
+ // Subpath exports
252
+ import { setupEnvironment } from '@revealui/setup/environment'
253
+ import { validateEnv } from '@revealui/setup/validators'
254
+ import { createLogger } from '@revealui/setup/utils'
255
+ ```
256
+
257
+ ## Integration
258
+
259
+ ### In @revealui/cli
260
+
261
+ ```typescript
262
+ import { setupEnvironment, createLogger } from '@revealui/setup'
263
+
264
+ const logger = createLogger({ prefix: '@revealui/cli' })
265
+
266
+ await setupEnvironment({
267
+ projectRoot: projectPath,
268
+ interactive: true,
269
+ logger
270
+ })
271
+ ```
272
+
273
+ ### In Setup Scripts
274
+
275
+ ```typescript
276
+ #!/usr/bin/env tsx
277
+ import { setupEnvironment } from '@revealui/setup'
278
+
279
+ await setupEnvironment({
280
+ projectRoot: process.cwd(),
281
+ force: process.argv.includes('--force')
282
+ })
283
+ ```
284
+
285
+ ## Development
286
+
287
+ ```bash
288
+ # Build package
289
+ pnpm build
290
+
291
+ # Watch mode
292
+ pnpm dev
293
+
294
+ # Type check
295
+ pnpm typecheck
296
+
297
+ # Run tests
298
+ pnpm test
299
+
300
+ # Coverage
301
+ pnpm test:coverage
302
+ ```
303
+
304
+ ## License
305
+
306
+ MIT
@@ -0,0 +1,95 @@
1
+ import { createLogger } from '../utils/index.js';
2
+ import { EnvVariable } from '../validators/index.js';
3
+
4
+ /**
5
+ * Environment secret and password generators
6
+ */
7
+ /**
8
+ * Generates a secure random secret.
9
+ *
10
+ * @param length - Length in bytes (default: 32 bytes = 64 hex chars)
11
+ * @returns Hex-encoded random secret
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * const secret = generateSecret() // 64 char hex string
16
+ * ```
17
+ */
18
+ declare function generateSecret(length?: number): string;
19
+ /**
20
+ * Generates a secure password with alphanumeric and special characters.
21
+ *
22
+ * @param length - Password length (default: 16)
23
+ * @returns Random password
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * const password = generatePassword(16) // e.g., "aB3!xY9@pQ5#mN7$"
28
+ * ```
29
+ */
30
+ declare function generatePassword(length?: number): string;
31
+ /**
32
+ * Updates a value in environment file content.
33
+ *
34
+ * @param content - Original env file content
35
+ * @param key - Environment variable name
36
+ * @param value - New value
37
+ * @returns Updated env file content
38
+ *
39
+ * @example
40
+ * ```typescript
41
+ * const updated = updateEnvValue(content, 'DB_URL', 'postgresql://...')
42
+ * ```
43
+ */
44
+ declare function updateEnvValue(content: string, key: string, value: string): string;
45
+ /**
46
+ * Parses environment file content into key-value pairs.
47
+ *
48
+ * @param content - Environment file content
49
+ * @returns Parsed environment variables
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * const env = parseEnvContent('DB_URL=postgresql://...\nAPI_KEY=abc123')
54
+ * // { DB_URL: 'postgresql://...', API_KEY: 'abc123' }
55
+ * ```
56
+ */
57
+ declare function parseEnvContent(content: string): Record<string, string>;
58
+
59
+ /**
60
+ * Environment setup orchestration
61
+ */
62
+
63
+ interface SetupEnvironmentOptions {
64
+ projectRoot: string;
65
+ templatePath?: string;
66
+ outputPath?: string;
67
+ force?: boolean;
68
+ generateOnly?: boolean;
69
+ interactive?: boolean;
70
+ customVariables?: EnvVariable[];
71
+ logger?: ReturnType<typeof createLogger>;
72
+ }
73
+ interface SetupEnvironmentResult {
74
+ success: boolean;
75
+ envPath: string;
76
+ missing: string[];
77
+ invalid: string[];
78
+ }
79
+ /**
80
+ * Sets up environment variables for a project.
81
+ *
82
+ * @param options - Setup configuration options
83
+ * @returns Setup result with validation info
84
+ *
85
+ * @example
86
+ * ```typescript
87
+ * const result = await setupEnvironment({
88
+ * projectRoot: '/path/to/project',
89
+ * interactive: true
90
+ * })
91
+ * ```
92
+ */
93
+ declare function setupEnvironment(options: SetupEnvironmentOptions): Promise<SetupEnvironmentResult>;
94
+
95
+ export { type SetupEnvironmentOptions, type SetupEnvironmentResult, generatePassword, generateSecret, parseEnvContent, setupEnvironment, updateEnvValue };