pgflow 0.0.18 → 0.0.20

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.
@@ -0,0 +1,4 @@
1
+ export declare function copyMigrations({ supabasePath, }: {
2
+ supabasePath: string;
3
+ }): Promise<boolean>;
4
+ //# sourceMappingURL=copy-migrations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"copy-migrations.d.ts","sourceRoot":"","sources":["../../../src/commands/install/copy-migrations.ts"],"names":[],"mappings":"AAyEA,wBAAsB,cAAc,CAAC,EACnC,YAAY,GACb,EAAE;IACD,YAAY,EAAE,MAAM,CAAC;CACtB,GAAG,OAAO,CAAC,OAAO,CAAC,CAwFnB"}
@@ -0,0 +1,109 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { createRequire } from 'module';
4
+ import { fileURLToPath } from 'url';
5
+ import { log, confirm, note } from '@clack/prompts';
6
+ import chalk from 'chalk';
7
+ // Get the directory name in ES modules
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = path.dirname(__filename);
10
+ // Create a require function to use require.resolve
11
+ const require = createRequire(import.meta.url);
12
+ // Function to find migrations directory
13
+ function findMigrationsDirectory() {
14
+ try {
15
+ // First try: resolve from installed @pgflow/core package
16
+ const corePackageJsonPath = require.resolve('@pgflow/core/package.json');
17
+ const corePackageFolder = path.dirname(corePackageJsonPath);
18
+ const packageMigrationsPath = path.join(corePackageFolder, 'dist', 'supabase', 'migrations');
19
+ if (fs.existsSync(packageMigrationsPath)) {
20
+ return packageMigrationsPath;
21
+ }
22
+ // If that fails, try development path
23
+ log.info('Could not find migrations in installed package, trying development paths...');
24
+ }
25
+ catch (error) {
26
+ log.info('Could not resolve @pgflow/core package, trying development paths...');
27
+ }
28
+ // Try development paths
29
+ // 1. Try relative to CLI dist folder (when running built CLI)
30
+ const distRelativePath = path.resolve(__dirname, '../../../../core/supabase/migrations');
31
+ if (fs.existsSync(distRelativePath)) {
32
+ return distRelativePath;
33
+ }
34
+ // 2. Try relative to CLI source folder (when running from source)
35
+ const sourceRelativePath = path.resolve(__dirname, '../../../../../core/supabase/migrations');
36
+ if (fs.existsSync(sourceRelativePath)) {
37
+ return sourceRelativePath;
38
+ }
39
+ // 3. Try local migrations directory (for backward compatibility)
40
+ const localMigrationsPath = path.resolve(__dirname, '../../migrations');
41
+ if (fs.existsSync(localMigrationsPath)) {
42
+ return localMigrationsPath;
43
+ }
44
+ // No migrations found
45
+ return null;
46
+ }
47
+ // Find the migrations directory
48
+ const sourcePath = findMigrationsDirectory();
49
+ export async function copyMigrations({ supabasePath, }) {
50
+ const migrationsPath = path.join(supabasePath, 'migrations');
51
+ if (!fs.existsSync(migrationsPath)) {
52
+ fs.mkdirSync(migrationsPath);
53
+ }
54
+ // Check if pgflow migrations directory exists
55
+ if (!sourcePath || !fs.existsSync(sourcePath)) {
56
+ log.error(`Could not find migrations directory`);
57
+ log.info('This might happen if @pgflow/core is not properly installed or built.');
58
+ log.info('Make sure @pgflow/core is installed and contains the migrations.');
59
+ log.info('If running in development mode, try building the core package first with: nx build core');
60
+ return false;
61
+ }
62
+ const files = fs.readdirSync(sourcePath);
63
+ const filesToCopy = [];
64
+ const skippedFiles = [];
65
+ // Determine which files need to be copied
66
+ for (const file of files) {
67
+ const destination = path.join(migrationsPath, file);
68
+ if (fs.existsSync(destination)) {
69
+ skippedFiles.push(file);
70
+ }
71
+ else {
72
+ filesToCopy.push(file);
73
+ }
74
+ }
75
+ // If no files to copy, show message and return false (no changes made)
76
+ if (filesToCopy.length === 0) {
77
+ log.info('No new migrations to copy - all migrations are already in place');
78
+ return false;
79
+ }
80
+ // Prepare summary message with colored output
81
+ const summaryParts = [];
82
+ if (filesToCopy.length > 0) {
83
+ summaryParts.push(`${chalk.green('Files to be copied:')}
84
+ ${filesToCopy.map((file) => `${chalk.green('+')} ${file}`).join('\n')}`);
85
+ }
86
+ if (skippedFiles.length > 0) {
87
+ summaryParts.push(`${chalk.yellow('Files to be skipped (already exist):')}
88
+ ${skippedFiles.map((file) => `${chalk.yellow('=')} ${file}`).join('\n')}`);
89
+ }
90
+ // Show summary and ask for confirmation
91
+ note(summaryParts.join('\n\n'), 'Migration Summary');
92
+ const shouldContinue = await confirm({
93
+ message: `Do you want to proceed with copying ${filesToCopy.length} migration file${filesToCopy.length !== 1 ? 's' : ''}?`,
94
+ });
95
+ if (!shouldContinue) {
96
+ log.info('Migration copy cancelled');
97
+ return false;
98
+ }
99
+ log.info(`Copying migrations`);
100
+ // Copy the files
101
+ for (const file of filesToCopy) {
102
+ const source = path.join(sourcePath, file);
103
+ const destination = path.join(migrationsPath, file);
104
+ fs.copyFileSync(source, destination);
105
+ log.step(`Copied ${file}`);
106
+ }
107
+ log.success(`Successfully copied ${filesToCopy.length} migration file${filesToCopy.length !== 1 ? 's' : ''}`);
108
+ return true; // Return true to indicate migrations were copied
109
+ }
@@ -0,0 +1,4 @@
1
+ import { type Command } from 'commander';
2
+ declare const _default: (program: Command) => void;
3
+ export default _default;
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/commands/install/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,WAAW,CAAC;kCAMhB,OAAO;AAAhC,wBAsCE"}
@@ -0,0 +1,32 @@
1
+ import { intro, isCancel, log } from '@clack/prompts';
2
+ import { copyMigrations } from './copy-migrations.js';
3
+ import { updateConfigToml } from './update-config-toml.js';
4
+ import { supabasePathPrompt } from './supabase-path-prompt.js';
5
+ export default (program) => {
6
+ program
7
+ .command('install')
8
+ .description('Copies migrations and sets config.toml values')
9
+ .action(async () => {
10
+ intro('pgflow - Postgres-native workflows for Supabase');
11
+ const supabasePath = await supabasePathPrompt();
12
+ if (isCancel(supabasePath)) {
13
+ log.error('Aborting installation');
14
+ return;
15
+ }
16
+ const migrationsCopied = await copyMigrations({ supabasePath });
17
+ const configUpdated = await updateConfigToml({ supabasePath });
18
+ if (migrationsCopied || configUpdated) {
19
+ log.success('pgflow installation is completed');
20
+ }
21
+ if (!migrationsCopied && !configUpdated) {
22
+ log.success('No changes were made - pgflow is already properly configured.');
23
+ }
24
+ // Show specific reminders based on what was actually done
25
+ if (configUpdated) {
26
+ log.warn('Remember to restart Supabase for the configuration changes to take effect!');
27
+ }
28
+ if (migrationsCopied) {
29
+ log.warn('Remember to apply the migrations!');
30
+ }
31
+ });
32
+ };
@@ -0,0 +1,2 @@
1
+ export declare function supabasePathPrompt(): Promise<string | symbol>;
2
+ //# sourceMappingURL=supabase-path-prompt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"supabase-path-prompt.d.ts","sourceRoot":"","sources":["../../../src/commands/install/supabase-path-prompt.ts"],"names":[],"mappings":"AAIA,wBAAsB,kBAAkB,6BAMvC"}
@@ -0,0 +1,24 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { text } from '@clack/prompts';
4
+ export async function supabasePathPrompt() {
5
+ return await text({
6
+ message: 'Enter the path to your supabase/ directory',
7
+ placeholder: 'supabase/',
8
+ validate,
9
+ });
10
+ }
11
+ function validate(inputPath) {
12
+ const pathsToTest = [
13
+ [inputPath, 'is not a valid path'],
14
+ [path.join(inputPath, 'config.toml'), 'does not contain config.toml'],
15
+ ];
16
+ // if any of the pathsToTest fail, return the error message
17
+ for (const [testPath, errorMessage] of pathsToTest) {
18
+ if (!fs.existsSync(testPath)) {
19
+ return `${testPath} ${errorMessage}`;
20
+ }
21
+ }
22
+ // otherwise, return undefined
23
+ return undefined;
24
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Updates the config.toml file with necessary configurations for EdgeWorker
3
+ * while preserving comments and formatting
4
+ *
5
+ * Makes the following changes:
6
+ * 1. Enables the connection pooler
7
+ * 2. Ensures pool_mode is set to "transaction"
8
+ * 3. Changes edge_runtime policy from "oneshot" to "per_worker"
9
+ * 4. Creates a backup of the original config.toml file before making changes
10
+ *
11
+ * @param options.supabasePath - Path to the supabase directory
12
+ * @returns Promise<boolean> - True if changes were made, false otherwise
13
+ */
14
+ export declare function updateConfigToml({ supabasePath, }: {
15
+ supabasePath: string;
16
+ }): Promise<boolean>;
17
+ //# sourceMappingURL=update-config-toml.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"update-config-toml.d.ts","sourceRoot":"","sources":["../../../src/commands/install/update-config-toml.ts"],"names":[],"mappings":"AAqBA;;;;;;;;;;;;GAYG;AACH,wBAAsB,gBAAgB,CAAC,EACrC,YAAY,GACb,EAAE;IACD,YAAY,EAAE,MAAM,CAAC;CACtB,GAAG,OAAO,CAAC,OAAO,CAAC,CA6FnB"}
@@ -0,0 +1,89 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { log, confirm, note } from '@clack/prompts';
4
+ import * as TOML from 'toml-patch';
5
+ import chalk from 'chalk';
6
+ /**
7
+ * Updates the config.toml file with necessary configurations for EdgeWorker
8
+ * while preserving comments and formatting
9
+ *
10
+ * Makes the following changes:
11
+ * 1. Enables the connection pooler
12
+ * 2. Ensures pool_mode is set to "transaction"
13
+ * 3. Changes edge_runtime policy from "oneshot" to "per_worker"
14
+ * 4. Creates a backup of the original config.toml file before making changes
15
+ *
16
+ * @param options.supabasePath - Path to the supabase directory
17
+ * @returns Promise<boolean> - True if changes were made, false otherwise
18
+ */
19
+ export async function updateConfigToml({ supabasePath, }) {
20
+ const configPath = path.join(supabasePath, 'config.toml');
21
+ const backupPath = `${configPath}.backup`;
22
+ try {
23
+ if (!fs.existsSync(configPath)) {
24
+ throw new Error(`config.toml not found at ${configPath}`);
25
+ }
26
+ const configContent = fs.readFileSync(configPath, 'utf8');
27
+ const config = TOML.parse(configContent);
28
+ const currentSettings = {
29
+ poolerEnabled: config.db?.pooler?.enabled ?? false,
30
+ poolMode: config.db?.pooler?.pool_mode ?? 'none',
31
+ edgeRuntimePolicy: config.edge_runtime?.policy ?? 'oneshot',
32
+ };
33
+ const needsChanges = currentSettings.poolerEnabled !== true ||
34
+ currentSettings.poolMode !== 'transaction' ||
35
+ currentSettings.edgeRuntimePolicy !== 'per_worker';
36
+ if (!needsChanges) {
37
+ log.info(`No changes needed in config.toml - all required settings are already configured`);
38
+ return false;
39
+ }
40
+ const changes = [];
41
+ if (currentSettings.poolerEnabled !== true) {
42
+ changes.push(`[db.pooler]
43
+ ${chalk.red(`- enabled = ${currentSettings.poolerEnabled}`)}
44
+ ${chalk.green('+ enabled = true')}`);
45
+ }
46
+ if (currentSettings.poolMode !== 'transaction') {
47
+ changes.push(`[db.pooler]
48
+ ${chalk.red(`- pool_mode = "${currentSettings.poolMode}"`)}
49
+ ${chalk.green('+ pool_mode = "transaction"')}`);
50
+ }
51
+ if (currentSettings.edgeRuntimePolicy !== 'per_worker') {
52
+ changes.push(`[edge_runtime]
53
+ ${chalk.red(`- policy = "${currentSettings.edgeRuntimePolicy}"`)}
54
+ ${chalk.green('+ policy = "per_worker"')}`);
55
+ }
56
+ note(changes.join('\n\n'), 'Config Changes');
57
+ const shouldContinue = await confirm({
58
+ message: `Do you want to proceed with these configuration changes? A backup will be created at ${backupPath}`,
59
+ });
60
+ if (!shouldContinue) {
61
+ log.info('Configuration update cancelled');
62
+ return false;
63
+ }
64
+ fs.copyFileSync(configPath, backupPath);
65
+ log.info(`Created backup at ${backupPath}`);
66
+ log.info(`Updating config.toml`);
67
+ const updatedConfig = { ...config };
68
+ // Ensure required objects exist and set values
69
+ if (!updatedConfig.db)
70
+ updatedConfig.db = {};
71
+ if (!updatedConfig.db.pooler)
72
+ updatedConfig.db.pooler = {};
73
+ if (!updatedConfig.edge_runtime)
74
+ updatedConfig.edge_runtime = {};
75
+ updatedConfig.db.pooler.enabled = true;
76
+ updatedConfig.db.pooler.pool_mode = 'transaction';
77
+ updatedConfig.edge_runtime.policy = 'per_worker';
78
+ const updatedContent = TOML.patch(configContent, updatedConfig, {
79
+ trailingComma: false,
80
+ });
81
+ fs.writeFileSync(configPath, updatedContent);
82
+ log.success(`Successfully updated ${configPath} (backup created at ${backupPath})`);
83
+ return true;
84
+ }
85
+ catch (error) {
86
+ log.error(`Failed to update ${configPath}: ${error instanceof Error ? error.message : String(error)}`);
87
+ throw error;
88
+ }
89
+ }
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""}
package/dist/index.js ADDED
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import { fileURLToPath } from 'url';
4
+ import { readFileSync } from 'fs';
5
+ import { dirname, join } from 'path';
6
+ import installCommand from './commands/install/index.js';
7
+ // Create a function to handle errors
8
+ const errorHandler = (error) => {
9
+ console.error('Error:', error instanceof Error ? error.message : String(error));
10
+ process.exit(1);
11
+ };
12
+ // Set up process-wide unhandled rejection handler
13
+ process.on('unhandledRejection', errorHandler);
14
+ // Function to get version from package.json
15
+ function getVersion() {
16
+ const __filename = fileURLToPath(import.meta.url);
17
+ const __dirname = dirname(__filename);
18
+ const packageJsonPath = join(__dirname, '..', 'package.json');
19
+ try {
20
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
21
+ return packageJson.version || 'unknown';
22
+ }
23
+ catch (error) {
24
+ // Log error but don't display it to the user when showing version
25
+ console.error('Error reading package.json:', error);
26
+ return 'unknown';
27
+ }
28
+ }
29
+ const program = new Command();
30
+ program
31
+ .name('npx pgflow')
32
+ .description('Command line interface to help you work with pgflow')
33
+ .version(getVersion())
34
+ .exitOverride((err) => {
35
+ // Don't treat version display as an error
36
+ if (err.code === 'commander.version') {
37
+ process.exit(0);
38
+ }
39
+ throw err;
40
+ });
41
+ installCommand(program);
42
+ // Use a promise-aware approach to parse arguments
43
+ async function main() {
44
+ try {
45
+ await program.parseAsync(process.argv);
46
+ // If we get here with no command specified, it's not an error
47
+ process.exitCode = 0;
48
+ }
49
+ catch (err) {
50
+ // Commander throws a CommanderError when help or version is displayed
51
+ // We want to exit with code 0 in these cases
52
+ if (err &&
53
+ typeof err === 'object' &&
54
+ 'code' in err &&
55
+ (err.code === 'commander.helpDisplayed' ||
56
+ err.code === 'commander.help' ||
57
+ err.code === 'commander.version')) {
58
+ process.exitCode = 0;
59
+ }
60
+ else {
61
+ // For other errors, use our error handler
62
+ errorHandler(err);
63
+ }
64
+ }
65
+ }
66
+ // Execute and handle any errors
67
+ main();
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "pgflow",
3
+ "version": "0.0.19",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "typings": "./dist/index.d.ts",
7
+ "bin": "./dist/index.js",
8
+ "exports": {
9
+ "./package.json": "./package.json",
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "types": "./dist/index.d.ts",
16
+ "module": "./dist/index.js",
17
+ "devDependencies": {
18
+ "@types/node": "^22.14.1",
19
+ "tsx": "^4.19.3"
20
+ },
21
+ "dependencies": {
22
+ "@clack/prompts": "^0.10.1",
23
+ "@commander-js/extra-typings": "^13.1.0",
24
+ "@pgflow/core": "workspace:*",
25
+ "chalk": "^5.4.1",
26
+ "commander": "^13.1.0",
27
+ "toml-patch": "^0.2.3"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public",
31
+ "directory": "."
32
+ },
33
+ "files": [
34
+ "dist"
35
+ ],
36
+ "scripts": {
37
+ "postinstall": "chmod +x dist/index.js || true"
38
+ }
39
+ }
@@ -0,0 +1 @@
1
+ {"version":"5.6.3"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pgflow",
3
- "version": "0.0.18",
3
+ "version": "0.0.20",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "typings": "./dist/index.d.ts",
@@ -23,7 +23,8 @@
23
23
  "@commander-js/extra-typings": "^13.1.0",
24
24
  "chalk": "^5.4.1",
25
25
  "commander": "^13.1.0",
26
- "toml-patch": "^0.2.3"
26
+ "toml-patch": "^0.2.3",
27
+ "@pgflow/core": "0.0.20"
27
28
  },
28
29
  "publishConfig": {
29
30
  "access": "public",