proxylang 0.1.3 → 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 +31 -2
- package/dist/cli.js +48 -13
- package/dist/{host-CB08cTs0.js → host-BPBSZ-jw.js} +117 -21
- package/dist/index.d.ts +54 -13
- package/dist/index.js +165 -2
- 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
|
|
@@ -109,7 +111,23 @@ const routing = sequence(
|
|
|
109
111
|
|
|
110
112
|
`slot` 是普通 TypeScript 函数,表示模板的出口参数;`route` 引用具体节点或组。编辑器会检查字面量槽位名称、缺失或多余的绑定,并沿嵌套块与模板保留提示。`defineConfig` 也会检查目标与案例引用的程序名称。动态输入仍由 `check` 验证。
|
|
111
113
|
|
|
112
|
-
### 2.
|
|
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
|
+
原有显式平台配置仍然支持:
|
|
113
131
|
|
|
114
132
|
规则引用 `adaptive`,节点成员与出口名称可以共用,具体选路算法由每个平台独立声明。
|
|
115
133
|
|
|
@@ -192,6 +210,17 @@ PROXY_PASSWORD=example-only npx proxylang build proxy.config.ts --out out
|
|
|
192
210
|
|
|
193
211
|
默认输出是包含节点、策略组和规则的 **fragment**,需要与客户端的入口、DNS 等配置组合。可选 `standalone` 提供本机显式代理配置;生成文件不等于部署或系统接管。
|
|
194
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
|
+
|
|
195
224
|
## 组合规则集与原生能力
|
|
196
225
|
|
|
197
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,6 +14,32 @@ 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
|
+
}
|
|
15
43
|
function loadFailure(cause) {
|
|
16
44
|
let code;
|
|
17
45
|
let name;
|
|
@@ -47,14 +75,10 @@ async function main(args) {
|
|
|
47
75
|
print(targetCatalog);
|
|
48
76
|
return 0;
|
|
49
77
|
}
|
|
50
|
-
|
|
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) {
|
|
51
80
|
print({
|
|
52
|
-
usage: [
|
|
53
|
-
"proxylang targets",
|
|
54
|
-
"proxylang check config.ts",
|
|
55
|
-
"proxylang explain config.ts --target ID --request JSON",
|
|
56
|
-
"proxylang build config.ts --out DIRECTORY"
|
|
57
|
-
],
|
|
81
|
+
usage: command && Object.hasOwn(usages, command) ? usages[command] : Object.values(usages).flat(),
|
|
58
82
|
trustedConfig: true
|
|
59
83
|
});
|
|
60
84
|
return 0;
|
|
@@ -63,16 +87,21 @@ async function main(args) {
|
|
|
63
87
|
"check",
|
|
64
88
|
"explain",
|
|
65
89
|
"build"
|
|
66
|
-
].includes(command) || !file) return failure("INVALID_ARGUMENTS");
|
|
90
|
+
].includes(command) || !file?.trim() || help(file)) return failure("INVALID_ARGUMENTS");
|
|
67
91
|
const options = /* @__PURE__ */ new Map();
|
|
68
92
|
for (let i = 0; i < rest.length; i += 2) {
|
|
69
93
|
const key = rest[i];
|
|
70
94
|
const value = rest[i + 1];
|
|
71
|
-
if (!key.startsWith("--") || value
|
|
95
|
+
if (!key.startsWith("--") || !value?.trim() || options.has(key)) return failure("INVALID_ARGUMENTS");
|
|
72
96
|
options.set(key, value);
|
|
73
97
|
}
|
|
74
|
-
const allowed = command === "check" ? [] : command === "build" ? ["--out"] : [
|
|
75
|
-
|
|
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");
|
|
76
105
|
let config;
|
|
77
106
|
try {
|
|
78
107
|
const loaded = await tsImport(pathToFileURL(resolve(file)).href, import.meta.url);
|
|
@@ -106,9 +135,15 @@ async function main(args) {
|
|
|
106
135
|
return 0;
|
|
107
136
|
}
|
|
108
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
|
+
}
|
|
109
144
|
let request;
|
|
110
145
|
try {
|
|
111
|
-
request = JSON.parse(
|
|
146
|
+
request = JSON.parse(source);
|
|
112
147
|
} catch {
|
|
113
148
|
return failure("INVALID_REQUEST");
|
|
114
149
|
}
|
|
@@ -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({
|
|
@@ -479,12 +489,13 @@ const defineConfig = (config) => config;
|
|
|
479
489
|
function selectNodes(nodes, query = {}) {
|
|
480
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);
|
|
481
491
|
}
|
|
482
|
-
/** A shared strategy
|
|
492
|
+
/** A shared strategy declares an algorithm or explicitly selects native implementations. */
|
|
483
493
|
const strategy = (definition) => ({
|
|
484
494
|
type: "strategy",
|
|
485
495
|
...definition
|
|
486
496
|
});
|
|
487
497
|
const group = {
|
|
498
|
+
auto: () => ({ type: "auto" }),
|
|
488
499
|
select: () => ({ type: "select" }),
|
|
489
500
|
urltest: (options) => ({
|
|
490
501
|
type: "urltest",
|
|
@@ -1116,6 +1127,7 @@ const targetCatalog = deepFreeze([
|
|
|
1116
1127
|
{
|
|
1117
1128
|
engine: "sing-box",
|
|
1118
1129
|
version: "1.11.0",
|
|
1130
|
+
autoGroup: "urltest",
|
|
1119
1131
|
platforms: ["linux", "macos"],
|
|
1120
1132
|
protocols: [
|
|
1121
1133
|
"trojan",
|
|
@@ -1132,6 +1144,7 @@ const targetCatalog = deepFreeze([
|
|
|
1132
1144
|
{
|
|
1133
1145
|
engine: "sing-box",
|
|
1134
1146
|
version: "1.12.0",
|
|
1147
|
+
autoGroup: "urltest",
|
|
1135
1148
|
platforms: ["linux", "macos"],
|
|
1136
1149
|
protocols: [
|
|
1137
1150
|
"trojan",
|
|
@@ -1149,6 +1162,7 @@ const targetCatalog = deepFreeze([
|
|
|
1149
1162
|
{
|
|
1150
1163
|
engine: "surge",
|
|
1151
1164
|
version: "6.10.0",
|
|
1165
|
+
autoGroup: "surge-smart",
|
|
1152
1166
|
platforms: ["macos"],
|
|
1153
1167
|
protocols: [
|
|
1154
1168
|
"trojan",
|
|
@@ -1165,6 +1179,7 @@ const targetCatalog = deepFreeze([
|
|
|
1165
1179
|
{
|
|
1166
1180
|
engine: "mihomo",
|
|
1167
1181
|
version: "1.19.32",
|
|
1182
|
+
autoGroup: "urltest",
|
|
1168
1183
|
platforms: ["linux", "macos"],
|
|
1169
1184
|
protocols: [
|
|
1170
1185
|
"trojan",
|
|
@@ -1182,6 +1197,7 @@ const targetCatalog = deepFreeze([
|
|
|
1182
1197
|
{
|
|
1183
1198
|
engine: "stash",
|
|
1184
1199
|
version: "4.2.1",
|
|
1200
|
+
autoGroup: null,
|
|
1185
1201
|
platforms: ["macos"],
|
|
1186
1202
|
protocols: [
|
|
1187
1203
|
"trojan",
|
|
@@ -1219,16 +1235,44 @@ function isReservedNativeName(name, engine) {
|
|
|
1219
1235
|
}
|
|
1220
1236
|
//#endregion
|
|
1221
1237
|
//#region src/strategies.ts
|
|
1222
|
-
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) {
|
|
1223
1244
|
const selected = [];
|
|
1224
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));
|
|
1225
1248
|
for (const group of groups) {
|
|
1226
1249
|
if (group.type !== "strategy") {
|
|
1227
1250
|
selected.push(group);
|
|
1228
1251
|
continue;
|
|
1229
1252
|
}
|
|
1230
|
-
const
|
|
1231
|
-
|
|
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;
|
|
1232
1276
|
if (code) {
|
|
1233
1277
|
diagnostics.push({
|
|
1234
1278
|
severity: "error",
|
|
@@ -1247,7 +1291,11 @@ function lowerStrategies(groups, engine, diagnostics, path) {
|
|
|
1247
1291
|
id: group.id,
|
|
1248
1292
|
engine,
|
|
1249
1293
|
algorithm,
|
|
1250
|
-
members: group.members
|
|
1294
|
+
members: group.members,
|
|
1295
|
+
...requested ? {
|
|
1296
|
+
requestedAlgorithm: requested,
|
|
1297
|
+
implementationSource: override ? "override" : "default"
|
|
1298
|
+
} : {}
|
|
1251
1299
|
});
|
|
1252
1300
|
}
|
|
1253
1301
|
return {
|
|
@@ -1344,7 +1392,7 @@ function compileStrategyGroups(input) {
|
|
|
1344
1392
|
if ([...nativeNames.values()].some((name) => !nativeNameSchema.safeParse(name).success)) error("INVALID_NATIVE_NAME", "names", "最终名称不符合原生名称约束");
|
|
1345
1393
|
if ([...nativeNames.values()].some((value) => isReservedNativeName(value, target.engine))) error("INVALID_NATIVE_NAME", "names", "最终名称与目标内建策略冲突");
|
|
1346
1394
|
if (new Set(nativeNames.values()).size !== nativeNames.size) error("DUPLICATE_NATIVE_NAME", "names", "最终节点和策略名称必须唯一");
|
|
1347
|
-
const { groups, selections } = lowerStrategies(strategies, target
|
|
1395
|
+
const { groups, selections } = lowerStrategies(strategies, target, diagnostics, "$");
|
|
1348
1396
|
const all = new Set(ids);
|
|
1349
1397
|
for (const g of groups) {
|
|
1350
1398
|
if (!descriptor.groups.includes(g.type)) error("GROUP_UNSUPPORTED", `strategies.${g.id}`, "目标后端不能保持此算法的参数语义");
|
|
@@ -1476,7 +1524,7 @@ function compile(input) {
|
|
|
1476
1524
|
continue;
|
|
1477
1525
|
}
|
|
1478
1526
|
const originalProgram = config.programs[target.program];
|
|
1479
|
-
const lowered = lowerStrategies(originalProgram?.groups ?? [], target
|
|
1527
|
+
const lowered = lowerStrategies(originalProgram?.groups ?? [], target, diagnostics, path);
|
|
1480
1528
|
const program = originalProgram ? {
|
|
1481
1529
|
...originalProgram,
|
|
1482
1530
|
groups: lowered.groups
|
|
@@ -1785,13 +1833,49 @@ function surge(plan, secret) {
|
|
|
1785
1833
|
}
|
|
1786
1834
|
//#endregion
|
|
1787
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
|
+
}
|
|
1788
1872
|
async function directory(path) {
|
|
1789
1873
|
await mkdir(path, {
|
|
1790
1874
|
recursive: true,
|
|
1791
1875
|
mode: 448
|
|
1792
1876
|
});
|
|
1793
1877
|
const stat = await lstat(path);
|
|
1794
|
-
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" });
|
|
1795
1879
|
}
|
|
1796
1880
|
/** All targets publish together by one active.json rename. Config files never go to stdout. */
|
|
1797
1881
|
async function buildToDirectory(compilation, output, resolveSecret = (token) => process.env[token.name]) {
|
|
@@ -1800,6 +1884,12 @@ async function buildToDirectory(compilation, output, resolveSecret = (token) =>
|
|
|
1800
1884
|
exitCode: 1,
|
|
1801
1885
|
code: "COMPILATION_FAILED"
|
|
1802
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
|
+
};
|
|
1803
1893
|
const root = resolve(output);
|
|
1804
1894
|
if (compilation.plans.some((plan) => plan.program.endpoints?.some((endpoint) => pathsOverlap(root, endpoint.stateDirectory)))) return {
|
|
1805
1895
|
published: false,
|
|
@@ -1816,6 +1906,7 @@ async function buildToDirectory(compilation, output, resolveSecret = (token) =>
|
|
|
1816
1906
|
let published = false;
|
|
1817
1907
|
let code = "BUILD_FAILED";
|
|
1818
1908
|
let cleanupFailed = false;
|
|
1909
|
+
let detail = {};
|
|
1819
1910
|
try {
|
|
1820
1911
|
await directory(root);
|
|
1821
1912
|
try {
|
|
@@ -1825,7 +1916,8 @@ async function buildToDirectory(compilation, output, resolveSecret = (token) =>
|
|
|
1825
1916
|
if (error.code === "EEXIST") return {
|
|
1826
1917
|
published: false,
|
|
1827
1918
|
exitCode: 1,
|
|
1828
|
-
code: "OUTPUT_LOCKED"
|
|
1919
|
+
code: "OUTPUT_LOCKED",
|
|
1920
|
+
hint: buildHints.OUTPUT_LOCKED
|
|
1829
1921
|
};
|
|
1830
1922
|
throw error;
|
|
1831
1923
|
}
|
|
@@ -1873,6 +1965,7 @@ async function buildToDirectory(compilation, output, resolveSecret = (token) =>
|
|
|
1873
1965
|
code = "PUBLISHED";
|
|
1874
1966
|
} catch (error) {
|
|
1875
1967
|
code = error instanceof RenderError ? error.code : "OUTPUT_FAILED";
|
|
1968
|
+
detail = error instanceof RenderError ? { hint: buildHints[code] } : outputFailure(error);
|
|
1876
1969
|
} finally {
|
|
1877
1970
|
if (locked) {
|
|
1878
1971
|
try {
|
|
@@ -1892,10 +1985,13 @@ async function buildToDirectory(compilation, output, resolveSecret = (token) =>
|
|
|
1892
1985
|
}
|
|
1893
1986
|
}
|
|
1894
1987
|
}
|
|
1988
|
+
const resultCode = cleanupFailed ? published ? "PUBLISHED_CLEANUP_FAILED" : "FAILED_CLEANUP_REQUIRED" : code;
|
|
1895
1989
|
return {
|
|
1896
1990
|
published,
|
|
1897
1991
|
exitCode: published ? cleanupFailed ? 2 : 0 : 1,
|
|
1898
|
-
code:
|
|
1992
|
+
code: resultCode,
|
|
1993
|
+
...detail,
|
|
1994
|
+
...buildHints[resultCode] ? { hint: buildHints[resultCode] } : {},
|
|
1899
1995
|
...published ? {
|
|
1900
1996
|
active: join(root, "active.json"),
|
|
1901
1997
|
generation
|
package/dist/index.d.ts
CHANGED
|
@@ -169,22 +169,37 @@ export type GroupAlgorithm = {
|
|
|
169
169
|
readonly intervalSeconds?: number;
|
|
170
170
|
readonly toleranceMs?: number;
|
|
171
171
|
};
|
|
172
|
-
export type
|
|
173
|
-
readonly type: "
|
|
172
|
+
export type PortableAlgorithm = {
|
|
173
|
+
readonly type: "auto";
|
|
174
|
+
} | Extract<GroupAlgorithm, {
|
|
175
|
+
readonly type: "select" | "urltest";
|
|
176
|
+
}>;
|
|
177
|
+
export type StrategyImplementations = {
|
|
178
|
+
readonly surge?: GroupAlgorithm;
|
|
179
|
+
readonly "sing-box"?: GroupAlgorithm;
|
|
180
|
+
readonly mihomo?: GroupAlgorithm;
|
|
181
|
+
readonly stash?: GroupAlgorithm;
|
|
182
|
+
};
|
|
183
|
+
export type StrategyDefinition = {
|
|
174
184
|
readonly id: string;
|
|
175
185
|
readonly members: readonly string[];
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
186
|
+
} & ({
|
|
187
|
+
readonly algorithm: PortableAlgorithm;
|
|
188
|
+
readonly implementations?: StrategyImplementations;
|
|
189
|
+
} | {
|
|
190
|
+
readonly algorithm?: never;
|
|
191
|
+
readonly implementations: StrategyImplementations;
|
|
192
|
+
});
|
|
193
|
+
export type Strategy = StrategyDefinition & {
|
|
194
|
+
readonly type: "strategy";
|
|
182
195
|
};
|
|
183
196
|
export type StrategySelection = {
|
|
184
197
|
readonly id: string;
|
|
185
198
|
readonly engine: Engine;
|
|
186
199
|
readonly algorithm: GroupAlgorithm;
|
|
187
200
|
readonly members: readonly string[];
|
|
201
|
+
readonly requestedAlgorithm?: PortableAlgorithm;
|
|
202
|
+
readonly implementationSource?: "default" | "override";
|
|
188
203
|
};
|
|
189
204
|
export type ConcreteGroup = {
|
|
190
205
|
readonly id: string;
|
|
@@ -341,16 +356,25 @@ export declare function selectNodes(nodes: readonly ProxyNode[], query?: {
|
|
|
341
356
|
providers?: readonly string[];
|
|
342
357
|
tags?: readonly string[];
|
|
343
358
|
}): string[];
|
|
344
|
-
/** A shared strategy
|
|
345
|
-
export declare const strategy: (definition:
|
|
359
|
+
/** A shared strategy declares an algorithm or explicitly selects native implementations. */
|
|
360
|
+
export declare const strategy: (definition: StrategyDefinition) => Strategy;
|
|
346
361
|
export declare const group: {
|
|
347
|
-
|
|
362
|
+
auto: () => {
|
|
363
|
+
readonly type: "auto";
|
|
364
|
+
};
|
|
365
|
+
select: () => Extract<GroupAlgorithm, {
|
|
366
|
+
type: "select";
|
|
367
|
+
}>;
|
|
348
368
|
urltest: (options: Omit<Extract<GroupAlgorithm, {
|
|
349
369
|
type: "urltest";
|
|
350
|
-
}>, "type">) => GroupAlgorithm
|
|
370
|
+
}>, "type">) => Extract<GroupAlgorithm, {
|
|
371
|
+
type: "urltest";
|
|
372
|
+
}>;
|
|
351
373
|
};
|
|
352
374
|
export declare const surge: {
|
|
353
|
-
smart: () => GroupAlgorithm
|
|
375
|
+
smart: () => Extract<GroupAlgorithm, {
|
|
376
|
+
type: "surge-smart";
|
|
377
|
+
}>;
|
|
354
378
|
ruleSet: (options: Omit<Extract<NativeRuleSet, {
|
|
355
379
|
engine: "surge";
|
|
356
380
|
}>, "type" | "engine" | "format"> & {
|
|
@@ -382,6 +406,7 @@ export declare const singbox: {
|
|
|
382
406
|
export declare const targetCatalog: readonly [{
|
|
383
407
|
readonly engine: "sing-box";
|
|
384
408
|
readonly version: "1.11.0";
|
|
409
|
+
readonly autoGroup: "urltest";
|
|
385
410
|
readonly platforms: readonly ["linux", "macos"];
|
|
386
411
|
readonly protocols: readonly ["trojan", "http", "shadowsocks", "vmess", "vless"];
|
|
387
412
|
readonly endpoints: readonly [];
|
|
@@ -391,6 +416,7 @@ export declare const targetCatalog: readonly [{
|
|
|
391
416
|
}, {
|
|
392
417
|
readonly engine: "sing-box";
|
|
393
418
|
readonly version: "1.12.0";
|
|
419
|
+
readonly autoGroup: "urltest";
|
|
394
420
|
readonly platforms: readonly ["linux", "macos"];
|
|
395
421
|
readonly protocols: readonly ["trojan", "http", "anytls", "shadowsocks", "vmess", "vless"];
|
|
396
422
|
readonly endpoints: readonly ["sing-box-tailscale"];
|
|
@@ -400,6 +426,7 @@ export declare const targetCatalog: readonly [{
|
|
|
400
426
|
}, {
|
|
401
427
|
readonly engine: "surge";
|
|
402
428
|
readonly version: "6.10.0";
|
|
429
|
+
readonly autoGroup: "surge-smart";
|
|
403
430
|
readonly platforms: readonly ["macos"];
|
|
404
431
|
readonly protocols: readonly ["trojan", "http", "anytls", "shadowsocks", "vmess"];
|
|
405
432
|
readonly endpoints: readonly [];
|
|
@@ -409,6 +436,7 @@ export declare const targetCatalog: readonly [{
|
|
|
409
436
|
}, {
|
|
410
437
|
readonly engine: "mihomo";
|
|
411
438
|
readonly version: "1.19.32";
|
|
439
|
+
readonly autoGroup: "urltest";
|
|
412
440
|
readonly platforms: readonly ["linux", "macos"];
|
|
413
441
|
readonly protocols: readonly ["trojan", "http", "anytls", "shadowsocks", "vmess", "vless"];
|
|
414
442
|
readonly endpoints: readonly [];
|
|
@@ -418,6 +446,7 @@ export declare const targetCatalog: readonly [{
|
|
|
418
446
|
}, {
|
|
419
447
|
readonly engine: "stash";
|
|
420
448
|
readonly version: "4.2.1";
|
|
449
|
+
readonly autoGroup: null;
|
|
421
450
|
readonly platforms: readonly ["macos"];
|
|
422
451
|
readonly protocols: readonly ["trojan", "http", "anytls", "shadowsocks", "vmess"];
|
|
423
452
|
readonly endpoints: readonly [];
|
|
@@ -486,6 +515,8 @@ type BuildResult = {
|
|
|
486
515
|
readonly code: string;
|
|
487
516
|
readonly active?: string;
|
|
488
517
|
readonly generation?: string;
|
|
518
|
+
readonly reason?: "ACCESS_DENIED" | "NO_SPACE" | "READ_ONLY" | "INVALID_DIRECTORY" | "IO_ERROR";
|
|
519
|
+
readonly hint?: string;
|
|
489
520
|
};
|
|
490
521
|
/** All targets publish together by one active.json rename. Config files never go to stdout. */
|
|
491
522
|
export declare function buildToDirectory(compilation: Compilation, output: string, resolveSecret?: (token: Secret) => string | undefined): Promise<BuildResult>;
|
|
@@ -756,4 +787,14 @@ export declare function compileSurgeProfile(input: unknown): SurgeProfileCompila
|
|
|
756
787
|
export declare function renderSurgeProfile(compilation: SurgeProfileCompilation, resolveSecret: (token: Secret) => string | undefined): SurgeProfileArtifact;
|
|
757
788
|
export declare function renderSurgeProfiles(compilations: readonly SurgeProfileCompilation[], resolveSecret: (token: Secret) => string | undefined): readonly SurgeProfileArtifact[];
|
|
758
789
|
//#endregion
|
|
790
|
+
//#region src/surge-compose.d.ts
|
|
791
|
+
/** Bind shared names only for included resources; explicit input mappings remain compiler-checked. */
|
|
792
|
+
export declare function surgeProfile(input: SurgeProfileInput, names?: Readonly<Record<string, string>>): SurgeProfileInput;
|
|
793
|
+
/** Stable queries produce native-profile policy references without consumer mapping code. */
|
|
794
|
+
export declare function surgeMembers(nodes: readonly ProxyNode[], query?: Parameters<typeof selectNodes>[1]): SurgePolicy[];
|
|
795
|
+
//#endregion
|
|
796
|
+
//#region src/surge-host.d.ts
|
|
797
|
+
/** Complete-profile batches use the out symlink protocol; the Program host remains unchanged. */
|
|
798
|
+
export declare function buildSurgeProfilesToDirectory(profiles: Readonly<Record<string, SurgeProfileInput>>, output: string, resolveSecret?: (token: Secret) => string | undefined): Promise<BuildResult>;
|
|
799
|
+
//#endregion
|
|
759
800
|
export type { Artifact, BuildResult, CaseResult, Compilation, ProxyBuilder, ProxyNodeArtifact, ProxyNodeCompilation, ProxyNodeInput, StrategyGroupCompilation, StrategyGroupInput, SurgeCondition, SurgeGeneral, SurgeGroup, SurgeHost, SurgePolicy, SurgeProfileArtifact, SurgeProfileCompilation, SurgeProfileInput, SurgeRule, SurgeTunnel, TargetPlan };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
import { A as slot, C as route, D as selectNodes, E as secret, F as deepFreeze, I as idSchema, L as nodeSchema, M as surge, N as use, O as sequence, P as assertData, S as reject, T as ruleSet, _ as group, a as explain, b as policy, c as nativeNameSchema, d as surgeProxy, f as validateProxyOptions, g as direct, h as defineConfig, i as compile, j as strategy, k as singbox, l as targetCatalog, m as block, n as render, o as compileStrategyGroups, p as StaticRuleSetUnknownError, r as secretReader, s as isReservedNativeName, t as buildToDirectory, u as RenderError, v as match, w as rule, x as proxy, y as mihomo } from "./host-
|
|
1
|
+
import { A as slot, C as route, D as selectNodes, E as secret, F as deepFreeze, I as idSchema, L as nodeSchema, M as surge, N as use, O as sequence, P as assertData, S as reject, T as ruleSet, _ as group, a as explain, b as policy, c as nativeNameSchema, d as surgeProxy, f as validateProxyOptions, g as direct, h as defineConfig, i as compile, j as strategy, k as singbox, l as targetCatalog, m as block, n as render, o as compileStrategyGroups, p as StaticRuleSetUnknownError, r as secretReader, s as isReservedNativeName, t as buildToDirectory, u as RenderError, v as match, w as rule, x as proxy, y as mihomo } from "./host-BPBSZ-jw.js";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { isIP } from "node:net";
|
|
4
4
|
import ipaddr from "ipaddr.js";
|
|
5
|
+
import { lstat, mkdir, readlink, rename, rm, symlink, writeFile } from "node:fs/promises";
|
|
6
|
+
import { join, resolve } from "node:path";
|
|
7
|
+
import { randomUUID } from "node:crypto";
|
|
5
8
|
//#region src/proxy-fragments.ts
|
|
6
9
|
const inputSchema$1 = z.strictObject({
|
|
7
10
|
target: z.strictObject({
|
|
@@ -581,4 +584,164 @@ function renderSurgeProfiles(compilations, resolveSecret) {
|
|
|
581
584
|
return deepFreeze(compilations.map((c) => renderProfile(c, read)));
|
|
582
585
|
}
|
|
583
586
|
//#endregion
|
|
584
|
-
|
|
587
|
+
//#region src/surge-compose.ts
|
|
588
|
+
/** Bind shared names only for included resources; explicit input mappings remain compiler-checked. */
|
|
589
|
+
function surgeProfile(input, names = {}) {
|
|
590
|
+
const bindings = {};
|
|
591
|
+
for (const node of input.nodes) bindings[node.id] = names[node.id] ?? node.label ?? node.id;
|
|
592
|
+
for (const resource of [...input.tunnels ?? [], ...input.groups]) bindings[resource.id] = names[resource.id] ?? resource.id;
|
|
593
|
+
return {
|
|
594
|
+
...input,
|
|
595
|
+
names: {
|
|
596
|
+
...bindings,
|
|
597
|
+
...input.names
|
|
598
|
+
}
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
/** Stable queries produce native-profile policy references without consumer mapping code. */
|
|
602
|
+
function surgeMembers(nodes, query = {}) {
|
|
603
|
+
return selectNodes(nodes, query).map((ref) => ({ ref }));
|
|
604
|
+
}
|
|
605
|
+
//#endregion
|
|
606
|
+
//#region src/surge-publish.ts
|
|
607
|
+
var SurgePublishError = class extends Error {
|
|
608
|
+
published;
|
|
609
|
+
constructor(message, published) {
|
|
610
|
+
super(message);
|
|
611
|
+
this.published = published;
|
|
612
|
+
}
|
|
613
|
+
};
|
|
614
|
+
async function publishProfiles(files, surgeDirectory, io = { rename }) {
|
|
615
|
+
if (!files.size || files.size > 16 || [...files.keys()].some((name) => !/^[a-z0-9][a-z0-9-]*\.conf$/.test(name))) throw new Error("INVALID_PROFILE_FILENAMES");
|
|
616
|
+
const root = resolve(surgeDirectory);
|
|
617
|
+
const generations = join(root, ".generations");
|
|
618
|
+
const id = randomUUID();
|
|
619
|
+
const generation = join(generations, id);
|
|
620
|
+
const pointer = join(root, `.out-${id}`);
|
|
621
|
+
const output = join(root, "out");
|
|
622
|
+
const backup = join(generations, `legacy-${id}`);
|
|
623
|
+
const lock = join(root, ".build-lock");
|
|
624
|
+
const remove = io.rm ?? rm;
|
|
625
|
+
let failure;
|
|
626
|
+
let locked = false, created = false, committed = false, movedLegacy = false, recoveryFailed = false;
|
|
627
|
+
async function directory(path) {
|
|
628
|
+
await mkdir(path, {
|
|
629
|
+
recursive: true,
|
|
630
|
+
mode: 448
|
|
631
|
+
});
|
|
632
|
+
const stat = await lstat(path);
|
|
633
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
|
|
634
|
+
}
|
|
635
|
+
try {
|
|
636
|
+
await directory(root);
|
|
637
|
+
try {
|
|
638
|
+
await mkdir(lock, { mode: 448 });
|
|
639
|
+
locked = true;
|
|
640
|
+
} catch (error) {
|
|
641
|
+
if (error.code === "EEXIST") throw new Error("OUTPUT_LOCKED");
|
|
642
|
+
throw error;
|
|
643
|
+
}
|
|
644
|
+
await directory(generations);
|
|
645
|
+
let previous;
|
|
646
|
+
try {
|
|
647
|
+
previous = await lstat(output);
|
|
648
|
+
} catch (error) {
|
|
649
|
+
if (error.code !== "ENOENT") throw error;
|
|
650
|
+
}
|
|
651
|
+
if (previous?.isSymbolicLink()) {
|
|
652
|
+
const target = await readlink(output);
|
|
653
|
+
if (!/^\.generations\/(?:legacy-)?[a-f0-9-]{36}$/.test(target)) throw new Error("UNMANAGED_OUTPUT_LINK");
|
|
654
|
+
const stat = await lstat(join(root, target));
|
|
655
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
|
|
656
|
+
} else if (previous && !previous.isDirectory()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
|
|
657
|
+
await mkdir(generation, { mode: 448 });
|
|
658
|
+
created = true;
|
|
659
|
+
for (const [name, content] of files) await writeFile(join(generation, name), content, {
|
|
660
|
+
mode: 384,
|
|
661
|
+
flag: "wx"
|
|
662
|
+
});
|
|
663
|
+
await symlink(`.generations/${id}`, pointer, "dir");
|
|
664
|
+
if (previous?.isDirectory()) {
|
|
665
|
+
await io.rename(output, backup);
|
|
666
|
+
movedLegacy = true;
|
|
667
|
+
}
|
|
668
|
+
try {
|
|
669
|
+
await io.rename(pointer, output);
|
|
670
|
+
committed = true;
|
|
671
|
+
} catch (error) {
|
|
672
|
+
if (movedLegacy) try {
|
|
673
|
+
await io.rename(backup, output);
|
|
674
|
+
movedLegacy = false;
|
|
675
|
+
} catch {
|
|
676
|
+
recoveryFailed = true;
|
|
677
|
+
throw new Error("PUBLISH_RECOVERY_REQUIRED");
|
|
678
|
+
}
|
|
679
|
+
throw error;
|
|
680
|
+
}
|
|
681
|
+
} catch (error) {
|
|
682
|
+
const code = error instanceof Error && /^(?:INVALID_PROFILE_FILENAMES|OUTPUT_LOCKED|UNMANAGED_OUTPUT_LINK|UNSAFE_OUTPUT_DIRECTORY|PUBLISH_RECOVERY_REQUIRED)$/.test(error.message) ? error.message : "PROFILE_PUBLISH_FAILED";
|
|
683
|
+
failure = new Error(code);
|
|
684
|
+
} finally {
|
|
685
|
+
if (!recoveryFailed) try {
|
|
686
|
+
await remove(pointer, { force: true });
|
|
687
|
+
if (created && !committed) await remove(generation, {
|
|
688
|
+
recursive: true,
|
|
689
|
+
force: true
|
|
690
|
+
});
|
|
691
|
+
if (locked) await remove(lock, {
|
|
692
|
+
recursive: true,
|
|
693
|
+
force: true
|
|
694
|
+
});
|
|
695
|
+
} catch {
|
|
696
|
+
failure ??= /* @__PURE__ */ new Error("PROFILE_PUBLISH_CLEANUP_FAILED");
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
if (failure) throw new SurgePublishError(failure.message === "PROFILE_PUBLISH_CLEANUP_FAILED" ? committed ? "PUBLISHED_CLEANUP_FAILED" : "FAILED_CLEANUP_REQUIRED" : failure.message, committed);
|
|
700
|
+
}
|
|
701
|
+
//#endregion
|
|
702
|
+
//#region src/surge-host.ts
|
|
703
|
+
/** Complete-profile batches use the out symlink protocol; the Program host remains unchanged. */
|
|
704
|
+
async function buildSurgeProfilesToDirectory(profiles, output, resolveSecret = (token) => process.env[token.name]) {
|
|
705
|
+
if (typeof output !== "string" || !output.trim()) return {
|
|
706
|
+
published: false,
|
|
707
|
+
exitCode: 1,
|
|
708
|
+
code: "INVALID_OUTPUT_DIRECTORY"
|
|
709
|
+
};
|
|
710
|
+
try {
|
|
711
|
+
const entries = Object.entries(profiles);
|
|
712
|
+
if (!entries.length || entries.length > 16 || entries.some(([id]) => !/^[a-z0-9][a-z0-9-]*$/.test(id))) return {
|
|
713
|
+
published: false,
|
|
714
|
+
exitCode: 1,
|
|
715
|
+
code: "INVALID_PROFILE_FILENAMES"
|
|
716
|
+
};
|
|
717
|
+
const compiled = entries.map(([, input]) => compileSurgeProfile(input));
|
|
718
|
+
if (compiled.some((profile) => !profile.ok)) return {
|
|
719
|
+
published: false,
|
|
720
|
+
exitCode: 1,
|
|
721
|
+
code: "COMPILATION_FAILED"
|
|
722
|
+
};
|
|
723
|
+
const artifacts = renderSurgeProfiles(compiled, resolveSecret);
|
|
724
|
+
await publishProfiles(new Map(entries.map(([id], i) => [`${id}.conf`, artifacts[i].content])), output);
|
|
725
|
+
return {
|
|
726
|
+
published: true,
|
|
727
|
+
exitCode: 0,
|
|
728
|
+
code: "PUBLISHED",
|
|
729
|
+
active: join(resolve(output), "out")
|
|
730
|
+
};
|
|
731
|
+
} catch (error) {
|
|
732
|
+
if (error instanceof SurgePublishError) return {
|
|
733
|
+
published: error.published,
|
|
734
|
+
exitCode: error.published ? 2 : 1,
|
|
735
|
+
code: error.message,
|
|
736
|
+
...error.published ? { active: join(resolve(output), "out") } : {},
|
|
737
|
+
...error.message === "PUBLISH_RECOVERY_REQUIRED" ? { hint: "out may be absent; preserve the lock, backup, generation and temporary pointer for manual recovery" } : {}
|
|
738
|
+
};
|
|
739
|
+
return {
|
|
740
|
+
published: false,
|
|
741
|
+
exitCode: 1,
|
|
742
|
+
code: error instanceof RenderError ? error.code : "BUILD_FAILED"
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
//#endregion
|
|
747
|
+
export { RenderError, StaticRuleSetUnknownError, block, buildSurgeProfilesToDirectory, buildToDirectory, compile, compileProxyNodes, compileStrategyGroups, compileSurgeProfile, defineConfig, direct, explain, group, match, mihomo, policy, proxy, reject, render, renderProxyNodes, renderSurgeProfile, renderSurgeProfiles, route, rule, ruleSet, secret, selectNodes, sequence, singbox, slot, strategy, surge, surgeMembers, surgeProfile, targetCatalog, use };
|
package/package.json
CHANGED