From 65495ba1dd4733bb759dd3a0b51ea2e5be7c790f Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 20 Jan 2026 22:50:12 -0600 Subject: [PATCH] Add Railway deployment --- services/favicon.ts | 5 + src/components/AddCustomProviderDialog.tsx | 28 +- src/components/deploy/DeploySteps.tsx | 83 +++- src/components/deploy/RailwayDeployForm.tsx | 382 +++++++++++++++ src/contexts/DeploySettingsContext.ts | 9 +- src/hooks/useProjectDeploySettings.ts | 13 + src/lib/configUtils.ts | 7 + src/lib/deploy/RailwayAdapter.ts | 494 ++++++++++++++++++++ src/lib/deploy/index.ts | 1 + src/lib/deploy/types.ts | 14 +- src/lib/deployProviderPresets.ts | 10 + src/pages/DeploySettings.tsx | 8 + 12 files changed, 1045 insertions(+), 9 deletions(-) create mode 100644 src/components/deploy/RailwayDeployForm.tsx create mode 100644 src/lib/deploy/RailwayAdapter.ts diff --git a/services/favicon.ts b/services/favicon.ts index e76b99f8..73840f25 100644 --- a/services/favicon.ts +++ b/services/favicon.ts @@ -48,6 +48,11 @@ export default { hostname = 'docs.z.ai'; } + // Deployment-provider-specific hacks + if (url.host === 'backboard.railway.com') { + hostname = 'railway.com'; + } + // Fetch the favicon from DuckDuckGo's service return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`); }, diff --git a/src/components/AddCustomProviderDialog.tsx b/src/components/AddCustomProviderDialog.tsx index 1bd97b3c..d55a6314 100644 --- a/src/components/AddCustomProviderDialog.tsx +++ b/src/components/AddCustomProviderDialog.tsx @@ -28,6 +28,7 @@ import type { NsiteProvider, CloudflareProvider, DenoDeployProvider, + RailwayProvider, } from '@/contexts/DeploySettingsContext'; // Type for provider without the 'id' field (will be generated) @@ -37,7 +38,8 @@ type DeployProviderInput = | Omit | Omit | Omit - | Omit; + | Omit + | Omit; interface AddCustomProviderDialogProps { open: boolean; @@ -51,7 +53,7 @@ export function AddCustomProviderDialog({ onAdd, }: AddCustomProviderDialogProps) { const { t } = useTranslation(); - const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | ''>(''); + const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway' | ''>(''); const [customName, setCustomName] = useState(''); const [customApiKey, setCustomApiKey] = useState(''); const [customAccountId, setCustomAccountId] = useState(''); @@ -129,6 +131,15 @@ export function AddCustomProviderDialog({ ...(customBaseDomain?.trim() && { baseDomain: customBaseDomain.trim() }), ...(customProxy && { proxy: true }), }; + } else if (customProviderType === 'railway') { + if (!customApiKey.trim()) return; + provider = { + type: 'railway', + name: customName.trim(), + apiKey: customApiKey.trim(), + ...(customBaseURL?.trim() && { baseURL: customBaseURL.trim() }), + ...(customProxy && { proxy: true }), + }; } else { return; // Unknown type } @@ -156,7 +167,8 @@ export function AddCustomProviderDialog({ (customProviderType === 'shakespeare' || customProviderType === 'nsite' || (customApiKey.trim() && (customProviderType !== 'cloudflare' || customAccountId.trim()) && - (customProviderType !== 'deno' || customOrganizationId.trim()))); + (customProviderType !== 'deno' || customOrganizationId.trim()) && + (customProviderType !== 'railway' || true))); return ( @@ -175,7 +187,7 @@ export function AddCustomProviderDialog({ @@ -299,7 +312,8 @@ export function AddCustomProviderDialog({ {customProviderType === 'netlify' ? 'Personal Access Token' : customProviderType === 'cloudflare' ? 'API Token' : customProviderType === 'deno' ? 'Access Token' : - 'Access Token'} * + customProviderType === 'railway' ? 'API Token' : + 'Access Token'} * setCustomBaseURL(e.target.value)} diff --git a/src/components/deploy/DeploySteps.tsx b/src/components/deploy/DeploySteps.tsx index 7563dad7..d9debd94 100644 --- a/src/components/deploy/DeploySteps.tsx +++ b/src/components/deploy/DeploySteps.tsx @@ -23,6 +23,7 @@ import { VercelDeployForm } from '@/components/deploy/VercelDeployForm'; import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm'; import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm'; import { DenoDeployForm } from '@/components/deploy/DenoDeployForm'; +import { RailwayDeployForm } from '@/components/deploy/RailwayDeployForm'; import { cn } from '@/lib/utils'; import { DeployAdapter } from '@/lib/deploy/types'; import { ShakespeareAdapter } from '@/lib/deploy/ShakespeareAdapter'; @@ -31,6 +32,7 @@ import { NetlifyAdapter } from '@/lib/deploy/NetlifyAdapter'; import { VercelAdapter } from '@/lib/deploy/VercelAdapter'; import { CloudflareAdapter } from '@/lib/deploy/CloudflareAdapter'; import { DenoDeployAdapter } from '@/lib/deploy/DenoDeployAdapter'; +import { RailwayAdapter } from '@/lib/deploy/RailwayAdapter'; /** * Normalize a URL string to ensure it has a protocol @@ -101,6 +103,14 @@ interface DenoDeployFormData { projectName: string; } +interface RailwayFormData { + workspaceId: string; + projectId: string; + environmentId: string; + serviceId: string; + projectName?: string; +} + export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProps) { const { t } = useTranslation(); const { settings } = useDeploySettings(); @@ -138,6 +148,13 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp const [denoDeployForm, setDenoDeployForm] = useState({ projectName: projectName || projectId, }); + const [railwayForm, setRailwayForm] = useState({ + workspaceId: '', + projectId: '', + environmentId: '', + serviceId: '', + projectName: projectName || projectId, + }); // Load project settings when component mounts useEffect(() => { @@ -261,6 +278,23 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp projectName: denoDeployForm.projectName || undefined, corsProxy: denoProvider.proxy ? config.corsProxy : undefined, }); + } else if (selectedProvider.type === 'railway') { + const railwayProvider = selectedProvider; + if (!railwayProvider.apiKey) { + throw new Error('Railway API token is required'); + } + + adapter = new RailwayAdapter({ + fs, + apiKey: railwayProvider.apiKey, + baseURL: railwayProvider.baseURL, + workspaceId: railwayForm.workspaceId || undefined, + projectId: railwayForm.projectId || undefined, + environmentId: railwayForm.environmentId || undefined, + serviceId: railwayForm.serviceId || undefined, + projectName: railwayForm.projectName || undefined, + corsProxy: railwayProvider.proxy ? config.corsProxy : undefined, + }); } else { throw new Error('Unknown provider type'); } @@ -320,6 +354,17 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp projectName: denoDeployForm.projectName || undefined, }, }); + } else if (selectedProvider.type === 'railway') { + await updateProjectSettings(selectedProviderId, { + type: 'railway', + url: result.url, + data: { + workspaceId: railwayForm.workspaceId || undefined, + projectId: result.metadata?.projectId as string | undefined, + environmentId: result.metadata?.environmentId as string | undefined, + serviceId: result.metadata?.serviceId as string | undefined, + }, + }); } setDeployResult(result); @@ -341,6 +386,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp setVercelForm({ projectName: projectName || projectId, teamId: '' }); setCloudflareForm({ projectName: projectName || projectId }); setDenoDeployForm({ projectName: projectName || projectId }); + setRailwayForm({ workspaceId: '', projectId: '', environmentId: '', serviceId: '', projectName: projectName || projectId }); onClose(); }; @@ -372,6 +418,16 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp setDenoDeployForm({ projectName }); }, []); + const handleRailwayConfigChange = useCallback((config: { + workspaceId: string; + projectId: string; + environmentId: string; + serviceId: string; + projectName?: string; + }) => { + setRailwayForm(config); + }, []); + const renderProviderFields = () => { if (!selectedProvider) return null; @@ -477,6 +533,30 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp ); } + if (selectedProvider.type === 'railway') { + const railwayProvider = selectedProvider; + const savedConfig = projectSettings.providers[selectedProviderId]; + const savedWorkspaceId = savedConfig?.type === 'railway' ? savedConfig.data.workspaceId : undefined; + const savedProjectId = savedConfig?.type === 'railway' ? savedConfig.data.projectId : undefined; + const savedEnvironmentId = savedConfig?.type === 'railway' ? savedConfig.data.environmentId : undefined; + const savedServiceId = savedConfig?.type === 'railway' ? savedConfig.data.serviceId : undefined; + + return ( + + ); + } + return null; }; @@ -653,7 +733,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp (selectedProvider.type === 'nsite' && !nsiteForm.nsec) || (selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) || (selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) || - (selectedProvider.type === 'deno' && !denoDeployForm.projectName) + (selectedProvider.type === 'deno' && !denoDeployForm.projectName) || + (selectedProvider.type === 'railway' && !railwayForm.workspaceId) } className="w-full" > diff --git a/src/components/deploy/RailwayDeployForm.tsx b/src/components/deploy/RailwayDeployForm.tsx new file mode 100644 index 00000000..baa4ae21 --- /dev/null +++ b/src/components/deploy/RailwayDeployForm.tsx @@ -0,0 +1,382 @@ +import { useState, useEffect, useCallback } from 'react'; +import { Plus, ExternalLink } from 'lucide-react'; +import { Label } from '@/components/ui/label'; +import { Input } from '@/components/ui/input'; +import { Button } from '@/components/ui/button'; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from '@/components/ui/select'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { Skeleton } from '@/components/ui/skeleton'; +import { proxyUrl } from '@/lib/proxyUrl'; + +interface Workspace { + id: string; + name: string; + projects: { + edges: Array<{ + node: Project; + }>; + }; +} + +interface Project { + id: string; + name: string; + environments: { + edges: Array<{ + node: { + id: string; + name: string; + }; + }>; + }; + services: { + edges: Array<{ + node: { + id: string; + name: string; + }; + }>; + }; +} + +interface RailwayDeployFormProps { + apiKey: string; + baseURL?: string; + projectId: string; + projectName?: string; + savedWorkspaceId?: string; + savedProjectId?: string; + savedEnvironmentId?: string; + savedServiceId?: string; + onConfigChange: (config: { + workspaceId: string; + projectId: string; + environmentId: string; + serviceId: string; + projectName?: string; + }) => void; + corsProxy?: string; +} + +export function RailwayDeployForm({ + apiKey, + baseURL = 'https://backboard.railway.com', + projectId, + projectName, + savedWorkspaceId, + savedProjectId, + savedEnvironmentId, + savedServiceId, + onConfigChange, + corsProxy, +}: RailwayDeployFormProps) { + const [workspaces, setWorkspaces] = useState([]); + const [isLoading, setIsLoading] = useState(true); + const [error, setError] = useState(null); + const [selectedWorkspaceId, setSelectedWorkspaceId] = useState(''); + const [selectedProjectId, setSelectedProjectId] = useState(''); + const [selectedEnvironmentId, setSelectedEnvironmentId] = useState(''); + const [selectedServiceId, setSelectedServiceId] = useState(''); + const [newProjectName, setNewProjectName] = useState(projectName || projectId); + + const fetchWorkspaces = useCallback(async () => { + setIsLoading(true); + setError(null); + + try { + const query = ` + query UserWorkspaces { + me { + workspaces { + id + name + projects(first: 500) { + edges { + node { + id + name + environments { + edges { + node { + id + name + } + } + } + services { + edges { + node { + id + name + } + } + } + } + } + } + } + } + } + `; + + const url = `${baseURL}/graphql/v2`; + const targetUrl = corsProxy ? proxyUrl({ template: corsProxy, url }) : url; + + const response = await fetch(targetUrl, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${apiKey}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ query }), + }); + + if (!response.ok) { + throw new Error(`Failed to fetch workspaces: ${response.status} ${response.statusText}`); + } + + const result = await response.json(); + + if (result.errors) { + throw new Error(`Railway API error: ${result.errors[0]?.message || 'Unknown error'}`); + } + + const workspacesData: Workspace[] = result.data.me.workspaces; + setWorkspaces(workspacesData); + + // Auto-select workspace if saved or if there's only one + if (savedWorkspaceId && workspacesData.some(w => w.id === savedWorkspaceId)) { + setSelectedWorkspaceId(savedWorkspaceId); + } else if (workspacesData.length === 1) { + setSelectedWorkspaceId(workspacesData[0].id); + } + + // Auto-select project if saved + if (savedProjectId) { + setSelectedProjectId(savedProjectId); + } + + // Auto-select environment if saved + if (savedEnvironmentId) { + setSelectedEnvironmentId(savedEnvironmentId); + } + + // Auto-select service if saved + if (savedServiceId) { + setSelectedServiceId(savedServiceId); + } + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to fetch workspaces'); + } finally { + setIsLoading(false); + } + }, [apiKey, baseURL, savedWorkspaceId, savedProjectId, savedEnvironmentId, savedServiceId, corsProxy]); + + useEffect(() => { + fetchWorkspaces(); + }, [fetchWorkspaces]); + + // Update newProjectName when switching to "new" if it's empty + useEffect(() => { + if (selectedProjectId === 'new' && !newProjectName) { + setNewProjectName(projectName || projectId); + } + }, [selectedProjectId, newProjectName, projectName, projectId]); + + // Notify parent of configuration changes + useEffect(() => { + if (!selectedWorkspaceId || !selectedProjectId) { + return; + } + + if (selectedProjectId === 'new') { + // Creating new project - only require workspace and project name + onConfigChange({ + workspaceId: selectedWorkspaceId, + projectId: '', + environmentId: '', + serviceId: '', + projectName: newProjectName, + }); + } else { + // Existing project - require environment and service + if (!selectedEnvironmentId || !selectedServiceId) { + return; + } + onConfigChange({ + workspaceId: selectedWorkspaceId, + projectId: selectedProjectId, + environmentId: selectedEnvironmentId, + serviceId: selectedServiceId === 'new' ? '' : selectedServiceId, + }); + } + }, [selectedWorkspaceId, selectedProjectId, selectedEnvironmentId, selectedServiceId, newProjectName, onConfigChange]); + + if (isLoading) { + return ( +
+
+ + +
+
+ + +
+
+ ); + } + + const selectedWorkspace = workspaces.find(w => w.id === selectedWorkspaceId); + const projects = selectedWorkspace?.projects.edges.map(e => e.node) || []; + const selectedProject = projects.find(p => p.id === selectedProjectId); + const environments = selectedProject?.environments.edges.map(e => e.node) || []; + const services = selectedProject?.services.edges.map(e => e.node) || []; + + return ( +
+ {error && ( + + {error} + + )} + + {/* Workspace Selection */} +
+ + +
+ + {/* Project Selection */} + {selectedWorkspaceId && ( +
+ + +
+ )} + + {/* New Project Name */} + {selectedProjectId === 'new' && ( +
+ + setNewProjectName(e.target.value)} + placeholder={projectName || projectId} + /> +

+ A new project with a production environment and web service will be created when you deploy +

+
+ )} + + {/* Environment Selection */} + {selectedProjectId && selectedProjectId !== 'new' && environments.length > 0 && ( +
+ + +
+ )} + + {/* Service Selection */} + {selectedProjectId && selectedProjectId !== 'new' && selectedEnvironmentId && ( +
+ + +
+ )} + + {/* Project Info */} + {selectedProject && selectedProjectId !== 'new' && ( +
+
+
+

{selectedProject.name}

+

+ {environments.length} environment(s), {services.length} service(s) +

+
+ +
+
+ )} +
+ ); +} diff --git a/src/contexts/DeploySettingsContext.ts b/src/contexts/DeploySettingsContext.ts index 09abe69a..dc2ca51d 100644 --- a/src/contexts/DeploySettingsContext.ts +++ b/src/contexts/DeploySettingsContext.ts @@ -50,7 +50,14 @@ export interface DenoDeployProvider extends BaseDeployProvider { proxy?: boolean; } -export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider; +export interface RailwayProvider extends BaseDeployProvider { + type: 'railway'; + apiKey: string; + baseURL?: string; + proxy?: boolean; +} + +export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | RailwayProvider; export interface DeploySettings { providers: DeployProvider[]; diff --git a/src/hooks/useProjectDeploySettings.ts b/src/hooks/useProjectDeploySettings.ts index 917929f0..9c46801a 100644 --- a/src/hooks/useProjectDeploySettings.ts +++ b/src/hooks/useProjectDeploySettings.ts @@ -52,6 +52,17 @@ const denoDeployProjectConfigSchema = z.object({ }), }); +const railwayProjectConfigSchema = z.object({ + type: z.literal('railway'), + url: z.string(), + data: z.object({ + workspaceId: z.string().optional(), + projectId: z.string().optional(), + environmentId: z.string().optional(), + serviceId: z.string().optional(), + }), +}); + const projectProviderConfigSchema = z.discriminatedUnion('type', [ shakespeareProjectConfigSchema, nsiteProjectConfigSchema, @@ -59,6 +70,7 @@ const projectProviderConfigSchema = z.discriminatedUnion('type', [ vercelProjectConfigSchema, cloudflareProjectConfigSchema, denoDeployProjectConfigSchema, + railwayProjectConfigSchema, ]); const projectDeploySettingsSchema = z.object({ @@ -72,6 +84,7 @@ export type NetlifyProjectConfig = z.infer; export type VercelProjectConfig = z.infer; export type CloudflareProjectConfig = z.infer; export type DenoDeployProjectConfig = z.infer; +export type RailwayProjectConfig = z.infer; export type ProjectProviderConfig = z.infer; export type ProjectDeploySettings = z.infer; diff --git a/src/lib/configUtils.ts b/src/lib/configUtils.ts index 28096149..8349f3dc 100644 --- a/src/lib/configUtils.ts +++ b/src/lib/configUtils.ts @@ -130,6 +130,12 @@ const denoDeployProviderSchema = baseDeployProviderSchema.extend({ baseDomain: z.string().optional(), }); +const railwayProviderSchema = baseDeployProviderSchema.extend({ + type: z.literal('railway'), + apiKey: z.string(), + baseURL: z.string().optional(), +}); + const deployProviderSchema: z.ZodType = z.discriminatedUnion('type', [ shakespeareDeployProviderSchema, netlifyProviderSchema, @@ -137,6 +143,7 @@ const deployProviderSchema: z.ZodType = z.discriminatedUnion('ty nsiteProviderSchema, cloudflareProviderSchema, denoDeployProviderSchema, + railwayProviderSchema, ]); const deploySettingsSchema = z.object({ diff --git a/src/lib/deploy/RailwayAdapter.ts b/src/lib/deploy/RailwayAdapter.ts new file mode 100644 index 00000000..7fdd8a86 --- /dev/null +++ b/src/lib/deploy/RailwayAdapter.ts @@ -0,0 +1,494 @@ +import type { JSRuntimeFS } from '../JSRuntime'; +import type { DeployAdapter, DeployOptions, DeployResult, RailwayDeployConfig } from './types'; +import { proxyUrl } from '../proxyUrl'; + +interface Workspace { + id: string; + name: string; + team: { + id: string; + } | null; + projects: { + edges: Array<{ + node: Project; + }>; + }; +} + +interface Project { + id: string; + name: string; + environments: { + edges: Array<{ + node: Environment; + }>; + }; + services: { + edges: Array<{ + node: Service; + }>; + }; +} + +interface Environment { + id: string; + name: string; +} + +interface Service { + id: string; + name: string; +} + +interface DeploymentResponse { + deploymentId: string; + url: string; + logsUrl?: string; + deploymentDomain: string; +} + +/** + * Railway Deploy Adapter + * Uses Railway GraphQL API and REST upload endpoint + * + * Implements the Railway deployment workflow: + * 1. Query for workspaces and projects (or use provided IDs) + * 2. Create project if needed + * 3. Create service if needed + * 4. Create tarball of entire source code (excluding common dev files) + * 5. Upload tarball to Railway via multipart/form-data + */ +export class RailwayAdapter implements DeployAdapter { + private fs: JSRuntimeFS; + private apiKey: string; + private baseURL: string; + private workspaceId?: string; + private projectId?: string; + private environmentId?: string; + private serviceId?: string; + private projectName?: string; + private corsProxy?: string; + + constructor(config: RailwayDeployConfig) { + this.fs = config.fs; + this.apiKey = config.apiKey; + this.baseURL = config.baseURL || 'https://backboard.railway.com'; + this.workspaceId = config.workspaceId; + this.projectId = config.projectId; + this.environmentId = config.environmentId; + this.serviceId = config.serviceId; + this.projectName = config.projectName; + this.corsProxy = config.corsProxy; + } + + async deploy(options: DeployOptions): Promise { + const { projectId, projectPath } = options; + + // Step 1: Ensure we have a workspace + if (!this.workspaceId) { + const workspaces = await this.getWorkspaces(); + if (workspaces.length === 0) { + throw new Error('No workspaces found. Please create a workspace on Railway first.'); + } + this.workspaceId = workspaces[0].id; + } + + // Step 2: Get or create project + let activeProjectId = this.projectId; + let activeEnvironmentId = this.environmentId; + + if (!activeProjectId) { + const project = await this.createProject(this.projectName || projectId); + activeProjectId = project.id; + // Get the default production environment + activeEnvironmentId = project.environments.edges[0]?.node.id; + } else if (!activeEnvironmentId) { + // If we have project ID but no environment, fetch the project to get the environment + const project = await this.getProject(activeProjectId); + activeEnvironmentId = project.environments.edges[0]?.node.id; + } + + if (!activeEnvironmentId) { + throw new Error('No environment found for project'); + } + + // Step 3: Get or create service + let activeServiceId = this.serviceId; + + if (!activeServiceId) { + const service = await this.createService(activeProjectId, 'web'); + activeServiceId = service.id; + } + + // Step 4: Create tarball of source code + const tarball = await this.createTarball(projectPath); + + // Step 5: Upload to Railway + const deployment = await this.uploadDeployment( + activeProjectId, + activeEnvironmentId, + activeServiceId, + tarball + ); + + return { + url: deployment.url, + metadata: { + deploymentId: deployment.deploymentId, + projectId: activeProjectId, + environmentId: activeEnvironmentId, + serviceId: activeServiceId, + provider: 'railway', + deploymentDomain: deployment.deploymentDomain, + }, + }; + } + + private async graphqlRequest(query: string, variables?: Record): Promise { + const url = `${this.baseURL}/graphql/v2`; + const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url; + + const response = await fetch(targetUrl, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ query, variables }), + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Railway GraphQL request failed: ${response.status} ${response.statusText}. ${errorText}`); + } + + const result = await response.json(); + + if (result.errors) { + const errorMessages = result.errors.map((e: { message: string }) => e.message).join(', '); + throw new Error(`Railway GraphQL error: ${errorMessages}`); + } + + return result.data; + } + + private async getWorkspaces(): Promise { + const query = ` + query UserWorkspaces { + me { + workspaces { + id + name + team { + id + } + projects(first: 500) { + edges { + node { + id + name + environments { + edges { + node { + id + name + } + } + } + services { + edges { + node { + id + name + } + } + } + } + } + } + } + } + } + `; + + const data = await this.graphqlRequest<{ me: { workspaces: Workspace[] } }>(query); + return data.me.workspaces; + } + + private async getProject(projectId: string): Promise { + const query = ` + query GetProject($projectId: String!) { + project(id: $projectId) { + id + name + environments { + edges { + node { + id + name + } + } + } + services { + edges { + node { + id + name + } + } + } + } + } + `; + + const data = await this.graphqlRequest<{ project: Project }>(query, { projectId }); + return data.project; + } + + private async createProject(name: string): Promise { + const query = ` + mutation ProjectCreate($name: String, $workspaceId: String) { + projectCreate(input: { + name: $name, + workspaceId: $workspaceId + }) { + id + name + environments { + edges { + node { + id + name + } + } + } + } + } + `; + + const data = await this.graphqlRequest<{ projectCreate: Project }>(query, { + name, + workspaceId: this.workspaceId, + }); + + return data.projectCreate; + } + + private async createService(projectId: string, name: string): Promise { + const query = ` + mutation ServiceCreate($input: ServiceCreateInput!) { + serviceCreate(input: $input) { + id + name + } + } + `; + + const data = await this.graphqlRequest<{ serviceCreate: Service }>(query, { + input: { + name, + projectId, + source: { + image: null, + repo: null, + }, + }, + }); + + return data.serviceCreate; + } + + private async createTarball(projectPath: string): Promise { + // Import tar library dynamically (needs to be available in the project) + // For browser environment, we'll need to use a tar implementation + // Using a simpler approach: collect files and create a tar-like structure + + // Collect all files excluding common dev files + const files = new Map(); + await this.collectFilesForTarball(projectPath, '', files); + + // Create a simple tar.gz equivalent using browser APIs + // Since we're in a browser environment, we'll create a structure that Railway can accept + const tarData = await this.createTarGzBlob(files); + + return tarData; + } + + private async collectFilesForTarball( + dirPath: string, + relativePath: string, + files: Map + ): Promise { + // Directories to exclude + const excludeDirs = new Set([ + '.git', + 'node_modules', + 'dist', + 'build', + '.next', + '.nuxt', + '.output', + '.vite', + '.cache', + '__pycache__', + '.pytest_cache', + '.venv', + 'venv', + 'env', + '.DS_Store', + 'coverage', + '.nyc_output', + ]); + + // Files to exclude + const excludeFiles = new Set([ + '.env', + '.env.local', + '.env.development', + '.env.production', + '.env.test', + 'npm-debug.log', + 'yarn-debug.log', + 'yarn-error.log', + '.DS_Store', + ]); + + try { + const entries = await this.fs.readdir(dirPath, { withFileTypes: true }); + + for (const entry of entries) { + // Skip excluded directories and files + if (excludeDirs.has(entry.name) || excludeFiles.has(entry.name)) { + continue; + } + + const fullPath = `${dirPath}/${entry.name}`; + const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name; + + if (entry.isDirectory()) { + await this.collectFilesForTarball(fullPath, entryRelativePath, files); + } else if (entry.isFile()) { + try { + const fileContent = await this.fs.readFile(fullPath); + + let bytes: Uint8Array; + if (typeof fileContent === 'string') { + bytes = new TextEncoder().encode(fileContent); + } else { + bytes = fileContent; + } + + files.set(entryRelativePath, bytes); + } catch (error) { + console.warn(`Failed to read file ${fullPath}:`, error); + } + } + } + } catch (error) { + console.warn(`Failed to read directory ${dirPath}:`, error); + } + } + + private async createTarGzBlob(files: Map): Promise { + // Create a simple tar structure + // TAR format: 512-byte header + file data (padded to 512 bytes) + const blocks: Uint8Array[] = []; + + for (const [filePath, content] of files) { + // Create tar header (simplified) + const header = new Uint8Array(512); + const encoder = new TextEncoder(); + + // File name (offset 0, 100 bytes) + const nameBytes = encoder.encode(filePath); + header.set(nameBytes.slice(0, 100), 0); + + // File mode (offset 100, 8 bytes) - "0000644\0" + header.set(encoder.encode('0000644\0'), 100); + + // Owner UID (offset 108, 8 bytes) - "0000000\0" + header.set(encoder.encode('0000000\0'), 108); + + // Group GID (offset 116, 8 bytes) - "0000000\0" + header.set(encoder.encode('0000000\0'), 116); + + // File size in octal (offset 124, 12 bytes) + const sizeOctal = content.length.toString(8).padStart(11, '0') + '\0'; + header.set(encoder.encode(sizeOctal), 124); + + // Modification time (offset 136, 12 bytes) + const mtime = Math.floor(Date.now() / 1000).toString(8).padStart(11, '0') + '\0'; + header.set(encoder.encode(mtime), 136); + + // Checksum (offset 148, 8 bytes) - calculate after setting type flag + header.set(encoder.encode(' '), 148); + + // Type flag (offset 156, 1 byte) - '0' for regular file + header.set(encoder.encode('0'), 156); + + // Calculate checksum + let checksum = 0; + for (let i = 0; i < 512; i++) { + checksum += header[i]; + } + const checksumOctal = checksum.toString(8).padStart(6, '0') + '\0 '; + header.set(encoder.encode(checksumOctal), 148); + + blocks.push(header); + + // Add file content, padded to 512-byte boundary + const paddedSize = Math.ceil(content.length / 512) * 512; + const paddedContent = new Uint8Array(paddedSize); + paddedContent.set(content); + blocks.push(paddedContent); + } + + // Add two empty 512-byte blocks to mark end of archive + blocks.push(new Uint8Array(512)); + blocks.push(new Uint8Array(512)); + + // Combine all blocks + const totalSize = blocks.reduce((sum, block) => sum + block.length, 0); + const tarData = new Uint8Array(totalSize); + let offset = 0; + for (const block of blocks) { + tarData.set(block, offset); + offset += block.length; + } + + // Compress with gzip (using CompressionStream API) + const stream = new Blob([tarData]).stream(); + const compressedStream = stream.pipeThrough(new CompressionStream('gzip')); + const compressedBlob = await new Response(compressedStream).blob(); + + return compressedBlob; + } + + private async uploadDeployment( + projectId: string, + environmentId: string, + serviceId: string, + tarball: Blob + ): Promise { + const url = `${this.baseURL}/project/${projectId}/environment/${environmentId}/up?serviceId=${serviceId}`; + const targetUrl = this.corsProxy ? proxyUrl({ template: this.corsProxy, url }) : url; + + // Railway expects the raw tarball bytes with Content-Type: multipart/form-data + // NOT wrapped in FormData + const response = await fetch(targetUrl, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${this.apiKey}`, + 'Content-Type': 'multipart/form-data', + }, + body: tarball, + }); + + if (!response.ok) { + const errorText = await response.text().catch(() => 'Unknown error'); + throw new Error(`Failed to upload deployment to Railway: ${response.status} ${response.statusText}. ${errorText}`); + } + + return response.json(); + } +} diff --git a/src/lib/deploy/index.ts b/src/lib/deploy/index.ts index 24bf4795..3c26b898 100644 --- a/src/lib/deploy/index.ts +++ b/src/lib/deploy/index.ts @@ -5,3 +5,4 @@ export * from './VercelAdapter'; export * from './NsiteAdapter'; export * from './CloudflareAdapter'; export * from './DenoDeployAdapter'; +export * from './RailwayAdapter'; diff --git a/src/lib/deploy/types.ts b/src/lib/deploy/types.ts index 6c9df61a..147bcec8 100644 --- a/src/lib/deploy/types.ts +++ b/src/lib/deploy/types.ts @@ -75,9 +75,21 @@ export interface DenoDeployConfig { corsProxy?: string; } +export interface RailwayDeployConfig { + fs: JSRuntimeFS; + apiKey: string; + baseURL?: string; + workspaceId?: string; + projectId?: string; + environmentId?: string; + serviceId?: string; + projectName?: string; + corsProxy?: string; +} + export interface PresetDeployProvider { id: string; - type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno'; + type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway'; name: string; description: string; baseURL?: string; diff --git a/src/lib/deployProviderPresets.ts b/src/lib/deployProviderPresets.ts index 5bf6d8a4..030d4d61 100644 --- a/src/lib/deployProviderPresets.ts +++ b/src/lib/deployProviderPresets.ts @@ -60,4 +60,14 @@ export const PRESET_DEPLOY_PROVIDERS: PresetDeployProvider[] = [ organizationIdURL: 'https://dash.deno.com/orgs', proxy: true, }, + { + id: 'railway', + type: 'railway', + name: 'Railway', + description: 'Deploy to Railway', + baseURL: 'https://backboard.railway.com', + apiKeyLabel: 'API Token', + apiKeyURL: 'https://railway.app/account/tokens', + proxy: true, + }, ]; diff --git a/src/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx index e4cdfbec..10856723 100644 --- a/src/pages/DeploySettings.tsx +++ b/src/pages/DeploySettings.tsx @@ -260,6 +260,14 @@ export function DeploySettings() { organizationId: organizationId.trim(), ...(preset.proxy && { proxy: true }), }; + } else if (preset.type === 'railway') { + newProvider = { + id: preset.id, // Use preset ID for presets + name: preset.name, + type: 'railway', + apiKey: apiKey.trim(), + ...(preset.proxy && { proxy: true }), + }; } else { return; // Unknown type }