forked from cloudflare/vibesdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeploy.ts
More file actions
2128 lines (1843 loc) · 65.4 KB
/
deploy.ts
File metadata and controls
2128 lines (1843 loc) · 65.4 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
/**
* Cloudflare Orange Build - Automated Deployment Script
*
* This script handles the complete setup and deployment process for the
* Cloudflare Orange Build platform, including:
* - Workers for Platforms dispatch namespace creation
* - Templates repository deployment to R2
* - Container configuration updates
* - Environment validation
*
* Used by the "Deploy to Cloudflare" button for one-click deployment.
*/
import { execSync } from 'child_process';
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { parse, modify, applyEdits } from 'jsonc-parser';
import Cloudflare from 'cloudflare';
// Get current directory for ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const PROJECT_ROOT = join(__dirname, '..');
// Types for configuration
interface WranglerConfig {
name: string;
dispatch_namespaces?: Array<{
binding: string;
namespace: string;
experimental_remote?: boolean;
}>;
r2_buckets?: Array<{
binding: string;
bucket_name: string;
experimental_remote?: boolean;
}>;
containers?: Array<{
class_name: string;
image: string;
max_instances: number;
instance_type?: {
vcpu: number;
memory_mib: number;
disk_mb?: number;
} | string;
rollout_step_percentage?: number;
}>;
d1_databases?: Array<{
binding: string;
database_name: string;
database_id: string;
migrations_dir?: string;
experimental_remote?: boolean;
}>;
routes?: Array<{
pattern: string;
custom_domain: boolean;
zone_id?: string;
}>;
vars?: {
TEMPLATES_REPOSITORY?: string;
CLOUDFLARE_AI_GATEWAY?: string;
MAX_SANDBOX_INSTANCES?: string;
CUSTOM_DOMAIN?: string;
CUSTOM_PREVIEW_DOMAIN?: string;
SANDBOX_INSTANCE_TYPE?: string;
DISPATCH_NAMESPACE?: string;
[key: string]: string | undefined;
};
}
interface EnvironmentConfig {
CLOUDFLARE_API_TOKEN: string;
CLOUDFLARE_ACCOUNT_ID: string;
TEMPLATES_REPOSITORY: string;
CLOUDFLARE_AI_GATEWAY?: string;
CLOUDFLARE_AI_GATEWAY_TOKEN?: string;
}
class DeploymentError extends Error {
constructor(
message: string,
public cause?: Error,
) {
super(message);
this.name = 'DeploymentError';
}
}
class CloudflareDeploymentManager {
private config: WranglerConfig;
private env: EnvironmentConfig;
private cloudflare: Cloudflare;
private aiGatewayCloudflare?: Cloudflare; // Separate SDK instance for AI Gateway operations
private conflictingVarsForCleanup: Record<string, string> | null = null; // For signal cleanup
constructor() {
this.validateEnvironment();
this.config = this.parseWranglerConfig();
this.extractConfigurationValues();
this.env = this.getEnvironmentVariables();
this.cloudflare = new Cloudflare({
apiToken: this.env.CLOUDFLARE_API_TOKEN,
});
// Set up signal handling for graceful cleanup
this.setupSignalHandlers();
}
/**
* Sets up signal handlers for graceful cleanup on Ctrl+C or termination
* Reuses existing restoreOriginalVars method following DRY principles
*/
private setupSignalHandlers(): void {
const gracefulExit = async (signal: string) => {
console.log(`\n🛑 Received ${signal}, performing cleanup...`);
try {
// Restore conflicting vars using existing restoration method
if (this.conflictingVarsForCleanup) {
console.log('🔄 Restoring original wrangler.jsonc configuration...');
await this.restoreOriginalVars(this.conflictingVarsForCleanup);
} else {
console.log('ℹ️ No configuration changes to restore');
}
} catch (error) {
console.error(`❌ Error during cleanup: ${error instanceof Error ? error.message : String(error)}`);
}
console.log('👋 Cleanup completed. Exiting...');
process.exit(1);
};
// Handle Ctrl+C (SIGINT)
process.on('SIGINT', () => gracefulExit('SIGINT'));
// Handle termination (SIGTERM)
process.on('SIGTERM', () => gracefulExit('SIGTERM'));
console.log('✅ Signal handlers registered for graceful cleanup');
}
/**
* Validates that all required build variables are present
*/
private validateEnvironment(): void {
const requiredBuildVars = ['CLOUDFLARE_API_TOKEN'];
const missingVars = requiredBuildVars.filter(
(varName) => !process.env[varName],
);
if (missingVars.length > 0) {
throw new DeploymentError(
`Missing required build variables: ${missingVars.join(', ')}\n` +
`Please ensure all required build variables are configured in your deployment.`,
);
}
console.log('✅ Build variables validation passed');
}
/**
* Extracts and validates key configuration values from wrangler.jsonc
*/
private extractConfigurationValues(): void {
console.log(
'📋 Extracting configuration values from wrangler.jsonc...',
);
// Log key extracted values
const databaseName = this.config.d1_databases?.[0]?.database_name;
const customDomain = this.config.vars?.CUSTOM_DOMAIN;
const customPreviewDomain = this.config.vars?.CUSTOM_PREVIEW_DOMAIN;
const maxInstances = this.config.vars?.MAX_SANDBOX_INSTANCES;
const templatesRepo = this.config.vars?.TEMPLATES_REPOSITORY;
const aiGateway = this.config.vars?.CLOUDFLARE_AI_GATEWAY;
const dispatchNamespace = this.config.vars?.DISPATCH_NAMESPACE;
console.log('📊 Configuration Summary:');
console.log(` Database Name: ${databaseName || 'Not configured'}`);
console.log(` Custom Domain: ${customDomain || 'Not configured'}`);
console.log(` Custom Preview Domain: ${customPreviewDomain || 'Not configured'}`);
console.log(
` Max Sandbox Instances: ${maxInstances || 'Not configured'}`,
);
console.log(
` Templates Repository: ${templatesRepo || 'Not configured'}`,
);
console.log(` AI Gateway: ${aiGateway || 'Not configured'}`);
console.log(` Dispatch Namespace: ${dispatchNamespace || 'Not configured'}`);
// Validate critical configuration
if (!databaseName) {
console.warn(
'⚠️ No D1 database configured - database operations may fail',
);
}
if (!customDomain) {
console.warn(
'⚠️ No custom domain configured - using default routes',
);
}
console.log('✅ Configuration extraction completed');
}
/**
* Safely parses wrangler.jsonc file, handling comments and JSON-like syntax
*/
private parseWranglerConfig(): WranglerConfig {
const wranglerPath = this.getWranglerPath();
if (!existsSync(wranglerPath)) {
throw new DeploymentError(
'wrangler.jsonc not found',
new Error('Please ensure wrangler.jsonc exists in the project root'),
);
}
try {
const { config } = this.readWranglerConfig();
this.logSuccess(`Parsed wrangler.jsonc - Project: ${config.name}`);
return config;
} catch (error) {
throw new DeploymentError(
'Failed to parse wrangler.jsonc',
error instanceof Error ? error : new Error(`Please check your wrangler.jsonc syntax: ${String(error)}`),
);
}
}
/**
* Gets and validates environment variables, with defaults from wrangler.jsonc
*/
private getEnvironmentVariables(): EnvironmentConfig {
const apiToken = process.env.CLOUDFLARE_API_TOKEN!;
const aiGatewayToken = process.env.CLOUDFLARE_AI_GATEWAY_TOKEN || apiToken;
return {
CLOUDFLARE_API_TOKEN: apiToken,
CLOUDFLARE_ACCOUNT_ID:
process.env.CLOUDFLARE_ACCOUNT_ID ||
this.config.vars?.CLOUDFLARE_ACCOUNT_ID!,
TEMPLATES_REPOSITORY:
process.env.TEMPLATES_REPOSITORY ||
this.config.vars?.TEMPLATES_REPOSITORY!,
CLOUDFLARE_AI_GATEWAY:
process.env.CLOUDFLARE_AI_GATEWAY ||
this.config.vars?.CLOUDFLARE_AI_GATEWAY || "orange-build-gateway",
CLOUDFLARE_AI_GATEWAY_TOKEN: aiGatewayToken,
};
}
/**
* Creates or ensures Workers for Platforms dispatch namespace exists
*/
private async ensureDispatchNamespace(): Promise<void> {
const dispatchConfig = this.config.dispatch_namespaces?.[0];
if (!dispatchConfig) {
console.log('ℹ️ No dispatch namespace configuration found, skipping setup');
return;
}
const namespaceName = dispatchConfig.namespace;
console.log(`🔍 Checking dispatch namespace: ${namespaceName}`);
try {
// Check if namespace exists using Cloudflare SDK
try {
await this.cloudflare.workersForPlatforms.dispatch.namespaces.get(
namespaceName,
{ account_id: this.env.CLOUDFLARE_ACCOUNT_ID },
);
console.log(
`✅ Dispatch namespace '${namespaceName}' already exists`,
);
return;
} catch (error: any) {
// Check if error indicates dispatch namespaces are not available
const errorMessage = error?.message || '';
if (errorMessage.includes('You do not have access to dispatch namespaces') ||
errorMessage.includes('code: 10121')) {
console.log('⚠️ Dispatch namespaces became unavailable during execution');
console.log(' Workers for Platforms access may have changed');
return;
}
// If error is not 404, re-throw it
if (
error?.status !== 404 &&
error?.message?.indexOf('not found') === -1
) {
throw error;
}
// Namespace doesn't exist, continue to create it
}
console.log(`📦 Creating dispatch namespace: ${namespaceName}`);
await this.cloudflare.workersForPlatforms.dispatch.namespaces.create(
{
account_id: this.env.CLOUDFLARE_ACCOUNT_ID,
name: namespaceName,
},
);
console.log(
`✅ Successfully created dispatch namespace: ${namespaceName}`,
);
} catch (error) {
// Check if the error is related to dispatch namespace access
const errorMessage = error instanceof Error ? error.message : String(error);
if (errorMessage.includes('You do not have access to dispatch namespaces') ||
errorMessage.includes('code: 10121')) {
console.warn('⚠️ Dispatch namespaces are not available for this account');
console.warn(' Skipping dispatch namespace setup and continuing deployment');
return;
}
throw new DeploymentError(
`Failed to ensure dispatch namespace: ${namespaceName}`,
error instanceof Error ? error : new Error(String(error)),
);
}
}
/**
* Creates or ensures AI Gateway exists (non-blocking)
*/
private async ensureAIGateway(): Promise<void> {
if (!this.env.CLOUDFLARE_AI_GATEWAY) {
console.log(
'ℹ️ AI Gateway setup skipped (CLOUDFLARE_AI_GATEWAY not provided)',
);
return;
}
const gatewayName = this.env.CLOUDFLARE_AI_GATEWAY;
console.log(`🔍 Checking AI Gateway: ${gatewayName}`);
try {
// Step 1: Check main token permissions and create AI Gateway token if needed
console.log('🔍 Checking API token permissions...');
const tokenCheck = await this.checkTokenPermissions();
const aiGatewayToken = await this.ensureAIGatewayToken();
// Step 2: Check if gateway exists first using appropriate SDK
const aiGatewaySDK = this.getAIGatewaySDK();
try {
await aiGatewaySDK.aiGateway.get(gatewayName, {
account_id: this.env.CLOUDFLARE_ACCOUNT_ID,
});
console.log(`✅ AI Gateway '${gatewayName}' already exists`);
return;
} catch (error: any) {
// If error is not 404, log but continue
if (
error?.status !== 404 &&
!error?.message?.includes('not found')
) {
console.warn(
`⚠️ Could not check AI Gateway '${gatewayName}': ${error.message}`,
);
return;
}
// Gateway doesn't exist, continue to create it
}
// Validate gateway name length (64 character limit)
if (gatewayName.length > 64) {
console.warn(
`⚠️ AI Gateway name too long (${gatewayName.length} > 64 chars), skipping creation`,
);
return;
}
// Step 3: Create AI Gateway with authentication based on token availability
console.log(`📦 Creating AI Gateway: ${gatewayName}`);
await aiGatewaySDK.aiGateway.create({
account_id: this.env.CLOUDFLARE_ACCOUNT_ID,
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, // Enable authentication only if we have a token
});
console.log(
`✅ Successfully created AI Gateway: ${gatewayName} (authentication: ${aiGatewayToken ? 'enabled' : 'disabled'})`,
);
} catch (error) {
// Non-blocking: Log warning but continue deployment
console.warn(
`⚠️ Could not create AI Gateway '${gatewayName}': ${error instanceof Error ? error.message : String(error)}`,
);
console.warn(
' Continuing deployment without AI Gateway setup...',
);
}
}
/**
* Verifies if the current API token has AI Gateway permissions
*/
private async checkTokenPermissions(): Promise<{
hasAIGatewayAccess: boolean;
tokenInfo?: any;
}> {
try {
const verifyResponse = await fetch(
'https://api.cloudflare.com/client/v4/user/tokens/verify',
{
headers: {
Authorization: `Bearer ${this.env.CLOUDFLARE_API_TOKEN}`,
},
},
);
if (!verifyResponse.ok) {
console.warn('⚠️ Could not verify API token permissions');
return { hasAIGatewayAccess: false };
}
const verifyData = await verifyResponse.json();
if (!verifyData.success) {
console.warn('⚠️ API token verification failed');
return { hasAIGatewayAccess: false };
}
// For now, assume we need to create a separate token for AI Gateway operations
// This is a conservative approach since permission checking is complex
console.log(
'ℹ️ Main API token verified, but will create dedicated AI Gateway token',
);
return { hasAIGatewayAccess: false, tokenInfo: verifyData.result };
} catch (error) {
console.warn(
`⚠️ Token verification failed: ${error instanceof Error ? error.message : String(error)}`,
);
return { hasAIGatewayAccess: false };
}
}
/**
* Creates AI Gateway authentication token if needed (non-blocking)
* Returns the token if created/available, null otherwise
*/
private async ensureAIGatewayToken(): Promise<string | null> {
const currentToken = this.env.CLOUDFLARE_AI_GATEWAY_TOKEN;
// Check if token is already set and not the default placeholder
if (
currentToken &&
currentToken !== 'optional-your-cf-ai-gateway-token'
) {
console.log('✅ AI Gateway token already configured');
// Initialize separate AI Gateway SDK instance
this.aiGatewayCloudflare = new Cloudflare({
apiToken: currentToken,
});
return currentToken;
}
try {
console.log(`🔐 Creating AI Gateway authentication token...`);
// Create API token with required permissions for AI Gateway including RUN
const tokenResponse = await fetch(
`https://api.cloudflare.com/client/v4/user/tokens`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${this.env.CLOUDFLARE_API_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: `AI Gateway Token - ${new Date().toISOString().split('T')[0]}`,
policies: [
{
effect: 'allow',
resources: {
[`com.cloudflare.api.account.${this.env.CLOUDFLARE_ACCOUNT_ID}`]:
'*',
},
permission_groups: [
// Note: Using descriptive names, actual IDs would need to be fetched from the API
{ name: 'AI Gateway Read' },
{ name: 'AI Gateway Edit' },
{ name: 'AI Gateway Run' }, // This is the key permission for authentication
{ name: 'Workers AI Read' },
{ name: 'Workers AI Edit' },
],
},
],
condition: {
request_ip: { in: [], not_in: [] },
},
expires_on: new Date(
Date.now() + 365 * 24 * 60 * 60 * 1000,
).toISOString(), // 1 year
}),
},
);
if (!tokenResponse.ok) {
const errorData = await tokenResponse
.json()
.catch(() => ({ errors: [{ message: 'Unknown error' }] }));
throw new Error(
`API token creation failed: ${errorData.errors?.[0]?.message || tokenResponse.statusText}`,
);
}
const tokenData = await tokenResponse.json();
if (tokenData.success && tokenData.result?.value) {
const newToken = tokenData.result.value;
console.log(
'✅ AI Gateway authentication token created successfully',
);
console.log(` Token ID: ${tokenData.result.id}`);
console.warn(
'⚠️ Store this token securely and set CLOUDFLARE_AI_GATEWAY_TOKEN for future deployments.',
);
if (!process.env.CI) {
console.warn(` ${newToken}`);
} else {
console.warn(' (Token value suppressed because CI=true)');
}
// Initialize separate AI Gateway SDK instance
this.aiGatewayCloudflare = new Cloudflare({
apiToken: newToken,
});
return newToken;
} else {
throw new Error(
'Token creation succeeded but no token value returned',
);
}
} catch (error) {
// Non-blocking: Log warning but continue
console.warn(
`⚠️ Could not create AI Gateway token: ${error instanceof Error ? error.message : String(error)}`,
);
console.warn(
' AI Gateway will be created without authentication...',
);
return null;
}
}
/**
* Gets the appropriate Cloudflare SDK instance for AI Gateway operations
*/
private getAIGatewaySDK(): Cloudflare {
return this.aiGatewayCloudflare || this.cloudflare;
}
/**
* Clones templates repository and deploys templates to R2
*/
private async deployTemplates(): Promise<void> {
const templatesDir = join(PROJECT_ROOT, 'templates');
const templatesRepo = this.env.TEMPLATES_REPOSITORY;
console.log(`📥 Setting up templates from: ${templatesRepo}`);
try {
// Create templates directory if it doesn't exist
if (!existsSync(templatesDir)) {
mkdirSync(templatesDir, { recursive: true });
}
// Clone repository if not already present
if (!existsSync(join(templatesDir, '.git'))) {
console.log(`🔄 Cloning templates repository...`);
execSync(`git clone "${templatesRepo}" "${templatesDir}"`, {
stdio: 'pipe',
cwd: PROJECT_ROOT,
});
console.log('✅ Templates repository cloned successfully');
} else {
console.log(
'📁 Templates repository already exists, pulling latest changes...',
);
try {
execSync('git pull origin main || git pull origin master', {
stdio: 'pipe',
cwd: templatesDir,
});
console.log('✅ Templates repository updated');
} catch (pullError) {
console.warn(
'⚠️ Could not pull latest changes, continuing with existing templates',
);
}
}
// Find R2 bucket name from config
const templatesBucket = this.config.r2_buckets?.find(
(bucket) => bucket.binding === 'TEMPLATES_BUCKET',
);
if (!templatesBucket) {
throw new Error(
'TEMPLATES_BUCKET not found in wrangler.jsonc r2_buckets configuration',
);
}
// Check if deploy script exists
const deployScript = join(templatesDir, 'deploy_templates.sh');
if (!existsSync(deployScript)) {
console.warn(
'⚠️ deploy_templates.sh not found in templates repository, skipping template deployment',
);
return;
}
// Make script executable
execSync(`chmod +x "${deployScript}"`, { cwd: templatesDir });
// Run deployment script with environment variables
console.log(
`🚀 Deploying templates to R2 bucket: ${templatesBucket.bucket_name}`,
);
const inheritedKeys = [
'PATH',
'HOME',
'USER',
'SHELL',
'TMPDIR',
'TMP',
'TEMP',
'LANG',
'LC_ALL',
'CI',
'GITHUB_WORKSPACE',
];
const inheritedEnv: NodeJS.ProcessEnv = {};
inheritedKeys.forEach((key) => {
const value = process.env[key];
if (value !== undefined) {
inheritedEnv[key] = value;
}
});
const deployEnv: NodeJS.ProcessEnv = {
...inheritedEnv,
CLOUDFLARE_API_TOKEN: this.env.CLOUDFLARE_API_TOKEN,
CLOUDFLARE_ACCOUNT_ID: this.env.CLOUDFLARE_ACCOUNT_ID,
BUCKET_NAME: templatesBucket.bucket_name,
R2_BUCKET_NAME: templatesBucket.bucket_name,
};
execSync('./deploy_templates.sh', {
stdio: 'inherit',
cwd: templatesDir,
env: deployEnv,
});
console.log('✅ Templates deployed successfully to R2');
} catch (error) {
// Don't fail the entire deployment if templates fail
console.warn(
'⚠️ Templates deployment failed, but continuing with main deployment:',
);
console.warn(
` ${error instanceof Error ? error.message : String(error)}`,
);
}
}
/**
* Cleans ARM64 platform flags from SandboxDockerfile for production deployment
* Returns the original content if ARM64 flags were removed (for restoration)
*/
private cleanDockerfileForDeployment(): string | null {
const dockerfilePath = join(PROJECT_ROOT, 'SandboxDockerfile');
if (!existsSync(dockerfilePath)) {
console.log(' ℹ️ SandboxDockerfile not found - skipping ARM64 cleanup');
return null;
}
try {
const originalContent = readFileSync(dockerfilePath, 'utf-8');
let modified = false;
// Split content into lines for processing
const lines = originalContent.split('\n');
const cleanedLines = lines.map(line => {
// Look for FROM statements with --platform=linux/arm64 and remove the flag
const fromMatch = line.match(/^(\s*FROM\s+)--platform=linux\/arm64\s+(.*)/);
if (fromMatch) {
modified = true;
const [, prefix, image] = fromMatch;
return `${prefix}${image}`;
}
return line;
});
if (modified) {
writeFileSync(dockerfilePath, cleanedLines.join('\n'), 'utf-8');
console.log(' ✅ Removed ARM64 platform flags from SandboxDockerfile');
return originalContent; // Return original for restoration
} else {
console.log(' ✅ No ARM64 platform flags found in SandboxDockerfile');
return null; // Nothing to restore
}
} catch (error) {
console.warn(
` ⚠️ Could not clean SandboxDockerfile: ${error instanceof Error ? error.message : String(error)}`,
);
console.warn(' → Continuing deployment, but may encounter platform compatibility issues');
return null;
}
}
/**
* Restores ARM64 platform flags to SandboxDockerfile if they were previously removed
*/
private restoreDockerfileARM64Flags(originalContent: string): void {
const dockerfilePath = join(PROJECT_ROOT, 'SandboxDockerfile');
try {
writeFileSync(dockerfilePath, originalContent, 'utf-8');
console.log('🔄 Restored ARM64 platform flags to SandboxDockerfile for local development');
} catch (error) {
console.warn(
`⚠️ Could not restore ARM64 flags to SandboxDockerfile: ${error instanceof Error ? error.message : String(error)}`,
);
console.warn(' You may need to manually re-run the setup script to restore ARM64 flags');
}
}
/**
* Updates package.json database commands with the actual database name from wrangler.jsonc
*/
private updatePackageJsonDatabaseCommands(): void {
const databaseName = this.config.d1_databases?.[0]?.database_name;
if (!databaseName) {
console.log(
'ℹ️ No D1 database found in wrangler.jsonc, skipping package.json database command update',
);
return;
}
console.log(
`🔧 Updating package.json database commands with database: ${databaseName}`,
);
try {
const packageJsonPath = join(PROJECT_ROOT, 'package.json');
const content = readFileSync(packageJsonPath, 'utf-8');
// Parse the package.json file
const packageJson = JSON.parse(content);
if (!packageJson.scripts) {
console.warn('⚠️ No scripts section found in package.json');
return;
}
// Update database migration commands
const commandsToUpdate = ['db:migrate:local', 'db:migrate:remote'];
let updated = false;
commandsToUpdate.forEach((command) => {
if (packageJson.scripts[command]) {
const oldCommand = packageJson.scripts[command];
// Replace any existing database name in the wrangler d1 migrations apply command
const newCommand = oldCommand.replace(
/wrangler d1 migrations apply [^\s]+ /,
`wrangler d1 migrations apply ${databaseName} `,
);
if (newCommand !== oldCommand) {
packageJson.scripts[command] = newCommand;
console.log(
` ✅ Updated ${command}: ${oldCommand} → ${newCommand}`,
);
updated = true;
}
}
});
if (updated) {
// Write back the updated package.json with proper formatting
writeFileSync(
packageJsonPath,
JSON.stringify(packageJson, null, '\t'),
'utf-8',
);
console.log(
'✅ Updated package.json database commands successfully',
);
} else {
console.log(
'ℹ️ No database commands needed updating in package.json',
);
}
} catch (error) {
console.warn(
`⚠️ Could not update package.json database commands: ${error instanceof Error ? error.message : String(error)}`,
);
// Non-blocking - continue deployment
}
}
/**
* Gets the zone name and ID for a given domain by testing subdomains
*/
private async detectZoneForDomain(customDomain: string, originalDomain: string): Promise<{
zoneName: string | null;
zoneId: string | null;
}> {
console.log(`🔍 Detecting zone for custom domain: ${customDomain}, Original domain was: ${originalDomain}`);
// Extract possible zone names by progressively removing subdomains
const domainParts = customDomain.split('.');
const possibleZones: string[] = [];
// Generate all possible zone names from longest to shortest
// e.g., for 'abc.test.xyz.build.cloudflare.dev' generates:
// ['abc.test.xyz.build.cloudflare.dev', 'test.xyz.build.cloudflare.dev', 'xyz.build.cloudflare.dev', 'build.cloudflare.dev', 'cloudflare.dev']
for (let i = 0; i < domainParts.length - 1; i++) {
const zoneName = domainParts.slice(i).join('.');
possibleZones.push(zoneName);
}
console.log(`🔍 Testing possible zones: ${possibleZones.join(', ')}`);
// Test each possible zone name
for (const zoneName of possibleZones) {
try {
console.log(` Testing zone: ${zoneName}`);
const response = await fetch(
`https://api.cloudflare.com/client/v4/zones?name=${encodeURIComponent(zoneName)}`,
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.env.CLOUDFLARE_API_TOKEN}`,
},
}
);
if (!response.ok) {
console.log(` ❌ API error for zone ${zoneName}: ${response.status} ${response.statusText}`);
continue;
}
const data = await response.json();
if (data.success && data.result && data.result.length > 0) {
const zone = data.result[0];
console.log(` ✅ Found zone: ${zoneName} (ID: ${zone.id})`);
console.log(` Zone status: ${zone.status}`);
console.log(` Account: ${zone.account.name}`);
return {
zoneName: zoneName,
zoneId: zone.id,
};
} else {
console.log(` ❌ No zone found for: ${zoneName}`);
}
} catch (error) {
console.log(` ❌ Error checking zone ${zoneName}: ${error instanceof Error ? error.message : String(error)}`);
}
}
console.error(`❌ No valid zone found for custom domain: ${customDomain}`);
console.error(` Tested zones: ${possibleZones.join(', ')}`);
console.error(` Please ensure:`);
console.error(` 1. The domain is managed by Cloudflare`);
console.error(` 2. Your API token has zone read permissions`);
console.error(` 3. The domain is active and properly configured`);
return { zoneName: null, zoneId: null };
}
/**
* Updates wrangler.jsonc routes and deployment settings based on CUSTOM_DOMAIN
*/
/**
* Standard formatting options for JSONC modifications
*/
private static readonly JSONC_FORMAT_OPTIONS = {
formattingOptions: {
insertSpaces: true,
keepLines: true,
tabSize: 4
}
};
/**
* Gets the path to wrangler.jsonc
*/
private getWranglerPath(): string {
return join(PROJECT_ROOT, 'wrangler.jsonc');
}
/**
* Reads and parses wrangler.jsonc file
*/
private readWranglerConfig(): { content: string; config: WranglerConfig } {
const wranglerPath = this.getWranglerPath();
const content = readFileSync(wranglerPath, 'utf-8');
const config = parse(content) as WranglerConfig;
return { content, config };
}
/**
* Writes content to wrangler.jsonc file
*/
private writeWranglerConfig(content: string): void {
const wranglerPath = this.getWranglerPath();
writeFileSync(wranglerPath, content, 'utf-8');
}
/**
* Standardized success logging
*/
private logSuccess(message: string, details?: string[]): void {
console.log(`✅ ${message}`);
if (details) {
details.forEach(detail => console.log(` ${detail}`));
}
}
/**
* Standardized warning logging
*/
private logWarning(message: string, details?: string[]): void {
console.warn(`⚠️ ${message}`);
if (details) {
details.forEach(detail => console.warn(` ${detail}`));
}
}
/**
* Updates a specific field in wrangler.jsonc configuration
*/
private updateWranglerField<T>(content: string, field: string, value: T): string {
const edits = modify(content, [field], value, CloudflareDeploymentManager.JSONC_FORMAT_OPTIONS);
return applyEdits(content, edits);
}
/**
* Updates wrangler.jsonc for workers.dev deployment (no custom domain)
*/
private updateWranglerForWorkersDev(content: string): string {
let updatedContent = content;
// Remove routes property if it exists
const removeRoutesEdits = modify(content, ['routes'], undefined, CloudflareDeploymentManager.JSONC_FORMAT_OPTIONS);
updatedContent = applyEdits(updatedContent, removeRoutesEdits);
// Set workers_dev = true and preview_urls = true
updatedContent = this.updateWranglerField(updatedContent, 'workers_dev', true);
updatedContent = this.updateWranglerField(updatedContent, 'preview_urls', true);
return updatedContent;
}
/**
* Updates wrangler.jsonc for custom domain deployment
*/
private updateWranglerForCustomDomain(
content: string,
routes: Array<{ pattern: string; custom_domain: boolean; zone_id?: string; zone_name?: string }>,
preserveExistingFlags: boolean = false
): string {
let updatedContent = content;
// Update routes
updatedContent = this.updateWranglerField(updatedContent, 'routes', routes);
// Only update workers_dev and preview_urls if not preserving existing flags
if (!preserveExistingFlags) {
updatedContent = this.updateWranglerField(updatedContent, 'workers_dev', false);
updatedContent = this.updateWranglerField(updatedContent, 'preview_urls', false);
}