diff --git a/src/components/AddProviderDialog.tsx b/src/components/AddProviderDialog.tsx index 59e78bb8..e98d5ce8 100644 --- a/src/components/AddProviderDialog.tsx +++ b/src/components/AddProviderDialog.tsx @@ -22,7 +22,7 @@ import { Link } from 'react-router-dom'; interface PresetProvider { id: string; - type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno'; + type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'apkbuilder'; name: string; description: string; requiresNostr?: boolean; @@ -32,6 +32,7 @@ interface PresetProvider { accountIdURL?: string; organizationIdLabel?: string; organizationIdURL?: string; + buildServerUrlLabel?: string; proxy?: boolean; } @@ -50,7 +51,7 @@ interface AddProviderDialogProps { oauthHook: OAuthHook | null; forceManualEntry: boolean; onSetForceManualEntry: (force: boolean) => void; - onAdd: (apiKey: string, accountId?: string, organizationId?: string) => void; + onAdd: (apiKey: string, accountId?: string, organizationId?: string, buildServerUrl?: string) => void; } function getProviderUrl(preset: PresetProvider): string | null { @@ -67,6 +68,8 @@ function getProviderUrl(preset: PresetProvider): string | null { return 'https://deno.com'; case 'nsite': return null; + case 'apkbuilder': + return null; default: return null; } @@ -86,6 +89,7 @@ export function AddProviderDialog({ const [apiKey, setApiKey] = useState(''); const [accountId, setAccountId] = useState(''); const [organizationId, setOrganizationId] = useState(''); + const [buildServerUrl, setBuildServerUrl] = useState(''); const showNostrLoginRequired = preset.requiresNostr && !isLoggedIntoNostr; const isOAuthConfigured = oauthHook?.isOAuthConfigured ?? false; @@ -93,10 +97,11 @@ export function AddProviderDialog({ const oauthError = oauthHook?.error ?? null; const handleAdd = () => { - onAdd(apiKey, accountId, organizationId); + onAdd(apiKey, accountId, organizationId, buildServerUrl); setApiKey(''); setAccountId(''); setOrganizationId(''); + setBuildServerUrl(''); onOpenChange(false); }; @@ -225,6 +230,19 @@ export function AddProviderDialog({ urlTitle="Find ID" /> )} + {preset.type === 'apkbuilder' && ( + setBuildServerUrl(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' && apiKey.trim() && buildServerUrl.trim()) { + handleAdd(); + } + }} + /> + )} {t('add')} diff --git a/src/components/ProviderConfigDialog.tsx b/src/components/ProviderConfigDialog.tsx index a8031779..94c75a27 100644 --- a/src/components/ProviderConfigDialog.tsx +++ b/src/components/ProviderConfigDialog.tsx @@ -19,7 +19,7 @@ import { ExternalFavicon } from '@/components/ExternalFavicon'; interface PresetProvider { id: string; - type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno'; + type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'apkbuilder'; name: string; description: string; requiresNostr?: boolean; @@ -29,6 +29,7 @@ interface PresetProvider { accountIdURL?: string; organizationIdLabel?: string; organizationIdURL?: string; + buildServerUrlLabel?: string; proxy?: boolean; } @@ -97,6 +98,13 @@ function getProviderUrl(provider: DeployProvider | PresetProvider): string | nul // nsite uses Rocket icon fallback return null; + case 'apkbuilder': + // APK Builder - check for custom buildServerUrl + if ('buildServerUrl' in provider && provider.buildServerUrl) { + return provider.buildServerUrl; + } + return null; + default: return null; } @@ -183,6 +191,44 @@ export function ProviderConfigDialog({ /> + ) : localProvider.type === 'apkbuilder' ? ( + <> +
+ + setLocalProvider({ ...localProvider, buildServerUrl: e.target.value })} + /> +
+
+ + setLocalProvider({ ...localProvider, apiKey: e.target.value })} + /> +
+
+ setLocalProvider({ ...localProvider, proxy: checked === true })} + /> + +
+ ) : localProvider.type === 'nsite' ? ( <>
diff --git a/src/components/deploy/APKBuilderDeployForm.tsx b/src/components/deploy/APKBuilderDeployForm.tsx new file mode 100644 index 00000000..61a7f2c8 --- /dev/null +++ b/src/components/deploy/APKBuilderDeployForm.tsx @@ -0,0 +1,198 @@ +import { useState, useEffect, useCallback } from 'react'; +import { CheckCircle, XCircle, Loader2 } from 'lucide-react'; +import { Label } from '@/components/ui/label'; +import { Input } from '@/components/ui/input'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { proxyUrl } from '@/lib/proxyUrl'; + +interface APKBuilderDeployFormProps { + buildServerUrl: string; + apiKey: string; + projectId: string; + projectName?: string; + savedAppName?: string; + savedPackageId?: string; + onConfigChange: (appName: string, packageId: string) => void; + corsProxy?: string; +} + +interface ServerHealth { + status: 'ok' | 'error'; + version?: string; + queue?: { + running: number; + queued: number; + }; +} + +export function APKBuilderDeployForm({ + buildServerUrl, + apiKey, + projectId, + projectName, + savedAppName, + savedPackageId, + onConfigChange, + corsProxy, +}: APKBuilderDeployFormProps) { + const [appName, setAppName] = useState(savedAppName || projectName || projectId); + const [packageId, setPackageId] = useState(savedPackageId || ''); + const [packageIdError, setPackageIdError] = useState(null); + const [serverHealth, setServerHealth] = useState(null); + const [isCheckingServer, setIsCheckingServer] = useState(true); + + // Generate default package ID from project name + useEffect(() => { + if (!savedPackageId && !packageId) { + const safeName = (projectName || projectId) + .toLowerCase() + .replace(/[^a-z0-9]/g, ''); + setPackageId(`com.app.${safeName}`); + } + }, [projectName, projectId, savedPackageId, packageId]); + + // Check server health + const checkServerHealth = useCallback(async () => { + setIsCheckingServer(true); + try { + const url = `${buildServerUrl}/health`; + const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url; + + const response = await fetch(targetUrl, { + headers: { + 'X-API-Key': apiKey, + }, + }); + + if (response.ok) { + const data = await response.json(); + setServerHealth({ status: 'ok', ...data }); + } else { + setServerHealth({ status: 'error' }); + } + } catch { + setServerHealth({ status: 'error' }); + } finally { + setIsCheckingServer(false); + } + }, [buildServerUrl, apiKey, corsProxy]); + + useEffect(() => { + checkServerHealth(); + }, [checkServerHealth]); + + // Validate package ID + const validatePackageId = (value: string): boolean => { + // Android package ID rules: + // - Must have at least two segments (e.g., com.example) + // - Each segment must start with a letter + // - Can only contain letters, numbers, and underscores + const pattern = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)+$/i; + return pattern.test(value); + }; + + // Handle package ID change with validation + const handlePackageIdChange = (value: string) => { + setPackageId(value); + if (value && !validatePackageId(value)) { + setPackageIdError('Package ID must be like "com.example.myapp" (letters, numbers, underscores)'); + } else { + setPackageIdError(null); + } + }; + + // Notify parent of config changes + useEffect(() => { + if (appName && packageId && !packageIdError) { + onConfigChange(appName, packageId); + } + }, [appName, packageId, packageIdError, onConfigChange]); + + return ( +
+ {/* Server Status */} +
+
+ {isCheckingServer ? ( + + ) : serverHealth?.status === 'ok' ? ( + + ) : ( + + )} +
+

+ {isCheckingServer + ? 'Checking build server...' + : serverHealth?.status === 'ok' + ? 'Build server connected' + : 'Build server unavailable'} +

+ {serverHealth?.status === 'ok' && serverHealth.queue && ( +

+ {serverHealth.queue.running > 0 + ? `${serverHealth.queue.running} build(s) in progress` + : 'Ready to build'} + {serverHealth.queue.queued > 0 && `, ${serverHealth.queue.queued} queued`} +

+ )} +
+
+
+ + {serverHealth?.status === 'error' && ( + + + Cannot connect to build server. Check your server URL and API key in Deploy Settings. + + + )} + + {/* App Name */} +
+ + setAppName(e.target.value)} + placeholder="My App" + /> +

+ This name appears on the Android home screen +

+
+ + {/* Package ID */} +
+ + handlePackageIdChange(e.target.value)} + placeholder="com.example.myapp" + className={packageIdError ? 'border-red-500' : ''} + /> + {packageIdError ? ( +

{packageIdError}

+ ) : ( +

+ Unique identifier for your app (e.g., com.yourcompany.appname) +

+ )} +
+ + {/* Build Info */} +
+

