proxylang 0.1.2 → 0.1.4
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/README.md +35 -2
- package/dist/cli.js +79 -15
- package/dist/{host-BvBQxdmA.js → host-BPBSZ-jw.js} +137 -27
- package/dist/index.d.ts +281 -32
- package/dist/index.js +622 -7
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -36,7 +36,7 @@ npx proxylang --help
|
|
|
36
36
|
git clone https://github.com/CorrectRoadH/proxylang.git
|
|
37
37
|
cd proxylang
|
|
38
38
|
vp install --frozen-lockfile
|
|
39
|
-
vp
|
|
39
|
+
vp run build
|
|
40
40
|
|
|
41
41
|
# 检查现成的四客户端示例,不读取密码
|
|
42
42
|
vp exec node dist/cli.js check examples/clients.ts
|
|
@@ -45,6 +45,8 @@ vp exec node dist/cli.js check examples/clients.ts
|
|
|
45
45
|
DEMO_PASSWORD=example-only vp exec node dist/cli.js build examples/clients.ts --out out/clients
|
|
46
46
|
```
|
|
47
47
|
|
|
48
|
+
仓库开发统一使用 Vite+:`vp run dev` 监听构建,`vp run check` 检查源码,`vp run verify` 完成源码与隔离安装包验收。`vp add` / `vp remove` 管理依赖,提交更新后的 `package-lock.json`。
|
|
49
|
+
|
|
48
50
|
[四客户端示例](examples/clients.ts)展示完整配置;下面从规则开始,逐步写出自己的版本。
|
|
49
51
|
|
|
50
52
|
## Usage
|
|
@@ -107,7 +109,25 @@ const routing = sequence(
|
|
|
107
109
|
|
|
108
110
|
`slot("proxy")` 让模板不依赖具体节点名称。换一台设备时,可以把同一个 `work` 模板绑定到别的出口;规则正文不用复制。`sequence` 保留原始顺序,不排序、不去重,最终未匹配的流量交给程序的 `fallback`。
|
|
109
111
|
|
|
110
|
-
|
|
112
|
+
`slot` 是普通 TypeScript 函数,表示模板的出口参数;`route` 引用具体节点或组。编辑器会检查字面量槽位名称、缺失或多余的绑定,并沿嵌套块与模板保留提示。`defineConfig` 也会检查目标与案例引用的程序名称。动态输入仍由 `check` 验证。
|
|
113
|
+
|
|
114
|
+
### 2. 一个出口,共享算法意图
|
|
115
|
+
|
|
116
|
+
自动择优可以只声明一次,让各平台选择实现:
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
const automatic = strategy({
|
|
120
|
+
id: "automatic",
|
|
121
|
+
members: ["edge"],
|
|
122
|
+
algorithm: group.auto(),
|
|
123
|
+
});
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Surge 使用 Smart,sing-box 与 Mihomo 使用 URLTest。`auto` 允许评分和切换时机不同;`check` 会显示声明的算法与实际实现。默认 URLTest 使用 `https://www.gstatic.com/generate_204`、180 秒周期和 50 毫秒容差。Stash 当前不支持 `auto`。
|
|
127
|
+
|
|
128
|
+
要求固定机制时使用 `algorithm: group.select()` 或 `algorithm: group.urltest({ url: "https://example.com/probe" })`;目标不能满足就报错。也可以给 `auto` 添加 `implementations`,明确覆写某个平台的实现。
|
|
129
|
+
|
|
130
|
+
原有显式平台配置仍然支持:
|
|
111
131
|
|
|
112
132
|
规则引用 `adaptive`,节点成员与出口名称可以共用,具体选路算法由每个平台独立声明。
|
|
113
133
|
|
|
@@ -186,8 +206,21 @@ PROXY_PASSWORD=example-only npx proxylang build proxy.config.ts --out out
|
|
|
186
206
|
|
|
187
207
|
`explain` 展示条件匹配与逻辑出口,不模拟节点测速或网络连通性。`build` 生成原生配置,整批成功后更新 `out/active.json`,其中列出各目标文件路径;一个目标失败不会替换上一批结果。
|
|
188
208
|
|
|
209
|
+
配置错误提供字段路径和约束提示,例如端口越界会定位到对应规则的条件字段。加载失败会说明是模块缺失、权限不足、语法错误还是执行失败;诊断不会回显原始异常或配置中的秘密。
|
|
210
|
+
|
|
189
211
|
默认输出是包含节点、策略组和规则的 **fragment**,需要与客户端的入口、DNS 等配置组合。可选 `standalone` 提供本机显式代理配置;生成文件不等于部署或系统接管。
|
|
190
212
|
|
|
213
|
+
### 从文件解释请求
|
|
214
|
+
|
|
215
|
+
把请求元数据保存为 UTF-8 JSON,避免 shell 转义:
|
|
216
|
+
|
|
217
|
+
```sh
|
|
218
|
+
npx proxylang explain proxy.config.ts --target backup --request-file request.json
|
|
219
|
+
npx proxylang build --help
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
`--request` 与 `--request-file` 二选一。请求文件和输出目录相对调用目录,配置内的相对 import 仍相对配置文件。构建失败会给出受控原因与恢复建议;锁占用时不会自动抢锁。
|
|
223
|
+
|
|
191
224
|
## 组合规则集与原生能力
|
|
192
225
|
|
|
193
226
|
规则集是可以命名、复用的匹配条件。`any`、`all`、`not` 可以组合本地条件、其它规则集,以及客户端原生能力;动作由使用处绑定。
|
package/dist/cli.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { R as requestSchema, a as explain, i as compile, l as targetCatalog, p as StaticRuleSetUnknownError, t as buildToDirectory } from "./host-
|
|
2
|
+
import { R as requestSchema, a as explain, i as compile, l as targetCatalog, p as StaticRuleSetUnknownError, t as buildToDirectory } from "./host-BPBSZ-jw.js";
|
|
3
|
+
import { open } from "node:fs/promises";
|
|
3
4
|
import { resolve } from "node:path";
|
|
4
5
|
import { pathToFileURL } from "node:url";
|
|
6
|
+
import { constants } from "node:fs";
|
|
5
7
|
import { tsImport } from "tsx/esm/api";
|
|
6
8
|
//#region src/cli.ts
|
|
7
9
|
const print = (value) => process.stdout.write(JSON.stringify(value, null, 2) + "\n");
|
|
@@ -12,20 +14,71 @@ const failure = (code) => {
|
|
|
12
14
|
});
|
|
13
15
|
return 1;
|
|
14
16
|
};
|
|
17
|
+
const usages = {
|
|
18
|
+
targets: ["proxylang targets"],
|
|
19
|
+
check: ["proxylang check config.ts"],
|
|
20
|
+
explain: ["proxylang explain config.ts --target ID --request JSON", "proxylang explain config.ts --target ID --request-file FILE"],
|
|
21
|
+
build: ["proxylang build config.ts --out DIRECTORY"]
|
|
22
|
+
};
|
|
23
|
+
async function readRequestFile(path) {
|
|
24
|
+
const limit = 1048576;
|
|
25
|
+
const file = await open(resolve(path), constants.O_RDONLY | constants.O_NONBLOCK);
|
|
26
|
+
try {
|
|
27
|
+
const stat = await file.stat();
|
|
28
|
+
if (!stat.isFile()) throw new Error("REQUEST_FILE_READ_FAILED");
|
|
29
|
+
if (stat.size > limit) throw new Error("REQUEST_FILE_TOO_LARGE");
|
|
30
|
+
const buffer = Buffer.alloc(1048577);
|
|
31
|
+
let size = 0;
|
|
32
|
+
while (size < buffer.length) {
|
|
33
|
+
const read = await file.read(buffer, size, buffer.length - size, null);
|
|
34
|
+
if (!read.bytesRead) break;
|
|
35
|
+
size += read.bytesRead;
|
|
36
|
+
}
|
|
37
|
+
if (size > limit) throw new Error("REQUEST_FILE_TOO_LARGE");
|
|
38
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, size));
|
|
39
|
+
} finally {
|
|
40
|
+
await file.close();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function loadFailure(cause) {
|
|
44
|
+
let code;
|
|
45
|
+
let name;
|
|
46
|
+
try {
|
|
47
|
+
if (cause && typeof cause === "object") {
|
|
48
|
+
code = Object.getOwnPropertyDescriptor(cause, "code")?.value;
|
|
49
|
+
name = Object.getOwnPropertyDescriptor(cause, "name")?.value;
|
|
50
|
+
if (cause instanceof SyntaxError) name = "SyntaxError";
|
|
51
|
+
}
|
|
52
|
+
} catch {}
|
|
53
|
+
print({
|
|
54
|
+
ok: false,
|
|
55
|
+
code: "CONFIG_LOAD_FAILED",
|
|
56
|
+
...code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND" || code === "ENOENT" ? {
|
|
57
|
+
reason: "MODULE_NOT_FOUND",
|
|
58
|
+
hint: "检查配置文件和 import 路径,并安装所需依赖"
|
|
59
|
+
} : code === "EACCES" || code === "EPERM" ? {
|
|
60
|
+
reason: "ACCESS_DENIED",
|
|
61
|
+
hint: "检查配置及导入文件的读取权限"
|
|
62
|
+
} : name === "TransformError" || name === "SyntaxError" ? {
|
|
63
|
+
reason: "INVALID_SYNTAX",
|
|
64
|
+
hint: "使用 TypeScript 检查配置与导入文件的语法"
|
|
65
|
+
} : {
|
|
66
|
+
reason: "EXECUTION_FAILED",
|
|
67
|
+
hint: "检查默认导出、导入依赖和配置顶层执行逻辑"
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
return 1;
|
|
71
|
+
}
|
|
15
72
|
async function main(args) {
|
|
16
73
|
const [command, file, ...rest] = args;
|
|
17
74
|
if (command === "targets" && args.length === 1) {
|
|
18
75
|
print(targetCatalog);
|
|
19
76
|
return 0;
|
|
20
77
|
}
|
|
21
|
-
|
|
78
|
+
const help = (value) => value === "--help" || value === "-h";
|
|
79
|
+
if (!command || help(command) && args.length === 1 || Object.hasOwn(usages, command) && help(file) && args.length === 2) {
|
|
22
80
|
print({
|
|
23
|
-
usage: [
|
|
24
|
-
"proxylang targets",
|
|
25
|
-
"proxylang check config.ts",
|
|
26
|
-
"proxylang explain config.ts --target ID --request JSON",
|
|
27
|
-
"proxylang build config.ts --out DIRECTORY"
|
|
28
|
-
],
|
|
81
|
+
usage: command && Object.hasOwn(usages, command) ? usages[command] : Object.values(usages).flat(),
|
|
29
82
|
trustedConfig: true
|
|
30
83
|
});
|
|
31
84
|
return 0;
|
|
@@ -34,22 +87,27 @@ async function main(args) {
|
|
|
34
87
|
"check",
|
|
35
88
|
"explain",
|
|
36
89
|
"build"
|
|
37
|
-
].includes(command) || !file) return failure("INVALID_ARGUMENTS");
|
|
90
|
+
].includes(command) || !file?.trim() || help(file)) return failure("INVALID_ARGUMENTS");
|
|
38
91
|
const options = /* @__PURE__ */ new Map();
|
|
39
92
|
for (let i = 0; i < rest.length; i += 2) {
|
|
40
93
|
const key = rest[i];
|
|
41
94
|
const value = rest[i + 1];
|
|
42
|
-
if (!key.startsWith("--") || value
|
|
95
|
+
if (!key.startsWith("--") || !value?.trim() || options.has(key)) return failure("INVALID_ARGUMENTS");
|
|
43
96
|
options.set(key, value);
|
|
44
97
|
}
|
|
45
|
-
const allowed = command === "check" ? [] : command === "build" ? ["--out"] : [
|
|
46
|
-
|
|
98
|
+
const allowed = command === "check" ? [] : command === "build" ? ["--out"] : [
|
|
99
|
+
"--target",
|
|
100
|
+
"--request",
|
|
101
|
+
"--request-file"
|
|
102
|
+
];
|
|
103
|
+
const required = command === "check" ? [] : command === "build" ? ["--out"] : ["--target"];
|
|
104
|
+
if ([...options.keys()].some((key) => !allowed.includes(key)) || required.some((key) => !options.has(key)) || command === "explain" && options.has("--request") === options.has("--request-file")) return failure("INVALID_ARGUMENTS");
|
|
47
105
|
let config;
|
|
48
106
|
try {
|
|
49
107
|
const loaded = await tsImport(pathToFileURL(resolve(file)).href, import.meta.url);
|
|
50
108
|
config = loaded.default?.__esModule === true ? loaded.default.default : loaded.default;
|
|
51
|
-
} catch {
|
|
52
|
-
return
|
|
109
|
+
} catch (cause) {
|
|
110
|
+
return loadFailure(cause);
|
|
53
111
|
}
|
|
54
112
|
const result = compile(config);
|
|
55
113
|
if (!result.ok) {
|
|
@@ -77,9 +135,15 @@ async function main(args) {
|
|
|
77
135
|
return 0;
|
|
78
136
|
}
|
|
79
137
|
if (command === "explain") {
|
|
138
|
+
let source = options.get("--request");
|
|
139
|
+
if (options.has("--request-file")) try {
|
|
140
|
+
source = await readRequestFile(options.get("--request-file"));
|
|
141
|
+
} catch (cause) {
|
|
142
|
+
return failure(cause instanceof Error && cause.message === "REQUEST_FILE_TOO_LARGE" ? "REQUEST_FILE_TOO_LARGE" : "REQUEST_FILE_READ_FAILED");
|
|
143
|
+
}
|
|
80
144
|
let request;
|
|
81
145
|
try {
|
|
82
|
-
request = JSON.parse(
|
|
146
|
+
request = JSON.parse(source);
|
|
83
147
|
} catch {
|
|
84
148
|
return failure("INVALID_REQUEST");
|
|
85
149
|
}
|
|
@@ -38,7 +38,7 @@ const remoteBase = {
|
|
|
38
38
|
})
|
|
39
39
|
};
|
|
40
40
|
const updateInterval = z.number().int().min(60).max(2147483647);
|
|
41
|
-
const nativeRuleSetSchema = z.
|
|
41
|
+
const nativeRuleSetSchema = z.discriminatedUnion("engine", [
|
|
42
42
|
z.strictObject({
|
|
43
43
|
...remoteBase,
|
|
44
44
|
engine: z.literal("surge"),
|
|
@@ -63,7 +63,7 @@ const nativeRuleSetSchema = z.union([
|
|
|
63
63
|
intervalSeconds: updateInterval
|
|
64
64
|
})
|
|
65
65
|
]);
|
|
66
|
-
const matchSchema = z.lazy(() => z.
|
|
66
|
+
const matchSchema = z.lazy(() => z.discriminatedUnion("type", [
|
|
67
67
|
nativeRuleSetSchema,
|
|
68
68
|
z.strictObject({
|
|
69
69
|
type: z.literal("ruleSet"),
|
|
@@ -97,7 +97,7 @@ const matchSchema = z.lazy(() => z.union([
|
|
|
97
97
|
condition: matchSchema
|
|
98
98
|
})
|
|
99
99
|
]));
|
|
100
|
-
const actionSchema = z.
|
|
100
|
+
const actionSchema = z.discriminatedUnion("type", [z.strictObject({ type: z.enum(["direct", "reject"]) }), z.strictObject({
|
|
101
101
|
type: z.literal("route"),
|
|
102
102
|
to: idSchema
|
|
103
103
|
})]);
|
|
@@ -105,7 +105,7 @@ const slotSchema = z.strictObject({
|
|
|
105
105
|
type: z.literal("slot"),
|
|
106
106
|
name: idSchema
|
|
107
107
|
});
|
|
108
|
-
const ruleAction = z.
|
|
108
|
+
const ruleAction = z.discriminatedUnion("type", [actionSchema, slotSchema]);
|
|
109
109
|
const unique = (items) => new Set(items).size === items.length;
|
|
110
110
|
const policySchema = z.lazy(() => z.strictObject({
|
|
111
111
|
type: z.literal("policy"),
|
|
@@ -113,7 +113,7 @@ const policySchema = z.lazy(() => z.strictObject({
|
|
|
113
113
|
exits: z.array(idSchema).refine(unique),
|
|
114
114
|
rules: z.array(entrySchema).min(1)
|
|
115
115
|
}));
|
|
116
|
-
const entrySchema = z.lazy(() => z.
|
|
116
|
+
const entrySchema = z.lazy(() => z.discriminatedUnion("type", [
|
|
117
117
|
z.strictObject({
|
|
118
118
|
type: z.literal("rule"),
|
|
119
119
|
id: idSchema,
|
|
@@ -243,23 +243,33 @@ const url = z.string().url().refine((value) => {
|
|
|
243
243
|
return false;
|
|
244
244
|
}
|
|
245
245
|
});
|
|
246
|
-
const
|
|
246
|
+
const urltestAlgorithmSchema = z.strictObject({
|
|
247
247
|
type: z.literal("urltest"),
|
|
248
248
|
url,
|
|
249
249
|
intervalSeconds: z.number().int().min(1).max(86400).default(180),
|
|
250
250
|
toleranceMs: z.number().int().min(0).max(6e4).default(50)
|
|
251
|
-
})
|
|
252
|
-
const
|
|
251
|
+
});
|
|
252
|
+
const algorithmSchema = z.union([z.strictObject({ type: z.enum(["select", "surge-smart"]) }), urltestAlgorithmSchema]);
|
|
253
|
+
const portableAlgorithmSchema = z.union([z.strictObject({ type: z.enum(["select", "auto"]) }), urltestAlgorithmSchema]);
|
|
254
|
+
const implementationsSchema = z.strictObject({
|
|
255
|
+
surge: algorithmSchema.optional(),
|
|
256
|
+
"sing-box": algorithmSchema.optional(),
|
|
257
|
+
mihomo: algorithmSchema.optional(),
|
|
258
|
+
stash: algorithmSchema.optional()
|
|
259
|
+
});
|
|
260
|
+
const strategyBase = {
|
|
253
261
|
type: z.literal("strategy"),
|
|
254
262
|
id: idSchema,
|
|
255
|
-
members
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
+
members
|
|
264
|
+
};
|
|
265
|
+
const strategySchema = z.union([z.strictObject({
|
|
266
|
+
...strategyBase,
|
|
267
|
+
algorithm: portableAlgorithmSchema,
|
|
268
|
+
implementations: implementationsSchema.optional()
|
|
269
|
+
}), z.strictObject({
|
|
270
|
+
...strategyBase,
|
|
271
|
+
implementations: implementationsSchema.refine((v) => !!v.surge || !!v["sing-box"] || !!v.mihomo || !!v.stash)
|
|
272
|
+
})]);
|
|
263
273
|
const groupSchema = z.union([
|
|
264
274
|
strategySchema,
|
|
265
275
|
z.strictObject({
|
|
@@ -326,6 +336,19 @@ const configSchema = z.strictObject({
|
|
|
326
336
|
})).optional(),
|
|
327
337
|
warningsAsErrors: z.boolean().optional()
|
|
328
338
|
});
|
|
339
|
+
/** Only schema-owned constraints are rendered; Zod messages can contain input values. */
|
|
340
|
+
function schemaIssueMessage(issue) {
|
|
341
|
+
switch (issue.code) {
|
|
342
|
+
case "invalid_type": return `字段类型错误或缺失;需要 ${issue.expected}`;
|
|
343
|
+
case "too_small": return `字段低于下限;${issue.origin} 的最小值或长度为 ${issue.minimum}`;
|
|
344
|
+
case "too_big": return `字段超过上限;${issue.origin} 的最大值或长度为 ${issue.maximum}`;
|
|
345
|
+
case "invalid_value": return `字段必须使用声明的枚举值:${issue.values.map(String).join("、")}`;
|
|
346
|
+
case "invalid_format": return "字段格式不符合约束;检查域名、标识符或路径格式";
|
|
347
|
+
case "unrecognized_keys": return "对象包含当前声明不支持的字段;请删除额外字段";
|
|
348
|
+
case "invalid_union": return "声明不符合任何支持的分支;检查 type、engine 及对应必填字段";
|
|
349
|
+
default: return "字段不满足语义约束;检查地址、范围顺序、重复项或相关字段组合";
|
|
350
|
+
}
|
|
351
|
+
}
|
|
329
352
|
/** Reject cycles, executable values and excessive expansion before recursive schema parsing. */
|
|
330
353
|
function assertData(value) {
|
|
331
354
|
const ancestors = /* @__PURE__ */ new Set();
|
|
@@ -429,6 +452,7 @@ const route = (to) => ({
|
|
|
429
452
|
type: "route",
|
|
430
453
|
to
|
|
431
454
|
});
|
|
455
|
+
/** An exit parameter declared by policy.exits and resolved by use.bindings. */
|
|
432
456
|
const slot = (name) => ({
|
|
433
457
|
type: "slot",
|
|
434
458
|
name
|
|
@@ -465,12 +489,13 @@ const defineConfig = (config) => config;
|
|
|
465
489
|
function selectNodes(nodes, query = {}) {
|
|
466
490
|
return nodes.filter((node) => (!query.regions || node.region !== void 0 && query.regions.includes(node.region)) && (!query.providers || node.provider !== void 0 && query.providers.includes(node.provider)) && (!query.tags || query.tags.every((tag) => node.tags?.includes(tag)))).map((node) => node.id);
|
|
467
491
|
}
|
|
468
|
-
/** A shared strategy
|
|
492
|
+
/** A shared strategy declares an algorithm or explicitly selects native implementations. */
|
|
469
493
|
const strategy = (definition) => ({
|
|
470
494
|
type: "strategy",
|
|
471
495
|
...definition
|
|
472
496
|
});
|
|
473
497
|
const group = {
|
|
498
|
+
auto: () => ({ type: "auto" }),
|
|
474
499
|
select: () => ({ type: "select" }),
|
|
475
500
|
urltest: (options) => ({
|
|
476
501
|
type: "urltest",
|
|
@@ -1102,6 +1127,7 @@ const targetCatalog = deepFreeze([
|
|
|
1102
1127
|
{
|
|
1103
1128
|
engine: "sing-box",
|
|
1104
1129
|
version: "1.11.0",
|
|
1130
|
+
autoGroup: "urltest",
|
|
1105
1131
|
platforms: ["linux", "macos"],
|
|
1106
1132
|
protocols: [
|
|
1107
1133
|
"trojan",
|
|
@@ -1118,6 +1144,7 @@ const targetCatalog = deepFreeze([
|
|
|
1118
1144
|
{
|
|
1119
1145
|
engine: "sing-box",
|
|
1120
1146
|
version: "1.12.0",
|
|
1147
|
+
autoGroup: "urltest",
|
|
1121
1148
|
platforms: ["linux", "macos"],
|
|
1122
1149
|
protocols: [
|
|
1123
1150
|
"trojan",
|
|
@@ -1135,6 +1162,7 @@ const targetCatalog = deepFreeze([
|
|
|
1135
1162
|
{
|
|
1136
1163
|
engine: "surge",
|
|
1137
1164
|
version: "6.10.0",
|
|
1165
|
+
autoGroup: "surge-smart",
|
|
1138
1166
|
platforms: ["macos"],
|
|
1139
1167
|
protocols: [
|
|
1140
1168
|
"trojan",
|
|
@@ -1151,6 +1179,7 @@ const targetCatalog = deepFreeze([
|
|
|
1151
1179
|
{
|
|
1152
1180
|
engine: "mihomo",
|
|
1153
1181
|
version: "1.19.32",
|
|
1182
|
+
autoGroup: "urltest",
|
|
1154
1183
|
platforms: ["linux", "macos"],
|
|
1155
1184
|
protocols: [
|
|
1156
1185
|
"trojan",
|
|
@@ -1168,6 +1197,7 @@ const targetCatalog = deepFreeze([
|
|
|
1168
1197
|
{
|
|
1169
1198
|
engine: "stash",
|
|
1170
1199
|
version: "4.2.1",
|
|
1200
|
+
autoGroup: null,
|
|
1171
1201
|
platforms: ["macos"],
|
|
1172
1202
|
protocols: [
|
|
1173
1203
|
"trojan",
|
|
@@ -1205,16 +1235,44 @@ function isReservedNativeName(name, engine) {
|
|
|
1205
1235
|
}
|
|
1206
1236
|
//#endregion
|
|
1207
1237
|
//#region src/strategies.ts
|
|
1208
|
-
function
|
|
1238
|
+
function satisfiesAlgorithm(requested, actual) {
|
|
1239
|
+
if (requested.type === "auto") return actual.type === "urltest" || actual.type === "surge-smart";
|
|
1240
|
+
if (requested.type === "select") return actual.type === "select";
|
|
1241
|
+
return actual.type === "urltest" && actual.url === requested.url && (actual.intervalSeconds ?? 180) === (requested.intervalSeconds ?? 180) && (actual.toleranceMs ?? 50) === (requested.toleranceMs ?? 50);
|
|
1242
|
+
}
|
|
1243
|
+
function lowerStrategies(groups, target, diagnostics, path) {
|
|
1209
1244
|
const selected = [];
|
|
1210
1245
|
const selections = [];
|
|
1246
|
+
const { engine } = target;
|
|
1247
|
+
const descriptor = targetCatalog.find((d) => d.engine === engine && d.version === target.version && d.platforms.includes(target.platform));
|
|
1211
1248
|
for (const group of groups) {
|
|
1212
1249
|
if (group.type !== "strategy") {
|
|
1213
1250
|
selected.push(group);
|
|
1214
1251
|
continue;
|
|
1215
1252
|
}
|
|
1216
|
-
const
|
|
1217
|
-
|
|
1253
|
+
const requested = group.algorithm;
|
|
1254
|
+
if (requested && Object.values(group.implementations ?? {}).some((implementation) => implementation && !satisfiesAlgorithm(requested, implementation))) {
|
|
1255
|
+
diagnostics.push({
|
|
1256
|
+
severity: "error",
|
|
1257
|
+
code: "ALGORITHM_CONTRACT_MISMATCH",
|
|
1258
|
+
path: `${path}.groups.${group.id}.implementations`,
|
|
1259
|
+
message: "平台实现不满足声明的通用算法或固定参数"
|
|
1260
|
+
});
|
|
1261
|
+
continue;
|
|
1262
|
+
}
|
|
1263
|
+
const override = group.implementations?.[engine];
|
|
1264
|
+
let algorithm = override;
|
|
1265
|
+
if (!algorithm && requested) {
|
|
1266
|
+
if (requested.type !== "auto") algorithm = requested;
|
|
1267
|
+
else if (descriptor?.autoGroup === "surge-smart") algorithm = { type: "surge-smart" };
|
|
1268
|
+
else if (descriptor?.autoGroup === "urltest") algorithm = {
|
|
1269
|
+
type: "urltest",
|
|
1270
|
+
url: "https://www.gstatic.com/generate_204",
|
|
1271
|
+
intervalSeconds: 180,
|
|
1272
|
+
toleranceMs: 50
|
|
1273
|
+
};
|
|
1274
|
+
}
|
|
1275
|
+
const code = !algorithm ? requested ? "GROUP_UNSUPPORTED" : "STRATEGY_IMPLEMENTATION_MISSING" : algorithm.type === "surge-smart" && engine !== "surge" ? "ALGORITHM_ENGINE_MISMATCH" : void 0;
|
|
1218
1276
|
if (code) {
|
|
1219
1277
|
diagnostics.push({
|
|
1220
1278
|
severity: "error",
|
|
@@ -1233,7 +1291,11 @@ function lowerStrategies(groups, engine, diagnostics, path) {
|
|
|
1233
1291
|
id: group.id,
|
|
1234
1292
|
engine,
|
|
1235
1293
|
algorithm,
|
|
1236
|
-
members: group.members
|
|
1294
|
+
members: group.members,
|
|
1295
|
+
...requested ? {
|
|
1296
|
+
requestedAlgorithm: requested,
|
|
1297
|
+
implementationSource: override ? "override" : "default"
|
|
1298
|
+
} : {}
|
|
1237
1299
|
});
|
|
1238
1300
|
}
|
|
1239
1301
|
return {
|
|
@@ -1330,7 +1392,7 @@ function compileStrategyGroups(input) {
|
|
|
1330
1392
|
if ([...nativeNames.values()].some((name) => !nativeNameSchema.safeParse(name).success)) error("INVALID_NATIVE_NAME", "names", "最终名称不符合原生名称约束");
|
|
1331
1393
|
if ([...nativeNames.values()].some((value) => isReservedNativeName(value, target.engine))) error("INVALID_NATIVE_NAME", "names", "最终名称与目标内建策略冲突");
|
|
1332
1394
|
if (new Set(nativeNames.values()).size !== nativeNames.size) error("DUPLICATE_NATIVE_NAME", "names", "最终节点和策略名称必须唯一");
|
|
1333
|
-
const { groups, selections } = lowerStrategies(strategies, target
|
|
1395
|
+
const { groups, selections } = lowerStrategies(strategies, target, diagnostics, "$");
|
|
1334
1396
|
const all = new Set(ids);
|
|
1335
1397
|
for (const g of groups) {
|
|
1336
1398
|
if (!descriptor.groups.includes(g.type)) error("GROUP_UNSUPPORTED", `strategies.${g.id}`, "目标后端不能保持此算法的参数语义");
|
|
@@ -1386,7 +1448,7 @@ function compile(input) {
|
|
|
1386
1448
|
}
|
|
1387
1449
|
const parsed = configSchema.safeParse(input);
|
|
1388
1450
|
if (!parsed.success) {
|
|
1389
|
-
for (const issue of parsed.error.issues.slice(0, 20)) error("INVALID_SCHEMA", issue.path.map(String).join(".") || "$",
|
|
1451
|
+
for (const issue of parsed.error.issues.slice(0, 20)) error("INVALID_SCHEMA", issue.path.map(String).join(".") || "$", schemaIssueMessage(issue));
|
|
1390
1452
|
return deepFreeze({
|
|
1391
1453
|
ok: false,
|
|
1392
1454
|
diagnostics,
|
|
@@ -1462,7 +1524,7 @@ function compile(input) {
|
|
|
1462
1524
|
continue;
|
|
1463
1525
|
}
|
|
1464
1526
|
const originalProgram = config.programs[target.program];
|
|
1465
|
-
const lowered = lowerStrategies(originalProgram?.groups ?? [], target
|
|
1527
|
+
const lowered = lowerStrategies(originalProgram?.groups ?? [], target, diagnostics, path);
|
|
1466
1528
|
const program = originalProgram ? {
|
|
1467
1529
|
...originalProgram,
|
|
1468
1530
|
groups: lowered.groups
|
|
@@ -1771,13 +1833,49 @@ function surge(plan, secret) {
|
|
|
1771
1833
|
}
|
|
1772
1834
|
//#endregion
|
|
1773
1835
|
//#region src/host.ts
|
|
1836
|
+
const buildHints = {
|
|
1837
|
+
INVALID_OUTPUT_DIRECTORY: "提供非空输出目录路径",
|
|
1838
|
+
OUTPUT_LOCKED: "确认没有构建正在运行;检查并处理遗留锁后重试,不要删除仍在使用的锁",
|
|
1839
|
+
SECRET_MISSING: "在构建环境提供配置引用的非空秘密变量",
|
|
1840
|
+
SECRET_RESOLUTION_FAILED: "检查秘密解析器;原始异常不会进入构建报告",
|
|
1841
|
+
PUBLISHED_CLEANUP_FAILED: "活动指针已经切换;检查残留锁和临时文件,不要假设发布失败",
|
|
1842
|
+
FAILED_CLEANUP_REQUIRED: "旧活动指针保留;检查本次残留产物和锁后重试"
|
|
1843
|
+
};
|
|
1844
|
+
function outputFailure(error) {
|
|
1845
|
+
const code = error && typeof error === "object" ? Object.getOwnPropertyDescriptor(error, "code")?.value : void 0;
|
|
1846
|
+
if (code === "EACCES" || code === "EPERM") return {
|
|
1847
|
+
reason: "ACCESS_DENIED",
|
|
1848
|
+
hint: "检查输出目录的写入和遍历权限"
|
|
1849
|
+
};
|
|
1850
|
+
if (code === "ENOSPC" || code === "EDQUOT") return {
|
|
1851
|
+
reason: "NO_SPACE",
|
|
1852
|
+
hint: "释放磁盘空间或调整存储配额后重试"
|
|
1853
|
+
};
|
|
1854
|
+
if (code === "EROFS") return {
|
|
1855
|
+
reason: "READ_ONLY",
|
|
1856
|
+
hint: "选择可写的本地输出目录"
|
|
1857
|
+
};
|
|
1858
|
+
if ([
|
|
1859
|
+
"ENOTDIR",
|
|
1860
|
+
"EISDIR",
|
|
1861
|
+
"EEXIST",
|
|
1862
|
+
"UNSAFE_DIRECTORY"
|
|
1863
|
+
].includes(code)) return {
|
|
1864
|
+
reason: "INVALID_DIRECTORY",
|
|
1865
|
+
hint: "检查输出根、generations 和 active.json 的文件类型;输出目录不能是符号链接"
|
|
1866
|
+
};
|
|
1867
|
+
return {
|
|
1868
|
+
reason: "IO_ERROR",
|
|
1869
|
+
hint: "检查输出目录及文件系统状态,旧活动配置在发布前失败时保持不变"
|
|
1870
|
+
};
|
|
1871
|
+
}
|
|
1774
1872
|
async function directory(path) {
|
|
1775
1873
|
await mkdir(path, {
|
|
1776
1874
|
recursive: true,
|
|
1777
1875
|
mode: 448
|
|
1778
1876
|
});
|
|
1779
1877
|
const stat = await lstat(path);
|
|
1780
|
-
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("UNSAFE_DIRECTORY");
|
|
1878
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw Object.assign(/* @__PURE__ */ new Error("UNSAFE_DIRECTORY"), { code: "UNSAFE_DIRECTORY" });
|
|
1781
1879
|
}
|
|
1782
1880
|
/** All targets publish together by one active.json rename. Config files never go to stdout. */
|
|
1783
1881
|
async function buildToDirectory(compilation, output, resolveSecret = (token) => process.env[token.name]) {
|
|
@@ -1786,6 +1884,12 @@ async function buildToDirectory(compilation, output, resolveSecret = (token) =>
|
|
|
1786
1884
|
exitCode: 1,
|
|
1787
1885
|
code: "COMPILATION_FAILED"
|
|
1788
1886
|
};
|
|
1887
|
+
if (typeof output !== "string" || !output.trim()) return {
|
|
1888
|
+
published: false,
|
|
1889
|
+
exitCode: 1,
|
|
1890
|
+
code: "INVALID_OUTPUT_DIRECTORY",
|
|
1891
|
+
hint: buildHints.INVALID_OUTPUT_DIRECTORY
|
|
1892
|
+
};
|
|
1789
1893
|
const root = resolve(output);
|
|
1790
1894
|
if (compilation.plans.some((plan) => plan.program.endpoints?.some((endpoint) => pathsOverlap(root, endpoint.stateDirectory)))) return {
|
|
1791
1895
|
published: false,
|
|
@@ -1802,6 +1906,7 @@ async function buildToDirectory(compilation, output, resolveSecret = (token) =>
|
|
|
1802
1906
|
let published = false;
|
|
1803
1907
|
let code = "BUILD_FAILED";
|
|
1804
1908
|
let cleanupFailed = false;
|
|
1909
|
+
let detail = {};
|
|
1805
1910
|
try {
|
|
1806
1911
|
await directory(root);
|
|
1807
1912
|
try {
|
|
@@ -1811,7 +1916,8 @@ async function buildToDirectory(compilation, output, resolveSecret = (token) =>
|
|
|
1811
1916
|
if (error.code === "EEXIST") return {
|
|
1812
1917
|
published: false,
|
|
1813
1918
|
exitCode: 1,
|
|
1814
|
-
code: "OUTPUT_LOCKED"
|
|
1919
|
+
code: "OUTPUT_LOCKED",
|
|
1920
|
+
hint: buildHints.OUTPUT_LOCKED
|
|
1815
1921
|
};
|
|
1816
1922
|
throw error;
|
|
1817
1923
|
}
|
|
@@ -1859,6 +1965,7 @@ async function buildToDirectory(compilation, output, resolveSecret = (token) =>
|
|
|
1859
1965
|
code = "PUBLISHED";
|
|
1860
1966
|
} catch (error) {
|
|
1861
1967
|
code = error instanceof RenderError ? error.code : "OUTPUT_FAILED";
|
|
1968
|
+
detail = error instanceof RenderError ? { hint: buildHints[code] } : outputFailure(error);
|
|
1862
1969
|
} finally {
|
|
1863
1970
|
if (locked) {
|
|
1864
1971
|
try {
|
|
@@ -1878,10 +1985,13 @@ async function buildToDirectory(compilation, output, resolveSecret = (token) =>
|
|
|
1878
1985
|
}
|
|
1879
1986
|
}
|
|
1880
1987
|
}
|
|
1988
|
+
const resultCode = cleanupFailed ? published ? "PUBLISHED_CLEANUP_FAILED" : "FAILED_CLEANUP_REQUIRED" : code;
|
|
1881
1989
|
return {
|
|
1882
1990
|
published,
|
|
1883
1991
|
exitCode: published ? cleanupFailed ? 2 : 0 : 1,
|
|
1884
|
-
code:
|
|
1992
|
+
code: resultCode,
|
|
1993
|
+
...detail,
|
|
1994
|
+
...buildHints[resultCode] ? { hint: buildHints[resultCode] } : {},
|
|
1885
1995
|
...published ? {
|
|
1886
1996
|
active: join(root, "active.json"),
|
|
1887
1997
|
generation
|