proxylang 0.4.0 → 0.6.0

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,10 +1,348 @@
1
+ import { createHash, randomUUID } from "node:crypto";
1
2
  import { isIP } from "node:net";
2
3
  import { z } from "zod";
3
4
  import ipaddr from "ipaddr.js";
4
5
  import { stringify } from "yaml";
5
6
  import { lstat, mkdir, readlink, rename, rm, symlink, writeFile } from "node:fs/promises";
6
7
  import { join, resolve } from "node:path";
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$1 = (code) => {
18
+ throw new ProfileDefinitionError(code);
19
+ };
20
+ /** Inspect descriptors before any caller spreads or reads input fields. Shared DAGs are legal. */
21
+ function inspectDefinition(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$1("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$1("DEFINITION_NOT_DATA");
35
+ return 0;
36
+ }
37
+ if (visiting.has(value)) fail$1("DEFINITION_CYCLE");
38
+ const cached = heights.get(value);
39
+ if (cached !== void 0) {
40
+ if (depth + cached > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
41
+ return cached;
42
+ }
43
+ if (++objects > 2e4) fail$1("DEFINITION_OBJECT_BUDGET_EXCEEDED");
44
+ const proto = Object.getPrototypeOf(value);
45
+ if (proto !== Object.prototype && proto !== null && !(Array.isArray(value) && proto === Array.prototype)) fail$1("DEFINITION_NOT_DATA");
46
+ if (Array.isArray(value) && value.length > 1e5) fail$1("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$1("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$1("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);
60
+ }
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$1("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
66
+ if (depth > 64) fail$1("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;
72
+ }
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
79
+ });
80
+ return output;
81
+ }
82
+ return copy(input, 0);
83
+ }
84
+ function snapshotDefinition(input) {
85
+ inspectDefinition(input);
86
+ return snapshot(input);
87
+ }
88
+ function exactDefinition(value, keys) {
89
+ if (!value || typeof value !== "object" || Array.isArray(value)) fail$1("DEFINITION_NOT_DATA");
90
+ if (Object.keys(value).some((key) => !keys.includes(key))) fail$1("DEFINITION_UNKNOWN_FIELD");
91
+ }
92
+ const outbound = {
93
+ direct: Object.freeze({ builtin: "DIRECT" }),
94
+ reject: Object.freeze({ builtin: "REJECT" }),
95
+ rejectDrop: Object.freeze({ builtin: "REJECT-DROP" }),
96
+ rejectNoDrop: Object.freeze({ builtin: "REJECT-NO-DROP" }),
97
+ rejectTinyGif: Object.freeze({ builtin: "REJECT-TINYGIF" })
98
+ };
99
+ function defineProxyGroup(input) {
100
+ inspectDefinition(input);
101
+ exactDefinition(input, [
102
+ "id",
103
+ "name",
104
+ "algorithm",
105
+ "members",
106
+ "url",
107
+ "intervalSeconds",
108
+ "timeoutSeconds"
109
+ ]);
110
+ if (!input.algorithm || ![
111
+ "select",
112
+ "surge-smart",
113
+ "urltest"
114
+ ].includes(input.algorithm.type)) fail$1("UNSUPPORTED_GROUP_ALGORITHM");
115
+ exactDefinition(input.algorithm, input.algorithm.type === "urltest" ? [
116
+ "type",
117
+ "url",
118
+ "intervalSeconds",
119
+ "toleranceMs"
120
+ ] : ["type"]);
121
+ if (!Array.isArray(input.members)) fail$1("INVALID_GROUP_DEFINITION");
122
+ return {
123
+ ...input,
124
+ type: "proxy-group",
125
+ algorithm: { ...input.algorithm },
126
+ members: [...input.members]
127
+ };
128
+ }
129
+ function defineRoute(input) {
130
+ inspectDefinition(input);
131
+ exactDefinition(input, ["when", "to"]);
132
+ return {
133
+ ...input,
134
+ type: "route"
135
+ };
136
+ }
137
+ function defineRoutes(input) {
138
+ inspectDefinition(input);
139
+ exactDefinition(input, ["when", "to"]);
140
+ if (!Array.isArray(input.when)) fail$1("INVALID_ROUTE_DEFINITION");
141
+ return input.when.map((when) => ({
142
+ type: "route",
143
+ when,
144
+ to: input.to
145
+ }));
146
+ }
147
+ function selectProxies(nodes, query = {}) {
148
+ inspectDefinition({
149
+ nodes,
150
+ query
151
+ });
152
+ exactDefinition(query, [
153
+ "ids",
154
+ "regions",
155
+ "providers",
156
+ "tags"
157
+ ]);
158
+ if (!Array.isArray(nodes) || nodes.some((node) => !node || typeof node !== "object")) fail$1("DEFINITION_NOT_DATA");
159
+ for (const values of Object.values(query)) if (values !== void 0 && !Array.isArray(values)) fail$1("DEFINITION_NOT_DATA");
160
+ 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))));
161
+ }
162
+ function lowerSurgeProfile(input) {
163
+ inspectDefinition(input);
164
+ exactDefinition(input, [
165
+ "target",
166
+ "managed",
167
+ "general",
168
+ "hosts",
169
+ "nodes",
170
+ "tunnels",
171
+ "names",
172
+ "groups",
173
+ "routes",
174
+ "fallback"
175
+ ]);
176
+ 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");
177
+ const registry = /* @__PURE__ */ new Map();
178
+ const names = Object.assign(Object.create(null), input.names);
179
+ for (const resource of [
180
+ ...input.nodes,
181
+ ...input.tunnels ?? [],
182
+ ...input.groups
183
+ ]) {
184
+ if (!resource || typeof resource !== "object" || typeof resource.id !== "string") fail$1("INVALID_RESOURCE_DEFINITION");
185
+ if (registry.has(resource.id)) fail$1("DUPLICATE_RESOURCE_ID");
186
+ registry.set(resource.id, resource);
187
+ const name = resource.type === "proxy-group" ? resource.name : "label" in resource ? resource.label ?? resource.id : resource.id;
188
+ if (resource.type === "proxy-group" && names[resource.id] !== void 0 && names[resource.id] !== name) fail$1("GROUP_NAME_CONFLICT");
189
+ Object.defineProperty(names, resource.id, {
190
+ value: names[resource.id] ?? name,
191
+ enumerable: true,
192
+ configurable: true,
193
+ writable: true
194
+ });
195
+ }
196
+ function lower(destination) {
197
+ if (typeof destination === "string") {
198
+ if (!registry.has(destination)) fail$1("UNKNOWN_DESTINATION_ID");
199
+ return { ref: destination };
200
+ }
201
+ if (!destination || typeof destination !== "object") fail$1("INVALID_DESTINATION");
202
+ if ("builtin" in destination) {
203
+ exactDefinition(destination, ["builtin"]);
204
+ if (!Object.values(outbound).some((value) => value.builtin === destination.builtin)) fail$1("INVALID_DESTINATION");
205
+ return { builtin: destination.builtin };
206
+ }
207
+ if (registry.get(destination.id) !== destination) fail$1("UNREGISTERED_DESTINATION_INSTANCE");
208
+ return { ref: destination.id };
209
+ }
210
+ const groups = input.groups.map((definition) => {
211
+ exactDefinition(definition, [
212
+ "type",
213
+ "id",
214
+ "name",
215
+ "algorithm",
216
+ "members",
217
+ "url",
218
+ "intervalSeconds",
219
+ "timeoutSeconds"
220
+ ]);
221
+ if (definition.type !== "proxy-group") fail$1("INVALID_GROUP_DEFINITION");
222
+ if (!definition.algorithm || !["select", "surge-smart"].includes(definition.algorithm.type)) fail$1("UNSUPPORTED_GROUP_ALGORITHM");
223
+ exactDefinition(definition.algorithm, ["type"]);
224
+ if (!Array.isArray(definition.members)) fail$1("INVALID_GROUP_DEFINITION");
225
+ const { id, url, intervalSeconds, timeoutSeconds } = definition;
226
+ return {
227
+ id,
228
+ type: definition.algorithm.type === "select" ? "select" : "smart",
229
+ members: definition.members.map(lower),
230
+ ...url === void 0 ? {} : { url },
231
+ ...intervalSeconds === void 0 ? {} : { intervalSeconds },
232
+ ...timeoutSeconds === void 0 ? {} : { timeoutSeconds }
233
+ };
234
+ });
235
+ const rules = input.routes.map((definition) => {
236
+ exactDefinition(definition, [
237
+ "type",
238
+ "when",
239
+ "to"
240
+ ]);
241
+ if (definition.type !== "route") fail$1("INVALID_ROUTE_DEFINITION");
242
+ return {
243
+ when: definition.when,
244
+ then: lower(definition.to)
245
+ };
246
+ });
247
+ const { routes: _routes, groups: _groups, fallback, ...rest } = input;
248
+ return snapshot({
249
+ ...rest,
250
+ names,
251
+ groups,
252
+ rules,
253
+ fallback: lower(fallback)
254
+ });
255
+ }
256
+ function condition(value) {
257
+ inspectDefinition(value);
258
+ return value;
259
+ }
260
+ function atom$2(type) {
261
+ return (value, options = {}) => {
262
+ inspectDefinition(options);
263
+ return condition({
264
+ ...options,
265
+ type,
266
+ value
267
+ });
268
+ };
269
+ }
270
+ const surgeMatch = {
271
+ domain: atom$2("domain"),
272
+ domainSuffix: atom$2("domainSuffix"),
273
+ ipCidr: atom$2("ipCidr"),
274
+ ipCidr6: atom$2("ipCidr6"),
275
+ sourceIp: atom$2("sourceIp"),
276
+ processName: atom$2("processName"),
277
+ macAddress: atom$2("macAddress"),
278
+ network: (value, options = {}) => {
279
+ inspectDefinition(options);
280
+ return condition({
281
+ ...options,
282
+ type: "network",
283
+ value
284
+ });
285
+ },
286
+ port: (from, to, options = {}) => {
287
+ inspectDefinition(options);
288
+ return condition({
289
+ ...options,
290
+ type: "port",
291
+ from,
292
+ ...to === void 0 ? {} : { to }
293
+ });
294
+ },
295
+ sourcePort: (from, to, options = {}) => {
296
+ inspectDefinition(options);
297
+ return condition({
298
+ ...options,
299
+ type: "sourcePort",
300
+ from,
301
+ ...to === void 0 ? {} : { to }
302
+ });
303
+ },
304
+ all: (conditions, options = {}) => {
305
+ inspectDefinition({
306
+ conditions,
307
+ options
308
+ });
309
+ return condition({
310
+ ...options,
311
+ type: "all",
312
+ conditions: [...conditions]
313
+ });
314
+ },
315
+ any: (conditions, options = {}) => {
316
+ inspectDefinition({
317
+ conditions,
318
+ options
319
+ });
320
+ return condition({
321
+ ...options,
322
+ type: "any",
323
+ conditions: [...conditions]
324
+ });
325
+ },
326
+ not: (value, options = {}) => {
327
+ inspectDefinition({
328
+ value,
329
+ options
330
+ });
331
+ return condition({
332
+ ...options,
333
+ type: "not",
334
+ condition: value
335
+ });
336
+ },
337
+ ruleSet: (options) => {
338
+ inspectDefinition(options);
339
+ return condition({
340
+ ...options,
341
+ type: "ruleSet"
342
+ });
343
+ }
344
+ };
345
+ //#endregion
8
346
  //#region src/dns.ts
