pi-auto-web-search 0.1.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.
package/src/config.ts ADDED
@@ -0,0 +1,547 @@
1
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { parse, stringify } from "comment-json";
5
+ import { assertBaseUrl } from "./base-url.ts";
6
+ import { parseQuotaPeriod, type KeyQuotaConfig } from "./key-quota.ts";
7
+ import { resolveSecret, secretVariables } from "./secrets.ts";
8
+ import { PRESETS, isPresetId, type AuthSetting, type AuthType, type ChainKind, type Preset } from "./presets.ts";
9
+
10
+ export type InstanceMode = "sdk" | "pool" | "proxy";
11
+
12
+ export type InstanceStatus = "ready" | "unconfigured";
13
+
14
+ export const ERROR_CLASSES = [
15
+ "auth",
16
+ "quota",
17
+ "rateLimit",
18
+ "server",
19
+ "network",
20
+ "timeout",
21
+ "invalidRequest",
22
+ "aborted",
23
+ ] as const;
24
+
25
+ export type ErrorClass = (typeof ERROR_CLASSES)[number];
26
+
27
+ export interface Limits {
28
+ maxResults: number;
29
+ maxPages: number;
30
+ timeoutMs: number;
31
+ crawlTimeoutMs: number;
32
+ }
33
+
34
+ export interface FailoverConfig {
35
+ enabled: boolean;
36
+ on: ErrorClass[];
37
+ stopOn: ErrorClass[];
38
+ maxAttempts: number;
39
+ retrySameInstance: number;
40
+ }
41
+
42
+ export interface CloudflareOAuthConfig {
43
+ clientId: string;
44
+ redirectUri: string;
45
+ authorizeUrl: string;
46
+ tokenUrl: string;
47
+ scopes: string;
48
+ }
49
+
50
+ /** 实例配置解析后的形态:地址已规范化,凭据保持原值,请求前才插值。 */
51
+ export interface ResolvedInstance {
52
+ id: string;
53
+ preset: Preset;
54
+ mode: InstanceMode;
55
+ baseUrl: string;
56
+ keys: string[];
57
+ auth: AuthSetting;
58
+ accountId?: string;
59
+ /** 模型名,仅 xai 这类按模型调用的供应商使用。 */
60
+ model?: string;
61
+ /** 仅 xai 实例使用:固定是否把 x_search 加入工具列表,与 quality 无关。 */
62
+ xSearch: boolean;
63
+ paths: Record<string, string>;
64
+ concurrency: number;
65
+ cooldownSeconds: number;
66
+ enabled: boolean;
67
+ failover: boolean;
68
+ priority?: number;
69
+ userAgent?: string;
70
+ /** 按密钥的调用次数硬限额;未配置时继承供应商默认限额,显式 false/null 关闭。 */
71
+ keyQuota?: KeyQuotaConfig;
72
+ status: InstanceStatus;
73
+ warnings: string[];
74
+ }
75
+
76
+ export interface ConfigFile {
77
+ instances?: unknown;
78
+ defaultChain?: unknown;
79
+ fetchChain?: unknown;
80
+ limits?: unknown;
81
+ failover?: unknown;
82
+ cloudflareOAuth?: unknown;
83
+ userAgent?: unknown;
84
+ [key: string]: unknown;
85
+ }
86
+
87
+ /** 解析配置时的运行时上下文,保持 resolveConfig 纯函数且便于测试隔离。 */
88
+ export interface ResolveConfigOptions {
89
+ /** Cloudflare OAuth 令牌摘要;存在时允许免静态 key 的 cloudflare sdk 实例就绪。 */
90
+ cloudflareOAuthToken?: { accountId?: string };
91
+ }
92
+
93
+ export interface LoadedConfig {
94
+ file: ConfigFile;
95
+ instances: ResolvedInstance[];
96
+ searchChain: string[];
97
+ fetchChain: string[];
98
+ limits: Limits;
99
+ failover: FailoverConfig;
100
+ cloudflareOAuth: CloudflareOAuthConfig;
101
+ userAgent?: string;
102
+ warnings: string[];
103
+ }
104
+
105
+ const MODES: readonly InstanceMode[] = ["sdk", "pool", "proxy"];
106
+
107
+ const AUTH_TYPES: readonly AuthType[] = ["bearer", "header", "query", "body", "none"];
108
+
109
+ const DEFAULT_LIMITS: Limits = {
110
+ maxResults: 20,
111
+ maxPages: 3,
112
+ timeoutMs: 20_000,
113
+ crawlTimeoutMs: 90_000,
114
+ };
115
+
116
+ const DEFAULT_FAILOVER: FailoverConfig = {
117
+ enabled: true,
118
+ on: ["auth", "quota", "rateLimit", "server", "network"],
119
+ stopOn: ["timeout", "invalidRequest", "aborted"],
120
+ maxAttempts: 3,
121
+ retrySameInstance: 0,
122
+ };
123
+
124
+ const DEFAULT_CLOUDFLARE_OAUTH: CloudflareOAuthConfig = {
125
+ clientId: "9f211403f438578c72d299494764ff22",
126
+ redirectUri: "https://browser-run.alxy.app/callback",
127
+ authorizeUrl: "https://dash.cloudflare.com/oauth2/auth",
128
+ tokenUrl: "https://dash.cloudflare.com/oauth2/token",
129
+ scopes: "browser-rendering.write account-settings.read offline_access",
130
+ };
131
+
132
+ function invalid(message: string): never {
133
+ throw new Error(message);
134
+ }
135
+
136
+ function isRecord(value: unknown): value is Record<string, unknown> {
137
+ return typeof value === "object" && value !== null && !Array.isArray(value);
138
+ }
139
+
140
+ function record(value: unknown, label: string): Record<string, unknown> {
141
+ if (!isRecord(value)) invalid(`${label} 必须是对象`);
142
+ return value;
143
+ }
144
+
145
+ function optionalRecord(value: unknown, label: string): Record<string, unknown> {
146
+ if (value === undefined) return {};
147
+ return record(value, label);
148
+ }
149
+
150
+ /** 允许空字符串:表示不带标识的 User-Agent;fetch 无法省略该头,实际发送空值。 */
151
+ function stringValue(value: unknown, label: string): string {
152
+ if (typeof value !== "string") invalid(`${label} 必须是字符串`);
153
+ return value;
154
+ }
155
+
156
+ function requiredString(value: unknown, label: string): string {
157
+ if (typeof value !== "string" || !value.trim()) invalid(`${label} 必须是非空字符串`);
158
+ return value;
159
+ }
160
+
161
+ function integerInRange(value: unknown, label: string, min: number, max: number, fallback: number): number {
162
+ if (value === undefined) return fallback;
163
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
164
+ invalid(`${label} 必须是 ${min} 到 ${max} 的整数`);
165
+ }
166
+ return value;
167
+ }
168
+
169
+ function integerAtLeast(value: unknown, label: string, min: number, fallback: number): number {
170
+ if (value === undefined) return fallback;
171
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min) {
172
+ invalid(`${label} 必须是不小于 ${min} 的整数`);
173
+ }
174
+ return value;
175
+ }
176
+
177
+ function booleanValue(value: unknown, label: string, fallback: boolean): boolean {
178
+ if (value === undefined) return fallback;
179
+ if (typeof value !== "boolean") invalid(`${label} 必须是布尔值`);
180
+ return value;
181
+ }
182
+
183
+ function keyList(value: unknown, label: string, warnings: string[], mode: InstanceMode): string[] {
184
+ if (value === undefined) return [];
185
+ if (!Array.isArray(value)) invalid(`${label}.keys 必须是字符串数组`);
186
+ const keys = Array.from(value, (item, index) => requiredString(item, `${label}.keys[${index}]`));
187
+ if (mode === "pool" && keys.length > 1) {
188
+ warnings.push(`pool 模式只用一个凭证,已忽略后 ${keys.length - 1} 个`);
189
+ return keys.slice(0, 1);
190
+ }
191
+ return keys;
192
+ }
193
+
194
+ function resolveAuth(value: unknown, preset: Preset, label: string): AuthSetting {
195
+ if (value === undefined) return { ...preset.auth };
196
+ const raw = record(value, `${label}.auth`);
197
+ const type = raw.type === undefined ? preset.auth.type : requiredString(raw.type, `${label}.auth.type`);
198
+ if (!(AUTH_TYPES as readonly string[]).includes(type)) {
199
+ invalid(`${label}.auth.type 未知鉴权类型:${type}`);
200
+ }
201
+ if (type === "bearer" || type === "none") return { type: type as AuthType };
202
+ const name = raw.name === undefined ? preset.auth.name : requiredString(raw.name, `${label}.auth.name`);
203
+ if (!name) invalid(`${label}.auth.name 在 ${type} 类型下必填`);
204
+ return { type: type as AuthType, name };
205
+ }
206
+
207
+ function resolvePaths(value: unknown, preset: Preset, label: string): Record<string, string> {
208
+ const paths = { ...preset.paths };
209
+ if (value === undefined) return paths;
210
+ const raw = record(value, `${label}.paths`);
211
+ for (const [key, item] of Object.entries(raw)) {
212
+ const path = requiredString(item, `${label}.paths.${key}`);
213
+ if (!path.startsWith("/")) invalid(`${label}.paths.${key} 必须以 / 开头`);
214
+ paths[key] = path;
215
+ }
216
+ return paths;
217
+ }
218
+
219
+ function resolveMode(value: unknown, label: string): InstanceMode {
220
+ if (value === undefined) return "sdk";
221
+ const mode = requiredString(value, `${label}.mode`);
222
+ if (!(MODES as readonly string[]).includes(mode)) invalid(`${label}.mode 未知模式:${mode}`);
223
+ return mode as InstanceMode;
224
+ }
225
+
226
+ function resolveKeyQuota(value: unknown, preset: Preset, label: string): KeyQuotaConfig | undefined {
227
+ if (value === undefined) {
228
+ return preset.defaultKeyQuota ? { ...preset.defaultKeyQuota } : undefined;
229
+ }
230
+ if (value === false || value === null) return undefined;
231
+ const raw = record(value, `${label}.keyQuota`);
232
+ const fallbackLimit = preset.defaultKeyQuota?.limit;
233
+ const limit = raw.limit === undefined
234
+ ? fallbackLimit !== undefined
235
+ ? fallbackLimit
236
+ : invalid(`${label}.keyQuota.limit 必须是不小于 1 的整数`)
237
+ : integerAtLeast(raw.limit, `${label}.keyQuota.limit`, 1, 1);
238
+ const rawPeriod = raw.period === undefined
239
+ ? (preset.defaultKeyQuota?.period ?? "month")
240
+ : requiredString(raw.period, `${label}.keyQuota.period`);
241
+ const parsed = parseQuotaPeriod(rawPeriod);
242
+ if (!parsed) {
243
+ invalid(
244
+ `${label}.keyQuota.period 不支持的周期:${rawPeriod}(支持 day、week、month、year,或固定时长如 24h、7d、30d、2w)`,
245
+ );
246
+ }
247
+ return { limit, period: parsed.canonical };
248
+ }
249
+
250
+ function missingVariables(keys: string[], env: NodeJS.ProcessEnv): string[] {
251
+ const names = new Set<string>();
252
+ for (const key of keys) {
253
+ for (const name of secretVariables(key)) {
254
+ if (!env[name]) names.add(name);
255
+ }
256
+ }
257
+ return [...names];
258
+ }
259
+
260
+ function resolveInstance(
261
+ value: unknown,
262
+ index: number,
263
+ env: NodeJS.ProcessEnv,
264
+ options?: ResolveConfigOptions,
265
+ ): ResolvedInstance {
266
+ const label = `instances[${index}]`;
267
+ const raw = record(value, label);
268
+ const id = requiredString(raw.id, `${label}.id`);
269
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) invalid(`${label}.id 只能包含字母、数字、下划线和短横线:${id}`);
270
+ const presetId = requiredString(raw.preset, `${label}.preset`);
271
+ if (!isPresetId(presetId)) invalid(`${label}.preset 未知供应商预设:${presetId}`);
272
+ const preset = PRESETS[presetId];
273
+ const mode = resolveMode(raw.mode, label);
274
+ const explicitBase = raw.baseUrl === undefined ? undefined : requiredString(raw.baseUrl, `${label}.baseUrl`);
275
+ if (explicitBase === undefined && mode !== "sdk") invalid(`${label}.baseUrl 在 ${mode} 模式下必填`);
276
+ const baseUrl = explicitBase === undefined ? preset.baseUrl : assertBaseUrl(explicitBase, `${label}.baseUrl`);
277
+ const auth = resolveAuth(raw.auth, preset, label);
278
+
279
+ const warnings: string[] = [];
280
+ const keys = keyList(raw.keys, label, warnings, mode);
281
+ const resolvedKeys = keys.filter((key) => resolveSecret(key, env) !== undefined);
282
+ const cloudflareOAuthEligible =
283
+ preset.id === "cloudflare" && mode === "sdk" && auth.type === "bearer" && keys.length === 0;
284
+ let status: InstanceStatus = "ready";
285
+ if (auth.type === "none" && keys.length === 0) {
286
+ status = "ready";
287
+ } else if (cloudflareOAuthEligible && options?.cloudflareOAuthToken) {
288
+ status = "ready";
289
+ } else if (resolvedKeys.length === 0) {
290
+ status = "unconfigured";
291
+ const missing = missingVariables(keys, env);
292
+ if (cloudflareOAuthEligible) {
293
+ warnings.push("未配置 API Token,也未登录 Cloudflare OAuth(在 /search 登录)");
294
+ } else {
295
+ warnings.push(missing.length ? `凭证变量未设置:${missing.join(", ")}` : "没有可用凭证");
296
+ }
297
+ }
298
+
299
+ let accountId: string | undefined;
300
+ if (raw.accountId !== undefined) {
301
+ const value = requiredString(raw.accountId, `${label}.accountId`);
302
+ const resolved = resolveSecret(value, env);
303
+ if (resolved === undefined) {
304
+ const missing = missingVariables([value], env);
305
+ warnings.push(`accountId 变量未设置:${missing.join(", ") || value}`);
306
+ } else {
307
+ accountId = resolved;
308
+ }
309
+ }
310
+ if (!accountId && cloudflareOAuthEligible && options?.cloudflareOAuthToken?.accountId) {
311
+ accountId = options.cloudflareOAuthToken.accountId;
312
+ }
313
+ if (preset.requiresAccountId && !accountId) warnings.push("accountId 待回填,OAuth 登录后自动写入");
314
+
315
+ return {
316
+ id,
317
+ preset,
318
+ mode,
319
+ baseUrl,
320
+ keys,
321
+ auth,
322
+ accountId,
323
+ model: raw.model === undefined ? undefined : requiredString(raw.model, `${label}.model`),
324
+ xSearch: booleanValue(raw.xSearch, `${label}.xSearch`, false),
325
+ paths: resolvePaths(raw.paths, preset, label),
326
+ concurrency: integerInRange(raw.concurrency, `${label}.concurrency`, 1, 64, 4),
327
+ cooldownSeconds: integerInRange(raw.cooldownSeconds, `${label}.cooldownSeconds`, 0, 86_400, 600),
328
+ enabled: booleanValue(raw.enabled, `${label}.enabled`, true),
329
+ failover: booleanValue(raw.failover, `${label}.failover`, true),
330
+ priority: raw.priority === undefined
331
+ ? undefined
332
+ : integerInRange(raw.priority, `${label}.priority`, 0, 999, 0),
333
+ userAgent: raw.userAgent === undefined ? undefined : stringValue(raw.userAgent, `${label}.userAgent`),
334
+ keyQuota: resolveKeyQuota(raw.keyQuota, preset, label),
335
+ status,
336
+ warnings,
337
+ };
338
+ }
339
+
340
+ function chainPosition(instance: ResolvedInstance, kind: ChainKind): number | undefined {
341
+ return instance.priority ?? instance.preset.defaultPriority[kind];
342
+ }
343
+
344
+ /** 实例可被调用:已启用且凭证已配置;链构建与传输层都用这一条判断。 */
345
+ export function callableInstance(instance: ResolvedInstance): boolean {
346
+ return instance.enabled && instance.status === "ready";
347
+ }
348
+
349
+ function buildChain(value: unknown, kind: ChainKind, field: string, instances: ResolvedInstance[]): string[] {
350
+ if (value !== undefined) {
351
+ if (!Array.isArray(value)) invalid(`${field} 必须是数组`);
352
+ const byId = new Map(instances.map((instance) => [instance.id, instance]));
353
+ return Array.from(value, (item, index) => {
354
+ const id = requiredString(item, `${field}[${index}]`);
355
+ const instance = byId.get(id);
356
+ if (!instance) invalid(`${field} 引用了不存在的实例:${id}`);
357
+ return instance;
358
+ })
359
+ .filter(callableInstance)
360
+ .map((instance) => instance.id);
361
+ }
362
+
363
+ const order = new Map(instances.map((instance, index) => [instance.id, index]));
364
+ return instances
365
+ .filter((instance) => callableInstance(instance) && chainPosition(instance, kind) !== undefined)
366
+ .sort((left, right) => {
367
+ const position = (chainPosition(left, kind) ?? 0) - (chainPosition(right, kind) ?? 0);
368
+ if (position !== 0) return position;
369
+ return (order.get(left.id) ?? 0) - (order.get(right.id) ?? 0);
370
+ })
371
+ .map((instance) => instance.id);
372
+ }
373
+
374
+ function resolveLimits(value: unknown): Limits {
375
+ const raw = optionalRecord(value, "limits");
376
+ return {
377
+ maxResults: integerInRange(raw.maxResults, "limits.maxResults", 1, 20, DEFAULT_LIMITS.maxResults),
378
+ maxPages: integerAtLeast(raw.maxPages, "limits.maxPages", 1, DEFAULT_LIMITS.maxPages),
379
+ timeoutMs: integerAtLeast(raw.timeoutMs, "limits.timeoutMs", 1, DEFAULT_LIMITS.timeoutMs),
380
+ crawlTimeoutMs: integerAtLeast(raw.crawlTimeoutMs, "limits.crawlTimeoutMs", 1, DEFAULT_LIMITS.crawlTimeoutMs),
381
+ };
382
+ }
383
+
384
+ function errorClassList(value: unknown, label: string, fallback: readonly ErrorClass[]): ErrorClass[] {
385
+ if (value === undefined) return [...fallback];
386
+ if (!Array.isArray(value)) invalid(`${label} 必须是数组`);
387
+ return Array.from(value, (item, index) => {
388
+ const name = requiredString(item, `${label}[${index}]`);
389
+ if (!(ERROR_CLASSES as readonly string[]).includes(name)) invalid(`${label} 含未知错误类:${name}`);
390
+ return name as ErrorClass;
391
+ });
392
+ }
393
+
394
+ function resolveFailover(value: unknown, chainLength: number): FailoverConfig {
395
+ const raw = optionalRecord(value, "failover");
396
+ const on = errorClassList(raw.on, "failover.on", DEFAULT_FAILOVER.on);
397
+ const stopOn = errorClassList(raw.stopOn, "failover.stopOn", DEFAULT_FAILOVER.stopOn);
398
+ const overlap = on.filter((name) => stopOn.includes(name));
399
+ if (overlap.length) invalid(`failover.on 与 failover.stopOn 不能重叠:${overlap.join(", ")}`);
400
+
401
+ const ceiling = Math.max(1, chainLength);
402
+ const fallbackAttempts = Math.min(DEFAULT_FAILOVER.maxAttempts, ceiling);
403
+ return {
404
+ enabled: booleanValue(raw.enabled, "failover.enabled", DEFAULT_FAILOVER.enabled),
405
+ on,
406
+ stopOn,
407
+ maxAttempts: integerInRange(raw.maxAttempts, "failover.maxAttempts", 1, ceiling, fallbackAttempts),
408
+ retrySameInstance: integerAtLeast(
409
+ raw.retrySameInstance,
410
+ "failover.retrySameInstance",
411
+ 0,
412
+ DEFAULT_FAILOVER.retrySameInstance,
413
+ ),
414
+ };
415
+ }
416
+
417
+ function resolveCloudflareOAuth(value: unknown): CloudflareOAuthConfig {
418
+ const raw = optionalRecord(value, "cloudflareOAuth");
419
+ const field = (name: keyof CloudflareOAuthConfig): string =>
420
+ raw[name] === undefined
421
+ ? DEFAULT_CLOUDFLARE_OAUTH[name]
422
+ : requiredString(raw[name], `cloudflareOAuth.${name}`);
423
+ return {
424
+ clientId: field("clientId"),
425
+ redirectUri: field("redirectUri"),
426
+ authorizeUrl: field("authorizeUrl"),
427
+ tokenUrl: field("tokenUrl"),
428
+ scopes: field("scopes"),
429
+ };
430
+ }
431
+
432
+ /** 首次无配置文件时的默认配置:内置匿名 anysearch 兜底,排在用户自配实例之后;从配置移除后不再兜底。 */
433
+ export function defaultConfigFile(): ConfigFile {
434
+ return {
435
+ instances: [{ id: "anysearch", preset: "anysearch", mode: "sdk", keys: [], priority: 999 }],
436
+ };
437
+ }
438
+
439
+ /** 校验并解析配置,纯函数,便于测试与面板复用。 */
440
+ export function resolveConfig(
441
+ file: ConfigFile,
442
+ env: NodeJS.ProcessEnv = process.env,
443
+ options?: ResolveConfigOptions,
444
+ ): LoadedConfig {
445
+ if (!isRecord(file)) invalid("配置必须是对象");
446
+ const rawInstances = file.instances ?? [];
447
+ if (!Array.isArray(rawInstances)) invalid("instances 必须是数组");
448
+
449
+ const instances = Array.from(rawInstances, (value, index) => resolveInstance(value, index, env, options));
450
+ const ids = new Set<string>();
451
+ for (const instance of instances) {
452
+ if (ids.has(instance.id)) invalid(`实例 id 重复:${instance.id}`);
453
+ ids.add(instance.id);
454
+ }
455
+
456
+ const searchChain = buildChain(file.defaultChain, "search", "defaultChain", instances);
457
+ const fetchChain = buildChain(file.fetchChain, "fetch", "fetchChain", instances);
458
+
459
+ return {
460
+ file,
461
+ instances,
462
+ searchChain,
463
+ fetchChain,
464
+ limits: resolveLimits(file.limits),
465
+ failover: resolveFailover(file.failover, Math.max(searchChain.length, fetchChain.length)),
466
+ cloudflareOAuth: resolveCloudflareOAuth(file.cloudflareOAuth),
467
+ userAgent: file.userAgent === undefined ? undefined : stringValue(file.userAgent, "userAgent"),
468
+ warnings: instances.flatMap((instance) => instance.warnings.map((warning) => `${instance.id}: ${warning}`)),
469
+ };
470
+ }
471
+
472
+ /** 空文件与不存在的文件都按空配置处理,其余解析失败直接报错。 */
473
+ function parseConfigText(text: string, path: string): ConfigFile {
474
+ if (!text.trim()) return {};
475
+ let parsed: unknown;
476
+ try {
477
+ parsed = parse(text);
478
+ } catch {
479
+ invalid(`配置文件无法解析,未修改文件: ${path}`);
480
+ }
481
+ if (!isRecord(parsed)) invalid(`配置文件必须是对象,未修改文件: ${path}`);
482
+ return parsed as ConfigFile;
483
+ }
484
+
485
+ /** 配置读写:JSONC 注释与 BOM、换行符保留,写入走临时文件 + rename。 */
486
+ export class ConfigStore {
487
+ readonly path: string;
488
+
489
+ constructor(path: string) {
490
+ this.path = path;
491
+ }
492
+
493
+ load(env: NodeJS.ProcessEnv = process.env, options?: ResolveConfigOptions): LoadedConfig {
494
+ const { text, exists } = this.read();
495
+ const file = exists ? parseConfigText(text, this.path) : defaultConfigFile();
496
+ return resolveConfig(file, env, options);
497
+ }
498
+
499
+ /** 读入、修改、校验后原子写回;任一步失败都不改动原文件。 */
500
+ update(
501
+ mutate: (file: ConfigFile) => void,
502
+ env: NodeJS.ProcessEnv = process.env,
503
+ options?: ResolveConfigOptions,
504
+ ): LoadedConfig {
505
+ const { raw, text, exists } = this.read();
506
+ const file = exists ? parseConfigText(text, this.path) : defaultConfigFile();
507
+ mutate(file);
508
+ const loaded = resolveConfig(file, env, options);
509
+ this.write(file, raw, exists);
510
+ return loaded;
511
+ }
512
+
513
+ save(file: ConfigFile, env: NodeJS.ProcessEnv = process.env, options?: ResolveConfigOptions): void {
514
+ const { raw, exists } = this.read();
515
+ resolveConfig(file, env, options);
516
+ this.write(file, raw, exists);
517
+ }
518
+
519
+ private read(): { raw: string; text: string; exists: boolean } {
520
+ const exists = existsSync(this.path);
521
+ const raw = exists ? readFileSync(this.path, "utf8") : "";
522
+ return { raw, text: raw.replace(/^\uFEFF/, ""), exists };
523
+ }
524
+
525
+ private write(file: ConfigFile, previousRaw: string, existed: boolean): void {
526
+ const newline = previousRaw.includes("\r\n") ? "\r\n" : "\n";
527
+ const bom = previousRaw.startsWith("\uFEFF") ? "\uFEFF" : "";
528
+ const next = bom + `${stringify(file, null, 2)}\n`.replace(/\r?\n/g, newline);
529
+
530
+ mkdirSync(dirname(this.path), { recursive: true });
531
+ const temp = `${this.path}.${randomUUID()}.tmp`;
532
+ const mode = existed ? statSync(this.path).mode & 0o777 : 0o600;
533
+ const fd = openSync(temp, "wx", mode);
534
+ try {
535
+ try {
536
+ writeFileSync(fd, next, "utf8");
537
+ } finally {
538
+ closeSync(fd);
539
+ }
540
+ const current = existsSync(this.path) ? readFileSync(this.path, "utf8") : "";
541
+ if (current !== previousRaw) invalid(`配置文件已被其他进程修改,未写入: ${this.path}`);
542
+ renameSync(temp, this.path);
543
+ } finally {
544
+ if (existsSync(temp)) unlinkSync(temp);
545
+ }
546
+ }
547
+ }