proxylang 0.1.5 → 0.1.7

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,346 +1,138 @@
1
- import { z } from "zod";
2
1
  import { isIP } from "node:net";
3
2
  import ipaddr from "ipaddr.js";
3
+ import { z } from "zod";
4
4
  import { stringify } from "yaml";
5
- import { lstat, mkdir, rename, rm, writeFile } from "node:fs/promises";
5
+ import { lstat, mkdir, readlink, rename, rm, symlink, writeFile } from "node:fs/promises";
6
6
  import { join, resolve } from "node:path";
7
7
  import { randomUUID } from "node:crypto";
8
- //#region src/surge-definitions.ts
9
- var ProfileDefinitionError = class extends Error {
10
- code;
11
- constructor(code) {
12
- super(code);
13
- this.code = code;
14
- this.name = "ProfileDefinitionError";
15
- }
16
- };
17
- const fail = (code) => {
18
- throw new ProfileDefinitionError(code);
19
- };
20
- /** Inspect descriptors before any caller spreads or reads input fields. Shared DAGs are legal. */
21
- function inspect(root) {
22
- let edges = 0;
23
- let objects = 0;
24
- const visiting = /* @__PURE__ */ new Set();
25
- const heights = /* @__PURE__ */ new Map();
26
- function visit(value, depth) {
27
- if (depth > 64) fail("DEFINITION_DEPTH_EXCEEDED");
28
- if (value === null || typeof value !== "object") {
29
- if (![
30
- "undefined",
31
- "string",
32
- "number",
33
- "boolean"
34
- ].includes(typeof value) && value !== null) fail("DEFINITION_NOT_DATA");
35
- return 0;
36
- }
37
- if (visiting.has(value)) fail("DEFINITION_CYCLE");
38
- const cached = heights.get(value);
39
- if (cached !== void 0) {
40
- if (depth + cached > 64) fail("DEFINITION_DEPTH_EXCEEDED");
41
- return cached;
42
- }
43
- if (++objects > 2e4) fail("DEFINITION_OBJECT_BUDGET_EXCEEDED");
44
- const proto = Object.getPrototypeOf(value);
45
- if (proto !== Object.prototype && proto !== null && !(Array.isArray(value) && proto === Array.prototype)) fail("DEFINITION_NOT_DATA");
46
- if (Array.isArray(value) && value.length > 1e5) fail("DEFINITION_EDGE_BUDGET_EXCEEDED");
47
- visiting.add(value);
48
- let height = 0;
49
- for (const key of Reflect.ownKeys(value)) {
50
- if (++edges > 1e5) fail("DEFINITION_EDGE_BUDGET_EXCEEDED");
51
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
52
- if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable && !(Array.isArray(value) && key === "length")) fail("DEFINITION_NOT_DATA");
53
- height = Math.max(height, 1 + visit(descriptor.value, depth + 1));
54
- }
55
- visiting.delete(value);
56
- heights.set(value, height);
57
- return height;
58
- }
59
- visit(root, 0);
8
+ //#region src/rulesets.ts
9
+ function canonical(value) {
10
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
11
+ 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(",")}}`;
12
+ return JSON.stringify(value);
60
13
  }
61
- /** Count output occurrences, not identities, before allocating each copied value. */
62
- function snapshot(input) {
63
- let remaining = 1e5;
64
- function copy(value, depth) {
65
- if (--remaining < 0) fail("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
66
- if (depth > 64) fail("DEFINITION_DEPTH_EXCEEDED");
67
- if (value === null || typeof value !== "object") return value;
68
- if (Array.isArray(value)) {
69
- const output = [];
70
- for (const item of value) output.push(copy(item, depth + 1));
71
- return output;
14
+ function validateRuleSets(entries, engine, diagnostics, path) {
15
+ const definitions = /* @__PURE__ */ new Map();
16
+ const urls = /* @__PURE__ */ new Map();
17
+ const error = (code) => diagnostics.push({
18
+ severity: "error",
19
+ code,
20
+ path,
21
+ message: "原生规则集引擎不匹配或相同 ID/URL 的定义冲突"
22
+ });
23
+ const visit = (m) => {
24
+ if (m.type === "ruleSet" || m.type === "nativeRuleSet") {
25
+ const key = canonical(m);
26
+ if (definitions.has(m.id) && definitions.get(m.id) !== key) error("RULESET_ID_CONFLICT");
27
+ definitions.set(m.id, key);
28
+ if (m.type === "ruleSet") visit(m.when);
29
+ else {
30
+ if (m.engine !== engine) error("NATIVE_TARGET_MISMATCH");
31
+ if (m.engine === "surge") {
32
+ const settings = canonical([m.format, m.intervalSeconds ?? 86400]);
33
+ const url = new URL(m.url).href;
34
+ if (urls.has(url) && urls.get(url) !== settings) error("RULESET_URL_CONFLICT");
35
+ urls.set(url, settings);
36
+ }
37
+ }
38
+ } else if (m.type === "all" || m.type === "any") m.conditions.forEach(visit);
39
+ else if (m.type === "not") visit(m.condition);
40
+ };
41
+ const walk = (items) => {
42
+ for (const item of items) if (item.type === "rule") visit(item.when);
43
+ else if (item.type === "block") {
44
+ if (item.when) visit(item.when);
45
+ walk(item.rules);
46
+ } else walk(item.policy.rules);
47
+ };
48
+ walk(entries);
49
+ }
50
+ function lowerRuleSets(rules, diagnostics, path) {
51
+ let count = 0;
52
+ let origins = 0;
53
+ const lower = (m, origin, depth) => {
54
+ if (++count > 1e5 || depth > 64) throw new Error("EXPANSION_LIMIT");
55
+ if (m.type === "ruleSet") {
56
+ origin.push(`rule-set:${m.id}`);
57
+ return lower(m.when, origin, depth + 1);
72
58
  }
73
- const output = {};
74
- for (const [key, item] of Object.entries(value)) Object.defineProperty(output, key, {
75
- value: copy(item, depth + 1),
76
- enumerable: true,
77
- writable: true,
78
- configurable: true
59
+ if (m.type === "all" || m.type === "any") return {
60
+ ...m,
61
+ conditions: m.conditions.map((c) => lower(c, origin, depth + 1))
62
+ };
63
+ if (m.type === "not") return {
64
+ ...m,
65
+ condition: lower(m.condition, origin, depth + 1)
66
+ };
67
+ return m;
68
+ };
69
+ try {
70
+ if (rules.length > 1e4) throw new Error("EXPANSION_LIMIT");
71
+ return rules.map((r) => {
72
+ const origin = [...r.origin];
73
+ const when = lower(r.when, origin, 0);
74
+ origins += origin.length;
75
+ if (origins > 1e5) throw new Error("EXPANSION_LIMIT");
76
+ return {
77
+ ...r,
78
+ when,
79
+ origin
80
+ };
79
81
  });
80
- return output;
82
+ } catch {
83
+ diagnostics.push({
84
+ severity: "error",
85
+ code: "EXPANSION_LIMIT",
86
+ path,
87
+ message: "展开规则、条件或来源超过预算"
88
+ });
89
+ return [];
81
90
  }
82
- return copy(input, 0);
83
- }
84
- function exact(value, keys) {
85
- if (!value || typeof value !== "object" || Array.isArray(value)) fail("DEFINITION_NOT_DATA");
86
- if (Object.keys(value).some((key) => !keys.includes(key))) fail("DEFINITION_UNKNOWN_FIELD");
87
- }
88
- const outbound = {
89
- direct: Object.freeze({ builtin: "DIRECT" }),
90
- reject: Object.freeze({ builtin: "REJECT" }),
91
- rejectDrop: Object.freeze({ builtin: "REJECT-DROP" }),
92
- rejectNoDrop: Object.freeze({ builtin: "REJECT-NO-DROP" }),
93
- rejectTinyGif: Object.freeze({ builtin: "REJECT-TINYGIF" })
94
- };
95
- function defineProxyGroup(input) {
96
- inspect(input);
97
- exact(input, [
98
- "id",
99
- "name",
100
- "algorithm",
101
- "members",
102
- "url",
103
- "intervalSeconds",
104
- "timeoutSeconds"
105
- ]);
106
- if (!input.algorithm || !["select", "surge-smart"].includes(input.algorithm.type)) fail("UNSUPPORTED_GROUP_ALGORITHM");
107
- exact(input.algorithm, ["type"]);
108
- if (!Array.isArray(input.members)) fail("INVALID_GROUP_DEFINITION");
109
- return {
110
- ...input,
111
- type: "proxy-group",
112
- algorithm: { ...input.algorithm },
113
- members: [...input.members]
114
- };
115
91
  }
116
- function defineRoute(input) {
117
- inspect(input);
118
- exact(input, [
119
- "id",
120
- "when",
121
- "to"
122
- ]);
123
- return {
124
- ...input,
125
- type: "route"
92
+ function collectNativeRuleSets(rules, target, diagnostics) {
93
+ const found = /* @__PURE__ */ new Map();
94
+ const visit = (m, nested) => {
95
+ if (m.type === "nativeRuleSet") {
96
+ found.set(m.id, m);
97
+ if (nested && m.engine === "surge" && m.intervalSeconds !== void 0) diagnostics.push({
98
+ severity: "error",
99
+ code: "RULESET_COMPOSITION_UNSUPPORTED",
100
+ target: target.id,
101
+ path: `targets.${target.id}.ruleSets.${m.id}`,
102
+ message: "Surge 嵌套外部规则只支持客户端默认更新间隔"
103
+ });
104
+ } else if (m.type === "all" || m.type === "any") m.conditions.forEach((c) => visit(c, true));
105
+ else if (m.type === "not") visit(m.condition, true);
106
+ else if (m.type === "ruleSet") visit(m.when, nested);
126
107
  };
127
- }
128
- function selectProxies(nodes, query = {}) {
129
- inspect({
130
- nodes,
131
- query
108
+ rules.forEach((r) => visit(r.when, false));
109
+ for (const r of found.values()) diagnostics.push({
110
+ severity: "warning",
111
+ code: "EXTERNAL_RULESET_UNVERIFIED",
112
+ target: target.id,
113
+ path: `targets.${target.id}.ruleSets.${r.id}`,
114
+ message: "外部规则由客户端更新和解释;编译器未获取内容或验证运行时匹配"
132
115
  });
133
- exact(query, [
134
- "ids",
135
- "regions",
136
- "providers",
137
- "tags"
138
- ]);
139
- if (!Array.isArray(nodes) || nodes.some((node) => !node || typeof node !== "object")) fail("DEFINITION_NOT_DATA");
140
- for (const values of Object.values(query)) if (values !== void 0 && !Array.isArray(values)) fail("DEFINITION_NOT_DATA");
141
- return nodes.filter((node) => (!query.ids || query.ids.includes(node.id)) && (!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))));
116
+ return [...found.values()];
142
117
  }
143
- function defineSurgeProfile(input) {
144
- inspect(input);
145
- exact(input, [
146
- "target",
147
- "managed",
148
- "general",
149
- "hosts",
150
- "nodes",
151
- "tunnels",
152
- "names",
153
- "groups",
154
- "routes",
155
- "fallback"
156
- ]);
157
- if (!Array.isArray(input.nodes) || !Array.isArray(input.groups) || !Array.isArray(input.routes) || input.tunnels !== void 0 && !Array.isArray(input.tunnels)) fail("DEFINITION_NOT_DATA");
158
- const registry = /* @__PURE__ */ new Map();
159
- const names = Object.assign(Object.create(null), input.names);
160
- for (const resource of [
161
- ...input.nodes,
162
- ...input.tunnels ?? [],
163
- ...input.groups
164
- ]) {
165
- if (!resource || typeof resource !== "object" || typeof resource.id !== "string") fail("INVALID_RESOURCE_DEFINITION");
166
- if (registry.has(resource.id)) fail("DUPLICATE_RESOURCE_ID");
167
- registry.set(resource.id, resource);
168
- const name = resource.type === "proxy-group" ? resource.name : "label" in resource ? resource.label ?? resource.id : resource.id;
169
- if (resource.type === "proxy-group" && names[resource.id] !== void 0 && names[resource.id] !== name) fail("GROUP_NAME_CONFLICT");
170
- Object.defineProperty(names, resource.id, {
171
- value: names[resource.id] ?? name,
172
- enumerable: true,
173
- configurable: true,
174
- writable: true
175
- });
176
- }
177
- function lower(destination) {
178
- if (!destination || typeof destination !== "object") fail("INVALID_DESTINATION");
179
- if ("builtin" in destination) {
180
- exact(destination, ["builtin"]);
181
- if (!Object.values(outbound).some((value) => value.builtin === destination.builtin)) fail("INVALID_DESTINATION");
182
- return { builtin: destination.builtin };
183
- }
184
- if (registry.get(destination.id) !== destination) fail("UNREGISTERED_DESTINATION_INSTANCE");
185
- return { ref: destination.id };
186
- }
187
- const groups = input.groups.map((definition) => {
188
- exact(definition, [
189
- "type",
190
- "id",
191
- "name",
192
- "algorithm",
193
- "members",
194
- "url",
195
- "intervalSeconds",
196
- "timeoutSeconds"
197
- ]);
198
- if (definition.type !== "proxy-group") fail("INVALID_GROUP_DEFINITION");
199
- if (!definition.algorithm || !["select", "surge-smart"].includes(definition.algorithm.type)) fail("UNSUPPORTED_GROUP_ALGORITHM");
200
- exact(definition.algorithm, ["type"]);
201
- if (!Array.isArray(definition.members)) fail("INVALID_GROUP_DEFINITION");
202
- const { id, url, intervalSeconds, timeoutSeconds } = definition;
203
- return {
204
- id,
205
- type: definition.algorithm.type === "select" ? "select" : "smart",
206
- members: definition.members.map(lower),
207
- ...url === void 0 ? {} : { url },
208
- ...intervalSeconds === void 0 ? {} : { intervalSeconds },
209
- ...timeoutSeconds === void 0 ? {} : { timeoutSeconds }
210
- };
211
- });
212
- const ids = /* @__PURE__ */ new Set();
213
- const rules = input.routes.map((definition) => {
214
- exact(definition, [
215
- "type",
216
- "id",
217
- "when",
218
- "to"
219
- ]);
220
- if (definition.type !== "route") fail("INVALID_ROUTE_DEFINITION");
221
- if (ids.has(definition.id)) fail("DUPLICATE_ROUTE_ID");
222
- ids.add(definition.id);
223
- return {
224
- when: definition.when,
225
- then: lower(definition.to)
226
- };
227
- });
228
- const { routes: _routes, groups: _groups, fallback, ...rest } = input;
229
- return snapshot({
230
- ...rest,
231
- names,
232
- groups,
233
- rules,
234
- fallback: lower(fallback)
235
- });
236
- }
237
- function condition(value) {
238
- inspect(value);
239
- return value;
240
- }
241
- function atom$1(type) {
242
- return (value, options = {}) => {
243
- inspect(options);
244
- return condition({
245
- ...options,
246
- type,
247
- value
248
- });
249
- };
250
- }
251
- const surgeMatch = {
252
- domain: atom$1("domain"),
253
- domainSuffix: atom$1("domainSuffix"),
254
- ipCidr: atom$1("ipCidr"),
255
- ipCidr6: atom$1("ipCidr6"),
256
- sourceIp: atom$1("sourceIp"),
257
- processName: atom$1("processName"),
258
- macAddress: atom$1("macAddress"),
259
- network: (value, options = {}) => {
260
- inspect(options);
261
- return condition({
262
- ...options,
263
- type: "network",
264
- value
265
- });
266
- },
267
- port: (from, to, options = {}) => {
268
- inspect(options);
269
- return condition({
270
- ...options,
271
- type: "port",
272
- from,
273
- ...to === void 0 ? {} : { to }
274
- });
275
- },
276
- sourcePort: (from, to, options = {}) => {
277
- inspect(options);
278
- return condition({
279
- ...options,
280
- type: "sourcePort",
281
- from,
282
- ...to === void 0 ? {} : { to }
283
- });
284
- },
285
- all: (conditions, options = {}) => {
286
- inspect({
287
- conditions,
288
- options
289
- });
290
- return condition({
291
- ...options,
292
- type: "all",
293
- conditions: [...conditions]
294
- });
295
- },
296
- any: (conditions, options = {}) => {
297
- inspect({
298
- conditions,
299
- options
300
- });
301
- return condition({
302
- ...options,
303
- type: "any",
304
- conditions: [...conditions]
305
- });
306
- },
307
- not: (value, options = {}) => {
308
- inspect({
309
- value,
310
- options
311
- });
312
- return condition({
313
- ...options,
314
- type: "not",
315
- condition: value
316
- });
317
- },
318
- ruleSet: (options) => {
319
- inspect(options);
320
- return condition({
321
- ...options,
322
- type: "ruleSet"
323
- });
324
- }
325
- };
326
- //#endregion
327
- //#region src/schema.ts
328
- const idSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/).refine((x) => !x.startsWith("pl-"));
329
- 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])?$/);
330
- const ip = z.string().refine((x) => isIP(x) !== 0 && !x.includes("%"));
331
- const cidr = z.string().refine((x) => {
332
- try {
333
- const [address, prefix] = x.split("/");
334
- if (!address || !prefix || !/^\d+$/.test(prefix) || isIP(address) === 0 || address.includes("%")) return false;
335
- ipaddr.parseCIDR(x);
336
- return true;
337
- } catch {
338
- return false;
118
+ //#endregion
119
+ //#region src/schema.ts
120
+ const idSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/).refine((x) => !x.startsWith("pl-"));
121
+ const domain$1 = 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])?$/);
122
+ const ip$1 = z.string().refine((x) => isIP(x) !== 0 && !x.includes("%"));
123
+ const cidr$1 = z.string().refine((x) => {
124
+ try {
125
+ const [address, prefix] = x.split("/");
126
+ if (!address || !prefix || !/^\d+$/.test(prefix) || isIP(address) === 0 || address.includes("%")) return false;
127
+ ipaddr.parseCIDR(x);
128
+ return true;
129
+ } catch {
130
+ return false;
339
131
  }
340
132
  });
341
- const port = z.number().int().min(1).max(65535);
133
+ const port$1 = z.number().int().min(1).max(65535);
342
134
  const network = z.enum(["tcp", "udp"]);
343
- const atom = (type, value) => z.strictObject({
135
+ const atom$2 = (type, value) => z.strictObject({
344
136
  type: z.literal(type),
345
137
  value
346
138
  });
@@ -389,19 +181,19 @@ const matchSchema = z.lazy(() => z.discriminatedUnion("type", [
389
181
  id: idSchema,
390
182
  when: matchSchema
391
183
  }),
392
- atom("domain", domain),
393
- atom("domainSuffix", domain),
394
- atom("ipCidr", cidr),
395
- atom("sourceIp", cidr),
184
+ atom$2("domain", domain$1),
185
+ atom$2("domainSuffix", domain$1),
186
+ atom$2("ipCidr", cidr$1),
187
+ atom$2("sourceIp", cidr$1),
396
188
  z.strictObject({
397
189
  type: z.literal("port"),
398
- from: port,
399
- to: port
190
+ from: port$1,
191
+ to: port$1
400
192
  }).refine((v) => v.from <= v.to),
401
193
  z.strictObject({
402
194
  type: z.literal("sourcePort"),
403
- from: port,
404
- to: port
195
+ from: port$1,
196
+ to: port$1
405
197
  }).refine((v) => v.from <= v.to),
406
198
  z.strictObject({
407
199
  type: z.literal("network"),
@@ -458,8 +250,8 @@ const secretSchema = z.strictObject({
458
250
  });
459
251
  const nodeBase = {
460
252
  id: idSchema,
461
- server: z.union([ip, domain]),
462
- port,
253
+ server: z.union([ip$1, domain$1]),
254
+ port: port$1,
463
255
  via: idSchema.optional(),
464
256
  tcpFastOpen: z.boolean().optional(),
465
257
  label: z.string().min(1).max(256).optional(),
@@ -468,14 +260,14 @@ const nodeBase = {
468
260
  tags: z.array(idSchema).refine(unique).optional()
469
261
  };
470
262
  const tlsSchema = z.strictObject({
471
- serverName: domain,
263
+ serverName: domain$1,
472
264
  skipCertVerify: z.boolean().optional(),
473
265
  alpn: z.array(z.string().min(1).refine((x) => !/\p{C}/u.test(x) && Buffer.byteLength(x) <= 255)).min(1).refine(unique).optional()
474
266
  });
475
267
  const transportSchema = z.strictObject({
476
268
  type: z.literal("ws"),
477
269
  path: z.string().max(2048).regex(/^\/[A-Za-z0-9/._~-]*$/).refine((x) => !x.startsWith("//")),
478
- host: domain.optional()
270
+ host: domain$1.optional()
479
271
  });
480
272
  const uuidNode = {
481
273
  ...nodeBase,
@@ -493,7 +285,7 @@ const nodeSchema = z.discriminatedUnion("type", [
493
285
  ...nodeBase,
494
286
  type: z.literal("trojan"),
495
287
  password: secretSchema,
496
- serverName: domain.optional(),
288
+ serverName: domain$1.optional(),
497
289
  skipCertVerify: z.boolean().optional(),
498
290
  surge: z.strictObject({
499
291
  ...surgeOptions,
@@ -504,7 +296,7 @@ const nodeSchema = z.discriminatedUnion("type", [
504
296
  ...nodeBase,
505
297
  type: z.literal("anytls"),
506
298
  password: secretSchema,
507
- serverName: domain.optional(),
299
+ serverName: domain$1.optional(),
508
300
  skipCertVerify: z.boolean().optional(),
509
301
  surge: z.strictObject({
510
302
  ...surgeOptions,
@@ -545,16 +337,16 @@ const nodeSchema = z.discriminatedUnion("type", [
545
337
  const endpointSchema = z.strictObject({
546
338
  type: z.literal("sing-box-tailscale"),
547
339
  id: idSchema,
548
- hostname: domain.refine((x) => !x.includes(".")),
340
+ hostname: domain$1.refine((x) => !x.includes(".")),
549
341
  stateDirectory: z.string().max(4096).refine((x) => x.startsWith("/") && !/[\p{C}$\\]/u.test(x) && x.split("/").slice(1).every((part) => part !== "" && part !== "." && part !== "..")),
550
342
  acceptRoutes: z.boolean(),
551
- bootstrapResolver: ip,
343
+ bootstrapResolver: ip$1,
552
344
  authKey: secretSchema.optional(),
553
- exitNode: ip.optional(),
345
+ exitNode: ip$1.optional(),
554
346
  exitNodeAllowLanAccess: z.boolean().optional()
555
347
  }).refine((endpoint) => endpoint.exitNodeAllowLanAccess === void 0 || endpoint.exitNode !== void 0);
556
348
  const members = z.array(idSchema).min(1).refine(unique);
557
- const url = z.string().url().refine((value) => {
349
+ const url$1 = z.string().url().refine((value) => {
558
350
  try {
559
351
  const u = new URL(value);
560
352
  return ["http:", "https:"].includes(u.protocol) && !u.username && !u.password && !u.hash;
@@ -564,7 +356,7 @@ const url = z.string().url().refine((value) => {
564
356
  });
565
357
  const urltestAlgorithmSchema = z.strictObject({
566
358
  type: z.literal("urltest"),
567
- url,
359
+ url: url$1,
568
360
  intervalSeconds: z.number().int().min(1).max(86400).default(180),
569
361
  toleranceMs: z.number().int().min(0).max(6e4).default(50)
570
362
  });
@@ -589,7 +381,7 @@ const strategySchema = z.union([z.strictObject({
589
381
  ...strategyBase,
590
382
  implementations: implementationsSchema.refine((v) => !!v.surge || !!v["sing-box"] || !!v.mihomo || !!v.stash)
591
383
  })]);
592
- const groupSchema = z.union([
384
+ const groupSchema$1 = z.union([
593
385
  strategySchema,
594
386
  z.strictObject({
595
387
  type: z.enum(["select", "smart"]),
@@ -600,18 +392,18 @@ const groupSchema = z.union([
600
392
  type: z.literal("urltest"),
601
393
  id: idSchema,
602
394
  members,
603
- url,
395
+ url: url$1,
604
396
  intervalSeconds: z.number().int().min(1).max(86400).default(180),
605
397
  toleranceMs: z.number().int().min(0).max(6e4).default(50)
606
398
  })
607
399
  ]);
608
400
  const requestSchema = z.strictObject({
609
401
  network,
610
- domain: domain.optional(),
611
- ip: ip.optional(),
612
- sourceIp: ip.optional(),
613
- port: port.optional(),
614
- sourcePort: port.optional()
402
+ domain: domain$1.optional(),
403
+ ip: ip$1.optional(),
404
+ sourceIp: ip$1.optional(),
405
+ port: port$1.optional(),
406
+ sourcePort: port$1.optional()
615
407
  });
616
408
  const configSchema = z.strictObject({
617
409
  programs: z.record(idSchema, z.strictObject({
@@ -623,12 +415,12 @@ const configSchema = z.strictObject({
623
415
  ]),
624
416
  nodes: z.array(nodeSchema),
625
417
  endpoints: z.array(endpointSchema).max(1e3).optional(),
626
- groups: z.array(groupSchema),
418
+ groups: z.array(groupSchema$1),
627
419
  routing: z.array(entrySchema),
628
420
  fallback: actionSchema,
629
421
  listener: z.strictObject({
630
- port,
631
- resolver: ip
422
+ port: port$1,
423
+ resolver: ip$1
632
424
  }).optional()
633
425
  })),
634
426
  targets: z.array(z.strictObject({
@@ -698,446 +490,169 @@ function deepFreeze(value) {
698
490
  return value;
699
491
  }
700
492
  //#endregion
701
- //#region src/proxy-builder.ts
702
- /** Fluent construction is separate from the plain-data node consumed by the compiler. */
703
- function proxyBuilder(node) {
704
- assertData(node);
705
- const copy = deepFreeze(structuredClone(node));
706
- const fork = (patch) => proxyBuilder({
707
- ...copy,
708
- ...patch
709
- });
710
- return Object.freeze({
711
- via: (id) => fork({ via: id }),
712
- label: (text) => fork({ label: text }),
713
- tcpFastOpen: (enabled) => fork({ tcpFastOpen: enabled }),
714
- build: () => deepFreeze(structuredClone(copy))
493
+ //#region src/rules.ts
494
+ function expandRules(entries, diagnostics, path = "routing") {
495
+ const output = [];
496
+ const seen = /* @__PURE__ */ new Set();
497
+ let limited = false;
498
+ const error = (code, where, message) => diagnostics.push({
499
+ severity: "error",
500
+ code,
501
+ path: where,
502
+ message
715
503
  });
504
+ function resolve(action, bindings, inPolicy, where) {
505
+ if (action.type === "slot") {
506
+ if (!Object.hasOwn(bindings, action.name)) {
507
+ error("UNBOUND_SLOT", where, "出口槽位未声明或未绑定");
508
+ return;
509
+ }
510
+ return bindings[action.name];
511
+ }
512
+ if (inPolicy && action.type === "route") {
513
+ error("POLICY_RESOURCE_CAPTURE", where, "共享 policy 必须通过 slot 引用出口");
514
+ return;
515
+ }
516
+ return action;
517
+ }
518
+ function walk(items, prefix, guards, bindings, inPolicy, origin) {
519
+ for (const entry of items) {
520
+ if (limited) return;
521
+ if (entry.type === "rule" && output.length >= 1e4) {
522
+ limited = true;
523
+ error("EXPANSION_LIMIT", path, "展开规则超过10000条");
524
+ return;
525
+ }
526
+ const id = `${prefix}/${entry.id}`;
527
+ if (seen.has(id)) {
528
+ error("DUPLICATE_RULE_ID", id, "同一实例路径出现重复 ID");
529
+ continue;
530
+ }
531
+ seen.add(id);
532
+ if (entry.type === "rule") {
533
+ const action = resolve(entry.then, bindings, inPolicy, id);
534
+ if (action) output.push({
535
+ id,
536
+ when: guards.length ? match.all(...guards, entry.when) : entry.when,
537
+ then: action,
538
+ origin: [...origin, entry.id]
539
+ });
540
+ } else if (entry.type === "block") walk(entry.rules, id, entry.when ? [...guards, entry.when] : guards, bindings, inPolicy, [...origin, entry.id]);
541
+ else {
542
+ const expected = new Set(entry.policy.exits);
543
+ if (Object.keys(entry.bindings).some((key) => !expected.has(key)) || entry.policy.exits.some((key) => !Object.hasOwn(entry.bindings, key))) {
544
+ error("POLICY_BINDINGS", id, "bindings 必须完整且只包含 policy 声明的出口");
545
+ continue;
546
+ }
547
+ const bound = Object.create(null);
548
+ for (const key of entry.policy.exits) {
549
+ const result = resolve(entry.bindings[key], bindings, inPolicy, `${id}/bindings/${key}`);
550
+ if (result) bound[key] = result;
551
+ }
552
+ walk(entry.policy.rules, id, guards, bound, true, [
553
+ ...origin,
554
+ `use:${entry.id}`,
555
+ `policy:${entry.policy.id}`
556
+ ]);
557
+ }
558
+ }
559
+ }
560
+ walk(entries, path, [], {}, false, []);
561
+ return limited ? [] : output;
716
562
  }
717
- //#endregion
718
- //#region src/dsl.ts
719
- const ruleSet = (definition) => ({
720
- ...definition,
721
- type: "ruleSet"
722
- });
723
- const match = {
724
- ruleSet: (set) => set,
725
- domain: (value) => ({
726
- type: "domain",
727
- value
728
- }),
729
- domainSuffix: (value) => ({
730
- type: "domainSuffix",
731
- value
732
- }),
733
- ipCidr: (value) => ({
734
- type: "ipCidr",
735
- value
736
- }),
737
- sourceIp: (value) => ({
738
- type: "sourceIp",
739
- value
740
- }),
741
- port: (from, to = from) => ({
742
- type: "port",
743
- from,
744
- to
745
- }),
746
- sourcePort: (from, to = from) => ({
747
- type: "sourcePort",
748
- from,
749
- to
750
- }),
751
- network: (value) => ({
752
- type: "network",
753
- value
754
- }),
755
- all: (...conditions) => ({
756
- type: "all",
757
- conditions
758
- }),
759
- any: (...conditions) => ({
760
- type: "any",
761
- conditions
762
- }),
763
- not: (condition) => ({
764
- type: "not",
765
- condition
766
- })
767
- };
768
- const direct = () => ({ type: "direct" });
769
- const reject = () => ({ type: "reject" });
770
- const route = (to) => ({
771
- type: "route",
772
- to
773
- });
774
- /** An exit parameter declared by policy.exits and resolved by use.bindings. */
775
- const slot = (name) => ({
776
- type: "slot",
777
- name
778
- });
779
- const secret = (name) => ({
780
- type: "env",
781
- name
782
- });
783
- const rule = (id, when, then) => ({
784
- type: "rule",
785
- id,
786
- when,
787
- then
788
- });
789
- const block = (id, rules, when) => ({
790
- type: "block",
791
- id,
792
- rules,
793
- ...when ? { when } : {}
794
- });
795
- const policy$1 = (definition) => ({
796
- type: "policy",
797
- ...definition
798
- });
799
- const use = (definition, options) => ({
800
- type: "use",
801
- id: options.id,
802
- policy: definition,
803
- bindings: options.bindings
804
- });
805
- const sequence = (...parts) => parts.flatMap((part) => Array.isArray(part) ? part : [part]);
806
- const defineConfig = (config) => config;
807
- /** Filtering is stable: catalogue order determines initial selector order. */
808
- function selectNodes(nodes, query = {}) {
809
- 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);
810
- }
811
- /** A shared strategy declares an algorithm or explicitly selects native implementations. */
812
- const strategy = (definition) => ({
813
- type: "strategy",
814
- ...definition
815
- });
816
- const group = {
817
- auto: () => ({ type: "auto" }),
818
- select: () => ({ type: "select" }),
819
- urltest: (options) => ({
820
- type: "urltest",
821
- ...options
822
- })
823
- };
824
- const surge$1 = {
825
- match: surgeMatch,
826
- smart: () => ({ type: "surge-smart" }),
827
- ruleSet: (options) => ({
828
- format: "rule-set",
829
- ...options,
830
- type: "nativeRuleSet",
831
- engine: "surge"
832
- })
833
- };
834
- const mihomo = { ruleProvider: (options) => ({
835
- ...options,
836
- type: "nativeRuleSet",
837
- engine: "mihomo"
838
- }) };
839
- /** Protocol constructors keep credentials and options specific to their protocol. */
840
- function nodeConstructor(type) {
841
- return (options) => ({
842
- ...options,
843
- type
844
- });
563
+ function inCidr(address, cidr) {
564
+ if (!address) return false;
565
+ const parsed = ipaddr.parse(address);
566
+ const [base, bits] = ipaddr.parseCIDR(cidr);
567
+ return parsed.kind() === base.kind() && parsed.match(base, bits);
845
568
  }
846
- const proxy = {
847
- builder: proxyBuilder,
848
- http: nodeConstructor("http"),
849
- trojan: nodeConstructor("trojan"),
850
- anytls: nodeConstructor("anytls"),
851
- shadowsocks: nodeConstructor("shadowsocks"),
852
- vmess: nodeConstructor("vmess"),
853
- vless: nodeConstructor("vless")
854
- };
855
- const singbox$1 = {
856
- ruleSet: (options) => ({
857
- ...options,
858
- type: "nativeRuleSet",
859
- engine: "sing-box"
860
- }),
861
- tailscale: (options) => ({
862
- ...options,
863
- type: "sing-box-tailscale"
864
- })
569
+ var StaticRuleSetUnknownError = class extends Error {
570
+ constructor() {
571
+ super("STATIC_RULESET_UNKNOWN");
572
+ this.name = "StaticRuleSetUnknownError";
573
+ }
865
574
  };
866
- //#endregion
867
- //#region src/rulesets.ts
868
- function canonical(value) {
869
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
870
- 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(",")}}`;
871
- return JSON.stringify(value);
872
- }
873
- function validateRuleSets(entries, engine, diagnostics, path) {
874
- const definitions = /* @__PURE__ */ new Map();
875
- const urls = /* @__PURE__ */ new Map();
876
- const error = (code) => diagnostics.push({
877
- severity: "error",
878
- code,
879
- path,
880
- message: "原生规则集引擎不匹配或相同 ID/URL 的定义冲突"
881
- });
882
- const visit = (m) => {
883
- if (m.type === "ruleSet" || m.type === "nativeRuleSet") {
884
- const key = canonical(m);
885
- if (definitions.has(m.id) && definitions.get(m.id) !== key) error("RULESET_ID_CONFLICT");
886
- definitions.set(m.id, key);
887
- if (m.type === "ruleSet") visit(m.when);
888
- else {
889
- if (m.engine !== engine) error("NATIVE_TARGET_MISMATCH");
890
- if (m.engine === "surge") {
891
- const settings = canonical([m.format, m.intervalSeconds ?? 86400]);
892
- const url = new URL(m.url).href;
893
- if (urls.has(url) && urls.get(url) !== settings) error("RULESET_URL_CONFLICT");
894
- urls.set(url, settings);
895
- }
896
- }
897
- } else if (m.type === "all" || m.type === "any") m.conditions.forEach(visit);
898
- else if (m.type === "not") visit(m.condition);
899
- };
900
- const walk = (items) => {
901
- for (const item of items) if (item.type === "rule") visit(item.when);
902
- else if (item.type === "block") {
903
- if (item.when) visit(item.when);
904
- walk(item.rules);
905
- } else walk(item.policy.rules);
575
+ function evaluate(condition, request) {
576
+ if (condition.type === "ruleSet") return evaluate(condition.when, request);
577
+ if (condition.type === "nativeRuleSet") return {
578
+ type: condition.type,
579
+ matched: null,
580
+ reason: "外部规则内容由客户端解释,静态未知"
906
581
  };
907
- walk(entries);
908
- }
909
- function lowerRuleSets(rules, diagnostics, path) {
910
- let count = 0;
911
- let origins = 0;
912
- const lower = (m, origin, depth) => {
913
- if (++count > 1e5 || depth > 64) throw new Error("EXPANSION_LIMIT");
914
- if (m.type === "ruleSet") {
915
- origin.push(`rule-set:${m.id}`);
916
- return lower(m.when, origin, depth + 1);
917
- }
918
- if (m.type === "all" || m.type === "any") return {
919
- ...m,
920
- conditions: m.conditions.map((c) => lower(c, origin, depth + 1))
582
+ if (condition.type === "all" || condition.type === "any") {
583
+ const children = condition.conditions.map((child) => evaluate(child, request));
584
+ const matched = condition.type === "all" ? children.some((child) => child.matched === false) ? false : children.some((child) => child.matched === null) ? null : true : children.some((child) => child.matched === true) ? true : children.some((child) => child.matched === null) ? null : false;
585
+ return {
586
+ type: condition.type,
587
+ matched,
588
+ reason: condition.type === "all" ? "所有子条件同时成立" : "至少一个子条件成立",
589
+ children
921
590
  };
922
- if (m.type === "not") return {
923
- ...m,
924
- condition: lower(m.condition, origin, depth + 1)
591
+ }
592
+ if (condition.type === "not") {
593
+ const child = evaluate(condition.condition, request);
594
+ return {
595
+ type: "not",
596
+ matched: child.matched === null ? null : !child.matched,
597
+ reason: "布尔取反;缺失字段的原子条件为 false",
598
+ children: [child]
925
599
  };
926
- return m;
600
+ }
601
+ let matched;
602
+ let present;
603
+ switch (condition.type) {
604
+ case "domain":
605
+ present = request.domain !== void 0;
606
+ matched = request.domain === condition.value;
607
+ break;
608
+ case "domainSuffix":
609
+ present = request.domain !== void 0;
610
+ matched = request.domain === condition.value || !!request.domain?.endsWith(`.${condition.value}`);
611
+ break;
612
+ case "ipCidr":
613
+ present = request.ip !== void 0;
614
+ matched = inCidr(request.ip, condition.value);
615
+ break;
616
+ case "sourceIp":
617
+ present = request.sourceIp !== void 0;
618
+ matched = inCidr(request.sourceIp, condition.value);
619
+ break;
620
+ case "port":
621
+ present = request.port !== void 0;
622
+ matched = present && request.port >= condition.from && request.port <= condition.to;
623
+ break;
624
+ case "sourcePort":
625
+ present = request.sourcePort !== void 0;
626
+ matched = present && request.sourcePort >= condition.from && request.sourcePort <= condition.to;
627
+ break;
628
+ case "network":
629
+ present = true;
630
+ matched = request.network === condition.value;
631
+ }
632
+ return {
633
+ type: condition.type,
634
+ matched,
635
+ reason: present ? matched ? "匹配" : "不匹配" : "字段缺失,原子条件为 false"
927
636
  };
928
- try {
929
- if (rules.length > 1e4) throw new Error("EXPANSION_LIMIT");
930
- return rules.map((r) => {
931
- const origin = [...r.origin];
932
- const when = lower(r.when, origin, 0);
933
- origins += origin.length;
934
- if (origins > 1e5) throw new Error("EXPANSION_LIMIT");
935
- return {
936
- ...r,
937
- when,
938
- origin
939
- };
940
- });
941
- } catch {
942
- diagnostics.push({
943
- severity: "error",
944
- code: "EXPANSION_LIMIT",
945
- path,
946
- message: "展开规则、条件或来源超过预算"
637
+ }
638
+ function explainRules(rules, fallback, input) {
639
+ const parsed = requestSchema.safeParse(input);
640
+ if (!parsed.success) throw new Error("INVALID_REQUEST");
641
+ const trace = [];
642
+ for (const rule of rules) {
643
+ const condition = evaluate(rule.when, parsed.data);
644
+ trace.push({
645
+ id: rule.id,
646
+ origin: rule.origin,
647
+ condition
947
648
  });
948
- return [];
949
- }
950
- }
951
- function collectNativeRuleSets(rules, target, diagnostics) {
952
- const found = /* @__PURE__ */ new Map();
953
- const visit = (m, nested) => {
954
- if (m.type === "nativeRuleSet") {
955
- found.set(m.id, m);
956
- if (nested && m.engine === "surge" && m.intervalSeconds !== void 0) diagnostics.push({
957
- severity: "error",
958
- code: "RULESET_COMPOSITION_UNSUPPORTED",
959
- target: target.id,
960
- path: `targets.${target.id}.ruleSets.${m.id}`,
961
- message: "Surge 嵌套外部规则只支持客户端默认更新间隔"
962
- });
963
- } else if (m.type === "all" || m.type === "any") m.conditions.forEach((c) => visit(c, true));
964
- else if (m.type === "not") visit(m.condition, true);
965
- else if (m.type === "ruleSet") visit(m.when, nested);
966
- };
967
- rules.forEach((r) => visit(r.when, false));
968
- for (const r of found.values()) diagnostics.push({
969
- severity: "warning",
970
- code: "EXTERNAL_RULESET_UNVERIFIED",
971
- target: target.id,
972
- path: `targets.${target.id}.ruleSets.${r.id}`,
973
- message: "外部规则由客户端更新和解释;编译器未获取内容或验证运行时匹配"
974
- });
975
- return [...found.values()];
976
- }
977
- //#endregion
978
- //#region src/rules.ts
979
- function expandRules(entries, diagnostics, path = "routing") {
980
- const output = [];
981
- const seen = /* @__PURE__ */ new Set();
982
- let limited = false;
983
- const error = (code, where, message) => diagnostics.push({
984
- severity: "error",
985
- code,
986
- path: where,
987
- message
988
- });
989
- function resolve(action, bindings, inPolicy, where) {
990
- if (action.type === "slot") {
991
- if (!Object.hasOwn(bindings, action.name)) {
992
- error("UNBOUND_SLOT", where, "出口槽位未声明或未绑定");
993
- return;
994
- }
995
- return bindings[action.name];
996
- }
997
- if (inPolicy && action.type === "route") {
998
- error("POLICY_RESOURCE_CAPTURE", where, "共享 policy 必须通过 slot 引用出口");
999
- return;
1000
- }
1001
- return action;
1002
- }
1003
- function walk(items, prefix, guards, bindings, inPolicy, origin) {
1004
- for (const entry of items) {
1005
- if (limited) return;
1006
- if (entry.type === "rule" && output.length >= 1e4) {
1007
- limited = true;
1008
- error("EXPANSION_LIMIT", path, "展开规则超过10000条");
1009
- return;
1010
- }
1011
- const id = `${prefix}/${entry.id}`;
1012
- if (seen.has(id)) {
1013
- error("DUPLICATE_RULE_ID", id, "同一实例路径出现重复 ID");
1014
- continue;
1015
- }
1016
- seen.add(id);
1017
- if (entry.type === "rule") {
1018
- const action = resolve(entry.then, bindings, inPolicy, id);
1019
- if (action) output.push({
1020
- id,
1021
- when: guards.length ? match.all(...guards, entry.when) : entry.when,
1022
- then: action,
1023
- origin: [...origin, entry.id]
1024
- });
1025
- } else if (entry.type === "block") walk(entry.rules, id, entry.when ? [...guards, entry.when] : guards, bindings, inPolicy, [...origin, entry.id]);
1026
- else {
1027
- const expected = new Set(entry.policy.exits);
1028
- if (Object.keys(entry.bindings).some((key) => !expected.has(key)) || entry.policy.exits.some((key) => !Object.hasOwn(entry.bindings, key))) {
1029
- error("POLICY_BINDINGS", id, "bindings 必须完整且只包含 policy 声明的出口");
1030
- continue;
1031
- }
1032
- const bound = Object.create(null);
1033
- for (const key of entry.policy.exits) {
1034
- const result = resolve(entry.bindings[key], bindings, inPolicy, `${id}/bindings/${key}`);
1035
- if (result) bound[key] = result;
1036
- }
1037
- walk(entry.policy.rules, id, guards, bound, true, [
1038
- ...origin,
1039
- `use:${entry.id}`,
1040
- `policy:${entry.policy.id}`
1041
- ]);
1042
- }
1043
- }
1044
- }
1045
- walk(entries, path, [], {}, false, []);
1046
- return limited ? [] : output;
1047
- }
1048
- function inCidr(address, cidr) {
1049
- if (!address) return false;
1050
- const parsed = ipaddr.parse(address);
1051
- const [base, bits] = ipaddr.parseCIDR(cidr);
1052
- return parsed.kind() === base.kind() && parsed.match(base, bits);
1053
- }
1054
- var StaticRuleSetUnknownError = class extends Error {
1055
- constructor() {
1056
- super("STATIC_RULESET_UNKNOWN");
1057
- this.name = "StaticRuleSetUnknownError";
1058
- }
1059
- };
1060
- function evaluate(condition, request) {
1061
- if (condition.type === "ruleSet") return evaluate(condition.when, request);
1062
- if (condition.type === "nativeRuleSet") return {
1063
- type: condition.type,
1064
- matched: null,
1065
- reason: "外部规则内容由客户端解释,静态未知"
1066
- };
1067
- if (condition.type === "all" || condition.type === "any") {
1068
- const children = condition.conditions.map((child) => evaluate(child, request));
1069
- const matched = condition.type === "all" ? children.some((child) => child.matched === false) ? false : children.some((child) => child.matched === null) ? null : true : children.some((child) => child.matched === true) ? true : children.some((child) => child.matched === null) ? null : false;
1070
- return {
1071
- type: condition.type,
1072
- matched,
1073
- reason: condition.type === "all" ? "所有子条件同时成立" : "至少一个子条件成立",
1074
- children
1075
- };
1076
- }
1077
- if (condition.type === "not") {
1078
- const child = evaluate(condition.condition, request);
1079
- return {
1080
- type: "not",
1081
- matched: child.matched === null ? null : !child.matched,
1082
- reason: "布尔取反;缺失字段的原子条件为 false",
1083
- children: [child]
1084
- };
1085
- }
1086
- let matched;
1087
- let present;
1088
- switch (condition.type) {
1089
- case "domain":
1090
- present = request.domain !== void 0;
1091
- matched = request.domain === condition.value;
1092
- break;
1093
- case "domainSuffix":
1094
- present = request.domain !== void 0;
1095
- matched = request.domain === condition.value || !!request.domain?.endsWith(`.${condition.value}`);
1096
- break;
1097
- case "ipCidr":
1098
- present = request.ip !== void 0;
1099
- matched = inCidr(request.ip, condition.value);
1100
- break;
1101
- case "sourceIp":
1102
- present = request.sourceIp !== void 0;
1103
- matched = inCidr(request.sourceIp, condition.value);
1104
- break;
1105
- case "port":
1106
- present = request.port !== void 0;
1107
- matched = present && request.port >= condition.from && request.port <= condition.to;
1108
- break;
1109
- case "sourcePort":
1110
- present = request.sourcePort !== void 0;
1111
- matched = present && request.sourcePort >= condition.from && request.sourcePort <= condition.to;
1112
- break;
1113
- case "network":
1114
- present = true;
1115
- matched = request.network === condition.value;
1116
- }
1117
- return {
1118
- type: condition.type,
1119
- matched,
1120
- reason: present ? matched ? "匹配" : "不匹配" : "字段缺失,原子条件为 false"
1121
- };
1122
- }
1123
- function explainRules(rules, fallback, input) {
1124
- const parsed = requestSchema.safeParse(input);
1125
- if (!parsed.success) throw new Error("INVALID_REQUEST");
1126
- const trace = [];
1127
- for (const rule of rules) {
1128
- const condition = evaluate(rule.when, parsed.data);
1129
- trace.push({
1130
- id: rule.id,
1131
- origin: rule.origin,
1132
- condition
1133
- });
1134
- if (condition.matched === null) throw new StaticRuleSetUnknownError();
1135
- if (condition.matched) return {
1136
- mode: "static",
1137
- rule: rule.id,
1138
- action: rule.then,
1139
- trace
1140
- };
649
+ if (condition.matched === null) throw new StaticRuleSetUnknownError();
650
+ if (condition.matched) return {
651
+ mode: "static",
652
+ rule: rule.id,
653
+ action: rule.then,
654
+ trace
655
+ };
1141
656
  }
1142
657
  return {
1143
658
  mode: "static",
@@ -1384,13 +899,13 @@ function clashGroup(group, name = (id) => id) {
1384
899
  } : {}
1385
900
  };
1386
901
  }
1387
- function conditionText(condition) {
902
+ function conditionText$1(condition) {
1388
903
  switch (condition.type) {
1389
- case "ruleSet": return conditionText(condition.when);
904
+ case "ruleSet": return conditionText$1(condition.when);
1390
905
  case "nativeRuleSet": return `RULE-SET,${condition.id}`;
1391
906
  case "all":
1392
- case "any": return `${condition.type === "all" ? "AND" : "OR"},(${condition.conditions.map((c) => `(${conditionText(c)})`).join(",")})`;
1393
- case "not": return `NOT,((${conditionText(condition.condition)}))`;
907
+ case "any": return `${condition.type === "all" ? "AND" : "OR"},(${condition.conditions.map((c) => `(${conditionText$1(c)})`).join(",")})`;
908
+ case "not": return `NOT,((${conditionText$1(condition.condition)}))`;
1394
909
  case "domain": return `DOMAIN,${condition.value}`;
1395
910
  case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
1396
911
  case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value},no-resolve`;
@@ -1400,13 +915,13 @@ function conditionText(condition) {
1400
915
  case "sourcePort": return `${condition.type === "port" ? "DST-PORT" : "SRC-PORT"},${condition.from === condition.to ? condition.from : `${condition.from}-${condition.to}`}`;
1401
916
  }
1402
917
  }
1403
- const policy = (action) => action.type === "route" ? action.to : action.type === "direct" ? "DIRECT" : "REJECT";
918
+ const policy$2 = (action) => action.type === "route" ? action.to : action.type === "direct" ? "DIRECT" : "REJECT";
1404
919
  function clashConfig(plan, secret) {
1405
920
  const { program, target } = plan;
1406
921
  const config = {
1407
922
  proxies: program.nodes.map((node) => clashProxy(node, target.engine, secret)),
1408
923
  "proxy-groups": program.groups.map((g) => clashGroup(g)),
1409
- rules: [...plan.rules.map((rule) => rule.when.type === "ipCidr" ? `${conditionText(rule.when).replace(/,no-resolve$/, "")},${policy(rule.then)},no-resolve` : `${conditionText(rule.when)},${policy(rule.then)}`), `MATCH,${policy(program.fallback)}`]
924
+ rules: [...plan.rules.map((rule) => rule.when.type === "ipCidr" ? `${conditionText$1(rule.when).replace(/,no-resolve$/, "")},${policy$2(rule.then)},no-resolve` : `${conditionText$1(rule.when)},${policy$2(rule.then)}`), `MATCH,${policy$2(program.fallback)}`]
1410
925
  };
1411
926
  if (plan.nativeRuleSets.length) config["rule-providers"] = Object.fromEntries(plan.nativeRuleSets.map((r) => [r.id, {
1412
927
  type: "http",
@@ -1654,7 +1169,7 @@ function singboxGroup(group, name = (id) => id) {
1654
1169
  interrupt_exist_connections: false
1655
1170
  };
1656
1171
  }
1657
- const inputSchema = z.strictObject({
1172
+ const inputSchema$1 = z.strictObject({
1658
1173
  target: z.strictObject({
1659
1174
  engine: z.enum([
1660
1175
  "surge",
@@ -1694,7 +1209,7 @@ function compileStrategyGroups(input) {
1694
1209
  error("INVALID_INPUT_GRAPH", "$", "输入不是有限的声明数据");
1695
1210
  return failure();
1696
1211
  }
1697
- const parsed = inputSchema.safeParse(input);
1212
+ const parsed = inputSchema$1.safeParse(input);
1698
1213
  if (!parsed.success) {
1699
1214
  error("INVALID_SCHEMA", "$", "策略目录、名字或目标不符合严格 schema");
1700
1215
  return failure();
@@ -1766,221 +1281,1385 @@ function compile(input) {
1766
1281
  cases
1767
1282
  });
1768
1283
  }
1769
- const parsed = configSchema.safeParse(input);
1770
- if (!parsed.success) {
1771
- for (const issue of parsed.error.issues.slice(0, 20)) error("INVALID_SCHEMA", issue.path.map(String).join(".") || "$", schemaIssueMessage(issue));
1772
- return deepFreeze({
1773
- ok: false,
1774
- diagnostics,
1775
- plans: [],
1776
- cases
1777
- });
1284
+ const parsed = configSchema.safeParse(input);
1285
+ if (!parsed.success) {
1286
+ for (const issue of parsed.error.issues.slice(0, 20)) error("INVALID_SCHEMA", issue.path.map(String).join(".") || "$", schemaIssueMessage(issue));
1287
+ return deepFreeze({
1288
+ ok: false,
1289
+ diagnostics,
1290
+ plans: [],
1291
+ cases
1292
+ });
1293
+ }
1294
+ const config = deepFreeze(parsed.data);
1295
+ const expanded = /* @__PURE__ */ new Map();
1296
+ if (Object.keys(config.programs).length === 0) error("EMPTY_PROGRAMS", "programs", "至少需要一个程序");
1297
+ for (const [name, program] of Object.entries(config.programs)) {
1298
+ const path = `programs.${name}`;
1299
+ for (const node of program.nodes) if (!isIP(node.server)) error("PROXY_HOSTNAME_MODE_UNSUPPORTED", `${path}.nodes.${node.id}`, "域名代理地址目前仅允许节点片段入口");
1300
+ validateRuleSets(program.routing, program.engine, diagnostics, path);
1301
+ const rules = lowerRuleSets(expandRules(program.routing, diagnostics, name), diagnostics, path);
1302
+ expanded.set(name, rules);
1303
+ const endpoints = program.endpoints ?? [];
1304
+ const resources = [
1305
+ ...program.nodes,
1306
+ ...program.groups,
1307
+ ...endpoints
1308
+ ];
1309
+ const byId = new Map(resources.map((resource) => [resource.id, resource]));
1310
+ if (byId.size !== resources.length) error("DUPLICATE_RESOURCE", path, "节点、组与端点共用唯一 ID 命名空间");
1311
+ const edges = new Map(resources.map((resource) => [resource.id, "members" in resource ? resource.members : "via" in resource && resource.via ? [resource.via] : []]));
1312
+ for (const [id, refs] of edges) for (const ref of refs) if (!byId.has(ref)) error("MISSING_REFERENCE", `${path}.${id}`, "节点或组引用不存在");
1313
+ for (const [id, refs] of edges) for (const ref of refs) if (byId.get(ref)?.type === "sing-box-tailscale") error("ENDPOINT_REFERENCE_UNSUPPORTED", `${path}.${id}`, "端点只能由 route 引用,不能作为组成员或 via");
1314
+ for (let i = 0; i < endpoints.length; i++) for (let j = 0; j < i; j++) if (pathsOverlap(endpoints[i].stateDirectory, endpoints[j].stateDirectory)) error("ENDPOINT_STATE_OVERLAP", `${path}.endpoints.${endpoints[i].id}`, "端点状态目录不能重复或互为祖先");
1315
+ const states = /* @__PURE__ */ new Map();
1316
+ const tcpOnly = /* @__PURE__ */ new Map();
1317
+ const visit = (id) => {
1318
+ if (states.get(id) === 1) {
1319
+ error("RESOURCE_CYCLE", `${path}.${id}`, "组成员和 via 拨号依赖不能形成循环");
1320
+ return true;
1321
+ }
1322
+ if (states.get(id) === 2) return tcpOnly.get(id) ?? false;
1323
+ states.set(id, 1);
1324
+ const item = byId.get(id);
1325
+ let limited = !!item && "server" in item && nodeIsTcpOnly(item, program.engine);
1326
+ for (const ref of edges.get(id) ?? []) limited = visit(ref) || limited;
1327
+ states.set(id, 2);
1328
+ tcpOnly.set(id, limited);
1329
+ return limited;
1330
+ };
1331
+ if (resources.length > 1e3) error("RESOURCE_LIMIT", path, "单程序最多 1000 个节点、组与端点");
1332
+ else for (const id of byId.keys()) visit(id);
1333
+ const validateAction = (action, where, udpPossible) => {
1334
+ if (action.type !== "route") return;
1335
+ if (!byId.has(action.to)) error("MISSING_REFERENCE", where, "路由出口不存在");
1336
+ else if (udpPossible && tcpOnly.get(action.to)) error("NETWORK_UNSUPPORTED", where, "出口的可选或 via 路径含 TCP-only 节点;请用 network(tcp) 限定规则,且不能用于 fallback");
1337
+ };
1338
+ for (const rule of rules) validateAction(rule.then, rule.id, truthPossibilities(rule.when, "udp").includes(true));
1339
+ const validateBindings = (entries, prefix) => {
1340
+ for (const entry of entries) {
1341
+ if (entry.type === "block") validateBindings(entry.rules, `${prefix}/${entry.id}`);
1342
+ if (entry.type === "use") {
1343
+ for (const [key, action] of Object.entries(entry.bindings)) if (action.type !== "slot") validateAction(action, `${prefix}/${entry.id}/bindings/${key}`, false);
1344
+ validateBindings(entry.policy.rules, `${prefix}/${entry.id}`);
1345
+ }
1346
+ }
1347
+ };
1348
+ validateBindings(program.routing, name);
1349
+ validateAction(program.fallback, `${path}.fallback`, true);
1350
+ }
1351
+ const targetIds = /* @__PURE__ */ new Set();
1352
+ for (const target of config.targets) {
1353
+ const path = `targets.${target.id}`;
1354
+ if (targetIds.has(target.id)) error("DUPLICATE_TARGET", path, "构建目标 ID 重复");
1355
+ targetIds.add(target.id);
1356
+ const descriptor = targetCatalog.find((item) => item.engine === target.engine && item.version === target.version && item.platforms.includes(target.platform));
1357
+ if (!descriptor) {
1358
+ error("UNKNOWN_TARGET", path, "目标引擎、精确版本和平台组合不在支持目录中", target.id);
1359
+ continue;
1360
+ }
1361
+ const originalProgram = config.programs[target.program];
1362
+ const lowered = lowerStrategies(originalProgram?.groups ?? [], target, diagnostics, path);
1363
+ const program = originalProgram ? {
1364
+ ...originalProgram,
1365
+ groups: lowered.groups
1366
+ } : void 0;
1367
+ if (!program) {
1368
+ error("MISSING_PROGRAM", path, "目标引用的程序不存在", target.id);
1369
+ continue;
1370
+ }
1371
+ if (program.engine !== target.engine) error("ENGINE_MISMATCH", path, "平台程序与目标引擎不一致", target.id);
1372
+ if (target.mode === "standalone" && !program.listener) error("LISTENER_REQUIRED", path, "standalone 必须声明 loopback listener 与 IP DNS resolver", target.id);
1373
+ if (target.mode !== "standalone" && program.listener) error("UNUSED_LISTENER", path, "fragment 不能静默忽略 listener;请使用独立程序或 standalone 目标", target.id);
1374
+ for (const endpoint of program.endpoints ?? []) {
1375
+ if (!descriptor.endpoints.includes(endpoint.type)) error("ENDPOINT_UNSUPPORTED", `${path}.endpoints.${endpoint.id}`, "Tailscale 端点仅支持 sing-box 1.12.0", target.id);
1376
+ if (target.mode !== "standalone") error("ENDPOINT_MODE_UNSUPPORTED", `${path}.endpoints.${endpoint.id}`, "Tailscale 需要 standalone 的普通 DNS/final 隔离引导解析", target.id);
1377
+ }
1378
+ for (const node of program.nodes) {
1379
+ validateProxyOptions(node, target, diagnostics);
1380
+ if (!descriptor.protocols.includes(node.type)) error("PROTOCOL_UNSUPPORTED", `${path}.nodes.${node.id}`, "目标版本不支持该代理协议", target.id);
1381
+ if (node.label) diagnostics.push({
1382
+ severity: "warning",
1383
+ code: "LABEL_NOT_EMITTED",
1384
+ path: `${path}.nodes.${node.id}.label`,
1385
+ target: target.id,
1386
+ message: "原生节点使用稳定 ID;展示 label 不写入配置,不影响路由"
1387
+ });
1388
+ }
1389
+ for (const group of program.groups) if (!descriptor.groups.includes(group.type)) error("GROUP_UNSUPPORTED", `${path}.groups.${group.id}`, "目标未实现该组机制;不会自动替换为另一种组", target.id);
1390
+ validateSmartMembers(program.groups, new Set(program.nodes.map((n) => n.id)), diagnostics, path);
1391
+ const rules = expanded.get(target.program);
1392
+ if (target.engine === "mihomo" || target.engine === "stash") validateClashTarget(target, rules, diagnostics);
1393
+ if (target.engine === "surge") {
1394
+ for (const rule of rules) if (logicalDepth(rule.when) > 10) error("LOGICAL_DEPTH", rule.id, "Surge 逻辑条件最多嵌套 10 层", target.id);
1395
+ }
1396
+ const nativeRuleSets = collectNativeRuleSets(rules, target, diagnostics);
1397
+ for (const resource of nativeRuleSets) if (!descriptor.nativeRuleSets.includes(resource.format)) error("RULESET_UNSUPPORTED", `${path}.ruleSets.${resource.id}`, "精确目标不支持此原生规则资源格式", target.id);
1398
+ plans.push({
1399
+ nativeRuleSets,
1400
+ target,
1401
+ program,
1402
+ rules,
1403
+ strategySelections: lowered.selections,
1404
+ sourceMap: rules.map((rule, nativeIndex) => ({
1405
+ rule: rule.id,
1406
+ nativeIndex,
1407
+ origin: rule.origin
1408
+ })),
1409
+ preconditions: [
1410
+ ...nativeRuleSets.length ? ["原生外部规则由客户端持续下载和解释;静态布尔结果不验证 DNS 等副作用。缓存与下载失败处理沿用客户端机制,fragment 运行方提供工作目录与下载 DNS 路径。"] : [],
1411
+ ...program.endpoints?.length ? [
1412
+ "Tailscale 需要 with_tailscale 构建标签;运行方负责登录、路由批准及每实例独占身份目录。构建不注册 tailnet。",
1413
+ "状态目录真实路径必须独立于产物与清理范围;output 重叠检查仅为词法检查,不能证明运行主机符号链接隔离。",
1414
+ "普通 DNS/final 与端点控制面引导 DNS 分离;未配置 MagicDNS,私有域名须由运行方提供适用的普通解析器。"
1415
+ ] : [],
1416
+ ...target.engine === "surge" && program.nodes.some((node) => node.type === "vmess") ? ["Surge VMess 的 TCP-only 由语言路由检查保证;fragment 组合方不得额外引入通往此节点的 UDP 路由。"] : [],
1417
+ ...target.engine === "stash" ? ["Stash 4.2.1 原生未验证;block-quic: off 按现行文档编码,历史版本 QUIC 行为未验证。"] : [],
1418
+ "规则只匹配已观测元数据;不自动嗅探或为了 IP 条件解析域名。",
1419
+ "节点 server 与 via 各跳必须是 IP;运行时组选择、代理连通性不由静态解释保证。",
1420
+ ...target.mode !== "standalone" ? ["此配置是 fragment,组合方负责入口、直接 DNS 解析路径及 source/domain/IP 元数据来源。"] : ["仅本机 loopback 显式代理;不是 TUN 或 LAN 网关。DNS 上游固定直连。"]
1421
+ ],
1422
+ nativeValidation: "not-run"
1423
+ });
1424
+ }
1425
+ const caseIds = /* @__PURE__ */ new Set();
1426
+ for (const test of config.cases ?? []) {
1427
+ if (caseIds.has(test.id)) error("DUPLICATE_CASE", `cases.${test.id}`, "案例 ID 重复");
1428
+ caseIds.add(test.id);
1429
+ const program = config.programs[test.program];
1430
+ if (!program) {
1431
+ error("MISSING_PROGRAM", `cases.${test.id}`, "案例引用的程序不存在");
1432
+ continue;
1433
+ }
1434
+ let actual;
1435
+ try {
1436
+ actual = explainRules(expanded.get(test.program), program.fallback, test.request);
1437
+ } catch (cause) {
1438
+ if (!(cause instanceof StaticRuleSetUnknownError)) throw cause;
1439
+ cases.push({
1440
+ id: test.id,
1441
+ passed: false,
1442
+ code: "CASE_INDETERMINATE"
1443
+ });
1444
+ error("CASE_INDETERMINATE", `cases.${test.id}`, "外部规则内容未知,无法静态确定首命中");
1445
+ continue;
1446
+ }
1447
+ const passed = (test.expect.rule === void 0 || test.expect.rule === actual.rule) && sameAction(test.expect.action, actual.action);
1448
+ cases.push({
1449
+ id: test.id,
1450
+ passed,
1451
+ actual: {
1452
+ rule: actual.rule,
1453
+ action: actual.action
1454
+ }
1455
+ });
1456
+ if (!passed) error("CASE_FAILED", `cases.${test.id}`, "请求的首命中规则或逻辑出口不符合预期");
1457
+ }
1458
+ if (config.warningsAsErrors) {
1459
+ for (let i = 0; i < diagnostics.length; i++) if (diagnostics[i].severity === "warning") diagnostics[i] = {
1460
+ ...diagnostics[i],
1461
+ severity: "error"
1462
+ };
1463
+ }
1464
+ const ok = !diagnostics.some((d) => d.severity === "error");
1465
+ return deepFreeze({
1466
+ ok,
1467
+ diagnostics,
1468
+ plans: ok ? plans : [],
1469
+ cases
1470
+ });
1471
+ }
1472
+ function sameAction(a, b) {
1473
+ return a.type === b.type && (a.type !== "route" || b.type === "route" && a.to === b.to);
1474
+ }
1475
+ function explain(compilation, target, request) {
1476
+ if (!compilation.ok) throw new Error("COMPILATION_FAILED");
1477
+ const plan = compilation.plans.find((plan) => plan.target.id === target);
1478
+ if (!plan) throw new Error("UNKNOWN_TARGET");
1479
+ return explainRules(plan.rules, plan.program.fallback, request);
1480
+ }
1481
+ //#endregion
1482
+ //#region src/secrets.ts
1483
+ /** One reader per rendering batch; exceptions and missing values never disclose credentials. */
1484
+ function secretReader(resolveSecret) {
1485
+ const values = /* @__PURE__ */ new Map();
1486
+ return (token) => {
1487
+ if (values.has(token.name)) return values.get(token.name);
1488
+ let value;
1489
+ try {
1490
+ value = resolveSecret(token);
1491
+ } catch {
1492
+ throw new RenderError("SECRET_RESOLUTION_FAILED");
1493
+ }
1494
+ if (typeof value !== "string" || value.length === 0) throw new RenderError("SECRET_MISSING");
1495
+ values.set(token.name, value);
1496
+ return value;
1497
+ };
1498
+ }
1499
+ //#endregion
1500
+ //#region src/surge-profile.ts
1501
+ const builtin = z.enum([
1502
+ "DIRECT",
1503
+ "REJECT",
1504
+ "REJECT-DROP",
1505
+ "REJECT-NO-DROP",
1506
+ "REJECT-TINYGIF"
1507
+ ]);
1508
+ const policy$1 = z.union([z.strictObject({ ref: idSchema }), z.strictObject({ builtin })]);
1509
+ const token = z.strictObject({
1510
+ type: z.literal("env"),
1511
+ name: z.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/)
1512
+ });
1513
+ const safe = z.string().min(1).max(4096).refine((v) => v.trim() === v && !/[\p{C}\p{Zl}\p{Zp},=()#;"'\\]/u.test(v));
1514
+ const domain = z.string().max(253).regex(/^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/);
1515
+ const hostPattern = safe.refine((v) => /^[a-zA-Z0-9*?._-]+$/.test(v));
1516
+ const ip = safe.refine((v) => isIP(v) !== 0 && !v.includes("%"));
1517
+ const cidr = (version) => safe.refine((v) => {
1518
+ try {
1519
+ const [address] = ipaddr.parseCIDR(v);
1520
+ return (!version || (address.kind() === "ipv4" ? 4 : 6) === version) && !v.includes("%");
1521
+ } catch {
1522
+ return false;
1523
+ }
1524
+ });
1525
+ const port = z.number().int().min(1).max(65535);
1526
+ function addressPort(value, allowHost, portRequired) {
1527
+ if (!portRequired && isIP(value)) return true;
1528
+ const match = /^(\[[^\]]+\]|[^:]+):(\d+)$/.exec(value);
1529
+ if (!match || Number(match[2]) < 1 || Number(match[2]) > 65535) return false;
1530
+ const host = match[1];
1531
+ return host.startsWith("[") ? isIP(host.slice(1, -1)) === 6 : isIP(host) === 4 || allowHost && domain.safeParse(host).success;
1532
+ }
1533
+ const listener = safe.refine((v) => addressPort(v, false, false));
1534
+ const endpoint = safe.refine((v) => addressPort(v, true, true));
1535
+ const dns = safe.refine((v) => v === "system" || addressPort(v, false, false));
1536
+ const url = z.string().min(1).max(4096).refine((v) => {
1537
+ try {
1538
+ const u = new URL(v);
1539
+ return /^https?:\/\//.test(v) && !u.username && !u.password && !u.hash && !/[\s\p{C},()\\"']/u.test(v);
1540
+ } catch {
1541
+ return false;
1542
+ }
1543
+ });
1544
+ const encryptedDns = z.string().max(4096).refine((v) => {
1545
+ try {
1546
+ const u = new URL(v);
1547
+ return [
1548
+ "https:",
1549
+ "h3:",
1550
+ "quic:",
1551
+ "tls:",
1552
+ "tcp:"
1553
+ ].includes(u.protocol) && !!u.hostname && !u.username && !u.password && !u.hash && !/[\s\p{C},()\\"']/u.test(v);
1554
+ } catch {
1555
+ return false;
1556
+ }
1557
+ });
1558
+ const list = (item) => z.array(item).min(1).max(1e3);
1559
+ const control = z.strictObject({
1560
+ password: token,
1561
+ listen: safe.refine((v) => addressPort(v, false, true))
1562
+ });
1563
+ const generalSchema = z.strictObject({
1564
+ loglevel: z.enum([
1565
+ "verbose",
1566
+ "info",
1567
+ "notify",
1568
+ "warning"
1569
+ ]).optional(),
1570
+ "dns-server": list(dns).optional(),
1571
+ "encrypted-dns-server": list(encryptedDns).optional(),
1572
+ "show-error-page-for-reject": z.boolean().optional(),
1573
+ "exclude-simple-hostnames": z.boolean().optional(),
1574
+ "internet-test-url": url.optional(),
1575
+ "skip-proxy": list(z.union([
1576
+ hostPattern,
1577
+ ip,
1578
+ cidr()
1579
+ ])).optional(),
1580
+ ipv6: z.boolean().optional(),
1581
+ "ipv6-vif": z.enum([
1582
+ "auto",
1583
+ "always",
1584
+ "disabled"
1585
+ ]).optional(),
1586
+ "bypass-system": z.boolean().optional(),
1587
+ replica: z.boolean().optional(),
1588
+ "tls-provider": z.enum(["default", "openssl"]).optional(),
1589
+ "bypass-tun": list(cidr()).optional(),
1590
+ "always-real-ip": list(hostPattern).optional(),
1591
+ "http-api": control.optional(),
1592
+ "http-api-web-dashboard": z.boolean().optional(),
1593
+ "external-controller-access": control.optional(),
1594
+ "hijack-dns": list(safe.refine((v) => /^\*(?::\d+)?$/.test(v) ? !v.includes(":") || Number(v.slice(2)) > 0 && Number(v.slice(2)) <= 65535 : addressPort(v, false, false))).optional(),
1595
+ "http-listen": listener.optional(),
1596
+ "socks5-listen": listener.optional(),
1597
+ "proxy-restricted-to-lan": z.boolean().optional()
1598
+ });
1599
+ const hostSchema = z.strictObject({
1600
+ pattern: hostPattern,
1601
+ address: z.union([ip, domain]).optional(),
1602
+ server: z.union([dns, encryptedDns]).optional()
1603
+ }).refine((v) => v.address !== void 0 || v.server !== void 0);
1604
+ const key = z.string().regex(/^[A-Za-z0-9+/]{43}=$/).refine((v) => Buffer.from(v, "base64").length === 32 && Buffer.from(v, "base64").toString("base64") === v);
1605
+ const sectionName = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,127}$/);
1606
+ const tunnelSchema = z.discriminatedUnion("type", [z.strictObject({
1607
+ type: z.literal("tailscale"),
1608
+ id: idSchema,
1609
+ sectionName,
1610
+ authKey: token,
1611
+ hostname: domain,
1612
+ dnsServer: list(dns).optional(),
1613
+ autoAddMagicDnsRule: z.boolean().optional(),
1614
+ idleKeepalive: z.number().int().min(-1).max(2147483647).optional()
1615
+ }), z.strictObject({
1616
+ type: z.literal("wireguard"),
1617
+ id: idSchema,
1618
+ sectionName,
1619
+ privateKey: token,
1620
+ selfIp: ip.refine((v) => isIP(v) === 4),
1621
+ dnsServer: list(dns).optional(),
1622
+ mtu: z.number().int().min(576).max(9e3).optional(),
1623
+ peers: list(z.strictObject({
1624
+ publicKey: key,
1625
+ endpoint,
1626
+ allowedIps: list(cidr()),
1627
+ presharedKey: token.optional(),
1628
+ persistentKeepalive: z.number().int().min(0).max(65535).optional()
1629
+ }))
1630
+ })]);
1631
+ const groupSchema = z.strictObject({
1632
+ id: idSchema,
1633
+ type: z.enum(["select", "smart"]),
1634
+ members: list(policy$1),
1635
+ url: url.optional(),
1636
+ intervalSeconds: z.number().int().positive().max(2147483647).optional(),
1637
+ timeoutSeconds: z.number().int().positive().max(3600).optional()
1638
+ });
1639
+ const options = {
1640
+ noResolve: z.boolean().optional(),
1641
+ extendedMatching: z.boolean().optional()
1642
+ };
1643
+ const atom$1 = (type, value) => z.strictObject({
1644
+ type: z.literal(type),
1645
+ value,
1646
+ ...options
1647
+ });
1648
+ const conditionSchema = z.lazy(() => z.union([
1649
+ atom$1("domain", domain),
1650
+ atom$1("domainSuffix", domain),
1651
+ atom$1("ipCidr", cidr(4)),
1652
+ atom$1("ipCidr6", cidr(6)),
1653
+ atom$1("sourceIp", z.union([ip, cidr()])),
1654
+ atom$1("processName", safe),
1655
+ atom$1("macAddress", z.string().regex(/^(?:[\da-fA-F]{2}:){5}[\da-fA-F]{2}$/)),
1656
+ z.strictObject({
1657
+ type: z.enum(["port", "sourcePort"]),
1658
+ from: port,
1659
+ to: port.optional(),
1660
+ ...options
1661
+ }).refine((v) => v.to === void 0 || v.to >= v.from),
1662
+ z.strictObject({
1663
+ type: z.literal("network"),
1664
+ value: z.enum(["tcp", "udp"]),
1665
+ ...options
1666
+ }),
1667
+ z.strictObject({
1668
+ type: z.enum(["all", "any"]),
1669
+ conditions: z.array(conditionSchema).min(2).max(100),
1670
+ ...options
1671
+ }),
1672
+ z.strictObject({
1673
+ type: z.literal("not"),
1674
+ condition: conditionSchema,
1675
+ ...options
1676
+ }),
1677
+ z.strictObject({
1678
+ type: z.literal("ruleSet"),
1679
+ format: z.enum(["rule-set", "domain-set"]),
1680
+ url: url.optional(),
1681
+ builtin: z.enum(["LAN", "SYSTEM"]).optional(),
1682
+ ...options
1683
+ }).refine((v) => v.url !== void 0 !== (v.builtin !== void 0))
1684
+ ]));
1685
+ const managedSchema = z.strictObject({
1686
+ url: url.refine((v) => !new URL(v).search && !v.includes("?")),
1687
+ query: z.record(z.string().min(1).max(128).regex(/^[A-Za-z][A-Za-z0-9_-]*$/), z.union([z.string().max(4096), token])).optional(),
1688
+ intervalSeconds: z.number().int().min(60).max(2147483647),
1689
+ strict: z.boolean()
1690
+ });
1691
+ const inputSchema = z.strictObject({
1692
+ target: z.strictObject({
1693
+ engine: z.literal("surge"),
1694
+ platform: z.enum(["macos", "ios"]),
1695
+ version: z.string()
1696
+ }),
1697
+ managed: managedSchema.optional(),
1698
+ general: generalSchema.optional(),
1699
+ hosts: z.array(hostSchema).max(2e3).optional(),
1700
+ nodes: z.array(nodeSchema).max(1e3),
1701
+ tunnels: z.array(tunnelSchema).max(1e3).optional(),
1702
+ groups: z.array(groupSchema).max(1e3),
1703
+ rules: z.array(z.strictObject({
1704
+ when: conditionSchema,
1705
+ then: policy$1
1706
+ })).max(1e4),
1707
+ fallback: policy$1,
1708
+ names: z.record(idSchema, nativeNameSchema).optional()
1709
+ });
1710
+ const plans = /* @__PURE__ */ new WeakMap();
1711
+ function compileSurgeProfile(input) {
1712
+ const diagnostics = [];
1713
+ const error = (code) => diagnostics.push({
1714
+ severity: "error",
1715
+ code,
1716
+ path: "$",
1717
+ message: code
1718
+ });
1719
+ const failure = () => deepFreeze({
1720
+ ok: false,
1721
+ artifactKind: "surge-profile",
1722
+ diagnostics,
1723
+ bindings: []
1724
+ });
1725
+ try {
1726
+ assertData(input);
1727
+ } catch {
1728
+ error("INVALID_INPUT_GRAPH");
1729
+ return failure();
1730
+ }
1731
+ const parsed = inputSchema.safeParse(input);
1732
+ if (!parsed.success) {
1733
+ error("INVALID_SCHEMA");
1734
+ return failure();
1735
+ }
1736
+ if (parsed.data.general) {
1737
+ const general = parsed.data.general;
1738
+ parsed.data.general = Object.fromEntries(Object.keys(input.general).map((key) => [key, general[key]]));
1739
+ }
1740
+ const p = deepFreeze(parsed.data);
1741
+ if (!(p.target.platform === "macos" && p.target.version === "6.10.0") && !(p.target.platform === "ios" && p.target.version === "5.21.0")) error("UNKNOWN_TARGET");
1742
+ const tunnels = p.tunnels ?? [];
1743
+ const resources = [
1744
+ ...p.nodes,
1745
+ ...tunnels,
1746
+ ...p.groups
1747
+ ];
1748
+ if (resources.length > 1e3) error("RESOURCE_LIMIT");
1749
+ const ids = new Set(resources.map((r) => r.id));
1750
+ if (ids.size !== resources.length) error("DUPLICATE_RESOURCE");
1751
+ if (Object.keys(p.names ?? {}).some((id) => !ids.has(id))) error("UNKNOWN_NAME_MAPPING");
1752
+ const bindings = resources.map((r) => ({
1753
+ id: r.id,
1754
+ nativeName: p.names?.[r.id] ?? r.id
1755
+ }));
1756
+ if (bindings.some((b) => !nativeNameSchema.safeParse(b.nativeName).success || isReservedNativeName(b.nativeName, "surge"))) error("INVALID_NATIVE_NAME");
1757
+ if (new Set(bindings.map((b) => b.nativeName)).size !== bindings.length) error("DUPLICATE_NATIVE_NAME");
1758
+ if (new Set(tunnels.map((t) => t.sectionName)).size !== tunnels.length) error("DUPLICATE_TUNNEL_SECTION");
1759
+ if (p.target.platform === "ios" && [
1760
+ "bypass-system",
1761
+ "replica",
1762
+ "tls-provider",
1763
+ "bypass-tun",
1764
+ "external-controller-access"
1765
+ ].some((k) => Object.hasOwn(p.general ?? {}, k))) error("PLATFORM_OPTION_UNSUPPORTED");
1766
+ if (new Set((p.hosts ?? []).map((h) => h.pattern.toLowerCase())).size !== (p.hosts ?? []).length) error("DUPLICATE_HOST_PATTERN");
1767
+ const checkPolicy = (action) => {
1768
+ if ("ref" in action && !ids.has(action.ref)) error("MISSING_REFERENCE");
1769
+ };
1770
+ const edges = new Map(resources.map((r) => [r.id, []]));
1771
+ const proxyIds = new Set([...p.nodes, ...tunnels].map((n) => n.id));
1772
+ for (const node of p.nodes) {
1773
+ if (node.type === "vless") error("PROTOCOL_UNSUPPORTED");
1774
+ validateProxyOptions(node, {
1775
+ id: "profile",
1776
+ engine: "surge"
1777
+ }, diagnostics);
1778
+ if (node.via) {
1779
+ checkPolicy({ ref: node.via });
1780
+ edges.get(node.id).push(node.via);
1781
+ }
1782
+ }
1783
+ for (const group of p.groups) {
1784
+ if (group.type === "smart" && (group.url !== void 0 || group.intervalSeconds !== void 0 || group.timeoutSeconds !== void 0)) error("GROUP_OPTION_UNSUPPORTED");
1785
+ for (const member of group.members) {
1786
+ checkPolicy(member);
1787
+ if (group.type === "smart" && (!("ref" in member) || !proxyIds.has(member.ref))) error("SMART_MEMBER_UNSUPPORTED");
1788
+ if ("ref" in member) edges.get(group.id).push(member.ref);
1789
+ }
1790
+ }
1791
+ const active = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set();
1792
+ const visit = (id) => {
1793
+ if (active.has(id)) {
1794
+ error("RESOURCE_CYCLE");
1795
+ return;
1796
+ }
1797
+ if (visited.has(id)) return;
1798
+ active.add(id);
1799
+ for (const next of edges.get(id) ?? []) visit(next);
1800
+ active.delete(id);
1801
+ visited.add(id);
1802
+ };
1803
+ if (resources.length <= 1e3) for (const id of ids) visit(id);
1804
+ const formats = /* @__PURE__ */ new Map();
1805
+ const checkCondition = (c, depth) => {
1806
+ if (depth > 10) {
1807
+ error("LOGICAL_DEPTH_EXCEEDED");
1808
+ return;
1809
+ }
1810
+ if (c.noResolve !== void 0 && ![
1811
+ "ipCidr",
1812
+ "ipCidr6",
1813
+ "ruleSet"
1814
+ ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
1815
+ if (c.extendedMatching !== void 0 && ![
1816
+ "domain",
1817
+ "domainSuffix",
1818
+ "ruleSet"
1819
+ ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
1820
+ if (p.target.platform === "ios" && ["processName", "macAddress"].includes(c.type)) error("PLATFORM_RULE_UNSUPPORTED");
1821
+ if (c.type === "all" || c.type === "any") for (const child of c.conditions) checkCondition(child, depth + 1);
1822
+ if (c.type === "not") checkCondition(c.condition, depth + 1);
1823
+ if (c.type === "ruleSet") {
1824
+ if (c.builtin && c.format !== "rule-set") error("BUILTIN_RULESET_FORMAT");
1825
+ if (c.url) {
1826
+ if (formats.has(c.url) && formats.get(c.url) !== c.format) error("RULESET_FORMAT_CONFLICT");
1827
+ formats.set(c.url, c.format);
1828
+ }
1829
+ }
1830
+ };
1831
+ for (const rule of p.rules) {
1832
+ checkPolicy(rule.then);
1833
+ checkCondition(rule.when, 0);
1834
+ }
1835
+ checkPolicy(p.fallback);
1836
+ if (diagnostics.some((d) => d.severity === "error")) return failure();
1837
+ if (formats.size) diagnostics.push({
1838
+ severity: "warning",
1839
+ code: "EXTERNAL_RULESET_UNVERIFIED",
1840
+ path: "rules",
1841
+ message: "External rule sets are resolved by the client, not by the compiler."
1842
+ });
1843
+ const result = deepFreeze({
1844
+ ok: true,
1845
+ artifactKind: "surge-profile",
1846
+ diagnostics,
1847
+ bindings
1848
+ });
1849
+ plans.set(result, p);
1850
+ return result;
1851
+ }
1852
+ function conditionOptions(c) {
1853
+ return [...c.noResolve ? ["no-resolve"] : [], ...c.extendedMatching ? ["extended-matching"] : []];
1854
+ }
1855
+ function conditionText(c) {
1856
+ switch (c.type) {
1857
+ case "all":
1858
+ case "any": return `${c.type === "all" ? "AND" : "OR"},(${c.conditions.map((x) => `(${[conditionText(x), ...conditionOptions(x)].join(",")})`).join(",")})`;
1859
+ case "not": return `NOT,((${[conditionText(c.condition), ...conditionOptions(c.condition)].join(",")}))`;
1860
+ case "port":
1861
+ case "sourcePort": return `${c.type === "port" ? "DEST-PORT" : "SRC-PORT"},${c.from}${c.to === void 0 || c.to === c.from ? "" : `-${c.to}`}`;
1862
+ case "network": return `PROTOCOL,${c.value.toUpperCase()}`;
1863
+ case "ruleSet": return `${c.format === "rule-set" ? "RULE-SET" : "DOMAIN-SET"},${c.url ?? c.builtin}`;
1864
+ default: return `${{
1865
+ domain: "DOMAIN",
1866
+ domainSuffix: "DOMAIN-SUFFIX",
1867
+ ipCidr: "IP-CIDR",
1868
+ ipCidr6: "IP-CIDR6",
1869
+ sourceIp: "SRC-IP",
1870
+ processName: "PROCESS-NAME",
1871
+ macAddress: "MAC-ADDRESS"
1872
+ }[c.type]},${c.value}`;
1873
+ }
1874
+ }
1875
+ function renderProfile(compilation, read) {
1876
+ const p = plans.get(compilation);
1877
+ if (!p) throw new RenderError("COMPILATION_FAILED");
1878
+ const name = (id) => p.names?.[id] ?? id;
1879
+ const action = (value) => "ref" in value ? name(value.ref) : value.builtin;
1880
+ const credential = (token, kind) => {
1881
+ const value = read(token);
1882
+ if (!(kind === "key" ? key.safeParse(value).success : kind === "control" ? /^[A-Za-z0-9_.+%-]+$/.test(value) : /^[A-Za-z0-9_-]+$/.test(value))) throw new RenderError("SURGE_VALUE_UNREPRESENTABLE");
1883
+ return value;
1884
+ };
1885
+ const lines = [];
1886
+ if (p.managed) {
1887
+ const address = new URL(p.managed.url);
1888
+ for (const [k, v] of Object.entries(p.managed.query ?? {})) address.searchParams.set(k, typeof v === "string" ? v : read(v));
1889
+ lines.push(`#!MANAGED-CONFIG ${address.href} interval=${p.managed.intervalSeconds} strict=${p.managed.strict}`, "");
1890
+ }
1891
+ lines.push("[General]");
1892
+ for (const [k, v] of Object.entries(p.general ?? {})) {
1893
+ const value = Array.isArray(v) ? v.join(", ") : typeof v === "object" ? `${credential(v.password, "control")}@${v.listen}` : String(v);
1894
+ lines.push(`${k} = ${value}`);
1895
+ }
1896
+ lines.push("", "[Host]");
1897
+ for (const h of p.hosts ?? []) lines.push(`${h.pattern} = ${[...h.address ? [h.address] : [], ...h.server ? [`server:${h.server}`] : []].join(", ")}`);
1898
+ lines.push("", "[Proxy]");
1899
+ for (const n of p.nodes) lines.push(surgeProxy(n, read, name));
1900
+ for (const t of p.tunnels ?? []) lines.push(`${name(t.id)} = ${t.type}, section-name=${t.sectionName}`);
1901
+ for (const t of p.tunnels ?? []) {
1902
+ lines.push("", `[${t.type === "tailscale" ? "Tailscale" : "WireGuard"} ${t.sectionName}]`);
1903
+ if (t.type === "tailscale") {
1904
+ lines.push(`auth-key = ${credential(t.authKey, "tailscale")}`, `hostname = ${t.hostname}`);
1905
+ if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
1906
+ if (t.autoAddMagicDnsRule !== void 0) lines.push(`auto-add-magic-dns-rule = ${t.autoAddMagicDnsRule}`);
1907
+ if (t.idleKeepalive !== void 0) lines.push(`idle-keepalive = ${t.idleKeepalive}`);
1908
+ } else {
1909
+ lines.push(`private-key = ${credential(t.privateKey, "key")}`, `self-ip = ${t.selfIp}`);
1910
+ if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
1911
+ if (t.mtu !== void 0) lines.push(`mtu = ${t.mtu}`);
1912
+ for (const peer of t.peers) {
1913
+ const values = [`public-key = ${peer.publicKey}`];
1914
+ if (peer.presharedKey) values.push(`preshared-key = ${credential(peer.presharedKey, "key")}`);
1915
+ values.push(`allowed-ips = "${peer.allowedIps.join(", ")}"`, `endpoint = ${peer.endpoint}`);
1916
+ if (peer.persistentKeepalive !== void 0) values.push(`keepalive = ${peer.persistentKeepalive}`);
1917
+ lines.push(`peer = (${values.join(", ")})`);
1918
+ }
1919
+ }
1920
+ }
1921
+ lines.push("", "[Proxy Group]");
1922
+ for (const g of p.groups) lines.push(`${name(g.id)} = ${[
1923
+ g.type,
1924
+ ...g.members.map(action),
1925
+ ...g.url ? [`url=${g.url}`] : [],
1926
+ ...g.intervalSeconds !== void 0 ? [`interval=${g.intervalSeconds}`] : [],
1927
+ ...g.timeoutSeconds !== void 0 ? [`timeout=${g.timeoutSeconds}`] : []
1928
+ ].join(", ")}`);
1929
+ lines.push("", "[Rule]");
1930
+ for (const r of p.rules) lines.push([
1931
+ conditionText(r.when),
1932
+ action(r.then),
1933
+ ...conditionOptions(r.when)
1934
+ ].join(","));
1935
+ lines.push(`FINAL,${action(p.fallback)}`, "");
1936
+ return deepFreeze({
1937
+ artifactKind: "surge-profile",
1938
+ content: lines.join("\n")
1939
+ });
1940
+ }
1941
+ function renderSurgeProfile(compilation, resolveSecret) {
1942
+ return renderProfile(compilation, secretReader(resolveSecret));
1943
+ }
1944
+ function renderSurgeProfiles(compilations, resolveSecret) {
1945
+ if (compilations.some((c) => !plans.has(c))) throw new RenderError("COMPILATION_FAILED");
1946
+ const read = secretReader(resolveSecret);
1947
+ return deepFreeze(compilations.map((c) => renderProfile(c, read)));
1948
+ }
1949
+ //#endregion
1950
+ //#region src/surge-definitions.ts
1951
+ var ProfileDefinitionError = class extends Error {
1952
+ code;
1953
+ constructor(code) {
1954
+ super(code);
1955
+ this.code = code;
1956
+ this.name = "ProfileDefinitionError";
1957
+ }
1958
+ };
1959
+ const fail$1 = (code) => {
1960
+ throw new ProfileDefinitionError(code);
1961
+ };
1962
+ /** Inspect descriptors before any caller spreads or reads input fields. Shared DAGs are legal. */
1963
+ function inspectDefinition(root) {
1964
+ let edges = 0;
1965
+ let objects = 0;
1966
+ const visiting = /* @__PURE__ */ new Set();
1967
+ const heights = /* @__PURE__ */ new Map();
1968
+ function visit(value, depth) {
1969
+ if (depth > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
1970
+ if (value === null || typeof value !== "object") {
1971
+ if (![
1972
+ "undefined",
1973
+ "string",
1974
+ "number",
1975
+ "boolean"
1976
+ ].includes(typeof value) && value !== null) fail$1("DEFINITION_NOT_DATA");
1977
+ return 0;
1978
+ }
1979
+ if (visiting.has(value)) fail$1("DEFINITION_CYCLE");
1980
+ const cached = heights.get(value);
1981
+ if (cached !== void 0) {
1982
+ if (depth + cached > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
1983
+ return cached;
1984
+ }
1985
+ if (++objects > 2e4) fail$1("DEFINITION_OBJECT_BUDGET_EXCEEDED");
1986
+ const proto = Object.getPrototypeOf(value);
1987
+ if (proto !== Object.prototype && proto !== null && !(Array.isArray(value) && proto === Array.prototype)) fail$1("DEFINITION_NOT_DATA");
1988
+ if (Array.isArray(value) && value.length > 1e5) fail$1("DEFINITION_EDGE_BUDGET_EXCEEDED");
1989
+ visiting.add(value);
1990
+ let height = 0;
1991
+ for (const key of Reflect.ownKeys(value)) {
1992
+ if (++edges > 1e5) fail$1("DEFINITION_EDGE_BUDGET_EXCEEDED");
1993
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
1994
+ if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable && !(Array.isArray(value) && key === "length")) fail$1("DEFINITION_NOT_DATA");
1995
+ height = Math.max(height, 1 + visit(descriptor.value, depth + 1));
1996
+ }
1997
+ visiting.delete(value);
1998
+ heights.set(value, height);
1999
+ return height;
2000
+ }
2001
+ visit(root, 0);
2002
+ }
2003
+ /** Count output occurrences, not identities, before allocating each copied value. */
2004
+ function snapshot(input) {
2005
+ let remaining = 1e5;
2006
+ function copy(value, depth) {
2007
+ if (--remaining < 0) fail$1("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
2008
+ if (depth > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
2009
+ if (value === null || typeof value !== "object") return value;
2010
+ if (Array.isArray(value)) {
2011
+ const output = [];
2012
+ for (const item of value) output.push(copy(item, depth + 1));
2013
+ return output;
2014
+ }
2015
+ const output = {};
2016
+ for (const [key, item] of Object.entries(value)) Object.defineProperty(output, key, {
2017
+ value: copy(item, depth + 1),
2018
+ enumerable: true,
2019
+ writable: true,
2020
+ configurable: true
2021
+ });
2022
+ return output;
2023
+ }
2024
+ return copy(input, 0);
2025
+ }
2026
+ function snapshotDefinition(input) {
2027
+ inspectDefinition(input);
2028
+ return snapshot(input);
2029
+ }
2030
+ function exactDefinition(value, keys) {
2031
+ if (!value || typeof value !== "object" || Array.isArray(value)) fail$1("DEFINITION_NOT_DATA");
2032
+ if (Object.keys(value).some((key) => !keys.includes(key))) fail$1("DEFINITION_UNKNOWN_FIELD");
2033
+ }
2034
+ const outbound = {
2035
+ direct: Object.freeze({ builtin: "DIRECT" }),
2036
+ reject: Object.freeze({ builtin: "REJECT" }),
2037
+ rejectDrop: Object.freeze({ builtin: "REJECT-DROP" }),
2038
+ rejectNoDrop: Object.freeze({ builtin: "REJECT-NO-DROP" }),
2039
+ rejectTinyGif: Object.freeze({ builtin: "REJECT-TINYGIF" })
2040
+ };
2041
+ function defineProxyGroup(input) {
2042
+ inspectDefinition(input);
2043
+ exactDefinition(input, [
2044
+ "id",
2045
+ "name",
2046
+ "algorithm",
2047
+ "members",
2048
+ "url",
2049
+ "intervalSeconds",
2050
+ "timeoutSeconds"
2051
+ ]);
2052
+ if (!input.algorithm || ![
2053
+ "select",
2054
+ "surge-smart",
2055
+ "urltest"
2056
+ ].includes(input.algorithm.type)) fail$1("UNSUPPORTED_GROUP_ALGORITHM");
2057
+ exactDefinition(input.algorithm, input.algorithm.type === "urltest" ? [
2058
+ "type",
2059
+ "url",
2060
+ "intervalSeconds",
2061
+ "toleranceMs"
2062
+ ] : ["type"]);
2063
+ if (!Array.isArray(input.members)) fail$1("INVALID_GROUP_DEFINITION");
2064
+ return {
2065
+ ...input,
2066
+ type: "proxy-group",
2067
+ algorithm: { ...input.algorithm },
2068
+ members: [...input.members]
2069
+ };
2070
+ }
2071
+ function defineRoute(input) {
2072
+ inspectDefinition(input);
2073
+ exactDefinition(input, ["when", "to"]);
2074
+ return {
2075
+ ...input,
2076
+ type: "route"
2077
+ };
2078
+ }
2079
+ function defineRoutes(input) {
2080
+ inspectDefinition(input);
2081
+ exactDefinition(input, ["when", "to"]);
2082
+ if (!Array.isArray(input.when)) fail$1("INVALID_ROUTE_DEFINITION");
2083
+ return input.when.map((when) => ({
2084
+ type: "route",
2085
+ when,
2086
+ to: input.to
2087
+ }));
2088
+ }
2089
+ function selectProxies(nodes, query = {}) {
2090
+ inspectDefinition({
2091
+ nodes,
2092
+ query
2093
+ });
2094
+ exactDefinition(query, [
2095
+ "ids",
2096
+ "regions",
2097
+ "providers",
2098
+ "tags"
2099
+ ]);
2100
+ if (!Array.isArray(nodes) || nodes.some((node) => !node || typeof node !== "object")) fail$1("DEFINITION_NOT_DATA");
2101
+ for (const values of Object.values(query)) if (values !== void 0 && !Array.isArray(values)) fail$1("DEFINITION_NOT_DATA");
2102
+ return nodes.filter((node) => (!query.ids || query.ids.includes(node.id)) && (!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))));
2103
+ }
2104
+ function defineSurgeProfile(input) {
2105
+ inspectDefinition(input);
2106
+ exactDefinition(input, [
2107
+ "target",
2108
+ "managed",
2109
+ "general",
2110
+ "hosts",
2111
+ "nodes",
2112
+ "tunnels",
2113
+ "names",
2114
+ "groups",
2115
+ "routes",
2116
+ "fallback"
2117
+ ]);
2118
+ if (!Array.isArray(input.nodes) || !Array.isArray(input.groups) || !Array.isArray(input.routes) || input.tunnels !== void 0 && !Array.isArray(input.tunnels)) fail$1("DEFINITION_NOT_DATA");
2119
+ const registry = /* @__PURE__ */ new Map();
2120
+ const names = Object.assign(Object.create(null), input.names);
2121
+ for (const resource of [
2122
+ ...input.nodes,
2123
+ ...input.tunnels ?? [],
2124
+ ...input.groups
2125
+ ]) {
2126
+ if (!resource || typeof resource !== "object" || typeof resource.id !== "string") fail$1("INVALID_RESOURCE_DEFINITION");
2127
+ if (registry.has(resource.id)) fail$1("DUPLICATE_RESOURCE_ID");
2128
+ registry.set(resource.id, resource);
2129
+ const name = resource.type === "proxy-group" ? resource.name : "label" in resource ? resource.label ?? resource.id : resource.id;
2130
+ if (resource.type === "proxy-group" && names[resource.id] !== void 0 && names[resource.id] !== name) fail$1("GROUP_NAME_CONFLICT");
2131
+ Object.defineProperty(names, resource.id, {
2132
+ value: names[resource.id] ?? name,
2133
+ enumerable: true,
2134
+ configurable: true,
2135
+ writable: true
2136
+ });
2137
+ }
2138
+ function lower(destination) {
2139
+ if (!destination || typeof destination !== "object") fail$1("INVALID_DESTINATION");
2140
+ if ("builtin" in destination) {
2141
+ exactDefinition(destination, ["builtin"]);
2142
+ if (!Object.values(outbound).some((value) => value.builtin === destination.builtin)) fail$1("INVALID_DESTINATION");
2143
+ return { builtin: destination.builtin };
2144
+ }
2145
+ if (registry.get(destination.id) !== destination) fail$1("UNREGISTERED_DESTINATION_INSTANCE");
2146
+ return { ref: destination.id };
2147
+ }
2148
+ const groups = input.groups.map((definition) => {
2149
+ exactDefinition(definition, [
2150
+ "type",
2151
+ "id",
2152
+ "name",
2153
+ "algorithm",
2154
+ "members",
2155
+ "url",
2156
+ "intervalSeconds",
2157
+ "timeoutSeconds"
2158
+ ]);
2159
+ if (definition.type !== "proxy-group") fail$1("INVALID_GROUP_DEFINITION");
2160
+ if (!definition.algorithm || !["select", "surge-smart"].includes(definition.algorithm.type)) fail$1("UNSUPPORTED_GROUP_ALGORITHM");
2161
+ exactDefinition(definition.algorithm, ["type"]);
2162
+ if (!Array.isArray(definition.members)) fail$1("INVALID_GROUP_DEFINITION");
2163
+ const { id, url, intervalSeconds, timeoutSeconds } = definition;
2164
+ return {
2165
+ id,
2166
+ type: definition.algorithm.type === "select" ? "select" : "smart",
2167
+ members: definition.members.map(lower),
2168
+ ...url === void 0 ? {} : { url },
2169
+ ...intervalSeconds === void 0 ? {} : { intervalSeconds },
2170
+ ...timeoutSeconds === void 0 ? {} : { timeoutSeconds }
2171
+ };
2172
+ });
2173
+ const rules = input.routes.map((definition) => {
2174
+ exactDefinition(definition, [
2175
+ "type",
2176
+ "when",
2177
+ "to"
2178
+ ]);
2179
+ if (definition.type !== "route") fail$1("INVALID_ROUTE_DEFINITION");
2180
+ return {
2181
+ when: definition.when,
2182
+ then: lower(definition.to)
2183
+ };
2184
+ });
2185
+ const { routes: _routes, groups: _groups, fallback, ...rest } = input;
2186
+ return snapshot({
2187
+ ...rest,
2188
+ names,
2189
+ groups,
2190
+ rules,
2191
+ fallback: lower(fallback)
2192
+ });
2193
+ }
2194
+ function condition(value) {
2195
+ inspectDefinition(value);
2196
+ return value;
2197
+ }
2198
+ function atom(type) {
2199
+ return (value, options = {}) => {
2200
+ inspectDefinition(options);
2201
+ return condition({
2202
+ ...options,
2203
+ type,
2204
+ value
2205
+ });
2206
+ };
2207
+ }
2208
+ const surgeMatch = {
2209
+ domain: atom("domain"),
2210
+ domainSuffix: atom("domainSuffix"),
2211
+ ipCidr: atom("ipCidr"),
2212
+ ipCidr6: atom("ipCidr6"),
2213
+ sourceIp: atom("sourceIp"),
2214
+ processName: atom("processName"),
2215
+ macAddress: atom("macAddress"),
2216
+ network: (value, options = {}) => {
2217
+ inspectDefinition(options);
2218
+ return condition({
2219
+ ...options,
2220
+ type: "network",
2221
+ value
2222
+ });
2223
+ },
2224
+ port: (from, to, options = {}) => {
2225
+ inspectDefinition(options);
2226
+ return condition({
2227
+ ...options,
2228
+ type: "port",
2229
+ from,
2230
+ ...to === void 0 ? {} : { to }
2231
+ });
2232
+ },
2233
+ sourcePort: (from, to, options = {}) => {
2234
+ inspectDefinition(options);
2235
+ return condition({
2236
+ ...options,
2237
+ type: "sourcePort",
2238
+ from,
2239
+ ...to === void 0 ? {} : { to }
2240
+ });
2241
+ },
2242
+ all: (conditions, options = {}) => {
2243
+ inspectDefinition({
2244
+ conditions,
2245
+ options
2246
+ });
2247
+ return condition({
2248
+ ...options,
2249
+ type: "all",
2250
+ conditions: [...conditions]
2251
+ });
2252
+ },
2253
+ any: (conditions, options = {}) => {
2254
+ inspectDefinition({
2255
+ conditions,
2256
+ options
2257
+ });
2258
+ return condition({
2259
+ ...options,
2260
+ type: "any",
2261
+ conditions: [...conditions]
2262
+ });
2263
+ },
2264
+ not: (value, options = {}) => {
2265
+ inspectDefinition({
2266
+ value,
2267
+ options
2268
+ });
2269
+ return condition({
2270
+ ...options,
2271
+ type: "not",
2272
+ condition: value
2273
+ });
2274
+ },
2275
+ ruleSet: (options) => {
2276
+ inspectDefinition(options);
2277
+ return condition({
2278
+ ...options,
2279
+ type: "ruleSet"
2280
+ });
2281
+ }
2282
+ };
2283
+ //#endregion
2284
+ //#region src/profile.ts
2285
+ const fail = (code) => {
2286
+ throw new ProfileDefinitionError(code);
2287
+ };
2288
+ /** Keep aliases across nodes, groups and destinations; reject accessors before cloning. */
2289
+ function snapshotProfile(input) {
2290
+ inspectDefinition(input);
2291
+ return deepFreeze(structuredClone(input));
2292
+ }
2293
+ function surgeConfig(input) {
2294
+ inspectDefinition(input);
2295
+ exactDefinition(input, [
2296
+ "managed",
2297
+ "general",
2298
+ "hosts",
2299
+ "names"
2300
+ ]);
2301
+ return snapshotProfile(input);
2302
+ }
2303
+ function defineProfile(input) {
2304
+ inspectDefinition(input);
2305
+ exactDefinition(input, [
2306
+ "target",
2307
+ "nodes",
2308
+ "groups",
2309
+ "routes",
2310
+ "fallback",
2311
+ "endpoints",
2312
+ "surge",
2313
+ "singBox"
2314
+ ]);
2315
+ exactDefinition(input.target, [
2316
+ "engine",
2317
+ "platform",
2318
+ "version"
2319
+ ]);
2320
+ if (input.surge !== void 0) exactDefinition(input.surge, [
2321
+ "managed",
2322
+ "general",
2323
+ "hosts",
2324
+ "names"
2325
+ ]);
2326
+ if (input.singBox !== void 0) {
2327
+ exactDefinition(input.singBox, ["mode", "listener"]);
2328
+ if (!["fragment", "standalone"].includes(input.singBox.mode)) fail("INVALID_PROFILE_DEFINITION");
2329
+ if (input.singBox.listener !== void 0) exactDefinition(input.singBox.listener, ["port", "resolver"]);
1778
2330
  }
1779
- const config = deepFreeze(parsed.data);
1780
- const expanded = /* @__PURE__ */ new Map();
1781
- if (Object.keys(config.programs).length === 0) error("EMPTY_PROGRAMS", "programs", "至少需要一个程序");
1782
- for (const [name, program] of Object.entries(config.programs)) {
1783
- const path = `programs.${name}`;
1784
- for (const node of program.nodes) if (!isIP(node.server)) error("PROXY_HOSTNAME_MODE_UNSUPPORTED", `${path}.nodes.${node.id}`, "域名代理地址目前仅允许节点片段入口");
1785
- validateRuleSets(program.routing, program.engine, diagnostics, path);
1786
- const rules = lowerRuleSets(expandRules(program.routing, diagnostics, name), diagnostics, path);
1787
- expanded.set(name, rules);
1788
- const endpoints = program.endpoints ?? [];
1789
- const resources = [
1790
- ...program.nodes,
1791
- ...program.groups,
1792
- ...endpoints
1793
- ];
1794
- const byId = new Map(resources.map((resource) => [resource.id, resource]));
1795
- if (byId.size !== resources.length) error("DUPLICATE_RESOURCE", path, "节点、组与端点共用唯一 ID 命名空间");
1796
- const edges = new Map(resources.map((resource) => [resource.id, "members" in resource ? resource.members : "via" in resource && resource.via ? [resource.via] : []]));
1797
- for (const [id, refs] of edges) for (const ref of refs) if (!byId.has(ref)) error("MISSING_REFERENCE", `${path}.${id}`, "节点或组引用不存在");
1798
- for (const [id, refs] of edges) for (const ref of refs) if (byId.get(ref)?.type === "sing-box-tailscale") error("ENDPOINT_REFERENCE_UNSUPPORTED", `${path}.${id}`, "端点只能由 route 引用,不能作为组成员或 via");
1799
- for (let i = 0; i < endpoints.length; i++) for (let j = 0; j < i; j++) if (pathsOverlap(endpoints[i].stateDirectory, endpoints[j].stateDirectory)) error("ENDPOINT_STATE_OVERLAP", `${path}.endpoints.${endpoints[i].id}`, "端点状态目录不能重复或互为祖先");
1800
- const states = /* @__PURE__ */ new Map();
1801
- const tcpOnly = /* @__PURE__ */ new Map();
1802
- const visit = (id) => {
1803
- if (states.get(id) === 1) {
1804
- error("RESOURCE_CYCLE", `${path}.${id}`, "组成员和 via 拨号依赖不能形成循环");
1805
- return true;
1806
- }
1807
- if (states.get(id) === 2) return tcpOnly.get(id) ?? false;
1808
- states.set(id, 1);
1809
- const item = byId.get(id);
1810
- let limited = !!item && "server" in item && nodeIsTcpOnly(item, program.engine);
1811
- for (const ref of edges.get(id) ?? []) limited = visit(ref) || limited;
1812
- states.set(id, 2);
1813
- tcpOnly.set(id, limited);
1814
- return limited;
1815
- };
1816
- if (resources.length > 1e3) error("RESOURCE_LIMIT", path, "单程序最多 1000 个节点、组与端点");
1817
- else for (const id of byId.keys()) visit(id);
1818
- const validateAction = (action, where, udpPossible) => {
1819
- if (action.type !== "route") return;
1820
- if (!byId.has(action.to)) error("MISSING_REFERENCE", where, "路由出口不存在");
1821
- else if (udpPossible && tcpOnly.get(action.to)) error("NETWORK_UNSUPPORTED", where, "出口的可选或 via 路径含 TCP-only 节点;请用 network(tcp) 限定规则,且不能用于 fallback");
1822
- };
1823
- for (const rule of rules) validateAction(rule.then, rule.id, truthPossibilities(rule.when, "udp").includes(true));
1824
- const validateBindings = (entries, prefix) => {
1825
- for (const entry of entries) {
1826
- if (entry.type === "block") validateBindings(entry.rules, `${prefix}/${entry.id}`);
1827
- if (entry.type === "use") {
1828
- for (const [key, action] of Object.entries(entry.bindings)) if (action.type !== "slot") validateAction(action, `${prefix}/${entry.id}/bindings/${key}`, false);
1829
- validateBindings(entry.policy.rules, `${prefix}/${entry.id}`);
1830
- }
1831
- }
2331
+ if (!Array.isArray(input.nodes) || !Array.isArray(input.groups) || !Array.isArray(input.routes) || input.endpoints !== void 0 && !Array.isArray(input.endpoints)) fail("INVALID_PROFILE_DEFINITION");
2332
+ return snapshotProfile(input);
2333
+ }
2334
+ function surgeCondition$1(condition, depth = 0) {
2335
+ if (depth > 10) return fail("LOGICAL_DEPTH_EXCEEDED");
2336
+ if (condition.type === "nativeRuleSet" || condition.type === "ruleSet" && "when" in condition) {
2337
+ const parsed = matchSchema.safeParse(condition);
2338
+ if (!parsed.success) return fail("PROFILE_CONDITION_UNSUPPORTED");
2339
+ const value = parsed.data;
2340
+ if (value.type === "ruleSet") return surgeCondition$1(value.when, depth);
2341
+ if (value.type !== "nativeRuleSet" || value.engine !== "surge" || value.intervalSeconds !== void 0) return fail("PROFILE_CONDITION_UNSUPPORTED");
2342
+ return {
2343
+ type: "ruleSet",
2344
+ format: value.format,
2345
+ url: value.url
1832
2346
  };
1833
- validateBindings(program.routing, name);
1834
- validateAction(program.fallback, `${path}.fallback`, true);
1835
2347
  }
1836
- const targetIds = /* @__PURE__ */ new Set();
1837
- for (const target of config.targets) {
1838
- const path = `targets.${target.id}`;
1839
- if (targetIds.has(target.id)) error("DUPLICATE_TARGET", path, "构建目标 ID 重复");
1840
- targetIds.add(target.id);
1841
- const descriptor = targetCatalog.find((item) => item.engine === target.engine && item.version === target.version && item.platforms.includes(target.platform));
1842
- if (!descriptor) {
1843
- error("UNKNOWN_TARGET", path, "目标引擎、精确版本和平台组合不在支持目录中", target.id);
1844
- continue;
1845
- }
1846
- const originalProgram = config.programs[target.program];
1847
- const lowered = lowerStrategies(originalProgram?.groups ?? [], target, diagnostics, path);
1848
- const program = originalProgram ? {
1849
- ...originalProgram,
1850
- groups: lowered.groups
1851
- } : void 0;
1852
- if (!program) {
1853
- error("MISSING_PROGRAM", path, "目标引用的程序不存在", target.id);
1854
- continue;
1855
- }
1856
- if (program.engine !== target.engine) error("ENGINE_MISMATCH", path, "平台程序与目标引擎不一致", target.id);
1857
- if (target.mode === "standalone" && !program.listener) error("LISTENER_REQUIRED", path, "standalone 必须声明 loopback listener 与 IP DNS resolver", target.id);
1858
- if (target.mode !== "standalone" && program.listener) error("UNUSED_LISTENER", path, "fragment 不能静默忽略 listener;请使用独立程序或 standalone 目标", target.id);
1859
- for (const endpoint of program.endpoints ?? []) {
1860
- if (!descriptor.endpoints.includes(endpoint.type)) error("ENDPOINT_UNSUPPORTED", `${path}.endpoints.${endpoint.id}`, "Tailscale 端点仅支持 sing-box 1.12.0", target.id);
1861
- if (target.mode !== "standalone") error("ENDPOINT_MODE_UNSUPPORTED", `${path}.endpoints.${endpoint.id}`, "Tailscale 需要 standalone 的普通 DNS/final 隔离引导解析", target.id);
1862
- }
1863
- for (const node of program.nodes) {
1864
- validateProxyOptions(node, target, diagnostics);
1865
- if (!descriptor.protocols.includes(node.type)) error("PROTOCOL_UNSUPPORTED", `${path}.nodes.${node.id}`, "目标版本不支持该代理协议", target.id);
1866
- if (node.label) diagnostics.push({
1867
- severity: "warning",
1868
- code: "LABEL_NOT_EMITTED",
1869
- path: `${path}.nodes.${node.id}.label`,
1870
- target: target.id,
1871
- message: "原生节点使用稳定 ID;展示 label 不写入配置,不影响路由"
1872
- });
1873
- }
1874
- for (const group of program.groups) if (!descriptor.groups.includes(group.type)) error("GROUP_UNSUPPORTED", `${path}.groups.${group.id}`, "目标未实现该组机制;不会自动替换为另一种组", target.id);
1875
- validateSmartMembers(program.groups, new Set(program.nodes.map((n) => n.id)), diagnostics, path);
1876
- const rules = expanded.get(target.program);
1877
- if (target.engine === "mihomo" || target.engine === "stash") validateClashTarget(target, rules, diagnostics);
1878
- if (target.engine === "surge") {
1879
- for (const rule of rules) if (logicalDepth(rule.when) > 10) error("LOGICAL_DEPTH", rule.id, "Surge 逻辑条件最多嵌套 10 层", target.id);
2348
+ if (condition.type === "all" || condition.type === "any") {
2349
+ if (!Array.isArray(condition.conditions)) return fail("PROFILE_CONDITION_UNSUPPORTED");
2350
+ if (condition.conditions.length === 1) {
2351
+ exactDefinition(condition, ["type", "conditions"]);
2352
+ return surgeCondition$1(condition.conditions[0], depth + 1);
1880
2353
  }
1881
- const nativeRuleSets = collectNativeRuleSets(rules, target, diagnostics);
1882
- for (const resource of nativeRuleSets) if (!descriptor.nativeRuleSets.includes(resource.format)) error("RULESET_UNSUPPORTED", `${path}.ruleSets.${resource.id}`, "精确目标不支持此原生规则资源格式", target.id);
1883
- plans.push({
1884
- nativeRuleSets,
1885
- target,
1886
- program,
1887
- rules,
1888
- strategySelections: lowered.selections,
1889
- sourceMap: rules.map((rule, nativeIndex) => ({
1890
- rule: rule.id,
1891
- nativeIndex,
1892
- origin: rule.origin
1893
- })),
1894
- preconditions: [
1895
- ...nativeRuleSets.length ? ["原生外部规则由客户端持续下载和解释;静态布尔结果不验证 DNS 等副作用。缓存与下载失败处理沿用客户端机制,fragment 运行方提供工作目录与下载 DNS 路径。"] : [],
1896
- ...program.endpoints?.length ? [
1897
- "Tailscale 需要 with_tailscale 构建标签;运行方负责登录、路由批准及每实例独占身份目录。构建不注册 tailnet。",
1898
- "状态目录真实路径必须独立于产物与清理范围;output 重叠检查仅为词法检查,不能证明运行主机符号链接隔离。",
1899
- "普通 DNS/final 与端点控制面引导 DNS 分离;未配置 MagicDNS,私有域名须由运行方提供适用的普通解析器。"
1900
- ] : [],
1901
- ...target.engine === "surge" && program.nodes.some((node) => node.type === "vmess") ? ["Surge VMess 的 TCP-only 由语言路由检查保证;fragment 组合方不得额外引入通往此节点的 UDP 路由。"] : [],
1902
- ...target.engine === "stash" ? ["Stash 4.2.1 原生未验证;block-quic: off 按现行文档编码,历史版本 QUIC 行为未验证。"] : [],
1903
- "规则只匹配已观测元数据;不自动嗅探或为了 IP 条件解析域名。",
1904
- "节点 server 与 via 各跳必须是 IP;运行时组选择、代理连通性不由静态解释保证。",
1905
- ...target.mode !== "standalone" ? ["此配置是 fragment,组合方负责入口、直接 DNS 解析路径及 source/domain/IP 元数据来源。"] : ["仅本机 loopback 显式代理;不是 TUN 或 LAN 网关。DNS 上游固定直连。"]
1906
- ],
1907
- nativeValidation: "not-run"
1908
- });
2354
+ return {
2355
+ ...condition,
2356
+ conditions: condition.conditions.map((child) => surgeCondition$1(child, depth + 1))
2357
+ };
1909
2358
  }
1910
- const caseIds = /* @__PURE__ */ new Set();
1911
- for (const test of config.cases ?? []) {
1912
- if (caseIds.has(test.id)) error("DUPLICATE_CASE", `cases.${test.id}`, "案例 ID 重复");
1913
- caseIds.add(test.id);
1914
- const program = config.programs[test.program];
1915
- if (!program) {
1916
- error("MISSING_PROGRAM", `cases.${test.id}`, "案例引用的程序不存在");
1917
- continue;
2359
+ if (condition.type === "not") return {
2360
+ ...condition,
2361
+ condition: surgeCondition$1(condition.condition, depth + 1)
2362
+ };
2363
+ if (condition.type === "ipCidr" && isIP(condition.value.split("/")[0]) === 6) return {
2364
+ ...condition,
2365
+ type: "ipCidr6"
2366
+ };
2367
+ return condition;
2368
+ }
2369
+ /** No secrets or I/O. All engine adaptations retain strict validation. */
2370
+ function compileProfile(input) {
2371
+ try {
2372
+ const profile = defineProfile(input);
2373
+ snapshotDefinition(profile.routes.map((route) => route.when));
2374
+ if (profile.target.engine === "surge") {
2375
+ if (profile.singBox !== void 0) fail("PROFILE_EXTENSION_UNSUPPORTED");
2376
+ if (profile.endpoints?.some((endpoint) => endpoint.type === "sing-box-tailscale")) fail("PROFILE_ENDPOINT_UNSUPPORTED");
2377
+ const compilation = compileSurgeProfile(defineSurgeProfile({
2378
+ target: profile.target,
2379
+ ...profile.surge,
2380
+ nodes: profile.nodes,
2381
+ tunnels: profile.endpoints,
2382
+ groups: profile.groups,
2383
+ routes: profile.routes.map((route) => ({
2384
+ ...route,
2385
+ when: surgeCondition$1(route.when)
2386
+ })),
2387
+ fallback: profile.fallback
2388
+ }));
2389
+ return {
2390
+ engine: "surge",
2391
+ ok: compilation.ok,
2392
+ compilation
2393
+ };
1918
2394
  }
1919
- let actual;
1920
- try {
1921
- actual = explainRules(expanded.get(test.program), program.fallback, test.request);
1922
- } catch (cause) {
1923
- if (!(cause instanceof StaticRuleSetUnknownError)) throw cause;
1924
- cases.push({
1925
- id: test.id,
1926
- passed: false,
1927
- code: "CASE_INDETERMINATE"
1928
- });
1929
- error("CASE_INDETERMINATE", `cases.${test.id}`, "外部规则内容未知,无法静态确定首命中");
1930
- continue;
2395
+ if (profile.target.engine !== "sing-box") return fail("PROFILE_TARGET_UNSUPPORTED");
2396
+ if (profile.surge !== void 0) fail("PROFILE_EXTENSION_UNSUPPORTED");
2397
+ if (profile.endpoints?.some((endpoint) => endpoint.type !== "sing-box-tailscale")) fail("PROFILE_ENDPOINT_UNSUPPORTED");
2398
+ const registry = /* @__PURE__ */ new Map();
2399
+ for (const resource of [
2400
+ ...profile.nodes,
2401
+ ...profile.groups,
2402
+ ...profile.endpoints ?? []
2403
+ ]) {
2404
+ if (!resource || typeof resource.id !== "string") fail("INVALID_RESOURCE_DEFINITION");
2405
+ if (registry.has(resource.id)) fail("DUPLICATE_RESOURCE_ID");
2406
+ registry.set(resource.id, resource);
1931
2407
  }
1932
- const passed = (test.expect.rule === void 0 || test.expect.rule === actual.rule) && sameAction(test.expect.action, actual.action);
1933
- cases.push({
1934
- id: test.id,
1935
- passed,
1936
- actual: {
1937
- rule: actual.rule,
1938
- action: actual.action
2408
+ const lower = (destination) => {
2409
+ if (!destination || typeof destination !== "object") return fail("INVALID_DESTINATION");
2410
+ if ("builtin" in destination) {
2411
+ exactDefinition(destination, ["builtin"]);
2412
+ if (destination.builtin === "DIRECT") return { type: "direct" };
2413
+ if (destination.builtin === "REJECT") return { type: "reject" };
2414
+ return fail("PROFILE_DESTINATION_UNSUPPORTED");
1939
2415
  }
2416
+ if (registry.get(destination.id) !== destination) fail("UNREGISTERED_DESTINATION_INSTANCE");
2417
+ return {
2418
+ type: "route",
2419
+ to: destination.id
2420
+ };
2421
+ };
2422
+ const groups = profile.groups.map((definition) => {
2423
+ exactDefinition(definition, [
2424
+ "type",
2425
+ "id",
2426
+ "name",
2427
+ "algorithm",
2428
+ "members",
2429
+ "url",
2430
+ "intervalSeconds",
2431
+ "timeoutSeconds"
2432
+ ]);
2433
+ if (definition.type !== "proxy-group" || typeof definition.name !== "string" || !definition.name.trim()) fail("INVALID_GROUP_DEFINITION");
2434
+ if (definition.url !== void 0 || definition.intervalSeconds !== void 0 || definition.timeoutSeconds !== void 0) fail("PROFILE_GROUP_OPTIONS_UNSUPPORTED");
2435
+ exactDefinition(definition.algorithm, definition.algorithm.type === "urltest" ? [
2436
+ "type",
2437
+ "url",
2438
+ "intervalSeconds",
2439
+ "toleranceMs"
2440
+ ] : ["type"]);
2441
+ const members = definition.members.map((member) => {
2442
+ const action = lower(member);
2443
+ if (action.type !== "route") return fail("PROFILE_GROUP_MEMBER_UNSUPPORTED");
2444
+ return action.to;
2445
+ });
2446
+ return {
2447
+ ...definition.algorithm,
2448
+ id: definition.id,
2449
+ members
2450
+ };
1940
2451
  });
1941
- if (!passed) error("CASE_FAILED", `cases.${test.id}`, "请求的首命中规则或逻辑出口不符合预期");
1942
- }
1943
- if (config.warningsAsErrors) {
1944
- for (let i = 0; i < diagnostics.length; i++) if (diagnostics[i].severity === "warning") diagnostics[i] = {
1945
- ...diagnostics[i],
1946
- severity: "error"
2452
+ const routing = profile.routes.map((route, index) => {
2453
+ exactDefinition(route, [
2454
+ "type",
2455
+ "when",
2456
+ "to"
2457
+ ]);
2458
+ if (route.type !== "route") fail("INVALID_ROUTE_DEFINITION");
2459
+ return {
2460
+ type: "rule",
2461
+ id: `route-${index + 1}`,
2462
+ when: route.when,
2463
+ then: lower(route.to)
2464
+ };
2465
+ });
2466
+ const compilation = compile(snapshotDefinition({
2467
+ programs: { profile: {
2468
+ engine: "sing-box",
2469
+ nodes: profile.nodes,
2470
+ endpoints: profile.endpoints,
2471
+ groups,
2472
+ routing,
2473
+ fallback: lower(profile.fallback),
2474
+ ...profile.singBox?.listener ? { listener: profile.singBox.listener } : {}
2475
+ } },
2476
+ targets: [{
2477
+ ...profile.target,
2478
+ id: "profile",
2479
+ program: "profile",
2480
+ mode: profile.singBox?.mode ?? "fragment"
2481
+ }]
2482
+ }));
2483
+ return {
2484
+ engine: "sing-box",
2485
+ ok: compilation.ok,
2486
+ compilation
2487
+ };
2488
+ } catch (error) {
2489
+ return {
2490
+ engine: "invalid",
2491
+ ok: false,
2492
+ code: error instanceof ProfileDefinitionError ? error.code : "INVALID_PROFILE_DEFINITION"
1947
2493
  };
1948
2494
  }
1949
- const ok = !diagnostics.some((d) => d.severity === "error");
1950
- return deepFreeze({
1951
- ok,
1952
- diagnostics,
1953
- plans: ok ? plans : [],
1954
- cases
1955
- });
1956
2495
  }
1957
- function sameAction(a, b) {
1958
- return a.type === b.type && (a.type !== "route" || b.type === "route" && a.to === b.to);
2496
+ //#endregion
2497
+ //#region src/proxy-builder.ts
2498
+ /** Fluent construction is separate from the plain-data node consumed by the compiler. */
2499
+ function proxyBuilder(node) {
2500
+ assertData(node);
2501
+ const copy = deepFreeze(structuredClone(node));
2502
+ const fork = (patch) => proxyBuilder({
2503
+ ...copy,
2504
+ ...patch
2505
+ });
2506
+ return Object.freeze({
2507
+ via: (id) => fork({ via: id }),
2508
+ label: (text) => fork({ label: text }),
2509
+ tcpFastOpen: (enabled) => fork({ tcpFastOpen: enabled }),
2510
+ build: () => deepFreeze(structuredClone(copy))
2511
+ });
1959
2512
  }
1960
- function explain(compilation, target, request) {
1961
- if (!compilation.ok) throw new Error("COMPILATION_FAILED");
1962
- const plan = compilation.plans.find((plan) => plan.target.id === target);
1963
- if (!plan) throw new Error("UNKNOWN_TARGET");
1964
- return explainRules(plan.rules, plan.program.fallback, request);
2513
+ //#endregion
2514
+ //#region src/dsl.ts
2515
+ const ruleSet = (definition) => ({
2516
+ ...definition,
2517
+ type: "ruleSet"
2518
+ });
2519
+ const match = {
2520
+ ruleSet: (set) => set,
2521
+ domain: (value) => ({
2522
+ type: "domain",
2523
+ value
2524
+ }),
2525
+ domainSuffix: (value) => ({
2526
+ type: "domainSuffix",
2527
+ value
2528
+ }),
2529
+ ipCidr: (value) => ({
2530
+ type: "ipCidr",
2531
+ value
2532
+ }),
2533
+ sourceIp: (value) => ({
2534
+ type: "sourceIp",
2535
+ value
2536
+ }),
2537
+ port: (from, to = from) => ({
2538
+ type: "port",
2539
+ from,
2540
+ to
2541
+ }),
2542
+ sourcePort: (from, to = from) => ({
2543
+ type: "sourcePort",
2544
+ from,
2545
+ to
2546
+ }),
2547
+ network: (value) => ({
2548
+ type: "network",
2549
+ value
2550
+ }),
2551
+ all: (...conditions) => ({
2552
+ type: "all",
2553
+ conditions
2554
+ }),
2555
+ any: (...conditions) => ({
2556
+ type: "any",
2557
+ conditions
2558
+ }),
2559
+ not: (condition) => ({
2560
+ type: "not",
2561
+ condition
2562
+ })
2563
+ };
2564
+ const direct = () => ({ type: "direct" });
2565
+ const reject = () => ({ type: "reject" });
2566
+ const route = (to) => ({
2567
+ type: "route",
2568
+ to
2569
+ });
2570
+ /** An exit parameter declared by policy.exits and resolved by use.bindings. */
2571
+ const slot = (name) => ({
2572
+ type: "slot",
2573
+ name
2574
+ });
2575
+ const secret = (name) => ({
2576
+ type: "env",
2577
+ name
2578
+ });
2579
+ const rule = (id, when, then) => ({
2580
+ type: "rule",
2581
+ id,
2582
+ when,
2583
+ then
2584
+ });
2585
+ const block = (id, rules, when) => ({
2586
+ type: "block",
2587
+ id,
2588
+ rules,
2589
+ ...when ? { when } : {}
2590
+ });
2591
+ const policy = (definition) => ({
2592
+ type: "policy",
2593
+ ...definition
2594
+ });
2595
+ const use = (definition, options) => ({
2596
+ type: "use",
2597
+ id: options.id,
2598
+ policy: definition,
2599
+ bindings: options.bindings
2600
+ });
2601
+ const sequence = (...parts) => parts.flatMap((part) => Array.isArray(part) ? part : [part]);
2602
+ const defineConfig = (config) => config;
2603
+ /** Filtering is stable: catalogue order determines initial selector order. */
2604
+ function selectNodes(nodes, query = {}) {
2605
+ 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);
1965
2606
  }
1966
- //#endregion
1967
- //#region src/secrets.ts
1968
- /** One reader per rendering batch; exceptions and missing values never disclose credentials. */
1969
- function secretReader(resolveSecret) {
1970
- const values = /* @__PURE__ */ new Map();
1971
- return (token) => {
1972
- if (values.has(token.name)) return values.get(token.name);
1973
- let value;
1974
- try {
1975
- value = resolveSecret(token);
1976
- } catch {
1977
- throw new RenderError("SECRET_RESOLUTION_FAILED");
1978
- }
1979
- if (typeof value !== "string" || value.length === 0) throw new RenderError("SECRET_MISSING");
1980
- values.set(token.name, value);
1981
- return value;
1982
- };
2607
+ /** A shared strategy declares an algorithm or explicitly selects native implementations. */
2608
+ const strategy = (definition) => ({
2609
+ type: "strategy",
2610
+ ...definition
2611
+ });
2612
+ const group = {
2613
+ auto: () => ({ type: "auto" }),
2614
+ select: () => ({ type: "select" }),
2615
+ urltest: (options) => ({
2616
+ type: "urltest",
2617
+ ...options
2618
+ })
2619
+ };
2620
+ const surge$1 = {
2621
+ config: surgeConfig,
2622
+ match: surgeMatch,
2623
+ smart: () => ({ type: "surge-smart" }),
2624
+ ruleSet: (options) => ({
2625
+ format: "rule-set",
2626
+ ...options,
2627
+ type: "nativeRuleSet",
2628
+ engine: "surge"
2629
+ })
2630
+ };
2631
+ const mihomo = { ruleProvider: (options) => ({
2632
+ ...options,
2633
+ type: "nativeRuleSet",
2634
+ engine: "mihomo"
2635
+ }) };
2636
+ /** Protocol constructors keep credentials and options specific to their protocol. */
2637
+ function nodeConstructor(type) {
2638
+ return (options) => ({
2639
+ ...options,
2640
+ type
2641
+ });
1983
2642
  }
2643
+ const proxy = {
2644
+ builder: proxyBuilder,
2645
+ http: nodeConstructor("http"),
2646
+ trojan: nodeConstructor("trojan"),
2647
+ anytls: nodeConstructor("anytls"),
2648
+ shadowsocks: nodeConstructor("shadowsocks"),
2649
+ vmess: nodeConstructor("vmess"),
2650
+ vless: nodeConstructor("vless")
2651
+ };
2652
+ const singbox$1 = {
2653
+ ruleSet: (options) => ({
2654
+ ...options,
2655
+ type: "nativeRuleSet",
2656
+ engine: "sing-box"
2657
+ }),
2658
+ tailscale: (options) => ({
2659
+ ...options,
2660
+ type: "sing-box-tailscale"
2661
+ })
2662
+ };
1984
2663
  //#endregion
1985
2664
  //#region src/render.ts
1986
2665
  const DIRECT = "pl-direct";
@@ -2319,4 +2998,292 @@ async function buildToDirectory(compilation, output, resolveSecret = (token) =>
2319
2998
  };
2320
2999
  }
2321
3000
  //#endregion
2322
- export { slot as A, defineProxyGroup as B, route as C, selectNodes as D, secret as E, deepFreeze as F, defineSurgeProfile as H, 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, outbound as U, defineRoute as V, selectProxies as W, 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, ProfileDefinitionError as z };
3001
+ //#region src/surge-publish.ts
3002
+ var SurgePublishError = class extends Error {
3003
+ published;
3004
+ constructor(message, published) {
3005
+ super(message);
3006
+ this.published = published;
3007
+ }
3008
+ };
3009
+ async function publishProfiles(files, surgeDirectory, io = { rename }) {
3010
+ if (!files.size || files.size > 16 || [...files.keys()].some((name) => !/^[a-z0-9][a-z0-9-]*\.(?:conf|json)$/.test(name))) throw new Error("INVALID_PROFILE_FILENAMES");
3011
+ const root = resolve(surgeDirectory);
3012
+ const generations = join(root, ".generations");
3013
+ const id = randomUUID();
3014
+ const generation = join(generations, id);
3015
+ const pointer = join(root, `.out-${id}`);
3016
+ const output = join(root, "out");
3017
+ const backup = join(generations, `legacy-${id}`);
3018
+ const lock = join(root, ".build-lock");
3019
+ const remove = io.rm ?? rm;
3020
+ let failure;
3021
+ let locked = false, created = false, committed = false, movedLegacy = false, recoveryFailed = false;
3022
+ async function directory(path) {
3023
+ await mkdir(path, {
3024
+ recursive: true,
3025
+ mode: 448
3026
+ });
3027
+ const stat = await lstat(path);
3028
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
3029
+ }
3030
+ try {
3031
+ await directory(root);
3032
+ try {
3033
+ await mkdir(lock, { mode: 448 });
3034
+ locked = true;
3035
+ } catch (error) {
3036
+ if (error.code === "EEXIST") throw new Error("OUTPUT_LOCKED");
3037
+ throw error;
3038
+ }
3039
+ await directory(generations);
3040
+ let previous;
3041
+ try {
3042
+ previous = await lstat(output);
3043
+ } catch (error) {
3044
+ if (error.code !== "ENOENT") throw error;
3045
+ }
3046
+ if (previous?.isSymbolicLink()) {
3047
+ const target = await readlink(output);
3048
+ if (!/^\.generations\/(?:legacy-)?[a-f0-9-]{36}$/.test(target)) throw new Error("UNMANAGED_OUTPUT_LINK");
3049
+ const stat = await lstat(join(root, target));
3050
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
3051
+ } else if (previous && !previous.isDirectory()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
3052
+ await mkdir(generation, { mode: 448 });
3053
+ created = true;
3054
+ for (const [name, content] of files) await writeFile(join(generation, name), content, {
3055
+ mode: 384,
3056
+ flag: "wx"
3057
+ });
3058
+ await symlink(`.generations/${id}`, pointer, "dir");
3059
+ if (previous?.isDirectory()) {
3060
+ await io.rename(output, backup);
3061
+ movedLegacy = true;
3062
+ }
3063
+ try {
3064
+ await io.rename(pointer, output);
3065
+ committed = true;
3066
+ } catch (error) {
3067
+ if (movedLegacy) try {
3068
+ await io.rename(backup, output);
3069
+ movedLegacy = false;
3070
+ } catch {
3071
+ recoveryFailed = true;
3072
+ throw new Error("PUBLISH_RECOVERY_REQUIRED");
3073
+ }
3074
+ throw error;
3075
+ }
3076
+ } catch (error) {
3077
+ 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";
3078
+ failure = new Error(code);
3079
+ } finally {
3080
+ if (!recoveryFailed) try {
3081
+ await remove(pointer, { force: true });
3082
+ if (created && !committed) await remove(generation, {
3083
+ recursive: true,
3084
+ force: true
3085
+ });
3086
+ if (locked) await remove(lock, {
3087
+ recursive: true,
3088
+ force: true
3089
+ });
3090
+ } catch {
3091
+ failure ??= /* @__PURE__ */ new Error("PROFILE_PUBLISH_CLEANUP_FAILED");
3092
+ }
3093
+ }
3094
+ if (failure) throw new SurgePublishError(failure.message === "PROFILE_PUBLISH_CLEANUP_FAILED" ? committed ? "PUBLISHED_CLEANUP_FAILED" : "FAILED_CLEANUP_REQUIRED" : failure.message, committed);
3095
+ }
3096
+ //#endregion
3097
+ //#region src/surge-host.ts
3098
+ /** Complete-profile batches use the out symlink protocol; the Program host remains unchanged. */
3099
+ async function buildSurgeProfilesToDirectory(profiles, output, resolveSecret = (token) => process.env[token.name]) {
3100
+ if (typeof output !== "string" || !output.trim()) return {
3101
+ published: false,
3102
+ exitCode: 1,
3103
+ code: "INVALID_OUTPUT_DIRECTORY"
3104
+ };
3105
+ try {
3106
+ const entries = Object.entries(profiles);
3107
+ if (!entries.length || entries.length > 16 || entries.some(([id]) => !/^[a-z0-9][a-z0-9-]*$/.test(id))) return {
3108
+ published: false,
3109
+ exitCode: 1,
3110
+ code: "INVALID_PROFILE_FILENAMES"
3111
+ };
3112
+ const compiled = entries.map(([, input]) => compileSurgeProfile(input));
3113
+ if (compiled.some((profile) => !profile.ok)) return {
3114
+ published: false,
3115
+ exitCode: 1,
3116
+ code: "COMPILATION_FAILED"
3117
+ };
3118
+ const artifacts = renderSurgeProfiles(compiled, resolveSecret);
3119
+ await publishProfiles(new Map(entries.map(([id], i) => [`${id}.conf`, artifacts[i].content])), output);
3120
+ return {
3121
+ published: true,
3122
+ exitCode: 0,
3123
+ code: "PUBLISHED",
3124
+ active: join(resolve(output), "out")
3125
+ };
3126
+ } catch (error) {
3127
+ if (error instanceof SurgePublishError) return {
3128
+ published: error.published,
3129
+ exitCode: error.published ? 2 : 1,
3130
+ code: error.message,
3131
+ ...error.published ? { active: join(resolve(output), "out") } : {},
3132
+ ...error.message === "PUBLISH_RECOVERY_REQUIRED" ? { hint: "out may be absent; preserve the lock, backup, generation and temporary pointer for manual recovery" } : {}
3133
+ };
3134
+ return {
3135
+ published: false,
3136
+ exitCode: 1,
3137
+ code: error instanceof RenderError ? error.code : "BUILD_FAILED"
3138
+ };
3139
+ }
3140
+ }
3141
+ //#endregion
3142
+ //#region src/build-core.ts
3143
+ function record(value, keys) {
3144
+ if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
3145
+ for (const key of Reflect.ownKeys(value)) {
3146
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
3147
+ if (typeof key !== "string" || keys && !keys.includes(key) || !descriptor.enumerable || !("value" in descriptor)) throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
3148
+ }
3149
+ }
3150
+ /** Capture data and callback references before application preflight can change its source. */
3151
+ function captureBuild(input, snapshot) {
3152
+ try {
3153
+ record(input, [
3154
+ "profiles",
3155
+ "preflight",
3156
+ "resolveSecret"
3157
+ ]);
3158
+ record(input.profiles);
3159
+ for (const callback of [input.preflight, input.resolveSecret]) if (callback !== void 0 && typeof callback !== "function") throw new Error();
3160
+ return Object.freeze({
3161
+ profiles: deepFreeze(snapshot(input.profiles)),
3162
+ ...input.preflight === void 0 ? {} : { preflight: input.preflight },
3163
+ ...input.resolveSecret === void 0 ? {} : { resolveSecret: input.resolveSecret }
3164
+ });
3165
+ } catch {
3166
+ throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
3167
+ }
3168
+ }
3169
+ function profileBuildFailure(code, validation = false, profileCount = 0) {
3170
+ return {
3171
+ published: false,
3172
+ exitCode: 1,
3173
+ code,
3174
+ warnings: {},
3175
+ validation,
3176
+ profileCount
3177
+ };
3178
+ }
3179
+ /** Pure orchestration result; the CLI owns stdout and process exit status. */
3180
+ async function executeBuild(input, output, options, capture, publish) {
3181
+ let validation;
3182
+ try {
3183
+ record(options, ["validation"]);
3184
+ if (options.validation !== void 0 && typeof options.validation !== "boolean") throw new Error();
3185
+ validation = options.validation ?? false;
3186
+ } catch {
3187
+ return profileBuildFailure("INVALID_BUILD_OPTIONS");
3188
+ }
3189
+ let definition;
3190
+ try {
3191
+ definition = capture(input);
3192
+ } catch {
3193
+ return profileBuildFailure("INVALID_BUILD_DEFINITION", validation);
3194
+ }
3195
+ const profileCount = Object.keys(definition.profiles).length;
3196
+ const failure = (code) => profileBuildFailure(code, validation, profileCount);
3197
+ if (typeof output !== "string" || !output.trim()) return failure("INVALID_OUTPUT_DIRECTORY");
3198
+ if (validation && !definition.resolveSecret) return failure("VALIDATION_RESOLVER_REQUIRED");
3199
+ let codes;
3200
+ try {
3201
+ codes = definition.preflight ? definition.preflight() : [];
3202
+ } catch {
3203
+ return failure("PREFLIGHT_FAILED");
3204
+ }
3205
+ try {
3206
+ codes = snapshotDefinition(codes);
3207
+ if (!Array.isArray(codes) || codes.length > 1e3 || codes.some((code) => typeof code !== "string" || !/^[A-Z][A-Z0-9_]{0,63}$/.test(code))) throw new Error();
3208
+ } catch {
3209
+ return failure("INVALID_PREFLIGHT_WARNINGS");
3210
+ }
3211
+ const warnings = {};
3212
+ for (const code of codes) warnings[code] = (warnings[code] ?? 0) + 1;
3213
+ const context = Object.freeze({ validation });
3214
+ const resolver = definition.resolveSecret;
3215
+ return {
3216
+ ...await publish(definition.profiles, output, resolver ? (token) => resolver(token, context) : (token) => process.env[token.name]),
3217
+ warnings,
3218
+ validation,
3219
+ profileCount
3220
+ };
3221
+ }
3222
+ //#endregion
3223
+ //#region src/surge-build.ts
3224
+ const surgeBuildFailure = profileBuildFailure;
3225
+ function defineSurgeBuild(input) {
3226
+ return captureBuild(input, snapshotDefinition);
3227
+ }
3228
+ function runSurgeBuild(input, output, options = {}) {
3229
+ return executeBuild(input, output, options, defineSurgeBuild, buildSurgeProfilesToDirectory);
3230
+ }
3231
+ //#endregion
3232
+ //#region src/profile-build.ts
3233
+ function defineBuild(input) {
3234
+ return captureBuild(input, snapshotProfile);
3235
+ }
3236
+ async function publish(profiles, output, resolver) {
3237
+ try {
3238
+ const entries = Object.entries(profiles);
3239
+ if (!entries.length || entries.length > 16 || entries.some(([id]) => !/^[a-z0-9][a-z0-9-]*$/.test(id))) return {
3240
+ published: false,
3241
+ exitCode: 1,
3242
+ code: "INVALID_PROFILE_FILENAMES"
3243
+ };
3244
+ const compiled = entries.map(([, profile]) => compileProfile(profile));
3245
+ const invalid = compiled.find((profile) => !profile.ok);
3246
+ if (invalid) return {
3247
+ published: false,
3248
+ exitCode: 1,
3249
+ code: invalid.engine === "invalid" ? invalid.code : "COMPILATION_FAILED"
3250
+ };
3251
+ if (compiled.some((profile) => profile.engine === "sing-box" && profile.compilation.plans.some((plan) => plan.program.endpoints?.some((endpoint) => pathsOverlap(resolve(output), endpoint.stateDirectory))))) return {
3252
+ published: false,
3253
+ exitCode: 1,
3254
+ code: "ENDPOINT_STATE_OVERLAP"
3255
+ };
3256
+ const read = secretReader(resolver);
3257
+ const files = /* @__PURE__ */ new Map();
3258
+ for (const [index, profile] of compiled.entries()) {
3259
+ if (profile.engine === "invalid") throw new Error();
3260
+ const artifacts = profile.engine === "surge" ? renderSurgeProfiles([profile.compilation], read) : render(profile.compilation, read);
3261
+ files.set(`${entries[index][0]}.${profile.engine === "surge" ? "conf" : "json"}`, artifacts[0].content);
3262
+ }
3263
+ await publishProfiles(files, output);
3264
+ return {
3265
+ published: true,
3266
+ exitCode: 0,
3267
+ code: "PUBLISHED",
3268
+ active: join(resolve(output), "out")
3269
+ };
3270
+ } catch (error) {
3271
+ if (error instanceof SurgePublishError) return {
3272
+ published: error.published,
3273
+ exitCode: error.published ? 2 : 1,
3274
+ code: error.message,
3275
+ ...error.published ? { active: join(resolve(output), "out") } : {},
3276
+ ...error.message === "PUBLISH_RECOVERY_REQUIRED" ? { hint: "out may be absent; preserve the lock, backup, generation and temporary pointer for manual recovery" } : {}
3277
+ };
3278
+ return {
3279
+ published: false,
3280
+ exitCode: 1,
3281
+ code: error instanceof RenderError ? error.code : "BUILD_FAILED"
3282
+ };
3283
+ }
3284
+ }
3285
+ function runBuild(input, output, options = {}) {
3286
+ return executeBuild(input, output, options, defineBuild, publish);
3287
+ }
3288
+ //#endregion
3289
+ export { deepFreeze as $, defineProfile as A, renderSurgeProfiles as B, sequence as C, surge$1 as D, strategy as E, defineSurgeProfile as F, isReservedNativeName as G, compile as H, outbound as I, RenderError as J, nativeNameSchema as K, selectProxies as L, defineProxyGroup as M, defineRoute as N, use as O, defineRoutes as P, assertData as Q, compileSurgeProfile as R, selectNodes as S, slot as T, explain as U, secretReader as V, compileStrategyGroups as W, validateProxyOptions as X, surgeProxy as Y, StaticRuleSetUnknownError as Z, reject as _, surgeBuildFailure as a, ruleSet as b, render as c, direct as d, idSchema as et, group as f, proxy as g, policy as h, runSurgeBuild as i, ProfileDefinitionError as j, compileProfile as k, block as l, mihomo as m, runBuild as n, requestSchema as nt, buildSurgeProfilesToDirectory as o, match as p, targetCatalog as q, defineSurgeBuild as r, buildToDirectory as s, defineBuild as t, nodeSchema as tt, defineConfig as u, route as v, singbox$1 as w, secret as x, rule as y, renderSurgeProfile as z };