9
347
  const domain$2 = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;
10
348
  function dohUrl(value) {
@@ -68,7 +406,7 @@ const cidr$1 = z.string().refine((x) => {
68
406
  const processNameSchema = z.string().min(1).max(255).regex(/^[^/\\*?[\],()\p{C}]+$/u);
69
407
  const port$1 = z.number().int().min(1).max(65535);
70
408
  const network = z.enum(["tcp", "udp"]);
71
- const atom$2 = (type, value) => z.strictObject({
409
+ const atom$1 = (type, value) => z.strictObject({
72
410
  type: z.literal(type),
73
411
  value
74
412
  });
@@ -90,7 +428,9 @@ const nativeRuleSetSchema = z.discriminatedUnion("engine", [
90
428
  ...remoteBase,
91
429
  engine: z.literal("surge"),
92
430
  format: z.enum(["rule-set", "domain-set"]),
93
- intervalSeconds: updateInterval.optional()
431
+ intervalSeconds: updateInterval.optional(),
432
+ noResolve: z.boolean().optional(),
433
+ extendedMatching: z.boolean().optional()
94
434
  }),
95
435
  z.strictObject({
96
436
  ...remoteBase,
@@ -117,11 +457,23 @@ const matchSchema = z.lazy(() => z.discriminatedUnion("type", [
117
457
  id: idSchema,
118
458
  when: matchSchema
119
459
  }),
120
- atom$2("domain", domain$1),
121
- atom$2("domainSuffix", domain$1),
122
- atom$2("ipCidr", cidr$1),
123
- atom$2("sourceIp", z.union([ip$1, cidr$1])),
124
- atom$2("processName", processNameSchema),
460
+ z.strictObject({
461
+ type: z.literal("domain"),
462
+ value: domain$1,
463
+ extendedMatching: z.boolean().optional()
464
+ }),
465
+ z.strictObject({
466
+ type: z.literal("domainSuffix"),
467
+ value: domain$1,
468
+ extendedMatching: z.boolean().optional()
469
+ }),
470
+ z.strictObject({
471
+ type: z.literal("ipCidr"),
472
+ value: cidr$1,
473
+ noResolve: z.boolean().optional()
474
+ }),
475
+ atom$1("sourceIp", z.union([ip$1, cidr$1])),
476
+ atom$1("processName", processNameSchema),
125
477
  z.strictObject({
126
478
  type: z.literal("port"),
127
479
  from: port$1,
@@ -212,7 +564,7 @@ const uuidNode = {
212
564
  tls: tlsSchema.optional(),
213
565
  transport: transportSchema.optional()
214
566
  };
215
- const surgeOptions = { blockQuic: z.enum([
567
+ const surgeOptions$1 = { blockQuic: z.enum([
216
568
  "auto",
217
569
  "on",
218
570
  "off"
@@ -225,7 +577,7 @@ const nodeSchema = z.discriminatedUnion("type", [
225
577
  serverName: domain$1.optional(),
226
578
  skipCertVerify: z.boolean().optional(),
227
579
  surge: z.strictObject({
228
- ...surgeOptions,
580
+ ...surgeOptions$1,
229
581
  udpRelay: z.literal(true).optional()
230
582
  }).optional()
231
583
  }),
@@ -236,7 +588,7 @@ const nodeSchema = z.discriminatedUnion("type", [
236
588
  serverName: domain$1.optional(),
237
589
  skipCertVerify: z.boolean().optional(),
238
590
  surge: z.strictObject({
239
- ...surgeOptions,
591
+ ...surgeOptions$1,
240
592
  udpRelay: z.literal(true).optional()
241
593
  }).optional()
242
594
  }),
@@ -251,7 +603,7 @@ const nodeSchema = z.discriminatedUnion("type", [
251
603
  ...nodeBase,
252
604
  type: z.literal("shadowsocks"),
253
605
  surge: z.strictObject({
254
- ...surgeOptions,
606
+ ...surgeOptions$1,
255
607
  udpRelay: z.boolean().optional()
256
608
  }).optional(),
257
609
  method: z.enum([
@@ -264,7 +616,7 @@ const nodeSchema = z.discriminatedUnion("type", [
264
616
  z.strictObject({
265
617
  ...uuidNode,
266
618
  type: z.literal("vmess"),
267
- surge: z.strictObject(surgeOptions).optional()
619
+ surge: z.strictObject(surgeOptions$1).optional()
268
620
  }),
269
621
  z.strictObject({
270
622
  ...uuidNode,
@@ -337,6 +689,8 @@ const groupSchema$1 = z.union([
337
689
  const requestSchema = z.strictObject({
338
690
  network,
339
691
  domain: domain$1.optional(),
692
+ tlsSni: domain$1.optional(),
693
+ httpHost: domain$1.optional(),
340
694
  ip: ip$1.optional(),
341
695
  sourceIp: ip$1.optional(),
342
696
  processName: processNameSchema.optional(),
@@ -344,6 +698,7 @@ const requestSchema = z.strictObject({
344
698
  sourcePort: port$1.optional()
345
699
  });
346
700
  const configSchema = z.strictObject({
701
+ outDir: z.string().min(1).refine((value) => value.trim() === value && !value.includes("\0")).optional(),
347
702
  programs: z.record(idSchema, z.strictObject({
348
703
  engine: z.enum([
349
704
  "surge",
@@ -652,13 +1007,16 @@ function evaluate(condition, request) {
652
1007
  let present;
653
1008
  switch (condition.type) {
654
1009
  case "domain":
655
- present = request.domain !== void 0;
656
- matched = request.domain === condition.value;
657
- break;
658
- case "domainSuffix":
659
- present = request.domain !== void 0;
660
- matched = request.domain === condition.value || !!request.domain?.endsWith(`.${condition.value}`);
1010
+ case "domainSuffix": {
1011
+ const domains = condition.extendedMatching ? [
1012
+ request.domain,
1013
+ request.tlsSni,
1014
+ request.httpHost
1015
+ ] : [request.domain];
1016
+ present = domains.some((value) => value !== void 0);
1017
+ matched = domains.some((value) => value !== void 0 && (value === condition.value || condition.type === "domainSuffix" && value.endsWith(`.${condition.value}`)));
661
1018
  break;
1019
+ }
662
1020
  case "ipCidr":
663
1021
  present = request.ip !== void 0;
664
1022
  matched = inCidr(request.ip, condition.value);
@@ -962,7 +1320,7 @@ function conditionText$1(condition) {
962
1320
  case "not": return `NOT,((${conditionText$1(condition.condition)}))`;
963
1321
  case "domain": return `DOMAIN,${condition.value}`;
964
1322
  case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
965
- case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value},no-resolve`;
1323
+ case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value}${condition.noResolve !== false ? ",no-resolve" : ""}`;
966
1324
  case "processName": return `PROCESS-NAME,${condition.value}`;
967
1325
  case "sourceIp": return `SRC-IP-CIDR,${condition.value.includes("/") ? condition.value : `${condition.value}/${condition.value.includes(":") ? 128 : 32}`}`;
968
1326
  case "network": return `NETWORK,${condition.value}`;
@@ -976,7 +1334,7 @@ function clashConfig(plan, secret) {
976
1334
  const config = {
977
1335
  proxies: program.nodes.map((node) => clashProxy(node, target.engine, secret)),
978
1336
  "proxy-groups": program.groups.map((g) => clashGroup(g)),
979
- 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)}`]
1337
+ rules: [...plan.rules.map((rule) => rule.when.type === "ipCidr" ? `${conditionText$1(rule.when).replace(/,no-resolve$/, "")},${policy$2(rule.then)}${rule.when.noResolve !== false ? ",no-resolve" : ""}` : `${conditionText$1(rule.when)},${policy$2(rule.then)}`), `MATCH,${policy$2(program.fallback)}`]
980
1338
  };
981
1339
  if (plan.nativeRuleSets.length) config["rule-providers"] = Object.fromEntries(plan.nativeRuleSets.map((r) => [r.id, {
982
1340
  type: "http",
@@ -1452,6 +1810,13 @@ function compile(input) {
1452
1810
  if (target.engine === "surge") {
1453
1811
  for (const rule of rules) if (logicalDepth(rule.when) > 10) error("LOGICAL_DEPTH", rule.id, "Surge 逻辑条件最多嵌套 10 层", target.id);
1454
1812
  }
1813
+ const checkOptions = (condition) => {
1814
+ if ("extendedMatching" in condition && condition.extendedMatching === true && target.engine !== "surge" || condition.type === "ipCidr" && condition.noResolve !== void 0 && target.engine === "sing-box") error("MATCH_OPTION_UNSUPPORTED", path, "目标无法等价实现显式匹配选项", target.id);
1815
+ if (condition.type === "all" || condition.type === "any") condition.conditions.forEach(checkOptions);
1816
+ else if (condition.type === "not") checkOptions(condition.condition);
1817
+ else if (condition.type === "ruleSet") checkOptions(condition.when);
1818
+ };
1819
+ rules.forEach((rule) => checkOptions(rule.when));
1455
1820
  const nativeRuleSets = collectNativeRuleSets(rules, target, diagnostics);
1456
1821
  for (const resource of nativeRuleSets) if (!descriptor.nativeRuleSets.includes(resource.format)) error("RULESET_UNSUPPORTED", `${path}.ruleSets.${resource.id}`, "精确目标不支持此原生规则资源格式", target.id);
1457
1822
  plans.push({
@@ -1697,50 +2062,51 @@ const groupSchema = z.strictObject({
1697
2062
  intervalSeconds: z.number().int().positive().max(2147483647).optional(),
1698
2063
  timeoutSeconds: z.number().int().positive().max(3600).optional()
1699
2064
  });
1700
- const options = {
2065
+ const options$1 = {
1701
2066
  noResolve: z.boolean().optional(),
1702
2067
  extendedMatching: z.boolean().optional()
1703
2068
  };
1704
- const atom$1 = (type, value) => z.strictObject({
2069
+ const atom = (type, value) => z.strictObject({
1705
2070
  type: z.literal(type),
1706
2071
  value,
1707
- ...options
2072
+ ...options$1
1708
2073
  });
1709
2074
  const conditionSchema = z.lazy(() => z.union([
1710
- atom$1("domain", domain),
1711
- atom$1("domainSuffix", domain),
1712
- atom$1("ipCidr", cidr(4)),
1713
- atom$1("ipCidr6", cidr(6)),
1714
- atom$1("sourceIp", z.union([ip, cidr()])),
1715
- atom$1("processName", safe),
1716
- atom$1("macAddress", z.string().regex(/^(?:[\da-fA-F]{2}:){5}[\da-fA-F]{2}$/)),
2075
+ atom("domain", domain),
2076
+ atom("domainSuffix", domain),
2077
+ atom("ipCidr", cidr(4)),
2078
+ atom("ipCidr6", cidr(6)),
2079
+ atom("sourceIp", z.union([ip, cidr()])),
2080
+ atom("processName", safe),
2081
+ atom("macAddress", z.string().regex(/^(?:[\da-fA-F]{2}:){5}[\da-fA-F]{2}$/)),
1717
2082
  z.strictObject({
1718
2083
  type: z.enum(["port", "sourcePort"]),
1719
2084
  from: port,
1720
2085
  to: port.optional(),
1721
- ...options
2086
+ ...options$1
1722
2087
  }).refine((v) => v.to === void 0 || v.to >= v.from),
1723
2088
  z.strictObject({
1724
2089
  type: z.literal("network"),
1725
2090
  value: z.enum(["tcp", "udp"]),
1726
- ...options
2091
+ ...options$1
1727
2092
  }),
1728
2093
  z.strictObject({
1729
2094
  type: z.enum(["all", "any"]),
1730
2095
  conditions: z.array(conditionSchema).min(2).max(100),
1731
- ...options
2096
+ ...options$1
1732
2097
  }),
1733
2098
  z.strictObject({
1734
2099
  type: z.literal("not"),
1735
2100
  condition: conditionSchema,
1736
- ...options
2101
+ ...options$1
1737
2102
  }),
1738
2103
  z.strictObject({
1739
2104
  type: z.literal("ruleSet"),
1740
2105
  format: z.enum(["rule-set", "domain-set"]),
1741
2106
  url: url.optional(),
1742
2107
  builtin: z.enum(["LAN", "SYSTEM"]).optional(),
1743
- ...options
2108
+ intervalSeconds: z.number().int().min(60).max(2147483647).optional(),
2109
+ ...options$1
1744
2110
  }).refine((v) => v.url !== void 0 !== (v.builtin !== void 0))
1745
2111
  ]));
1746
2112
  const managedSchema = z.strictObject({
@@ -1796,555 +2162,224 @@ function compileSurgeProfile(input) {
1796
2162
  }
1797
2163
  if (parsed.data.general) {
1798
2164
  const general = parsed.data.general;
1799
- parsed.data.general = Object.fromEntries(Object.keys(input.general).map((key) => [key, general[key]]));
1800
- }
1801
- const p = deepFreeze(parsed.data);
1802
- if (!(p.target.platform === "macos" && p.target.version === "6.10.0") && !(p.target.platform === "ios" && p.target.version === "5.21.0")) error("UNKNOWN_TARGET");
1803
- const tunnels = p.tunnels ?? [];
1804
- const resources = [
1805
- ...p.nodes,
1806
- ...tunnels,
1807
- ...p.groups
1808
- ];
1809
- if (resources.length > 1e3) error("RESOURCE_LIMIT");
1810
- const ids = new Set(resources.map((r) => r.id));
1811
- if (ids.size !== resources.length) error("DUPLICATE_RESOURCE");
1812
- if (Object.keys(p.names ?? {}).some((id) => !ids.has(id))) error("UNKNOWN_NAME_MAPPING");
1813
- const bindings = resources.map((r) => ({
1814
- id: r.id,
1815
- nativeName: p.names?.[r.id] ?? r.id
1816
- }));
1817
- if (bindings.some((b) => !nativeNameSchema.safeParse(b.nativeName).success || isReservedNativeName(b.nativeName, "surge"))) error("INVALID_NATIVE_NAME");
1818
- if (new Set(bindings.map((b) => b.nativeName)).size !== bindings.length) error("DUPLICATE_NATIVE_NAME");
1819
- if (new Set(tunnels.map((t) => t.sectionName)).size !== tunnels.length) error("DUPLICATE_TUNNEL_SECTION");
1820
- if (p.target.platform === "ios" && [
1821
- "bypass-system",
1822
- "replica",
1823
- "tls-provider",
1824
- "bypass-tun",
1825
- "external-controller-access"
1826
- ].some((k) => Object.hasOwn(p.general ?? {}, k))) error("PLATFORM_OPTION_UNSUPPORTED");
1827
- if (new Set((p.hosts ?? []).map((h) => h.pattern.toLowerCase())).size !== (p.hosts ?? []).length) error("DUPLICATE_HOST_PATTERN");
1828
- const checkPolicy = (action) => {
1829
- if ("ref" in action && !ids.has(action.ref)) error("MISSING_REFERENCE");
1830
- };
1831
- const edges = new Map(resources.map((r) => [r.id, []]));
1832
- const proxyIds = new Set([...p.nodes, ...tunnels].map((n) => n.id));
1833
- for (const node of p.nodes) {
1834
- if (node.type === "vless") error("PROTOCOL_UNSUPPORTED");
1835
- validateProxyOptions(node, {
1836
- id: "profile",
1837
- engine: "surge"
1838
- }, diagnostics);
1839
- if (node.via) {
1840
- checkPolicy({ ref: node.via });
1841
- edges.get(node.id).push(node.via);
1842
- }
1843
- }
1844
- for (const group of p.groups) {
1845
- if (group.type === "smart" && (group.url !== void 0 || group.intervalSeconds !== void 0 || group.timeoutSeconds !== void 0)) error("GROUP_OPTION_UNSUPPORTED");
1846
- for (const member of group.members) {
1847
- checkPolicy(member);
1848
- if (group.type === "smart" && (!("ref" in member) || !proxyIds.has(member.ref))) error("SMART_MEMBER_UNSUPPORTED");
1849
- if ("ref" in member) edges.get(group.id).push(member.ref);
1850
- }
1851
- }
1852
- const active = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set();
1853
- const visit = (id) => {
1854
- if (active.has(id)) {
1855
- error("RESOURCE_CYCLE");
1856
- return;
1857
- }
1858
- if (visited.has(id)) return;
1859
- active.add(id);
1860
- for (const next of edges.get(id) ?? []) visit(next);
1861
- active.delete(id);
1862
- visited.add(id);
1863
- };
1864
- if (resources.length <= 1e3) for (const id of ids) visit(id);
1865
- const formats = /* @__PURE__ */ new Map();
1866
- const checkCondition = (c, depth) => {
1867
- if (depth > 10) {
1868
- error("LOGICAL_DEPTH_EXCEEDED");
1869
- return;
1870
- }
1871
- if (c.noResolve !== void 0 && ![
1872
- "ipCidr",
1873
- "ipCidr6",
1874
- "ruleSet"
1875
- ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
1876
- if (c.extendedMatching !== void 0 && ![
1877
- "domain",
1878
- "domainSuffix",
1879
- "ruleSet"
1880
- ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
1881
- if (p.target.platform === "ios" && ["processName", "macAddress"].includes(c.type)) error("PLATFORM_RULE_UNSUPPORTED");
1882
- if (c.type === "all" || c.type === "any") for (const child of c.conditions) checkCondition(child, depth + 1);
1883
- if (c.type === "not") checkCondition(c.condition, depth + 1);
1884
- if (c.type === "ruleSet") {
1885
- if (c.builtin && c.format !== "rule-set") error("BUILTIN_RULESET_FORMAT");
1886
- if (c.url) {
1887
- if (formats.has(c.url) && formats.get(c.url) !== c.format) error("RULESET_FORMAT_CONFLICT");
1888
- formats.set(c.url, c.format);
1889
- }
1890
- }
1891
- };
1892
- for (const rule of p.rules) {
1893
- checkPolicy(rule.then);
1894
- checkCondition(rule.when, 0);
1895
- }
1896
- checkPolicy(p.fallback);
1897
- if (diagnostics.some((d) => d.severity === "error")) return failure();
1898
- if (formats.size) diagnostics.push({
1899
- severity: "warning",
1900
- code: "EXTERNAL_RULESET_UNVERIFIED",
1901
- path: "rules",
1902
- message: "External rule sets are resolved by the client, not by the compiler."
1903
- });
1904
- const result = deepFreeze({
1905
- ok: true,
1906
- artifactKind: "surge-profile",
1907
- diagnostics,
1908
- bindings
1909
- });
1910
- plans.set(result, p);
1911
- return result;
1912
- }
1913
- function conditionOptions(c) {
1914
- return [...c.noResolve ? ["no-resolve"] : [], ...c.extendedMatching ? ["extended-matching"] : []];
1915
- }
1916
- function conditionText(c) {
1917
- switch (c.type) {
1918
- case "all":
1919
- case "any": return `${c.type === "all" ? "AND" : "OR"},(${c.conditions.map((x) => `(${[conditionText(x), ...conditionOptions(x)].join(",")})`).join(",")})`;
1920
- case "not": return `NOT,((${[conditionText(c.condition), ...conditionOptions(c.condition)].join(",")}))`;
1921
- case "port":
1922
- case "sourcePort": return `${c.type === "port" ? "DEST-PORT" : "SRC-PORT"},${c.from}${c.to === void 0 || c.to === c.from ? "" : `-${c.to}`}`;
1923
- case "network": return `PROTOCOL,${c.value.toUpperCase()}`;
1924
- case "ruleSet": return `${c.format === "rule-set" ? "RULE-SET" : "DOMAIN-SET"},${c.url ?? c.builtin}`;
1925
- default: return `${{
1926
- domain: "DOMAIN",
1927
- domainSuffix: "DOMAIN-SUFFIX",
1928
- ipCidr: "IP-CIDR",
1929
- ipCidr6: "IP-CIDR6",
1930
- sourceIp: "SRC-IP",
1931
- processName: "PROCESS-NAME",
1932
- macAddress: "MAC-ADDRESS"
1933
- }[c.type]},${c.value}`;
1934
- }
1935
- }
1936
- function renderProfile(compilation, read) {
1937
- const p = plans.get(compilation);
1938
- if (!p) throw new RenderError("COMPILATION_FAILED");
1939
- const name = (id) => p.names?.[id] ?? id;
1940
- const action = (value) => "ref" in value ? name(value.ref) : value.builtin;
1941
- const credential = (token, kind) => {
1942
- const value = read(token);
1943
- 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");
1944
- return value;
1945
- };
1946
- const lines = [];
1947
- if (p.managed) {
1948
- const address = new URL(p.managed.url);
1949
- for (const [k, v] of Object.entries(p.managed.query ?? {})) address.searchParams.set(k, typeof v === "string" ? v : read(v));
1950
- lines.push(`#!MANAGED-CONFIG ${address.href} interval=${p.managed.intervalSeconds} strict=${p.managed.strict}`, "");
1951
- }
1952
- lines.push("[General]");
1953
- for (const [k, v] of Object.entries(p.general ?? {})) {
1954
- const value = Array.isArray(v) ? v.join(", ") : typeof v === "object" ? `${credential(v.password, "control")}@${v.listen}` : String(v);
1955
- lines.push(`${k} = ${value}`);
1956
- }
1957
- lines.push("", "[Host]");
1958
- for (const h of p.hosts ?? []) lines.push(`${h.pattern} = ${[...h.address ? [h.address] : [], ...h.server ? [`server:${h.server}`] : []].join(", ")}`);
1959
- lines.push("", "[Proxy]");
1960
- for (const n of p.nodes) lines.push(surgeProxy(n, read, name));
1961
- for (const t of p.tunnels ?? []) lines.push(`${name(t.id)} = ${t.type}, section-name=${t.sectionName}`);
1962
- for (const t of p.tunnels ?? []) {
1963
- lines.push("", `[${t.type === "tailscale" ? "Tailscale" : "WireGuard"} ${t.sectionName}]`);
1964
- if (t.type === "tailscale") {
1965
- lines.push(`auth-key = ${credential(t.authKey, "tailscale")}`, `hostname = ${t.hostname}`);
1966
- if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
1967
- if (t.autoAddMagicDnsRule !== void 0) lines.push(`auto-add-magic-dns-rule = ${t.autoAddMagicDnsRule}`);
1968
- if (t.idleKeepalive !== void 0) lines.push(`idle-keepalive = ${t.idleKeepalive}`);
1969
- } else {
1970
- lines.push(`private-key = ${credential(t.privateKey, "key")}`, `self-ip = ${t.selfIp}`);
1971
- if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
1972
- if (t.mtu !== void 0) lines.push(`mtu = ${t.mtu}`);
1973
- for (const peer of t.peers) {
1974
- const values = [`public-key = ${peer.publicKey}`];
1975
- if (peer.presharedKey) values.push(`preshared-key = ${credential(peer.presharedKey, "key")}`);
1976
- values.push(`allowed-ips = "${peer.allowedIps.join(", ")}"`, `endpoint = ${peer.endpoint}`);
1977
- if (peer.persistentKeepalive !== void 0) values.push(`keepalive = ${peer.persistentKeepalive}`);
1978
- lines.push(`peer = (${values.join(", ")})`);
1979
- }
1980
- }
1981
- }
1982
- lines.push("", "[Proxy Group]");
1983
- for (const g of p.groups) lines.push(`${name(g.id)} = ${[
1984
- g.type,
1985
- ...g.members.map(action),
1986
- ...g.url ? [`url=${g.url}`] : [],
1987
- ...g.intervalSeconds !== void 0 ? [`interval=${g.intervalSeconds}`] : [],
1988
- ...g.timeoutSeconds !== void 0 ? [`timeout=${g.timeoutSeconds}`] : []
1989
- ].join(", ")}`);
1990
- lines.push("", "[Rule]");
1991
- for (const r of p.rules) lines.push([
1992
- conditionText(r.when),
1993
- action(r.then),
1994
- ...conditionOptions(r.when)
1995
- ].join(","));
1996
- lines.push(`FINAL,${action(p.fallback)}`, "");
1997
- return deepFreeze({
1998
- artifactKind: "surge-profile",
1999
- content: lines.join("\n")
2000
- });
2001
- }
2002
- function renderSurgeProfile(compilation, resolveSecret) {
2003
- return renderProfile(compilation, secretReader(resolveSecret));
2004
- }
2005
- function renderSurgeProfiles(compilations, resolveSecret) {
2006
- if (compilations.some((c) => !plans.has(c))) throw new RenderError("COMPILATION_FAILED");
2007
- const read = secretReader(resolveSecret);
2008
- return deepFreeze(compilations.map((c) => renderProfile(c, read)));
2009
- }
2010
- //#endregion
2011
- //#region src/surge-definitions.ts
2012
- var ProfileDefinitionError = class extends Error {
2013
- code;
2014
- constructor(code) {
2015
- super(code);
2016
- this.code = code;
2017
- this.name = "ProfileDefinitionError";
2018
- }
2019
- };
2020
- const fail$1 = (code) => {
2021
- throw new ProfileDefinitionError(code);
2022
- };
2023
- /** Inspect descriptors before any caller spreads or reads input fields. Shared DAGs are legal. */
2024
- function inspectDefinition(root) {
2025
- let edges = 0;
2026
- let objects = 0;
2027
- const visiting = /* @__PURE__ */ new Set();
2028
- const heights = /* @__PURE__ */ new Map();
2029
- function visit(value, depth) {
2030
- if (depth > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
2031
- if (value === null || typeof value !== "object") {
2032
- if (![
2033
- "undefined",
2034
- "string",
2035
- "number",
2036
- "boolean"
2037
- ].includes(typeof value) && value !== null) fail$1("DEFINITION_NOT_DATA");
2038
- return 0;
2039
- }
2040
- if (visiting.has(value)) fail$1("DEFINITION_CYCLE");
2041
- const cached = heights.get(value);
2042
- if (cached !== void 0) {
2043
- if (depth + cached > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
2044
- return cached;
2045
- }
2046
- if (++objects > 2e4) fail$1("DEFINITION_OBJECT_BUDGET_EXCEEDED");
2047
- const proto = Object.getPrototypeOf(value);
2048
- if (proto !== Object.prototype && proto !== null && !(Array.isArray(value) && proto === Array.prototype)) fail$1("DEFINITION_NOT_DATA");
2049
- if (Array.isArray(value) && value.length > 1e5) fail$1("DEFINITION_EDGE_BUDGET_EXCEEDED");
2050
- visiting.add(value);
2051
- let height = 0;
2052
- for (const key of Reflect.ownKeys(value)) {
2053
- if (++edges > 1e5) fail$1("DEFINITION_EDGE_BUDGET_EXCEEDED");
2054
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
2055
- if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable && !(Array.isArray(value) && key === "length")) fail$1("DEFINITION_NOT_DATA");
2056
- height = Math.max(height, 1 + visit(descriptor.value, depth + 1));
2165
+ parsed.data.general = Object.fromEntries(Object.keys(input.general).map((key) => [key, general[key]]));
2166
+ }
2167
+ const p = deepFreeze(parsed.data);
2168
+ if (!(p.target.platform === "macos" && p.target.version === "6.10.0") && !(p.target.platform === "ios" && p.target.version === "5.21.0")) error("UNKNOWN_TARGET");
2169
+ const tunnels = p.tunnels ?? [];
2170
+ const resources = [
2171
+ ...p.nodes,
2172
+ ...tunnels,
2173
+ ...p.groups
2174
+ ];
2175
+ if (resources.length > 1e3) error("RESOURCE_LIMIT");
2176
+ const ids = new Set(resources.map((r) => r.id));
2177
+ if (ids.size !== resources.length) error("DUPLICATE_RESOURCE");
2178
+ if (Object.keys(p.names ?? {}).some((id) => !ids.has(id))) error("UNKNOWN_NAME_MAPPING");
2179
+ const bindings = resources.map((r) => ({
2180
+ id: r.id,
2181
+ nativeName: p.names?.[r.id] ?? r.id
2182
+ }));
2183
+ if (bindings.some((b) => !nativeNameSchema.safeParse(b.nativeName).success || isReservedNativeName(b.nativeName, "surge"))) error("INVALID_NATIVE_NAME");
2184
+ if (new Set(bindings.map((b) => b.nativeName)).size !== bindings.length) error("DUPLICATE_NATIVE_NAME");
2185
+ if (new Set(tunnels.map((t) => t.sectionName)).size !== tunnels.length) error("DUPLICATE_TUNNEL_SECTION");
2186
+ if (p.target.platform === "ios" && [
2187
+ "bypass-system",
2188
+ "replica",
2189
+ "tls-provider",
2190
+ "bypass-tun",
2191
+ "external-controller-access"
2192
+ ].some((k) => Object.hasOwn(p.general ?? {}, k))) error("PLATFORM_OPTION_UNSUPPORTED");
2193
+ if (new Set((p.hosts ?? []).map((h) => h.pattern.toLowerCase())).size !== (p.hosts ?? []).length) error("DUPLICATE_HOST_PATTERN");
2194
+ const checkPolicy = (action) => {
2195
+ if ("ref" in action && !ids.has(action.ref)) error("MISSING_REFERENCE");
2196
+ };
2197
+ const edges = new Map(resources.map((r) => [r.id, []]));
2198
+ const proxyIds = new Set([...p.nodes, ...tunnels].map((n) => n.id));
2199
+ for (const node of p.nodes) {
2200
+ if (node.type === "vless") error("PROTOCOL_UNSUPPORTED");
2201
+ validateProxyOptions(node, {
2202
+ id: "profile",
2203
+ engine: "surge"
2204
+ }, diagnostics);
2205
+ if (node.via) {
2206
+ checkPolicy({ ref: node.via });
2207
+ edges.get(node.id).push(node.via);
2057
2208
  }
2058
- visiting.delete(value);
2059
- heights.set(value, height);
2060
- return height;
2061
2209
  }
2062
- visit(root, 0);
2063
- }
2064
- /** Count output occurrences, not identities, before allocating each copied value. */
2065
- function snapshot(input) {
2066
- let remaining = 1e5;
2067
- function copy(value, depth) {
2068
- if (--remaining < 0) fail$1("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
2069
- if (depth > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
2070
- if (value === null || typeof value !== "object") return value;
2071
- if (Array.isArray(value)) {
2072
- const output = [];
2073
- for (const item of value) output.push(copy(item, depth + 1));
2074
- return output;
2210
+ for (const group of p.groups) {
2211
+ if (group.type === "smart" && (group.url !== void 0 || group.intervalSeconds !== void 0 || group.timeoutSeconds !== void 0)) error("GROUP_OPTION_UNSUPPORTED");
2212
+ for (const member of group.members) {
2213
+ checkPolicy(member);
2214
+ if (group.type === "smart" && (!("ref" in member) || !proxyIds.has(member.ref))) error("SMART_MEMBER_UNSUPPORTED");
2215
+ if ("ref" in member) edges.get(group.id).push(member.ref);
2075
2216
  }
2076
- const output = {};
2077
- for (const [key, item] of Object.entries(value)) Object.defineProperty(output, key, {
2078
- value: copy(item, depth + 1),
2079
- enumerable: true,
2080
- writable: true,
2081
- configurable: true
2082
- });
2083
- return output;
2084
2217
  }
2085
- return copy(input, 0);
2086
- }
2087
- function snapshotDefinition(input) {
2088
- inspectDefinition(input);
2089
- return snapshot(input);
2090
- }
2091
- function exactDefinition(value, keys) {
2092
- if (!value || typeof value !== "object" || Array.isArray(value)) fail$1("DEFINITION_NOT_DATA");
2093
- if (Object.keys(value).some((key) => !keys.includes(key))) fail$1("DEFINITION_UNKNOWN_FIELD");
2094
- }
2095
- const outbound = {
2096
- direct: Object.freeze({ builtin: "DIRECT" }),
2097
- reject: Object.freeze({ builtin: "REJECT" }),
2098
- rejectDrop: Object.freeze({ builtin: "REJECT-DROP" }),
2099
- rejectNoDrop: Object.freeze({ builtin: "REJECT-NO-DROP" }),
2100
- rejectTinyGif: Object.freeze({ builtin: "REJECT-TINYGIF" })
2101
- };
2102
- function defineProxyGroup(input) {
2103
- inspectDefinition(input);
2104
- exactDefinition(input, [
2105
- "id",
2106
- "name",
2107
- "algorithm",
2108
- "members",
2109
- "url",
2110
- "intervalSeconds",
2111
- "timeoutSeconds"
2112
- ]);
2113
- if (!input.algorithm || ![
2114
- "select",
2115
- "surge-smart",
2116
- "urltest"
2117
- ].includes(input.algorithm.type)) fail$1("UNSUPPORTED_GROUP_ALGORITHM");
2118
- exactDefinition(input.algorithm, input.algorithm.type === "urltest" ? [
2119
- "type",
2120
- "url",
2121
- "intervalSeconds",
2122
- "toleranceMs"
2123
- ] : ["type"]);
2124
- if (!Array.isArray(input.members)) fail$1("INVALID_GROUP_DEFINITION");
2125
- return {
2126
- ...input,
2127
- type: "proxy-group",
2128
- algorithm: { ...input.algorithm },
2129
- members: [...input.members]
2218
+ const active = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set();
2219
+ const visit = (id) => {
2220
+ if (active.has(id)) {
2221
+ error("RESOURCE_CYCLE");
2222
+ return;
2223
+ }
2224
+ if (visited.has(id)) return;
2225
+ active.add(id);
2226
+ for (const next of edges.get(id) ?? []) visit(next);
2227
+ active.delete(id);
2228
+ visited.add(id);
2130
2229
  };
2131
- }
2132
- function defineRoute(input) {
2133
- inspectDefinition(input);
2134
- exactDefinition(input, ["when", "to"]);
2135
- return {
2136
- ...input,
2137
- type: "route"
2230
+ if (resources.length <= 1e3) for (const id of ids) visit(id);
2231
+ const formats = /* @__PURE__ */ new Map();
2232
+ const checkCondition = (c, depth) => {
2233
+ if (depth > 10) {
2234
+ error("LOGICAL_DEPTH_EXCEEDED");
2235
+ return;
2236
+ }
2237
+ if (c.noResolve !== void 0 && ![
2238
+ "ipCidr",
2239
+ "ipCidr6",
2240
+ "ruleSet"
2241
+ ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
2242
+ if (c.extendedMatching !== void 0 && ![
2243
+ "domain",
2244
+ "domainSuffix",
2245
+ "ruleSet"
2246
+ ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
2247
+ if (p.target.platform === "ios" && ["processName", "macAddress"].includes(c.type)) error("PLATFORM_RULE_UNSUPPORTED");
2248
+ if (c.type === "all" || c.type === "any") for (const child of c.conditions) checkCondition(child, depth + 1);
2249
+ if (c.type === "not") checkCondition(c.condition, depth + 1);
2250
+ if (c.type === "ruleSet") {
2251
+ if (c.intervalSeconds !== void 0 && (depth > 0 || c.builtin)) error("RULESET_COMPOSITION_UNSUPPORTED");
2252
+ if (c.builtin && c.format !== "rule-set") error("BUILTIN_RULESET_FORMAT");
2253
+ if (c.url) {
2254
+ const key = new URL(c.url).href;
2255
+ const settings = `${c.format}:${c.intervalSeconds ?? 86400}`;
2256
+ if (formats.has(key) && formats.get(key) !== settings) error("RULESET_FORMAT_CONFLICT");
2257
+ formats.set(key, settings);
2258
+ }
2259
+ }
2138
2260
  };
2139
- }
2140
- function defineRoutes(input) {
2141
- inspectDefinition(input);
2142
- exactDefinition(input, ["when", "to"]);
2143
- if (!Array.isArray(input.when)) fail$1("INVALID_ROUTE_DEFINITION");
2144
- return input.when.map((when) => ({
2145
- type: "route",
2146
- when,
2147
- to: input.to
2148
- }));
2149
- }
2150
- function selectProxies(nodes, query = {}) {
2151
- inspectDefinition({
2152
- nodes,
2153
- query
2261
+ for (const rule of p.rules) {
2262
+ checkPolicy(rule.then);
2263
+ checkCondition(rule.when, 0);
2264
+ }
2265
+ checkPolicy(p.fallback);
2266
+ if (diagnostics.some((d) => d.severity === "error")) return failure();
2267
+ if (formats.size) diagnostics.push({
2268
+ severity: "warning",
2269
+ code: "EXTERNAL_RULESET_UNVERIFIED",
2270
+ path: "rules",
2271
+ message: "External rule sets are resolved by the client, not by the compiler."
2154
2272
  });
2155
- exactDefinition(query, [
2156
- "ids",
2157
- "regions",
2158
- "providers",
2159
- "tags"
2160
- ]);
2161
- if (!Array.isArray(nodes) || nodes.some((node) => !node || typeof node !== "object")) fail$1("DEFINITION_NOT_DATA");
2162
- for (const values of Object.values(query)) if (values !== void 0 && !Array.isArray(values)) fail$1("DEFINITION_NOT_DATA");
2163
- 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))));
2273
+ const result = deepFreeze({
2274
+ ok: true,
2275
+ artifactKind: "surge-profile",
2276
+ diagnostics,
2277
+ bindings
2278
+ });
2279
+ plans.set(result, p);
2280
+ return result;
2164
2281
  }
2165
- function lowerSurgeProfile(input) {
2166
- inspectDefinition(input);
2167
- exactDefinition(input, [
2168
- "target",
2169
- "managed",
2170
- "general",
2171
- "hosts",
2172
- "nodes",
2173
- "tunnels",
2174
- "names",
2175
- "groups",
2176
- "routes",
2177
- "fallback"
2178
- ]);
2179
- 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");
2180
- const registry = /* @__PURE__ */ new Map();
2181
- const names = Object.assign(Object.create(null), input.names);
2182
- for (const resource of [
2183
- ...input.nodes,
2184
- ...input.tunnels ?? [],
2185
- ...input.groups
2186
- ]) {
2187
- if (!resource || typeof resource !== "object" || typeof resource.id !== "string") fail$1("INVALID_RESOURCE_DEFINITION");
2188
- if (registry.has(resource.id)) fail$1("DUPLICATE_RESOURCE_ID");
2189
- registry.set(resource.id, resource);
2190
- const name = resource.type === "proxy-group" ? resource.name : "label" in resource ? resource.label ?? resource.id : resource.id;
2191
- if (resource.type === "proxy-group" && names[resource.id] !== void 0 && names[resource.id] !== name) fail$1("GROUP_NAME_CONFLICT");
2192
- Object.defineProperty(names, resource.id, {
2193
- value: names[resource.id] ?? name,
2194
- enumerable: true,
2195
- configurable: true,
2196
- writable: true
2197
- });
2282
+ function conditionOptions(c) {
2283
+ return [
2284
+ ...c.noResolve ? ["no-resolve"] : [],
2285
+ ...c.extendedMatching ? ["extended-matching"] : [],
2286
+ ...c.type === "ruleSet" && c.intervalSeconds !== void 0 ? [`update-interval=${c.intervalSeconds}`] : []
2287
+ ];
2288
+ }
2289
+ function conditionText(c) {
2290
+ switch (c.type) {
2291
+ case "all":
2292
+ case "any": return `${c.type === "all" ? "AND" : "OR"},(${c.conditions.map((x) => `(${[conditionText(x), ...conditionOptions(x)].join(",")})`).join(",")})`;
2293
+ case "not": return `NOT,((${[conditionText(c.condition), ...conditionOptions(c.condition)].join(",")}))`;
2294
+ case "port":
2295
+ case "sourcePort": return `${c.type === "port" ? "DEST-PORT" : "SRC-PORT"},${c.from}${c.to === void 0 || c.to === c.from ? "" : `-${c.to}`}`;
2296
+ case "network": return `PROTOCOL,${c.value.toUpperCase()}`;
2297
+ case "ruleSet": return `${c.format === "rule-set" ? "RULE-SET" : "DOMAIN-SET"},${c.url ?? c.builtin}`;
2298
+ default: return `${{
2299
+ domain: "DOMAIN",
2300
+ domainSuffix: "DOMAIN-SUFFIX",
2301
+ ipCidr: "IP-CIDR",
2302
+ ipCidr6: "IP-CIDR6",
2303
+ sourceIp: "SRC-IP",
2304
+ processName: "PROCESS-NAME",
2305
+ macAddress: "MAC-ADDRESS"
2306
+ }[c.type]},${c.value}`;
2198
2307
  }
2199
- function lower(destination) {
2200
- if (typeof destination === "string") {
2201
- if (!registry.has(destination)) fail$1("UNKNOWN_DESTINATION_ID");
2202
- return { ref: destination };
2203
- }
2204
- if (!destination || typeof destination !== "object") fail$1("INVALID_DESTINATION");
2205
- if ("builtin" in destination) {
2206
- exactDefinition(destination, ["builtin"]);
2207
- if (!Object.values(outbound).some((value) => value.builtin === destination.builtin)) fail$1("INVALID_DESTINATION");
2208
- return { builtin: destination.builtin };
2308
+ }
2309
+ function renderProfile(compilation, read) {
2310
+ const p = plans.get(compilation);
2311
+ if (!p) throw new RenderError("COMPILATION_FAILED");
2312
+ const name = (id) => p.names?.[id] ?? id;
2313
+ const action = (value) => "ref" in value ? name(value.ref) : value.builtin;
2314
+ const credential = (token, kind) => {
2315
+ const value = read(token);
2316
+ 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");
2317
+ return value;
2318
+ };
2319
+ const lines = [];
2320
+ if (p.managed) {
2321
+ const address = new URL(p.managed.url);
2322
+ for (const [k, v] of Object.entries(p.managed.query ?? {})) address.searchParams.set(k, typeof v === "string" ? v : read(v));
2323
+ lines.push(`#!MANAGED-CONFIG ${address.href} interval=${p.managed.intervalSeconds} strict=${p.managed.strict}`, "");
2324
+ }
2325
+ lines.push("[General]");
2326
+ for (const [k, v] of Object.entries(p.general ?? {})) {
2327
+ const value = Array.isArray(v) ? v.join(", ") : typeof v === "object" ? `${credential(v.password, "control")}@${v.listen}` : String(v);
2328
+ lines.push(`${k} = ${value}`);
2329
+ }
2330
+ lines.push("", "[Host]");
2331
+ for (const h of p.hosts ?? []) lines.push(`${h.pattern} = ${[...h.address ? [h.address] : [], ...h.server ? [`server:${h.server}`] : []].join(", ")}`);
2332
+ lines.push("", "[Proxy]");
2333
+ for (const n of p.nodes) lines.push(surgeProxy(n, read, name));
2334
+ for (const t of p.tunnels ?? []) lines.push(`${name(t.id)} = ${t.type}, section-name=${t.sectionName}`);
2335
+ for (const t of p.tunnels ?? []) {
2336
+ lines.push("", `[${t.type === "tailscale" ? "Tailscale" : "WireGuard"} ${t.sectionName}]`);
2337
+ if (t.type === "tailscale") {
2338
+ lines.push(`auth-key = ${credential(t.authKey, "tailscale")}`, `hostname = ${t.hostname}`);
2339
+ if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
2340
+ if (t.autoAddMagicDnsRule !== void 0) lines.push(`auto-add-magic-dns-rule = ${t.autoAddMagicDnsRule}`);
2341
+ if (t.idleKeepalive !== void 0) lines.push(`idle-keepalive = ${t.idleKeepalive}`);
2342
+ } else {
2343
+ lines.push(`private-key = ${credential(t.privateKey, "key")}`, `self-ip = ${t.selfIp}`);
2344
+ if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
2345
+ if (t.mtu !== void 0) lines.push(`mtu = ${t.mtu}`);
2346
+ for (const peer of t.peers) {
2347
+ const values = [`public-key = ${peer.publicKey}`];
2348
+ if (peer.presharedKey) values.push(`preshared-key = ${credential(peer.presharedKey, "key")}`);
2349
+ values.push(`allowed-ips = "${peer.allowedIps.join(", ")}"`, `endpoint = ${peer.endpoint}`);
2350
+ if (peer.persistentKeepalive !== void 0) values.push(`keepalive = ${peer.persistentKeepalive}`);
2351
+ lines.push(`peer = (${values.join(", ")})`);
2352
+ }
2209
2353
  }
2210
- if (registry.get(destination.id) !== destination) fail$1("UNREGISTERED_DESTINATION_INSTANCE");
2211
- return { ref: destination.id };
2212
2354
  }
2213
- const groups = input.groups.map((definition) => {
2214
- exactDefinition(definition, [
2215
- "type",
2216
- "id",
2217
- "name",
2218
- "algorithm",
2219
- "members",
2220
- "url",
2221
- "intervalSeconds",
2222
- "timeoutSeconds"
2223
- ]);
2224
- if (definition.type !== "proxy-group") fail$1("INVALID_GROUP_DEFINITION");
2225
- if (!definition.algorithm || !["select", "surge-smart"].includes(definition.algorithm.type)) fail$1("UNSUPPORTED_GROUP_ALGORITHM");
2226
- exactDefinition(definition.algorithm, ["type"]);
2227
- if (!Array.isArray(definition.members)) fail$1("INVALID_GROUP_DEFINITION");
2228
- const { id, url, intervalSeconds, timeoutSeconds } = definition;
2229
- return {
2230
- id,
2231
- type: definition.algorithm.type === "select" ? "select" : "smart",
2232
- members: definition.members.map(lower),
2233
- ...url === void 0 ? {} : { url },
2234
- ...intervalSeconds === void 0 ? {} : { intervalSeconds },
2235
- ...timeoutSeconds === void 0 ? {} : { timeoutSeconds }
2236
- };
2237
- });
2238
- const rules = input.routes.map((definition) => {
2239
- exactDefinition(definition, [
2240
- "type",
2241
- "when",
2242
- "to"
2243
- ]);
2244
- if (definition.type !== "route") fail$1("INVALID_ROUTE_DEFINITION");
2245
- return {
2246
- when: definition.when,
2247
- then: lower(definition.to)
2248
- };
2249
- });
2250
- const { routes: _routes, groups: _groups, fallback, ...rest } = input;
2251
- return snapshot({
2252
- ...rest,
2253
- names,
2254
- groups,
2255
- rules,
2256
- fallback: lower(fallback)
2355
+ lines.push("", "[Proxy Group]");
2356
+ for (const g of p.groups) lines.push(`${name(g.id)} = ${[
2357
+ g.type,
2358
+ ...g.members.map(action),
2359
+ ...g.url ? [`url=${g.url}`] : [],
2360
+ ...g.intervalSeconds !== void 0 ? [`interval=${g.intervalSeconds}`] : [],
2361
+ ...g.timeoutSeconds !== void 0 ? [`timeout=${g.timeoutSeconds}`] : []
2362
+ ].join(", ")}`);
2363
+ lines.push("", "[Rule]");
2364
+ for (const r of p.rules) lines.push([
2365
+ conditionText(r.when),
2366
+ action(r.then),
2367
+ ...conditionOptions(r.when)
2368
+ ].join(","));
2369
+ lines.push(`FINAL,${action(p.fallback)}`, "");
2370
+ return deepFreeze({
2371
+ artifactKind: "surge-profile",
2372
+ content: lines.join("\n")
2257
2373
  });
2258
2374
  }
2259
- function condition(value) {
2260
- inspectDefinition(value);
2261
- return value;
2375
+ function renderSurgeProfile(compilation, resolveSecret) {
2376
+ return renderProfile(compilation, secretReader(resolveSecret));
2262
2377
  }
2263
- function atom(type) {
2264
- return (value, options = {}) => {
2265
- inspectDefinition(options);
2266
- return condition({
2267
- ...options,
2268
- type,
2269
- value
2270
- });
2271
- };
2378
+ function renderSurgeProfiles(compilations, resolveSecret) {
2379
+ if (compilations.some((c) => !plans.has(c))) throw new RenderError("COMPILATION_FAILED");
2380
+ const read = secretReader(resolveSecret);
2381
+ return deepFreeze(compilations.map((c) => renderProfile(c, read)));
2272
2382
  }
2273
- const surgeMatch = {
2274
- domain: atom("domain"),
2275
- domainSuffix: atom("domainSuffix"),
2276
- ipCidr: atom("ipCidr"),
2277
- ipCidr6: atom("ipCidr6"),
2278
- sourceIp: atom("sourceIp"),
2279
- processName: atom("processName"),
2280
- macAddress: atom("macAddress"),
2281
- network: (value, options = {}) => {
2282
- inspectDefinition(options);
2283
- return condition({
2284
- ...options,
2285
- type: "network",
2286
- value
2287
- });
2288
- },
2289
- port: (from, to, options = {}) => {
2290
- inspectDefinition(options);
2291
- return condition({
2292
- ...options,
2293
- type: "port",
2294
- from,
2295
- ...to === void 0 ? {} : { to }
2296
- });
2297
- },
2298
- sourcePort: (from, to, options = {}) => {
2299
- inspectDefinition(options);
2300
- return condition({
2301
- ...options,
2302
- type: "sourcePort",
2303
- from,
2304
- ...to === void 0 ? {} : { to }
2305
- });
2306
- },
2307
- all: (conditions, options = {}) => {
2308
- inspectDefinition({
2309
- conditions,
2310
- options
2311
- });
2312
- return condition({
2313
- ...options,
2314
- type: "all",
2315
- conditions: [...conditions]
2316
- });
2317
- },
2318
- any: (conditions, options = {}) => {
2319
- inspectDefinition({
2320
- conditions,
2321
- options
2322
- });
2323
- return condition({
2324
- ...options,
2325
- type: "any",
2326
- conditions: [...conditions]
2327
- });
2328
- },
2329
- not: (value, options = {}) => {
2330
- inspectDefinition({
2331
- value,
2332
- options
2333
- });
2334
- return condition({
2335
- ...options,
2336
- type: "not",
2337
- condition: value
2338
- });
2339
- },
2340
- ruleSet: (options) => {
2341
- inspectDefinition(options);
2342
- return condition({
2343
- ...options,
2344
- type: "ruleSet"
2345
- });
2346
- }
2347
- };
2348
2383
  //#endregion
2349
2384
  //#region src/profile.ts
2350
2385
  const fail = (code) => {
@@ -2478,11 +2513,15 @@ function surgeCondition$1(condition, depth = 0) {
2478
2513
  if (!parsed.success) return fail("PROFILE_CONDITION_UNSUPPORTED");
2479
2514
  const value = parsed.data;
2480
2515
  if (value.type === "ruleSet") return surgeCondition$1(value.when, depth);
2481
- if (value.type !== "nativeRuleSet" || value.engine !== "surge" || value.intervalSeconds !== void 0) return fail("PROFILE_CONDITION_UNSUPPORTED");
2516
+ if (value.type !== "nativeRuleSet" || value.engine !== "surge") return fail("PROFILE_CONDITION_UNSUPPORTED");
2517
+ if (depth > 0 && value.intervalSeconds !== void 0) return fail("RULESET_COMPOSITION_UNSUPPORTED");
2482
2518
  return {
2483
2519
  type: "ruleSet",
2484
2520
  format: value.format,
2485
- url: value.url
2521
+ url: value.url,
2522
+ ...value.intervalSeconds !== void 0 ? { intervalSeconds: value.intervalSeconds } : {},
2523
+ ...value.noResolve !== void 0 ? { noResolve: value.noResolve } : {},
2524
+ ...value.extendedMatching !== void 0 ? { extendedMatching: value.extendedMatching } : {}
2486
2525
  };
2487
2526
  }
2488
2527
  if (condition.type === "all" || condition.type === "any") {
@@ -2663,6 +2702,12 @@ const ruleSet = (definition) => ({
2663
2702
  ...definition,
2664
2703
  type: "ruleSet"
2665
2704
  });
2705
+ function options(value, keys) {
2706
+ inspectDefinition(value);
2707
+ exactDefinition(value, keys);
2708
+ if (Object.values(value).some((v) => v !== void 0 && typeof v !== "boolean")) throw new ProfileDefinitionError("INVALID_MATCH_OPTIONS");
2709
+ return { ...value };
2710
+ }
2666
2711
  const match = {
2667
2712
  processName: (value) => {
2668
2713
  if (!processNameSchema.safeParse(value).success) throw new Error("INVALID_PROCESS_NAME");
@@ -2672,17 +2717,20 @@ const match = {
2672
2717
  };
2673
2718
  },
2674
2719
  ruleSet: (set) => set,
2675
- domain: (value) => ({
2720
+ domain: (value, opts = {}) => ({
2676
2721
  type: "domain",
2677
- value
2722
+ value,
2723
+ ...options(opts, ["extendedMatching"])
2678
2724
  }),
2679
- domainSuffix: (value) => ({
2725
+ domainSuffix: (value, opts = {}) => ({
2680
2726
  type: "domainSuffix",
2681
- value
2727
+ value,
2728
+ ...options(opts, ["extendedMatching"])
2682
2729
  }),
2683
- ipCidr: (value) => ({
2730
+ ipCidr: (value, opts = {}) => ({
2684
2731
  type: "ipCidr",
2685
- value
2732
+ value,
2733
+ ...options(opts, ["noResolve"])
2686
2734
  }),
2687
2735
  sourceIp: (value) => ({
2688
2736
  type: "sourceIp",
@@ -2715,6 +2763,58 @@ const match = {
2715
2763
  condition
2716
2764
  })
2717
2765
  };
2766
+ function nativeConstructor(engine) {
2767
+ function construct(value) {
2768
+ inspectDefinition(value);
2769
+ if (!value || typeof value !== "object") throw new ProfileDefinitionError("INVALID_NATIVE_RULESET");
2770
+ exactDefinition(value, [
2771
+ "id",
2772
+ "url",
2773
+ "format",
2774
+ "intervalSeconds",
2775
+ "noResolve",
2776
+ "extendedMatching",
2777
+ "behavior",
2778
+ "to"
2779
+ ]);
2780
+ const input = value;
2781
+ const { to, ...resource } = input;
2782
+ exactDefinition(resource, [
2783
+ "id",
2784
+ "url",
2785
+ "format",
2786
+ "intervalSeconds",
2787
+ ...engine === "surge" ? ["noResolve", "extendedMatching"] : engine === "mihomo" ? ["behavior"] : []
2788
+ ]);
2789
+ const parsed = nativeRuleSetSchema.safeParse({
2790
+ ...engine === "surge" ? { format: "rule-set" } : {},
2791
+ ...resource,
2792
+ id: resource.id ?? "ruleset-pending",
2793
+ type: "nativeRuleSet",
2794
+ engine
2795
+ });
2796
+ if (!parsed.success) throw new ProfileDefinitionError("INVALID_NATIVE_RULESET");
2797
+ const { id: _id, type: _type, ...fields } = parsed.data;
2798
+ const id = resource.id ?? `ruleset-${createHash("sha256").update(JSON.stringify(Object.entries(fields).filter(([, value]) => value !== void 0).sort(([a], [b]) => a.localeCompare(b)))).digest("hex").slice(0, 16)}`;
2799
+ const when = snapshotDefinition({
2800
+ ...parsed.data,
2801
+ id
2802
+ });
2803
+ if (Object.hasOwn(input, "to")) {
2804
+ if (to === void 0) throw new ProfileDefinitionError("INVALID_DESTINATION");
2805
+ return {
2806
+ type: "route",
2807
+ when,
2808
+ to
2809
+ };
2810
+ }
2811
+ return when;
2812
+ }
2813
+ return construct;
2814
+ }
2815
+ const surgeRuleSet = nativeConstructor("surge");
2816
+ const mihomoRuleSet = nativeConstructor("mihomo");
2817
+ const singboxRuleSet = nativeConstructor("sing-box");
2718
2818
  const direct = () => ({ type: "direct" });
2719
2819
  const reject = () => ({ type: "reject" });
2720
2820
  const route = (to) => ({
@@ -2775,18 +2875,12 @@ const surge$1 = {
2775
2875
  config: surgeConfig,
2776
2876
  match: surgeMatch,
2777
2877
  smart: () => ({ type: "surge-smart" }),
2778
- ruleSet: (options) => ({
2779
- format: "rule-set",
2780
- ...options,
2781
- type: "nativeRuleSet",
2782
- engine: "surge"
2783
- })
2878
+ ruleSet: surgeRuleSet
2879
+ };
2880
+ const mihomo = {
2881
+ ruleSet: mihomoRuleSet,
2882
+ ruleProvider: mihomoRuleSet
2784
2883
  };
2785
- const mihomo = { ruleProvider: (options) => ({
2786
- ...options,
2787
- type: "nativeRuleSet",
2788
- engine: "mihomo"
2789
- }) };
2790
2884
  /** Protocol constructors keep credentials and options specific to their protocol. */
2791
2885
  function nodeConstructor(type) {
2792
2886
  return (options) => ({
@@ -2804,11 +2898,7 @@ const proxy = {
2804
2898
  vless: nodeConstructor("vless")
2805
2899
  };
2806
2900
  const singbox$1 = {
2807
- ruleSet: (options) => ({
2808
- ...options,
2809
- type: "nativeRuleSet",
2810
- engine: "sing-box"
2811
- }),
2901
+ ruleSet: singboxRuleSet,
2812
2902
  tailscale: (options) => ({
2813
2903
  ...options,
2814
2904
  type: "sing-box-tailscale"
@@ -2994,16 +3084,23 @@ function singbox(plan, secret) {
2994
3084
  }
2995
3085
  return config;
2996
3086
  }
3087
+ function surgeOptions(condition) {
3088
+ return [
3089
+ ...condition.type === "ipCidr" && condition.noResolve !== false ? ["no-resolve"] : [],
3090
+ ...condition.type === "nativeRuleSet" && condition.engine === "surge" && condition.noResolve ? ["no-resolve"] : [],
3091
+ ..."extendedMatching" in condition && condition.extendedMatching ? ["extended-matching"] : []
3092
+ ].map((value) => `,${value}`).join("");
3093
+ }
2997
3094
  function surgeCondition(condition) {
2998
3095
  switch (condition.type) {
2999
3096
  case "ruleSet": return surgeCondition(condition.when);
3000
3097
  case "nativeRuleSet": return `${condition.format === "domain-set" ? "DOMAIN-SET" : "RULE-SET"},${condition.url}`;
3001
3098
  case "all":
3002
- case "any": return `${condition.type === "all" ? "AND" : "OR"},(${condition.conditions.map((c) => `(${surgeCondition(c)})`).join(",")})`;
3003
- case "not": return `NOT,((${surgeCondition(condition.condition)}))`;
3099
+ case "any": return `${condition.type === "all" ? "AND" : "OR"},(${condition.conditions.map((c) => `(${surgeCondition(c)}${surgeOptions(c)})`).join(",")})`;
3100
+ case "not": return `NOT,((${surgeCondition(condition.condition)}${surgeOptions(condition.condition)}))`;
3004
3101
  case "domain": return `DOMAIN,${condition.value}`;
3005
3102
  case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
3006
- case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value},no-resolve`;
3103
+ case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value}`;
3007
3104
  case "processName": return `PROCESS-NAME,${condition.value}`;
3008
3105
  case "sourceIp": return `SRC-IP,${condition.value}`;
3009
3106
  case "network": return `PROTOCOL,${condition.value.toUpperCase()}`;
@@ -3022,10 +3119,7 @@ function surge(plan, secret) {
3022
3119
  lines.push("", "[Rule]");
3023
3120
  for (const rule of plan.rules) {
3024
3121
  lines.push(`# ${rule.id}`);
3025
- if (rule.when.type === "ipCidr") {
3026
- const condition = surgeCondition(rule.when).replace(/,no-resolve$/, "");
3027
- lines.push(`${condition},${policy(rule.then)},no-resolve`);
3028
- } else lines.push(`${surgeCondition(rule.when)},${policy(rule.then)}${rule.when.type === "nativeRuleSet" && rule.when.intervalSeconds !== void 0 ? `,update-interval=${rule.when.intervalSeconds}` : ""}`);
3122
+ lines.push(`${surgeCondition(rule.when)},${policy(rule.then)}${surgeOptions(rule.when)}${rule.when.type === "nativeRuleSet" && rule.when.intervalSeconds !== void 0 ? `,update-interval=${rule.when.intervalSeconds}` : ""}`);
3029
3123
  }
3030
3124
  lines.push(`FINAL,${policy(plan.program.fallback)}`);
3031
3125
  return lines.join("\n") + "\n";
@@ -3295,26 +3389,67 @@ async function publishProfiles(files, surgeDirectory, io = { rename }) {
3295
3389
  }
3296
3390
  //#endregion
3297
3391
  //#region src/profile-build.ts
3298
- async function publish(profiles, output, resolver) {
3392
+ function compileBatch(profiles, output) {
3393
+ const entries = Object.entries(profiles);
3394
+ const compiled = [];
3395
+ let outputDirectoryChecked = false;
3396
+ const result = (code) => ({
3397
+ ok: code === "CHECKED",
3398
+ code,
3399
+ entries,
3400
+ compiled,
3401
+ outputDirectoryChecked
3402
+ });
3403
+ if (!entries.length || entries.length > 16 || entries.some(([id]) => !/^[a-z0-9][a-z0-9-]*$/.test(id))) return result("INVALID_PROFILE_FILENAMES");
3404
+ compiled.push(...entries.map(([, profile]) => compileProfile(profile)));
3405
+ const invalid = compiled.find((profile) => !profile.ok);
3406
+ if (invalid) return result(invalid.engine === "invalid" ? invalid.code : "COMPILATION_FAILED");
3407
+ if (output !== void 0) {
3408
+ outputDirectoryChecked = true;
3409
+ if (compiled.some((profile) => profile.engine === "sing-box" && profile.compilation.plans.some((plan) => plan.program.endpoints?.some((endpoint) => pathsOverlap(output, endpoint.stateDirectory))))) return result("ENDPOINT_STATE_OVERLAP");
3410
+ }
3411
+ return result("CHECKED");
3412
+ }
3413
+ function checkBuild(input) {
3414
+ const root = process.cwd();
3415
+ let definition;
3299
3416
  try {
3300
- const entries = Object.entries(profiles);
3301
- if (!entries.length || entries.length > 16 || entries.some(([id]) => !/^[a-z0-9][a-z0-9-]*$/.test(id))) return {
3302
- published: false,
3303
- exitCode: 1,
3304
- code: "INVALID_PROFILE_FILENAMES"
3305
- };
3306
- const compiled = entries.map(([, profile]) => compileProfile(profile));
3307
- const invalid = compiled.find((profile) => !profile.ok);
3308
- if (invalid) return {
3309
- published: false,
3310
- exitCode: 1,
3311
- code: invalid.engine === "invalid" ? invalid.code : "COMPILATION_FAILED"
3417
+ definition = defineBuild(input);
3418
+ } catch {
3419
+ return {
3420
+ ok: false,
3421
+ code: "INVALID_BUILD_DEFINITION",
3422
+ profileCount: 0,
3423
+ outputDirectoryChecked: false,
3424
+ profiles: []
3312
3425
  };
3313
- if (compiled.some((profile) => profile.engine === "sing-box" && profile.compilation.plans.some((plan) => plan.program.endpoints?.some((endpoint) => pathsOverlap(resolve(output), endpoint.stateDirectory))))) return {
3426
+ }
3427
+ const checked = compileBatch(definition.profiles, definition.outDir === void 0 ? void 0 : resolve(root, definition.outDir));
3428
+ return {
3429
+ ok: checked.ok,
3430
+ code: checked.code,
3431
+ profileCount: checked.entries.length,
3432
+ outputDirectoryChecked: checked.outputDirectoryChecked,
3433
+ profiles: checked.compiled.map((profile, index) => ({
3434
+ id: checked.entries[index][0],
3435
+ engine: profile.engine,
3436
+ ok: profile.ok,
3437
+ ...profile.engine === "invalid" ? {
3438
+ code: profile.code,
3439
+ diagnostics: []
3440
+ } : { diagnostics: profile.compilation.diagnostics }
3441
+ }))
3442
+ };
3443
+ }
3444
+ async function publish(profiles, output, resolver) {
3445
+ try {
3446
+ const checked = compileBatch(profiles, output);
3447
+ if (!checked.ok) return {
3314
3448
  published: false,
3315
3449
  exitCode: 1,
3316
- code: "ENDPOINT_STATE_OVERLAP"
3450
+ code: checked.code
3317
3451
  };
3452
+ const { entries, compiled } = checked;
3318
3453
  const read = secretReader(resolver);
3319
3454
  const files = /* @__PURE__ */ new Map();
3320
3455
  for (const [index, profile] of compiled.entries()) {
@@ -3357,11 +3492,14 @@ function defineBuild(input) {
3357
3492
  record(input, [
3358
3493
  "profiles",
3359
3494
  "preflight",
3360
- "resolveSecret"
3495
+ "resolveSecret",
3496
+ "outDir"
3361
3497
  ]);
3498
+ if (input.outDir !== void 0 && (typeof input.outDir !== "string" || !input.outDir.trim() || input.outDir.trim() !== input.outDir || input.outDir.includes("\0"))) throw new Error();
3362
3499
  record(input.profiles);
3363
3500
  for (const callback of [input.preflight, input.resolveSecret]) if (callback !== void 0 && typeof callback !== "function") throw new Error();
3364
3501
  return Object.freeze({
3502
+ ...input.outDir === void 0 ? {} : { outDir: input.outDir },
3365
3503
  profiles: snapshotProfile(input.profiles),
3366
3504
  ...input.preflight === void 0 ? {} : { preflight: input.preflight },
3367
3505
  ...input.resolveSecret === void 0 ? {} : { resolveSecret: input.resolveSecret }
@@ -3382,6 +3520,7 @@ function profileBuildFailure(code, validation = false, profileCount = 0) {
3382
3520
  }
3383
3521
  /** Pure orchestration result; the CLI owns stdout and process exit status. */
3384
3522
  async function runBuild(input, output, options = {}) {
3523
+ const root = process.cwd();
3385
3524
  let validation;
3386
3525
  try {
3387
3526
  record(options, ["validation"]);
@@ -3399,6 +3538,7 @@ async function runBuild(input, output, options = {}) {
3399
3538
  const profileCount = Object.keys(definition.profiles).length;
3400
3539
  const failure = (code) => profileBuildFailure(code, validation, profileCount);
3401
3540
  if (typeof output !== "string" || !output.trim()) return failure("INVALID_OUTPUT_DIRECTORY");
3541
+ output = resolve(root, output);
3402
3542
  if (validation && !definition.resolveSecret) return failure("VALIDATION_RESOLVER_REQUIRED");
3403
3543
  let codes;
3404
3544
  try {
@@ -3424,4 +3564,4 @@ async function runBuild(input, output, options = {}) {
3424
3564
  };
3425
3565
  }
3426
3566
  //#endregion
3427
- export { defineRoute as A, compileStrategyGroups as B, strategy as C, defineProfile as D, compileProfile as E, renderSurgeProfile as F, surgeProxy as G, nativeNameSchema as H, renderSurgeProfiles as I, assertData as J, validateProxyOptions as K, secretReader as L, outbound as M, selectProxies as N, ProfileDefinitionError as O, compileSurgeProfile as P, requestSchema as Q, compile as R, slot as S, use as T, targetCatalog as U, isReservedNativeName as V, RenderError as W, idSchema as X, deepFreeze as Y, nodeSchema as Z, ruleSet as _, render as a, sequence as b, direct as c, mihomo as d, policy as f, rule as g, route as h, buildToDirectory as i, defineRoutes as j, defineProxyGroup as k, group as l, reject as m, profileBuildFailure as n, block as o, proxy as p, StaticRuleSetUnknownError as q, runBuild as r, defineConfig as s, defineBuild as t, match as u, secret as v, surge$1 as w, singbox$1 as x, selectNodes as y, explain as z };
3567
+ export { renderSurgeProfiles as A, validateProxyOptions as B, strategy as C, defineProfile as D, compileProfile as E, isReservedNativeName as F, nodeSchema as G, assertData as H, nativeNameSchema as I, defineProxyGroup as J, requestSchema as K, targetCatalog as L, compile as M, explain as N, compileSurgeProfile as O, compileStrategyGroups as P, selectProxies as Q, RenderError as R, slot as S, use as T, deepFreeze as U, StaticRuleSetUnknownError as V, idSchema as W, defineRoutes as X, defineRoute as Y, outbound as Z, ruleSet as _, render as a, sequence as b, direct as c, mihomo as d, policy as f, rule as g, route as h, buildToDirectory as i, secretReader as j, renderSurgeProfile as k, group as l, reject as m, defineBuild as n, block as o, proxy as p, ProfileDefinitionError as q, runBuild as r, defineConfig as s, checkBuild as t, match as u, secret as v, surge$1 as w, singbox$1 as x, selectNodes as y, surgeProxy as z };