smoonb 0.0.7 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,375 +1,149 @@
1
- /**
2
- * Comando de gerenciamento de Edge Functions
3
- * Deploy via Supabase CLI
4
- */
5
-
1
+ const { Command } = require('commander');
6
2
  const chalk = require('chalk');
7
- const { execSync } = require('child_process');
8
- const fs = require('fs');
9
- const path = require('path');
10
-
11
- /**
12
- * Gerenciamento de Edge Functions
13
- * Resolve o problema: Edge Functions ficam fora da database
14
- */
15
- async function functionsCommand(options) {
16
- console.log(chalk.red.bold('🚀 smoonb - EXPERIMENTAL VERSION'));
17
- console.log(chalk.red.bold('⚠️ VERSÃO EXPERIMENTAL - NUNCA TESTADA EM PRODUÇÃO!'));
18
- console.log(chalk.red.bold('🚨 USE POR SUA CONTA E RISCO - Pode causar perda de dados!'));
19
- console.log(chalk.red.bold('❌ NÃO NOS RESPONSABILIZAMOS por qualquer perda de dados!\n'));
20
-
21
- console.log(chalk.cyan.bold('⚡ Gerenciamento de Edge Functions...\n'));
22
-
23
- try {
24
- const args = process.argv.slice(3); // Remover 'smoonb', 'functions'
3
+ const { ensureBin, runCommand } = require('../utils/cli');
4
+ const { readConfig, validateFor } = require('../utils/config');
5
+ const { showBetaBanner } = require('../index');
6
+
7
+ const functionsCommand = new Command('functions')
8
+ .description('Gerenciar Edge Functions do Supabase')
9
+ .action(async () => {
10
+ showBetaBanner();
25
11
 
26
- if (args.length === 0) {
27
- showFunctionsHelp();
28
- return;
29
- }
30
-
31
- const action = args[0];
32
-
33
- switch (action) {
34
- case 'push':
35
- await pushFunctions(options);
36
- break;
37
- case 'pull':
38
- await pullFunctions(options);
39
- break;
40
- case 'list':
41
- await listFunctions(options);
42
- break;
43
- case 'backup':
44
- await backupFunctions(options);
45
- break;
46
- case 'restore':
47
- await restoreFunctions(options);
48
- break;
49
- default:
50
- console.error(chalk.red.bold('❌ Ação não reconhecida:'), action);
51
- showFunctionsHelp();
12
+ try {
13
+ // Verificar se Supabase CLI está disponível
14
+ const supabasePath = await ensureBin('supabase');
15
+ if (!supabasePath) {
16
+ console.error(chalk.red('❌ Supabase CLI não encontrado'));
17
+ console.log(chalk.yellow('💡 Instale o Supabase CLI:'));
18
+ console.log(chalk.yellow(' npm install -g supabase'));
19
+ console.log(chalk.yellow(' ou visite: https://supabase.com/docs/guides/cli'));
52
20
  process.exit(1);
53
- }
54
-
55
- } catch (error) {
56
- console.error(chalk.red.bold('❌ Erro durante o gerenciamento de functions:'), error.message);
57
- process.exit(1);
58
- }
59
- }
60
-
61
- /**
62
- * Deploy de Edge Functions via Supabase CLI
63
- */
64
- async function pushFunctions(options) {
65
- console.log(chalk.blue.bold('🚀 Deploy de Edge Functions...\n'));
66
-
67
- try {
68
- // Verificar se Supabase CLI está instalado
69
- if (!await checkSupabaseCLI()) {
70
- return;
71
- }
72
-
73
- // Verificar se existe pasta supabase/functions
74
- const functionsDir = 'supabase/functions';
75
- if (!fs.existsSync(functionsDir)) {
76
- console.log(chalk.yellow('⚠️ Pasta supabase/functions não encontrada'));
77
- console.log(chalk.gray(' - Crie a estrutura: mkdir -p supabase/functions'));
78
- console.log(chalk.gray(' - Ou use "smoonb functions pull" para baixar functions existentes'));
79
- return;
80
- }
21
+ }
81
22
 
82
- // Listar functions locais
83
- const localFunctions = fs.readdirSync(functionsDir, { withFileTypes: true })
84
- .filter(dirent => dirent.isDirectory())
85
- .map(dirent => dirent.name);
23
+ console.log(chalk.blue('⚡ Comandos disponíveis para Edge Functions:'));
24
+ console.log(chalk.yellow('\n📋 Listar functions:'));
25
+ console.log(chalk.gray(' npx smoonb functions list'));
26
+ console.log(chalk.yellow('\n🚀 Deploy functions:'));
27
+ console.log(chalk.gray(' npx smoonb functions push'));
28
+ console.log(chalk.yellow('\n📥 Pull functions (se disponível):'));
29
+ console.log(chalk.gray(' npx smoonb functions pull'));
30
+ console.log(chalk.yellow('\n💡 Para mais opções, use o Supabase CLI diretamente:'));
31
+ console.log(chalk.gray(' supabase functions --help'));
86
32
 
87
- if (localFunctions.length === 0) {
88
- console.log(chalk.yellow('⚠️ Nenhuma Edge Function encontrada em supabase/functions'));
89
- return;
33
+ } catch (error) {
34
+ console.error(chalk.red(`❌ Erro: ${error.message}`));
35
+ process.exit(1);
90
36
  }
37
+ });
91
38
 
92
- console.log(chalk.gray(' - Functions locais encontradas:'));
93
- localFunctions.forEach(func => {
94
- console.log(chalk.gray(` • ${func}`));
95
- });
96
-
97
- // Deploy via Supabase CLI
98
- console.log(chalk.gray('\n - Executando deploy via Supabase CLI...'));
39
+ // Subcomando para listar functions
40
+ functionsCommand
41
+ .command('list')
42
+ .description('Listar Edge Functions do projeto')
43
+ .action(async () => {
44
+ showBetaBanner();
99
45
 
100
46
  try {
101
- const deployCmd = 'supabase functions deploy';
102
- execSync(deployCmd, { stdio: 'inherit' });
103
-
104
- console.log(chalk.green(' Edge Functions deployadas com sucesso!'));
105
- console.log(chalk.blue('🔢 Functions deployadas:'), localFunctions.length);
106
-
107
- } catch (error) {
108
- console.log(chalk.yellow('⚠️ Deploy falhou (projeto não configurado)'));
109
- console.log(chalk.gray(' - Configure o projeto: supabase link --project-ref <project-id>'));
110
- console.log(chalk.gray(' - Ou use: smoonb config --init'));
111
- }
112
-
113
- } catch (error) {
114
- console.error(chalk.red.bold('❌ Erro durante deploy de functions:'), error.message);
115
- throw error;
116
- }
117
- }
118
-
119
- /**
120
- * Baixar Edge Functions do projeto remoto
121
- */
122
- async function pullFunctions(options) {
123
- console.log(chalk.blue.bold('📥 Baixando Edge Functions do projeto...\n'));
47
+ const config = await readConfig();
48
+ validateFor(config, 'inventory');
49
+
50
+ console.log(chalk.blue('📋 Listando Edge Functions...'));
51
+
52
+ const { stdout, stderr } = await runCommand(
53
+ 'supabase functions list',
54
+ {
55
+ env: {
56
+ ...process.env,
57
+ SUPABASE_ACCESS_TOKEN: config.supabase.serviceKey
58
+ }
59
+ }
60
+ );
124
61
 
125
- try {
126
- // Verificar se Supabase CLI está instalado
127
- if (!await checkSupabaseCLI()) {
128
- return;
129
- }
62
+ if (stderr && !stderr.includes('WARN')) {
63
+ console.log(chalk.yellow(`⚠️ Avisos: ${stderr}`));
64
+ }
130
65
 
131
- // Criar estrutura de pastas se não existir
132
- const functionsDir = 'supabase/functions';
133
- if (!fs.existsSync(functionsDir)) {
134
- await fs.promises.mkdir(functionsDir, { recursive: true });
135
- console.log(chalk.gray(' - Pasta supabase/functions criada'));
136
- }
66
+ console.log(chalk.green('✅ Edge Functions listadas:'));
67
+ console.log(stdout);
137
68
 
138
- // Listar functions remotas
139
- console.log(chalk.gray(' - Listando functions remotas...'));
69
+ } catch (error) {
70
+ console.error(chalk.red(`❌ Erro ao listar functions: ${error.message}`));
71
+ process.exit(1);
72
+ }
73
+ });
74
+
75
+ // Subcomando para deploy de functions
76
+ functionsCommand
77
+ .command('push')
78
+ .description('Fazer deploy das Edge Functions')
79
+ .option('--project-ref <ref>', 'ID do projeto Supabase')
80
+ .action(async (options) => {
81
+ showBetaBanner();
140
82
 
141
83
  try {
142
- const listCmd = 'supabase functions list';
143
- const output = execSync(listCmd, { encoding: 'utf8', stdio: 'pipe' });
144
-
145
- if (output.trim()) {
146
- console.log(chalk.gray(' - Functions remotas encontradas:'));
147
- console.log(chalk.gray(output));
148
- } else {
149
- console.log(chalk.yellow('⚠️ Nenhuma Edge Function encontrada no projeto remoto'));
150
- return;
151
- }
152
-
153
- } catch (error) {
154
- console.log(chalk.yellow('⚠️ Não foi possível listar functions remotas'));
155
- console.log(chalk.gray(' - Configure o projeto: supabase link --project-ref <project-id>'));
156
- return;
157
- }
158
-
159
- // TODO: Implementar download real das functions
160
- console.log(chalk.yellow('⚠️ Download de functions remotas em desenvolvimento'));
161
- console.log(chalk.gray(' - Use o Supabase CLI diretamente para baixar functions específicas'));
162
-
163
- } catch (error) {
164
- console.error(chalk.red.bold('❌ Erro durante pull de functions:'), error.message);
165
- throw error;
166
- }
167
- }
168
-
169
- /**
170
- * Listar Edge Functions (locais e remotas)
171
- */
172
- async function listFunctions(options) {
173
- console.log(chalk.blue.bold('📋 Listando Edge Functions...\n'));
174
-
175
- try {
176
- // Listar functions locais
177
- const functionsDir = 'supabase/functions';
178
- if (fs.existsSync(functionsDir)) {
179
- const localFunctions = fs.readdirSync(functionsDir, { withFileTypes: true })
180
- .filter(dirent => dirent.isDirectory())
181
- .map(dirent => dirent.name);
182
-
183
- console.log(chalk.green('📁 Functions Locais:'));
184
- if (localFunctions.length > 0) {
185
- localFunctions.forEach(func => {
186
- console.log(chalk.gray(` • ${func}`));
187
- });
188
- } else {
189
- console.log(chalk.gray(' (nenhuma function local encontrada)'));
190
- }
191
- } else {
192
- console.log(chalk.yellow('⚠️ Pasta supabase/functions não encontrada'));
193
- }
84
+ const config = await readConfig();
85
+ const projectRef = options.projectRef || config.supabase.projectId;
194
86
 
195
- // Listar functions remotas
196
- console.log(chalk.green('\n🌐 Functions Remotas:'));
197
- if (await checkSupabaseCLI()) {
198
- try {
199
- const listCmd = 'supabase functions list';
200
- const output = execSync(listCmd, { encoding: 'utf8', stdio: 'pipe' });
201
-
202
- if (output.trim()) {
203
- console.log(chalk.gray(output));
204
- } else {
205
- console.log(chalk.gray(' (nenhuma function remota encontrada)'));
206
- }
207
- } catch (error) {
208
- console.log(chalk.gray(' (não foi possível conectar ao projeto remoto)'));
87
+ if (!projectRef) {
88
+ console.error(chalk.red(' Project ID não encontrado'));
89
+ console.log(chalk.yellow('💡 Use: npx smoonb functions push --project-ref <id>'));
90
+ process.exit(1);
209
91
  }
210
- }
211
-
212
- } catch (error) {
213
- console.error(chalk.red.bold('❌ Erro durante listagem de functions:'), error.message);
214
- throw error;
215
- }
216
- }
217
-
218
- /**
219
- * Backup de Edge Functions locais
220
- */
221
- async function backupFunctions(options) {
222
- console.log(chalk.blue.bold('💾 Backup de Edge Functions...\n'));
223
-
224
- try {
225
- const functionsDir = 'supabase/functions';
226
- if (!fs.existsSync(functionsDir)) {
227
- console.log(chalk.yellow('⚠️ Pasta supabase/functions não encontrada'));
228
- return;
229
- }
230
-
231
- // Criar diretório de backup
232
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
233
- const backupDir = `functions-backup-${timestamp}`;
234
- await fs.promises.mkdir(backupDir, { recursive: true });
235
-
236
- // Copiar functions
237
- const localFunctions = fs.readdirSync(functionsDir, { withFileTypes: true })
238
- .filter(dirent => dirent.isDirectory())
239
- .map(dirent => dirent.name);
240
-
241
- if (localFunctions.length === 0) {
242
- console.log(chalk.yellow('⚠️ Nenhuma Edge Function encontrada para backup'));
243
- return;
244
- }
245
-
246
- console.log(chalk.gray(' - Copiando functions:'));
247
- for (const func of localFunctions) {
248
- const srcPath = path.join(functionsDir, func);
249
- const destPath = path.join(backupDir, func);
250
-
251
- // Copiar recursivamente (Windows compatible)
252
- execSync(`xcopy "${srcPath}" "${destPath}" /E /I /Y`, { stdio: 'pipe' });
253
- console.log(chalk.gray(` • ${func}`));
254
- }
255
-
256
- // Criar manifesto do backup
257
- const manifest = {
258
- timestamp: new Date().toISOString(),
259
- functions: localFunctions,
260
- count: localFunctions.length
261
- };
262
-
263
- const manifestPath = path.join(backupDir, 'functions-manifest.json');
264
- await fs.promises.writeFile(manifestPath, JSON.stringify(manifest, null, 2));
265
92
 
266
- console.log(chalk.green('✅ Backup de Edge Functions concluído!'));
267
- console.log(chalk.blue('📁 Diretório:'), backupDir);
268
- console.log(chalk.blue('🔢 Functions backupadas:'), localFunctions.length);
93
+ console.log(chalk.blue(`🚀 Fazendo deploy das Edge Functions para: ${projectRef}`));
269
94
 
270
- } catch (error) {
271
- console.error(chalk.red.bold('❌ Erro durante backup de functions:'), error.message);
272
- throw error;
273
- }
274
- }
275
-
276
- /**
277
- * Restaurar Edge Functions de backup
278
- */
279
- async function restoreFunctions(options) {
280
- console.log(chalk.blue.bold('🔄 Restaurando Edge Functions...\n'));
281
-
282
- try {
283
- // Procurar diretório de backup mais recente
284
- const backupDirs = fs.readdirSync('.')
285
- .filter(dir => dir.startsWith('functions-backup-'))
286
- .sort()
287
- .reverse();
95
+ const { stdout, stderr } = await runCommand(
96
+ `supabase functions deploy --project-ref ${projectRef}`,
97
+ {
98
+ env: {
99
+ ...process.env,
100
+ SUPABASE_ACCESS_TOKEN: config.supabase.serviceKey
101
+ }
102
+ }
103
+ );
288
104
 
289
- if (backupDirs.length === 0) {
290
- console.error(chalk.red.bold('❌ Nenhum backup de functions encontrado'));
291
- console.log(chalk.yellow('💡 Use "smoonb functions backup" primeiro'));
292
- return;
293
- }
105
+ if (stderr && !stderr.includes('WARN')) {
106
+ console.log(chalk.yellow(`⚠️ Avisos: ${stderr}`));
107
+ }
294
108
 
295
- const backupDir = backupDirs[0];
296
- console.log(chalk.gray(` - Usando backup: ${backupDir}`));
109
+ console.log(chalk.green('✅ Deploy concluído:'));
110
+ console.log(stdout);
297
111
 
298
- // Verificar manifesto
299
- const manifestPath = path.join(backupDir, 'functions-manifest.json');
300
- let manifest = null;
301
- if (fs.existsSync(manifestPath)) {
302
- const manifestContent = await fs.promises.readFile(manifestPath, 'utf8');
303
- manifest = JSON.parse(manifestContent);
304
- console.log(chalk.gray(` - Backup de: ${manifest.timestamp}`));
305
- console.log(chalk.gray(` - Functions: ${manifest.count}`));
306
- }
112
+ } catch (error) {
113
+ console.error(chalk.red(`❌ Erro no deploy: ${error.message}`));
114
+ process.exit(1);
115
+ }
116
+ });
117
+
118
+ // Subcomando para pull de functions
119
+ functionsCommand
120
+ .command('pull')
121
+ .description('Baixar Edge Functions do projeto remoto')
122
+ .option('--project-ref <ref>', 'ID do projeto Supabase')
123
+ .action(async (options) => {
124
+ showBetaBanner();
125
+
126
+ try {
127
+ const config = await readConfig();
128
+ const projectRef = options.projectRef || config.supabase.projectId;
307
129
 
308
- // Criar pasta de destino
309
- const functionsDir = 'supabase/functions';
310
- if (!fs.existsSync(functionsDir)) {
311
- await fs.promises.mkdir(functionsDir, { recursive: true });
312
- }
130
+ if (!projectRef) {
131
+ console.error(chalk.red('❌ Project ID não encontrado'));
132
+ console.log(chalk.yellow('💡 Use: npx smoonb functions pull --project-ref <id>'));
133
+ process.exit(1);
134
+ }
313
135
 
314
- // Restaurar functions
315
- const functions = fs.readdirSync(backupDir, { withFileTypes: true })
316
- .filter(dirent => dirent.isDirectory())
317
- .map(dirent => dirent.name);
136
+ console.log(chalk.yellow('⚠️ Pull de Edge Functions não é oficialmente suportado pelo Supabase CLI'));
137
+ console.log(chalk.yellow('💡 Para baixar código das functions remotas:'));
138
+ console.log(chalk.gray(' 1. Use o Dashboard do Supabase'));
139
+ console.log(chalk.gray(' 2. Ou clone o código do seu repositório Git'));
140
+ console.log(chalk.gray(' 3. Ou use a API do Supabase diretamente'));
141
+ console.log(chalk.blue('\n📚 Documentação: https://supabase.com/docs/guides/functions'));
318
142
 
319
- console.log(chalk.gray(' - Restaurando functions:'));
320
- for (const func of functions) {
321
- const srcPath = path.join(backupDir, func);
322
- const destPath = path.join(functionsDir, func);
323
-
324
- // Copiar recursivamente (Windows compatible)
325
- execSync(`xcopy "${srcPath}" "${destPath}" /E /I /Y`, { stdio: 'pipe' });
326
- console.log(chalk.gray(` • ${func}`));
143
+ } catch (error) {
144
+ console.error(chalk.red(`❌ Erro: ${error.message}`));
145
+ process.exit(1);
327
146
  }
147
+ });
328
148
 
329
- console.log(chalk.green('✅ Edge Functions restauradas com sucesso!'));
330
- console.log(chalk.blue('📁 Destino:'), functionsDir);
331
- console.log(chalk.blue('🔢 Functions restauradas:'), functions.length);
332
- console.log(chalk.yellow('\n💡 Use "smoonb functions push" para deployar as functions'));
333
-
334
- } catch (error) {
335
- console.error(chalk.red.bold('❌ Erro durante restauração de functions:'), error.message);
336
- throw error;
337
- }
338
- }
339
-
340
- /**
341
- * Verificar se Supabase CLI está instalado
342
- */
343
- async function checkSupabaseCLI() {
344
- try {
345
- execSync('supabase --version', { stdio: 'pipe' });
346
- return true;
347
- } catch (error) {
348
- console.log(chalk.yellow('⚠️ Supabase CLI não encontrado'));
349
- console.log(chalk.gray(' - Instale: npm install -g supabase'));
350
- console.log(chalk.gray(' - Ou: https://supabase.com/docs/guides/cli/getting-started'));
351
- return false;
352
- }
353
- }
354
-
355
- /**
356
- * Mostrar ajuda do comando functions
357
- */
358
- function showFunctionsHelp() {
359
- console.log(chalk.cyan.bold('⚡ Comandos de Edge Functions disponíveis:\n'));
360
- console.log(chalk.cyan(' push'), chalk.gray(' - Deploy de Edge Functions via Supabase CLI'));
361
- console.log(chalk.cyan(' pull'), chalk.gray(' - Baixar Edge Functions do projeto remoto'));
362
- console.log(chalk.cyan(' list'), chalk.gray(' - Listar Edge Functions (locais e remotas)'));
363
- console.log(chalk.cyan(' backup'), chalk.gray(' - Backup de Edge Functions locais'));
364
- console.log(chalk.cyan(' restore'), chalk.gray(' - Restaurar Edge Functions de backup'));
365
- console.log(chalk.yellow('\n💡 Exemplos:'));
366
- console.log(chalk.gray(' smoonb functions push'));
367
- console.log(chalk.gray(' smoonb functions list'));
368
- console.log(chalk.gray(' smoonb functions backup'));
369
- console.log(chalk.gray(' smoonb functions restore'));
370
- console.log(chalk.yellow('\n📋 Pré-requisitos:'));
371
- console.log(chalk.gray(' - Supabase CLI instalado: npm install -g supabase'));
372
- console.log(chalk.gray(' - Projeto configurado: supabase link --project-ref <project-id>'));
373
- }
374
-
375
- module.exports = functionsCommand;
149
+ module.exports = functionsCommand;