-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathindex.ts
More file actions
213 lines (188 loc) · 6.94 KB
/
index.ts
File metadata and controls
213 lines (188 loc) · 6.94 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
import { type Command } from 'commander';
import chalk from 'chalk';
import { intro, log, outro } from '@clack/prompts';
import path from 'path';
import fs from 'fs';
// Default Supabase local development publishable key (same for all local projects)
const DEFAULT_PUBLISHABLE_KEY = 'sb_publishable_ACJWlzQHlZjBrEguHvfOxg_3BJgxAaH';
/**
* Fetch flow SQL from ControlPlane HTTP endpoint
*/
export async function fetchFlowSQL(
flowSlug: string,
controlPlaneUrl: string,
publishableKey: string
): Promise<{ flowSlug: string; sql: string[] }> {
const url = `${controlPlaneUrl}/flows/${flowSlug}`;
try {
const response = await fetch(url, {
headers: {
'Authorization': `Bearer ${publishableKey}`,
'apikey': publishableKey,
'Content-Type': 'application/json',
},
});
if (response.status === 404) {
const errorData = await response.json();
throw new Error(
`Flow '${flowSlug}' not found.\n\n` +
`${errorData.message || 'Did you add it to supabase/functions/pgflow/index.ts?'}\n\n` +
`Fix:\n` +
`1. Add your flow to supabase/functions/pgflow/index.ts\n` +
`2. Restart edge functions: supabase functions serve`
);
}
if (!response.ok) {
const errorText = await response.text();
throw new Error(`HTTP ${response.status}: ${errorText}`);
}
return await response.json();
} catch (error) {
if (error instanceof Error) {
// Check for connection refused errors
if (
error.message.includes('ECONNREFUSED') ||
error.message.includes('fetch failed')
) {
throw new Error(
'Could not connect to ControlPlane.\n\n' +
'Fix options:\n' +
'1. Start Supabase: supabase start\n' +
'2. Start edge functions: supabase functions serve\n\n' +
'Or use previous version: npx pgflow@0.8.0 compile path/to/flow.ts'
);
}
throw error;
}
throw new Error(`Unknown error: ${String(error)}`);
}
}
export default (program: Command) => {
program
.command('compile')
.description('Compiles a flow into SQL migration via ControlPlane HTTP')
.argument('<flowSlug>', 'Flow slug to compile (e.g., my_flow)')
.option(
'--deno-json <denoJsonPath>',
'[DEPRECATED] No longer used. Will be removed in v1.0'
)
.option('--supabase-path <supabasePath>', 'Path to the Supabase folder')
.option(
'--control-plane-url <url>',
'Control plane URL',
'http://127.0.0.1:54321/functions/v1/pgflow'
)
.option(
'--publishable-key <key>',
'Supabase publishable key (legacy anon keys also work)',
DEFAULT_PUBLISHABLE_KEY
)
.action(async (flowSlug, options) => {
intro('pgflow - Compile Flow to SQL');
try {
// Show deprecation warning for --deno-json
if (options.denoJson) {
log.warn(
'The --deno-json flag is deprecated and no longer used.\n' +
'Flow compilation now happens via HTTP, not local Deno.\n' +
'This flag will be removed in v1.0'
);
}
// Validate Supabase path
let supabasePath: string;
if (options.supabasePath) {
supabasePath = path.resolve(process.cwd(), options.supabasePath);
} else {
// Default to ./supabase/ if not provided
supabasePath = path.resolve(process.cwd(), 'supabase');
}
// Check if Supabase path exists
if (!fs.existsSync(supabasePath)) {
log.error(
`Supabase directory not found: ${supabasePath}\n` +
`Please provide a valid Supabase path using --supabase-path option or ensure ./supabase/ directory exists.`
);
process.exit(1);
}
// Create migrations directory if it doesn't exist
const migrationsDir = path.resolve(supabasePath, 'migrations');
if (!fs.existsSync(migrationsDir)) {
fs.mkdirSync(migrationsDir, { recursive: true });
log.success(`Created migrations directory: ${migrationsDir}`);
}
// Check for existing migrations
const existingMigrations = fs
.readdirSync(migrationsDir)
.filter((file) => file.endsWith(`_create_${flowSlug}_flow.sql`));
if (existingMigrations.length > 0) {
log.warn(
`Found existing migration(s) for '${flowSlug}':\n` +
existingMigrations.map((f) => ` ${f}`).join('\n') +
'\nCreating new migration anyway...'
);
}
// Fetch flow SQL from ControlPlane
log.info(`Compiling flow: ${flowSlug}`);
const result = await fetchFlowSQL(
flowSlug,
options.controlPlaneUrl,
options.publishableKey
);
// Validate result
if (!result.sql || result.sql.length === 0) {
throw new Error('ControlPlane returned empty SQL');
}
// Join SQL statements
const compiledSql = result.sql.join('\n') + '\n';
// Generate timestamp for migration file in format YYYYMMDDHHMMSS using UTC
const now = new Date();
const timestamp = [
now.getUTCFullYear(),
String(now.getUTCMonth() + 1).padStart(2, '0'),
String(now.getUTCDate()).padStart(2, '0'),
String(now.getUTCHours()).padStart(2, '0'),
String(now.getUTCMinutes()).padStart(2, '0'),
String(now.getUTCSeconds()).padStart(2, '0'),
].join('');
// Create migration filename in the format: <timestamp>_create_<flow_slug>_flow.sql
const migrationFileName = `${timestamp}_create_${flowSlug}_flow.sql`;
const migrationFilePath = path.join(migrationsDir, migrationFileName);
// Write the SQL to a migration file
fs.writeFileSync(migrationFilePath, compiledSql);
// Show the migration file path relative to the current directory
const relativeFilePath = path.relative(
process.cwd(),
migrationFilePath
);
log.success(`Migration file created: ${relativeFilePath}`);
// Display next steps with outro
outro(
[
chalk.bold('Flow compilation completed successfully!'),
'',
`- Run ${chalk.cyan('supabase migration up')} to apply the migration`,
'',
chalk.bold('Continue the setup:'),
chalk.blue.underline('https://pgflow.dev/getting-started/run-flow/'),
].join('\n')
);
} catch (error) {
log.error(
`Compilation failed: ${
error instanceof Error ? error.message : String(error)
}`
);
outro(
[
chalk.bold('Compilation failed!'),
'',
chalk.bold('For troubleshooting help:'),
chalk.blue.underline(
'https://pgflow.dev/getting-started/compile-to-sql/'
),
].join('\n')
);
process.exit(1);
}
});
};