@@ -7,9 +7,7 @@ import { expand } from "dotenv-expand";
77import { build } from "esbuild" ;
88import { importFromString } from "module-from-string" ;
99import { readFile } from "node:fs/promises" ;
10- import { dirname , resolve } from "node:path" ;
11- import { fileURLToPath } from "node:url" ;
12- import parentModule from "parent-module" ;
10+ import { resolve } from "node:path" ;
1311import { readPackageUp } from "read-pkg-up" ;
1412
1513// Matches the following patterns:
@@ -26,8 +24,8 @@ const secretRegExp = /^secret:\/\/(\w+)\/(.*)$/;
2624 * @see https://cloud.google.com/secret-manager
2725 * @example
2826 * const [env, secrets] = await loadEnv("development", {
29- * root: "..",
30- * schema: "./core/ env.ts",
27+ * root: "./apps/backend", // relative to process.cwd()
28+ * schema: "./env.ts", // relative to process.cwd()
3129 * mergeTo: process.env,
3230 * });
3331 *
@@ -37,7 +35,7 @@ const secretRegExp = /^secret:\/\/(\w+)\/(.*)$/;
3735 * files?: string[] | string;
3836 * schema?: string;
3937 * mergeTo?: Record<string, unknown>;
40- * }} options Loading options
38+ * }} options Loading options. The `root` defaults to `process.cwd()`, and `schema` is resolved relative to `process.cwd()`.
4139 * @return {Promise<[env: Record<string, string>, secrets: Map<string, { ref: string; source: "google" | "aws" | "azure" }]> }
4240 */
4341export async function loadEnv ( environment , options ) {
@@ -59,11 +57,7 @@ export async function loadEnv(environment, options) {
5957 }
6058
6159 // Load environment variables from the `.env` files
62- const parentFile = parentModule ( ) ;
63- const parentDir = dirname (
64- parentFile . startsWith ( "file://" ) ? fileURLToPath ( parentFile ) : parentFile ,
65- ) ;
66- const rootDir = resolve ( parentDir , options ?. root ?? "." ) ;
60+ const rootDir = resolve ( options ?. root ?? process . cwd ( ) ) ;
6761 const encoding = options ?. encoding ?? "utf-8" ;
6862 const parsed = await Promise . all (
6963 files . map ( ( file ) => {
@@ -98,8 +92,8 @@ export async function loadEnv(environment, options) {
9892
9993 if ( options ?. schema ) {
10094 // Transpile the schema file into ESM code
101- const schemaFile = resolve ( parentDir , options ? .schema ) ;
102- const { packageJson } = await readPackageUp ( { cwd : parentDir } ) ;
95+ const schemaFile = resolve ( process . cwd ( ) , options . schema ) ;
96+ const { packageJson } = await readPackageUp ( { cwd : process . cwd ( ) } ) ;
10397 const {
10498 outputFiles : [ { text : contents } ] ,
10599 } = await build ( {
@@ -118,7 +112,7 @@ export async function loadEnv(environment, options) {
118112
119113 // Import env schema
120114 const envObj = await importFromString ( contents , {
121- dirname : parentDir ,
115+ dirname : process . cwd ( ) ,
122116 filename : schemaFile ,
123117 useCurrentGlobal : true ,
124118 } ) . then ( ( module ) => module . env ?? module . default ) ;
0 commit comments