-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.js
More file actions
235 lines (199 loc) · 7.31 KB
/
Copy pathgithub.js
File metadata and controls
235 lines (199 loc) · 7.31 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
/**
* GitHub Integration Module
* Handles repository creation and commits from the frontend
*/
import { state, supabase } from './state.js';
import { showToast } from './utils.js';
import { devLog, devError } from './thinking.js';
/**
* Check if the API returned an error indicating it's not available
* This handles both dev environments (vite without vercel) and production issues
*/
function isApiUnavailableError(error) {
const msg = error?.message?.toLowerCase() || '';
return msg.includes('failed to fetch') ||
msg.includes('network error') ||
msg.includes('404') ||
msg.includes('function_invocation_failed');
}
/**
* Create a GitHub repository for a project
*/
export async function createGitHubRepo(projectId, name) {
devLog('Creating GitHub repo for project:', projectId, name);
const session = await supabase.auth.getSession();
const accessToken = session.data.session?.access_token;
if (!accessToken) {
devError('No access token for GitHub repo creation');
throw new Error('Not authenticated');
}
const response = await fetch('/api/github/create-repo', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
},
body: JSON.stringify({ projectId, name })
});
// Handle non-JSON responses (e.g., server errors)
let data;
try {
const text = await response.text();
data = text ? JSON.parse(text) : {};
} catch (parseError) {
devError('Failed to parse GitHub API response:', parseError);
throw new Error('Invalid response from GitHub API');
}
if (!response.ok) {
devError('GitHub repo creation failed:', data);
throw new Error(data.error || `Failed to create repository (HTTP ${response.status})`);
}
devLog('GitHub repo created:', data);
return data;
}
/**
* Commit files to a project's GitHub repository
*/
export async function commitToGitHub(projectId, files, message) {
devLog('Committing to GitHub:', projectId, files.length, 'files');
const session = await supabase.auth.getSession();
const accessToken = session.data.session?.access_token;
if (!accessToken) {
devError('No access token for GitHub commit');
throw new Error('Not authenticated');
}
const response = await fetch('/api/github/commit', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
},
body: JSON.stringify({ projectId, files, message })
});
// Handle non-JSON responses (e.g., server errors)
let data;
try {
const text = await response.text();
data = text ? JSON.parse(text) : {};
} catch (parseError) {
devError('Failed to parse GitHub commit response:', parseError);
throw new Error('Invalid response from GitHub API');
}
if (!response.ok) {
devError('GitHub commit failed:', data);
throw new Error(data.error || `Failed to commit (HTTP ${response.status})`);
}
devLog('GitHub commit successful:', data);
return data;
}
/**
* Convert SimpleSim file format to GitHub-compatible format
* Handles both array format [{path, content}] and object format {html, css, js}
*/
export function convertFilesForGitHub(files) {
devLog('Converting files for GitHub:', files);
// If it's already an array of {path, content}, return as-is
if (Array.isArray(files)) {
return files.map(f => ({
path: f.path,
content: f.content
}));
}
// Legacy object format {html, css, js}
const result = [];
if (files.html) {
result.push({ path: 'index.html', content: files.html });
}
if (files.css) {
result.push({ path: 'styles.css', content: files.css });
}
if (files.js) {
result.push({ path: 'script.js', content: files.js });
}
// Any additional files
if (files.additional && typeof files.additional === 'object') {
Object.entries(files.additional).forEach(([filename, content]) => {
result.push({ path: filename, content });
});
}
return result;
}
/**
* Auto-create repo for a new project if enabled in settings
*/
export async function autoCreateRepoIfEnabled(projectId, projectName) {
const autoCreate = localStorage.getItem('github_auto_create') === 'true';
devLog('Auto-create repo check:', { autoCreate, projectId, projectName });
if (!autoCreate) {
devLog('Auto-create repo disabled, skipping');
return null;
}
try {
const result = await createGitHubRepo(projectId, projectName);
showToast(`GitHub repo created: ${result.full_name}`);
return result;
} catch (error) {
devError('Auto-create repo failed:', error);
// Skip silently if API is unavailable (e.g., running vite dev without vercel)
if (!isApiUnavailableError(error)) {
showToast(`GitHub repo failed: ${error.message}`);
}
return null;
}
}
/**
* Auto-commit to GitHub after version creation
* If auto-sync is enabled and no repo exists, create one first
*/
export async function autoCommitIfLinked(projectId, files, prompt) {
const autoSync = localStorage.getItem('github_auto_sync') === 'true';
devLog('Auto-sync check:', { autoSync, projectId, filesCount: files?.length || 0 });
if (!autoSync) {
devLog('Auto-sync disabled, skipping');
return null;
}
// Check if project has a GitHub repo
const { data: project, error } = await supabase
.from('projects')
.select('github_repo, name')
.eq('id', projectId)
.single();
if (error) {
devError('Failed to check project GitHub link:', error);
return null;
}
let repoName = project?.github_repo;
// If no repo exists but auto-sync is enabled, create one
if (!repoName) {
devLog('No GitHub repo linked, creating one...');
try {
const projectName = project?.name || `simplesim-project-${projectId.slice(0, 8)}`;
const repoResult = await createGitHubRepo(projectId, projectName);
if (repoResult?.full_name) {
repoName = repoResult.full_name;
showToast(`GitHub repo created: ${repoName}`);
devLog('GitHub repo created:', repoName);
} else {
devError('Failed to create GitHub repo - no result');
return null;
}
} catch (createError) {
devError('Failed to create GitHub repo:', createError);
showToast(`GitHub repo creation failed: ${createError.message}`);
return null;
}
}
devLog('Project linked to GitHub:', repoName);
try {
const githubFiles = convertFilesForGitHub(files);
devLog('Converted files for GitHub:', githubFiles.map(f => f.path));
const message = `Update: ${prompt.slice(0, 72)}${prompt.length > 72 ? '...' : ''}`;
const result = await commitToGitHub(projectId, githubFiles, message);
showToast('Synced to GitHub');
return result;
} catch (error) {
devError('Auto-commit failed:', error);
showToast(`GitHub sync failed: ${error.message}`);
return null;
}
}