proxylang 0.1.4 → 0.1.6

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.
@@ -2,14 +2,339 @@ import { z } from "zod";
2
2
  import { isIP } from "node:net";
3
3
  import ipaddr from "ipaddr.js";
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);
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("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;
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
+ inspect(input);
86
+ return snapshot(input);
87
+ }
88
+ function exact(value, keys) {
89
+ if (!value || typeof value !== "object" || Array.isArray(value)) fail("DEFINITION_NOT_DATA");
90
+ if (Object.keys(value).some((key) => !keys.includes(key))) fail("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
+ inspect(input);
101
+ exact(input, [
102
+ "id",
103
+ "name",
104
+ "algorithm",
105
+ "members",
106
+ "url",
107
+ "intervalSeconds",
108
+ "timeoutSeconds"
109
+ ]);
110
+ if (!input.algorithm || !["select", "surge-smart"].includes(input.algorithm.type)) fail("UNSUPPORTED_GROUP_ALGORITHM");
111
+ exact(input.algorithm, ["type"]);
112
+ if (!Array.isArray(input.members)) fail("INVALID_GROUP_DEFINITION");
113
+ return {
114
+ ...input,
115
+ type: "proxy-group",
116
+ algorithm: { ...input.algorithm },
117
+ members: [...input.members]
118
+ };
119
+ }
120
+ function defineRoute(input) {
121
+ inspect(input);
122
+ exact(input, ["when", "to"]);
123
+ return {
124
+ ...input,
125
+ type: "route"
126
+ };
127
+ }
128
+ function defineRoutes(input) {
129
+ inspect(input);
130
+ exact(input, ["when", "to"]);
131
+ if (!Array.isArray(input.when)) fail("INVALID_ROUTE_DEFINITION");
132
+ return input.when.map((when) => ({
133
+ type: "route",
134
+ when,
135
+ to: input.to
136
+ }));
137
+ }
138
+ function selectProxies(nodes, query = {}) {
139
+ inspect({
140
+ nodes,
141
+ query
142
+ });
143
+ exact(query, [
144
+ "ids",
145
+ "regions",
146
+ "providers",
147
+ "tags"
148
+ ]);
149
+ if (!Array.isArray(nodes) || nodes.some((node) => !node || typeof node !== "object")) fail("DEFINITION_NOT_DATA");
150
+ for (const values of Object.values(query)) if (values !== void 0 && !Array.isArray(values)) fail("DEFINITION_NOT_DATA");
151
+ 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))));
152
+ }
153
+ function defineSurgeProfile(input) {
154
+ inspect(input);
155
+ exact(input, [
156
+ "target",
157
+ "managed",
158
+ "general",
159
+ "hosts",
160
+ "nodes",
161
+ "tunnels",
162
+ "names",
163
+ "groups",
164
+ "routes",
165
+ "fallback"
166
+ ]);
167
+ 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");
168
+ const registry = /* @__PURE__ */ new Map();
169
+ const names = Object.assign(Object.create(null), input.names);
170
+ for (const resource of [
171
+ ...input.nodes,
172
+ ...input.tunnels ?? [],
173
+ ...input.groups
174
+ ]) {
175
+ if (!resource || typeof resource !== "object" || typeof resource.id !== "string") fail("INVALID_RESOURCE_DEFINITION");
176
+ if (registry.has(resource.id)) fail("DUPLICATE_RESOURCE_ID");
177
+ registry.set(resource.id, resource);
178
+ const name = resource.type === "proxy-group" ? resource.name : "label" in resource ? resource.label ?? resource.id : resource.id;
179
+ if (resource.type === "proxy-group" && names[resource.id] !== void 0 && names[resource.id] !== name) fail("GROUP_NAME_CONFLICT");
180
+ Object.defineProperty(names, resource.id, {
181
+ value: names[resource.id] ?? name,
182
+ enumerable: true,
183
+ configurable: true,
184
+ writable: true
185
+ });
186
+ }
187
+ function lower(destination) {
188
+ if (!destination || typeof destination !== "object") fail("INVALID_DESTINATION");
189
+ if ("builtin" in destination) {
190
+ exact(destination, ["builtin"]);
191
+ if (!Object.values(outbound).some((value) => value.builtin === destination.builtin)) fail("INVALID_DESTINATION");
192
+ return { builtin: destination.builtin };
193
+ }
194
+ if (registry.get(destination.id) !== destination) fail("UNREGISTERED_DESTINATION_INSTANCE");
195
+ return { ref: destination.id };
196
+ }
197
+ const groups = input.groups.map((definition) => {
198
+ exact(definition, [
199
+ "type",
200
+ "id",
201
+ "name",
202
+ "algorithm",
203
+ "members",
204
+ "url",
205
+ "intervalSeconds",
206
+ "timeoutSeconds"
207
+ ]);
208
+ if (definition.type !== "proxy-group") fail("INVALID_GROUP_DEFINITION");
209
+ if (!definition.algorithm || !["select", "surge-smart"].includes(definition.algorithm.type)) fail("UNSUPPORTED_GROUP_ALGORITHM");
210
+ exact(definition.algorithm, ["type"]);
211
+ if (!Array.isArray(definition.members)) fail("INVALID_GROUP_DEFINITION");
212
+ const { id, url, intervalSeconds, timeoutSeconds } = definition;
213
+ return {
214
+ id,
215
+ type: definition.algorithm.type === "select" ? "select" : "smart",
216
+ members: definition.members.map(lower),
217
+ ...url === void 0 ? {} : { url },
218
+ ...intervalSeconds === void 0 ? {} : { intervalSeconds },
219
+ ...timeoutSeconds === void 0 ? {} : { timeoutSeconds }
220
+ };
221
+ });
222
+ const rules = input.routes.map((definition) => {
223
+ exact(definition, [
224
+ "type",
225
+ "when",
226
+ "to"
227
+ ]);
228
+ if (definition.type !== "route") fail("INVALID_ROUTE_DEFINITION");
229
+ return {
230
+ when: definition.when,
231
+ then: lower(definition.to)
232
+ };
233
+ });
234
+ const { routes: _routes, groups: _groups, fallback, ...rest } = input;
235
+ return snapshot({
236
+ ...rest,
237
+ names,
238
+ groups,
239
+ rules,
240
+ fallback: lower(fallback)
241
+ });
242
+ }
243
+ function condition(value) {
244
+ inspect(value);
245
+ return value;
246
+ }
247
+ function atom$2(type) {
248
+ return (value, options = {}) => {
249
+ inspect(options);
250
+ return condition({
251
+ ...options,
252
+ type,
253
+ value
254
+ });
255
+ };
256
+ }
257
+ const surgeMatch = {
258
+ domain: atom$2("domain"),
259
+ domainSuffix: atom$2("domainSuffix"),
260
+ ipCidr: atom$2("ipCidr"),
261
+ ipCidr6: atom$2("ipCidr6"),
262
+ sourceIp: atom$2("sourceIp"),
263
+ processName: atom$2("processName"),
264
+ macAddress: atom$2("macAddress"),
265
+ network: (value, options = {}) => {
266
+ inspect(options);
267
+ return condition({
268
+ ...options,
269
+ type: "network",
270
+ value
271
+ });
272
+ },
273
+ port: (from, to, options = {}) => {
274
+ inspect(options);
275
+ return condition({
276
+ ...options,
277
+ type: "port",
278
+ from,
279
+ ...to === void 0 ? {} : { to }
280
+ });
281
+ },
282
+ sourcePort: (from, to, options = {}) => {
283
+ inspect(options);
284
+ return condition({
285
+ ...options,
286
+ type: "sourcePort",
287
+ from,
288
+ ...to === void 0 ? {} : { to }
289
+ });
290
+ },
291
+ all: (conditions, options = {}) => {
292
+ inspect({
293
+ conditions,
294
+ options
295
+ });
296
+ return condition({
297
+ ...options,
298
+ type: "all",
299
+ conditions: [...conditions]
300
+ });
301
+ },
302
+ any: (conditions, options = {}) => {
303
+ inspect({
304
+ conditions,
305
+ options
306
+ });
307
+ return condition({
308
+ ...options,
309
+ type: "any",
310
+ conditions: [...conditions]
311
+ });
312
+ },
313
+ not: (value, options = {}) => {
314
+ inspect({
315
+ value,
316
+ options
317
+ });
318
+ return condition({
319
+ ...options,
320
+ type: "not",
321
+ condition: value
322
+ });
323
+ },
324
+ ruleSet: (options) => {
325
+ inspect(options);
326
+ return condition({
327
+ ...options,
328
+ type: "ruleSet"
329
+ });
330
+ }
331
+ };
332
+ //#endregion
8
333
  //#region src/schema.ts
