@pgpmjs/env 2.7.0

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.
package/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2025 Constructive <developers@constructive.io>
5
+ Copyright (c) 2020-present, Interweb, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,94 @@
1
+ # @launchql/env
2
+
3
+ Environment management for LaunchQL projects. Provides unified configuration resolution from defaults, config files, environment variables, and overrides.
4
+
5
+ ## Features
6
+
7
+ - Config file discovery using `walkUp` utility
8
+ - Environment variable parsing
9
+ - Unified merge hierarchy: defaults → config → env vars → overrides
10
+ - TypeScript support with full type safety
11
+
12
+ ## Usage
13
+
14
+ ```typescript
15
+ import { getEnvOptions } from '@launchql/env';
16
+
17
+ const options = getEnvOptions(overrides, cwd);
18
+ ```
19
+
20
+ ---
21
+
22
+ ## Education and Tutorials
23
+
24
+ 1. 🚀 [Quickstart: Getting Up and Running](https://constructive.io/learn/quickstart)
25
+ Get started with modular databases in minutes. Install prerequisites and deploy your first module.
26
+
27
+ 2. 📦 [Modular PostgreSQL Development with Database Packages](https://constructive.io/learn/modular-postgres)
28
+ Learn to organize PostgreSQL projects with pgpm workspaces and reusable database modules.
29
+
30
+ 3. ✏️ [Authoring Database Changes](https://constructive.io/learn/authoring-database-changes)
31
+ Master the workflow for adding, organizing, and managing database changes with pgpm.
32
+
33
+ 4. 🧪 [End-to-End PostgreSQL Testing with TypeScript](https://constructive.io/learn/e2e-postgres-testing)
34
+ Master end-to-end PostgreSQL testing with ephemeral databases, RLS testing, and CI/CD automation.
35
+
36
+ 5. ⚡ [Supabase Testing](https://constructive.io/learn/supabase)
37
+ Use TypeScript-first tools to test Supabase projects with realistic RLS, policies, and auth contexts.
38
+
39
+ 6. 💧 [Drizzle ORM Testing](https://constructive.io/learn/drizzle-testing)
40
+ Run full-stack tests with Drizzle ORM, including database setup, teardown, and RLS enforcement.
41
+
42
+ 7. 🔧 [Troubleshooting](https://constructive.io/learn/troubleshooting)
43
+ Common issues and solutions for pgpm, PostgreSQL, and testing.
44
+
45
+ ## Related Constructive Tooling
46
+
47
+ ### 🧪 Testing
48
+
49
+ * [pgsql-test](https://github.com/constructive-io/constructive/tree/main/packages/pgsql-test): **📊 Isolated testing environments** with per-test transaction rollbacks—ideal for integration tests, complex migrations, and RLS simulation.
50
+ * [supabase-test](https://github.com/constructive-io/constructive/tree/main/packages/supabase-test): **🧪 Supabase-native test harness** preconfigured for the local Supabase stack—per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
51
+ * [graphile-test](https://github.com/constructive-io/constructive/tree/main/packages/graphile-test): **🔐 Authentication mocking** for Graphile-focused test helpers and emulating row-level security contexts.
52
+ * [pg-query-context](https://github.com/constructive-io/constructive/tree/main/packages/pg-query-context): **🔒 Session context injection** to add session-local context (e.g., `SET LOCAL`) into queries—ideal for setting `role`, `jwt.claims`, and other session settings.
53
+
54
+ ### 🧠 Parsing & AST
55
+
56
+ * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **🔄 SQL conversion engine** that interprets and converts PostgreSQL syntax.
57
+ * [libpg-query-node](https://www.npmjs.com/package/libpg-query): **🌉 Node.js bindings** for `libpg_query`, converting SQL into parse trees.
58
+ * [pg-proto-parser](https://www.npmjs.com/package/pg-proto-parser): **📦 Protobuf parser** for parsing PostgreSQL Protocol Buffers definitions to generate TypeScript interfaces, utility functions, and JSON mappings for enums.
59
+ * [@pgsql/enums](https://www.npmjs.com/package/@pgsql/enums): **🏷️ TypeScript enums** for PostgreSQL AST for safe and ergonomic parsing logic.
60
+ * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **📝 Type definitions** for PostgreSQL AST nodes in TypeScript.
61
+ * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **🛠️ AST utilities** for constructing and transforming PostgreSQL syntax trees.
62
+ * [pg-ast](https://www.npmjs.com/package/pg-ast): **🔍 Low-level AST tools** and transformations for Postgres query structures.
63
+
64
+ ### 🚀 API & Dev Tools
65
+
66
+ * [launchql/server](https://github.com/constructive-io/constructive/tree/main/packages/server): **⚡ Express-based API server** powered by PostGraphile to expose a secure, scalable GraphQL API over your Postgres database.
67
+ * [launchql/explorer](https://github.com/constructive-io/constructive/tree/main/packages/explorer): **🔎 Visual API explorer** with GraphiQL for browsing across all databases and schemas—useful for debugging, documentation, and API prototyping.
68
+
69
+ ### 🔁 Streaming & Uploads
70
+
71
+ * [launchql/s3-streamer](https://github.com/constructive-io/constructive/tree/main/packages/s3-streamer): **📤 Direct S3 streaming** for large files with support for metadata injection and content validation.
72
+ * [launchql/etag-hash](https://github.com/constructive-io/constructive/tree/main/packages/etag-hash): **🏷️ S3-compatible ETags** created by streaming and hashing file uploads in chunks.
73
+ * [launchql/etag-stream](https://github.com/constructive-io/constructive/tree/main/packages/etag-stream): **🔄 ETag computation** via Node stream transformer during upload or transfer.
74
+ * [launchql/uuid-hash](https://github.com/constructive-io/constructive/tree/main/packages/uuid-hash): **🆔 Deterministic UUIDs** generated from hashed content, great for deduplication and asset referencing.
75
+ * [launchql/uuid-stream](https://github.com/constructive-io/constructive/tree/main/packages/uuid-stream): **🌊 Streaming UUID generation** based on piped file content—ideal for upload pipelines.
76
+ * [launchql/upload-names](https://github.com/constructive-io/constructive/tree/main/packages/upload-names): **📂 Collision-resistant filenames** utility for structured and unique file names for uploads.
77
+
78
+ ### 🧰 CLI & Codegen
79
+
80
+ * [pgpm](https://github.com/constructive-io/constructive/tree/main/packages/pgpm): **🖥️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
81
+ * [@launchql/cli](https://github.com/constructive-io/constructive/tree/main/packages/cli): **🖥️ Command-line toolkit** for managing LaunchQL projects—supports database scaffolding, migrations, seeding, code generation, and automation.
82
+ * [constructive-io/constructive-gen](https://github.com/constructive-io/constructive/tree/main/packages/launchql-gen): **✨ Auto-generated GraphQL** mutations and queries dynamically built from introspected schema data.
83
+ * [@launchql/query-builder](https://github.com/constructive-io/constructive/tree/main/packages/query-builder): **🏗️ SQL constructor** providing a robust TypeScript-based query builder for dynamic generation of `SELECT`, `INSERT`, `UPDATE`, `DELETE`, and stored procedure calls—supports advanced SQL features like `JOIN`, `GROUP BY`, and schema-qualified queries.
84
+ * [@launchql/query](https://github.com/constructive-io/constructive/tree/main/packages/query): **🧩 Fluent GraphQL builder** for PostGraphile schemas. ⚡ Schema-aware via introspection, 🧩 composable and ergonomic for building deeply nested queries.
85
+
86
+ ## Credits
87
+
88
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
89
+
90
+ ## Disclaimer
91
+
92
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
93
+
94
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/config.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ import { PgpmOptions } from '@pgpmjs/types';
2
+ /**
3
+ * Load configuration file with support for both .js and .json formats
4
+ * Moved from PgpmPackage class for better reusability
5
+ */
6
+ export declare const loadConfigFileSync: (configPath: string) => PgpmOptions;
7
+ /**
8
+ * Load configuration from a specific directory
9
+ * Moved from PgpmPackage class for better reusability
10
+ */
11
+ export declare const loadConfigSyncFromDir: (dir: string) => PgpmOptions;
12
+ /**
13
+ * Load configuration using walkUp to find config files
14
+ * Enhanced version that uses the robust config loading logic
15
+ */
16
+ export declare const loadConfigSync: (cwd?: string) => PgpmOptions;
17
+ /**
18
+ * Resolve the path to the PGPM workspace by finding config files
19
+ * Moved from PgpmPackage class for better reusability
20
+ */
21
+ export declare const resolvePgpmPath: (cwd?: string) => string | undefined;
package/config.js ADDED
@@ -0,0 +1,108 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.resolvePgpmPath = exports.loadConfigSync = exports.loadConfigSyncFromDir = exports.loadConfigFileSync = void 0;
37
+ const fs = __importStar(require("fs"));
38
+ const path = __importStar(require("path"));
39
+ const utils_1 = require("./utils");
40
+ /**
41
+ * Load configuration file with support for both .js and .json formats
42
+ * Moved from PgpmPackage class for better reusability
43
+ */
44
+ const loadConfigFileSync = (configPath) => {
45
+ const ext = path.extname(configPath);
46
+ switch (ext) {
47
+ case '.json':
48
+ return JSON.parse(fs.readFileSync(configPath, 'utf8'));
49
+ case '.js':
50
+ // delete require.cache[require.resolve(configPath)];
51
+ const configModule = require(configPath);
52
+ return configModule.default || configModule;
53
+ default:
54
+ throw new Error(`Unsupported config file type: ${ext}`);
55
+ }
56
+ };
57
+ exports.loadConfigFileSync = loadConfigFileSync;
58
+ /**
59
+ * Load configuration from a specific directory
60
+ * Moved from PgpmPackage class for better reusability
61
+ */
62
+ const loadConfigSyncFromDir = (dir) => {
63
+ const configFiles = [
64
+ 'pgpm.config.js',
65
+ 'pgpm.json'
66
+ ];
67
+ for (const filename of configFiles) {
68
+ const configPath = path.join(dir, filename);
69
+ if (fs.existsSync(configPath)) {
70
+ return (0, exports.loadConfigFileSync)(configPath);
71
+ }
72
+ }
73
+ throw new Error('No pgpm config file found. Expected one of: ' + configFiles.join(', '));
74
+ };
75
+ exports.loadConfigSyncFromDir = loadConfigSyncFromDir;
76
+ /**
77
+ * Load configuration using walkUp to find config files
78
+ * Enhanced version that uses the robust config loading logic
79
+ */
80
+ const loadConfigSync = (cwd = process.cwd()) => {
81
+ const configFiles = ['pgpm.config.js', 'pgpm.json'];
82
+ for (const filename of configFiles) {
83
+ try {
84
+ const configDir = (0, utils_1.walkUp)(cwd, filename);
85
+ return (0, exports.loadConfigSyncFromDir)(configDir);
86
+ }
87
+ catch {
88
+ }
89
+ }
90
+ return {};
91
+ };
92
+ exports.loadConfigSync = loadConfigSync;
93
+ /**
94
+ * Resolve the path to the PGPM workspace by finding config files
95
+ * Moved from PgpmPackage class for better reusability
96
+ */
97
+ const resolvePgpmPath = (cwd = process.cwd()) => {
98
+ const configFiles = ['pgpm.config.js', 'pgpm.json'];
99
+ for (const filename of configFiles) {
100
+ try {
101
+ return (0, utils_1.walkUp)(cwd, filename);
102
+ }
103
+ catch {
104
+ }
105
+ }
106
+ return undefined;
107
+ };
108
+ exports.resolvePgpmPath = resolvePgpmPath;
package/env.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import { PgpmOptions } from '@pgpmjs/types';
2
+ export declare const getEnvVars: () => PgpmOptions;
3
+ type NodeEnv = 'development' | 'production' | 'test';
4
+ export declare const getNodeEnv: () => NodeEnv;
5
+ export {};
package/env.js ADDED
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getNodeEnv = exports.getEnvVars = void 0;
4
+ const parseEnvNumber = (val) => {
5
+ const num = Number(val);
6
+ return !isNaN(num) ? num : undefined;
7
+ };
8
+ const parseEnvBoolean = (val) => {
9
+ if (val === undefined)
10
+ return undefined;
11
+ return ['true', '1', 'yes'].includes(val.toLowerCase());
12
+ };
13
+ const getEnvVars = () => {
14
+ const { PGROOTDATABASE, PGTEMPLATE, DB_PREFIX, DB_EXTENSIONS, DB_CWD, DB_CONNECTION_USER, DB_CONNECTION_PASSWORD, DB_CONNECTION_ROLE, PORT, SERVER_HOST, SERVER_TRUST_PROXY, SERVER_ORIGIN, SERVER_STRICT_AUTH, PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE, GRAPHILE_SCHEMA, FEATURES_SIMPLE_INFLECTION, FEATURES_OPPOSITE_BASE_NAMES, FEATURES_POSTGIS, API_ENABLE_META, API_IS_PUBLIC, API_EXPOSED_SCHEMAS, API_META_SCHEMAS, API_ANON_ROLE, API_ROLE_NAME, API_DEFAULT_DATABASE_ID, BUCKET_NAME, AWS_REGION, AWS_ACCESS_KEY, AWS_SECRET_KEY, MINIO_ENDPOINT, DEPLOYMENT_USE_TX, DEPLOYMENT_FAST, DEPLOYMENT_USE_PLAN, DEPLOYMENT_CACHE, DEPLOYMENT_TO_CHANGE, MIGRATIONS_CODEGEN_USE_TX, } = process.env;
15
+ return {
16
+ db: {
17
+ ...(PGROOTDATABASE && { rootDb: PGROOTDATABASE }),
18
+ ...(PGTEMPLATE && { template: PGTEMPLATE }),
19
+ ...(DB_PREFIX && { prefix: DB_PREFIX }),
20
+ ...(DB_EXTENSIONS && { extensions: DB_EXTENSIONS.split(',').map(ext => ext.trim()) }),
21
+ ...(DB_CWD && { cwd: DB_CWD }),
22
+ ...((DB_CONNECTION_USER || DB_CONNECTION_PASSWORD || DB_CONNECTION_ROLE) && {
23
+ connection: {
24
+ ...(DB_CONNECTION_USER && { user: DB_CONNECTION_USER }),
25
+ ...(DB_CONNECTION_PASSWORD && { password: DB_CONNECTION_PASSWORD }),
26
+ ...(DB_CONNECTION_ROLE && { role: DB_CONNECTION_ROLE }),
27
+ }
28
+ }),
29
+ },
30
+ server: {
31
+ ...(PORT && { port: parseEnvNumber(PORT) }),
32
+ ...(SERVER_HOST && { host: SERVER_HOST }),
33
+ ...(SERVER_TRUST_PROXY && { trustProxy: parseEnvBoolean(SERVER_TRUST_PROXY) }),
34
+ ...(SERVER_ORIGIN && { origin: SERVER_ORIGIN }),
35
+ ...(SERVER_STRICT_AUTH && { strictAuth: parseEnvBoolean(SERVER_STRICT_AUTH) }),
36
+ },
37
+ pg: {
38
+ ...(PGHOST && { host: PGHOST }),
39
+ ...(PGPORT && { port: parseEnvNumber(PGPORT) }),
40
+ ...(PGUSER && { user: PGUSER }),
41
+ ...(PGPASSWORD && { password: PGPASSWORD }),
42
+ ...(PGDATABASE && { database: PGDATABASE }),
43
+ },
44
+ graphile: {
45
+ ...(GRAPHILE_SCHEMA && {
46
+ schema: GRAPHILE_SCHEMA.includes(',')
47
+ ? GRAPHILE_SCHEMA.split(',').map(s => s.trim())
48
+ : GRAPHILE_SCHEMA
49
+ }),
50
+ },
51
+ features: {
52
+ ...(FEATURES_SIMPLE_INFLECTION && { simpleInflection: parseEnvBoolean(FEATURES_SIMPLE_INFLECTION) }),
53
+ ...(FEATURES_OPPOSITE_BASE_NAMES && { oppositeBaseNames: parseEnvBoolean(FEATURES_OPPOSITE_BASE_NAMES) }),
54
+ ...(FEATURES_POSTGIS && { postgis: parseEnvBoolean(FEATURES_POSTGIS) }),
55
+ },
56
+ api: {
57
+ ...(API_ENABLE_META && { enableMetaApi: parseEnvBoolean(API_ENABLE_META) }),
58
+ ...(API_IS_PUBLIC && { isPublic: parseEnvBoolean(API_IS_PUBLIC) }),
59
+ ...(API_EXPOSED_SCHEMAS && { exposedSchemas: API_EXPOSED_SCHEMAS.split(',').map(s => s.trim()) }),
60
+ ...(API_META_SCHEMAS && { metaSchemas: API_META_SCHEMAS.split(',').map(s => s.trim()) }),
61
+ ...(API_ANON_ROLE && { anonRole: API_ANON_ROLE }),
62
+ ...(API_ROLE_NAME && { roleName: API_ROLE_NAME }),
63
+ ...(API_DEFAULT_DATABASE_ID && { defaultDatabaseId: API_DEFAULT_DATABASE_ID }),
64
+ },
65
+ cdn: {
66
+ ...(BUCKET_NAME && { bucketName: BUCKET_NAME }),
67
+ ...(AWS_REGION && { awsRegion: AWS_REGION }),
68
+ ...(AWS_ACCESS_KEY && { awsAccessKey: AWS_ACCESS_KEY }),
69
+ ...(AWS_SECRET_KEY && { awsSecretKey: AWS_SECRET_KEY }),
70
+ ...(MINIO_ENDPOINT && { minioEndpoint: MINIO_ENDPOINT }),
71
+ },
72
+ deployment: {
73
+ ...(DEPLOYMENT_USE_TX && { useTx: parseEnvBoolean(DEPLOYMENT_USE_TX) }),
74
+ ...(DEPLOYMENT_FAST && { fast: parseEnvBoolean(DEPLOYMENT_FAST) }),
75
+ ...(DEPLOYMENT_USE_PLAN && { usePlan: parseEnvBoolean(DEPLOYMENT_USE_PLAN) }),
76
+ ...(DEPLOYMENT_CACHE && { cache: parseEnvBoolean(DEPLOYMENT_CACHE) }),
77
+ ...(DEPLOYMENT_TO_CHANGE && { toChange: DEPLOYMENT_TO_CHANGE }),
78
+ },
79
+ migrations: {
80
+ ...(MIGRATIONS_CODEGEN_USE_TX && {
81
+ codegen: {
82
+ useTx: parseEnvBoolean(MIGRATIONS_CODEGEN_USE_TX)
83
+ }
84
+ }),
85
+ }
86
+ };
87
+ };
88
+ exports.getEnvVars = getEnvVars;
89
+ const getNodeEnv = () => {
90
+ const env = process.env.NODE_ENV?.toLowerCase();
91
+ if (env === 'production' || env === 'test')
92
+ return env;
93
+ return 'development';
94
+ };
95
+ exports.getNodeEnv = getNodeEnv;
package/esm/config.js ADDED
@@ -0,0 +1,68 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { walkUp } from './utils';
4
+ /**
5
+ * Load configuration file with support for both .js and .json formats
6
+ * Moved from PgpmPackage class for better reusability
7
+ */
8
+ export const loadConfigFileSync = (configPath) => {
9
+ const ext = path.extname(configPath);
10
+ switch (ext) {
11
+ case '.json':
12
+ return JSON.parse(fs.readFileSync(configPath, 'utf8'));
13
+ case '.js':
14
+ // delete require.cache[require.resolve(configPath)];
15
+ const configModule = require(configPath);
16
+ return configModule.default || configModule;
17
+ default:
18
+ throw new Error(`Unsupported config file type: ${ext}`);
19
+ }
20
+ };
21
+ /**
22
+ * Load configuration from a specific directory
23
+ * Moved from PgpmPackage class for better reusability
24
+ */
25
+ export const loadConfigSyncFromDir = (dir) => {
26
+ const configFiles = [
27
+ 'pgpm.config.js',
28
+ 'pgpm.json'
29
+ ];
30
+ for (const filename of configFiles) {
31
+ const configPath = path.join(dir, filename);
32
+ if (fs.existsSync(configPath)) {
33
+ return loadConfigFileSync(configPath);
34
+ }
35
+ }
36
+ throw new Error('No pgpm config file found. Expected one of: ' + configFiles.join(', '));
37
+ };
38
+ /**
39
+ * Load configuration using walkUp to find config files
40
+ * Enhanced version that uses the robust config loading logic
41
+ */
42
+ export const loadConfigSync = (cwd = process.cwd()) => {
43
+ const configFiles = ['pgpm.config.js', 'pgpm.json'];
44
+ for (const filename of configFiles) {
45
+ try {
46
+ const configDir = walkUp(cwd, filename);
47
+ return loadConfigSyncFromDir(configDir);
48
+ }
49
+ catch {
50
+ }
51
+ }
52
+ return {};
53
+ };
54
+ /**
55
+ * Resolve the path to the PGPM workspace by finding config files
56
+ * Moved from PgpmPackage class for better reusability
57
+ */
58
+ export const resolvePgpmPath = (cwd = process.cwd()) => {
59
+ const configFiles = ['pgpm.config.js', 'pgpm.json'];
60
+ for (const filename of configFiles) {
61
+ try {
62
+ return walkUp(cwd, filename);
63
+ }
64
+ catch {
65
+ }
66
+ }
67
+ return undefined;
68
+ };
package/esm/env.js ADDED
@@ -0,0 +1,90 @@
1
+ const parseEnvNumber = (val) => {
2
+ const num = Number(val);
3
+ return !isNaN(num) ? num : undefined;
4
+ };
5
+ const parseEnvBoolean = (val) => {
6
+ if (val === undefined)
7
+ return undefined;
8
+ return ['true', '1', 'yes'].includes(val.toLowerCase());
9
+ };
10
+ export const getEnvVars = () => {
11
+ const { PGROOTDATABASE, PGTEMPLATE, DB_PREFIX, DB_EXTENSIONS, DB_CWD, DB_CONNECTION_USER, DB_CONNECTION_PASSWORD, DB_CONNECTION_ROLE, PORT, SERVER_HOST, SERVER_TRUST_PROXY, SERVER_ORIGIN, SERVER_STRICT_AUTH, PGHOST, PGPORT, PGUSER, PGPASSWORD, PGDATABASE, GRAPHILE_SCHEMA, FEATURES_SIMPLE_INFLECTION, FEATURES_OPPOSITE_BASE_NAMES, FEATURES_POSTGIS, API_ENABLE_META, API_IS_PUBLIC, API_EXPOSED_SCHEMAS, API_META_SCHEMAS, API_ANON_ROLE, API_ROLE_NAME, API_DEFAULT_DATABASE_ID, BUCKET_NAME, AWS_REGION, AWS_ACCESS_KEY, AWS_SECRET_KEY, MINIO_ENDPOINT, DEPLOYMENT_USE_TX, DEPLOYMENT_FAST, DEPLOYMENT_USE_PLAN, DEPLOYMENT_CACHE, DEPLOYMENT_TO_CHANGE, MIGRATIONS_CODEGEN_USE_TX, } = process.env;
12
+ return {
13
+ db: {
14
+ ...(PGROOTDATABASE && { rootDb: PGROOTDATABASE }),
15
+ ...(PGTEMPLATE && { template: PGTEMPLATE }),
16
+ ...(DB_PREFIX && { prefix: DB_PREFIX }),
17
+ ...(DB_EXTENSIONS && { extensions: DB_EXTENSIONS.split(',').map(ext => ext.trim()) }),
18
+ ...(DB_CWD && { cwd: DB_CWD }),
19
+ ...((DB_CONNECTION_USER || DB_CONNECTION_PASSWORD || DB_CONNECTION_ROLE) && {
20
+ connection: {
21
+ ...(DB_CONNECTION_USER && { user: DB_CONNECTION_USER }),
22
+ ...(DB_CONNECTION_PASSWORD && { password: DB_CONNECTION_PASSWORD }),
23
+ ...(DB_CONNECTION_ROLE && { role: DB_CONNECTION_ROLE }),
24
+ }
25
+ }),
26
+ },
27
+ server: {
28
+ ...(PORT && { port: parseEnvNumber(PORT) }),
29
+ ...(SERVER_HOST && { host: SERVER_HOST }),
30
+ ...(SERVER_TRUST_PROXY && { trustProxy: parseEnvBoolean(SERVER_TRUST_PROXY) }),
31
+ ...(SERVER_ORIGIN && { origin: SERVER_ORIGIN }),
32
+ ...(SERVER_STRICT_AUTH && { strictAuth: parseEnvBoolean(SERVER_STRICT_AUTH) }),
33
+ },
34
+ pg: {
35
+ ...(PGHOST && { host: PGHOST }),
36
+ ...(PGPORT && { port: parseEnvNumber(PGPORT) }),
37
+ ...(PGUSER && { user: PGUSER }),
38
+ ...(PGPASSWORD && { password: PGPASSWORD }),
39
+ ...(PGDATABASE && { database: PGDATABASE }),
40
+ },
41
+ graphile: {
42
+ ...(GRAPHILE_SCHEMA && {
43
+ schema: GRAPHILE_SCHEMA.includes(',')
44
+ ? GRAPHILE_SCHEMA.split(',').map(s => s.trim())
45
+ : GRAPHILE_SCHEMA
46
+ }),
47
+ },
48
+ features: {
49
+ ...(FEATURES_SIMPLE_INFLECTION && { simpleInflection: parseEnvBoolean(FEATURES_SIMPLE_INFLECTION) }),
50
+ ...(FEATURES_OPPOSITE_BASE_NAMES && { oppositeBaseNames: parseEnvBoolean(FEATURES_OPPOSITE_BASE_NAMES) }),
51
+ ...(FEATURES_POSTGIS && { postgis: parseEnvBoolean(FEATURES_POSTGIS) }),
52
+ },
53
+ api: {
54
+ ...(API_ENABLE_META && { enableMetaApi: parseEnvBoolean(API_ENABLE_META) }),
55
+ ...(API_IS_PUBLIC && { isPublic: parseEnvBoolean(API_IS_PUBLIC) }),
56
+ ...(API_EXPOSED_SCHEMAS && { exposedSchemas: API_EXPOSED_SCHEMAS.split(',').map(s => s.trim()) }),
57
+ ...(API_META_SCHEMAS && { metaSchemas: API_META_SCHEMAS.split(',').map(s => s.trim()) }),
58
+ ...(API_ANON_ROLE && { anonRole: API_ANON_ROLE }),
59
+ ...(API_ROLE_NAME && { roleName: API_ROLE_NAME }),
60
+ ...(API_DEFAULT_DATABASE_ID && { defaultDatabaseId: API_DEFAULT_DATABASE_ID }),
61
+ },
62
+ cdn: {
63
+ ...(BUCKET_NAME && { bucketName: BUCKET_NAME }),
64
+ ...(AWS_REGION && { awsRegion: AWS_REGION }),
65
+ ...(AWS_ACCESS_KEY && { awsAccessKey: AWS_ACCESS_KEY }),
66
+ ...(AWS_SECRET_KEY && { awsSecretKey: AWS_SECRET_KEY }),
67
+ ...(MINIO_ENDPOINT && { minioEndpoint: MINIO_ENDPOINT }),
68
+ },
69
+ deployment: {
70
+ ...(DEPLOYMENT_USE_TX && { useTx: parseEnvBoolean(DEPLOYMENT_USE_TX) }),
71
+ ...(DEPLOYMENT_FAST && { fast: parseEnvBoolean(DEPLOYMENT_FAST) }),
72
+ ...(DEPLOYMENT_USE_PLAN && { usePlan: parseEnvBoolean(DEPLOYMENT_USE_PLAN) }),
73
+ ...(DEPLOYMENT_CACHE && { cache: parseEnvBoolean(DEPLOYMENT_CACHE) }),
74
+ ...(DEPLOYMENT_TO_CHANGE && { toChange: DEPLOYMENT_TO_CHANGE }),
75
+ },
76
+ migrations: {
77
+ ...(MIGRATIONS_CODEGEN_USE_TX && {
78
+ codegen: {
79
+ useTx: parseEnvBoolean(MIGRATIONS_CODEGEN_USE_TX)
80
+ }
81
+ }),
82
+ }
83
+ };
84
+ };
85
+ export const getNodeEnv = () => {
86
+ const env = process.env.NODE_ENV?.toLowerCase();
87
+ if (env === 'production' || env === 'test')
88
+ return env;
89
+ return 'development';
90
+ };
package/esm/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { getEnvOptions, getConnEnvOptions, getDeploymentEnvOptions } from './merge';
2
+ export { loadConfigSync, loadConfigSyncFromDir, loadConfigFileSync, resolvePgpmPath } from './config';
3
+ export { getEnvVars, getNodeEnv } from './env';
4
+ export { walkUp } from './utils';
package/esm/merge.js ADDED
@@ -0,0 +1,22 @@
1
+ import deepmerge from 'deepmerge';
2
+ import { pgpmDefaults } from '@pgpmjs/types';
3
+ import { loadConfigSync } from './config';
4
+ import { getEnvVars } from './env';
5
+ export const getEnvOptions = (overrides = {}, cwd = process.cwd()) => {
6
+ const defaults = pgpmDefaults;
7
+ const configOptions = loadConfigSync(cwd);
8
+ const envOptions = getEnvVars();
9
+ return deepmerge.all([defaults, configOptions, envOptions, overrides]);
10
+ };
11
+ export const getConnEnvOptions = (overrides = {}, cwd = process.cwd()) => {
12
+ const opts = getEnvOptions({
13
+ db: overrides
14
+ }, cwd);
15
+ return opts.db;
16
+ };
17
+ export const getDeploymentEnvOptions = (overrides = {}, cwd = process.cwd()) => {
18
+ const opts = getEnvOptions({
19
+ deployment: overrides
20
+ }, cwd);
21
+ return opts.deployment;
22
+ };
package/esm/utils.js ADDED
@@ -0,0 +1,23 @@
1
+ import { existsSync } from 'fs';
2
+ import { dirname, resolve } from 'path';
3
+ /**
4
+ * Recursively walks up directories to find a specific file (sync version).
5
+ * @param startDir - Starting directory.
6
+ * @param filename - The target file to search for.
7
+ * @returns The directory path containing the file.
8
+ */
9
+ export const walkUp = (startDir, filename) => {
10
+ let currentDir = resolve(startDir);
11
+ while (currentDir) {
12
+ const targetPath = resolve(currentDir, filename);
13
+ if (existsSync(targetPath)) {
14
+ return currentDir;
15
+ }
16
+ const parentDir = dirname(currentDir);
17
+ if (parentDir === currentDir) {
18
+ break;
19
+ }
20
+ currentDir = parentDir;
21
+ }
22
+ throw new Error(`File "${filename}" not found in any parent directories.`);
23
+ };
package/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export { getEnvOptions, getConnEnvOptions, getDeploymentEnvOptions } from './merge';
2
+ export { loadConfigSync, loadConfigSyncFromDir, loadConfigFileSync, resolvePgpmPath } from './config';
3
+ export { getEnvVars, getNodeEnv } from './env';
4
+ export { walkUp } from './utils';
5
+ export type { PgpmOptions, PgTestConnectionOptions, DeploymentOptions } from '@pgpmjs/types';
package/index.js ADDED
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.walkUp = exports.getNodeEnv = exports.getEnvVars = exports.resolvePgpmPath = exports.loadConfigFileSync = exports.loadConfigSyncFromDir = exports.loadConfigSync = exports.getDeploymentEnvOptions = exports.getConnEnvOptions = exports.getEnvOptions = void 0;
4
+ var merge_1 = require("./merge");
5
+ Object.defineProperty(exports, "getEnvOptions", { enumerable: true, get: function () { return merge_1.getEnvOptions; } });
6
+ Object.defineProperty(exports, "getConnEnvOptions", { enumerable: true, get: function () { return merge_1.getConnEnvOptions; } });
7
+ Object.defineProperty(exports, "getDeploymentEnvOptions", { enumerable: true, get: function () { return merge_1.getDeploymentEnvOptions; } });
8
+ var config_1 = require("./config");
9
+ Object.defineProperty(exports, "loadConfigSync", { enumerable: true, get: function () { return config_1.loadConfigSync; } });
10
+ Object.defineProperty(exports, "loadConfigSyncFromDir", { enumerable: true, get: function () { return config_1.loadConfigSyncFromDir; } });
11
+ Object.defineProperty(exports, "loadConfigFileSync", { enumerable: true, get: function () { return config_1.loadConfigFileSync; } });
12
+ Object.defineProperty(exports, "resolvePgpmPath", { enumerable: true, get: function () { return config_1.resolvePgpmPath; } });
13
+ var env_1 = require("./env");
14
+ Object.defineProperty(exports, "getEnvVars", { enumerable: true, get: function () { return env_1.getEnvVars; } });
15
+ Object.defineProperty(exports, "getNodeEnv", { enumerable: true, get: function () { return env_1.getNodeEnv; } });
16
+ var utils_1 = require("./utils");
17
+ Object.defineProperty(exports, "walkUp", { enumerable: true, get: function () { return utils_1.walkUp; } });
package/merge.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import { PgpmOptions, PgTestConnectionOptions, DeploymentOptions } from '@pgpmjs/types';
2
+ export declare const getEnvOptions: (overrides?: PgpmOptions, cwd?: string) => PgpmOptions;
3
+ export declare const getConnEnvOptions: (overrides?: Partial<PgTestConnectionOptions>, cwd?: string) => PgTestConnectionOptions;
4
+ export declare const getDeploymentEnvOptions: (overrides?: Partial<DeploymentOptions>, cwd?: string) => DeploymentOptions;
package/merge.js ADDED
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.getDeploymentEnvOptions = exports.getConnEnvOptions = exports.getEnvOptions = void 0;
7
+ const deepmerge_1 = __importDefault(require("deepmerge"));
8
+ const types_1 = require("@pgpmjs/types");
9
+ const config_1 = require("./config");
10
+ const env_1 = require("./env");
11
+ const getEnvOptions = (overrides = {}, cwd = process.cwd()) => {
12
+ const defaults = types_1.pgpmDefaults;
13
+ const configOptions = (0, config_1.loadConfigSync)(cwd);
14
+ const envOptions = (0, env_1.getEnvVars)();
15
+ return deepmerge_1.default.all([defaults, configOptions, envOptions, overrides]);
16
+ };
17
+ exports.getEnvOptions = getEnvOptions;
18
+ const getConnEnvOptions = (overrides = {}, cwd = process.cwd()) => {
19
+ const opts = (0, exports.getEnvOptions)({
20
+ db: overrides
21
+ }, cwd);
22
+ return opts.db;
23
+ };
24
+ exports.getConnEnvOptions = getConnEnvOptions;
25
+ const getDeploymentEnvOptions = (overrides = {}, cwd = process.cwd()) => {
26
+ const opts = (0, exports.getEnvOptions)({
27
+ deployment: overrides
28
+ }, cwd);
29
+ return opts.deployment;
30
+ };
31
+ exports.getDeploymentEnvOptions = getDeploymentEnvOptions;
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@pgpmjs/env",
3
+ "version": "2.7.0",
4
+ "author": "Dan Lynch <Dan Lynch>",
5
+ "description": "PGPM environment management",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "homepage": "https://github.com/constructive-io/constructive",
10
+ "license": "MIT",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/constructive-io/constructive"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/constructive-io/constructive/issues"
21
+ },
22
+ "scripts": {
23
+ "clean": "makage clean",
24
+ "prepack": "npm run build",
25
+ "build": "makage build",
26
+ "build:dev": "makage build --dev",
27
+ "lint": "eslint . --fix",
28
+ "test": "jest",
29
+ "test:watch": "jest --watch"
30
+ },
31
+ "dependencies": {
32
+ "@pgpmjs/types": "^2.11.0",
33
+ "deepmerge": "^4.3.1"
34
+ },
35
+ "keywords": [
36
+ "environment",
37
+ "config",
38
+ "typescript",
39
+ "pgpm",
40
+ "pgpmjs",
41
+ "env"
42
+ ],
43
+ "devDependencies": {
44
+ "makage": "^0.1.8"
45
+ },
46
+ "gitHead": "e4d5396a5d9154f4886176bb00c2b460b0f320e5"
47
+ }
package/utils.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Recursively walks up directories to find a specific file (sync version).
3
+ * @param startDir - Starting directory.
4
+ * @param filename - The target file to search for.
5
+ * @returns The directory path containing the file.
6
+ */
7
+ export declare const walkUp: (startDir: string, filename: string) => string;
package/utils.js ADDED
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.walkUp = void 0;
4
+ const fs_1 = require("fs");
5
+ const path_1 = require("path");
6
+ /**
7
+ * Recursively walks up directories to find a specific file (sync version).
8
+ * @param startDir - Starting directory.
9
+ * @param filename - The target file to search for.
10
+ * @returns The directory path containing the file.
11
+ */
12
+ const walkUp = (startDir, filename) => {
13
+ let currentDir = (0, path_1.resolve)(startDir);
14
+ while (currentDir) {
15
+ const targetPath = (0, path_1.resolve)(currentDir, filename);
16
+ if ((0, fs_1.existsSync)(targetPath)) {
17
+ return currentDir;
18
+ }
19
+ const parentDir = (0, path_1.dirname)(currentDir);
20
+ if (parentDir === currentDir) {
21
+ break;
22
+ }
23
+ currentDir = parentDir;
24
+ }
25
+ throw new Error(`File "${filename}" not found in any parent directories.`);
26
+ };
27
+ exports.walkUp = walkUp;