env.ts 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. import { existsSync, statSync } from "node:fs";
  2. import { homedir } from "node:os";
  3. import { dirname, join, parse, resolve } from "node:path";
  4. import { config as loadDotenv } from "dotenv";
  5. import {
  6. ZCODE_RUNTIME_ENV_KEY,
  7. buildZCodeToolEnvPassthroughEnv,
  8. normalizeZCodeRuntimeEnv,
  9. sanitizeZCodeRuntimeEnv,
  10. sanitizeZCodeRuntimeEnvInPlace,
  11. type ZCodeRuntimeEnv,
  12. } from "@zcode/shared/runtime-env";
  13. export type CliEnv = Record<string, string | undefined>;
  14. export type DotenvLoadResult = {
  15. error?: Error;
  16. keys: string[];
  17. loaded: boolean;
  18. path?: string;
  19. };
  20. export type LoadCliDotenvOptions = {
  21. cwd?: string;
  22. env?: CliEnv;
  23. };
  24. export function prepareCliRuntimeEnv(
  25. env: CliEnv = process.env,
  26. argv: readonly string[] = process.argv,
  27. ): CliEnv {
  28. const prepared = {
  29. ...sanitizeZCodeRuntimeEnv(env),
  30. ...buildZCodeToolEnvPassthroughEnv(env),
  31. };
  32. applyCliRuntimeEnvDefaults(prepared, argv);
  33. return prepared;
  34. }
  35. export function applyCliRuntimeEnvSanitization(
  36. env: CliEnv,
  37. argv: readonly string[] = process.argv,
  38. ): void {
  39. const toolEnvPassthrough = buildZCodeToolEnvPassthroughEnv(env);
  40. sanitizeZCodeRuntimeEnvInPlace(env);
  41. Object.assign(env, toolEnvPassthrough);
  42. applyCliRuntimeEnvDefaults(env, argv);
  43. }
  44. export const findDotenv = (startDir: string): string | undefined => {
  45. let current = resolve(startDir);
  46. const root = parse(current).root;
  47. while (true) {
  48. const candidate = resolve(current, ".env");
  49. // 用户可能把 .env 当作目录使用(如 ~/.env/modelscope)。
  50. // existsSync 只检查存在性,不区分文件/目录;必须显式检查 isFile避免 loadDotenv 报错。
  51. if (existsSync(candidate) && statSync(candidate).isFile()) {
  52. return candidate;
  53. }
  54. if (current === root) {
  55. return undefined;
  56. }
  57. const parent = dirname(current);
  58. if (parent === current) {
  59. return undefined;
  60. }
  61. current = parent;
  62. }
  63. };
  64. export const loadCliDotenv = (options: LoadCliDotenvOptions = {}): DotenvLoadResult => {
  65. const env = options.env ?? process.env;
  66. const dotenvPath = findDotenv(options.cwd ?? process.cwd());
  67. if (!dotenvPath) {
  68. return {
  69. keys: [],
  70. loaded: false,
  71. };
  72. }
  73. // The build used to inline .env values into dist. Loading at the CLI boundary
  74. // keeps secrets runtime-scoped and lets users rotate .env without rebuilding.
  75. const result = loadDotenv({
  76. override: false,
  77. path: dotenvPath,
  78. processEnv: env,
  79. quiet: true,
  80. });
  81. if (result.error) {
  82. return {
  83. error: result.error,
  84. keys: [],
  85. loaded: false,
  86. path: dotenvPath,
  87. };
  88. }
  89. return {
  90. keys: Object.keys(result.parsed ?? {}),
  91. loaded: true,
  92. path: dotenvPath,
  93. };
  94. };
  95. export function shouldLoadCliDotenvForProtocolServer(env: CliEnv): boolean {
  96. return resolveCliRuntimeEnv(env, process.argv) === "development";
  97. }
  98. function applyCliRuntimeEnvDefaults(env: CliEnv, argv: readonly string[]): void {
  99. env[ZCODE_RUNTIME_ENV_KEY] = resolveCliRuntimeEnv(env, argv);
  100. applyBetaStorageDefault(env, argv);
  101. }
  102. function resolveCliRuntimeEnv(env: CliEnv, argv: readonly string[]): ZCodeRuntimeEnv {
  103. const explicit = normalizeZCodeRuntimeEnv(env[ZCODE_RUNTIME_ENV_KEY]);
  104. if (explicit) {
  105. return explicit;
  106. }
  107. // CLI 运行时不再读取 NODE_ENV。源码 tsx 入口仍表示本地开发形态,
  108. // 但该判定来自入口路径,不来自用户 shell 里的 NODE_ENV。
  109. const entrypoint = (argv[1] ?? "").replace(/\\/g, "/");
  110. return entrypoint.endsWith(".ts") && entrypoint.includes("packages/cli/src")
  111. ? "development"
  112. : "production";
  113. }
  114. function applyBetaStorageDefault(env: CliEnv, argv: readonly string[]): void {
  115. if (env.ZCODE_STORAGE_DIR?.trim()) return;
  116. const explicitBeta = env.ZCODE_BETA === "1" || env.ZCODE_ENV === "beta";
  117. const invokedAsBeta = argv.some((arg) => /(^|[/\\])zcode-beta(?:$|\.)/u.test(arg));
  118. if (!explicitBeta && !invokedAsBeta) return;
  119. env.ZCODE_STORAGE_DIR = join(homedir(), ".zcode-beta");
  120. }