9
334
  const idSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/).refine((x) => !x.startsWith("pl-"));
10
- const domain = z.string().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/);
11
- const ip = z.string().refine((x) => isIP(x) !== 0 && !x.includes("%"));
12
- const cidr = z.string().refine((x) => {
335
+ 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])?$/);
336
+ const ip$1 = z.string().refine((x) => isIP(x) !== 0 && !x.includes("%"));
337
+ const cidr$1 = z.string().refine((x) => {
13
338
  try {
14
339
  const [address, prefix] = x.split("/");
15
340
  if (!address || !prefix || !/^\d+$/.test(prefix) || isIP(address) === 0 || address.includes("%")) return false;
@@ -19,9 +344,9 @@ const cidr = z.string().refine((x) => {
19
344
  return false;
20
345
  }
21
346
  });
22
- const port = z.number().int().min(1).max(65535);
347
+ const port$1 = z.number().int().min(1).max(65535);
23
348
  const network = z.enum(["tcp", "udp"]);
24
- const atom = (type, value) => z.strictObject({
349
+ const atom$1 = (type, value) => z.strictObject({
25
350
  type: z.literal(type),
26
351
  value
27
352
  });
@@ -70,19 +395,19 @@ const matchSchema = z.lazy(() => z.discriminatedUnion("type", [
70
395
  id: idSchema,
71
396
  when: matchSchema
72
397
  }),
73
- atom("domain", domain),
74
- atom("domainSuffix", domain),
75
- atom("ipCidr", cidr),
76
- atom("sourceIp", cidr),
398
+ atom$1("domain", domain$1),
399
+ atom$1("domainSuffix", domain$1),
400
+ atom$1("ipCidr", cidr$1),
401
+ atom$1("sourceIp", cidr$1),
77
402
  z.strictObject({
78
403
  type: z.literal("port"),
79
- from: port,
80
- to: port
404
+ from: port$1,
405
+ to: port$1
81
406
  }).refine((v) => v.from <= v.to),
82
407
  z.strictObject({
83
408
  type: z.literal("sourcePort"),
84
- from: port,
85
- to: port
409
+ from: port$1,
410
+ to: port$1
86
411
  }).refine((v) => v.from <= v.to),
87
412
  z.strictObject({
88
413
  type: z.literal("network"),
@@ -139,8 +464,8 @@ const secretSchema = z.strictObject({
139
464
  });
140
465
  const nodeBase = {
141
466
  id: idSchema,
142
- server: z.union([ip, domain]),
143
- port,
467
+ server: z.union([ip$1, domain$1]),
468
+ port: port$1,
144
469
  via: idSchema.optional(),
145
470
  tcpFastOpen: z.boolean().optional(),
146
471
  label: z.string().min(1).max(256).optional(),
@@ -149,14 +474,14 @@ const nodeBase = {
149
474
  tags: z.array(idSchema).refine(unique).optional()
150
475
  };
151
476
  const tlsSchema = z.strictObject({
152
- serverName: domain,
477
+ serverName: domain$1,
153
478
  skipCertVerify: z.boolean().optional(),
154
479
  alpn: z.array(z.string().min(1).refine((x) => !/\p{C}/u.test(x) && Buffer.byteLength(x) <= 255)).min(1).refine(unique).optional()
155
480
  });
156
481
  const transportSchema = z.strictObject({
157
482
  type: z.literal("ws"),
158
483
  path: z.string().max(2048).regex(/^\/[A-Za-z0-9/._~-]*$/).refine((x) => !x.startsWith("//")),
159
- host: domain.optional()
484
+ host: domain$1.optional()
160
485
  });
161
486
  const uuidNode = {
162
487
  ...nodeBase,
@@ -174,7 +499,7 @@ const nodeSchema = z.discriminatedUnion("type", [
174
499
  ...nodeBase,
175
500
  type: z.literal("trojan"),
176
501
  password: secretSchema,
177
- serverName: domain.optional(),
502
+ serverName: domain$1.optional(),
178
503
  skipCertVerify: z.boolean().optional(),
179
504
  surge: z.strictObject({
180
505
  ...surgeOptions,
@@ -185,7 +510,7 @@ const nodeSchema = z.discriminatedUnion("type", [
185
510
  ...nodeBase,
186
511
  type: z.literal("anytls"),
187
512
  password: secretSchema,
188
- serverName: domain.optional(),
513
+ serverName: domain$1.optional(),
189
514
  skipCertVerify: z.boolean().optional(),
190
515
  surge: z.strictObject({
191
516
  ...surgeOptions,
@@ -226,16 +551,16 @@ const nodeSchema = z.discriminatedUnion("type", [
226
551
  const endpointSchema = z.strictObject({
227
552
  type: z.literal("sing-box-tailscale"),
228
553
  id: idSchema,
229
- hostname: domain.refine((x) => !x.includes(".")),
554
+ hostname: domain$1.refine((x) => !x.includes(".")),
230
555
  stateDirectory: z.string().max(4096).refine((x) => x.startsWith("/") && !/[\p{C}$\\]/u.test(x) && x.split("/").slice(1).every((part) => part !== "" && part !== "." && part !== "..")),
231
556
  acceptRoutes: z.boolean(),
232
- bootstrapResolver: ip,
557
+ bootstrapResolver: ip$1,
233
558
  authKey: secretSchema.optional(),
234
- exitNode: ip.optional(),
559
+ exitNode: ip$1.optional(),
235
560
  exitNodeAllowLanAccess: z.boolean().optional()
236
561
  }).refine((endpoint) => endpoint.exitNodeAllowLanAccess === void 0 || endpoint.exitNode !== void 0);
237
562
  const members = z.array(idSchema).min(1).refine(unique);
238
- const url = z.string().url().refine((value) => {
563
+ const url$1 = z.string().url().refine((value) => {
239
564
  try {
240
565
  const u = new URL(value);
241
566
  return ["http:", "https:"].includes(u.protocol) && !u.username && !u.password && !u.hash;
@@ -245,7 +570,7 @@ const url = z.string().url().refine((value) => {
245
570
  });
246
571
  const urltestAlgorithmSchema = z.strictObject({
247
572
  type: z.literal("urltest"),
248
- url,
573
+ url: url$1,
249
574
  intervalSeconds: z.number().int().min(1).max(86400).default(180),
250
575
  toleranceMs: z.number().int().min(0).max(6e4).default(50)
251
576
  });
@@ -270,7 +595,7 @@ const strategySchema = z.union([z.strictObject({
270
595
  ...strategyBase,
271
596
  implementations: implementationsSchema.refine((v) => !!v.surge || !!v["sing-box"] || !!v.mihomo || !!v.stash)
272
597
  })]);
273
- const groupSchema = z.union([
598
+ const groupSchema$1 = z.union([
274
599
  strategySchema,
275
600
  z.strictObject({
276
601
  type: z.enum(["select", "smart"]),
@@ -281,18 +606,18 @@ const groupSchema = z.union([
281
606
  type: z.literal("urltest"),
282
607
  id: idSchema,
283
608
  members,
284
- url,
609
+ url: url$1,
285
610
  intervalSeconds: z.number().int().min(1).max(86400).default(180),
286
611
  toleranceMs: z.number().int().min(0).max(6e4).default(50)
287
612
  })
288
613
  ]);
289
614
  const requestSchema = z.strictObject({
290
615
  network,
291
- domain: domain.optional(),
292
- ip: ip.optional(),
293
- sourceIp: ip.optional(),
294
- port: port.optional(),
295
- sourcePort: port.optional()
616
+ domain: domain$1.optional(),
617
+ ip: ip$1.optional(),
618
+ sourceIp: ip$1.optional(),
619
+ port: port$1.optional(),
620
+ sourcePort: port$1.optional()
296
621
  });
297
622
  const configSchema = z.strictObject({
298
623
  programs: z.record(idSchema, z.strictObject({
@@ -304,12 +629,12 @@ const configSchema = z.strictObject({
304
629
  ]),
305
630
  nodes: z.array(nodeSchema),
306
631
  endpoints: z.array(endpointSchema).max(1e3).optional(),
307
- groups: z.array(groupSchema),
632
+ groups: z.array(groupSchema$1),
308
633
  routing: z.array(entrySchema),
309
634
  fallback: actionSchema,
310
635
  listener: z.strictObject({
311
- port,
312
- resolver: ip
636
+ port: port$1,
637
+ resolver: ip$1
313
638
  }).optional()
314
639
  })),
315
640
  targets: z.array(z.strictObject({
@@ -473,7 +798,7 @@ const block = (id, rules, when) => ({
473
798
  rules,
474
799
  ...when ? { when } : {}
475
800
  });
476
- const policy$1 = (definition) => ({
801
+ const policy$2 = (definition) => ({
477
802
  type: "policy",
478
803
  ...definition
479
804
  });
@@ -503,6 +828,7 @@ const group = {
503
828
  })
504
829
  };
505
830
  const surge$1 = {
831
+ match: surgeMatch,
506
832
  smart: () => ({ type: "surge-smart" }),
507
833
  ruleSet: (options) => ({
508
834
  format: "rule-set",
@@ -1064,13 +1390,13 @@ function clashGroup(group, name = (id) => id) {
1064
1390
  } : {}
1065
1391
  };
1066
1392
  }
1067
- function conditionText(condition) {
1393
+ function conditionText$1(condition) {
1068
1394
  switch (condition.type) {
1069
- case "ruleSet": return conditionText(condition.when);
1395
+ case "ruleSet": return conditionText$1(condition.when);
1070
1396
  case "nativeRuleSet": return `RULE-SET,${condition.id}`;
1071
1397
  case "all":
1072
- case "any": return `${condition.type === "all" ? "AND" : "OR"},(${condition.conditions.map((c) => `(${conditionText(c)})`).join(",")})`;
1073
- case "not": return `NOT,((${conditionText(condition.condition)}))`;
1398
+ case "any": return `${condition.type === "all" ? "AND" : "OR"},(${condition.conditions.map((c) => `(${conditionText$1(c)})`).join(",")})`;
1399
+ case "not": return `NOT,((${conditionText$1(condition.condition)}))`;
1074
1400
  case "domain": return `DOMAIN,${condition.value}`;
1075
1401
  case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
1076
1402
  case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value},no-resolve`;
@@ -1080,13 +1406,13 @@ function conditionText(condition) {
1080
1406
  case "sourcePort": return `${condition.type === "port" ? "DST-PORT" : "SRC-PORT"},${condition.from === condition.to ? condition.from : `${condition.from}-${condition.to}`}`;
1081
1407
  }
1082
1408
  }
1083
- const policy = (action) => action.type === "route" ? action.to : action.type === "direct" ? "DIRECT" : "REJECT";
1409
+ const policy$1 = (action) => action.type === "route" ? action.to : action.type === "direct" ? "DIRECT" : "REJECT";
1084
1410
  function clashConfig(plan, secret) {
1085
1411
  const { program, target } = plan;
1086
1412
  const config = {
1087
1413
  proxies: program.nodes.map((node) => clashProxy(node, target.engine, secret)),
1088
1414
  "proxy-groups": program.groups.map((g) => clashGroup(g)),
1089
- 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)}`]
1415
+ rules: [...plan.rules.map((rule) => rule.when.type === "ipCidr" ? `${conditionText$1(rule.when).replace(/,no-resolve$/, "")},${policy$1(rule.then)},no-resolve` : `${conditionText$1(rule.when)},${policy$1(rule.then)}`), `MATCH,${policy$1(program.fallback)}`]
1090
1416
  };
1091
1417
  if (plan.nativeRuleSets.length) config["rule-providers"] = Object.fromEntries(plan.nativeRuleSets.map((r) => [r.id, {
1092
1418
  type: "http",
@@ -1334,7 +1660,7 @@ function singboxGroup(group, name = (id) => id) {
1334
1660
  interrupt_exist_connections: false
1335
1661
  };
1336
1662
  }
1337
- const inputSchema = z.strictObject({
1663
+ const inputSchema$1 = z.strictObject({
1338
1664
  target: z.strictObject({
1339
1665
  engine: z.enum([
1340
1666
  "surge",
@@ -1374,7 +1700,7 @@ function compileStrategyGroups(input) {
1374
1700
  error("INVALID_INPUT_GRAPH", "$", "输入不是有限的声明数据");
1375
1701
  return failure();
1376
1702
  }
1377
- const parsed = inputSchema.safeParse(input);
1703
+ const parsed = inputSchema$1.safeParse(input);
1378
1704
  if (!parsed.success) {
1379
1705
  error("INVALID_SCHEMA", "$", "策略目录、名字或目标不符合严格 schema");
1380
1706
  return failure();
@@ -1999,4 +2325,676 @@ async function buildToDirectory(compilation, output, resolveSecret = (token) =>
1999
2325
  };
2000
2326
  }
2001
2327
  //#endregion
2002
- export { slot as A, route as C, selectNodes as D, secret as E, deepFreeze as F, idSchema as I, nodeSchema as L, surge$1 as M, use as N, sequence as O, assertData as P, requestSchema as R, reject as S, ruleSet as T, group as _, explain as a, policy$1 as b, nativeNameSchema as c, surgeProxy as d, validateProxyOptions as f, direct as g, defineConfig as h, compile as i, strategy as j, singbox$1 as k, targetCatalog as l, block as m, render as n, compileStrategyGroups as o, StaticRuleSetUnknownError as p, secretReader as r, isReservedNativeName as s, buildToDirectory as t, RenderError as u, match as v, rule as w, proxy as x, mihomo as y };
2328
+ //#region src/surge-profile.ts
2329
+ const builtin = z.enum([
2330
+ "DIRECT",
2331
+ "REJECT",
2332
+ "REJECT-DROP",
2333
+ "REJECT-NO-DROP",
2334
+ "REJECT-TINYGIF"
2335
+ ]);
2336
+ const policy = z.union([z.strictObject({ ref: idSchema }), z.strictObject({ builtin })]);
2337
+ const token = z.strictObject({
2338
+ type: z.literal("env"),
2339
+ name: z.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/)
2340
+ });
2341
+ const safe = z.string().min(1).max(4096).refine((v) => v.trim() === v && !/[\p{C}\p{Zl}\p{Zp},=()#;"'\\]/u.test(v));
2342
+ 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])?$/);
2343
+ const hostPattern = safe.refine((v) => /^[a-zA-Z0-9*?._-]+$/.test(v));
2344
+ const ip = safe.refine((v) => isIP(v) !== 0 && !v.includes("%"));
2345
+ const cidr = (version) => safe.refine((v) => {
2346
+ try {
2347
+ const [address] = ipaddr.parseCIDR(v);
2348
+ return (!version || (address.kind() === "ipv4" ? 4 : 6) === version) && !v.includes("%");
2349
+ } catch {
2350
+ return false;
2351
+ }
2352
+ });
2353
+ const port = z.number().int().min(1).max(65535);
2354
+ function addressPort(value, allowHost, portRequired) {
2355
+ if (!portRequired && isIP(value)) return true;
2356
+ const match = /^(\[[^\]]+\]|[^:]+):(\d+)$/.exec(value);
2357
+ if (!match || Number(match[2]) < 1 || Number(match[2]) > 65535) return false;
2358
+ const host = match[1];
2359
+ return host.startsWith("[") ? isIP(host.slice(1, -1)) === 6 : isIP(host) === 4 || allowHost && domain.safeParse(host).success;
2360
+ }
2361
+ const listener = safe.refine((v) => addressPort(v, false, false));
2362
+ const endpoint = safe.refine((v) => addressPort(v, true, true));
2363
+ const dns = safe.refine((v) => v === "system" || addressPort(v, false, false));
2364
+ const url = z.string().min(1).max(4096).refine((v) => {
2365
+ try {
2366
+ const u = new URL(v);
2367
+ return /^https?:\/\//.test(v) && !u.username && !u.password && !u.hash && !/[\s\p{C},()\\"']/u.test(v);
2368
+ } catch {
2369
+ return false;
2370
+ }
2371
+ });
2372
+ const encryptedDns = z.string().max(4096).refine((v) => {
2373
+ try {
2374
+ const u = new URL(v);
2375
+ return [
2376
+ "https:",
2377
+ "h3:",
2378
+ "quic:",
2379
+ "tls:",
2380
+ "tcp:"
2381
+ ].includes(u.protocol) && !!u.hostname && !u.username && !u.password && !u.hash && !/[\s\p{C},()\\"']/u.test(v);
2382
+ } catch {
2383
+ return false;
2384
+ }
2385
+ });
2386
+ const list = (item) => z.array(item).min(1).max(1e3);
2387
+ const control = z.strictObject({
2388
+ password: token,
2389
+ listen: safe.refine((v) => addressPort(v, false, true))
2390
+ });
2391
+ const generalSchema = z.strictObject({
2392
+ loglevel: z.enum([
2393
+ "verbose",
2394
+ "info",
2395
+ "notify",
2396
+ "warning"
2397
+ ]).optional(),
2398
+ "dns-server": list(dns).optional(),
2399
+ "encrypted-dns-server": list(encryptedDns).optional(),
2400
+ "show-error-page-for-reject": z.boolean().optional(),
2401
+ "exclude-simple-hostnames": z.boolean().optional(),
2402
+ "internet-test-url": url.optional(),
2403
+ "skip-proxy": list(z.union([
2404
+ hostPattern,
2405
+ ip,
2406
+ cidr()
2407
+ ])).optional(),
2408
+ ipv6: z.boolean().optional(),
2409
+ "ipv6-vif": z.enum([
2410
+ "auto",
2411
+ "always",
2412
+ "disabled"
2413
+ ]).optional(),
2414
+ "bypass-system": z.boolean().optional(),
2415
+ replica: z.boolean().optional(),
2416
+ "tls-provider": z.enum(["default", "openssl"]).optional(),
2417
+ "bypass-tun": list(cidr()).optional(),
2418
+ "always-real-ip": list(hostPattern).optional(),
2419
+ "http-api": control.optional(),
2420
+ "http-api-web-dashboard": z.boolean().optional(),
2421
+ "external-controller-access": control.optional(),
2422
+ "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(),
2423
+ "http-listen": listener.optional(),
2424
+ "socks5-listen": listener.optional(),
2425
+ "proxy-restricted-to-lan": z.boolean().optional()
2426
+ });
2427
+ const hostSchema = z.strictObject({
2428
+ pattern: hostPattern,
2429
+ address: z.union([ip, domain]).optional(),
2430
+ server: z.union([dns, encryptedDns]).optional()
2431
+ }).refine((v) => v.address !== void 0 || v.server !== void 0);
2432
+ 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);
2433
+ const sectionName = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,127}$/);
2434
+ const tunnelSchema = z.discriminatedUnion("type", [z.strictObject({
2435
+ type: z.literal("tailscale"),
2436
+ id: idSchema,
2437
+ sectionName,
2438
+ authKey: token,
2439
+ hostname: domain,
2440
+ dnsServer: list(dns).optional(),
2441
+ autoAddMagicDnsRule: z.boolean().optional(),
2442
+ idleKeepalive: z.number().int().min(-1).max(2147483647).optional()
2443
+ }), z.strictObject({
2444
+ type: z.literal("wireguard"),
2445
+ id: idSchema,
2446
+ sectionName,
2447
+ privateKey: token,
2448
+ selfIp: ip.refine((v) => isIP(v) === 4),
2449
+ dnsServer: list(dns).optional(),
2450
+ mtu: z.number().int().min(576).max(9e3).optional(),
2451
+ peers: list(z.strictObject({
2452
+ publicKey: key,
2453
+ endpoint,
2454
+ allowedIps: list(cidr()),
2455
+ presharedKey: token.optional(),
2456
+ persistentKeepalive: z.number().int().min(0).max(65535).optional()
2457
+ }))
2458
+ })]);
2459
+ const groupSchema = z.strictObject({
2460
+ id: idSchema,
2461
+ type: z.enum(["select", "smart"]),
2462
+ members: list(policy),
2463
+ url: url.optional(),
2464
+ intervalSeconds: z.number().int().positive().max(2147483647).optional(),
2465
+ timeoutSeconds: z.number().int().positive().max(3600).optional()
2466
+ });
2467
+ const options = {
2468
+ noResolve: z.boolean().optional(),
2469
+ extendedMatching: z.boolean().optional()
2470
+ };
2471
+ const atom = (type, value) => z.strictObject({
2472
+ type: z.literal(type),
2473
+ value,
2474
+ ...options
2475
+ });
2476
+ const conditionSchema = z.lazy(() => z.union([
2477
+ atom("domain", domain),
2478
+ atom("domainSuffix", domain),
2479
+ atom("ipCidr", cidr(4)),
2480
+ atom("ipCidr6", cidr(6)),
2481
+ atom("sourceIp", z.union([ip, cidr()])),
2482
+ atom("processName", safe),
2483
+ atom("macAddress", z.string().regex(/^(?:[\da-fA-F]{2}:){5}[\da-fA-F]{2}$/)),
2484
+ z.strictObject({
2485
+ type: z.enum(["port", "sourcePort"]),
2486
+ from: port,
2487
+ to: port.optional(),
2488
+ ...options
2489
+ }).refine((v) => v.to === void 0 || v.to >= v.from),
2490
+ z.strictObject({
2491
+ type: z.literal("network"),
2492
+ value: z.enum(["tcp", "udp"]),
2493
+ ...options
2494
+ }),
2495
+ z.strictObject({
2496
+ type: z.enum(["all", "any"]),
2497
+ conditions: z.array(conditionSchema).min(2).max(100),
2498
+ ...options
2499
+ }),
2500
+ z.strictObject({
2501
+ type: z.literal("not"),
2502
+ condition: conditionSchema,
2503
+ ...options
2504
+ }),
2505
+ z.strictObject({
2506
+ type: z.literal("ruleSet"),
2507
+ format: z.enum(["rule-set", "domain-set"]),
2508
+ url: url.optional(),
2509
+ builtin: z.enum(["LAN", "SYSTEM"]).optional(),
2510
+ ...options
2511
+ }).refine((v) => v.url !== void 0 !== (v.builtin !== void 0))
2512
+ ]));
2513
+ const managedSchema = z.strictObject({
2514
+ url: url.refine((v) => !new URL(v).search && !v.includes("?")),
2515
+ 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(),
2516
+ intervalSeconds: z.number().int().min(60).max(2147483647),
2517
+ strict: z.boolean()
2518
+ });
2519
+ const inputSchema = z.strictObject({
2520
+ target: z.strictObject({
2521
+ engine: z.literal("surge"),
2522
+ platform: z.enum(["macos", "ios"]),
2523
+ version: z.string()
2524
+ }),
2525
+ managed: managedSchema.optional(),
2526
+ general: generalSchema.optional(),
2527
+ hosts: z.array(hostSchema).max(2e3).optional(),
2528
+ nodes: z.array(nodeSchema).max(1e3),
2529
+ tunnels: z.array(tunnelSchema).max(1e3).optional(),
2530
+ groups: z.array(groupSchema).max(1e3),
2531
+ rules: z.array(z.strictObject({
2532
+ when: conditionSchema,
2533
+ then: policy
2534
+ })).max(1e4),
2535
+ fallback: policy,
2536
+ names: z.record(idSchema, nativeNameSchema).optional()
2537
+ });
2538
+ const plans = /* @__PURE__ */ new WeakMap();
2539
+ function compileSurgeProfile(input) {
2540
+ const diagnostics = [];
2541
+ const error = (code) => diagnostics.push({
2542
+ severity: "error",
2543
+ code,
2544
+ path: "$",
2545
+ message: code
2546
+ });
2547
+ const failure = () => deepFreeze({
2548
+ ok: false,
2549
+ artifactKind: "surge-profile",
2550
+ diagnostics,
2551
+ bindings: []
2552
+ });
2553
+ try {
2554
+ assertData(input);
2555
+ } catch {
2556
+ error("INVALID_INPUT_GRAPH");
2557
+ return failure();
2558
+ }
2559
+ const parsed = inputSchema.safeParse(input);
2560
+ if (!parsed.success) {
2561
+ error("INVALID_SCHEMA");
2562
+ return failure();
2563
+ }
2564
+ if (parsed.data.general) {
2565
+ const general = parsed.data.general;
2566
+ parsed.data.general = Object.fromEntries(Object.keys(input.general).map((key) => [key, general[key]]));
2567
+ }
2568
+ const p = deepFreeze(parsed.data);
2569
+ if (!(p.target.platform === "macos" && p.target.version === "6.10.0") && !(p.target.platform === "ios" && p.target.version === "5.21.0")) error("UNKNOWN_TARGET");
2570
+ const tunnels = p.tunnels ?? [];
2571
+ const resources = [
2572
+ ...p.nodes,
2573
+ ...tunnels,
2574
+ ...p.groups
2575
+ ];
2576
+ if (resources.length > 1e3) error("RESOURCE_LIMIT");
2577
+ const ids = new Set(resources.map((r) => r.id));
2578
+ if (ids.size !== resources.length) error("DUPLICATE_RESOURCE");
2579
+ if (Object.keys(p.names ?? {}).some((id) => !ids.has(id))) error("UNKNOWN_NAME_MAPPING");
2580
+ const bindings = resources.map((r) => ({
2581
+ id: r.id,
2582
+ nativeName: p.names?.[r.id] ?? r.id
2583
+ }));
2584
+ if (bindings.some((b) => !nativeNameSchema.safeParse(b.nativeName).success || isReservedNativeName(b.nativeName, "surge"))) error("INVALID_NATIVE_NAME");
2585
+ if (new Set(bindings.map((b) => b.nativeName)).size !== bindings.length) error("DUPLICATE_NATIVE_NAME");
2586
+ if (new Set(tunnels.map((t) => t.sectionName)).size !== tunnels.length) error("DUPLICATE_TUNNEL_SECTION");
2587
+ if (p.target.platform === "ios" && [
2588
+ "bypass-system",
2589
+ "replica",
2590
+ "tls-provider",
2591
+ "bypass-tun",
2592
+ "external-controller-access"
2593
+ ].some((k) => Object.hasOwn(p.general ?? {}, k))) error("PLATFORM_OPTION_UNSUPPORTED");
2594
+ if (new Set((p.hosts ?? []).map((h) => h.pattern.toLowerCase())).size !== (p.hosts ?? []).length) error("DUPLICATE_HOST_PATTERN");
2595
+ const checkPolicy = (action) => {
2596
+ if ("ref" in action && !ids.has(action.ref)) error("MISSING_REFERENCE");
2597
+ };
2598
+ const edges = new Map(resources.map((r) => [r.id, []]));
2599
+ const proxyIds = new Set([...p.nodes, ...tunnels].map((n) => n.id));
2600
+ for (const node of p.nodes) {
2601
+ if (node.type === "vless") error("PROTOCOL_UNSUPPORTED");
2602
+ validateProxyOptions(node, {
2603
+ id: "profile",
2604
+ engine: "surge"
2605
+ }, diagnostics);
2606
+ if (node.via) {
2607
+ checkPolicy({ ref: node.via });
2608
+ edges.get(node.id).push(node.via);
2609
+ }
2610
+ }
2611
+ for (const group of p.groups) {
2612
+ if (group.type === "smart" && (group.url !== void 0 || group.intervalSeconds !== void 0 || group.timeoutSeconds !== void 0)) error("GROUP_OPTION_UNSUPPORTED");
2613
+ for (const member of group.members) {
2614
+ checkPolicy(member);
2615
+ if (group.type === "smart" && (!("ref" in member) || !proxyIds.has(member.ref))) error("SMART_MEMBER_UNSUPPORTED");
2616
+ if ("ref" in member) edges.get(group.id).push(member.ref);
2617
+ }
2618
+ }
2619
+ const active = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set();
2620
+ const visit = (id) => {
2621
+ if (active.has(id)) {
2622
+ error("RESOURCE_CYCLE");
2623
+ return;
2624
+ }
2625
+ if (visited.has(id)) return;
2626
+ active.add(id);
2627
+ for (const next of edges.get(id) ?? []) visit(next);
2628
+ active.delete(id);
2629
+ visited.add(id);
2630
+ };
2631
+ if (resources.length <= 1e3) for (const id of ids) visit(id);
2632
+ const formats = /* @__PURE__ */ new Map();
2633
+ const checkCondition = (c, depth) => {
2634
+ if (depth > 10) {
2635
+ error("LOGICAL_DEPTH_EXCEEDED");
2636
+ return;
2637
+ }
2638
+ if (c.noResolve !== void 0 && ![
2639
+ "ipCidr",
2640
+ "ipCidr6",
2641
+ "ruleSet"
2642
+ ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
2643
+ if (c.extendedMatching !== void 0 && ![
2644
+ "domain",
2645
+ "domainSuffix",
2646
+ "ruleSet"
2647
+ ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
2648
+ if (p.target.platform === "ios" && ["processName", "macAddress"].includes(c.type)) error("PLATFORM_RULE_UNSUPPORTED");
2649
+ if (c.type === "all" || c.type === "any") for (const child of c.conditions) checkCondition(child, depth + 1);
2650
+ if (c.type === "not") checkCondition(c.condition, depth + 1);
2651
+ if (c.type === "ruleSet") {
2652
+ if (c.builtin && c.format !== "rule-set") error("BUILTIN_RULESET_FORMAT");
2653
+ if (c.url) {
2654
+ if (formats.has(c.url) && formats.get(c.url) !== c.format) error("RULESET_FORMAT_CONFLICT");
2655
+ formats.set(c.url, c.format);
2656
+ }
2657
+ }
2658
+ };
2659
+ for (const rule of p.rules) {
2660
+ checkPolicy(rule.then);
2661
+ checkCondition(rule.when, 0);
2662
+ }
2663
+ checkPolicy(p.fallback);
2664
+ if (diagnostics.some((d) => d.severity === "error")) return failure();
2665
+ if (formats.size) diagnostics.push({
2666
+ severity: "warning",
2667
+ code: "EXTERNAL_RULESET_UNVERIFIED",
2668
+ path: "rules",
2669
+ message: "External rule sets are resolved by the client, not by the compiler."
2670
+ });
2671
+ const result = deepFreeze({
2672
+ ok: true,
2673
+ artifactKind: "surge-profile",
2674
+ diagnostics,
2675
+ bindings
2676
+ });
2677
+ plans.set(result, p);
2678
+ return result;
2679
+ }
2680
+ function conditionOptions(c) {
2681
+ return [...c.noResolve ? ["no-resolve"] : [], ...c.extendedMatching ? ["extended-matching"] : []];
2682
+ }
2683
+ function conditionText(c) {
2684
+ switch (c.type) {
2685
+ case "all":
2686
+ case "any": return `${c.type === "all" ? "AND" : "OR"},(${c.conditions.map((x) => `(${[conditionText(x), ...conditionOptions(x)].join(",")})`).join(",")})`;
2687
+ case "not": return `NOT,((${[conditionText(c.condition), ...conditionOptions(c.condition)].join(",")}))`;
2688
+ case "port":
2689
+ case "sourcePort": return `${c.type === "port" ? "DEST-PORT" : "SRC-PORT"},${c.from}${c.to === void 0 || c.to === c.from ? "" : `-${c.to}`}`;
2690
+ case "network": return `PROTOCOL,${c.value.toUpperCase()}`;
2691
+ case "ruleSet": return `${c.format === "rule-set" ? "RULE-SET" : "DOMAIN-SET"},${c.url ?? c.builtin}`;
2692
+ default: return `${{
2693
+ domain: "DOMAIN",
2694
+ domainSuffix: "DOMAIN-SUFFIX",
2695
+ ipCidr: "IP-CIDR",
2696
+ ipCidr6: "IP-CIDR6",
2697
+ sourceIp: "SRC-IP",
2698
+ processName: "PROCESS-NAME",
2699
+ macAddress: "MAC-ADDRESS"
2700
+ }[c.type]},${c.value}`;
2701
+ }
2702
+ }
2703
+ function renderProfile(compilation, read) {
2704
+ const p = plans.get(compilation);
2705
+ if (!p) throw new RenderError("COMPILATION_FAILED");
2706
+ const name = (id) => p.names?.[id] ?? id;
2707
+ const action = (value) => "ref" in value ? name(value.ref) : value.builtin;
2708
+ const credential = (token, kind) => {
2709
+ const value = read(token);
2710
+ 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");
2711
+ return value;
2712
+ };
2713
+ const lines = [];
2714
+ if (p.managed) {
2715
+ const address = new URL(p.managed.url);
2716
+ for (const [k, v] of Object.entries(p.managed.query ?? {})) address.searchParams.set(k, typeof v === "string" ? v : read(v));
2717
+ lines.push(`#!MANAGED-CONFIG ${address.href} interval=${p.managed.intervalSeconds} strict=${p.managed.strict}`, "");
2718
+ }
2719
+ lines.push("[General]");
2720
+ for (const [k, v] of Object.entries(p.general ?? {})) {
2721
+ const value = Array.isArray(v) ? v.join(", ") : typeof v === "object" ? `${credential(v.password, "control")}@${v.listen}` : String(v);
2722
+ lines.push(`${k} = ${value}`);
2723
+ }
2724
+ lines.push("", "[Host]");
2725
+ for (const h of p.hosts ?? []) lines.push(`${h.pattern} = ${[...h.address ? [h.address] : [], ...h.server ? [`server:${h.server}`] : []].join(", ")}`);
2726
+ lines.push("", "[Proxy]");
2727
+ for (const n of p.nodes) lines.push(surgeProxy(n, read, name));
2728
+ for (const t of p.tunnels ?? []) lines.push(`${name(t.id)} = ${t.type}, section-name=${t.sectionName}`);
2729
+ for (const t of p.tunnels ?? []) {
2730
+ lines.push("", `[${t.type === "tailscale" ? "Tailscale" : "WireGuard"} ${t.sectionName}]`);
2731
+ if (t.type === "tailscale") {
2732
+ lines.push(`auth-key = ${credential(t.authKey, "tailscale")}`, `hostname = ${t.hostname}`);
2733
+ if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
2734
+ if (t.autoAddMagicDnsRule !== void 0) lines.push(`auto-add-magic-dns-rule = ${t.autoAddMagicDnsRule}`);
2735
+ if (t.idleKeepalive !== void 0) lines.push(`idle-keepalive = ${t.idleKeepalive}`);
2736
+ } else {
2737
+ lines.push(`private-key = ${credential(t.privateKey, "key")}`, `self-ip = ${t.selfIp}`);
2738
+ if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
2739
+ if (t.mtu !== void 0) lines.push(`mtu = ${t.mtu}`);
2740
+ for (const peer of t.peers) {
2741
+ const values = [`public-key = ${peer.publicKey}`];
2742
+ if (peer.presharedKey) values.push(`preshared-key = ${credential(peer.presharedKey, "key")}`);
2743
+ values.push(`allowed-ips = "${peer.allowedIps.join(", ")}"`, `endpoint = ${peer.endpoint}`);
2744
+ if (peer.persistentKeepalive !== void 0) values.push(`keepalive = ${peer.persistentKeepalive}`);
2745
+ lines.push(`peer = (${values.join(", ")})`);
2746
+ }
2747
+ }
2748
+ }
2749
+ lines.push("", "[Proxy Group]");
2750
+ for (const g of p.groups) lines.push(`${name(g.id)} = ${[
2751
+ g.type,
2752
+ ...g.members.map(action),
2753
+ ...g.url ? [`url=${g.url}`] : [],
2754
+ ...g.intervalSeconds !== void 0 ? [`interval=${g.intervalSeconds}`] : [],
2755
+ ...g.timeoutSeconds !== void 0 ? [`timeout=${g.timeoutSeconds}`] : []
2756
+ ].join(", ")}`);
2757
+ lines.push("", "[Rule]");
2758
+ for (const r of p.rules) lines.push([
2759
+ conditionText(r.when),
2760
+ action(r.then),
2761
+ ...conditionOptions(r.when)
2762
+ ].join(","));
2763
+ lines.push(`FINAL,${action(p.fallback)}`, "");
2764
+ return deepFreeze({
2765
+ artifactKind: "surge-profile",
2766
+ content: lines.join("\n")
2767
+ });
2768
+ }
2769
+ function renderSurgeProfile(compilation, resolveSecret) {
2770
+ return renderProfile(compilation, secretReader(resolveSecret));
2771
+ }
2772
+ function renderSurgeProfiles(compilations, resolveSecret) {
2773
+ if (compilations.some((c) => !plans.has(c))) throw new RenderError("COMPILATION_FAILED");
2774
+ const read = secretReader(resolveSecret);
2775
+ return deepFreeze(compilations.map((c) => renderProfile(c, read)));
2776
+ }
2777
+ //#endregion
2778
+ //#region src/surge-publish.ts
2779
+ var SurgePublishError = class extends Error {
2780
+ published;
2781
+ constructor(message, published) {
2782
+ super(message);
2783
+ this.published = published;
2784
+ }
2785
+ };
2786
+ async function publishProfiles(files, surgeDirectory, io = { rename }) {
2787
+ if (!files.size || files.size > 16 || [...files.keys()].some((name) => !/^[a-z0-9][a-z0-9-]*\.conf$/.test(name))) throw new Error("INVALID_PROFILE_FILENAMES");
2788
+ const root = resolve(surgeDirectory);
2789
+ const generations = join(root, ".generations");
2790
+ const id = randomUUID();
2791
+ const generation = join(generations, id);
2792
+ const pointer = join(root, `.out-${id}`);
2793
+ const output = join(root, "out");
2794
+ const backup = join(generations, `legacy-${id}`);
2795
+ const lock = join(root, ".build-lock");
2796
+ const remove = io.rm ?? rm;
2797
+ let failure;
2798
+ let locked = false, created = false, committed = false, movedLegacy = false, recoveryFailed = false;
2799
+ async function directory(path) {
2800
+ await mkdir(path, {
2801
+ recursive: true,
2802
+ mode: 448
2803
+ });
2804
+ const stat = await lstat(path);
2805
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
2806
+ }
2807
+ try {
2808
+ await directory(root);
2809
+ try {
2810
+ await mkdir(lock, { mode: 448 });
2811
+ locked = true;
2812
+ } catch (error) {
2813
+ if (error.code === "EEXIST") throw new Error("OUTPUT_LOCKED");
2814
+ throw error;
2815
+ }
2816
+ await directory(generations);
2817
+ let previous;
2818
+ try {
2819
+ previous = await lstat(output);
2820
+ } catch (error) {
2821
+ if (error.code !== "ENOENT") throw error;
2822
+ }
2823
+ if (previous?.isSymbolicLink()) {
2824
+ const target = await readlink(output);
2825
+ if (!/^\.generations\/(?:legacy-)?[a-f0-9-]{36}$/.test(target)) throw new Error("UNMANAGED_OUTPUT_LINK");
2826
+ const stat = await lstat(join(root, target));
2827
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
2828
+ } else if (previous && !previous.isDirectory()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
2829
+ await mkdir(generation, { mode: 448 });
2830
+ created = true;
2831
+ for (const [name, content] of files) await writeFile(join(generation, name), content, {
2832
+ mode: 384,
2833
+ flag: "wx"
2834
+ });
2835
+ await symlink(`.generations/${id}`, pointer, "dir");
2836
+ if (previous?.isDirectory()) {
2837
+ await io.rename(output, backup);
2838
+ movedLegacy = true;
2839
+ }
2840
+ try {
2841
+ await io.rename(pointer, output);
2842
+ committed = true;
2843
+ } catch (error) {
2844
+ if (movedLegacy) try {
2845
+ await io.rename(backup, output);
2846
+ movedLegacy = false;
2847
+ } catch {
2848
+ recoveryFailed = true;
2849
+ throw new Error("PUBLISH_RECOVERY_REQUIRED");
2850
+ }
2851
+ throw error;
2852
+ }
2853
+ } catch (error) {
2854
+ 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";
2855
+ failure = new Error(code);
2856
+ } finally {
2857
+ if (!recoveryFailed) try {
2858
+ await remove(pointer, { force: true });
2859
+ if (created && !committed) await remove(generation, {
2860
+ recursive: true,
2861
+ force: true
2862
+ });
2863
+ if (locked) await remove(lock, {
2864
+ recursive: true,
2865
+ force: true
2866
+ });
2867
+ } catch {
2868
+ failure ??= /* @__PURE__ */ new Error("PROFILE_PUBLISH_CLEANUP_FAILED");
2869
+ }
2870
+ }
2871
+ if (failure) throw new SurgePublishError(failure.message === "PROFILE_PUBLISH_CLEANUP_FAILED" ? committed ? "PUBLISHED_CLEANUP_FAILED" : "FAILED_CLEANUP_REQUIRED" : failure.message, committed);
2872
+ }
2873
+ //#endregion
2874
+ //#region src/surge-host.ts
2875
+ /** Complete-profile batches use the out symlink protocol; the Program host remains unchanged. */
2876
+ async function buildSurgeProfilesToDirectory(profiles, output, resolveSecret = (token) => process.env[token.name]) {
2877
+ if (typeof output !== "string" || !output.trim()) return {
2878
+ published: false,
2879
+ exitCode: 1,
2880
+ code: "INVALID_OUTPUT_DIRECTORY"
2881
+ };
2882
+ try {
2883
+ const entries = Object.entries(profiles);
2884
+ if (!entries.length || entries.length > 16 || entries.some(([id]) => !/^[a-z0-9][a-z0-9-]*$/.test(id))) return {
2885
+ published: false,
2886
+ exitCode: 1,
2887
+ code: "INVALID_PROFILE_FILENAMES"
2888
+ };
2889
+ const compiled = entries.map(([, input]) => compileSurgeProfile(input));
2890
+ if (compiled.some((profile) => !profile.ok)) return {
2891
+ published: false,
2892
+ exitCode: 1,
2893
+ code: "COMPILATION_FAILED"
2894
+ };
2895
+ const artifacts = renderSurgeProfiles(compiled, resolveSecret);
2896
+ await publishProfiles(new Map(entries.map(([id], i) => [`${id}.conf`, artifacts[i].content])), output);
2897
+ return {
2898
+ published: true,
2899
+ exitCode: 0,
2900
+ code: "PUBLISHED",
2901
+ active: join(resolve(output), "out")
2902
+ };
2903
+ } catch (error) {
2904
+ if (error instanceof SurgePublishError) return {
2905
+ published: error.published,
2906
+ exitCode: error.published ? 2 : 1,
2907
+ code: error.message,
2908
+ ...error.published ? { active: join(resolve(output), "out") } : {},
2909
+ ...error.message === "PUBLISH_RECOVERY_REQUIRED" ? { hint: "out may be absent; preserve the lock, backup, generation and temporary pointer for manual recovery" } : {}
2910
+ };
2911
+ return {
2912
+ published: false,
2913
+ exitCode: 1,
2914
+ code: error instanceof RenderError ? error.code : "BUILD_FAILED"
2915
+ };
2916
+ }
2917
+ }
2918
+ //#endregion
2919
+ //#region src/surge-build.ts
2920
+ function record(value, keys) {
2921
+ if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
2922
+ for (const key of Reflect.ownKeys(value)) {
2923
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
2924
+ if (typeof key !== "string" || keys && !keys.includes(key) || !descriptor.enumerable || !("value" in descriptor)) throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
2925
+ }
2926
+ }
2927
+ /** Capture data and callback references before application preflight can change its source. */
2928
+ function defineSurgeBuild(input) {
2929
+ try {
2930
+ record(input, [
2931
+ "profiles",
2932
+ "preflight",
2933
+ "resolveSecret"
2934
+ ]);
2935
+ record(input.profiles);
2936
+ for (const callback of [input.preflight, input.resolveSecret]) if (callback !== void 0 && typeof callback !== "function") throw new Error();
2937
+ return Object.freeze({
2938
+ profiles: deepFreeze(snapshotDefinition(input.profiles)),
2939
+ ...input.preflight === void 0 ? {} : { preflight: input.preflight },
2940
+ ...input.resolveSecret === void 0 ? {} : { resolveSecret: input.resolveSecret }
2941
+ });
2942
+ } catch {
2943
+ throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
2944
+ }
2945
+ }
2946
+ function surgeBuildFailure(code, validation = false, profileCount = 0) {
2947
+ return {
2948
+ published: false,
2949
+ exitCode: 1,
2950
+ code,
2951
+ warnings: {},
2952
+ validation,
2953
+ profileCount
2954
+ };
2955
+ }
2956
+ /** Pure orchestration result; the CLI owns stdout and process exit status. */
2957
+ async function runSurgeBuild(input, output, options = {}) {
2958
+ let validation;
2959
+ try {
2960
+ record(options, ["validation"]);
2961
+ if (options.validation !== void 0 && typeof options.validation !== "boolean") throw new Error();
2962
+ validation = options.validation ?? false;
2963
+ } catch {
2964
+ return surgeBuildFailure("INVALID_BUILD_OPTIONS");
2965
+ }
2966
+ let definition;
2967
+ try {
2968
+ definition = defineSurgeBuild(input);
2969
+ } catch {
2970
+ return surgeBuildFailure("INVALID_BUILD_DEFINITION", validation);
2971
+ }
2972
+ const profileCount = Object.keys(definition.profiles).length;
2973
+ const failure = (code) => surgeBuildFailure(code, validation, profileCount);
2974
+ if (typeof output !== "string" || !output.trim()) return failure("INVALID_OUTPUT_DIRECTORY");
2975
+ if (validation && !definition.resolveSecret) return failure("VALIDATION_RESOLVER_REQUIRED");
2976
+ let codes;
2977
+ try {
2978
+ codes = definition.preflight ? definition.preflight() : [];
2979
+ } catch {
2980
+ return failure("PREFLIGHT_FAILED");
2981
+ }
2982
+ try {
2983
+ codes = snapshotDefinition(codes);
2984
+ 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();
2985
+ } catch {
2986
+ return failure("INVALID_PREFLIGHT_WARNINGS");
2987
+ }
2988
+ const warnings = {};
2989
+ for (const code of codes) warnings[code] = (warnings[code] ?? 0) + 1;
2990
+ const context = Object.freeze({ validation });
2991
+ const resolver = definition.resolveSecret;
2992
+ return {
2993
+ ...await buildSurgeProfilesToDirectory(definition.profiles, output, resolver ? (token) => resolver(token, context) : (token) => process.env[token.name]),
2994
+ warnings,
2995
+ validation,
2996
+ profileCount
2997
+ };
2998
+ }
2999
+ //#endregion
3000
+ export { route as A, use as B, direct as C, policy$2 as D, mihomo as E, sequence as F, requestSchema as G, deepFreeze as H, singbox$1 as I, defineRoute as J, ProfileDefinitionError as K, slot as L, ruleSet as M, secret as N, proxy as O, selectNodes as P, selectProxies as Q, strategy as R, defineConfig as S, match as T, idSchema as U, assertData as V, nodeSchema as W, defineSurgeProfile as X, defineRoutes as Y, outbound as Z, RenderError as _, compileSurgeProfile as a, StaticRuleSetUnknownError as b, buildToDirectory as c, compile as d, explain as f, targetCatalog as g, nativeNameSchema as h, buildSurgeProfilesToDirectory as i, rule as j, reject as k, render as l, isReservedNativeName as m, runSurgeBuild as n, renderSurgeProfile as o, compileStrategyGroups as p, defineProxyGroup as q, surgeBuildFailure as r, renderSurgeProfiles as s, defineSurgeBuild as t, secretReader as u, surgeProxy as v, group as w, block as x, validateProxyOptions as y, surge$1 as z };