+ Build type: Debug APK (sideloading) +

+

+ Output: Downloadable .apk file +

+

+ App icon will be auto-detected from your project +

+
+
+ ); +} diff --git a/src/components/deploy/DeploySteps.tsx b/src/components/deploy/DeploySteps.tsx index 9bffde50..83196ec9 100644 --- a/src/components/deploy/DeploySteps.tsx +++ b/src/components/deploy/DeploySteps.tsx @@ -21,6 +21,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 { APKBuilderDeployForm } from '@/components/deploy/APKBuilderDeployForm'; import { cn } from '@/lib/utils'; import { DeployAdapter } from '@/lib/deploy/types'; import { ShakespeareAdapter } from '@/lib/deploy/ShakespeareAdapter'; @@ -29,6 +30,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 { APKBuilderAdapter } from '@/lib/deploy/APKBuilderAdapter'; /** * Helper function to get provider URL for favicon @@ -68,6 +70,9 @@ function getProviderUrl(provider: DeployProvider): string | null { case 'nsite': return null; + case 'apkbuilder': + return null; // No favicon for custom build server + default: return null; } @@ -124,6 +129,11 @@ interface DenoDeployFormData { projectName: string; } +interface APKBuilderFormData { + appName: string; + packageId: string; +} + export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProps) { const { t } = useTranslation(); const { settings } = useDeploySettings(); @@ -161,6 +171,10 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp const [denoDeployForm, setDenoDeployForm] = useState({ projectName: projectName || projectId, }); + const [apkBuilderForm, setApkBuilderForm] = useState({ + appName: projectName || projectId, + packageId: '', + }); // Load project settings when component mounts useEffect(() => { @@ -284,6 +298,29 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp projectName: denoDeployForm.projectName || undefined, corsProxy: denoProvider.proxy ? config.corsProxy : undefined, }); + } else if (selectedProvider.type === 'apkbuilder') { + const apkBuilderProvider = selectedProvider; + if (!apkBuilderProvider.buildServerUrl) { + throw new Error('APK Builder server URL is required'); + } + if (!apkBuilderProvider.apiKey) { + throw new Error('APK Builder API key is required'); + } + if (!apkBuilderForm.appName) { + throw new Error('App name is required'); + } + if (!apkBuilderForm.packageId) { + throw new Error('Package ID is required'); + } + + adapter = new APKBuilderAdapter({ + fs, + buildServerUrl: apkBuilderProvider.buildServerUrl, + apiKey: apkBuilderProvider.apiKey, + appName: apkBuilderForm.appName, + packageId: apkBuilderForm.packageId, + corsProxy: apkBuilderProvider.proxy ? config.corsProxy : undefined, + }); } else { throw new Error('Unknown provider type'); } @@ -343,6 +380,15 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp projectName: denoDeployForm.projectName || undefined, }, }); + } else if (selectedProvider.type === 'apkbuilder') { + await updateProjectSettings(selectedProviderId, { + type: 'apkbuilder', + url: result.url, + data: { + appName: apkBuilderForm.appName, + packageId: apkBuilderForm.packageId, + }, + }); } setDeployResult(result); @@ -364,6 +410,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp setVercelForm({ projectName: projectName || projectId, teamId: '' }); setCloudflareForm({ projectName: projectName || projectId }); setDenoDeployForm({ projectName: projectName || projectId }); + setApkBuilderForm({ appName: projectName || projectId, packageId: '' }); onClose(); }; @@ -395,6 +442,10 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp setDenoDeployForm({ projectName }); }, []); + const handleApkBuilderConfigChange = useCallback((appName: string, packageId: string) => { + setApkBuilderForm({ appName, packageId }); + }, []); + const renderProviderFields = () => { if (!selectedProvider) return null; @@ -500,6 +551,26 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp ); } + if (selectedProvider.type === 'apkbuilder') { + const apkBuilderProvider = selectedProvider; + const savedConfig = projectSettings.providers[selectedProviderId]; + const savedAppName = savedConfig?.type === 'apkbuilder' ? savedConfig.data.appName : undefined; + const savedPackageId = savedConfig?.type === 'apkbuilder' ? savedConfig.data.packageId : undefined; + + return ( + + ); + } + return null; }; @@ -673,7 +744,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 === 'apkbuilder' && (!apkBuilderForm.appName || !apkBuilderForm.packageId)) } className="w-full" > diff --git a/src/contexts/DeploySettingsContext.ts b/src/contexts/DeploySettingsContext.ts index 09abe69a..5284a063 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 APKBuilderProvider extends BaseDeployProvider { + type: 'apkbuilder'; + buildServerUrl: string; + apiKey: string; + proxy?: boolean; +} + +export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | APKBuilderProvider; export interface DeploySettings { providers: DeployProvider[]; diff --git a/src/hooks/useProjectDeploySettings.ts b/src/hooks/useProjectDeploySettings.ts index 917929f0..f9e8dd51 100644 --- a/src/hooks/useProjectDeploySettings.ts +++ b/src/hooks/useProjectDeploySettings.ts @@ -52,6 +52,15 @@ const denoDeployProjectConfigSchema = z.object({ }), }); +const apkBuilderProjectConfigSchema = z.object({ + type: z.literal('apkbuilder'), + url: z.string(), + data: z.object({ + appName: z.string(), + packageId: z.string(), + }), +}); + const projectProviderConfigSchema = z.discriminatedUnion('type', [ shakespeareProjectConfigSchema, nsiteProjectConfigSchema, @@ -59,6 +68,7 @@ const projectProviderConfigSchema = z.discriminatedUnion('type', [ vercelProjectConfigSchema, cloudflareProjectConfigSchema, denoDeployProjectConfigSchema, + apkBuilderProjectConfigSchema, ]); const projectDeploySettingsSchema = z.object({ @@ -72,6 +82,7 @@ export type NetlifyProjectConfig = z.infer; export type VercelProjectConfig = z.infer; export type CloudflareProjectConfig = z.infer; export type DenoDeployProjectConfig = z.infer; +export type APKBuilderProjectConfig = z.infer; export type ProjectProviderConfig = z.infer; export type ProjectDeploySettings = z.infer; diff --git a/src/lib/commands/index.ts b/src/lib/commands/index.ts index 415c5ded..ec83ab97 100644 --- a/src/lib/commands/index.ts +++ b/src/lib/commands/index.ts @@ -29,4 +29,5 @@ export { UniqCommand } from './uniq'; export { WcCommand } from './wc'; export { WhoamiCommand } from './whoami'; export { WhichCommand } from './which'; -export { UnzipCommand } from './unzip'; \ No newline at end of file +export { UnzipCommand } from './unzip'; +export { ZipCommand } from './zip'; \ No newline at end of file diff --git a/src/lib/commands/zip.ts b/src/lib/commands/zip.ts new file mode 100644 index 00000000..21bbc198 --- /dev/null +++ b/src/lib/commands/zip.ts @@ -0,0 +1,226 @@ +import { join, dirname, basename, normalize } from "path-browserify"; +import JSZip from "jszip"; +import type { JSRuntimeFS } from "../JSRuntime"; +import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; +import { createSuccessResult, createErrorResult } from "./ShellCommand"; + +/** + * Implementation of the 'zip' command + * Create ZIP archives from files and directories + */ +export class ZipCommand implements ShellCommand { + name = 'zip'; + description = 'Create ZIP archives'; + usage = 'zip [-r] [-q] archive.zip file1 [file2 ...]\n -r Recurse into directories\n -q Quiet mode'; + + private fs: JSRuntimeFS; + + constructor(fs: JSRuntimeFS) { + this.fs = fs; + } + + async execute(args: string[], cwd: string): Promise { + if (args.length === 0) { + return createErrorResult(`${this.name}: missing archive operand\nUsage: ${this.usage}`); + } + + let archivePath = ''; + let recursive = false; + let quiet = false; + const filesToAdd: string[] = []; + + // Parse command line options + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + if (arg === '-r') { + recursive = true; + } else if (arg === '-q') { + quiet = true; + } else if (arg === '-rq' || arg === '-qr') { + recursive = true; + quiet = true; + } else if (arg.startsWith('-')) { + // Check for combined flags like -rq + const flags = arg.slice(1); + let validFlags = true; + for (const flag of flags) { + if (flag === 'r') recursive = true; + else if (flag === 'q') quiet = true; + else { + validFlags = false; + break; + } + } + if (!validFlags) { + return createErrorResult(`${this.name}: invalid option '${arg}'\nUsage: ${this.usage}`); + } + } else if (!archivePath) { + // First non-option is the archive path + archivePath = arg; + } else { + // Remaining arguments are files to add + filesToAdd.push(arg); + } + } + + if (!archivePath) { + return createErrorResult(`${this.name}: no archive specified\nUsage: ${this.usage}`); + } + + if (filesToAdd.length === 0) { + return createErrorResult(`${this.name}: no files to add\nUsage: ${this.usage}`); + } + + // Ensure archive has .zip extension + if (!archivePath.toLowerCase().endsWith('.zip')) { + archivePath += '.zip'; + } + + try { + // Resolve archive path + const absoluteArchivePath = this.resolvePath(archivePath, cwd); + + // Security check + if (!this.isPathAllowed(absoluteArchivePath, cwd)) { + return createErrorResult(`${this.name}: cannot create archive outside allowed paths`); + } + + // Create parent directory if needed + const parentDir = dirname(absoluteArchivePath); + try { + await this.fs.stat(parentDir); + } catch { + await this.fs.mkdir(parentDir, { recursive: true }); + } + + const zip = new JSZip(); + const addedFiles: string[] = []; + const errors: string[] = []; + + // Add each file/directory to the archive + for (const filePath of filesToAdd) { + const absolutePath = this.resolvePath(filePath, cwd); + + try { + const stats = await this.fs.stat(absolutePath); + + if (stats.isDirectory()) { + if (recursive) { + await this.addDirectoryToZip(zip, absolutePath, basename(absolutePath), addedFiles, quiet); + } else { + errors.push(`${this.name}: ${filePath}: Is a directory (use -r to include)`); + } + } else if (stats.isFile()) { + const content = await this.fs.readFile(absolutePath); + const entryName = basename(absolutePath); + zip.file(entryName, content); + if (!quiet) { + addedFiles.push(` adding: ${entryName}`); + } + } + } catch { + errors.push(`${this.name}: ${filePath}: No such file or directory`); + } + } + + if (addedFiles.length === 0 && errors.length > 0) { + return createErrorResult(errors.join('\n')); + } + + // Generate the ZIP file + const zipContent = await zip.generateAsync({ + type: 'uint8array', + compression: 'DEFLATE', + compressionOptions: { level: 6 } + }); + + // Write the ZIP file + await this.fs.writeFile(absoluteArchivePath, zipContent); + + // Build output + let output = ''; + if (!quiet) { + output = addedFiles.join('\n'); + if (output) { + output += '\n'; + } + const sizeKB = (zipContent.length / 1024).toFixed(1); + output += `Created: ${archivePath} (${sizeKB} KB)`; + } + + if (errors.length > 0) { + return createErrorResult(output + (output ? '\n' : '') + errors.join('\n')); + } + + return createSuccessResult(output); + + } catch (error) { + if (error instanceof Error) { + return createErrorResult(`${this.name}: ${error.message}`); + } + return createErrorResult(`${this.name}: Unknown error`); + } + } + + /** + * Recursively add a directory to the ZIP archive + */ + private async addDirectoryToZip( + zip: JSZip, + dirPath: string, + zipPath: string, + addedFiles: string[], + quiet: boolean + ): Promise { + const entries = await this.fs.readdir(dirPath, { withFileTypes: true }); + + for (const entry of entries) { + const fullPath = join(dirPath, entry.name); + const entryZipPath = join(zipPath, entry.name); + + if (entry.isDirectory()) { + // Add directory entry and recurse + zip.folder(entryZipPath); + await this.addDirectoryToZip(zip, fullPath, entryZipPath, addedFiles, quiet); + } else if (entry.isFile()) { + try { + const content = await this.fs.readFile(fullPath); + zip.file(entryZipPath, content); + if (!quiet) { + addedFiles.push(` adding: ${entryZipPath}`); + } + } catch { + // Skip files we can't read + } + } + } + } + + /** + * Resolve a path relative to cwd + */ + private resolvePath(filePath: string, cwd: string): string { + if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) { + return normalize(filePath); + } + return normalize(join(cwd, filePath)); + } + + /** + * Check if a path is within allowed directories (cwd or /tmp) + */ + private isPathAllowed(targetPath: string, cwd: string): boolean { + const normalizedPath = normalize(targetPath); + const normalizedCwd = normalize(cwd); + const tmpPath = '/tmp'; + + const absolutePath = normalizedPath.startsWith('/') ? normalizedPath : normalize(join(normalizedCwd, normalizedPath)); + const absoluteCwd = normalizedCwd.startsWith('/') ? normalizedCwd : '/' + normalizedCwd; + + return absolutePath.startsWith(absoluteCwd + '/') || + absolutePath === absoluteCwd || + absolutePath.startsWith(tmpPath + '/') || + absolutePath === tmpPath; + } +} diff --git a/src/lib/configUtils.ts b/src/lib/configUtils.ts index 54d419c7..fff4cade 100644 --- a/src/lib/configUtils.ts +++ b/src/lib/configUtils.ts @@ -129,6 +129,12 @@ const denoDeployProviderSchema = baseDeployProviderSchema.extend({ baseDomain: z.string().optional(), }); +const apkBuilderProviderSchema = baseDeployProviderSchema.extend({ + type: z.literal('apkbuilder'), + buildServerUrl: z.string().url(), + apiKey: z.string(), +}); + const deployProviderSchema: z.ZodType = z.discriminatedUnion('type', [ shakespeareDeployProviderSchema, netlifyProviderSchema, @@ -136,6 +142,7 @@ const deployProviderSchema: z.ZodType = z.discriminatedUnion('ty nsiteProviderSchema, cloudflareProviderSchema, denoDeployProviderSchema, + apkBuilderProviderSchema, ]); const deploySettingsSchema = z.object({ diff --git a/src/lib/deploy/APKBuilderAdapter.ts b/src/lib/deploy/APKBuilderAdapter.ts new file mode 100644 index 00000000..3efcd444 --- /dev/null +++ b/src/lib/deploy/APKBuilderAdapter.ts @@ -0,0 +1,179 @@ +import JSZip from 'jszip'; +import type { JSRuntimeFS } from '../JSRuntime'; +import type { DeployAdapter, DeployOptions, DeployResult, APKBuilderDeployConfig } from './types'; +import { proxyUrl } from '../proxyUrl'; + +interface APKBuildStatus { + id: string; + status: 'queued' | 'building' | 'complete' | 'failed' | 'cancelled'; + progress: number; + error?: string; + apkSize?: number; + logs?: string[]; +} + +/** + * APK Builder Deploy Adapter + * Builds Android APKs from web projects using a Capacitor build service + */ +export class APKBuilderAdapter implements DeployAdapter { + private fs: JSRuntimeFS; + private buildServerUrl: string; + private apiKey: string; + private appName: string; + private packageId: string; + private corsProxy?: string; + private onProgress?: (status: APKBuildStatus) => void; + + constructor(config: APKBuilderDeployConfig) { + this.fs = config.fs; + this.buildServerUrl = config.buildServerUrl.replace(/\/$/, ''); + this.apiKey = config.apiKey; + this.appName = config.appName; + this.packageId = config.packageId; + this.corsProxy = config.corsProxy; + this.onProgress = config.onProgress; + } + + async deploy(options: DeployOptions): Promise { + const { projectPath } = options; + const distPath = `${projectPath}/dist`; + + // Verify dist exists + try { + await this.fs.readFile(`${distPath}/index.html`, 'utf8'); + } catch { + throw new Error('No dist folder found. Build the project first using the Build button.'); + } + + // Create ZIP of dist folder + const zip = new JSZip(); + const distFolder = zip.folder('dist'); + if (!distFolder) { + throw new Error('Failed to create ZIP folder'); + } + await this.addDirectoryToZip(distPath, distFolder); + const zipBlob = await zip.generateAsync({ type: 'blob' }); + + // Submit build request + const buildId = await this.submitBuild(zipBlob); + + // Poll for completion + const result = await this.waitForBuild(buildId); + + return result; + } + + private async submitBuild(zipBlob: Blob): Promise { + const url = `${this.buildServerUrl}/api/build`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + const formData = new FormData(); + formData.append('project', zipBlob, 'project.zip'); + formData.append('config', JSON.stringify({ + appName: this.appName, + packageId: this.packageId, + })); + + const response = await fetch(targetUrl, { + method: 'POST', + headers: { + 'X-API-Key': this.apiKey, + }, + body: formData, + }); + + if (!response.ok) { + const errorData = await response.json().catch(() => ({})); + throw new Error(errorData.error || `Build submission failed: ${response.status} ${response.statusText}`); + } + + const data = await response.json(); + return data.buildId; + } + + private async waitForBuild(buildId: string): Promise { + const maxWait = 10 * 60 * 1000; // 10 minutes + const pollInterval = 3000; // 3 seconds + const startTime = Date.now(); + + while (Date.now() - startTime < maxWait) { + const status = await this.getStatus(buildId); + + if (this.onProgress) { + this.onProgress(status); + } + + if (status.status === 'complete') { + const downloadUrl = `${this.buildServerUrl}/api/build/${buildId}/download?apiKey=${encodeURIComponent(this.apiKey)}`; + + return { + url: downloadUrl, + metadata: { + buildId, + type: 'apk', + appName: this.appName, + packageId: this.packageId, + apkSize: status.apkSize, + }, + }; + } + + if (status.status === 'failed') { + throw new Error(status.error || 'APK build failed'); + } + + if (status.status === 'cancelled') { + throw new Error('APK build was cancelled'); + } + + await new Promise(resolve => setTimeout(resolve, pollInterval)); + } + + throw new Error('APK build timed out after 10 minutes'); + } + + private async getStatus(buildId: string): Promise { + const url = `${this.buildServerUrl}/api/build/${buildId}/status`; + const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url; + + const response = await fetch(targetUrl, { + method: 'GET', + headers: { + 'X-API-Key': this.apiKey, + }, + }); + + if (!response.ok) { + throw new Error(`Failed to get build status: ${response.status}`); + } + + return response.json(); + } + + private async addDirectoryToZip(dirPath: string, zip: JSZip): Promise { + try { + const entries = await this.fs.readdir(dirPath, { withFileTypes: true }); + + for (const entry of entries) { + const fullPath = `${dirPath}/${entry.name}`; + + if (entry.isDirectory()) { + const folder = zip.folder(entry.name); + if (folder) { + await this.addDirectoryToZip(fullPath, folder); + } + } else if (entry.isFile()) { + try { + const fileContent = await this.fs.readFile(fullPath); + zip.file(entry.name, fileContent); + } catch { + console.warn(`Failed to read file ${fullPath}`); + } + } + } + } catch { + console.warn(`Failed to read directory ${dirPath}`); + } + } +} diff --git a/src/lib/deploy/index.ts b/src/lib/deploy/index.ts index 24bf4795..7c87071f 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 './APKBuilderAdapter'; diff --git a/src/lib/deploy/types.ts b/src/lib/deploy/types.ts index 60222a5d..eda3d238 100644 --- a/src/lib/deploy/types.ts +++ b/src/lib/deploy/types.ts @@ -74,3 +74,25 @@ export interface DenoDeployConfig { projectName?: string; corsProxy?: string; } + +export interface APKBuilderDeployConfig { + fs: JSRuntimeFS; + /** URL of the APK build server */ + buildServerUrl: string; + /** API key for the build server */ + apiKey: string; + /** Display name of the Android app */ + appName: string; + /** Android package ID (e.g., com.example.myapp) */ + packageId: string; + /** Optional CORS proxy */ + corsProxy?: string; + /** Optional progress callback */ + onProgress?: (status: { + id: string; + status: 'queued' | 'building' | 'complete' | 'failed' | 'cancelled'; + progress: number; + error?: string; + logs?: string[]; + }) => void; +} diff --git a/src/lib/tools/ShellTool.ts b/src/lib/tools/ShellTool.ts index 93b631d7..79d92753 100644 --- a/src/lib/tools/ShellTool.ts +++ b/src/lib/tools/ShellTool.ts @@ -35,7 +35,8 @@ import { UnzipCommand, WcCommand, WhoamiCommand, - WhichCommand + WhichCommand, + ZipCommand } from "../commands"; interface ShellToolParams { @@ -98,6 +99,7 @@ export class ShellTool implements Tool { this.registerCommand(new TrCommand(fs)); this.registerCommand(new UniqCommand(fs)); this.registerCommand(new UnzipCommand(fs)); + this.registerCommand(new ZipCommand(fs)); this.registerCommand(new WcCommand(fs)); this.registerCommand(new WhoamiCommand()); diff --git a/src/pages/DeploySettings.tsx b/src/pages/DeploySettings.tsx index e25fe797..6f0be256 100644 --- a/src/pages/DeploySettings.tsx +++ b/src/pages/DeploySettings.tsx @@ -32,7 +32,7 @@ import { CSS } from '@dnd-kit/utilities'; interface PresetProvider { id: string; - type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno'; + type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'apkbuilder'; name: string; description: string; requiresNostr?: boolean; @@ -42,6 +42,7 @@ interface PresetProvider { accountIdURL?: string; organizationIdLabel?: string; organizationIdURL?: string; + buildServerUrlLabel?: string; proxy?: boolean; } @@ -201,6 +202,15 @@ const PRESET_PROVIDERS: PresetProvider[] = [ organizationIdURL: 'https://dash.deno.com/orgs', proxy: true, }, + { + id: 'apkbuilder', + type: 'apkbuilder', + name: 'APK Builder', + description: 'Build Android APKs from your web app', + buildServerUrlLabel: 'Build Server URL', + apiKeyLabel: 'API Key', + proxy: true, + }, ]; // Helper function to generate custom provider ID @@ -267,6 +277,13 @@ function getProviderUrl(provider: DeployProvider | PresetProvider): string | nul // nsite uses Rocket icon fallback return null; + case 'apkbuilder': + // For APK Builder, check for custom buildServerUrl + if ('buildServerUrl' in provider && provider.buildServerUrl) { + return provider.buildServerUrl; + } + return null; + default: return null; } @@ -320,7 +337,7 @@ export function DeploySettings() { setAddDialogOpen(true); }; - const handleAddPresetProvider = (preset: PresetProvider, apiKey: string, accountId?: string, organizationId?: string) => { + const handleAddPresetProvider = (preset: PresetProvider, apiKey: string, accountId?: string, organizationId?: string, buildServerUrl?: string) => { // For Shakespeare, just check if user is logged in if (preset.requiresNostr && !user) { return; @@ -399,6 +416,18 @@ export function DeploySettings() { organizationId: organizationId.trim(), ...(preset.proxy && { proxy: true }), }; + } else if (preset.type === 'apkbuilder') { + if (!buildServerUrl?.trim() || !apiKey?.trim()) { + return; + } + newProvider = { + id: preset.id, + name: preset.name, + type: 'apkbuilder', + buildServerUrl: buildServerUrl.trim(), + apiKey: apiKey.trim(), + ...(preset.proxy && { proxy: true }), + }; } else { return; // Unknown type } @@ -536,8 +565,8 @@ export function DeploySettings() { onSetForceManualEntry={(force) => setForceManualEntry(prev => ({ ...prev, [selectedPreset.id]: force })) } - onAdd={(apiKey, accountId, organizationId) => - handleAddPresetProvider(selectedPreset, apiKey, accountId, organizationId) + onAdd={(apiKey, accountId, organizationId, buildServerUrl) => + handleAddPresetProvider(selectedPreset, apiKey, accountId, organizationId, buildServerUrl) } /> )}