proxylang 0.1.1 → 0.1.3

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.
@@ -1,266 +1,10 @@
1
- import ipaddr from "ipaddr.js";
2
1
  import { z } from "zod";
3
2
  import { isIP } from "node:net";
3
+ import ipaddr from "ipaddr.js";
4
4
  import { stringify } from "yaml";
5
5
  import { lstat, mkdir, rename, rm, writeFile } from "node:fs/promises";
6
6
  import { join, resolve } from "node:path";
7
7
  import { randomUUID } from "node:crypto";
8
- //#region src/dsl.ts
9
- const ruleSet = (definition) => ({
10
- ...definition,
11
- type: "ruleSet"
12
- });
13
- const match = {
14
- ruleSet: (set) => set,
15
- domain: (value) => ({
16
- type: "domain",
17
- value
18
- }),
19
- domainSuffix: (value) => ({
20
- type: "domainSuffix",
21
- value
22
- }),
23
- ipCidr: (value) => ({
24
- type: "ipCidr",
25
- value
26
- }),
27
- sourceIp: (value) => ({
28
- type: "sourceIp",
29
- value
30
- }),
31
- port: (from, to = from) => ({
32
- type: "port",
33
- from,
34
- to
35
- }),
36
- sourcePort: (from, to = from) => ({
37
- type: "sourcePort",
38
- from,
39
- to
40
- }),
41
- network: (value) => ({
42
- type: "network",
43
- value
44
- }),
45
- all: (...conditions) => ({
46
- type: "all",
47
- conditions
48
- }),
49
- any: (...conditions) => ({
50
- type: "any",
51
- conditions
52
- }),
53
- not: (condition) => ({
54
- type: "not",
55
- condition
56
- })
57
- };
58
- const direct = () => ({ type: "direct" });
59
- const reject = () => ({ type: "reject" });
60
- const route = (to) => ({
61
- type: "route",
62
- to
63
- });
64
- const slot = (name) => ({
65
- type: "slot",
66
- name
67
- });
68
- const secret = (name) => ({
69
- type: "env",
70
- name
71
- });
72
- const rule = (id, when, then) => ({
73
- type: "rule",
74
- id,
75
- when,
76
- then
77
- });
78
- const block = (id, rules, when) => ({
79
- type: "block",
80
- id,
81
- rules,
82
- ...when ? { when } : {}
83
- });
84
- const policy$1 = (definition) => ({
85
- type: "policy",
86
- ...definition
87
- });
88
- const use = (definition, options) => ({
89
- type: "use",
90
- id: options.id,
91
- policy: definition,
92
- bindings: options.bindings
93
- });
94
- const sequence = (...parts) => parts.flatMap((part) => Array.isArray(part) ? part : [part]);
95
- const defineConfig = (config) => config;
96
- /** Filtering is stable: catalogue order determines initial selector order. */
97
- function selectNodes(nodes, query = {}) {
98
- 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);
99
- }
100
- /** A shared strategy explicitly chooses an algorithm for each engine. */
101
- const strategy = (definition) => ({
102
- type: "strategy",
103
- ...definition
104
- });
105
- const group = {
106
- select: () => ({ type: "select" }),
107
- urltest: (options) => ({
108
- type: "urltest",
109
- ...options
110
- })
111
- };
112
- const surge$1 = {
113
- smart: () => ({ type: "surge-smart" }),
114
- ruleSet: (options) => ({
115
- format: "rule-set",
116
- ...options,
117
- type: "nativeRuleSet",
118
- engine: "surge"
119
- })
120
- };
121
- const mihomo = { ruleProvider: (options) => ({
122
- ...options,
123
- type: "nativeRuleSet",
124
- engine: "mihomo"
125
- }) };
126
- /** Protocol constructors keep credentials and options specific to their protocol. */
127
- function nodeConstructor(type) {
128
- return (options) => ({
129
- ...options,
130
- type
131
- });
132
- }
133
- const proxy = {
134
- http: nodeConstructor("http"),
135
- trojan: nodeConstructor("trojan"),
136
- anytls: nodeConstructor("anytls"),
137
- shadowsocks: nodeConstructor("shadowsocks"),
138
- vmess: nodeConstructor("vmess"),
139
- vless: nodeConstructor("vless")
140
- };
141
- const singbox$1 = {
142
- ruleSet: (options) => ({
143
- ...options,
144
- type: "nativeRuleSet",
145
- engine: "sing-box"
146
- }),
147
- tailscale: (options) => ({
148
- ...options,
149
- type: "sing-box-tailscale"
150
- })
151
- };
152
- //#endregion
153
- //#region src/rulesets.ts
154
- function canonical(value) {
155
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
156
- if (value && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
157
- return JSON.stringify(value);
158
- }
159
- function validateRuleSets(entries, engine, diagnostics, path) {
160
- const definitions = /* @__PURE__ */ new Map();
161
- const urls = /* @__PURE__ */ new Map();
162
- const error = (code) => diagnostics.push({
163
- severity: "error",
164
- code,
165
- path,
166
- message: "原生规则集引擎不匹配或相同 ID/URL 的定义冲突"
167
- });
168
- const visit = (m) => {
169
- if (m.type === "ruleSet" || m.type === "nativeRuleSet") {
170
- const key = canonical(m);
171
- if (definitions.has(m.id) && definitions.get(m.id) !== key) error("RULESET_ID_CONFLICT");
172
- definitions.set(m.id, key);
173
- if (m.type === "ruleSet") visit(m.when);
174
- else {
175
- if (m.engine !== engine) error("NATIVE_TARGET_MISMATCH");
176
- if (m.engine === "surge") {
177
- const settings = canonical([m.format, m.intervalSeconds ?? 86400]);
178
- const url = new URL(m.url).href;
179
- if (urls.has(url) && urls.get(url) !== settings) error("RULESET_URL_CONFLICT");
180
- urls.set(url, settings);
181
- }
182
- }
183
- } else if (m.type === "all" || m.type === "any") m.conditions.forEach(visit);
184
- else if (m.type === "not") visit(m.condition);
185
- };
186
- const walk = (items) => {
187
- for (const item of items) if (item.type === "rule") visit(item.when);
188
- else if (item.type === "block") {
189
- if (item.when) visit(item.when);
190
- walk(item.rules);
191
- } else walk(item.policy.rules);
192
- };
193
- walk(entries);
194
- }
195
- function lowerRuleSets(rules, diagnostics, path) {
196
- let count = 0;
197
- let origins = 0;
198
- const lower = (m, origin, depth) => {
199
- if (++count > 1e5 || depth > 64) throw new Error("EXPANSION_LIMIT");
200
- if (m.type === "ruleSet") {
201
- origin.push(`rule-set:${m.id}`);
202
- return lower(m.when, origin, depth + 1);
203
- }
204
- if (m.type === "all" || m.type === "any") return {
205
- ...m,
206
- conditions: m.conditions.map((c) => lower(c, origin, depth + 1))
207
- };
208
- if (m.type === "not") return {
209
- ...m,
210
- condition: lower(m.condition, origin, depth + 1)
211
- };
212
- return m;
213
- };
214
- try {
215
- if (rules.length > 1e4) throw new Error("EXPANSION_LIMIT");
216
- return rules.map((r) => {
217
- const origin = [...r.origin];
218
- const when = lower(r.when, origin, 0);
219
- origins += origin.length;
220
- if (origins > 1e5) throw new Error("EXPANSION_LIMIT");
221
- return {
222
- ...r,
223
- when,
224
- origin
225
- };
226
- });
227
- } catch {
228
- diagnostics.push({
229
- severity: "error",
230
- code: "EXPANSION_LIMIT",
231
- path,
232
- message: "展开规则、条件或来源超过预算"
233
- });
234
- return [];
235
- }
236
- }
237
- function collectNativeRuleSets(rules, target, diagnostics) {
238
- const found = /* @__PURE__ */ new Map();
239
- const visit = (m, nested) => {
240
- if (m.type === "nativeRuleSet") {
241
- found.set(m.id, m);
242
- if (nested && m.engine === "surge" && m.intervalSeconds !== void 0) diagnostics.push({
243
- severity: "error",
244
- code: "RULESET_COMPOSITION_UNSUPPORTED",
245
- target: target.id,
246
- path: `targets.${target.id}.ruleSets.${m.id}`,
247
- message: "Surge 嵌套外部规则只支持客户端默认更新间隔"
248
- });
249
- } else if (m.type === "all" || m.type === "any") m.conditions.forEach((c) => visit(c, true));
250
- else if (m.type === "not") visit(m.condition, true);
251
- else if (m.type === "ruleSet") visit(m.when, nested);
252
- };
253
- rules.forEach((r) => visit(r.when, false));
254
- for (const r of found.values()) diagnostics.push({
255
- severity: "warning",
256
- code: "EXTERNAL_RULESET_UNVERIFIED",
257
- target: target.id,
258
- path: `targets.${target.id}.ruleSets.${r.id}`,
259
- message: "外部规则由客户端更新和解释;编译器未获取内容或验证运行时匹配"
260
- });
261
- return [...found.values()];
262
- }
263
- //#endregion
264
8
  //#region src/schema.ts
265
9
  const idSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/).refine((x) => !x.startsWith("pl-"));
