@newcode-team/env 0.0.0-stage → 0.1.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 +21 -0
- package/README.md +161 -2
- package/dist/cli.d.mts +1 -0
- package/dist/cli.mjs +267 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/config-DdWBrqcV.mjs +48 -0
- package/dist/config-DdWBrqcV.mjs.map +1 -0
- package/dist/index.d.mts +39 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +1 -0
- package/package.json +84 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 NewCode
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,162 @@
|
|
|
1
|
-
#
|
|
1
|
+
# newenv
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Per-environment env files for any command, with switching and guards. Only reads files: no secrets service, no encryption, no syncing.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pnpm add -D @newcode-team/env
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```json
|
|
10
|
+
{
|
|
11
|
+
"scripts": {
|
|
12
|
+
"dev": "newenv next dev",
|
|
13
|
+
"db:push": "newenv drizzle-kit push",
|
|
14
|
+
"use-env": "newenv use"
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Requires Node 24+.
|
|
20
|
+
|
|
21
|
+
## Conventions
|
|
22
|
+
|
|
23
|
+
| File | Holds |
|
|
24
|
+
|---|---|
|
|
25
|
+
| `.envs/.env` | Shared base of every environment (optional) |
|
|
26
|
+
| `.envs/.env.<name>` | One environment: `local`, `staging`, `production`, … |
|
|
27
|
+
| `.envs/.env.example` | Template for `newenv init`, committed |
|
|
28
|
+
| `.envs/current` | Selected environment. Missing means `local` |
|
|
29
|
+
|
|
30
|
+
- An environment loads `.envs/.env`, then `.envs/.env.<name>`. Its own file wins over the base, both win over the shell.
|
|
31
|
+
- Available environments: the `.envs/.env.*` files that exist.
|
|
32
|
+
- No env files in the project root. Frameworks like Next.js load those on their own.
|
|
33
|
+
- Values are parsed with `dotenv` and expanded with `dotenv-expand`, exactly like `dotenv-cli -e .envs/.env -e .envs/.env.<name> -o`. So `$VAR` and `${VAR:-default}` expand, and a literal `$` needs `\$`. Expansion runs over the merged env, so shell variables with a `$` in their value expand too.
|
|
34
|
+
|
|
35
|
+
## Commands
|
|
36
|
+
|
|
37
|
+
| Command | Does |
|
|
38
|
+
|---|---|
|
|
39
|
+
| `newenv <command> [args]` | Run with the selected environment |
|
|
40
|
+
| `newenv use <name>` | Switch environment (`local` deletes `.envs/current`) |
|
|
41
|
+
| `newenv status` | Active environment and its files, never values |
|
|
42
|
+
| `newenv init` | Create `.envs/`, gitignore rules and `.envs/.env.local` |
|
|
43
|
+
| `newenv -- <command>` | Run a program named `use`, `status` or `init` |
|
|
44
|
+
|
|
45
|
+
Options go before the command, and parsing stops at the first argument that isn't one: `newenv next dev --turbopack` passes `--turbopack` to Next.
|
|
46
|
+
|
|
47
|
+
| Option | Does |
|
|
48
|
+
|---|---|
|
|
49
|
+
| `--confirm` | Ask before running, as for `confirmScripts` |
|
|
50
|
+
| `-h`, `--help` | Help |
|
|
51
|
+
| `-v`, `--version` | Version |
|
|
52
|
+
|
|
53
|
+
Outside package scripts, run it with `pnpm newenv use staging` or `pnpm exec newenv status`.
|
|
54
|
+
|
|
55
|
+
### Running
|
|
56
|
+
|
|
57
|
+
1. **Passthrough:** with a `passthrough` variable set, the command runs as is with the existing env. None by default.
|
|
58
|
+
2. **Root env files** (`.env`, `.env.local`, `.env.development`, `.env.production` and their `.local` variants): refused, with the `mv` command.
|
|
59
|
+
3. **Forbidden base keys** (`DATABASE_URL`): refused in `.envs/.env`, since the base applies to every environment.
|
|
60
|
+
4. **Missing environment file:** refused, with a hint.
|
|
61
|
+
5. **Banner** on stderr outside local: a yellow badge, red for production, plus the script and files.
|
|
62
|
+
6. **Confirmation** for `confirmScripts` (`db:push`, `db:migrate`, `db:seed`), matched on `npm_lifecycle_event`: `y/N`, or typing the name for production. Without a TTY it aborts, so agents and CI can't run them by accident. Local never asks.
|
|
63
|
+
7. **Runs** the command with inherited stdio, passes the exit code through and forwards signals.
|
|
64
|
+
|
|
65
|
+
### Switching
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
pnpm newenv use staging # .envs/.env + .envs/.env.staging
|
|
69
|
+
pnpm newenv use local # back to .envs/.env + .envs/.env.local
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Refuses environments without a file. Switching to production asks first. Running processes keep the environment they started with.
|
|
73
|
+
|
|
74
|
+
### Setting up
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
pnpm newenv init
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
```
|
|
81
|
+
Created .envs/
|
|
82
|
+
Updated .gitignore
|
|
83
|
+
Created .envs/.env.local from .envs/.env.example
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
The example is the first of `.envs/.env.example`, `.example-env` and `.env.example`. Existing files are kept. The gitignore rules:
|
|
87
|
+
|
|
88
|
+
```gitignore
|
|
89
|
+
# newenv
|
|
90
|
+
/.env*
|
|
91
|
+
!/.envs/
|
|
92
|
+
/.envs/*
|
|
93
|
+
!/.envs/.env.example
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
A `.env*` pattern also matches the `.envs` folder, and git can't re-include a file in an ignored folder. So the folder is re-included first, then its contents ignored, except the example.
|
|
97
|
+
|
|
98
|
+
## Config
|
|
99
|
+
|
|
100
|
+
Optional. `newenv.config.ts`, `.mjs` or `.js` in the project root, for exceptions:
|
|
101
|
+
|
|
102
|
+
```ts
|
|
103
|
+
import { defineConfig } from "@newcode-team/env";
|
|
104
|
+
|
|
105
|
+
export default defineConfig({
|
|
106
|
+
environments: {
|
|
107
|
+
staging: { color: "yellow", confirm: true },
|
|
108
|
+
production: { color: "red", confirm: "type-name" },
|
|
109
|
+
},
|
|
110
|
+
confirmScripts: ["db:push", "db:migrate", "db:seed"],
|
|
111
|
+
forbiddenInBase: ["DATABASE_URL"],
|
|
112
|
+
});
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
| Key | Default | Does |
|
|
116
|
+
|---|---|---|
|
|
117
|
+
| `environments.<name>.color` | `red` for production, else `yellow` | Badge: `red`, `yellow`, `green`, `blue`, `magenta`, `cyan`, `gray` |
|
|
118
|
+
| `environments.<name>.confirm` | `"type-name"` for production, `false` for local, else `true` | `true`: y/N. `"type-name"`: type the name, and `use` asks first. `false`: never |
|
|
119
|
+
| `confirmScripts` | `["db:push", "db:migrate", "db:seed"]` | Scripts that ask before running |
|
|
120
|
+
| `forbiddenInBase` | `["DATABASE_URL"]` | Keys refused in `.envs/.env` |
|
|
121
|
+
| `passthrough` | `[]` | Variables that skip the files, e.g. `["VERCEL"]` on a host that provides the env |
|
|
122
|
+
| `example` | | Source for `newenv init` |
|
|
123
|
+
|
|
124
|
+
## Prompt
|
|
125
|
+
|
|
126
|
+
Optional, zsh: the environment at the start of your prompt. Reads `.envs/current` directly, so it stays fast. Save as `~/.config/zsh/newenv.zsh` and add `source ~/.config/zsh/newenv.zsh` to the end of `~/.zshrc`:
|
|
127
|
+
|
|
128
|
+
```zsh
|
|
129
|
+
_app_env_prompt() {
|
|
130
|
+
local root
|
|
131
|
+
root=$(git rev-parse --show-toplevel 2>/dev/null) || return
|
|
132
|
+
[[ -f $root/.envs/current ]] || return
|
|
133
|
+
|
|
134
|
+
local app_env=$(<$root/.envs/current)
|
|
135
|
+
|
|
136
|
+
if [[ $app_env == production ]]; then
|
|
137
|
+
print -n "%K{red}%F{white}%B PRODUCTION %b%f%k "
|
|
138
|
+
else
|
|
139
|
+
print -n "%K{yellow}%F{black} ${(U)app_env} %f%k "
|
|
140
|
+
fi
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
setopt PROMPT_SUBST
|
|
144
|
+
[[ $PROMPT == *_app_env_prompt* ]] || PROMPT='$(_app_env_prompt)'$PROMPT
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
## Development
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
pnpm build # tsdown, with publint and attw
|
|
151
|
+
pnpm test # Vitest, builds dist/ first for the CLI tests
|
|
152
|
+
pnpm lint # Oxlint
|
|
153
|
+
pnpm format # Oxfmt
|
|
154
|
+
pnpm typecheck
|
|
155
|
+
pnpm changeset # describe a change for the next release
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
Releases go through Changesets: merging to `main` opens a release PR, and merging that PR publishes to npm.
|
|
159
|
+
|
|
160
|
+
## License
|
|
161
|
+
|
|
162
|
+
MIT
|
package/dist/cli.d.mts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {}
|
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { n as environmentSettings, r as loadConfig } from "./config-DdWBrqcV.mjs";
|
|
3
|
+
import { appendFileSync, constants, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { Command } from "commander";
|
|
6
|
+
import { parse } from "dotenv";
|
|
7
|
+
import { expand } from "dotenv-expand";
|
|
8
|
+
import confirmPrompt from "@inquirer/confirm";
|
|
9
|
+
import input from "@inquirer/input";
|
|
10
|
+
import { styleText } from "node:util";
|
|
11
|
+
import spawn from "cross-spawn";
|
|
12
|
+
// package.json
|
|
13
|
+
var version = "0.1.0";
|
|
14
|
+
// src/env.ts
|
|
15
|
+
const envsDir = ".envs";
|
|
16
|
+
const baseFile = ".envs/.env";
|
|
17
|
+
const currentFile = ".envs/current";
|
|
18
|
+
const rootEnvFiles = [
|
|
19
|
+
".env",
|
|
20
|
+
".env.local",
|
|
21
|
+
".env.development",
|
|
22
|
+
".env.development.local",
|
|
23
|
+
".env.production",
|
|
24
|
+
".env.production.local"
|
|
25
|
+
];
|
|
26
|
+
/**
|
|
27
|
+
* The selected environment: the name in .envs/current, or local
|
|
28
|
+
*/
|
|
29
|
+
function currentEnvironment(cwd) {
|
|
30
|
+
const file = join(cwd, currentFile);
|
|
31
|
+
return existsSync(file) && readFileSync(file, "utf8").trim() || "local";
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The environments with a .envs/.env.<name> file
|
|
35
|
+
*/
|
|
36
|
+
function listEnvironments(cwd) {
|
|
37
|
+
const dir = join(cwd, envsDir);
|
|
38
|
+
return existsSync(dir) ? readdirSync(dir).map((file) => /^\.env\.([\w-]+)$/.exec(file)?.[1]).filter((name) => name !== void 0 && name !== "example").toSorted() : [];
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Throws when root env files exist, the base holds forbidden keys or the environment file is missing
|
|
42
|
+
*/
|
|
43
|
+
function checkFiles(cwd, config, name) {
|
|
44
|
+
const rootFiles = rootEnvFiles.filter((file) => existsSync(join(cwd, file)));
|
|
45
|
+
if (rootFiles.length > 0) throw new Error(`${rootFiles.join(", ")} in the project root. Move into .envs/: mv -n ${rootFiles.join(" ")} .envs/`);
|
|
46
|
+
const base = join(cwd, baseFile);
|
|
47
|
+
const forbidden = existsSync(base) ? Object.keys(parse(readFileSync(base))).filter((key) => config.forbiddenInBase.includes(key)) : [];
|
|
48
|
+
if (forbidden.length > 0) throw new Error(`${forbidden.join(", ")} in the shared ${baseFile}. Move to .envs/.env.<name> for each environment.`);
|
|
49
|
+
const envFile = `.envs/.env.${name}`;
|
|
50
|
+
if (!existsSync(join(cwd, envFile))) throw new Error(name === "local" ? `${envFile} not found. Create it with: newenv init` : `${envFile} not found. Switch back with: newenv use local`);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Merges the shell env, the base and the environment file: the last one wins. Expands variables
|
|
54
|
+
* over the merged env, the same way dotenv-cli does.
|
|
55
|
+
*/
|
|
56
|
+
function loadEnv(cwd, name, shellEnv) {
|
|
57
|
+
const files = [baseFile, `.envs/.env.${name}`].filter((file) => existsSync(join(cwd, file)));
|
|
58
|
+
const env = Object.assign({}, shellEnv, ...files.map((file) => parse(readFileSync(join(cwd, file)))));
|
|
59
|
+
expand({
|
|
60
|
+
parsed: env,
|
|
61
|
+
processEnv: env
|
|
62
|
+
});
|
|
63
|
+
return {
|
|
64
|
+
env,
|
|
65
|
+
files
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
// src/prompt.ts
|
|
69
|
+
/**
|
|
70
|
+
* Asks y/N, or to type the name for `"type-name"`. Ctrl+C answers no. Throws without a TTY, so
|
|
71
|
+
* agents and CI can't confirm by accident.
|
|
72
|
+
*/
|
|
73
|
+
async function confirm(mode, name, question, streams) {
|
|
74
|
+
if (!streams.input.isTTY) throw new Error(`${question}: needs confirmation, no TTY. Aborted.`);
|
|
75
|
+
try {
|
|
76
|
+
return mode === "type-name" ? await input({ message: `${question}? Type "${name}" to confirm:` }, streams) === name : await confirmPrompt({
|
|
77
|
+
message: `${question}?`,
|
|
78
|
+
default: false
|
|
79
|
+
}, streams);
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (error instanceof Error && error.name === "ExitPromptError") return false;
|
|
82
|
+
throw error;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
// src/run.ts
|
|
86
|
+
const badgeStyles = {
|
|
87
|
+
red: [
|
|
88
|
+
"bgRed",
|
|
89
|
+
"white",
|
|
90
|
+
"bold"
|
|
91
|
+
],
|
|
92
|
+
yellow: ["bgYellow", "black"],
|
|
93
|
+
green: ["bgGreen", "black"],
|
|
94
|
+
blue: ["bgBlue", "white"],
|
|
95
|
+
magenta: ["bgMagenta", "white"],
|
|
96
|
+
cyan: ["bgCyan", "black"],
|
|
97
|
+
gray: ["bgGray", "white"]
|
|
98
|
+
};
|
|
99
|
+
const signals = [
|
|
100
|
+
"SIGINT",
|
|
101
|
+
"SIGTERM",
|
|
102
|
+
"SIGHUP"
|
|
103
|
+
];
|
|
104
|
+
/**
|
|
105
|
+
* Checks the files, prints the banner, confirms and returns the env to run a command with
|
|
106
|
+
*/
|
|
107
|
+
async function prepareRun(command, { cwd, env, config, streams }, forceConfirm = false) {
|
|
108
|
+
if (config.passthrough.some((key) => env[key])) return env;
|
|
109
|
+
const name = currentEnvironment(cwd);
|
|
110
|
+
checkFiles(cwd, config, name);
|
|
111
|
+
const loaded = loadEnv(cwd, name, env);
|
|
112
|
+
const settings = environmentSettings(config, name);
|
|
113
|
+
const script = env.npm_lifecycle_event ?? command;
|
|
114
|
+
if (name !== "local") {
|
|
115
|
+
const badge = styleText([...badgeStyles[settings.color]], ` ${name.toUpperCase()} `, { stream: streams.output });
|
|
116
|
+
streams.output.write(`${badge} ${script} uses ${loaded.files.join(" + ")}\n`);
|
|
117
|
+
}
|
|
118
|
+
if ((forceConfirm || config.confirmScripts.includes(env.npm_lifecycle_event ?? "")) && settings.confirm && !await confirm(settings.confirm, name, `Run ${script} against ${name}`, streams)) throw new Error("Aborted.");
|
|
119
|
+
return loaded.env;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Runs a command with inherited stdio and forwards signals to it until it exits. In a terminal,
|
|
123
|
+
* Ctrl+C and hangups already reach the whole foreground process group, the command included, so
|
|
124
|
+
* only SIGTERM is forwarded there. newenv still catches the others, to exit after the command.
|
|
125
|
+
*/
|
|
126
|
+
function spawnCommand(command, args, env) {
|
|
127
|
+
return new Promise((resolve, reject) => {
|
|
128
|
+
const child = spawn(command, args, {
|
|
129
|
+
stdio: "inherit",
|
|
130
|
+
env
|
|
131
|
+
});
|
|
132
|
+
const forward = (signal) => {
|
|
133
|
+
if (signal === "SIGTERM" || !process.stdin.isTTY) child.kill(signal);
|
|
134
|
+
};
|
|
135
|
+
const stopForwarding = () => {
|
|
136
|
+
signals.forEach((signal) => {
|
|
137
|
+
process.off(signal, forward);
|
|
138
|
+
});
|
|
139
|
+
};
|
|
140
|
+
signals.forEach((signal) => {
|
|
141
|
+
process.on(signal, forward);
|
|
142
|
+
});
|
|
143
|
+
child.on("error", (error) => {
|
|
144
|
+
stopForwarding();
|
|
145
|
+
reject(error);
|
|
146
|
+
});
|
|
147
|
+
child.on("exit", (code, signal) => {
|
|
148
|
+
stopForwarding();
|
|
149
|
+
resolve({
|
|
150
|
+
code,
|
|
151
|
+
signal
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
// src/cli.ts
|
|
157
|
+
const argv = process.argv.slice(2);
|
|
158
|
+
const cwd = process.cwd();
|
|
159
|
+
const streams = {
|
|
160
|
+
input: process.stdin,
|
|
161
|
+
output: process.stderr
|
|
162
|
+
};
|
|
163
|
+
const gitignoreBlock = [
|
|
164
|
+
"# newenv",
|
|
165
|
+
"/.env*",
|
|
166
|
+
"!/.envs/",
|
|
167
|
+
"/.envs/*",
|
|
168
|
+
"!/.envs/.env.example"
|
|
169
|
+
].join("\n");
|
|
170
|
+
const exampleFiles = [
|
|
171
|
+
".envs/.env.example",
|
|
172
|
+
".example-env",
|
|
173
|
+
".env.example"
|
|
174
|
+
];
|
|
175
|
+
const program = new Command("newenv").description("Run a command with the env files of the selected environment").usage("[options] <command> [args...]").version(version, "-v, --version", "Show version").helpOption("-h, --help", "Show help").enablePositionalOptions().passThroughOptions().option("--confirm", "Ask before running, as for confirmScripts").argument("[command...]", "Command to run. Put -- before one named use, status or init").configureOutput({ outputError: (message, write) => write(`newenv: ${message.replace(/^error: /, "")}`) }).action(async (command, options) => {
|
|
176
|
+
const [name, ...args] = command;
|
|
177
|
+
if (!name) return program.help({ error: argv.length > 0 });
|
|
178
|
+
const config = await loadConfig(cwd);
|
|
179
|
+
const { code, signal } = await spawnCommand(name, args, await prepareRun(name, {
|
|
180
|
+
cwd,
|
|
181
|
+
env: process.env,
|
|
182
|
+
config,
|
|
183
|
+
streams
|
|
184
|
+
}, options.confirm)).catch((error) => {
|
|
185
|
+
if (error.code !== "ENOENT") throw error;
|
|
186
|
+
console.error(`newenv: command not found: ${name}`);
|
|
187
|
+
return {
|
|
188
|
+
code: 127,
|
|
189
|
+
signal: null
|
|
190
|
+
};
|
|
191
|
+
});
|
|
192
|
+
if (signal) process.kill(process.pid, signal);
|
|
193
|
+
process.exitCode = code ?? 1;
|
|
194
|
+
});
|
|
195
|
+
if (argv[argv.findIndex((arg) => arg === "--" || !arg.startsWith("-"))] !== "--") {
|
|
196
|
+
program.command("use").description("Switch environment").argument("<name>", "Environment, local deletes .envs/current").action(async (name) => {
|
|
197
|
+
const envFile = `.envs/.env.${name}`;
|
|
198
|
+
if (name === "local") {
|
|
199
|
+
rmSync(join(cwd, currentFile), { force: true });
|
|
200
|
+
console.log(existsSync(join(cwd, envFile)) ? "Switched to local." : `Switched to local. ${envFile} not found. Create it with: newenv init`);
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
const environments = listEnvironments(cwd);
|
|
204
|
+
if (!environments.includes(name)) throw new Error(`${envFile} not found. Available: ${environments.join(", ") || "none"}`);
|
|
205
|
+
const config = await loadConfig(cwd);
|
|
206
|
+
if (environmentSettings(config, name).confirm === "type-name" && !await confirm(true, name, `Switch to ${name}`, streams)) throw new Error("Aborted.");
|
|
207
|
+
writeFileSync(join(cwd, currentFile), `${name}\n`);
|
|
208
|
+
console.log(`Switched to ${name}.`);
|
|
209
|
+
});
|
|
210
|
+
program.command("status").description("Show the environment and its files").action(async () => {
|
|
211
|
+
const config = await loadConfig(cwd);
|
|
212
|
+
const name = currentEnvironment(cwd);
|
|
213
|
+
const envFile = `.envs/.env.${name}`;
|
|
214
|
+
const files = [...existsSync(join(cwd, ".envs/.env")) ? [baseFile] : [], existsSync(join(cwd, envFile)) ? envFile : `${envFile} (missing)`];
|
|
215
|
+
const passthrough = config.passthrough.filter((key) => process.env[key]);
|
|
216
|
+
const problem = (() => {
|
|
217
|
+
try {
|
|
218
|
+
checkFiles(cwd, config, name);
|
|
219
|
+
return;
|
|
220
|
+
} catch (error) {
|
|
221
|
+
return error.message;
|
|
222
|
+
}
|
|
223
|
+
})();
|
|
224
|
+
console.log([
|
|
225
|
+
["Environment", name],
|
|
226
|
+
["Files", files.join(" + ")],
|
|
227
|
+
["Available", listEnvironments(cwd).join(", ") || "none"],
|
|
228
|
+
["Config", config.file],
|
|
229
|
+
["Passthrough", passthrough.length > 0 ? `${passthrough.join(", ")} set, files ignored` : void 0],
|
|
230
|
+
["Problem", problem]
|
|
231
|
+
].filter(([, value]) => value !== void 0).map(([label, value]) => `${label?.padEnd(12)} ${value}`).join("\n"));
|
|
232
|
+
});
|
|
233
|
+
program.command("init").description("Set up .envs/, the gitignore rules and .envs/.env.local").action(async () => {
|
|
234
|
+
const config = await loadConfig(cwd);
|
|
235
|
+
const dir = join(cwd, envsDir);
|
|
236
|
+
const dirExists = existsSync(dir);
|
|
237
|
+
mkdirSync(dir, { recursive: true });
|
|
238
|
+
const gitignorePath = join(cwd, ".gitignore");
|
|
239
|
+
const gitignore = existsSync(gitignorePath) ? readFileSync(gitignorePath, "utf8") : "";
|
|
240
|
+
const gitignoreDone = gitignore.includes(gitignoreBlock);
|
|
241
|
+
if (!gitignoreDone) {
|
|
242
|
+
const separator = gitignore === "" ? "" : gitignore.endsWith("\n") ? "\n" : "\n\n";
|
|
243
|
+
appendFileSync(gitignorePath, `${separator}${gitignoreBlock}\n`);
|
|
244
|
+
}
|
|
245
|
+
const local = join(cwd, ".envs/.env.local");
|
|
246
|
+
const localExists = existsSync(local);
|
|
247
|
+
const example = [config.example ?? [], exampleFiles].flat().find((file) => existsSync(join(cwd, file)));
|
|
248
|
+
if (!localExists) {
|
|
249
|
+
if (example) copyFileSync(join(cwd, example), local, constants.COPYFILE_EXCL);
|
|
250
|
+
else writeFileSync(local, "", { flag: "wx" });
|
|
251
|
+
}
|
|
252
|
+
console.log([
|
|
253
|
+
`${dirExists ? "Exists " : "Created"} .envs/`,
|
|
254
|
+
`${gitignoreDone ? "Exists " : "Updated"} .gitignore`,
|
|
255
|
+
localExists ? "Exists .envs/.env.local" : `Created .envs/.env.local ${example ? `from ${example}` : "(empty, no example file)"}`
|
|
256
|
+
].join("\n"));
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
try {
|
|
260
|
+
await program.parseAsync(argv, { from: "user" });
|
|
261
|
+
} catch (error) {
|
|
262
|
+
console.error(`newenv: ${error instanceof Error ? error.message : error}`);
|
|
263
|
+
process.exitCode = 1;
|
|
264
|
+
}
|
|
265
|
+
export {};
|
|
266
|
+
|
|
267
|
+
//# sourceMappingURL=cli.mjs.map
|
package/dist/cli.mjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.mjs","names":[],"sources":["../package.json","../src/env.ts","../src/prompt.ts","../src/run.ts","../src/cli.ts"],"sourcesContent":["","import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { parse } from \"dotenv\";\nimport { expand } from \"dotenv-expand\";\nimport type { ResolvedConfig } from \"./config\";\n\nexport const envsDir = \".envs\";\nexport const baseFile = \".envs/.env\";\nexport const currentFile = \".envs/current\";\n\n// Frameworks like Next.js load these from the project root on their own, which would mix them\n// into every environment\nexport const rootEnvFiles = [\n \".env\",\n \".env.local\",\n \".env.development\",\n \".env.development.local\",\n \".env.production\",\n \".env.production.local\",\n];\n\n/**\n * The selected environment: the name in .envs/current, or local\n */\nexport function currentEnvironment(cwd: string): string {\n const file = join(cwd, currentFile);\n return (existsSync(file) && readFileSync(file, \"utf8\").trim()) || \"local\";\n}\n\n/**\n * The environments with a .envs/.env.<name> file\n */\nexport function listEnvironments(cwd: string): string[] {\n const dir = join(cwd, envsDir);\n return existsSync(dir)\n ? readdirSync(dir)\n .map((file) => /^\\.env\\.([\\w-]+)$/.exec(file)?.[1])\n .filter((name): name is string => name !== undefined && name !== \"example\")\n .toSorted()\n : [];\n}\n\n/**\n * Throws when root env files exist, the base holds forbidden keys or the environment file is missing\n */\nexport function checkFiles(cwd: string, config: ResolvedConfig, name: string): void {\n const rootFiles = rootEnvFiles.filter((file) => existsSync(join(cwd, file)));\n if (rootFiles.length > 0) {\n throw new Error(\n `${rootFiles.join(\", \")} in the project root. Move into .envs/: mv -n ${rootFiles.join(\" \")} .envs/`,\n );\n }\n\n const base = join(cwd, baseFile);\n const forbidden = existsSync(base)\n ? Object.keys(parse(readFileSync(base))).filter((key) => config.forbiddenInBase.includes(key))\n : [];\n if (forbidden.length > 0) {\n throw new Error(\n `${forbidden.join(\", \")} in the shared ${baseFile}. Move to .envs/.env.<name> for each environment.`,\n );\n }\n\n const envFile = `.envs/.env.${name}`;\n if (!existsSync(join(cwd, envFile))) {\n throw new Error(\n name === \"local\"\n ? `${envFile} not found. Create it with: newenv init`\n : `${envFile} not found. Switch back with: newenv use local`,\n );\n }\n}\n\n/**\n * Merges the shell env, the base and the environment file: the last one wins. Expands variables\n * over the merged env, the same way dotenv-cli does.\n */\nexport function loadEnv(\n cwd: string,\n name: string,\n shellEnv: NodeJS.ProcessEnv,\n): { env: Record<string, string>; files: string[] } {\n const files = [baseFile, `.envs/.env.${name}`].filter((file) => existsSync(join(cwd, file)));\n const env: Record<string, string> = Object.assign(\n {},\n shellEnv,\n ...files.map((file) => parse(readFileSync(join(cwd, file)))),\n );\n expand({ parsed: env, processEnv: env });\n return { env, files };\n}\n","import type { Readable, Writable } from \"node:stream\";\nimport confirmPrompt from \"@inquirer/confirm\";\nimport input from \"@inquirer/input\";\n\nexport interface Streams {\n input: Readable & { isTTY?: boolean };\n output: Writable;\n}\n\n/**\n * Asks y/N, or to type the name for `\"type-name\"`. Ctrl+C answers no. Throws without a TTY, so\n * agents and CI can't confirm by accident.\n */\nexport async function confirm(\n mode: true | \"type-name\",\n name: string,\n question: string,\n streams: Streams,\n): Promise<boolean> {\n if (!streams.input.isTTY) {\n throw new Error(`${question}: needs confirmation, no TTY. Aborted.`);\n }\n\n try {\n return mode === \"type-name\"\n ? (await input({ message: `${question}? Type \"${name}\" to confirm:` }, streams)) === name\n : await confirmPrompt({ message: `${question}?`, default: false }, streams);\n } catch (error) {\n if (error instanceof Error && error.name === \"ExitPromptError\") {\n return false;\n }\n throw error;\n }\n}\n","import { styleText } from \"node:util\";\nimport spawn from \"cross-spawn\";\nimport { type Color, environmentSettings, type ResolvedConfig } from \"./config\";\nimport { checkFiles, currentEnvironment, loadEnv } from \"./env\";\nimport { confirm, type Streams } from \"./prompt\";\n\nexport interface Context {\n cwd: string;\n env: NodeJS.ProcessEnv;\n config: ResolvedConfig;\n streams: Streams;\n}\n\nconst badgeStyles = {\n red: [\"bgRed\", \"white\", \"bold\"],\n yellow: [\"bgYellow\", \"black\"],\n green: [\"bgGreen\", \"black\"],\n blue: [\"bgBlue\", \"white\"],\n magenta: [\"bgMagenta\", \"white\"],\n cyan: [\"bgCyan\", \"black\"],\n gray: [\"bgGray\", \"white\"],\n} as const satisfies Record<Color, readonly string[]>;\n\nconst signals = [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"] as const;\n\n/**\n * Checks the files, prints the banner, confirms and returns the env to run a command with\n */\nexport async function prepareRun(\n command: string,\n { cwd, env, config, streams }: Context,\n forceConfirm = false,\n): Promise<NodeJS.ProcessEnv> {\n if (config.passthrough.some((key) => env[key])) {\n return env;\n }\n\n const name = currentEnvironment(cwd);\n checkFiles(cwd, config, name);\n\n const loaded = loadEnv(cwd, name, env);\n const settings = environmentSettings(config, name);\n const script = env.npm_lifecycle_event ?? command;\n\n if (name !== \"local\") {\n const badge = styleText([...badgeStyles[settings.color]], ` ${name.toUpperCase()} `, {\n stream: streams.output,\n });\n streams.output.write(`${badge} ${script} uses ${loaded.files.join(\" + \")}\\n`);\n }\n\n const asks = forceConfirm || config.confirmScripts.includes(env.npm_lifecycle_event ?? \"\");\n if (\n asks &&\n settings.confirm &&\n !(await confirm(settings.confirm, name, `Run ${script} against ${name}`, streams))\n ) {\n throw new Error(\"Aborted.\");\n }\n\n return loaded.env;\n}\n\n/**\n * Runs a command with inherited stdio and forwards signals to it until it exits. In a terminal,\n * Ctrl+C and hangups already reach the whole foreground process group, the command included, so\n * only SIGTERM is forwarded there. newenv still catches the others, to exit after the command.\n */\nexport function spawnCommand(\n command: string,\n args: string[],\n env: NodeJS.ProcessEnv,\n): Promise<{ code: number | null; signal: NodeJS.Signals | null }> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, { stdio: \"inherit\", env });\n const forward = (signal: NodeJS.Signals) => {\n if (signal === \"SIGTERM\" || !process.stdin.isTTY) {\n child.kill(signal);\n }\n };\n const stopForwarding = () => {\n signals.forEach((signal) => {\n process.off(signal, forward);\n });\n };\n signals.forEach((signal) => {\n process.on(signal, forward);\n });\n\n child.on(\"error\", (error) => {\n stopForwarding();\n reject(error);\n });\n child.on(\"exit\", (code, signal) => {\n stopForwarding();\n resolve({ code, signal });\n });\n });\n}\n","#!/usr/bin/env node\nimport {\n appendFileSync,\n constants,\n copyFileSync,\n existsSync,\n mkdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport { Command } from \"commander\";\nimport { version } from \"../package.json\";\nimport { environmentSettings, loadConfig } from \"./config\";\nimport {\n baseFile,\n checkFiles,\n currentEnvironment,\n currentFile,\n envsDir,\n listEnvironments,\n} from \"./env\";\nimport { confirm } from \"./prompt\";\nimport { prepareRun, spawnCommand } from \"./run\";\n\nconst argv = process.argv.slice(2);\nconst cwd = process.cwd();\nconst streams = { input: process.stdin, output: process.stderr };\n\n// `.env*` patterns in existing gitignores also match the .envs folder, and git can't re-include a\n// file in an ignored folder. So the folder is re-included first, then its contents ignored.\nconst gitignoreBlock = [\"# newenv\", \"/.env*\", \"!/.envs/\", \"/.envs/*\", \"!/.envs/.env.example\"].join(\n \"\\n\",\n);\n\nconst exampleFiles = [\".envs/.env.example\", \".example-env\", \".env.example\"];\n\nconst program = new Command(\"newenv\")\n .description(\"Run a command with the env files of the selected environment\")\n .usage(\"[options] <command> [args...]\")\n .version(version, \"-v, --version\", \"Show version\")\n .helpOption(\"-h, --help\", \"Show help\")\n // Options after the command belong to the command\n .enablePositionalOptions()\n .passThroughOptions()\n .option(\"--confirm\", \"Ask before running, as for confirmScripts\")\n .argument(\"[command...]\", \"Command to run. Put -- before one named use, status or init\")\n .configureOutput({\n outputError: (message, write) => write(`newenv: ${message.replace(/^error: /, \"\")}`),\n })\n .action(async (command: string[], options: { confirm?: boolean }) => {\n const [name, ...args] = command;\n if (!name) {\n return program.help({ error: argv.length > 0 });\n }\n\n const config = await loadConfig(cwd);\n const env = await prepareRun(name, { cwd, env: process.env, config, streams }, options.confirm);\n const { code, signal } = await spawnCommand(name, args, env).catch(\n (error: NodeJS.ErrnoException) => {\n if (error.code !== \"ENOENT\") {\n throw error;\n }\n console.error(`newenv: command not found: ${name}`);\n return { code: 127, signal: null };\n },\n );\n if (signal) {\n process.kill(process.pid, signal);\n }\n process.exitCode = code ?? 1;\n });\n\n// Commander still matches subcommands after --, so `newenv -- status` gets none\nif (argv[argv.findIndex((arg) => arg === \"--\" || !arg.startsWith(\"-\"))] !== \"--\") {\n program\n .command(\"use\")\n .description(\"Switch environment\")\n .argument(\"<name>\", \"Environment, local deletes .envs/current\")\n .action(async (name: string) => {\n const envFile = `.envs/.env.${name}`;\n if (name === \"local\") {\n rmSync(join(cwd, currentFile), { force: true });\n console.log(\n existsSync(join(cwd, envFile))\n ? \"Switched to local.\"\n : `Switched to local. ${envFile} not found. Create it with: newenv init`,\n );\n return;\n }\n\n const environments = listEnvironments(cwd);\n if (!environments.includes(name)) {\n throw new Error(`${envFile} not found. Available: ${environments.join(\", \") || \"none\"}`);\n }\n\n const config = await loadConfig(cwd);\n if (\n environmentSettings(config, name).confirm === \"type-name\" &&\n !(await confirm(true, name, `Switch to ${name}`, streams))\n ) {\n throw new Error(\"Aborted.\");\n }\n\n writeFileSync(join(cwd, currentFile), `${name}\\n`);\n console.log(`Switched to ${name}.`);\n });\n\n program\n .command(\"status\")\n .description(\"Show the environment and its files\")\n .action(async () => {\n const config = await loadConfig(cwd);\n const name = currentEnvironment(cwd);\n const envFile = `.envs/.env.${name}`;\n const files = [\n ...(existsSync(join(cwd, baseFile)) ? [baseFile] : []),\n existsSync(join(cwd, envFile)) ? envFile : `${envFile} (missing)`,\n ];\n const passthrough = config.passthrough.filter((key) => process.env[key]);\n const problem = (() => {\n try {\n checkFiles(cwd, config, name);\n return undefined;\n } catch (error) {\n return (error as Error).message;\n }\n })();\n\n console.log(\n [\n [\"Environment\", name],\n [\"Files\", files.join(\" + \")],\n [\"Available\", listEnvironments(cwd).join(\", \") || \"none\"],\n [\"Config\", config.file],\n [\n \"Passthrough\",\n passthrough.length > 0 ? `${passthrough.join(\", \")} set, files ignored` : undefined,\n ],\n [\"Problem\", problem],\n ]\n .filter(([, value]) => value !== undefined)\n .map(([label, value]) => `${label?.padEnd(12)} ${value}`)\n .join(\"\\n\"),\n );\n });\n\n program\n .command(\"init\")\n .description(\"Set up .envs/, the gitignore rules and .envs/.env.local\")\n .action(async () => {\n const config = await loadConfig(cwd);\n const dir = join(cwd, envsDir);\n const dirExists = existsSync(dir);\n mkdirSync(dir, { recursive: true });\n\n const gitignorePath = join(cwd, \".gitignore\");\n const gitignore = existsSync(gitignorePath) ? readFileSync(gitignorePath, \"utf8\") : \"\";\n const gitignoreDone = gitignore.includes(gitignoreBlock);\n if (!gitignoreDone) {\n const separator = gitignore === \"\" ? \"\" : gitignore.endsWith(\"\\n\") ? \"\\n\" : \"\\n\\n\";\n appendFileSync(gitignorePath, `${separator}${gitignoreBlock}\\n`);\n }\n\n const local = join(cwd, \".envs/.env.local\");\n const localExists = existsSync(local);\n const example = [config.example ?? [], exampleFiles]\n .flat()\n .find((file) => existsSync(join(cwd, file)));\n if (!localExists) {\n if (example) {\n copyFileSync(join(cwd, example), local, constants.COPYFILE_EXCL);\n } else {\n writeFileSync(local, \"\", { flag: \"wx\" });\n }\n }\n\n console.log(\n [\n `${dirExists ? \"Exists \" : \"Created\"} .envs/`,\n `${gitignoreDone ? \"Exists \" : \"Updated\"} .gitignore`,\n localExists\n ? \"Exists .envs/.env.local\"\n : `Created .envs/.env.local ${example ? `from ${example}` : \"(empty, no example file)\"}`,\n ].join(\"\\n\"),\n );\n });\n}\n\ntry {\n await program.parseAsync(argv, { from: \"user\" });\n} catch (error) {\n console.error(`newenv: ${error instanceof Error ? error.message : error}`);\n process.exitCode = 1;\n}\n"],"mappings":";;;;;;;;;;;;;;ACMA,MAAa,UAAU;AACvB,MAAa,WAAW;AACxB,MAAa,cAAc;AAI3B,MAAa,eAAe;CAC1B;CACA;CACA;CACA;CACA;CACA;AACF;;;;AAKA,SAAgB,mBAAmB,KAAqB;CACtD,MAAM,OAAO,KAAK,K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AU;GACzC,cACI,6BACA,4BAA4B,UAAU,QAAQ,YAAY;EAChE,CAAC,CAAC,KAAK,IAAI,CACb;CACF,CAAC;AACL;AAEA,IAAI;CACF,MAAM,QAAQ,WAAW,MAAM,EAAE,MAAM,OAAO,CAAC;AACjD,SAAS,OAAO;CACd,QAAQ,MAAM,WAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO;CACzE,QAAQ,WAAW;AACrB"}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { pathToFileURL } from "node:url";
|
|
4
|
+
// src/config.ts
|
|
5
|
+
const defineConfig = (config) => config;
|
|
6
|
+
const defaults = {
|
|
7
|
+
environments: {},
|
|
8
|
+
confirmScripts: [
|
|
9
|
+
"db:push",
|
|
10
|
+
"db:migrate",
|
|
11
|
+
"db:seed"
|
|
12
|
+
],
|
|
13
|
+
forbiddenInBase: ["DATABASE_URL"],
|
|
14
|
+
passthrough: []
|
|
15
|
+
};
|
|
16
|
+
const defaultEnvironments = {
|
|
17
|
+
local: { confirm: false },
|
|
18
|
+
production: {
|
|
19
|
+
color: "red",
|
|
20
|
+
confirm: "type-name"
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
const configFiles = [
|
|
24
|
+
"newenv.config.ts",
|
|
25
|
+
"newenv.config.mjs",
|
|
26
|
+
"newenv.config.js"
|
|
27
|
+
];
|
|
28
|
+
async function loadConfig(cwd) {
|
|
29
|
+
const file = configFiles.find((name) => existsSync(join(cwd, name)));
|
|
30
|
+
if (!file) return defaults;
|
|
31
|
+
const module = await import(pathToFileURL(join(cwd, file)).href);
|
|
32
|
+
return {
|
|
33
|
+
...defaults,
|
|
34
|
+
...module.default,
|
|
35
|
+
file
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function environmentSettings(config, name) {
|
|
39
|
+
return {
|
|
40
|
+
color: "yellow",
|
|
41
|
+
confirm: true,
|
|
42
|
+
...defaultEnvironments[name],
|
|
43
|
+
...config.environments[name]
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export { environmentSettings as n, loadConfig as r, defineConfig as t };
|
|
47
|
+
|
|
48
|
+
//# sourceMappingURL=config-DdWBrqcV.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config-DdWBrqcV.mjs","names":[],"sources":["../src/config.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nexport type Color = \"red\" | \"yellow\" | \"green\" | \"blue\" | \"magenta\" | \"cyan\" | \"gray\";\n\nexport interface EnvironmentConfig {\n /**\n * Badge color. Default: red for production, yellow for others\n */\n color?: Color;\n /**\n * Confirmation before `confirmScripts`: `true` asks y/N, `\"type-name\"` asks to type the\n * environment name and also guards `newenv use`. Default: `\"type-name\"` for production,\n * `false` for local, `true` for others\n */\n confirm?: boolean | \"type-name\";\n}\n\nexport interface Config {\n /**\n * Settings per environment name\n */\n environments?: Record<string, EnvironmentConfig>;\n /**\n * Scripts (`npm_lifecycle_event`) that ask before running. Default: db:push, db:migrate, db:seed\n */\n confirmScripts?: string[];\n /**\n * Keys refused in the shared `.envs/.env`. Default: DATABASE_URL\n */\n forbiddenInBase?: string[];\n /**\n * When one of these is set, commands run as is with the existing env, e.g. `VERCEL` on a host\n * that provides the env. Default: none\n */\n passthrough?: string[];\n /**\n * Source for `newenv init`. Default: the first of .envs/.env.example, .example-env, .env.example\n */\n example?: string;\n}\n\nexport type ResolvedConfig = Required<Omit<Config, \"example\">> & {\n example?: string;\n /**\n * The config file that was loaded\n */\n file?: string;\n};\n\nexport const defineConfig = (config: Config): Config => config;\n\nexport const defaults: ResolvedConfig = {\n environments: {},\n confirmScripts: [\"db:push\", \"db:migrate\", \"db:seed\"],\n forbiddenInBase: [\"DATABASE_URL\"],\n passthrough: [],\n};\n\nconst defaultEnvironments: Record<string, EnvironmentConfig> = {\n local: { confirm: false },\n production: { color: \"red\", confirm: \"type-name\" },\n};\n\nexport const configFiles = [\"newenv.config.ts\", \"newenv.config.mjs\", \"newenv.config.js\"];\n\nexport async function loadConfig(cwd: string): Promise<ResolvedConfig> {\n const file = configFiles.find((name) => existsSync(join(cwd, name)));\n if (!file) {\n return defaults;\n }\n\n const module = await import(pathToFileURL(join(cwd, file)).href);\n return { ...defaults, ...(module.default as Config), file };\n}\n\nexport function environmentSettings(\n config: ResolvedConfig,\n name: string,\n): Required<EnvironmentConfig> {\n return {\n color: \"yellow\",\n confirm: true,\n ...defaultEnvironments[name],\n ...config.environments[name],\n };\n}\n"],"mappings":";;;;AAmDA,MAAa,gBAAgB,WAA2B;AAExD,MAAa,WAA2B;CACtC,cAAc,CAAC;CACf,gBAAgB;EAAC;EAAW;EAAc;CAAS;CACnD,iBAAiB,CAAC,cAAc;CAChC,aAAa,CAAC;AAChB;AAEA,MAAM,sBAAyD;CAC7D,OAAO,EAAE,SAAS,MAAM;CACxB,YAAY;EAAE,OAAO;EAAO,SAAS;CAAY;AACnD;AAEA,MAAa,cAAc;CAAC;CAAoB;CAAqB;AAAkB;AAEvF,eAAsB,WAAW,KAAsC;CACrE,MAAM,OAAO,YAAY,MAAM,SAAS,WAAW,KAAK,KAAK,IAAI,CAAC,CAAC;CACnE,IAAI,CAAC,MACH,OAAO;CAGT,MAAM,SAAS,MAAM,OAAO,cAAc,KAAK,KAAK,IAAI,CAAC,CAAC,CAAC;CAC3D,OAAO;EAAE,GAAG;EAAU,GAAI,OAAO;EAAoB;CAAK;AAC5D;AAEA,SAAgB,oBACd,QACA,MAC6B;CAC7B,OAAO;EACL,OAAO;EACP,SAAS;EACT,GAAG,oBAAoB;EACvB,GAAG,OAAO,aAAa;CACzB;AACF"}
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
type Color = "red" | "yellow" | "green" | "blue" | "magenta" | "cyan" | "gray";
|
|
2
|
+
interface EnvironmentConfig {
|
|
3
|
+
/**
|
|
4
|
+
* Badge color. Default: red for production, yellow for others
|
|
5
|
+
*/
|
|
6
|
+
color?: Color;
|
|
7
|
+
/**
|
|
8
|
+
* Confirmation before `confirmScripts`: `true` asks y/N, `"type-name"` asks to type the
|
|
9
|
+
* environment name and also guards `newenv use`. Default: `"type-name"` for production,
|
|
10
|
+
* `false` for local, `true` for others
|
|
11
|
+
*/
|
|
12
|
+
confirm?: boolean | "type-name";
|
|
13
|
+
}
|
|
14
|
+
interface Config {
|
|
15
|
+
/**
|
|
16
|
+
* Settings per environment name
|
|
17
|
+
*/
|
|
18
|
+
environments?: Record<string, EnvironmentConfig>;
|
|
19
|
+
/**
|
|
20
|
+
* Scripts (`npm_lifecycle_event`) that ask before running. Default: db:push, db:migrate, db:seed
|
|
21
|
+
*/
|
|
22
|
+
confirmScripts?: string[];
|
|
23
|
+
/**
|
|
24
|
+
* Keys refused in the shared `.envs/.env`. Default: DATABASE_URL
|
|
25
|
+
*/
|
|
26
|
+
forbiddenInBase?: string[];
|
|
27
|
+
/**
|
|
28
|
+
* When one of these is set, commands run as is with the existing env, e.g. `VERCEL` on a host
|
|
29
|
+
* that provides the env. Default: none
|
|
30
|
+
*/
|
|
31
|
+
passthrough?: string[];
|
|
32
|
+
/**
|
|
33
|
+
* Source for `newenv init`. Default: the first of .envs/.env.example, .example-env, .env.example
|
|
34
|
+
*/
|
|
35
|
+
example?: string;
|
|
36
|
+
}
|
|
37
|
+
export declare const defineConfig: (config: Config) => Config;
|
|
38
|
+
export type { Color, Config, EnvironmentConfig };
|
|
39
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/config.ts"],"mappings":"A,KAIY;UAEK;;;;EAIf,QAAQ;;;;;;EAMR;;UAGe;;;;EAIf,eAAe,eAAe;;;;EAI9B;;;;EAIA;;;;;EAKA;;;;EAIA;;qBAWW,eAAgB,QAAQ,WAAS"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { t as defineConfig } from "./config-DdWBrqcV.mjs";
|
package/package.json
CHANGED
|
@@ -1,6 +1,87 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@newcode-team/env",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Per-environment env files for any command, with switching and guards",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"sideEffects": false,
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"author": "NewCode",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/NewCodeDevelopment/newenv.git"
|
|
12
|
+
},
|
|
13
|
+
"homepage": "https://github.com/NewCodeDevelopment/newenv#readme",
|
|
14
|
+
"bugs": "https://github.com/NewCodeDevelopment/newenv/issues",
|
|
15
|
+
"keywords": [
|
|
16
|
+
"env",
|
|
17
|
+
"dotenv",
|
|
18
|
+
"environment",
|
|
19
|
+
"cli"
|
|
20
|
+
],
|
|
21
|
+
"bin": {
|
|
22
|
+
"newenv": "./dist/cli.mjs"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@inquirer/confirm": "^6.4.0",
|
|
26
|
+
"@inquirer/input": "^5.2.0",
|
|
27
|
+
"commander": "^15.1.0",
|
|
28
|
+
"cross-spawn": "^7.0.6",
|
|
29
|
+
"dotenv": "^17.4.2",
|
|
30
|
+
"dotenv-expand": "^12.0.3"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@arethetypeswrong/core": "^0.18.5",
|
|
34
|
+
"@changesets/cli": "^3.0.3",
|
|
35
|
+
"@types/cross-spawn": "^6.0.6",
|
|
36
|
+
"@types/node": "^24.19.2",
|
|
37
|
+
"dotenv-cli": "11.0.0",
|
|
38
|
+
"oxfmt": "0.78.0",
|
|
39
|
+
"oxlint": "1.93.0",
|
|
40
|
+
"publint": "^0.3.25",
|
|
41
|
+
"tsdown": "^0.23.7",
|
|
42
|
+
"typescript": "5.9.3",
|
|
43
|
+
"unrun": "^0.3.1",
|
|
44
|
+
"vitest": "^5.1.0",
|
|
45
|
+
"node": "runtime:^24.x"
|
|
46
|
+
},
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"engines": {
|
|
51
|
+
"node": ">=24"
|
|
52
|
+
},
|
|
53
|
+
"files": [
|
|
54
|
+
"dist"
|
|
55
|
+
],
|
|
56
|
+
"exports": {
|
|
57
|
+
".": "./dist/index.mjs",
|
|
58
|
+
"./package.json": "./package.json"
|
|
59
|
+
},
|
|
60
|
+
"devEngines": {
|
|
61
|
+
"packageManager": {
|
|
62
|
+
"name": "pnpm",
|
|
63
|
+
"version": "11.27.0"
|
|
64
|
+
},
|
|
65
|
+
"runtime": {
|
|
66
|
+
"name": "node",
|
|
67
|
+
"version": "^24.x",
|
|
68
|
+
"onFail": "download"
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
"scripts": {
|
|
72
|
+
"dev": "tsdown --config tsdown.config.ts --config-loader unrun --watch --no-clean",
|
|
73
|
+
"build": "tsdown --config tsdown.config.ts --config-loader unrun --no-clean",
|
|
74
|
+
"build:release": "tsdown --config tsdown.config.ts --config-loader unrun",
|
|
75
|
+
"lint": "oxlint",
|
|
76
|
+
"lint:fix": "oxlint --fix",
|
|
77
|
+
"format": "oxfmt",
|
|
78
|
+
"format:check": "oxfmt --check",
|
|
79
|
+
"typecheck": "tsc --noEmit",
|
|
80
|
+
"test": "vitest",
|
|
81
|
+
"test:ci": "vitest run",
|
|
82
|
+
"changeset": "changeset",
|
|
83
|
+
"version-packages": "changeset version",
|
|
84
|
+
"release": "pnpm build:release && changeset publish",
|
|
85
|
+
"clean": "rm -rf node_modules && rm -rf dist"
|
|
86
|
+
}
|
|
6
87
|
}
|