@secretenvs/cli 0.0.0-stage → 1.0.1

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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +79 -2
  3. package/dist/index.js +1258 -0
  4. package/package.json +49 -3
package/dist/index.js ADDED
@@ -0,0 +1,1258 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/deps.ts
4
+ import { spawn } from "child_process";
5
+ import { homedir } from "os";
6
+ import { confirm, input, password } from "@inquirer/prompts";
7
+ function defaultDeps() {
8
+ return {
9
+ env: process.env,
10
+ cwd: process.cwd(),
11
+ homeDir: homedir(),
12
+ stdout: process.stdout,
13
+ stderr: process.stderr,
14
+ interactive: Boolean(process.stdin.isTTY),
15
+ fetch: globalThis.fetch.bind(globalThis),
16
+ prompts: {
17
+ input: (config) => input(config),
18
+ password: (config) => password({ ...config, mask: false }),
19
+ confirm: (config) => confirm(config)
20
+ },
21
+ spawn: (command, args, options) => spawn(command, args, options)
22
+ };
23
+ }
24
+
25
+ // src/program.ts
26
+ import { Command, CommanderError } from "commander";
27
+
28
+ // src/commands.ts
29
+ import { chmod as chmod2, writeFile as writeFile2 } from "fs/promises";
30
+ import { constants as osConstants } from "os";
31
+ import { resolve } from "path";
32
+
33
+ // ../contracts/dist/index.js
34
+ import { z as z3 } from "zod";
35
+ import { z } from "zod";
36
+ import { z as z2 } from "zod";
37
+ var VARIABLE_KEY_REGEX = /^[A-Z_][A-Z0-9_]*$/;
38
+ var SLUG_REGEX = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
39
+ var MAX_KEY_LENGTH = 128;
40
+ var MAX_VALUE_BYTES = 64 * 1024;
41
+ var MAX_NAME_LENGTH = 64;
42
+ var MAX_BULK_VARIABLES = 500;
43
+ var MIN_PASSWORD_LENGTH = 12;
44
+ var MAX_PASSWORD_LENGTH = 256;
45
+ var MAX_VERSIONS_LIMIT = 100;
46
+ var CSRF_HEADER_NAME = "x-requested-with";
47
+ var CSRF_HEADER_VALUE = "secretenvs-web";
48
+ var ProjectRole = z.enum(["OWNER", "ADMIN", "EDITOR", "VIEWER"]);
49
+ var TokenAccess = z.enum(["READ", "READ_WRITE"]);
50
+ var VersionChangeType = z.enum(["CREATED", "UPDATED", "ROLLBACK"]);
51
+ var ErrorCode = z.enum([
52
+ "VALIDATION_ERROR",
53
+ "BAD_REQUEST",
54
+ "UNAUTHENTICATED",
55
+ "FORBIDDEN",
56
+ "NOT_FOUND",
57
+ "CONFLICT",
58
+ "RATE_LIMITED",
59
+ "INTERNAL"
60
+ ]);
61
+ var id = z2.uuid();
62
+ var isoDate = z2.iso.datetime();
63
+ var email = z2.string().trim().toLowerCase().pipe(z2.email().max(254));
64
+ var name = z2.string().trim().min(1).max(MAX_NAME_LENGTH);
65
+ var slug = z2.string().min(1).max(MAX_NAME_LENGTH).regex(SLUG_REGEX);
66
+ var variableKey = z2.string().min(1).max(MAX_KEY_LENGTH).regex(VARIABLE_KEY_REGEX);
67
+ var variableValue = z2.string().refine(
68
+ (value) => new TextEncoder().encode(value).length <= MAX_VALUE_BYTES,
69
+ {
70
+ message: `Value must be at most ${MAX_VALUE_BYTES} bytes`
71
+ }
72
+ );
73
+ var password2 = z2.string().min(MIN_PASSWORD_LENGTH).max(MAX_PASSWORD_LENGTH);
74
+ var RegisterInput = z2.object({ email, name, password: password2 }).strict();
75
+ var LoginInput = z2.object({ email, password: z2.string().min(1).max(MAX_PASSWORD_LENGTH) }).strict();
76
+ var UserDto = z2.object({ id, email, name, createdAt: isoDate }).strict();
77
+ var CreateProjectInput = z2.object({ name, slug, description: z2.string().max(500).optional() }).strict();
78
+ var UpdateProjectInput = z2.object({
79
+ name: name.optional(),
80
+ description: z2.string().max(500).nullable().optional()
81
+ }).strict();
82
+ var ProjectDto = z2.object({
83
+ id,
84
+ name,
85
+ slug,
86
+ description: z2.string().nullable(),
87
+ createdAt: isoDate,
88
+ updatedAt: isoDate
89
+ }).strict();
90
+ var ProjectSummaryDto = ProjectDto.extend({ role: ProjectRole });
91
+ var AddMemberInput = z2.object({ email, role: ProjectRole }).strict();
92
+ var UpdateMemberInput = z2.object({ role: ProjectRole }).strict();
93
+ var MemberDto = z2.object({ userId: id, email, name, role: ProjectRole, createdAt: isoDate }).strict();
94
+ var CreateEnvironmentInput = z2.object({ name, slug }).strict();
95
+ var UpdateEnvironmentInput = z2.object({ name: name.optional(), slug: slug.optional() }).strict();
96
+ var EnvironmentDto = z2.object({
97
+ id,
98
+ projectId: id,
99
+ name,
100
+ slug,
101
+ createdAt: isoDate,
102
+ updatedAt: isoDate
103
+ }).strict();
104
+ var CreateVariableInput = z2.object({ key: variableKey, value: variableValue }).strict();
105
+ var UpdateVariableInput = z2.object({ value: variableValue }).strict();
106
+ var VariableMetaDto = z2.object({
107
+ id,
108
+ key: variableKey,
109
+ currentVersion: z2.number().int().min(1),
110
+ updatedAt: isoDate
111
+ }).strict();
112
+ var VariableWithValueDto = VariableMetaDto.extend({
113
+ value: z2.string()
114
+ });
115
+ var BulkUpsertVariablesInput = z2.object({
116
+ variables: z2.array(CreateVariableInput).min(1).max(MAX_BULK_VARIABLES).refine(
117
+ (items) => new Set(items.map((item) => item.key)).size === items.length,
118
+ { message: "Duplicate keys are not allowed" }
119
+ )
120
+ }).strict();
121
+ var BulkUpsertVariablesResponse = z2.object({
122
+ created: z2.number().int().min(0),
123
+ updated: z2.number().int().min(0),
124
+ unchanged: z2.number().int().min(0)
125
+ }).strict();
126
+ var environmentIds = z2.array(id).max(100);
127
+ var CreateSharedVariableInput = z2.object({ key: variableKey, value: variableValue, environmentIds }).strict();
128
+ var UpdateSharedVariableInput = z2.object({
129
+ value: variableValue.optional(),
130
+ environmentIds: environmentIds.optional()
131
+ }).strict().refine(
132
+ (input2) => input2.value !== void 0 || input2.environmentIds !== void 0,
133
+ {
134
+ message: "Provide value and/or environmentIds"
135
+ }
136
+ );
137
+ var SharedVariableMetaDto = VariableMetaDto.extend({ environmentIds });
138
+ var ListVersionsQuery = z2.object({
139
+ cursor: z2.string().min(1).max(256).optional(),
140
+ limit: z2.coerce.number().int().min(1).max(MAX_VERSIONS_LIMIT).default(20)
141
+ }).strict();
142
+ var VariableVersionMetaDto = z2.object({
143
+ version: z2.number().int().min(1),
144
+ changeType: VersionChangeType,
145
+ restoredFromVersion: z2.number().int().min(1).nullable().optional(),
146
+ changedBy: z2.object({ id, name: z2.string() }).strict().nullable(),
147
+ createdAt: isoDate,
148
+ isCurrent: z2.boolean()
149
+ }).strict();
150
+ var PaginatedVersionsResponse = z2.object({
151
+ items: z2.array(VariableVersionMetaDto),
152
+ nextCursor: z2.string().optional()
153
+ }).strict();
154
+ var VariableVersionValueDto = z2.object({ version: z2.number().int().min(1), value: z2.string() }).strict();
155
+ var ResolvedVariableDto = z2.object({
156
+ key: variableKey,
157
+ value: z2.string(),
158
+ source: z2.enum(["environment", "shared"])
159
+ }).strict();
160
+ var ResolvedVariablesResponse = z2.object({
161
+ project: z2.object({ id, slug }).strict(),
162
+ environment: z2.object({ id, slug }).strict(),
163
+ variables: z2.array(ResolvedVariableDto)
164
+ }).strict();
165
+ var SdkEnvironmentDto = z2.object({ id, slug, name }).strict();
166
+ var SdkProjectDto = z2.object({
167
+ id,
168
+ slug,
169
+ name,
170
+ role: ProjectRole,
171
+ environments: z2.array(SdkEnvironmentDto)
172
+ }).strict();
173
+ var CreateTokenInput = z2.object({
174
+ name,
175
+ access: TokenAccess,
176
+ projectId: id.optional(),
177
+ environmentId: id.optional(),
178
+ expiresInDays: z2.number().int().min(1).max(365).optional()
179
+ }).strict().refine((input2) => !input2.environmentId || !!input2.projectId, {
180
+ message: "environmentId requires projectId",
181
+ path: ["environmentId"]
182
+ });
183
+ var TokenDto = z2.object({
184
+ id,
185
+ name,
186
+ prefix: z2.string().length(8),
187
+ access: TokenAccess,
188
+ projectId: id.nullable(),
189
+ environmentId: id.nullable(),
190
+ expiresAt: isoDate.nullable(),
191
+ revokedAt: isoDate.nullable(),
192
+ lastUsedAt: isoDate.nullable(),
193
+ createdAt: isoDate
194
+ }).strict();
195
+ var CreatedTokenDto = TokenDto.extend({ token: z2.string().min(1) });
196
+ var ApiErrorBody = z2.object({
197
+ error: z2.object({
198
+ code: ErrorCode,
199
+ message: z2.string(),
200
+ details: z2.unknown().optional()
201
+ }).strict()
202
+ }).strict();
203
+ var apiEnvironmentSchema = z3.object({
204
+ NODE_ENV: z3.enum(["development", "test", "production"]),
205
+ HOST: z3.string().min(1).default("0.0.0.0"),
206
+ PORT: z3.coerce.number().int().min(1).max(65535),
207
+ WEB_ORIGIN: z3.url().refine((value) => {
208
+ const url = new URL(value);
209
+ return ["http:", "https:"].includes(url.protocol) && url.origin === value;
210
+ }, "Expected an exact HTTP(S) origin"),
211
+ DATABASE_URL: z3.url().refine((value) => {
212
+ const url = new URL(value);
213
+ return ["postgres:", "postgresql:"].includes(url.protocol) && !!url.hostname;
214
+ }, "Expected a PostgreSQL connection URL"),
215
+ MASTER_KEY: z3.string().regex(
216
+ /^[A-Za-z0-9+/]{42}[AEIMQUYcgkosw048]=$/,
217
+ "Expected exactly 32 bytes encoded as canonical base64"
218
+ ),
219
+ COOKIE_SECURE: z3.enum(["true", "false"]).optional(),
220
+ VARIABLE_HISTORY_LIMIT: z3.coerce.number().int().min(1).max(500).default(50),
221
+ // Reverse-proxy hops in front of the API (Express `trust proxy`); 0 trusts none.
222
+ TRUST_PROXY: z3.coerce.number().int().min(0).max(10).default(0)
223
+ }).strict().transform((environment) => ({
224
+ ...environment,
225
+ COOKIE_SECURE: environment.COOKIE_SECURE === void 0 ? environment.NODE_ENV === "production" : environment.COOKIE_SECURE === "true"
226
+ }));
227
+
228
+ // ../sdk/dist/index.js
229
+ var SecretEnvsError = class extends Error {
230
+ constructor(message, options) {
231
+ super(message, options);
232
+ this.name = "SecretEnvsError";
233
+ }
234
+ };
235
+ var SecretEnvsNetworkError = class extends SecretEnvsError {
236
+ constructor(message, options) {
237
+ super(message, options);
238
+ this.name = "SecretEnvsNetworkError";
239
+ }
240
+ };
241
+ var SecretEnvsApiError = class extends SecretEnvsError {
242
+ constructor(message, status, code) {
243
+ super(message);
244
+ this.status = status;
245
+ this.code = code;
246
+ this.name = "SecretEnvsApiError";
247
+ }
248
+ status;
249
+ code;
250
+ };
251
+ var SecretEnvsAuthError = class extends SecretEnvsApiError {
252
+ constructor(message, status, code) {
253
+ super(message, status, code);
254
+ this.name = "SecretEnvsAuthError";
255
+ }
256
+ };
257
+ var SecretEnvsNotFoundError = class extends SecretEnvsApiError {
258
+ constructor(message, status = 404, code) {
259
+ super(message, status, code);
260
+ this.name = "SecretEnvsNotFoundError";
261
+ }
262
+ };
263
+ var DEFAULT_TIMEOUT_MS = 1e4;
264
+ var DEFAULT_RETRIES = 2;
265
+ var DEFAULT_RETRY_DELAY_MS = 200;
266
+ var LOCAL_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
267
+ var INSPECT = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
268
+ function nonEmpty(value) {
269
+ return value === void 0 || value === "" ? void 0 : value;
270
+ }
271
+ function normalizeBaseUrl(raw) {
272
+ let url;
273
+ try {
274
+ url = new URL(raw);
275
+ } catch {
276
+ throw new SecretEnvsError("baseUrl is not a valid URL");
277
+ }
278
+ if (url.username || url.password) {
279
+ throw new SecretEnvsError("baseUrl must not contain credentials");
280
+ }
281
+ const isLocalHttp = url.protocol === "http:" && LOCAL_HOSTS.has(url.hostname);
282
+ if (url.protocol !== "https:" && !isLocalHttp) {
283
+ throw new SecretEnvsError(
284
+ "baseUrl must use https (http is only allowed for localhost)"
285
+ );
286
+ }
287
+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
288
+ }
289
+ function integerOption(name2, value, fallback, min) {
290
+ if (value === void 0) return fallback;
291
+ if (!Number.isInteger(value) || value < min) {
292
+ throw new SecretEnvsError(`${name2} must be an integer >= ${min}`);
293
+ }
294
+ return value;
295
+ }
296
+ var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
297
+ var SecretEnvs = class {
298
+ #token;
299
+ #baseUrl;
300
+ #project;
301
+ #environment;
302
+ #timeoutMs;
303
+ #retries;
304
+ #retryDelayMs;
305
+ #cacheTtlMs;
306
+ #fetch;
307
+ #env;
308
+ #cache = /* @__PURE__ */ new Map();
309
+ constructor(options = {}) {
310
+ const env = options.env ?? process.env;
311
+ const token = nonEmpty(options.token) ?? nonEmpty(env.SECRETENVS_TOKEN);
312
+ const baseUrl = nonEmpty(options.baseUrl) ?? nonEmpty(env.SECRETENVS_URL);
313
+ if (!token) {
314
+ throw new SecretEnvsError(
315
+ 'A token is required (option "token" or SECRETENVS_TOKEN)'
316
+ );
317
+ }
318
+ if (!baseUrl) {
319
+ throw new SecretEnvsError(
320
+ 'A base URL is required (option "baseUrl" or SECRETENVS_URL)'
321
+ );
322
+ }
323
+ const fetchImpl = options.fetch ?? (typeof globalThis.fetch === "function" ? globalThis.fetch.bind(globalThis) : void 0);
324
+ if (!fetchImpl) {
325
+ throw new SecretEnvsError("fetch is not available (Node 18+ required)");
326
+ }
327
+ this.#token = token;
328
+ this.#baseUrl = normalizeBaseUrl(baseUrl);
329
+ this.#project = nonEmpty(options.project) ?? nonEmpty(env.SECRETENVS_PROJECT);
330
+ this.#environment = nonEmpty(options.environment) ?? nonEmpty(env.SECRETENVS_ENV);
331
+ this.#timeoutMs = integerOption(
332
+ "timeoutMs",
333
+ options.timeoutMs,
334
+ DEFAULT_TIMEOUT_MS,
335
+ 1
336
+ );
337
+ this.#retries = integerOption(
338
+ "retries",
339
+ options.retries,
340
+ DEFAULT_RETRIES,
341
+ 0
342
+ );
343
+ this.#retryDelayMs = integerOption(
344
+ "retryDelayMs",
345
+ options.retryDelayMs,
346
+ DEFAULT_RETRY_DELAY_MS,
347
+ 0
348
+ );
349
+ this.#cacheTtlMs = integerOption("cacheTtlMs", options.cacheTtlMs, 0, 0);
350
+ this.#fetch = fetchImpl;
351
+ this.#env = env;
352
+ }
353
+ /** Projects visible to the token, with their environments. */
354
+ async listProjects() {
355
+ return this.#get(
356
+ "/api/v1/sdk/projects",
357
+ (body) => SdkProjectDto.array().parse(body)
358
+ );
359
+ }
360
+ /** Resolved variables including where each value comes from. */
361
+ async getResolved(target = {}) {
362
+ const { project, environment } = this.#target(target);
363
+ const key = `${project}/${environment}`;
364
+ if (this.#cacheTtlMs > 0) {
365
+ const cached = this.#cache.get(key);
366
+ if (cached && cached.expiresAt > Date.now()) {
367
+ return structuredClone(cached.data);
368
+ }
369
+ }
370
+ const data = await this.#get(
371
+ `/api/v1/sdk/projects/${encodeURIComponent(project)}/environments/${encodeURIComponent(environment)}/variables`,
372
+ (body) => ResolvedVariablesResponse.parse(body)
373
+ );
374
+ if (this.#cacheTtlMs > 0) {
375
+ this.#cache.set(key, {
376
+ expiresAt: Date.now() + this.#cacheTtlMs,
377
+ data: structuredClone(data)
378
+ });
379
+ }
380
+ return data;
381
+ }
382
+ /** All variables of an environment as a plain object. */
383
+ async getVariables(target = {}) {
384
+ const { variables } = await this.getResolved(target);
385
+ return Object.fromEntries(variables.map(({ key, value }) => [key, value]));
386
+ }
387
+ /** A single value; throws SecretEnvsNotFoundError when the key is not defined. */
388
+ async get(target) {
389
+ const { variables } = await this.getResolved(target);
390
+ const found = variables.find((variable) => variable.key === target.key);
391
+ if (!found) {
392
+ throw new SecretEnvsNotFoundError(`Variable ${target.key} was not found`);
393
+ }
394
+ return found.value;
395
+ }
396
+ /** Injects variables into the environment; existing values win unless override is set. */
397
+ async load(target = {}) {
398
+ const variables = await this.getVariables(target);
399
+ for (const [key, value] of Object.entries(variables)) {
400
+ if (target.override || this.#env[key] === void 0) {
401
+ this.#env[key] = value;
402
+ }
403
+ }
404
+ }
405
+ clearCache() {
406
+ this.#cache.clear();
407
+ }
408
+ toString() {
409
+ return `SecretEnvs(${this.#baseUrl})`;
410
+ }
411
+ toJSON() {
412
+ return { baseUrl: this.#baseUrl };
413
+ }
414
+ [INSPECT]() {
415
+ return this.toString();
416
+ }
417
+ #target(target) {
418
+ const project = target.project ?? this.#project;
419
+ const environment = target.environment ?? this.#environment;
420
+ if (!project) {
421
+ throw new SecretEnvsError(
422
+ 'A project is required (argument "project" or SECRETENVS_PROJECT)'
423
+ );
424
+ }
425
+ if (!environment) {
426
+ throw new SecretEnvsError(
427
+ 'An environment is required (argument "environment" or SECRETENVS_ENV)'
428
+ );
429
+ }
430
+ return { project, environment };
431
+ }
432
+ // Retries only network errors and 5xx responses, with exponential backoff.
433
+ async #get(path, parse) {
434
+ const url = `${this.#baseUrl}${path}`;
435
+ for (let attempt = 0; ; attempt += 1) {
436
+ const canRetry = attempt < this.#retries;
437
+ try {
438
+ const { status, body } = await this.#attempt(url);
439
+ if (status >= 500 && canRetry) {
440
+ await sleep(this.#retryDelayMs * 2 ** attempt);
441
+ continue;
442
+ }
443
+ return this.#handle(status, body, parse);
444
+ } catch (error) {
445
+ if (error instanceof SecretEnvsNetworkError && canRetry) {
446
+ await sleep(this.#retryDelayMs * 2 ** attempt);
447
+ continue;
448
+ }
449
+ throw error;
450
+ }
451
+ }
452
+ }
453
+ async #attempt(url) {
454
+ const controller = new AbortController();
455
+ const timer = setTimeout(() => controller.abort(), this.#timeoutMs);
456
+ try {
457
+ const response = await this.#fetch(url, {
458
+ method: "GET",
459
+ headers: {
460
+ Authorization: `Bearer ${this.#token}`,
461
+ Accept: "application/json"
462
+ },
463
+ signal: controller.signal,
464
+ redirect: "error"
465
+ });
466
+ let body;
467
+ try {
468
+ body = await response.json();
469
+ } catch (error) {
470
+ if (controller.signal.aborted) throw error;
471
+ body = void 0;
472
+ }
473
+ return { status: response.status, body };
474
+ } catch (error) {
475
+ throw new SecretEnvsNetworkError(
476
+ controller.signal.aborted ? `Request timed out after ${this.#timeoutMs}ms` : "Network request failed",
477
+ { cause: error }
478
+ );
479
+ } finally {
480
+ clearTimeout(timer);
481
+ }
482
+ }
483
+ #handle(status, body, parse) {
484
+ if (status >= 200 && status < 300) {
485
+ try {
486
+ return parse(body);
487
+ } catch {
488
+ throw new SecretEnvsApiError("Unexpected response from server", status);
489
+ }
490
+ }
491
+ const parsed = ApiErrorBody.safeParse(body);
492
+ const message = parsed.success ? parsed.data.error.message : `Request failed with status ${status}`;
493
+ const code = parsed.success ? parsed.data.error.code : void 0;
494
+ if (status === 401 || status === 403) {
495
+ throw new SecretEnvsAuthError(message, status, code);
496
+ }
497
+ if (status === 404)
498
+ throw new SecretEnvsNotFoundError(message, status, code);
499
+ throw new SecretEnvsApiError(message, status, code);
500
+ }
501
+ };
502
+
503
+ // src/api.ts
504
+ var TIMEOUT_MS = 1e4;
505
+ async function send(fetchFn, baseUrl, request, parse) {
506
+ const controller = new AbortController();
507
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
508
+ let status;
509
+ let body;
510
+ try {
511
+ const response = await fetchFn(`${baseUrl}${request.path}`, {
512
+ method: request.method,
513
+ headers: {
514
+ Accept: "application/json",
515
+ ...request.body !== void 0 && {
516
+ "Content-Type": "application/json"
517
+ },
518
+ ...request.headers
519
+ },
520
+ ...request.body !== void 0 && {
521
+ body: JSON.stringify(request.body)
522
+ },
523
+ signal: controller.signal,
524
+ redirect: "error"
525
+ });
526
+ status = response.status;
527
+ body = await response.json().catch(() => void 0);
528
+ } catch (error) {
529
+ throw new SecretEnvsNetworkError(
530
+ controller.signal.aborted ? `Request timed out after ${TIMEOUT_MS}ms` : "Network request failed",
531
+ { cause: error }
532
+ );
533
+ } finally {
534
+ clearTimeout(timer);
535
+ }
536
+ if (status >= 200 && status < 300) {
537
+ try {
538
+ return parse(body);
539
+ } catch {
540
+ throw new SecretEnvsApiError("Unexpected response from server", status);
541
+ }
542
+ }
543
+ const parsed = ApiErrorBody.safeParse(body);
544
+ const message = parsed.success ? parsed.data.error.message : `Request failed with status ${status}`;
545
+ const code = parsed.success ? parsed.data.error.code : void 0;
546
+ if (status === 401 || status === 403) {
547
+ throw new SecretEnvsAuthError(message, status, code);
548
+ }
549
+ if (status === 404) throw new SecretEnvsNotFoundError(message, status, code);
550
+ throw new SecretEnvsApiError(message, status, code);
551
+ }
552
+ function cliLogin(options) {
553
+ return send(
554
+ options.fetch,
555
+ options.baseUrl,
556
+ {
557
+ method: "POST",
558
+ path: "/api/v1/auth/cli-login",
559
+ headers: { [CSRF_HEADER_NAME]: CSRF_HEADER_VALUE },
560
+ body: { email: options.email, password: options.password }
561
+ },
562
+ (body) => CreatedTokenDto.parse(body)
563
+ );
564
+ }
565
+ var ManagementClient = class {
566
+ #token;
567
+ #baseUrl;
568
+ #fetch;
569
+ constructor(options) {
570
+ this.#baseUrl = options.baseUrl;
571
+ this.#token = options.token;
572
+ this.#fetch = options.fetch;
573
+ }
574
+ #call(request, parse) {
575
+ return send(
576
+ this.#fetch,
577
+ this.#baseUrl,
578
+ {
579
+ ...request,
580
+ headers: { Authorization: `Bearer ${this.#token}` }
581
+ },
582
+ parse
583
+ );
584
+ }
585
+ listVariables(projectId, environmentId) {
586
+ return this.#call(
587
+ {
588
+ method: "GET",
589
+ path: `/api/v1/projects/${projectId}/environments/${environmentId}/variables`
590
+ },
591
+ (body) => VariableMetaDto.array().parse(body)
592
+ );
593
+ }
594
+ createVariable(projectId, environmentId, input2) {
595
+ return this.#call(
596
+ {
597
+ method: "POST",
598
+ path: `/api/v1/projects/${projectId}/environments/${environmentId}/variables`,
599
+ body: input2
600
+ },
601
+ (body) => VariableMetaDto.parse(body)
602
+ );
603
+ }
604
+ updateVariable(projectId, environmentId, variableId, value) {
605
+ return this.#call(
606
+ {
607
+ method: "PATCH",
608
+ path: `/api/v1/projects/${projectId}/environments/${environmentId}/variables/${variableId}`,
609
+ body: { value }
610
+ },
611
+ (body) => VariableMetaDto.parse(body)
612
+ );
613
+ }
614
+ listSharedVariables(projectId) {
615
+ return this.#call(
616
+ { method: "GET", path: `/api/v1/projects/${projectId}/shared-variables` },
617
+ (body) => SharedVariableMetaDto.array().parse(body)
618
+ );
619
+ }
620
+ // versionsPath is `.../variables/:id` or `.../shared-variables/:id`.
621
+ listVersions(variablePath, query) {
622
+ const params = new URLSearchParams({ limit: String(query.limit) });
623
+ if (query.cursor) params.set("cursor", query.cursor);
624
+ return this.#call(
625
+ { method: "GET", path: `${variablePath}/versions?${params}` },
626
+ (body) => PaginatedVersionsResponse.parse(body)
627
+ );
628
+ }
629
+ rollback(variablePath, version) {
630
+ return this.#call(
631
+ { method: "POST", path: `${variablePath}/versions/${version}/rollback` },
632
+ (body) => VariableMetaDto.parse(body)
633
+ );
634
+ }
635
+ };
636
+
637
+ // src/config.ts
638
+ import { readFile } from "fs/promises";
639
+ import { join } from "path";
640
+ import { z as z4 } from "zod";
641
+
642
+ // src/errors.ts
643
+ var CliError = class extends Error {
644
+ constructor(message) {
645
+ super(message);
646
+ this.name = "CliError";
647
+ }
648
+ };
649
+ function describeError(error) {
650
+ if (error instanceof CliError) return error.message;
651
+ if (error instanceof SecretEnvsAuthError) {
652
+ return error.status === 401 ? "Authentication failed: the token is invalid, expired or revoked. Run `secretenvs login`." : `Permission denied: ${error.message}`;
653
+ }
654
+ if (error instanceof SecretEnvsNotFoundError) {
655
+ return `Not found: ${error.message}`;
656
+ }
657
+ if (error instanceof SecretEnvsApiError) {
658
+ return `Server returned ${error.status}: ${error.message}`;
659
+ }
660
+ if (error instanceof SecretEnvsNetworkError) {
661
+ return `Could not reach the server: ${error.message}`;
662
+ }
663
+ if (error instanceof SecretEnvsError) return error.message;
664
+ if (error instanceof Error) return error.message;
665
+ return "Unexpected error";
666
+ }
667
+
668
+ // src/config.ts
669
+ var RC_FILE_NAME = ".secretenvsrc.json";
670
+ var RcSchema = z4.object({
671
+ project: z4.string().min(1).optional(),
672
+ environment: z4.string().min(1).optional()
673
+ }).strict();
674
+ var nonEmpty2 = (value) => value === void 0 || value === "" ? void 0 : value;
675
+ async function readRc(cwd) {
676
+ let raw;
677
+ try {
678
+ raw = await readFile(join(cwd, RC_FILE_NAME), "utf8");
679
+ } catch (error) {
680
+ if (error.code === "ENOENT") return {};
681
+ throw new CliError(`Cannot read ${RC_FILE_NAME}`);
682
+ }
683
+ let data;
684
+ try {
685
+ data = JSON.parse(raw);
686
+ } catch {
687
+ throw new CliError(`${RC_FILE_NAME} is not valid JSON`);
688
+ }
689
+ if (typeof data === "object" && data !== null && "token" in data) {
690
+ throw new CliError(
691
+ `${RC_FILE_NAME} must not contain a token; it only holds "project" and "environment"`
692
+ );
693
+ }
694
+ const parsed = RcSchema.safeParse(data);
695
+ if (!parsed.success) {
696
+ throw new CliError(
697
+ `${RC_FILE_NAME} may only contain "project" and "environment" strings`
698
+ );
699
+ }
700
+ return parsed.data;
701
+ }
702
+ function resolveAuth(options) {
703
+ const { env, credentials } = options;
704
+ const envToken = nonEmpty2(env.SECRETENVS_TOKEN);
705
+ const token = envToken ?? credentials?.token;
706
+ const baseUrl = nonEmpty2(options.url) ?? nonEmpty2(env.SECRETENVS_URL) ?? credentials?.baseUrl;
707
+ if (!token) {
708
+ throw new CliError("Not logged in. Run `secretenvs login` first.");
709
+ }
710
+ if (!baseUrl) {
711
+ throw new CliError(
712
+ "No server URL. Run `secretenvs login --url <url>` or set SECRETENVS_URL."
713
+ );
714
+ }
715
+ const fromCredentials = envToken === void 0;
716
+ return {
717
+ token,
718
+ baseUrl,
719
+ source: fromCredentials ? "credentials" : "environment",
720
+ ...fromCredentials && credentials?.email && { email: credentials.email },
721
+ ...fromCredentials && credentials?.prefix && { prefix: credentials.prefix }
722
+ };
723
+ }
724
+ function resolveNames(options) {
725
+ const project = nonEmpty2(options.project) ?? nonEmpty2(options.env.SECRETENVS_PROJECT) ?? options.rc.project;
726
+ const environment = nonEmpty2(options.environment) ?? nonEmpty2(options.env.SECRETENVS_ENV) ?? options.rc.environment;
727
+ if (!project) {
728
+ throw new CliError(
729
+ `A project is required: use -p <slug>, SECRETENVS_PROJECT or ${RC_FILE_NAME}.`
730
+ );
731
+ }
732
+ if (options.needEnvironment && !environment) {
733
+ throw new CliError(
734
+ `An environment is required: use -e <slug>, SECRETENVS_ENV or ${RC_FILE_NAME}.`
735
+ );
736
+ }
737
+ return { project, environment: environment ?? "" };
738
+ }
739
+
740
+ // src/credentials.ts
741
+ import { randomBytes } from "crypto";
742
+ import {
743
+ chmod,
744
+ mkdir,
745
+ readFile as readFile2,
746
+ rename,
747
+ rm,
748
+ writeFile
749
+ } from "fs/promises";
750
+ import { dirname, join as join2 } from "path";
751
+ import { z as z5 } from "zod";
752
+ var CredentialsSchema = z5.object({
753
+ baseUrl: z5.string().min(1),
754
+ token: z5.string().min(1),
755
+ email: z5.string().optional(),
756
+ prefix: z5.string().optional()
757
+ }).strict();
758
+ function credentialsPath(homeDir) {
759
+ return join2(homeDir, ".config", "secretenvs", "credentials.json");
760
+ }
761
+ async function readCredentials(path) {
762
+ let raw;
763
+ try {
764
+ raw = await readFile2(path, "utf8");
765
+ } catch (error) {
766
+ if (error.code === "ENOENT") return null;
767
+ throw new CliError(`Cannot read credentials file ${path}`);
768
+ }
769
+ try {
770
+ return CredentialsSchema.parse(JSON.parse(raw));
771
+ } catch {
772
+ throw new CliError(
773
+ `Credentials file ${path} is invalid. Run \`secretenvs login\` again.`
774
+ );
775
+ }
776
+ }
777
+ async function writeCredentials(path, credentials) {
778
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
779
+ const temp = `${path}.${randomBytes(4).toString("hex")}.tmp`;
780
+ try {
781
+ await writeFile(temp, `${JSON.stringify(credentials, null, 2)}
782
+ `, {
783
+ mode: 384,
784
+ flag: "wx"
785
+ });
786
+ await rename(temp, path);
787
+ await chmod(path, 384);
788
+ } catch (error) {
789
+ await rm(temp, { force: true });
790
+ throw error;
791
+ }
792
+ }
793
+ async function deleteCredentials(path) {
794
+ try {
795
+ await rm(path);
796
+ return true;
797
+ } catch (error) {
798
+ if (error.code === "ENOENT") return false;
799
+ throw error;
800
+ }
801
+ }
802
+
803
+ // src/format.ts
804
+ var MASK = "\u2022\u2022\u2022\u2022\u2022\u2022";
805
+ function renderTable(headers, rows) {
806
+ const widths = headers.map(
807
+ (header, column) => Math.max(header.length, ...rows.map((row) => (row[column] ?? "").length))
808
+ );
809
+ const line = (cells) => cells.map((cell, column) => cell.padEnd(widths[column] ?? 0)).join(" ").trimEnd();
810
+ return [line(headers), ...rows.map(line)].join("\n") + "\n";
811
+ }
812
+ var SAFE_DOTENV_VALUE = /^[A-Za-z0-9_@%+:,./-]*$/;
813
+ function dotenvValue(value) {
814
+ if (SAFE_DOTENV_VALUE.test(value)) return value;
815
+ const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r");
816
+ return `"${escaped}"`;
817
+ }
818
+ function formatDotenv(variables) {
819
+ const lines = Object.entries(variables).sort(([a], [b]) => a < b ? -1 : 1).map(([key, value]) => `${key}=${dotenvValue(value)}`);
820
+ return lines.length > 0 ? `${lines.join("\n")}
821
+ ` : "";
822
+ }
823
+ function formatJson(variables) {
824
+ const sorted = Object.fromEntries(
825
+ Object.entries(variables).sort(([a], [b]) => a < b ? -1 : 1)
826
+ );
827
+ return `${JSON.stringify(sorted, null, 2)}
828
+ `;
829
+ }
830
+ function parseAssignment(input2) {
831
+ const index = input2.indexOf("=");
832
+ if (index <= 0) return null;
833
+ return { key: input2.slice(0, index), value: input2.slice(index + 1) };
834
+ }
835
+
836
+ // src/commands.ts
837
+ async function connect(deps) {
838
+ const credentials = await readCredentials(credentialsPath(deps.homeDir));
839
+ const auth = resolveAuth({ env: deps.env, credentials });
840
+ const sdk = new SecretEnvs({
841
+ token: auth.token,
842
+ baseUrl: auth.baseUrl,
843
+ fetch: deps.fetch,
844
+ env: {}
845
+ });
846
+ const api = new ManagementClient({
847
+ baseUrl: sdk.toJSON().baseUrl,
848
+ token: auth.token,
849
+ fetch: deps.fetch
850
+ });
851
+ return { auth, sdk, api };
852
+ }
853
+ async function resolveTarget(deps, sdk, flags, needEnvironment) {
854
+ const names = resolveNames({
855
+ env: deps.env,
856
+ rc: await readRc(deps.cwd),
857
+ project: flags.project,
858
+ environment: flags.env,
859
+ needEnvironment
860
+ });
861
+ const projects = await sdk.listProjects();
862
+ const project = projects.find((item) => item.slug === names.project);
863
+ if (!project) {
864
+ throw new CliError(
865
+ `Project "${names.project}" was not found or is not accessible with this token.`
866
+ );
867
+ }
868
+ if (!needEnvironment) return { project, environment: null };
869
+ const environment = project.environments.find(
870
+ (item) => item.slug === names.environment
871
+ );
872
+ if (!environment) {
873
+ const available = project.environments.map((item) => item.slug).join(", ");
874
+ throw new CliError(
875
+ `Environment "${names.environment}" was not found in "${project.slug}" (available: ${available || "none"}).`
876
+ );
877
+ }
878
+ return { project, environment };
879
+ }
880
+ async function requireTarget(deps, sdk, flags) {
881
+ const target = await resolveTarget(deps, sdk, flags, true);
882
+ if (!target.environment) throw new CliError("An environment is required.");
883
+ return { project: target.project, environment: target.environment };
884
+ }
885
+ var out = (deps, text) => {
886
+ deps.stdout.write(`${text}
887
+ `);
888
+ };
889
+ async function login(deps, options) {
890
+ if (!deps.interactive) {
891
+ throw new CliError("`secretenvs login` needs an interactive terminal.");
892
+ }
893
+ const stored = await readCredentials(credentialsPath(deps.homeDir));
894
+ const knownUrl = options.url ?? deps.env.SECRETENVS_URL ?? stored?.baseUrl;
895
+ const rawUrl = knownUrl ?? await deps.prompts.input({
896
+ message: "Server URL",
897
+ default: "http://localhost:3000"
898
+ });
899
+ let baseUrl;
900
+ try {
901
+ baseUrl = normalizeBaseUrl(rawUrl);
902
+ } catch (error) {
903
+ throw new CliError(
904
+ error instanceof SecretEnvsError ? error.message : "Invalid server URL"
905
+ );
906
+ }
907
+ const email2 = (await deps.prompts.input({ message: "Email" })).trim();
908
+ const password3 = await deps.prompts.password({ message: "Password" });
909
+ const created = await cliLogin({
910
+ fetch: deps.fetch,
911
+ baseUrl,
912
+ email: email2,
913
+ password: password3
914
+ }).catch((error) => {
915
+ if (error instanceof SecretEnvsAuthError) {
916
+ throw new CliError(error.message);
917
+ }
918
+ throw error;
919
+ });
920
+ await writeCredentials(credentialsPath(deps.homeDir), {
921
+ baseUrl,
922
+ token: created.token,
923
+ email: email2,
924
+ prefix: created.prefix
925
+ });
926
+ out(deps, `Logged in as ${email2} on ${baseUrl}`);
927
+ }
928
+ async function logout(deps) {
929
+ const removed = await deleteCredentials(credentialsPath(deps.homeDir));
930
+ out(
931
+ deps,
932
+ removed ? "Removed the stored credentials. The API token stays valid until you revoke it in the web app (Settings > Tokens)." : "No stored credentials found."
933
+ );
934
+ }
935
+ async function whoami(deps) {
936
+ const { auth, sdk } = await connect(deps);
937
+ const projects = await sdk.listProjects();
938
+ const account = auth.email ?? (auth.source === "environment" ? "unknown (token from SECRETENVS_TOKEN)" : "unknown");
939
+ const token = auth.prefix ? `${auth.prefix}... (${auth.source})` : auth.source;
940
+ out(deps, `Server: ${sdk.toJSON().baseUrl}`);
941
+ out(deps, `Account: ${account}`);
942
+ out(deps, `Token: ${token}`);
943
+ out(deps, `Projects: ${projects.length} accessible`);
944
+ }
945
+ async function listProjects(deps) {
946
+ const { sdk } = await connect(deps);
947
+ const projects = await sdk.listProjects();
948
+ if (projects.length === 0) return out(deps, "No accessible projects.");
949
+ deps.stdout.write(
950
+ renderTable(
951
+ ["SLUG", "ROLE", "NAME"],
952
+ projects.map((project) => [project.slug, project.role, project.name])
953
+ )
954
+ );
955
+ }
956
+ async function listEnvironments(deps, flags) {
957
+ const { sdk } = await connect(deps);
958
+ const { project } = await resolveTarget(deps, sdk, flags, false);
959
+ if (project.environments.length === 0) {
960
+ return out(deps, "No environments.");
961
+ }
962
+ deps.stdout.write(
963
+ renderTable(
964
+ ["SLUG", "NAME"],
965
+ project.environments.map((environment) => [
966
+ environment.slug,
967
+ environment.name
968
+ ])
969
+ )
970
+ );
971
+ }
972
+ async function listVariables(deps, flags) {
973
+ const { sdk, api } = await connect(deps);
974
+ const { project, environment } = await requireTarget(deps, sdk, flags);
975
+ let rows;
976
+ if (flags.reveal) {
977
+ const resolved = await sdk.getResolved({
978
+ project: project.slug,
979
+ environment: environment.slug
980
+ });
981
+ rows = resolved.variables.map((variable) => ({
982
+ key: variable.key,
983
+ source: variable.source === "shared" ? "shared" : "env",
984
+ value: variable.value
985
+ }));
986
+ } else {
987
+ const own = await api.listVariables(project.id, environment.id);
988
+ const shared = await api.listSharedVariables(project.id).catch((error) => {
989
+ if (error instanceof SecretEnvsNotFoundError) return [];
990
+ throw error;
991
+ });
992
+ const ownKeys = new Set(own.map((variable) => variable.key));
993
+ rows = [
994
+ ...own.map((variable) => ({
995
+ key: variable.key,
996
+ source: "env",
997
+ value: MASK
998
+ })),
999
+ ...shared.filter(
1000
+ (variable) => variable.environmentIds.includes(environment.id) && !ownKeys.has(variable.key)
1001
+ ).map((variable) => ({
1002
+ key: variable.key,
1003
+ source: "shared",
1004
+ value: MASK
1005
+ }))
1006
+ ];
1007
+ }
1008
+ if (rows.length === 0) return out(deps, "No variables.");
1009
+ rows.sort((a, b) => a.key < b.key ? -1 : 1);
1010
+ deps.stdout.write(
1011
+ renderTable(
1012
+ ["KEY", "SOURCE", "VALUE"],
1013
+ rows.map((row) => [row.key, row.source, row.value])
1014
+ )
1015
+ );
1016
+ }
1017
+ async function setVariable(deps, assignment, flags) {
1018
+ const parsed = parseAssignment(assignment);
1019
+ if (!parsed) throw new CliError("Expected KEY=VALUE.");
1020
+ const input2 = CreateVariableInput.safeParse(parsed);
1021
+ if (!input2.success) {
1022
+ throw new CliError(
1023
+ `Invalid variable: ${input2.error.issues[0]?.message ?? "validation failed"}`
1024
+ );
1025
+ }
1026
+ const { sdk, api } = await connect(deps);
1027
+ const { project, environment } = await requireTarget(deps, sdk, flags);
1028
+ const existing = (await api.listVariables(project.id, environment.id)).find(
1029
+ (variable) => variable.key === input2.data.key
1030
+ );
1031
+ if (!existing) {
1032
+ const created = await api.createVariable(
1033
+ project.id,
1034
+ environment.id,
1035
+ input2.data
1036
+ );
1037
+ return out(deps, `Created ${created.key} (v${created.currentVersion})`);
1038
+ }
1039
+ const updated = await api.updateVariable(
1040
+ project.id,
1041
+ environment.id,
1042
+ existing.id,
1043
+ input2.data.value
1044
+ );
1045
+ out(
1046
+ deps,
1047
+ updated.currentVersion === existing.currentVersion ? `Unchanged ${updated.key} (v${updated.currentVersion})` : `Updated ${updated.key} (v${updated.currentVersion})`
1048
+ );
1049
+ }
1050
+ async function locateVariable(api, target, key, shared) {
1051
+ const { project, environment } = target;
1052
+ if (shared) {
1053
+ const found2 = (await api.listSharedVariables(project.id)).find(
1054
+ (variable) => variable.key === key
1055
+ );
1056
+ if (!found2) {
1057
+ throw new CliError(
1058
+ `Shared variable ${key} was not found in "${project.slug}".`
1059
+ );
1060
+ }
1061
+ return `/api/v1/projects/${project.id}/shared-variables/${found2.id}`;
1062
+ }
1063
+ const found = (await api.listVariables(project.id, environment.id)).find(
1064
+ (variable) => variable.key === key
1065
+ );
1066
+ if (!found) {
1067
+ throw new CliError(
1068
+ `Variable ${key} was not found in "${project.slug}/${environment.slug}".`
1069
+ );
1070
+ }
1071
+ return `/api/v1/projects/${project.id}/environments/${environment.id}/variables/${found.id}`;
1072
+ }
1073
+ var MAX_PAGE = 100;
1074
+ async function history(deps, key, flags) {
1075
+ const limit = flags.limit === void 0 ? 20 : Number(flags.limit);
1076
+ if (!Number.isInteger(limit) || limit < 1) {
1077
+ throw new CliError("--limit must be a positive integer.");
1078
+ }
1079
+ const { sdk, api } = await connect(deps);
1080
+ const target = await requireTarget(deps, sdk, flags);
1081
+ const path = await locateVariable(api, target, key, Boolean(flags.shared));
1082
+ const items = [];
1083
+ let cursor;
1084
+ while (items.length < limit) {
1085
+ const page = await api.listVersions(path, {
1086
+ limit: Math.min(MAX_PAGE, limit - items.length),
1087
+ cursor
1088
+ });
1089
+ items.push(...page.items);
1090
+ if (!page.nextCursor) break;
1091
+ cursor = page.nextCursor;
1092
+ }
1093
+ deps.stdout.write(
1094
+ renderTable(
1095
+ ["VERSION", "CHANGE", "AUTHOR", "WHEN"],
1096
+ items.map((item) => [
1097
+ `v${item.version}${item.isCurrent ? " (current)" : ""}`,
1098
+ item.changeType === "CREATED" ? "Created" : item.changeType === "UPDATED" ? "Updated" : `Restored from v${item.restoredFromVersion ?? "?"}`,
1099
+ item.changedBy?.name ?? "(deleted user)",
1100
+ `${item.createdAt.slice(0, 19).replace("T", " ")} UTC`
1101
+ ])
1102
+ )
1103
+ );
1104
+ }
1105
+ async function rollback(deps, key, flags) {
1106
+ const version = Number(flags.to);
1107
+ if (!Number.isInteger(version) || version < 1) {
1108
+ throw new CliError("--to <version> must be a positive integer.");
1109
+ }
1110
+ const { sdk, api } = await connect(deps);
1111
+ const target = await requireTarget(deps, sdk, flags);
1112
+ const path = await locateVariable(api, target, key, Boolean(flags.shared));
1113
+ if (!flags.yes) {
1114
+ if (!deps.interactive) {
1115
+ throw new CliError(
1116
+ "Refusing to roll back without confirmation; pass --yes."
1117
+ );
1118
+ }
1119
+ const confirmed = await deps.prompts.confirm({
1120
+ message: `Restore ${key} to version ${version} as a new version?`,
1121
+ default: false
1122
+ });
1123
+ if (!confirmed) {
1124
+ out(deps, "Aborted.");
1125
+ return 1;
1126
+ }
1127
+ }
1128
+ const result = await api.rollback(path, version);
1129
+ out(
1130
+ deps,
1131
+ `Restored ${result.key} to v${version} (now v${result.currentVersion})`
1132
+ );
1133
+ return 0;
1134
+ }
1135
+ async function pull(deps, flags) {
1136
+ const format = flags.format ?? "dotenv";
1137
+ if (format !== "dotenv" && format !== "json") {
1138
+ throw new CliError('--format must be "dotenv" or "json".');
1139
+ }
1140
+ const outFile = flags.out ?? ".env";
1141
+ const { sdk } = await connect(deps);
1142
+ const { project, environment } = await requireTarget(deps, sdk, flags);
1143
+ const resolved = await sdk.getResolved({
1144
+ project: project.slug,
1145
+ environment: environment.slug
1146
+ });
1147
+ const variables = Object.fromEntries(
1148
+ resolved.variables.map((variable) => [variable.key, variable.value])
1149
+ );
1150
+ const content = format === "json" ? formatJson(variables) : formatDotenv(variables);
1151
+ const path = resolve(deps.cwd, outFile);
1152
+ try {
1153
+ await writeFile2(path, content, {
1154
+ mode: 384,
1155
+ flag: flags.force ? "w" : "wx"
1156
+ });
1157
+ } catch (error) {
1158
+ if (error.code === "EEXIST") {
1159
+ throw new CliError(
1160
+ `${outFile} already exists. Use --force to overwrite it.`
1161
+ );
1162
+ }
1163
+ throw error;
1164
+ }
1165
+ if (flags.force) await chmod2(path, 384);
1166
+ out(deps, `Wrote ${resolved.variables.length} variables to ${outFile}`);
1167
+ }
1168
+ async function runCommand(deps, command, flags) {
1169
+ const [program, ...args] = command;
1170
+ if (!program) throw new CliError('Missing command after "--".');
1171
+ const { sdk } = await connect(deps);
1172
+ const { project, environment } = await requireTarget(deps, sdk, flags);
1173
+ const resolved = await sdk.getResolved({
1174
+ project: project.slug,
1175
+ environment: environment.slug
1176
+ });
1177
+ const env = { ...deps.env };
1178
+ delete env.SECRETENVS_TOKEN;
1179
+ for (const variable of resolved.variables) env[variable.key] = variable.value;
1180
+ const child = deps.spawn(program, args, {
1181
+ stdio: "inherit",
1182
+ env,
1183
+ shell: false
1184
+ });
1185
+ return new Promise((resolveExit, reject) => {
1186
+ const forward = (signal) => () => child.kill(signal);
1187
+ const onInt = forward("SIGINT");
1188
+ const onTerm = forward("SIGTERM");
1189
+ process.on("SIGINT", onInt);
1190
+ process.on("SIGTERM", onTerm);
1191
+ const cleanup = () => {
1192
+ process.off("SIGINT", onInt);
1193
+ process.off("SIGTERM", onTerm);
1194
+ };
1195
+ child.on("error", (error) => {
1196
+ cleanup();
1197
+ reject(
1198
+ error.code === "ENOENT" ? new CliError(`Command not found: ${program}`) : new CliError(`Could not start ${program}: ${error.message}`)
1199
+ );
1200
+ });
1201
+ child.on("close", (code, signal) => {
1202
+ cleanup();
1203
+ resolveExit(
1204
+ code ?? (signal ? 128 + (osConstants.signals[signal] ?? 0) : 1)
1205
+ );
1206
+ });
1207
+ });
1208
+ }
1209
+
1210
+ // src/program.ts
1211
+ var VERSION = true ? "1.0.1" : "dev";
1212
+ function buildProgram(deps, setExitCode) {
1213
+ const program = new Command().name("secretenvs").description("Read and manage SecretEnvs variables from the terminal").version(VERSION).configureOutput({
1214
+ writeOut: (text) => deps.stdout.write(text),
1215
+ writeErr: (text) => deps.stderr.write(text)
1216
+ }).exitOverride();
1217
+ const target = (command) => command.option("-p, --project <slug>", "project slug (or SECRETENVS_PROJECT)").option("-e, --env <slug>", "environment slug (or SECRETENVS_ENV)");
1218
+ program.command("login").description("Log in with email and password and store an API token").option("--url <baseUrl>", "server URL, e.g. https://vault.example.com").action((options) => login(deps, options));
1219
+ program.command("logout").description("Delete the stored credentials").action(() => logout(deps));
1220
+ program.command("whoami").description("Show the current server, account and token").action(() => whoami(deps));
1221
+ program.command("projects").description("List accessible projects").action(() => listProjects(deps));
1222
+ target(program.command("envs")).description("List the environments of a project").action((options) => listEnvironments(deps, options));
1223
+ target(program.command("list")).description("List variable keys and their source (values are masked)").option("--reveal", "show values").action((options) => listVariables(deps, options));
1224
+ target(program.command("set")).description("Create or update an environment variable").argument("<assignment>", "KEY=VALUE").action(
1225
+ (assignment, options) => setVariable(deps, assignment, options)
1226
+ );
1227
+ target(program.command("history")).description(
1228
+ "Show the version history of a variable (values are never shown)"
1229
+ ).argument("<key>", "variable key").option("--shared", "the key is a shared variable").option("--limit <n>", "number of versions to show", "20").action((key, options) => history(deps, key, options));
1230
+ target(program.command("rollback")).description("Restore an older version as a new version").argument("<key>", "variable key").requiredOption("--to <version>", "version to restore").option("--shared", "the key is a shared variable").option("--yes", "skip the confirmation prompt").action(
1231
+ async (key, options) => setExitCode(await rollback(deps, key, options))
1232
+ );
1233
+ target(program.command("pull")).description("Write the resolved variables to a file").option("--out <file>", "output file", ".env").option("--format <format>", "dotenv or json", "dotenv").option("--force", "overwrite an existing file").action((options) => pull(deps, options));
1234
+ target(program.command("run")).description(
1235
+ "Run a command with the variables injected into its environment"
1236
+ ).argument("<command...>", 'command and arguments, after "--"').action(
1237
+ async (command, options) => setExitCode(await runCommand(deps, command, options))
1238
+ );
1239
+ return program;
1240
+ }
1241
+ async function runCli(argv, deps) {
1242
+ let exitCode = 0;
1243
+ const program = buildProgram(deps, (code) => {
1244
+ exitCode = code;
1245
+ });
1246
+ try {
1247
+ await program.parseAsync(argv);
1248
+ return exitCode;
1249
+ } catch (error) {
1250
+ if (error instanceof CommanderError) return error.exitCode;
1251
+ deps.stderr.write(`Error: ${describeError(error)}
1252
+ `);
1253
+ return 1;
1254
+ }
1255
+ }
1256
+
1257
+ // src/index.ts
1258
+ process.exitCode = await runCli(process.argv, defaultDeps());