forked from cloudflare/vibesdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.ts
More file actions
executable file
·2121 lines (1803 loc) · 78.1 KB
/
setup.ts
File metadata and controls
executable file
·2121 lines (1803 loc) · 78.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
import { execSync } from 'child_process';
import { existsSync, readFileSync, writeFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { parse, modify, applyEdits } from 'jsonc-parser';
import Cloudflare from 'cloudflare';
import { createInterface } from 'readline';
// Get current directory for ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const PROJECT_ROOT = join(__dirname, '..');
interface SetupConfig {
accountId: string;
apiToken: string;
customDomain?: string;
useAIGateway: boolean;
aiGatewayUrl?: string;
useRemoteBindings: boolean;
devVars: Record<string, string>;
setupRemote?: boolean;
prodDomain?: string;
prodVars?: Record<string, string>;
customProviderKeys?: Array<{key: string, provider: string}>;
}
interface ResourceInfo {
kvNamespaces: Array<{ name: string; id: string; binding: string; accessible: boolean }>;
d1Databases: Array<{ name: string; id: string; binding: string; accessible: boolean }>;
r2Buckets: Array<{ name: string; binding: string; accessible: boolean }>;
dispatchNamespaces: Array<{ name: string; binding: string; accessible: boolean }>;
zones: Array<{ name: string; id: string }>;
aiGateway?: { name: string; exists: boolean; tokenCreated: boolean; tokenError?: string };
}
interface ReadinessReport {
localDevReady: boolean;
deploymentReady: boolean;
issues: string[];
suggestions: string[];
resourcesCreated: string[];
accountInfo?: {
plan: string;
features: string[];
};
}
class SetupManager {
private config!: SetupConfig;
private cloudflare!: Cloudflare;
private aiGatewayCloudflare?: Cloudflare;
private existingConfig: Record<string, string> = {};
private packageManager: 'bun' | 'npm' = 'npm';
private readline = createInterface({
input: process.stdin,
output: process.stdout,
});
constructor() {
console.log('🚀 VibeSDK Development Setup');
console.log('============================\n');
}
async setup(): Promise<void> {
try {
await this.setupPackageManager();
this.loadExistingConfig();
await this.collectUserConfig();
await this.initializeCloudflareClient();
const resources = await this.validateAndSetupResources();
await this.safeExecute('generate .dev.vars file', () => this.generateDevVarsFile());
if (this.config.setupRemote) {
await this.safeExecute('generate .prod.vars file', () => this.generateProdVarsFile());
}
await this.safeExecute('update wrangler.jsonc', () => this.updateWranglerConfig(resources));
await this.safeExecute('update vite.config.ts', () => this.updateViteConfig());
const report = await this.generateReadinessReport(resources);
// Setup AI Gateway if configured
if (this.config.useAIGateway) {
await this.safeExecute('setup AI Gateway', () => this.ensureAIGateway(resources));
}
// Update worker configuration for custom providers
if (this.config.customProviderKeys && this.config.customProviderKeys.length > 0) {
await this.safeExecute('update worker configuration', () => this.updateWorkerConfiguration());
}
await this.patchDockerfileForARM64();
this.displayFinalReport(report, resources);
} catch (error) {
console.error('\n❌ Setup encountered a critical error:', error instanceof Error ? error.message : String(error));
console.error('\n💡 Troubleshooting:');
console.error(' 1. Verify your Cloudflare API token has the required permissions');
console.error(' 2. Check your account has access to the required Cloudflare services');
console.error(' 3. Try running the script again or set up manually');
console.error('\n📚 See docs/setup.md for manual setup instructions');
process.exit(1);
} finally {
this.readline.close();
}
}
private async safeExecute(actionName: string, action: () => Promise<void>): Promise<void> {
try {
await action();
} catch (error) {
console.error(`❌ Failed to ${actionName}:`, error instanceof Error ? error.message : String(error));
console.error(' You may need to complete this step manually');
}
}
private async setupPackageManager(): Promise<void> {
console.log('📦 Package Manager Setup');
console.log('------------------------\n');
const hasBun = await this.checkCommandExists('bun');
const hasNpm = await this.checkCommandExists('npm');
if (hasBun) {
console.log('✅ Bun is available - using bun for optimal performance');
this.packageManager = 'bun';
} else if (hasNpm) {
console.log('✅ npm is available');
console.log('📥 Installing Bun for better performance...');
try {
execSync('curl -fsSL https://bun.sh/install | bash', { stdio: 'inherit' });
if (await this.checkCommandExists('bun')) {
console.log('✅ Bun installed successfully!');
this.packageManager = 'bun';
} else {
console.log('⚠️ Bun installation completed, but may require shell restart. Using npm for now.');
this.packageManager = 'npm';
}
} catch (error) {
console.error('❌ Failed to install Bun:', error instanceof Error ? error.message : String(error));
console.log(' Continuing with npm...');
this.packageManager = 'npm';
}
} else {
throw new Error('Neither npm nor bun is available. Please install Node.js with npm or Bun.');
}
console.log(`\n📦 Using package manager: ${this.packageManager}\n`);
}
private async checkCommandExists(command: string): Promise<boolean> {
try {
execSync(`${command} --version`, { stdio: 'pipe' });
return true;
} catch {
return false;
}
}
private loadExistingConfig(): void {
const devVarsPath = join(PROJECT_ROOT, '.dev.vars');
const prodVarsPath = join(PROJECT_ROOT, '.prod.vars');
// Load .dev.vars
if (existsSync(devVarsPath)) {
console.log('📄 Found existing .dev.vars file - reading current configuration...');
this.parseConfigFile(devVarsPath);
}
// Load .prod.vars for production config
if (existsSync(prodVarsPath)) {
console.log('📄 Found existing .prod.vars file - reading production configuration...');
this.parseConfigFile(prodVarsPath);
}
if (!existsSync(devVarsPath) && !existsSync(prodVarsPath)) {
console.log('📄 No existing configuration files found - starting fresh setup');
return;
}
const configuredKeys = Object.keys(this.existingConfig);
if (configuredKeys.length > 0) {
console.log(`✅ Found ${configuredKeys.length} existing configuration values`);
console.log(' Will only prompt for missing or updated values\n');
}
}
private parseConfigFile(filePath: string): void {
try {
const content = readFileSync(filePath, 'utf-8');
const lines = content.split('\n');
for (const line of lines) {
const trimmed = line.trim();
if (trimmed && !trimmed.startsWith('#') && trimmed.includes('=')) {
const [key, ...valueParts] = trimmed.split('=');
const value = valueParts.join('=').replace(/^["']|["']$/g, ''); // Remove quotes
if (key && value) {
this.existingConfig[key] = value;
}
}
}
} catch (error) {
console.warn(`⚠️ Could not read config file: ${error instanceof Error ? error.message : String(error)}`);
}
}
private async prompt(question: string): Promise<string> {
return new Promise((resolve) => {
this.readline.question(question, (answer) => {
resolve(answer.trim());
});
});
}
private async promptWithDefault(question: string, existingValue?: string): Promise<string> {
if (existingValue) {
const maskedValue = this.maskSensitiveValue(question, existingValue);
const answer = await this.prompt(`${question} [current: ${maskedValue}]: `);
return answer || existingValue;
}
return this.prompt(question);
}
private maskSensitiveValue(question: string, value: string): string {
const sensitivePatterns = ['TOKEN', 'SECRET', 'KEY', 'PASSWORD'];
const isSensitive = sensitivePatterns.some(pattern =>
question.toUpperCase().includes(pattern)
);
if (isSensitive && value.length > 8) {
return `${value.substring(0, 4)}...${value.substring(value.length - 4)}`;
}
return value;
}
private async collectUserConfig(): Promise<void> {
console.log('📋 Configuration Review & Setup');
console.log('--------------------------------\n');
// Get Cloudflare account ID
const accountId = await this.promptWithDefault(
'Enter your Cloudflare Account ID: ',
this.existingConfig.CLOUDFLARE_ACCOUNT_ID
);
if (!accountId) {
throw new Error('Account ID is required');
}
// Get API token
const apiToken = await this.promptWithDefault(
'Enter your Cloudflare API Token: ',
this.existingConfig.CLOUDFLARE_API_TOKEN
);
if (!apiToken) {
throw new Error('API Token is required');
}
// Domain Configuration - Ask once upfront with existing domain detection
console.log('\n🌐 Domain Configuration');
console.log('A custom domain is required for production deployment and remote resource access.');
console.log('Without a custom domain, only local development will be available.\n');
let customDomain: string | undefined;
let useRemoteBindings = false;
let setupRemote = false;
let prodDomain: string | undefined;
// Check if we already have a production domain configured
const existingProdDomain = this.existingConfig.CUSTOM_DOMAIN &&
this.existingConfig.CUSTOM_DOMAIN !== 'localhost:5173' ?
this.existingConfig.CUSTOM_DOMAIN : undefined;
while (true) {
customDomain = await this.promptWithDefault(
'Enter your custom domain (or press Enter to skip): ',
existingProdDomain || this.existingConfig.CUSTOM_DOMAIN
);
if (!customDomain || customDomain.trim() === '' || customDomain === 'localhost:5173') {
console.log('\n⚠️ No custom domain provided.');
console.log(' • Remote Cloudflare resources: Not available');
console.log(' • Production deployment: Not available');
console.log(' • Only local development will be configured\n');
const continueChoice = await this.prompt('Continue with local-only setup? (Y/n): ');
if (continueChoice.toLowerCase() === 'n') {
console.log('Please provide a custom domain:\n');
continue;
}
customDomain = 'localhost:5173';
useRemoteBindings = false;
setupRemote = false;
break;
} else {
console.log(`✅ Custom domain set: ${customDomain}`);
prodDomain = customDomain; // Use same domain for production
// Ask about remote resources
const remoteChoice = await this.prompt('Use remote Cloudflare resources (KV, D1, R2, etc.)? (Y/n): ');
useRemoteBindings = remoteChoice.toLowerCase() !== 'n';
// Ask about production setup
const prodChoice = await this.prompt('Configure for production deployment? (Y/n): ');
setupRemote = prodChoice.toLowerCase() !== 'n';
if (useRemoteBindings) {
console.log('✅ Remote Cloudflare resources will be used');
} else {
console.log('✅ Local-only bindings selected');
}
break;
}
}
const finalDomain = customDomain || 'localhost:5173';
// AI Gateway configuration
console.log('\n🤖 AI Gateway Configuration');
const useAIGatewayChoice = await this.prompt('Use Cloudflare AI Gateway? [STRONGLY RECOMMENDED for developer experience] (Y/n): ');
const useAIGateway = useAIGatewayChoice.toLowerCase() !== 'n';
let aiGatewayUrl: string | undefined;
const devVars: Record<string, string> = {};
const providedProviders: string[] = [];
let customProviderKeys: Array<{key: string, provider: string}> = [];
if (useAIGateway) {
console.log('✅ AI Gateway enabled - will auto-configure CLOUDFLARE_AI_GATEWAY_TOKEN');
// Generate suggested URL
const wranglerConfig = this.parseWranglerConfig();
const gatewayName = wranglerConfig.vars?.CLOUDFLARE_AI_GATEWAY || 'vibesdk-gateway';
const suggestedUrl = `https://gateway.ai.cloudflare.com/v1/${accountId}/${gatewayName}/`;
// Use existing URL if available, otherwise use suggested URL as default
const existingUrl = this.existingConfig.CLOUDFLARE_AI_GATEWAY_URL;
const defaultUrl = existingUrl || suggestedUrl;
if (!existingUrl) {
console.log(`\n💡 AI Gateway URL format: https://gateway.ai.cloudflare.com/v1/<account_id>/<gateway_name>/`);
console.log(` Suggested: ${suggestedUrl}`);
}
aiGatewayUrl = await this.promptWithDefault(
'Enter AI Gateway URL: ',
defaultUrl
);
if (!aiGatewayUrl || aiGatewayUrl.trim() === '') {
throw new Error('AI Gateway URL is required when AI Gateway is enabled');
}
} else {
console.log('\n⚠️ WARNING: Without AI Gateway, you MUST manually edit worker/agents/inferutils/config.ts');
console.log(' to configure your models. Model names should be in format: "<provider-name>/<model-name>"');
console.log(' Example: "openai/gpt-4" or "anthropic/claude-3-5-sonnet"\n');
aiGatewayUrl = await this.prompt('Enter custom OpenAI-compatible URL (optional): ');
}
// AI Provider configuration
console.log('\n🔧 AI Provider Configuration');
console.log('Available providers:');
console.log(' 1. OpenAI (for GPT models)');
console.log(' 2. Anthropic (for Claude models)');
console.log(' 3. Google AI Studio (for Gemini models) [DEFAULT]');
console.log(' 4. Cerebras (for open source models)');
console.log(' 5. OpenRouter (for various models)');
console.log(' 6. Custom provider\n');
const providerChoice = await this.prompt('Select providers (comma-separated numbers, e.g., 1,2,3): ');
const selectedProviders = providerChoice.split(',').map(n => parseInt(n.trim())).filter(n => n >= 1 && n <= 6);
if (selectedProviders.length === 0) {
console.log('⚠️ No providers selected - you MUST configure at least one provider!');
console.log(' Adding Google AI Studio as default...');
selectedProviders.push(3);
}
// Process selected providers
const providerMap = {
1: { name: 'OpenAI', key: 'OPENAI_API_KEY', provider: 'openai' },
2: { name: 'Anthropic', key: 'ANTHROPIC_API_KEY', provider: 'anthropic' },
3: { name: 'Google AI Studio', key: 'GOOGLE_AI_STUDIO_API_KEY', provider: 'google-ai-studio' },
4: { name: 'Cerebras', key: 'CEREBRAS_API_KEY', provider: 'cerebras' },
5: { name: 'OpenRouter', key: 'OPENROUTER_API_KEY', provider: 'openrouter' }
};
console.log('\n🔑 API Key Configuration');
for (const choice of selectedProviders) {
if (choice === 6) {
// Custom provider
const customProviderName = await this.prompt('Enter custom provider name: ');
if (customProviderName) {
const customKey = `${customProviderName.toUpperCase().replace(/[^A-Z0-9]/g, '_')}_API_KEY`;
const apiKey = await this.prompt(`${customKey}: `);
if (apiKey) {
devVars[customKey] = apiKey;
customProviderKeys.push({ key: customKey, provider: customProviderName });
providedProviders.push(customProviderName);
}
}
} else {
const provider = providerMap[choice as keyof typeof providerMap];
if (provider) {
const existing = this.existingConfig[provider.key];
const value = await this.promptWithDefault(`${provider.name} API Key (${provider.key}): `, existing);
if (value) {
devVars[provider.key] = value;
providedProviders.push(provider.provider);
}
}
}
}
// Warning about config.ts if not using Gemini as default
const hasGemini = selectedProviders.includes(3);
if (!hasGemini) {
console.log('\n⚠️ IMPORTANT: You selected providers other than Google AI Studio (Gemini).');
console.log(' You MUST edit worker/agents/inferutils/config.ts to change the default model configurations');
console.log(' from Gemini models to your selected providers!\n');
}
// OAuth and other configuration with smart prompts
console.log('\n🔐 OAuth & Other Configuration');
console.log('ℹ️ These credentials enable user authentication and external integrations:');
console.log(' • Google: For Google OAuth user login');
console.log(' • GitHub: For GitHub OAuth user login');
console.log(' • GitHub Export: For exporting generated apps to GitHub repositories\n');
const otherVars = [
'GOOGLE_CLIENT_ID',
'GOOGLE_CLIENT_SECRET',
'GITHUB_CLIENT_ID',
'GITHUB_CLIENT_SECRET',
'GITHUB_EXPORTER_CLIENT_ID',
'GITHUB_EXPORTER_CLIENT_SECRET'
];
for (const varName of otherVars) {
const existing = this.existingConfig[varName];
const value = await this.promptWithDefault(`${varName}: `, existing);
if (value) {
devVars[varName] = value;
}
}
// Provide guidance on model configuration
if (providedProviders.length > 0) {
console.log(`\n✅ API keys configured for: ${providedProviders.join(', ')}`);
}
if (!providedProviders.includes('google-ai-studio')) {
console.log('\n⚠️ No Google AI Studio key provided.');
console.log(' You may need to update model configs in worker/agents/inferutils/config.ts');
console.log(' to use alternative models (OpenAI, Anthropic, etc.) for Gemini fallbacks.');
}
// Generate or preserve required secrets
devVars.JWT_SECRET = this.existingConfig.JWT_SECRET || this.generateRandomSecret(64);
devVars.WEBHOOK_SECRET = this.existingConfig.WEBHOOK_SECRET || this.generateRandomSecret(32);
devVars.USE_TUNNEL_FOR_PREVIEW = 'true';
// Auto-set AI Gateway token if using AI Gateway
if (useAIGateway) {
devVars.CLOUDFLARE_AI_GATEWAY_TOKEN = apiToken;
}
// Prepare production vars (copy dev vars as defaults)
const prodVars = setupRemote && prodDomain ? { ...devVars, CUSTOM_DOMAIN: prodDomain } : undefined;
this.config = {
accountId,
apiToken,
customDomain: finalDomain,
useAIGateway,
aiGatewayUrl,
useRemoteBindings,
devVars,
setupRemote,
prodDomain,
prodVars,
customProviderKeys
};
console.log('\n✅ Configuration collected successfully\n');
}
private generateRandomSecret(length: number): string {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
private async initializeCloudflareClient(): Promise<void> {
console.log('🔐 Validating Cloudflare credentials...');
this.cloudflare = new Cloudflare({
apiToken: this.config.apiToken,
});
try {
// Verify token by getting account info
const account = await this.cloudflare.accounts.get({ account_id: this.config.accountId });
console.log(`✅ Connected to account: ${account.name}`);
} catch (error) {
throw new Error(`Failed to validate Cloudflare credentials: ${error instanceof Error ? error.message : String(error)}`);
}
}
private async validateAndSetupResources(): Promise<ResourceInfo> {
console.log('🔍 Validating and setting up Cloudflare resources...');
const wranglerConfig = this.parseWranglerConfig();
const resources: ResourceInfo = {
kvNamespaces: [],
d1Databases: [],
r2Buckets: [],
dispatchNamespaces: [],
zones: []
};
await this.processKVNamespaces(wranglerConfig, resources);
await this.processD1Databases(wranglerConfig, resources);
await this.safeExecute('setup database', () => this.setupDatabase(resources));
await this.processR2Buckets(wranglerConfig, resources);
await this.safeExecute('deploy templates', () => this.deployTemplates(resources));
await this.processDispatchNamespaces(wranglerConfig, resources);
await this.processCustomDomain(resources);
return resources;
}
private async processKVNamespaces(wranglerConfig: any, resources: ResourceInfo): Promise<void> {
if (!wranglerConfig.kv_namespaces) return;
for (const kv of wranglerConfig.kv_namespaces) {
if (!this.config.useRemoteBindings) {
resources.kvNamespaces.push(this.createLocalResource(kv.binding, 'local'));
} else {
try {
const kvInfo = await this.ensureKVNamespace(kv.binding);
resources.kvNamespaces.push({
name: kvInfo.title,
id: kvInfo.id,
binding: kv.binding,
accessible: true
});
} catch (error) {
this.handleResourceError('KV namespace', kv.binding, error);
resources.kvNamespaces.push(this.createLocalResource(kv.binding, 'local'));
}
}
}
}
private async processD1Databases(wranglerConfig: any, resources: ResourceInfo): Promise<void> {
if (!wranglerConfig.d1_databases) return;
for (const db of wranglerConfig.d1_databases) {
if (!this.config.useRemoteBindings) {
resources.d1Databases.push(this.createLocalResource(db.binding, 'local', db.database_name));
} else {
try {
const dbInfo = await this.ensureD1Database(db.database_name, db.binding);
resources.d1Databases.push({
name: dbInfo.name,
id: dbInfo.uuid,
binding: db.binding,
accessible: true
});
} catch (error) {
this.handleResourceError('D1 database', db.database_name, error, 'D1 Database not accessible (likely requires paid plan)');
resources.d1Databases.push(this.createLocalResource(db.binding, 'local', db.database_name));
}
}
}
}
private async processR2Buckets(wranglerConfig: any, resources: ResourceInfo): Promise<void> {
if (!wranglerConfig.r2_buckets) return;
for (const bucket of wranglerConfig.r2_buckets) {
if (!this.config.useRemoteBindings) {
resources.r2Buckets.push({ name: bucket.bucket_name, binding: bucket.binding, accessible: false });
} else {
try {
await this.ensureR2Bucket(bucket.bucket_name, bucket.binding);
resources.r2Buckets.push({ name: bucket.bucket_name, binding: bucket.binding, accessible: true });
} catch (error) {
this.handleResourceError('R2 bucket', bucket.bucket_name, error, 'R2 Bucket not accessible (likely requires paid plan)');
resources.r2Buckets.push({ name: bucket.bucket_name, binding: bucket.binding, accessible: false });
}
}
}
}
private async processDispatchNamespaces(wranglerConfig: any, resources: ResourceInfo): Promise<void> {
if (!wranglerConfig.dispatch_namespaces) return;
for (const dispatch of wranglerConfig.dispatch_namespaces) {
if (!this.config.useRemoteBindings) {
resources.dispatchNamespaces.push({ name: dispatch.namespace, binding: dispatch.binding, accessible: false });
} else {
try {
await this.ensureDispatchNamespace(dispatch.namespace, dispatch.binding);
resources.dispatchNamespaces.push({ name: dispatch.namespace, binding: dispatch.binding, accessible: true });
} catch (error) {
this.handleResourceError('dispatch namespace', dispatch.namespace, error, 'Dispatch Namespace not accessible (requires Workers for Platforms)');
resources.dispatchNamespaces.push({ name: dispatch.namespace, binding: dispatch.binding, accessible: false });
}
}
}
}
private async processCustomDomain(resources: ResourceInfo): Promise<void> {
// Check production domain first (priority for zone detection)
const domainToCheck = this.config.setupRemote && this.config.prodDomain
? this.config.prodDomain
: (this.config.customDomain !== 'localhost:5173' ? this.config.customDomain : null);
if (domainToCheck) {
try {
const zoneInfo = await this.detectZoneForDomain(domainToCheck);
if (zoneInfo.zoneId) {
resources.zones.push({ name: zoneInfo.zoneName!, id: zoneInfo.zoneId });
}
} catch (error) {
console.warn(`⚠️ Domain validation failed for ${domainToCheck}: ${error instanceof Error ? error.message : String(error)}`);
}
}
}
private createLocalResource(binding: string, id: string, name?: string) {
const resourceName = name || `${binding}-local`;
console.log(`📝 ${binding} - using local-only mode (user preference)`);
return { name: resourceName, id, binding, accessible: false };
}
private handleResourceError(resourceType: string, resourceName: string, error: unknown, specificMessage?: string): void {
const errorMsg = `Failed to setup ${resourceType} ${resourceName}: ${error instanceof Error ? error.message : String(error)}`;
console.warn(`⚠️ ${errorMsg} - will use local-only mode`);
if (specificMessage && error instanceof Error && error.message.includes('Unauthorized')) {
console.warn(`💡 ${specificMessage}`);
console.warn(' Will continue with local-only for development');
}
}
private async ensureKVNamespace(binding: string): Promise<{ id: string; title: string }> {
const namespaceName = `vibesdk-${binding.toLowerCase()}-local`;
try {
// Check if namespace exists using direct API call
const response = await fetch(
`https://api.cloudflare.com/client/v4/accounts/${this.config.accountId}/storage/kv/namespaces`,
{
headers: {
'Authorization': `Bearer ${this.config.apiToken}`,
'Content-Type': 'application/json',
},
}
);
if (response.ok) {
const data = await response.json();
if (data.success && data.result) {
const existingNamespace = data.result.find((ns: any) => ns.title === namespaceName);
if (existingNamespace) {
console.log(`✅ KV namespace '${namespaceName}' already exists`);
return { id: existingNamespace.id, title: existingNamespace.title };
}
}
}
// Create new namespace
console.log(`📦 Creating KV namespace: ${namespaceName}`);
const createResponse = await fetch(
`https://api.cloudflare.com/client/v4/accounts/${this.config.accountId}/storage/kv/namespaces`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${this.config.apiToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ title: namespaceName }),
}
);
if (createResponse.ok) {
const data = await createResponse.json();
if (data.success && data.result) {
console.log(`✅ Created KV namespace: ${namespaceName}`);
return { id: data.result.id, title: data.result.title };
}
}
throw new Error(`Failed to create KV namespace: ${createResponse.statusText}`);
} catch (error) {
throw new Error(`Failed to ensure KV namespace ${namespaceName}: ${error instanceof Error ? error.message : String(error)}`);
}
}
private async ensureD1Database(dbName: string, binding: string): Promise<{ uuid: string; name: string }> {
const baseUrl = `https://api.cloudflare.com/client/v4/accounts/${this.config.accountId}/d1/database`;
const headers = {
'Authorization': `Bearer ${this.config.apiToken}`,
'Content-Type': 'application/json',
};
const listResponse = await fetch(baseUrl, { headers });
if (listResponse.ok) {
const data = await listResponse.json();
const existingDb = data.result?.find((db: any) => db.name === dbName);
if (existingDb) {
console.log(`✅ D1 database '${dbName}' already exists`);
return { uuid: existingDb.uuid, name: existingDb.name };
}
}
console.log(`📦 Creating D1 database: ${dbName}`);
const createResponse = await fetch(baseUrl, {
method: 'POST',
headers,
body: JSON.stringify({ name: dbName }),
});
const data = await createResponse.json();
if (!createResponse.ok || !data.success) {
const errorDetails = data.errors?.map((e: any) => e.message).join(', ') || createResponse.statusText;
throw new Error(`HTTP ${createResponse.status}: ${errorDetails}`);
}
console.log(`✅ Created D1 database: ${dbName}`);
return { uuid: data.result.uuid, name: data.result.name };
}
private async ensureDispatchNamespace(namespaceName: string, binding: string): Promise<void> {
try {
console.log(`🔍 Checking dispatch namespace: ${namespaceName}`);
// Use wrangler CLI to check if namespace exists
try {
execSync(`wrangler dispatch-namespace get ${namespaceName}`, {
stdio: 'pipe',
env: {
...process.env,
CLOUDFLARE_API_TOKEN: this.config.apiToken,
CLOUDFLARE_ACCOUNT_ID: this.config.accountId,
},
});
console.log(`✅ Dispatch namespace '${namespaceName}' already exists`);
return;
} catch (error) {
// If namespace doesn't exist, create it
console.log(`📦 Creating dispatch namespace: ${namespaceName}`);
execSync(`wrangler dispatch-namespace create ${namespaceName}`, {
stdio: 'pipe',
env: {
...process.env,
CLOUDFLARE_API_TOKEN: this.config.apiToken,
CLOUDFLARE_ACCOUNT_ID: this.config.accountId,
},
});
console.log(`✅ Created dispatch namespace: ${namespaceName}`);
}
} catch (error) {
// Handle wrangler CLI errors gracefully
const stderr = error instanceof Error && 'stderr' in error ? (error as any).stderr?.toString() : '';
if (stderr.includes('You do not have access to dispatch namespaces') ||
stderr.includes('not available')) {
throw new Error('Dispatch namespaces not available on this account plan');
}
throw new Error(`Wrangler CLI error: ${error instanceof Error ? error.message : String(error)}`);
}
}
private async ensureR2Bucket(bucketName: string, binding: string): Promise<void> {
const headers = {
'Authorization': `Bearer ${this.config.apiToken}`,
'Content-Type': 'application/json',
};
const checkResponse = await fetch(
`https://api.cloudflare.com/client/v4/accounts/${this.config.accountId}/r2/buckets/${bucketName}`,
{ headers }
);
if (checkResponse.ok) {
console.log(`✅ R2 bucket '${bucketName}' already exists`);
return;
}
if (checkResponse.status !== 404) {
const errorData = await checkResponse.json().catch(() => ({}));
const errorDetails = errorData.errors?.map((e: any) => e.message).join(', ') || checkResponse.statusText;
throw new Error(`HTTP ${checkResponse.status}: ${errorDetails}`);
}
console.log(`📦 Creating R2 bucket: ${bucketName}`);
const createResponse = await fetch(
`https://api.cloudflare.com/client/v4/accounts/${this.config.accountId}/r2/buckets`,
{
method: 'POST',
headers,
body: JSON.stringify({ name: bucketName }),
}
);
const data = await createResponse.json();
if (!createResponse.ok || !data.success) {
const errorDetails = data.errors?.map((e: any) => e.message).join(', ') || createResponse.statusText;
throw new Error(`HTTP ${createResponse.status}: ${errorDetails}`);
}
console.log(`✅ Created R2 bucket: ${bucketName}`);
}
private async ensureAIGateway(resources: ResourceInfo): Promise<void> {
const gatewayName = this.config.useAIGateway ? 'vibesdk-gateway' : null;
if (!gatewayName) {
console.log('ℹ️ AI Gateway setup skipped (not configured)');
return;
}
console.log(`🔍 Checking AI Gateway: ${gatewayName}`);
let tokenCreated = false;
let tokenError: string | undefined;
let aiGatewayToken: string | null = null;
try {
// Check API token permissions first
console.log('🔍 Checking API token permissions...');
const permissionCheck = await this.checkTokenPermissions();
// Check if token already exists in config
const existingToken = this.config.devVars.CLOUDFLARE_AI_GATEWAY_TOKEN;
const hasExistingToken = existingToken && existingToken !== 'optional-your-cf-ai-gateway-token';
if (hasExistingToken) {
// Use existing configured token
aiGatewayToken = existingToken;
console.log('✅ Using existing AI Gateway token from configuration');
} else if (permissionCheck.hasAIGatewayAccess) {
// Main token has permissions, use it directly - no need to create a specialized token
aiGatewayToken = this.config.apiToken;
this.config.devVars.CLOUDFLARE_AI_GATEWAY_TOKEN = this.config.apiToken;
console.log('✅ Main API token has AI Gateway permissions, using it directly');
} else {
// Main token doesn't have permissions, try to create a specialized token
console.log('🔐 Main token lacks AI Gateway permissions, creating specialized token...');
try {
aiGatewayToken = await this.ensureAIGatewayToken();
tokenCreated = !!aiGatewayToken;
if (aiGatewayToken) {
this.config.devVars.CLOUDFLARE_AI_GATEWAY_TOKEN = aiGatewayToken;
console.log('✅ Created and using specialized AI Gateway token');
} else {
// Specialized token creation failed, fallback to main token with warning
console.warn('⚠️ WARNING: Specialized token creation failed');
console.warn(' Falling back to main API token, but it may not have AI Gateway permissions!');
console.warn(' You may experience 401 errors when using AI Gateway.');
console.warn(' Please verify your token has: AI Gateway Read, Edit, and Run permissions.');
this.config.devVars.CLOUDFLARE_AI_GATEWAY_TOKEN = this.config.apiToken;
aiGatewayToken = this.config.apiToken;
}
} catch (tokenErr) {
tokenError = tokenErr instanceof Error ? tokenErr.message : String(tokenErr);
console.warn(`⚠️ Token creation failed: ${tokenError}`);
console.warn(' Falling back to main API token');
this.config.devVars.CLOUDFLARE_AI_GATEWAY_TOKEN = this.config.apiToken;
aiGatewayToken = this.config.apiToken;
}
}
// Check if gateway exists first
const aiGatewaySDK = this.getAIGatewaySDK();
try {
await aiGatewaySDK.aiGateway.get(gatewayName, {
account_id: this.config.accountId,
});
console.log(`✅ AI Gateway '${gatewayName}' already exists`);
resources.aiGateway = { name: gatewayName, exists: true, tokenCreated, tokenError };
return;
} catch (error: any) {
if (error?.status !== 404 && !error?.message?.includes('not found')) {
console.warn(`⚠️ Could not check AI Gateway '${gatewayName}': ${error.message}`);
resources.aiGateway = { name: gatewayName, exists: false, tokenCreated, tokenError: error.message };
return;
}
}
// Validate gateway name length
if (gatewayName.length > 64) {
const lengthError = `Gateway name too long (${gatewayName.length} > 64 chars)`;
console.warn(`⚠️ ${lengthError}, skipping creation`);
resources.aiGateway = { name: gatewayName, exists: false, tokenCreated, tokenError: lengthError };
return;
}
// Create AI Gateway
console.log(`📦 Creating AI Gateway: ${gatewayName}`);
await aiGatewaySDK.aiGateway.create({
account_id: this.config.accountId,
id: gatewayName,
cache_invalidate_on_update: true,
cache_ttl: 3600,
collect_logs: true,
rate_limiting_interval: 0,
rate_limiting_limit: 0,
rate_limiting_technique: 'sliding',
authentication: !!aiGatewayToken,
});
console.log(`✅ Successfully created AI Gateway: ${gatewayName} (authentication: ${aiGatewayToken ? 'enabled' : 'disabled'})`);
resources.aiGateway = { name: gatewayName, exists: true, tokenCreated, tokenError };
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
console.warn(`⚠️ Could not create AI Gateway '${gatewayName}': ${errorMessage}`);
console.warn(' Continuing setup without AI Gateway...');
resources.aiGateway = { name: gatewayName, exists: false, tokenCreated, tokenError: errorMessage };
}
}
private async checkTokenPermissions(): Promise<{ hasAIGatewayAccess: boolean; tokenInfo?: any }> {
try {
// Step 1: Verify the token is valid and active
const verifyResponse = await fetch('https://api.cloudflare.com/client/v4/user/tokens/verify', {
headers: { Authorization: `Bearer ${this.config.apiToken}` },
});
if (!verifyResponse.ok) {
console.warn('⚠️ Could not verify API token');
return { hasAIGatewayAccess: false };
}
const verifyData = await verifyResponse.json();
const tokenStatus = verifyData.result?.status;
if (tokenStatus !== 'active') {
console.warn('⚠️ API token is not active');
return { hasAIGatewayAccess: false };
}
console.log('✅ API token is active and valid');
// Step 2: Check what AI Gateway permission groups exist (doesn't require special permissions)
try {
const permGroupsResponse = await fetch('https://api.cloudflare.com/client/v4/user/tokens/permission_groups?name=AI%20Gateway', {
headers: { Authorization: `Bearer ${this.config.apiToken}` },
});
if (permGroupsResponse.ok) {
const permData = await permGroupsResponse.json();
const aiGatewayPerms = permData.result || [];
if (aiGatewayPerms.length > 0) {
console.log(`ℹ️ Found ${aiGatewayPerms.length} AI Gateway permission group(s):`);
aiGatewayPerms.forEach((perm: any) => {
console.log(` • ${perm.name} (${perm.id})`);
});
}
}
} catch (e) {
// Non-critical - just for informational purposes
}
// Step 3: Test AI Gateway Read permission by listing gateways
// Note: We can only test Read permission without side effects
// Edit permission will be tested at runtime when actually creating the gateway
const testResponse = await fetch(`https://api.cloudflare.com/client/v4/accounts/${this.config.accountId}/ai-gateway/gateways`, {
headers: { Authorization: `Bearer ${this.config.apiToken}` },
});
if (testResponse.ok) {
console.log('✅ Token has AI Gateway Read permission');
console.log(' Note: Edit permission will be verified when creating gateway');
return { hasAIGatewayAccess: true, tokenInfo: verifyData.result };
}