266
10
  const domain = z.string().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/);
@@ -294,7 +38,7 @@ const remoteBase = {
294
38
  })
295
39
  };
296
40
  const updateInterval = z.number().int().min(60).max(2147483647);
297
- const nativeRuleSetSchema = z.union([
41
+ const nativeRuleSetSchema = z.discriminatedUnion("engine", [
298
42
  z.strictObject({
299
43
  ...remoteBase,
300
44
  engine: z.literal("surge"),
@@ -319,7 +63,7 @@ const nativeRuleSetSchema = z.union([
319
63
  intervalSeconds: updateInterval
320
64
  })
321
65
  ]);
322
- const matchSchema = z.lazy(() => z.union([
66
+ const matchSchema = z.lazy(() => z.discriminatedUnion("type", [
323
67
  nativeRuleSetSchema,
324
68
  z.strictObject({
325
69
  type: z.literal("ruleSet"),
@@ -353,7 +97,7 @@ const matchSchema = z.lazy(() => z.union([
353
97
  condition: matchSchema
354
98
  })
355
99
  ]));
356
- const actionSchema = z.union([z.strictObject({ type: z.enum(["direct", "reject"]) }), z.strictObject({
100
+ const actionSchema = z.discriminatedUnion("type", [z.strictObject({ type: z.enum(["direct", "reject"]) }), z.strictObject({
357
101
  type: z.literal("route"),
358
102
  to: idSchema
359
103
  })]);
@@ -361,7 +105,7 @@ const slotSchema = z.strictObject({
361
105
  type: z.literal("slot"),
362
106
  name: idSchema
363
107
  });
364
- const ruleAction = z.union([actionSchema, slotSchema]);
108
+ const ruleAction = z.discriminatedUnion("type", [actionSchema, slotSchema]);
365
109
  const unique = (items) => new Set(items).size === items.length;
366
110
  const policySchema = z.lazy(() => z.strictObject({
367
111
  type: z.literal("policy"),
@@ -369,7 +113,7 @@ const policySchema = z.lazy(() => z.strictObject({
369
113
  exits: z.array(idSchema).refine(unique),
370
114
  rules: z.array(entrySchema).min(1)
371
115
  }));
372
- const entrySchema = z.lazy(() => z.union([
116
+ const entrySchema = z.lazy(() => z.discriminatedUnion("type", [
373
117
  z.strictObject({
374
118
  type: z.literal("rule"),
375
119
  id: idSchema,
@@ -395,9 +139,10 @@ const secretSchema = z.strictObject({
395
139
  });
396
140
  const nodeBase = {
397
141
  id: idSchema,
398
- server: ip,
142
+ server: z.union([ip, domain]),
399
143
  port,
400
144
  via: idSchema.optional(),
145
+ tcpFastOpen: z.boolean().optional(),
401
146
  label: z.string().min(1).max(256).optional(),
402
147
  region: z.string().regex(/^[A-Z]{2}$/).optional(),
403
148
  provider: idSchema.optional(),
@@ -405,6 +150,7 @@ const nodeBase = {
405
150
  };
406
151
  const tlsSchema = z.strictObject({
407
152
  serverName: domain,
153
+ skipCertVerify: z.boolean().optional(),
408
154
  alpn: z.array(z.string().min(1).refine((x) => !/\p{C}/u.test(x) && Buffer.byteLength(x) <= 255)).min(1).refine(unique).optional()
409
155
  });
410
156
  const transportSchema = z.strictObject({
@@ -418,18 +164,33 @@ const uuidNode = {
418
164
  tls: tlsSchema.optional(),
419
165
  transport: transportSchema.optional()
420
166
  };
167
+ const surgeOptions = { blockQuic: z.enum([
168
+ "auto",
169
+ "on",
170
+ "off"
171
+ ]).optional() };
421
172
  const nodeSchema = z.discriminatedUnion("type", [
422
173
  z.strictObject({
423
174
  ...nodeBase,
424
175
  type: z.literal("trojan"),
425
176
  password: secretSchema,
426
- serverName: domain.optional()
177
+ serverName: domain.optional(),
178
+ skipCertVerify: z.boolean().optional(),
179
+ surge: z.strictObject({
180
+ ...surgeOptions,
181
+ udpRelay: z.literal(true).optional()
182
+ }).optional()
427
183
  }),
428
184
  z.strictObject({
429
185
  ...nodeBase,
430
186
  type: z.literal("anytls"),
431
187
  password: secretSchema,
432
- serverName: domain.optional()
188
+ serverName: domain.optional(),
189
+ skipCertVerify: z.boolean().optional(),
190
+ surge: z.strictObject({
191
+ ...surgeOptions,
192
+ udpRelay: z.literal(true).optional()
193
+ }).optional()
433
194
  }),
434
195
  z.strictObject({
435
196
  ...nodeBase,
@@ -441,6 +202,10 @@ const nodeSchema = z.discriminatedUnion("type", [
441
202
  z.strictObject({
442
203
  ...nodeBase,
443
204
  type: z.literal("shadowsocks"),
205
+ surge: z.strictObject({
206
+ ...surgeOptions,
207
+ udpRelay: z.boolean().optional()
208
+ }).optional(),
444
209
  method: z.enum([
445
210
  "aes-128-gcm",
446
211
  "aes-256-gcm",
@@ -450,7 +215,8 @@ const nodeSchema = z.discriminatedUnion("type", [
450
215
  }),
451
216
  z.strictObject({
452
217
  ...uuidNode,
453
- type: z.literal("vmess")
218
+ type: z.literal("vmess"),
219
+ surge: z.strictObject(surgeOptions).optional()
454
220
  }),
455
221
  z.strictObject({
456
222
  ...uuidNode,
@@ -501,93 +267,381 @@ const groupSchema = z.union([
501
267
  id: idSchema,
502
268
  members
503
269
  }),
504
- z.strictObject({
505
- type: z.literal("urltest"),
506
- id: idSchema,
507
- members,
508
- url,
509
- intervalSeconds: z.number().int().min(1).max(86400).default(180),
510
- toleranceMs: z.number().int().min(0).max(6e4).default(50)
270
+ z.strictObject({
271
+ type: z.literal("urltest"),
272
+ id: idSchema,
273
+ members,
274
+ url,
275
+ intervalSeconds: z.number().int().min(1).max(86400).default(180),
276
+ toleranceMs: z.number().int().min(0).max(6e4).default(50)
277
+ })
278
+ ]);
279
+ const requestSchema = z.strictObject({
280
+ network,
281
+ domain: domain.optional(),
282
+ ip: ip.optional(),
283
+ sourceIp: ip.optional(),
284
+ port: port.optional(),
285
+ sourcePort: port.optional()
286
+ });
287
+ const configSchema = z.strictObject({
288
+ programs: z.record(idSchema, z.strictObject({
289
+ engine: z.enum([
290
+ "surge",
291
+ "sing-box",
292
+ "mihomo",
293
+ "stash"
294
+ ]),
295
+ nodes: z.array(nodeSchema),
296
+ endpoints: z.array(endpointSchema).max(1e3).optional(),
297
+ groups: z.array(groupSchema),
298
+ routing: z.array(entrySchema),
299
+ fallback: actionSchema,
300
+ listener: z.strictObject({
301
+ port,
302
+ resolver: ip
303
+ }).optional()
304
+ })),
305
+ targets: z.array(z.strictObject({
306
+ id: idSchema,
307
+ program: idSchema,
308
+ engine: z.enum([
309
+ "surge",
310
+ "sing-box",
311
+ "mihomo",
312
+ "stash"
313
+ ]),
314
+ platform: z.enum(["macos", "linux"]),
315
+ version: z.string().regex(/^\d+\.\d+\.\d+$/),
316
+ mode: z.enum(["fragment", "standalone"]).default("fragment")
317
+ })).min(1),
318
+ cases: z.array(z.strictObject({
319
+ id: idSchema,
320
+ program: idSchema,
321
+ request: requestSchema,
322
+ expect: z.strictObject({
323
+ rule: z.string().min(1).optional(),
324
+ action: actionSchema
325
+ })
326
+ })).optional(),
327
+ warningsAsErrors: z.boolean().optional()
328
+ });
329
+ /** Only schema-owned constraints are rendered; Zod messages can contain input values. */
330
+ function schemaIssueMessage(issue) {
331
+ switch (issue.code) {
332
+ case "invalid_type": return `字段类型错误或缺失;需要 ${issue.expected}`;
333
+ case "too_small": return `字段低于下限;${issue.origin} 的最小值或长度为 ${issue.minimum}`;
334
+ case "too_big": return `字段超过上限;${issue.origin} 的最大值或长度为 ${issue.maximum}`;
335
+ case "invalid_value": return `字段必须使用声明的枚举值:${issue.values.map(String).join("、")}`;
336
+ case "invalid_format": return "字段格式不符合约束;检查域名、标识符或路径格式";
337
+ case "unrecognized_keys": return "对象包含当前声明不支持的字段;请删除额外字段";
338
+ case "invalid_union": return "声明不符合任何支持的分支;检查 type、engine 及对应必填字段";
339
+ default: return "字段不满足语义约束;检查地址、范围顺序、重复项或相关字段组合";
340
+ }
341
+ }
342
+ /** Reject cycles, executable values and excessive expansion before recursive schema parsing. */
343
+ function assertData(value) {
344
+ const ancestors = /* @__PURE__ */ new Set();
345
+ let count = 0;
346
+ const visit = (v, depth) => {
347
+ if (++count > 1e5 || depth > 64) throw new Error("INPUT_LIMIT");
348
+ if (v === void 0 || v === null || [
349
+ "string",
350
+ "number",
351
+ "boolean"
352
+ ].includes(typeof v)) return;
353
+ if (typeof v !== "object" || ancestors.has(v)) throw new Error("INPUT_GRAPH");
354
+ if (!Array.isArray(v) && Object.getPrototypeOf(v) !== Object.prototype && Object.getPrototypeOf(v) !== null) throw new Error("INPUT_OBJECT");
355
+ ancestors.add(v);
356
+ for (const descriptor of Object.values(Object.getOwnPropertyDescriptors(v))) {
357
+ if (descriptor.get || descriptor.set) throw new Error("INPUT_ACCESSOR");
358
+ visit(descriptor.value, depth + 1);
359
+ }
360
+ ancestors.delete(v);
361
+ };
362
+ visit(value, 0);
363
+ }
364
+ function deepFreeze(value) {
365
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
366
+ Object.freeze(value);
367
+ for (const item of Object.values(value)) deepFreeze(item);
368
+ }
369
+ return value;
370
+ }
371
+ //#endregion
372
+ //#region src/proxy-builder.ts
373
+ /** Fluent construction is separate from the plain-data node consumed by the compiler. */
374
+ function proxyBuilder(node) {
375
+ assertData(node);
376
+ const copy = deepFreeze(structuredClone(node));
377
+ const fork = (patch) => proxyBuilder({
378
+ ...copy,
379
+ ...patch
380
+ });
381
+ return Object.freeze({
382
+ via: (id) => fork({ via: id }),
383
+ label: (text) => fork({ label: text }),
384
+ tcpFastOpen: (enabled) => fork({ tcpFastOpen: enabled }),
385
+ build: () => deepFreeze(structuredClone(copy))
386
+ });
387
+ }
388
+ //#endregion
389
+ //#region src/dsl.ts
390
+ const ruleSet = (definition) => ({
391
+ ...definition,
392
+ type: "ruleSet"
393
+ });
394
+ const match = {
395
+ ruleSet: (set) => set,
396
+ domain: (value) => ({
397
+ type: "domain",
398
+ value
399
+ }),
400
+ domainSuffix: (value) => ({
401
+ type: "domainSuffix",
402
+ value
403
+ }),
404
+ ipCidr: (value) => ({
405
+ type: "ipCidr",
406
+ value
407
+ }),
408
+ sourceIp: (value) => ({
409
+ type: "sourceIp",
410
+ value
411
+ }),
412
+ port: (from, to = from) => ({
413
+ type: "port",
414
+ from,
415
+ to
416
+ }),
417
+ sourcePort: (from, to = from) => ({
418
+ type: "sourcePort",
419
+ from,
420
+ to
421
+ }),
422
+ network: (value) => ({
423
+ type: "network",
424
+ value
425
+ }),
426
+ all: (...conditions) => ({
427
+ type: "all",
428
+ conditions
429
+ }),
430
+ any: (...conditions) => ({
431
+ type: "any",
432
+ conditions
433
+ }),
434
+ not: (condition) => ({
435
+ type: "not",
436
+ condition
437
+ })
438
+ };
439
+ const direct = () => ({ type: "direct" });
440
+ const reject = () => ({ type: "reject" });
441
+ const route = (to) => ({
442
+ type: "route",
443
+ to
444
+ });
445
+ /** An exit parameter declared by policy.exits and resolved by use.bindings. */
446
+ const slot = (name) => ({
447
+ type: "slot",
448
+ name
449
+ });
450
+ const secret = (name) => ({
451
+ type: "env",
452
+ name
453
+ });
454
+ const rule = (id, when, then) => ({
455
+ type: "rule",
456
+ id,
457
+ when,
458
+ then
459
+ });
460
+ const block = (id, rules, when) => ({
461
+ type: "block",
462
+ id,
463
+ rules,
464
+ ...when ? { when } : {}
465
+ });
466
+ const policy$1 = (definition) => ({
467
+ type: "policy",
468
+ ...definition
469
+ });
470
+ const use = (definition, options) => ({
471
+ type: "use",
472
+ id: options.id,
473
+ policy: definition,
474
+ bindings: options.bindings
475
+ });
476
+ const sequence = (...parts) => parts.flatMap((part) => Array.isArray(part) ? part : [part]);
477
+ const defineConfig = (config) => config;
478
+ /** Filtering is stable: catalogue order determines initial selector order. */
479
+ function selectNodes(nodes, query = {}) {
480
+ 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
+ }
482
+ /** A shared strategy explicitly chooses an algorithm for each engine. */
483
+ const strategy = (definition) => ({
484
+ type: "strategy",
485
+ ...definition
486
+ });
487
+ const group = {
488
+ select: () => ({ type: "select" }),
489
+ urltest: (options) => ({
490
+ type: "urltest",
491
+ ...options
492
+ })
493
+ };
494
+ const surge$1 = {
495
+ smart: () => ({ type: "surge-smart" }),
496
+ ruleSet: (options) => ({
497
+ format: "rule-set",
498
+ ...options,
499
+ type: "nativeRuleSet",
500
+ engine: "surge"
501
+ })
502
+ };
503
+ const mihomo = { ruleProvider: (options) => ({
504
+ ...options,
505
+ type: "nativeRuleSet",
506
+ engine: "mihomo"
507
+ }) };
508
+ /** Protocol constructors keep credentials and options specific to their protocol. */
509
+ function nodeConstructor(type) {
510
+ return (options) => ({
511
+ ...options,
512
+ type
513
+ });
514
+ }
515
+ const proxy = {
516
+ builder: proxyBuilder,
517
+ http: nodeConstructor("http"),
518
+ trojan: nodeConstructor("trojan"),
519
+ anytls: nodeConstructor("anytls"),
520
+ shadowsocks: nodeConstructor("shadowsocks"),
521
+ vmess: nodeConstructor("vmess"),
522
+ vless: nodeConstructor("vless")
523
+ };
524
+ const singbox$1 = {
525
+ ruleSet: (options) => ({
526
+ ...options,
527
+ type: "nativeRuleSet",
528
+ engine: "sing-box"
529
+ }),
530
+ tailscale: (options) => ({
531
+ ...options,
532
+ type: "sing-box-tailscale"
511
533
  })
512
- ]);
513
- const requestSchema = z.strictObject({
514
- network,
515
- domain: domain.optional(),
516
- ip: ip.optional(),
517
- sourceIp: ip.optional(),
518
- port: port.optional(),
519
- sourcePort: port.optional()
520
- });
521
- const configSchema = z.strictObject({
522
- programs: z.record(idSchema, z.strictObject({
523
- engine: z.enum([
524
- "surge",
525
- "sing-box",
526
- "mihomo",
527
- "stash"
528
- ]),
529
- nodes: z.array(nodeSchema),
530
- endpoints: z.array(endpointSchema).max(1e3).optional(),
531
- groups: z.array(groupSchema),
532
- routing: z.array(entrySchema),
533
- fallback: actionSchema,
534
- listener: z.strictObject({
535
- port,
536
- resolver: ip
537
- }).optional()
538
- })),
539
- targets: z.array(z.strictObject({
540
- id: idSchema,
541
- program: idSchema,
542
- engine: z.enum([
543
- "surge",
544
- "sing-box",
545
- "mihomo",
546
- "stash"
547
- ]),
548
- platform: z.enum(["macos", "linux"]),
549
- version: z.string().regex(/^\d+\.\d+\.\d+$/),
550
- mode: z.enum(["fragment", "standalone"]).default("fragment")
551
- })).min(1),
552
- cases: z.array(z.strictObject({
553
- id: idSchema,
554
- program: idSchema,
555
- request: requestSchema,
556
- expect: z.strictObject({
557
- rule: z.string().min(1).optional(),
558
- action: actionSchema
559
- })
560
- })).optional(),
561
- warningsAsErrors: z.boolean().optional()
562
- });
563
- /** Reject cycles, executable values and excessive expansion before recursive schema parsing. */
564
- function assertData(value) {
565
- const ancestors = /* @__PURE__ */ new Set();
534
+ };
535
+ //#endregion
536
+ //#region src/rulesets.ts
537
+ function canonical(value) {
538
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
539
+ if (value && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
540
+ return JSON.stringify(value);
541
+ }
542
+ function validateRuleSets(entries, engine, diagnostics, path) {
543
+ const definitions = /* @__PURE__ */ new Map();
544
+ const urls = /* @__PURE__ */ new Map();
545
+ const error = (code) => diagnostics.push({
546
+ severity: "error",
547
+ code,
548
+ path,
549
+ message: "原生规则集引擎不匹配或相同 ID/URL 的定义冲突"
550
+ });
551
+ const visit = (m) => {
552
+ if (m.type === "ruleSet" || m.type === "nativeRuleSet") {
553
+ const key = canonical(m);
554
+ if (definitions.has(m.id) && definitions.get(m.id) !== key) error("RULESET_ID_CONFLICT");
555
+ definitions.set(m.id, key);
556
+ if (m.type === "ruleSet") visit(m.when);
557
+ else {
558
+ if (m.engine !== engine) error("NATIVE_TARGET_MISMATCH");
559
+ if (m.engine === "surge") {
560
+ const settings = canonical([m.format, m.intervalSeconds ?? 86400]);
561
+ const url = new URL(m.url).href;
562
+ if (urls.has(url) && urls.get(url) !== settings) error("RULESET_URL_CONFLICT");
563
+ urls.set(url, settings);
564
+ }
565
+ }
566
+ } else if (m.type === "all" || m.type === "any") m.conditions.forEach(visit);
567
+ else if (m.type === "not") visit(m.condition);
568
+ };
569
+ const walk = (items) => {
570
+ for (const item of items) if (item.type === "rule") visit(item.when);
571
+ else if (item.type === "block") {
572
+ if (item.when) visit(item.when);
573
+ walk(item.rules);
574
+ } else walk(item.policy.rules);
575
+ };
576
+ walk(entries);
577
+ }
578
+ function lowerRuleSets(rules, diagnostics, path) {
566
579
  let count = 0;
567
- const visit = (v, depth) => {
568
- if (++count > 1e5 || depth > 64) throw new Error("INPUT_LIMIT");
569
- if (v === void 0 || v === null || [
570
- "string",
571
- "number",
572
- "boolean"
573
- ].includes(typeof v)) return;
574
- if (typeof v !== "object" || ancestors.has(v)) throw new Error("INPUT_GRAPH");
575
- if (!Array.isArray(v) && Object.getPrototypeOf(v) !== Object.prototype && Object.getPrototypeOf(v) !== null) throw new Error("INPUT_OBJECT");
576
- ancestors.add(v);
577
- for (const descriptor of Object.values(Object.getOwnPropertyDescriptors(v))) {
578
- if (descriptor.get || descriptor.set) throw new Error("INPUT_ACCESSOR");
579
- visit(descriptor.value, depth + 1);
580
+ let origins = 0;
581
+ const lower = (m, origin, depth) => {
582
+ if (++count > 1e5 || depth > 64) throw new Error("EXPANSION_LIMIT");
583
+ if (m.type === "ruleSet") {
584
+ origin.push(`rule-set:${m.id}`);
585
+ return lower(m.when, origin, depth + 1);
580
586
  }
581
- ancestors.delete(v);
587
+ if (m.type === "all" || m.type === "any") return {
588
+ ...m,
589
+ conditions: m.conditions.map((c) => lower(c, origin, depth + 1))
590
+ };
591
+ if (m.type === "not") return {
592
+ ...m,
593
+ condition: lower(m.condition, origin, depth + 1)
594
+ };
595
+ return m;
582
596
  };
583
- visit(value, 0);
584
- }
585
- function deepFreeze(value) {
586
- if (value && typeof value === "object" && !Object.isFrozen(value)) {
587
- Object.freeze(value);
588
- for (const item of Object.values(value)) deepFreeze(item);
597
+ try {
598
+ if (rules.length > 1e4) throw new Error("EXPANSION_LIMIT");
599
+ return rules.map((r) => {
600
+ const origin = [...r.origin];
601
+ const when = lower(r.when, origin, 0);
602
+ origins += origin.length;
603
+ if (origins > 1e5) throw new Error("EXPANSION_LIMIT");
604
+ return {
605
+ ...r,
606
+ when,
607
+ origin
608
+ };
609
+ });
610
+ } catch {
611
+ diagnostics.push({
612
+ severity: "error",
613
+ code: "EXPANSION_LIMIT",
614
+ path,
615
+ message: "展开规则、条件或来源超过预算"
616
+ });
617
+ return [];
589
618
  }
590
- return value;
619
+ }
620
+ function collectNativeRuleSets(rules, target, diagnostics) {
621
+ const found = /* @__PURE__ */ new Map();
622
+ const visit = (m, nested) => {
623
+ if (m.type === "nativeRuleSet") {
624
+ found.set(m.id, m);
625
+ if (nested && m.engine === "surge" && m.intervalSeconds !== void 0) diagnostics.push({
626
+ severity: "error",
627
+ code: "RULESET_COMPOSITION_UNSUPPORTED",
628
+ target: target.id,
629
+ path: `targets.${target.id}.ruleSets.${m.id}`,
630
+ message: "Surge 嵌套外部规则只支持客户端默认更新间隔"
631
+ });
632
+ } else if (m.type === "all" || m.type === "any") m.conditions.forEach((c) => visit(c, true));
633
+ else if (m.type === "not") visit(m.condition, true);
634
+ else if (m.type === "ruleSet") visit(m.when, nested);
635
+ };
636
+ rules.forEach((r) => visit(r.when, false));
637
+ for (const r of found.values()) diagnostics.push({
638
+ severity: "warning",
639
+ code: "EXTERNAL_RULESET_UNVERIFIED",
640
+ target: target.id,
641
+ path: `targets.${target.id}.ruleSets.${r.id}`,
642
+ message: "外部规则由客户端更新和解释;编译器未获取内容或验证运行时匹配"
643
+ });
644
+ return [...found.values()];
591
645
  }
592
646
  //#endregion
593
647
  //#region src/rules.ts
@@ -797,12 +851,21 @@ var RenderError = class extends Error {
797
851
  function pathsOverlap(a, b) {
798
852
  return a === b || a.startsWith(b.endsWith("/") ? b : `${b}/`) || b.startsWith(a.endsWith("/") ? a : `${a}/`);
799
853
  }
800
- function nodeIsTcpOnly(node) {
801
- return node.type === "http" || node.type === "anytls" || node.type === "vmess" || node.type === "vless";
854
+ function nodeIsTcpOnly(node, engine) {
855
+ return node.type === "http" || node.type === "anytls" && engine !== "surge" || node.type === "vmess" || node.type === "vless" || engine === "surge" && node.type === "shadowsocks" && node.surge?.udpRelay === false;
802
856
  }
803
857
  function validateProxyOptions(node, target, diagnostics) {
804
- if (target.engine !== "surge") return;
805
858
  const tls = "tls" in node ? node.tls : void 0;
859
+ if (target.engine !== "surge") {
860
+ if (node.tcpFastOpen !== void 0 || "skipCertVerify" in node && node.skipCertVerify !== void 0 || tls?.skipCertVerify !== void 0 || "surge" in node && node.surge !== void 0) diagnostics.push({
861
+ severity: "error",
862
+ code: "PROXY_OPTION_UNSUPPORTED",
863
+ target: target.id,
864
+ path: `targets.${target.id}.nodes.${node.id}`,
865
+ message: "显式节点选项尚未实现此精确目标的编码"
866
+ });
867
+ return;
868
+ }
806
869
  if (("serverName" in node ? node.serverName : tls?.serverName) === "off" || tls?.alpn !== void 0) diagnostics.push({
807
870
  severity: "error",
808
871
  code: "PROXY_OPTION_UNSUPPORTED",
@@ -910,13 +973,13 @@ function clashProxy(node, engine, secret) {
910
973
  }
911
974
  return result;
912
975
  }
913
- function surgeProxy(node, secret) {
976
+ function surgeProxy(node, secret, name = (id) => id) {
914
977
  const atom = (value) => {
915
978
  if (!/^[A-Za-z0-9_./:@+%-]+$/.test(value)) throw new RenderError("SURGE_VALUE_UNREPRESENTABLE");
916
979
  return value;
917
980
  };
918
981
  const params = [
919
- `${node.id} = ${node.type === "shadowsocks" ? "ss" : node.type}`,
982
+ `${name(node.id)} = ${node.type === "shadowsocks" ? "ss" : node.type}`,
920
983
  node.server,
921
984
  String(node.port)
922
985
  ];
@@ -929,14 +992,15 @@ function surgeProxy(node, secret) {
929
992
  case "anytls":
930
993
  params.push(`password=${atom(secret(node.password))}`);
931
994
  if (node.serverName) params.push(`sni=${node.serverName}`);
932
- if (node.type === "trojan") params.push("udp-relay=true");
995
+ if (node.skipCertVerify !== void 0) params.push(`skip-cert-verify=${node.skipCertVerify}`);
933
996
  break;
934
997
  case "shadowsocks":
935
- params.push(`encrypt-method=${node.method}`, `password=${atom(secret(node.password))}`, "udp-relay=true", "block-quic=off");
998
+ params.push(`encrypt-method=${node.method}`, `password=${atom(secret(node.password))}`);
936
999
  break;
937
1000
  case "vmess":
938
1001
  params.push(`username=${uuid(node.uuid, secret)}`, "vmess-aead=true", "encrypt-method=aes-128-gcm", `tls=${!!node.tls}`);
939
1002
  if (node.tls) params.push(`sni=${node.tls.serverName}`);
1003
+ if (node.tls?.skipCertVerify !== void 0) params.push(`skip-cert-verify=${node.tls.skipCertVerify}`);
940
1004
  if (node.transport) {
941
1005
  params.push("ws=true", `ws-path=${node.transport.path}`);
942
1006
  if (node.transport.host) params.push(`ws-headers=Host:${node.transport.host}`);
@@ -944,7 +1008,11 @@ function surgeProxy(node, secret) {
944
1008
  break;
945
1009
  case "vless": throw new RenderError("PROTOCOL_UNSUPPORTED");
946
1010
  }
947
- if (node.via) params.push(`underlying-proxy=${node.via}`);
1011
+ if (node.tcpFastOpen !== void 0) params.push(`tfo=${node.tcpFastOpen}`);
1012
+ if (node.type === "trojan" || node.type === "anytls" && node.surge?.udpRelay) params.push("udp-relay=true");
1013
+ if (node.type === "shadowsocks") params.push(`udp-relay=${node.surge?.udpRelay ?? true}`, `block-quic=${node.surge?.blockQuic ?? "off"}`);
1014
+ if (node.type !== "shadowsocks" && "surge" in node && node.surge?.blockQuic !== void 0) params.push(`block-quic=${node.surge.blockQuic}`);
1015
+ if (node.via) params.push(`underlying-proxy=${name(node.via)}`);
948
1016
  return params.join(", ");
949
1017
  }
950
1018
  //#endregion
@@ -1129,6 +1197,27 @@ const targetCatalog = deepFreeze([
1129
1197
  }
1130
1198
  ]);
1131
1199
  //#endregion
1200
+ //#region src/native-names.ts
1201
+ const nativeNameSchema = z.string().min(1).max(256).refine((value) => value.trim() === value && !/[\p{C}\p{Zl}\p{Zp},=[\]()#;]/u.test(value) && !["DIRECT", "REJECT"].includes(value.toUpperCase()) && !value.toLowerCase().startsWith("pl-"));
1202
+ function isReservedNativeName(name, engine) {
1203
+ return (engine === "surge" ? [
1204
+ "REJECT-DROP",
1205
+ "REJECT-NO-DROP",
1206
+ "REJECT-TINYGIF"
1207
+ ] : engine === "mihomo" ? [
1208
+ "GLOBAL",
1209
+ "PASS",
1210
+ "COMPATIBLE",
1211
+ "REJECT-DROP",
1212
+ "PASS-RULE"
1213
+ ] : engine === "stash" ? [
1214
+ "GLOBAL",
1215
+ "PASS",
1216
+ "COMPATIBLE",
1217
+ "REJECT-DROP"
1218
+ ] : []).includes(name.toUpperCase());
1219
+ }
1220
+ //#endregion
1132
1221
  //#region src/strategies.ts
1133
1222
  function lowerStrategies(groups, engine, diagnostics, path) {
1134
1223
  const selected = [];
@@ -1197,7 +1286,6 @@ function singboxGroup(group, name = (id) => id) {
1197
1286
  interrupt_exist_connections: false
1198
1287
  };
1199
1288
  }
1200
- const nameSchema = z.string().min(1).max(256).refine((value) => value.trim() === value && !/[\p{C}\p{Zl}\p{Zp},=[\]()#;]/u.test(value) && !["DIRECT", "REJECT"].includes(value.toUpperCase()) && !value.toLowerCase().startsWith("pl-"));
1201
1289
  const inputSchema = z.strictObject({
1202
1290
  target: z.strictObject({
1203
1291
  engine: z.enum([
@@ -1211,10 +1299,10 @@ const inputSchema = z.strictObject({
1211
1299
  }),
1212
1300
  nodes: z.array(z.strictObject({
1213
1301
  id: idSchema,
1214
- nativeName: nameSchema
1302
+ nativeName: nativeNameSchema
1215
1303
  })).max(1e3),
1216
1304
  strategies: z.array(strategySchema).max(1e3),
1217
- names: z.record(idSchema, nameSchema).optional()
1305
+ names: z.record(idSchema, nativeNameSchema).optional()
1218
1306
  });
1219
1307
  /** Only group topology/encoding is checked here; nodes, via, protocols and routes remain consumer-owned. */
1220
1308
  function compileStrategyGroups(input) {
@@ -1252,21 +1340,9 @@ function compileStrategyGroups(input) {
1252
1340
  const ids = [...nodes.map((n) => n.id), ...strategies.map((s) => s.id)];
1253
1341
  if (new Set(ids).size !== ids.length || ids.length > 1e3) error("DUPLICATE_RESOURCE", "$", "资源 ID 必须唯一且总数不超过 1000");
1254
1342
  if (Object.keys(names).some((id) => !strategies.some((s) => s.id === id))) error("UNKNOWN_NAME_MAPPING", "names", "只能映射已声明策略 ID");
1255
- const nativeNames = new Map([...nodes.map((n) => [n.id, n.nativeName]), ...strategies.map((s) => [s.id, names[s.id] ?? s.id])]);
1256
- if ([...nativeNames.values()].some((name) => !nameSchema.safeParse(name).success)) error("INVALID_NATIVE_NAME", "names", "最终名称不符合原生名称约束");
1257
- const reserved = target.engine === "mihomo" ? [
1258
- "GLOBAL",
1259
- "PASS",
1260
- "COMPATIBLE",
1261
- "REJECT-DROP",
1262
- "PASS-RULE"
1263
- ] : target.engine === "stash" ? [
1264
- "GLOBAL",
1265
- "PASS",
1266
- "COMPATIBLE",
1267
- "REJECT-DROP"
1268
- ] : [];
1269
- if ([...nativeNames.values()].some((value) => reserved.includes(value.toUpperCase()))) error("INVALID_NATIVE_NAME", "names", "最终名称与目标内建策略冲突");
1343
+ const nativeNames = new Map([...nodes.map((n) => [n.id, n.nativeName]), ...strategies.map((s) => [s.id, Object.hasOwn(names, s.id) ? names[s.id] : s.id])]);
1344
+ if ([...nativeNames.values()].some((name) => !nativeNameSchema.safeParse(name).success)) error("INVALID_NATIVE_NAME", "names", "最终名称不符合原生名称约束");
1345
+ if ([...nativeNames.values()].some((value) => isReservedNativeName(value, target.engine))) error("INVALID_NATIVE_NAME", "names", "最终名称与目标内建策略冲突");
1270
1346
  if (new Set(nativeNames.values()).size !== nativeNames.size) error("DUPLICATE_NATIVE_NAME", "names", "最终节点和策略名称必须唯一");
1271
1347
  const { groups, selections } = lowerStrategies(strategies, target.engine, diagnostics, "$");
1272
1348
  const all = new Set(ids);
@@ -1324,7 +1400,7 @@ function compile(input) {
1324
1400
  }
1325
1401
  const parsed = configSchema.safeParse(input);
1326
1402
  if (!parsed.success) {
1327
- for (const issue of parsed.error.issues.slice(0, 20)) error("INVALID_SCHEMA", issue.path.map(String).join(".") || "$", "字段、类型或值不符合语言契约;检查严格 schema(不回显输入值)");
1403
+ for (const issue of parsed.error.issues.slice(0, 20)) error("INVALID_SCHEMA", issue.path.map(String).join(".") || "$", schemaIssueMessage(issue));
1328
1404
  return deepFreeze({
1329
1405
  ok: false,
1330
1406
  diagnostics,
@@ -1337,6 +1413,7 @@ function compile(input) {
1337
1413
  if (Object.keys(config.programs).length === 0) error("EMPTY_PROGRAMS", "programs", "至少需要一个程序");
1338
1414
  for (const [name, program] of Object.entries(config.programs)) {
1339
1415
  const path = `programs.${name}`;
1416
+ for (const node of program.nodes) if (!isIP(node.server)) error("PROXY_HOSTNAME_MODE_UNSUPPORTED", `${path}.nodes.${node.id}`, "域名代理地址目前仅允许节点片段入口");
1340
1417
  validateRuleSets(program.routing, program.engine, diagnostics, path);
1341
1418
  const rules = lowerRuleSets(expandRules(program.routing, diagnostics, name), diagnostics, path);
1342
1419
  expanded.set(name, rules);
@@ -1362,7 +1439,7 @@ function compile(input) {
1362
1439
  if (states.get(id) === 2) return tcpOnly.get(id) ?? false;
1363
1440
  states.set(id, 1);
1364
1441
  const item = byId.get(id);
1365
- let limited = !!item && "server" in item && nodeIsTcpOnly(item);
1442
+ let limited = !!item && "server" in item && nodeIsTcpOnly(item, program.engine);
1366
1443
  for (const ref of edges.get(id) ?? []) limited = visit(ref) || limited;
1367
1444
  states.set(id, 2);
1368
1445
  tcpOnly.set(id, limited);
@@ -1519,15 +1596,11 @@ function explain(compilation, target, request) {
1519
1596
  return explainRules(plan.rules, plan.program.fallback, request);
1520
1597
  }
1521
1598
  //#endregion
1522
- //#region src/render.ts
1523
- const DIRECT = "pl-direct";
1524
- const DNS = "pl-dns";
1525
- const actionTag = (action) => action.type === "route" ? action.to : action.type === "direct" ? DIRECT : "pl-reject";
1526
- /** Secret resolution is once per token per batch, including across providers. */
1527
- function render(compilation, resolveSecret) {
1528
- if (!compilation.ok) throw new RenderError("COMPILATION_FAILED");
1599
+ //#region src/secrets.ts
1600
+ /** One reader per rendering batch; exceptions and missing values never disclose credentials. */
1601
+ function secretReader(resolveSecret) {
1529
1602
  const values = /* @__PURE__ */ new Map();
1530
- const secret = (token) => {
1603
+ return (token) => {
1531
1604
  if (values.has(token.name)) return values.get(token.name);
1532
1605
  let value;
1533
1606
  try {
@@ -1539,6 +1612,16 @@ function render(compilation, resolveSecret) {
1539
1612
  values.set(token.name, value);
1540
1613
  return value;
1541
1614
  };
1615
+ }
1616
+ //#endregion
1617
+ //#region src/render.ts
1618
+ const DIRECT = "pl-direct";
1619
+ const DNS = "pl-dns";
1620
+ const actionTag = (action) => action.type === "route" ? action.to : action.type === "direct" ? DIRECT : "pl-reject";
1621
+ /** Secret resolution is once per token per batch, including across providers. */
1622
+ function render(compilation, resolveSecret) {
1623
+ if (!compilation.ok) throw new RenderError("COMPILATION_FAILED");
1624
+ const secret = secretReader(resolveSecret);
1542
1625
  return compilation.plans.map((plan) => ({
1543
1626
  target: plan.target.id,
1544
1627
  filename: `${plan.target.id}.${plan.target.engine === "surge" ? "conf" : plan.target.engine === "sing-box" ? "json" : "yaml"}`,
@@ -1820,4 +1903,4 @@ async function buildToDirectory(compilation, output, resolveSecret = (token) =>
1820
1903
  };
1821
1904
  }
1822
1905
  //#endregion
1823
- export { selectNodes as C, strategy as D, slot as E, surge$1 as O, secret as S, singbox$1 as T, proxy as _, compileStrategyGroups as a, rule as b, StaticRuleSetUnknownError as c, defineConfig as d, direct as f, policy$1 as g, mihomo as h, explain as i, use as k, requestSchema as l, match as m, render as n, targetCatalog as o, group as p, compile as r, RenderError as s, buildToDirectory as t, block as u, reject as v, sequence as w, ruleSet as x, route as y };
1906
+ export { slot as A, route as C, selectNodes as D, secret as E, deepFreeze as F, idSchema as I, nodeSchema as L, surge$1 as M, use as N, sequence as O, assertData as P, requestSchema as R, reject as S, ruleSet as T, group as _, explain as a, policy$1 as b, nativeNameSchema as c, surgeProxy as d, validateProxyOptions as f, direct as g, defineConfig as h, compile as i, strategy as j, singbox$1 as k, targetCatalog as l, block as m, render as n, compileStrategyGroups as o, StaticRuleSetUnknownError as p, secretReader as r, isReservedNativeName as s, buildToDirectory as t, RenderError as u, match as v, rule as w, proxy as x, mihomo as y };