proxylang 0.1.6 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,352 +1,138 @@
1
- import { z } from "zod";
2
1
  import { isIP } from "node:net";
3
2
  import ipaddr from "ipaddr.js";
3
+ import { z } from "zod";
4
4
  import { stringify } from "yaml";
5
5
  import { lstat, mkdir, readlink, rename, rm, symlink, writeFile } from "node:fs/promises";
6
6
  import { join, resolve } from "node:path";
7
7
  import { randomUUID } from "node:crypto";
8
- //#region src/surge-definitions.ts
9
- var ProfileDefinitionError = class extends Error {
10
- code;
11
- constructor(code) {
12
- super(code);
13
- this.code = code;
14
- this.name = "ProfileDefinitionError";
15
- }
16
- };
17
- const fail = (code) => {
18
- throw new ProfileDefinitionError(code);
19
- };
20
- /** Inspect descriptors before any caller spreads or reads input fields. Shared DAGs are legal. */
21
- function inspect(root) {
22
- let edges = 0;
23
- let objects = 0;
24
- const visiting = /* @__PURE__ */ new Set();
25
- const heights = /* @__PURE__ */ new Map();
26
- function visit(value, depth) {
27
- if (depth > 64) fail("DEFINITION_DEPTH_EXCEEDED");
28
- if (value === null || typeof value !== "object") {
29
- if (![
30
- "undefined",
31
- "string",
32
- "number",
33
- "boolean"
34
- ].includes(typeof value) && value !== null) fail("DEFINITION_NOT_DATA");
35
- return 0;
36
- }
37
- if (visiting.has(value)) fail("DEFINITION_CYCLE");
38
- const cached = heights.get(value);
39
- if (cached !== void 0) {
40
- if (depth + cached > 64) fail("DEFINITION_DEPTH_EXCEEDED");
41
- return cached;
42
- }
43
- if (++objects > 2e4) fail("DEFINITION_OBJECT_BUDGET_EXCEEDED");
44
- const proto = Object.getPrototypeOf(value);
45
- if (proto !== Object.prototype && proto !== null && !(Array.isArray(value) && proto === Array.prototype)) fail("DEFINITION_NOT_DATA");
46
- if (Array.isArray(value) && value.length > 1e5) fail("DEFINITION_EDGE_BUDGET_EXCEEDED");
47
- visiting.add(value);
48
- let height = 0;
49
- for (const key of Reflect.ownKeys(value)) {
50
- if (++edges > 1e5) fail("DEFINITION_EDGE_BUDGET_EXCEEDED");
51
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
52
- if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable && !(Array.isArray(value) && key === "length")) fail("DEFINITION_NOT_DATA");
53
- height = Math.max(height, 1 + visit(descriptor.value, depth + 1));
54
- }
55
- visiting.delete(value);
56
- heights.set(value, height);
57
- return height;
58
- }
59
- visit(root, 0);
8
+ //#region src/rulesets.ts
9
+ function canonical(value) {
10
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
11
+ if (value && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
12
+ return JSON.stringify(value);
60
13
  }
61
- /** Count output occurrences, not identities, before allocating each copied value. */
62
- function snapshot(input) {
63
- let remaining = 1e5;
64
- function copy(value, depth) {
65
- if (--remaining < 0) fail("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
66
- if (depth > 64) fail("DEFINITION_DEPTH_EXCEEDED");
67
- if (value === null || typeof value !== "object") return value;
68
- if (Array.isArray(value)) {
69
- const output = [];
70
- for (const item of value) output.push(copy(item, depth + 1));
71
- return output;
14
+ function validateRuleSets(entries, engine, diagnostics, path) {
15
+ const definitions = /* @__PURE__ */ new Map();
16
+ const urls = /* @__PURE__ */ new Map();
17
+ const error = (code) => diagnostics.push({
18
+ severity: "error",
19
+ code,
20
+ path,
21
+ message: "原生规则集引擎不匹配或相同 ID/URL 的定义冲突"
22
+ });
23
+ const visit = (m) => {
24
+ if (m.type === "ruleSet" || m.type === "nativeRuleSet") {
25
+ const key = canonical(m);
26
+ if (definitions.has(m.id) && definitions.get(m.id) !== key) error("RULESET_ID_CONFLICT");
27
+ definitions.set(m.id, key);
28
+ if (m.type === "ruleSet") visit(m.when);
29
+ else {
30
+ if (m.engine !== engine) error("NATIVE_TARGET_MISMATCH");
31
+ if (m.engine === "surge") {
32
+ const settings = canonical([m.format, m.intervalSeconds ?? 86400]);
33
+ const url = new URL(m.url).href;
34
+ if (urls.has(url) && urls.get(url) !== settings) error("RULESET_URL_CONFLICT");
35
+ urls.set(url, settings);
36
+ }
37
+ }
38
+ } else if (m.type === "all" || m.type === "any") m.conditions.forEach(visit);
39
+ else if (m.type === "not") visit(m.condition);
40
+ };
41
+ const walk = (items) => {
42
+ for (const item of items) if (item.type === "rule") visit(item.when);
43
+ else if (item.type === "block") {
44
+ if (item.when) visit(item.when);
45
+ walk(item.rules);
46
+ } else walk(item.policy.rules);
47
+ };
48
+ walk(entries);
49
+ }
50
+ function lowerRuleSets(rules, diagnostics, path) {
51
+ let count = 0;
52
+ let origins = 0;
53
+ const lower = (m, origin, depth) => {
54
+ if (++count > 1e5 || depth > 64) throw new Error("EXPANSION_LIMIT");
55
+ if (m.type === "ruleSet") {
56
+ origin.push(`rule-set:${m.id}`);
57
+ return lower(m.when, origin, depth + 1);
72
58
  }
73
- const output = {};
74
- for (const [key, item] of Object.entries(value)) Object.defineProperty(output, key, {
75
- value: copy(item, depth + 1),
76
- enumerable: true,
77
- writable: true,
78
- configurable: true
59
+ if (m.type === "all" || m.type === "any") return {
60
+ ...m,
61
+ conditions: m.conditions.map((c) => lower(c, origin, depth + 1))
62
+ };
63
+ if (m.type === "not") return {
64
+ ...m,
65
+ condition: lower(m.condition, origin, depth + 1)
66
+ };
67
+ return m;
68
+ };
69
+ try {
70
+ if (rules.length > 1e4) throw new Error("EXPANSION_LIMIT");
71
+ return rules.map((r) => {
72
+ const origin = [...r.origin];
73
+ const when = lower(r.when, origin, 0);
74
+ origins += origin.length;
75
+ if (origins > 1e5) throw new Error("EXPANSION_LIMIT");
76
+ return {
77
+ ...r,
78
+ when,
79
+ origin
80
+ };
79
81
  });
80
- return output;
82
+ } catch {
83
+ diagnostics.push({
84
+ severity: "error",
85
+ code: "EXPANSION_LIMIT",
86
+ path,
87
+ message: "展开规则、条件或来源超过预算"
88
+ });
89
+ return [];
81
90
  }
82
- return copy(input, 0);
83
- }
84
- function 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
91
  }
120
- function defineRoute(input) {
121
- inspect(input);
122
- exact(input, ["when", "to"]);
123
- return {
124
- ...input,
125
- type: "route"
92
+ function collectNativeRuleSets(rules, target, diagnostics) {
93
+ const found = /* @__PURE__ */ new Map();
94
+ const visit = (m, nested) => {
95
+ if (m.type === "nativeRuleSet") {
96
+ found.set(m.id, m);
97
+ if (nested && m.engine === "surge" && m.intervalSeconds !== void 0) diagnostics.push({
98
+ severity: "error",
99
+ code: "RULESET_COMPOSITION_UNSUPPORTED",
100
+ target: target.id,
101
+ path: `targets.${target.id}.ruleSets.${m.id}`,
102
+ message: "Surge 嵌套外部规则只支持客户端默认更新间隔"
103
+ });
104
+ } else if (m.type === "all" || m.type === "any") m.conditions.forEach((c) => visit(c, true));
105
+ else if (m.type === "not") visit(m.condition, true);
106
+ else if (m.type === "ruleSet") visit(m.when, nested);
126
107
  };
127
- }
128
- function 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
108
+ rules.forEach((r) => visit(r.when, false));
109
+ for (const r of found.values()) diagnostics.push({
110
+ severity: "warning",
111
+ code: "EXTERNAL_RULESET_UNVERIFIED",
112
+ target: target.id,
113
+ path: `targets.${target.id}.ruleSets.${r.id}`,
114
+ message: "外部规则由客户端更新和解释;编译器未获取内容或验证运行时匹配"
142
115
  });
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))));
116
+ return [...found.values()];
152
117
  }
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
333
- //#region src/schema.ts
334
- const idSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/).refine((x) => !x.startsWith("pl-"));
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) => {
338
- try {
339
- const [address, prefix] = x.split("/");
340
- if (!address || !prefix || !/^\d+$/.test(prefix) || isIP(address) === 0 || address.includes("%")) return false;
341
- ipaddr.parseCIDR(x);
342
- return true;
343
- } catch {
344
- return false;
118
+ //#endregion
119
+ //#region src/schema.ts
120
+ const idSchema = z.string().regex(/^[a-z][a-z0-9_-]{0,63}$/).refine((x) => !x.startsWith("pl-"));
121
+ const domain$1 = z.string().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/);
122
+ const ip$1 = z.string().refine((x) => isIP(x) !== 0 && !x.includes("%"));
123
+ const cidr$1 = z.string().refine((x) => {
124
+ try {
125
+ const [address, prefix] = x.split("/");
126
+ if (!address || !prefix || !/^\d+$/.test(prefix) || isIP(address) === 0 || address.includes("%")) return false;
127
+ ipaddr.parseCIDR(x);
128
+ return true;
129
+ } catch {
130
+ return false;
345
131
  }
346
132
  });
347
133
  const port$1 = z.number().int().min(1).max(65535);
348
134
  const network = z.enum(["tcp", "udp"]);
349
- const atom$1 = (type, value) => z.strictObject({
135
+ const atom$2 = (type, value) => z.strictObject({
350
136
  type: z.literal(type),
351
137
  value
352
138
  });
@@ -395,10 +181,10 @@ const matchSchema = z.lazy(() => z.discriminatedUnion("type", [
395
181
  id: idSchema,
396
182
  when: matchSchema
397
183
  }),
398
- atom$1("domain", domain$1),
399
- atom$1("domainSuffix", domain$1),
400
- atom$1("ipCidr", cidr$1),
401
- atom$1("sourceIp", cidr$1),
184
+ atom$2("domain", domain$1),
185
+ atom$2("domainSuffix", domain$1),
186
+ atom$2("ipCidr", cidr$1),
187
+ atom$2("sourceIp", cidr$1),
402
188
  z.strictObject({
403
189
  type: z.literal("port"),
404
190
  from: port$1,
@@ -704,427 +490,150 @@ function deepFreeze(value) {
704
490
  return value;
705
491
  }
706
492
  //#endregion
707
- //#region src/proxy-builder.ts
708
- /** Fluent construction is separate from the plain-data node consumed by the compiler. */
709
- function proxyBuilder(node) {
710
- assertData(node);
711
- const copy = deepFreeze(structuredClone(node));
712
- const fork = (patch) => proxyBuilder({
713
- ...copy,
714
- ...patch
715
- });
716
- return Object.freeze({
717
- via: (id) => fork({ via: id }),
718
- label: (text) => fork({ label: text }),
719
- tcpFastOpen: (enabled) => fork({ tcpFastOpen: enabled }),
720
- build: () => deepFreeze(structuredClone(copy))
493
+ //#region src/rules.ts
494
+ function expandRules(entries, diagnostics, path = "routing") {
495
+ const output = [];
496
+ const seen = /* @__PURE__ */ new Set();
497
+ let limited = false;
498
+ const error = (code, where, message) => diagnostics.push({
499
+ severity: "error",
500
+ code,
501
+ path: where,
502
+ message
721
503
  });
504
+ function resolve(action, bindings, inPolicy, where) {
505
+ if (action.type === "slot") {
506
+ if (!Object.hasOwn(bindings, action.name)) {
507
+ error("UNBOUND_SLOT", where, "出口槽位未声明或未绑定");
508
+ return;
509
+ }
510
+ return bindings[action.name];
511
+ }
512
+ if (inPolicy && action.type === "route") {
513
+ error("POLICY_RESOURCE_CAPTURE", where, "共享 policy 必须通过 slot 引用出口");
514
+ return;
515
+ }
516
+ return action;
517
+ }
518
+ function walk(items, prefix, guards, bindings, inPolicy, origin) {
519
+ for (const entry of items) {
520
+ if (limited) return;
521
+ if (entry.type === "rule" && output.length >= 1e4) {
522
+ limited = true;
523
+ error("EXPANSION_LIMIT", path, "展开规则超过10000条");
524
+ return;
525
+ }
526
+ const id = `${prefix}/${entry.id}`;
527
+ if (seen.has(id)) {
528
+ error("DUPLICATE_RULE_ID", id, "同一实例路径出现重复 ID");
529
+ continue;
530
+ }
531
+ seen.add(id);
532
+ if (entry.type === "rule") {
533
+ const action = resolve(entry.then, bindings, inPolicy, id);
534
+ if (action) output.push({
535
+ id,
536
+ when: guards.length ? match.all(...guards, entry.when) : entry.when,
537
+ then: action,
538
+ origin: [...origin, entry.id]
539
+ });
540
+ } else if (entry.type === "block") walk(entry.rules, id, entry.when ? [...guards, entry.when] : guards, bindings, inPolicy, [...origin, entry.id]);
541
+ else {
542
+ const expected = new Set(entry.policy.exits);
543
+ if (Object.keys(entry.bindings).some((key) => !expected.has(key)) || entry.policy.exits.some((key) => !Object.hasOwn(entry.bindings, key))) {
544
+ error("POLICY_BINDINGS", id, "bindings 必须完整且只包含 policy 声明的出口");
545
+ continue;
546
+ }
547
+ const bound = Object.create(null);
548
+ for (const key of entry.policy.exits) {
549
+ const result = resolve(entry.bindings[key], bindings, inPolicy, `${id}/bindings/${key}`);
550
+ if (result) bound[key] = result;
551
+ }
552
+ walk(entry.policy.rules, id, guards, bound, true, [
553
+ ...origin,
554
+ `use:${entry.id}`,
555
+ `policy:${entry.policy.id}`
556
+ ]);
557
+ }
558
+ }
559
+ }
560
+ walk(entries, path, [], {}, false, []);
561
+ return limited ? [] : output;
722
562
  }
723
- //#endregion
724
- //#region src/dsl.ts
725
- const ruleSet = (definition) => ({
726
- ...definition,
727
- type: "ruleSet"
728
- });
729
- const match = {
730
- ruleSet: (set) => set,
731
- domain: (value) => ({
732
- type: "domain",
733
- value
734
- }),
735
- domainSuffix: (value) => ({
736
- type: "domainSuffix",
737
- value
738
- }),
739
- ipCidr: (value) => ({
740
- type: "ipCidr",
741
- value
742
- }),
743
- sourceIp: (value) => ({
744
- type: "sourceIp",
745
- value
746
- }),
747
- port: (from, to = from) => ({
748
- type: "port",
749
- from,
750
- to
751
- }),
752
- sourcePort: (from, to = from) => ({
753
- type: "sourcePort",
754
- from,
755
- to
756
- }),
757
- network: (value) => ({
758
- type: "network",
759
- value
760
- }),
761
- all: (...conditions) => ({
762
- type: "all",
763
- conditions
764
- }),
765
- any: (...conditions) => ({
766
- type: "any",
767
- conditions
768
- }),
769
- not: (condition) => ({
770
- type: "not",
771
- condition
772
- })
773
- };
774
- const direct = () => ({ type: "direct" });
775
- const reject = () => ({ type: "reject" });
776
- const route = (to) => ({
777
- type: "route",
778
- to
779
- });
780
- /** An exit parameter declared by policy.exits and resolved by use.bindings. */
781
- const slot = (name) => ({
782
- type: "slot",
783
- name
784
- });
785
- const secret = (name) => ({
786
- type: "env",
787
- name
788
- });
789
- const rule = (id, when, then) => ({
790
- type: "rule",
791
- id,
792
- when,
793
- then
794
- });
795
- const block = (id, rules, when) => ({
796
- type: "block",
797
- id,
798
- rules,
799
- ...when ? { when } : {}
800
- });
801
- const policy$2 = (definition) => ({
802
- type: "policy",
803
- ...definition
804
- });
805
- const use = (definition, options) => ({
806
- type: "use",
807
- id: options.id,
808
- policy: definition,
809
- bindings: options.bindings
810
- });
811
- const sequence = (...parts) => parts.flatMap((part) => Array.isArray(part) ? part : [part]);
812
- const defineConfig = (config) => config;
813
- /** Filtering is stable: catalogue order determines initial selector order. */
814
- function selectNodes(nodes, query = {}) {
815
- return nodes.filter((node) => (!query.regions || node.region !== void 0 && query.regions.includes(node.region)) && (!query.providers || node.provider !== void 0 && query.providers.includes(node.provider)) && (!query.tags || query.tags.every((tag) => node.tags?.includes(tag)))).map((node) => node.id);
816
- }
817
- /** A shared strategy declares an algorithm or explicitly selects native implementations. */
818
- const strategy = (definition) => ({
819
- type: "strategy",
820
- ...definition
821
- });
822
- const group = {
823
- auto: () => ({ type: "auto" }),
824
- select: () => ({ type: "select" }),
825
- urltest: (options) => ({
826
- type: "urltest",
827
- ...options
828
- })
829
- };
830
- const surge$1 = {
831
- match: surgeMatch,
832
- smart: () => ({ type: "surge-smart" }),
833
- ruleSet: (options) => ({
834
- format: "rule-set",
835
- ...options,
836
- type: "nativeRuleSet",
837
- engine: "surge"
838
- })
839
- };
840
- const mihomo = { ruleProvider: (options) => ({
841
- ...options,
842
- type: "nativeRuleSet",
843
- engine: "mihomo"
844
- }) };
845
- /** Protocol constructors keep credentials and options specific to their protocol. */
846
- function nodeConstructor(type) {
847
- return (options) => ({
848
- ...options,
849
- type
850
- });
563
+ function inCidr(address, cidr) {
564
+ if (!address) return false;
565
+ const parsed = ipaddr.parse(address);
566
+ const [base, bits] = ipaddr.parseCIDR(cidr);
567
+ return parsed.kind() === base.kind() && parsed.match(base, bits);
851
568
  }
852
- const proxy = {
853
- builder: proxyBuilder,
854
- http: nodeConstructor("http"),
855
- trojan: nodeConstructor("trojan"),
856
- anytls: nodeConstructor("anytls"),
857
- shadowsocks: nodeConstructor("shadowsocks"),
858
- vmess: nodeConstructor("vmess"),
859
- vless: nodeConstructor("vless")
860
- };
861
- const singbox$1 = {
862
- ruleSet: (options) => ({
863
- ...options,
864
- type: "nativeRuleSet",
865
- engine: "sing-box"
866
- }),
867
- tailscale: (options) => ({
868
- ...options,
869
- type: "sing-box-tailscale"
870
- })
569
+ var StaticRuleSetUnknownError = class extends Error {
570
+ constructor() {
571
+ super("STATIC_RULESET_UNKNOWN");
572
+ this.name = "StaticRuleSetUnknownError";
573
+ }
871
574
  };
872
- //#endregion
873
- //#region src/rulesets.ts
874
- function canonical(value) {
875
- if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
876
- if (value && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
877
- return JSON.stringify(value);
878
- }
879
- function validateRuleSets(entries, engine, diagnostics, path) {
880
- const definitions = /* @__PURE__ */ new Map();
881
- const urls = /* @__PURE__ */ new Map();
882
- const error = (code) => diagnostics.push({
883
- severity: "error",
884
- code,
885
- path,
886
- message: "原生规则集引擎不匹配或相同 ID/URL 的定义冲突"
887
- });
888
- const visit = (m) => {
889
- if (m.type === "ruleSet" || m.type === "nativeRuleSet") {
890
- const key = canonical(m);
891
- if (definitions.has(m.id) && definitions.get(m.id) !== key) error("RULESET_ID_CONFLICT");
892
- definitions.set(m.id, key);
893
- if (m.type === "ruleSet") visit(m.when);
894
- else {
895
- if (m.engine !== engine) error("NATIVE_TARGET_MISMATCH");
896
- if (m.engine === "surge") {
897
- const settings = canonical([m.format, m.intervalSeconds ?? 86400]);
898
- const url = new URL(m.url).href;
899
- if (urls.has(url) && urls.get(url) !== settings) error("RULESET_URL_CONFLICT");
900
- urls.set(url, settings);
901
- }
902
- }
903
- } else if (m.type === "all" || m.type === "any") m.conditions.forEach(visit);
904
- else if (m.type === "not") visit(m.condition);
905
- };
906
- const walk = (items) => {
907
- for (const item of items) if (item.type === "rule") visit(item.when);
908
- else if (item.type === "block") {
909
- if (item.when) visit(item.when);
910
- walk(item.rules);
911
- } else walk(item.policy.rules);
575
+ function evaluate(condition, request) {
576
+ if (condition.type === "ruleSet") return evaluate(condition.when, request);
577
+ if (condition.type === "nativeRuleSet") return {
578
+ type: condition.type,
579
+ matched: null,
580
+ reason: "外部规则内容由客户端解释,静态未知"
912
581
  };
913
- walk(entries);
914
- }
915
- function lowerRuleSets(rules, diagnostics, path) {
916
- let count = 0;
917
- let origins = 0;
918
- const lower = (m, origin, depth) => {
919
- if (++count > 1e5 || depth > 64) throw new Error("EXPANSION_LIMIT");
920
- if (m.type === "ruleSet") {
921
- origin.push(`rule-set:${m.id}`);
922
- return lower(m.when, origin, depth + 1);
923
- }
924
- if (m.type === "all" || m.type === "any") return {
925
- ...m,
926
- conditions: m.conditions.map((c) => lower(c, origin, depth + 1))
582
+ if (condition.type === "all" || condition.type === "any") {
583
+ const children = condition.conditions.map((child) => evaluate(child, request));
584
+ const matched = condition.type === "all" ? children.some((child) => child.matched === false) ? false : children.some((child) => child.matched === null) ? null : true : children.some((child) => child.matched === true) ? true : children.some((child) => child.matched === null) ? null : false;
585
+ return {
586
+ type: condition.type,
587
+ matched,
588
+ reason: condition.type === "all" ? "所有子条件同时成立" : "至少一个子条件成立",
589
+ children
927
590
  };
928
- if (m.type === "not") return {
929
- ...m,
930
- condition: lower(m.condition, origin, depth + 1)
591
+ }
592
+ if (condition.type === "not") {
593
+ const child = evaluate(condition.condition, request);
594
+ return {
595
+ type: "not",
596
+ matched: child.matched === null ? null : !child.matched,
597
+ reason: "布尔取反;缺失字段的原子条件为 false",
598
+ children: [child]
931
599
  };
932
- return m;
933
- };
934
- try {
935
- if (rules.length > 1e4) throw new Error("EXPANSION_LIMIT");
936
- return rules.map((r) => {
937
- const origin = [...r.origin];
938
- const when = lower(r.when, origin, 0);
939
- origins += origin.length;
940
- if (origins > 1e5) throw new Error("EXPANSION_LIMIT");
941
- return {
942
- ...r,
943
- when,
944
- origin
945
- };
946
- });
947
- } catch {
948
- diagnostics.push({
949
- severity: "error",
950
- code: "EXPANSION_LIMIT",
951
- path,
952
- message: "展开规则、条件或来源超过预算"
953
- });
954
- return [];
955
600
  }
956
- }
957
- function collectNativeRuleSets(rules, target, diagnostics) {
958
- const found = /* @__PURE__ */ new Map();
959
- const visit = (m, nested) => {
960
- if (m.type === "nativeRuleSet") {
961
- found.set(m.id, m);
962
- if (nested && m.engine === "surge" && m.intervalSeconds !== void 0) diagnostics.push({
963
- severity: "error",
964
- code: "RULESET_COMPOSITION_UNSUPPORTED",
965
- target: target.id,
966
- path: `targets.${target.id}.ruleSets.${m.id}`,
967
- message: "Surge 嵌套外部规则只支持客户端默认更新间隔"
968
- });
969
- } else if (m.type === "all" || m.type === "any") m.conditions.forEach((c) => visit(c, true));
970
- else if (m.type === "not") visit(m.condition, true);
971
- else if (m.type === "ruleSet") visit(m.when, nested);
972
- };
973
- rules.forEach((r) => visit(r.when, false));
974
- for (const r of found.values()) diagnostics.push({
975
- severity: "warning",
976
- code: "EXTERNAL_RULESET_UNVERIFIED",
977
- target: target.id,
978
- path: `targets.${target.id}.ruleSets.${r.id}`,
979
- message: "外部规则由客户端更新和解释;编译器未获取内容或验证运行时匹配"
980
- });
981
- return [...found.values()];
982
- }
983
- //#endregion
984
- //#region src/rules.ts
985
- function expandRules(entries, diagnostics, path = "routing") {
986
- const output = [];
987
- const seen = /* @__PURE__ */ new Set();
988
- let limited = false;
989
- const error = (code, where, message) => diagnostics.push({
990
- severity: "error",
991
- code,
992
- path: where,
993
- message
994
- });
995
- function resolve(action, bindings, inPolicy, where) {
996
- if (action.type === "slot") {
997
- if (!Object.hasOwn(bindings, action.name)) {
998
- error("UNBOUND_SLOT", where, "出口槽位未声明或未绑定");
999
- return;
1000
- }
1001
- return bindings[action.name];
1002
- }
1003
- if (inPolicy && action.type === "route") {
1004
- error("POLICY_RESOURCE_CAPTURE", where, "共享 policy 必须通过 slot 引用出口");
1005
- return;
1006
- }
1007
- return action;
1008
- }
1009
- function walk(items, prefix, guards, bindings, inPolicy, origin) {
1010
- for (const entry of items) {
1011
- if (limited) return;
1012
- if (entry.type === "rule" && output.length >= 1e4) {
1013
- limited = true;
1014
- error("EXPANSION_LIMIT", path, "展开规则超过10000条");
1015
- return;
1016
- }
1017
- const id = `${prefix}/${entry.id}`;
1018
- if (seen.has(id)) {
1019
- error("DUPLICATE_RULE_ID", id, "同一实例路径出现重复 ID");
1020
- continue;
1021
- }
1022
- seen.add(id);
1023
- if (entry.type === "rule") {
1024
- const action = resolve(entry.then, bindings, inPolicy, id);
1025
- if (action) output.push({
1026
- id,
1027
- when: guards.length ? match.all(...guards, entry.when) : entry.when,
1028
- then: action,
1029
- origin: [...origin, entry.id]
1030
- });
1031
- } else if (entry.type === "block") walk(entry.rules, id, entry.when ? [...guards, entry.when] : guards, bindings, inPolicy, [...origin, entry.id]);
1032
- else {
1033
- const expected = new Set(entry.policy.exits);
1034
- if (Object.keys(entry.bindings).some((key) => !expected.has(key)) || entry.policy.exits.some((key) => !Object.hasOwn(entry.bindings, key))) {
1035
- error("POLICY_BINDINGS", id, "bindings 必须完整且只包含 policy 声明的出口");
1036
- continue;
1037
- }
1038
- const bound = Object.create(null);
1039
- for (const key of entry.policy.exits) {
1040
- const result = resolve(entry.bindings[key], bindings, inPolicy, `${id}/bindings/${key}`);
1041
- if (result) bound[key] = result;
1042
- }
1043
- walk(entry.policy.rules, id, guards, bound, true, [
1044
- ...origin,
1045
- `use:${entry.id}`,
1046
- `policy:${entry.policy.id}`
1047
- ]);
1048
- }
1049
- }
1050
- }
1051
- walk(entries, path, [], {}, false, []);
1052
- return limited ? [] : output;
1053
- }
1054
- function inCidr(address, cidr) {
1055
- if (!address) return false;
1056
- const parsed = ipaddr.parse(address);
1057
- const [base, bits] = ipaddr.parseCIDR(cidr);
1058
- return parsed.kind() === base.kind() && parsed.match(base, bits);
1059
- }
1060
- var StaticRuleSetUnknownError = class extends Error {
1061
- constructor() {
1062
- super("STATIC_RULESET_UNKNOWN");
1063
- this.name = "StaticRuleSetUnknownError";
1064
- }
1065
- };
1066
- function evaluate(condition, request) {
1067
- if (condition.type === "ruleSet") return evaluate(condition.when, request);
1068
- if (condition.type === "nativeRuleSet") return {
1069
- type: condition.type,
1070
- matched: null,
1071
- reason: "外部规则内容由客户端解释,静态未知"
1072
- };
1073
- if (condition.type === "all" || condition.type === "any") {
1074
- const children = condition.conditions.map((child) => evaluate(child, request));
1075
- const matched = condition.type === "all" ? children.some((child) => child.matched === false) ? false : children.some((child) => child.matched === null) ? null : true : children.some((child) => child.matched === true) ? true : children.some((child) => child.matched === null) ? null : false;
1076
- return {
1077
- type: condition.type,
1078
- matched,
1079
- reason: condition.type === "all" ? "所有子条件同时成立" : "至少一个子条件成立",
1080
- children
1081
- };
1082
- }
1083
- if (condition.type === "not") {
1084
- const child = evaluate(condition.condition, request);
1085
- return {
1086
- type: "not",
1087
- matched: child.matched === null ? null : !child.matched,
1088
- reason: "布尔取反;缺失字段的原子条件为 false",
1089
- children: [child]
1090
- };
1091
- }
1092
- let matched;
1093
- let present;
1094
- switch (condition.type) {
1095
- case "domain":
1096
- present = request.domain !== void 0;
1097
- matched = request.domain === condition.value;
1098
- break;
1099
- case "domainSuffix":
1100
- present = request.domain !== void 0;
1101
- matched = request.domain === condition.value || !!request.domain?.endsWith(`.${condition.value}`);
1102
- break;
1103
- case "ipCidr":
1104
- present = request.ip !== void 0;
1105
- matched = inCidr(request.ip, condition.value);
1106
- break;
1107
- case "sourceIp":
1108
- present = request.sourceIp !== void 0;
1109
- matched = inCidr(request.sourceIp, condition.value);
1110
- break;
1111
- case "port":
1112
- present = request.port !== void 0;
1113
- matched = present && request.port >= condition.from && request.port <= condition.to;
1114
- break;
1115
- case "sourcePort":
1116
- present = request.sourcePort !== void 0;
1117
- matched = present && request.sourcePort >= condition.from && request.sourcePort <= condition.to;
1118
- break;
1119
- case "network":
1120
- present = true;
1121
- matched = request.network === condition.value;
1122
- }
1123
- return {
1124
- type: condition.type,
1125
- matched,
1126
- reason: present ? matched ? "匹配" : "不匹配" : "字段缺失,原子条件为 false"
1127
- };
601
+ let matched;
602
+ let present;
603
+ switch (condition.type) {
604
+ case "domain":
605
+ present = request.domain !== void 0;
606
+ matched = request.domain === condition.value;
607
+ break;
608
+ case "domainSuffix":
609
+ present = request.domain !== void 0;
610
+ matched = request.domain === condition.value || !!request.domain?.endsWith(`.${condition.value}`);
611
+ break;
612
+ case "ipCidr":
613
+ present = request.ip !== void 0;
614
+ matched = inCidr(request.ip, condition.value);
615
+ break;
616
+ case "sourceIp":
617
+ present = request.sourceIp !== void 0;
618
+ matched = inCidr(request.sourceIp, condition.value);
619
+ break;
620
+ case "port":
621
+ present = request.port !== void 0;
622
+ matched = present && request.port >= condition.from && request.port <= condition.to;
623
+ break;
624
+ case "sourcePort":
625
+ present = request.sourcePort !== void 0;
626
+ matched = present && request.sourcePort >= condition.from && request.sourcePort <= condition.to;
627
+ break;
628
+ case "network":
629
+ present = true;
630
+ matched = request.network === condition.value;
631
+ }
632
+ return {
633
+ type: condition.type,
634
+ matched,
635
+ reason: present ? matched ? "匹配" : "不匹配" : "字段缺失,原子条件为 false"
636
+ };
1128
637
  }
1129
638
  function explainRules(rules, fallback, input) {
1130
639
  const parsed = requestSchema.safeParse(input);
@@ -1406,13 +915,13 @@ function conditionText$1(condition) {
1406
915
  case "sourcePort": return `${condition.type === "port" ? "DST-PORT" : "SRC-PORT"},${condition.from === condition.to ? condition.from : `${condition.from}-${condition.to}`}`;
1407
916
  }
1408
917
  }
1409
- const policy$1 = (action) => action.type === "route" ? action.to : action.type === "direct" ? "DIRECT" : "REJECT";
918
+ const policy$2 = (action) => action.type === "route" ? action.to : action.type === "direct" ? "DIRECT" : "REJECT";
1410
919
  function clashConfig(plan, secret) {
1411
920
  const { program, target } = plan;
1412
921
  const config = {
1413
922
  proxies: program.nodes.map((node) => clashProxy(node, target.engine, secret)),
1414
923
  "proxy-groups": program.groups.map((g) => clashGroup(g)),
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)}`]
924
+ rules: [...plan.rules.map((rule) => rule.when.type === "ipCidr" ? `${conditionText$1(rule.when).replace(/,no-resolve$/, "")},${policy$2(rule.then)},no-resolve` : `${conditionText$1(rule.when)},${policy$2(rule.then)}`), `MATCH,${policy$2(program.fallback)}`]
1416
925
  };
1417
926
  if (plan.nativeRuleSets.length) config["rule-providers"] = Object.fromEntries(plan.nativeRuleSets.map((r) => [r.id, {
1418
927
  type: "http",
@@ -1988,791 +1497,1505 @@ function secretReader(resolveSecret) {
1988
1497
  };
1989
1498
  }
1990
1499
  //#endregion
1991
- //#region src/render.ts
1992
- const DIRECT = "pl-direct";
1993
- const DNS = "pl-dns";
1994
- const actionTag = (action) => action.type === "route" ? action.to : action.type === "direct" ? DIRECT : "pl-reject";
1995
- /** Secret resolution is once per token per batch, including across providers. */
1996
- function render(compilation, resolveSecret) {
1997
- if (!compilation.ok) throw new RenderError("COMPILATION_FAILED");
1998
- const secret = secretReader(resolveSecret);
1999
- return compilation.plans.map((plan) => ({
2000
- target: plan.target.id,
2001
- filename: `${plan.target.id}.${plan.target.engine === "surge" ? "conf" : plan.target.engine === "sing-box" ? "json" : "yaml"}`,
2002
- content: plan.target.engine === "surge" ? surge(plan, secret) : plan.target.engine === "sing-box" ? JSON.stringify(singbox(plan, secret), null, 2) + "\n" : stringify(clashConfig(plan, secret))
2003
- }));
2004
- }
2005
- function singCondition(condition) {
2006
- switch (condition.type) {
2007
- case "ruleSet": return singCondition(condition.when);
2008
- case "nativeRuleSet": return { rule_set: [condition.id] };
2009
- case "all":
2010
- case "any": return {
2011
- type: "logical",
2012
- mode: condition.type === "all" ? "and" : "or",
2013
- rules: condition.conditions.map(singCondition)
2014
- };
2015
- case "not": return {
2016
- type: "logical",
2017
- mode: "and",
2018
- rules: [singCondition(condition.condition)],
2019
- invert: true
2020
- };
2021
- case "domain": return { domain: [condition.value] };
2022
- case "domainSuffix": return { domain_suffix: [condition.value] };
2023
- case "ipCidr": return { ip_cidr: [condition.value] };
2024
- case "sourceIp": return { source_ip_cidr: [condition.value] };
2025
- case "network": return { network: [condition.value] };
2026
- case "port":
2027
- case "sourcePort": {
2028
- const key = condition.type === "port" ? "port" : "source_port";
2029
- return condition.from === condition.to ? { [key]: [condition.from] } : { [`${key}_range`]: [`${condition.from}:${condition.to}`] };
2030
- }
1500
+ //#region src/surge-profile.ts
1501
+ const builtin = z.enum([
1502
+ "DIRECT",
1503
+ "REJECT",
1504
+ "REJECT-DROP",
1505
+ "REJECT-NO-DROP",
1506
+ "REJECT-TINYGIF"
1507
+ ]);
1508
+ const policy$1 = z.union([z.strictObject({ ref: idSchema }), z.strictObject({ builtin })]);
1509
+ const token = z.strictObject({
1510
+ type: z.literal("env"),
1511
+ name: z.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/)
1512
+ });
1513
+ const safe = z.string().min(1).max(4096).refine((v) => v.trim() === v && !/[\p{C}\p{Zl}\p{Zp},=()#;"'\\]/u.test(v));
1514
+ const domain = z.string().max(253).regex(/^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/);
1515
+ const hostPattern = safe.refine((v) => /^[a-zA-Z0-9*?._-]+$/.test(v));
1516
+ const ip = safe.refine((v) => isIP(v) !== 0 && !v.includes("%"));
1517
+ const cidr = (version) => safe.refine((v) => {
1518
+ try {
1519
+ const [address] = ipaddr.parseCIDR(v);
1520
+ return (!version || (address.kind() === "ipv4" ? 4 : 6) === version) && !v.includes("%");
1521
+ } catch {
1522
+ return false;
2031
1523
  }
1524
+ });
1525
+ const port = z.number().int().min(1).max(65535);
1526
+ function addressPort(value, allowHost, portRequired) {
1527
+ if (!portRequired && isIP(value)) return true;
1528
+ const match = /^(\[[^\]]+\]|[^:]+):(\d+)$/.exec(value);
1529
+ if (!match || Number(match[2]) < 1 || Number(match[2]) > 65535) return false;
1530
+ const host = match[1];
1531
+ return host.startsWith("[") ? isIP(host.slice(1, -1)) === 6 : isIP(host) === 4 || allowHost && domain.safeParse(host).success;
2032
1532
  }
2033
- function singAction(action) {
2034
- return action.type === "reject" ? {
2035
- action: "reject",
2036
- method: "default",
2037
- no_drop: true
2038
- } : {
2039
- action: "route",
2040
- outbound: actionTag(action)
2041
- };
2042
- }
2043
- function singbox(plan, secret) {
2044
- const { program, target } = plan;
2045
- const modern = target.version === "1.12.0";
2046
- const standalone = target.mode === "standalone";
2047
- const outbounds = [{
2048
- type: "direct",
2049
- tag: DIRECT,
2050
- ...!modern && standalone ? { domain_strategy: "prefer_ipv4" } : {}
2051
- }];
2052
- for (const node of program.nodes) outbounds.push(singboxProxy(node, secret));
2053
- for (const group of program.groups) outbounds.push(singboxGroup(group));
2054
- const rules = plan.rules.map((rule) => ({
2055
- ...singCondition(rule.when),
2056
- ...singAction(rule.then)
2057
- }));
2058
- const routing = { rules };
2059
- if (plan.nativeRuleSets.length) routing.rule_set = plan.nativeRuleSets.map((r) => ({
2060
- type: "remote",
2061
- tag: r.id,
2062
- url: r.url,
2063
- format: r.format,
2064
- update_interval: `${r.intervalSeconds}s`,
2065
- download_detour: DIRECT
1533
+ const listener = safe.refine((v) => addressPort(v, false, false));
1534
+ const endpoint = safe.refine((v) => addressPort(v, true, true));
1535
+ const dns = safe.refine((v) => v === "system" || addressPort(v, false, false));
1536
+ const url = z.string().min(1).max(4096).refine((v) => {
1537
+ try {
1538
+ const u = new URL(v);
1539
+ return /^https?:\/\//.test(v) && !u.username && !u.password && !u.hash && !/[\s\p{C},()\\"']/u.test(v);
1540
+ } catch {
1541
+ return false;
1542
+ }
1543
+ });
1544
+ const encryptedDns = z.string().max(4096).refine((v) => {
1545
+ try {
1546
+ const u = new URL(v);
1547
+ return [
1548
+ "https:",
1549
+ "h3:",
1550
+ "quic:",
1551
+ "tls:",
1552
+ "tcp:"
1553
+ ].includes(u.protocol) && !!u.hostname && !u.username && !u.password && !u.hash && !/[\s\p{C},()\\"']/u.test(v);
1554
+ } catch {
1555
+ return false;
1556
+ }
1557
+ });
1558
+ const list = (item) => z.array(item).min(1).max(1e3);
1559
+ const control = z.strictObject({
1560
+ password: token,
1561
+ listen: safe.refine((v) => addressPort(v, false, true))
1562
+ });
1563
+ const generalSchema = z.strictObject({
1564
+ loglevel: z.enum([
1565
+ "verbose",
1566
+ "info",
1567
+ "notify",
1568
+ "warning"
1569
+ ]).optional(),
1570
+ "dns-server": list(dns).optional(),
1571
+ "encrypted-dns-server": list(encryptedDns).optional(),
1572
+ "show-error-page-for-reject": z.boolean().optional(),
1573
+ "exclude-simple-hostnames": z.boolean().optional(),
1574
+ "internet-test-url": url.optional(),
1575
+ "skip-proxy": list(z.union([
1576
+ hostPattern,
1577
+ ip,
1578
+ cidr()
1579
+ ])).optional(),
1580
+ ipv6: z.boolean().optional(),
1581
+ "ipv6-vif": z.enum([
1582
+ "auto",
1583
+ "always",
1584
+ "disabled"
1585
+ ]).optional(),
1586
+ "bypass-system": z.boolean().optional(),
1587
+ replica: z.boolean().optional(),
1588
+ "tls-provider": z.enum(["default", "openssl"]).optional(),
1589
+ "bypass-tun": list(cidr()).optional(),
1590
+ "always-real-ip": list(hostPattern).optional(),
1591
+ "http-api": control.optional(),
1592
+ "http-api-web-dashboard": z.boolean().optional(),
1593
+ "external-controller-access": control.optional(),
1594
+ "hijack-dns": list(safe.refine((v) => /^\*(?::\d+)?$/.test(v) ? !v.includes(":") || Number(v.slice(2)) > 0 && Number(v.slice(2)) <= 65535 : addressPort(v, false, false))).optional(),
1595
+ "http-listen": listener.optional(),
1596
+ "socks5-listen": listener.optional(),
1597
+ "proxy-restricted-to-lan": z.boolean().optional()
1598
+ });
1599
+ const hostSchema = z.strictObject({
1600
+ pattern: hostPattern,
1601
+ address: z.union([ip, domain]).optional(),
1602
+ server: z.union([dns, encryptedDns]).optional()
1603
+ }).refine((v) => v.address !== void 0 || v.server !== void 0);
1604
+ const key = z.string().regex(/^[A-Za-z0-9+/]{43}=$/).refine((v) => Buffer.from(v, "base64").length === 32 && Buffer.from(v, "base64").toString("base64") === v);
1605
+ const sectionName = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,127}$/);
1606
+ const tunnelSchema = z.discriminatedUnion("type", [z.strictObject({
1607
+ type: z.literal("tailscale"),
1608
+ id: idSchema,
1609
+ sectionName,
1610
+ authKey: token,
1611
+ hostname: domain,
1612
+ dnsServer: list(dns).optional(),
1613
+ autoAddMagicDnsRule: z.boolean().optional(),
1614
+ idleKeepalive: z.number().int().min(-1).max(2147483647).optional()
1615
+ }), z.strictObject({
1616
+ type: z.literal("wireguard"),
1617
+ id: idSchema,
1618
+ sectionName,
1619
+ privateKey: token,
1620
+ selfIp: ip.refine((v) => isIP(v) === 4),
1621
+ dnsServer: list(dns).optional(),
1622
+ mtu: z.number().int().min(576).max(9e3).optional(),
1623
+ peers: list(z.strictObject({
1624
+ publicKey: key,
1625
+ endpoint,
1626
+ allowedIps: list(cidr()),
1627
+ presharedKey: token.optional(),
1628
+ persistentKeepalive: z.number().int().min(0).max(65535).optional()
1629
+ }))
1630
+ })]);
1631
+ const groupSchema = z.strictObject({
1632
+ id: idSchema,
1633
+ type: z.enum(["select", "smart"]),
1634
+ members: list(policy$1),
1635
+ url: url.optional(),
1636
+ intervalSeconds: z.number().int().positive().max(2147483647).optional(),
1637
+ timeoutSeconds: z.number().int().positive().max(3600).optional()
1638
+ });
1639
+ const options = {
1640
+ noResolve: z.boolean().optional(),
1641
+ extendedMatching: z.boolean().optional()
1642
+ };
1643
+ const atom$1 = (type, value) => z.strictObject({
1644
+ type: z.literal(type),
1645
+ value,
1646
+ ...options
1647
+ });
1648
+ const conditionSchema = z.lazy(() => z.union([
1649
+ atom$1("domain", domain),
1650
+ atom$1("domainSuffix", domain),
1651
+ atom$1("ipCidr", cidr(4)),
1652
+ atom$1("ipCidr6", cidr(6)),
1653
+ atom$1("sourceIp", z.union([ip, cidr()])),
1654
+ atom$1("processName", safe),
1655
+ atom$1("macAddress", z.string().regex(/^(?:[\da-fA-F]{2}:){5}[\da-fA-F]{2}$/)),
1656
+ z.strictObject({
1657
+ type: z.enum(["port", "sourcePort"]),
1658
+ from: port,
1659
+ to: port.optional(),
1660
+ ...options
1661
+ }).refine((v) => v.to === void 0 || v.to >= v.from),
1662
+ z.strictObject({
1663
+ type: z.literal("network"),
1664
+ value: z.enum(["tcp", "udp"]),
1665
+ ...options
1666
+ }),
1667
+ z.strictObject({
1668
+ type: z.enum(["all", "any"]),
1669
+ conditions: z.array(conditionSchema).min(2).max(100),
1670
+ ...options
1671
+ }),
1672
+ z.strictObject({
1673
+ type: z.literal("not"),
1674
+ condition: conditionSchema,
1675
+ ...options
1676
+ }),
1677
+ z.strictObject({
1678
+ type: z.literal("ruleSet"),
1679
+ format: z.enum(["rule-set", "domain-set"]),
1680
+ url: url.optional(),
1681
+ builtin: z.enum(["LAN", "SYSTEM"]).optional(),
1682
+ ...options
1683
+ }).refine((v) => v.url !== void 0 !== (v.builtin !== void 0))
1684
+ ]));
1685
+ const managedSchema = z.strictObject({
1686
+ url: url.refine((v) => !new URL(v).search && !v.includes("?")),
1687
+ query: z.record(z.string().min(1).max(128).regex(/^[A-Za-z][A-Za-z0-9_-]*$/), z.union([z.string().max(4096), token])).optional(),
1688
+ intervalSeconds: z.number().int().min(60).max(2147483647),
1689
+ strict: z.boolean()
1690
+ });
1691
+ const inputSchema = z.strictObject({
1692
+ target: z.strictObject({
1693
+ engine: z.literal("surge"),
1694
+ platform: z.enum(["macos", "ios"]),
1695
+ version: z.string()
1696
+ }),
1697
+ managed: managedSchema.optional(),
1698
+ general: generalSchema.optional(),
1699
+ hosts: z.array(hostSchema).max(2e3).optional(),
1700
+ nodes: z.array(nodeSchema).max(1e3),
1701
+ tunnels: z.array(tunnelSchema).max(1e3).optional(),
1702
+ groups: z.array(groupSchema).max(1e3),
1703
+ rules: z.array(z.strictObject({
1704
+ when: conditionSchema,
1705
+ then: policy$1
1706
+ })).max(1e4),
1707
+ fallback: policy$1,
1708
+ names: z.record(idSchema, nativeNameSchema).optional()
1709
+ });
1710
+ const plans = /* @__PURE__ */ new WeakMap();
1711
+ function compileSurgeProfile(input) {
1712
+ const diagnostics = [];
1713
+ const error = (code) => diagnostics.push({
1714
+ severity: "error",
1715
+ code,
1716
+ path: "$",
1717
+ message: code
1718
+ });
1719
+ const failure = () => deepFreeze({
1720
+ ok: false,
1721
+ artifactKind: "surge-profile",
1722
+ diagnostics,
1723
+ bindings: []
1724
+ });
1725
+ try {
1726
+ assertData(input);
1727
+ } catch {
1728
+ error("INVALID_INPUT_GRAPH");
1729
+ return failure();
1730
+ }
1731
+ const parsed = inputSchema.safeParse(input);
1732
+ if (!parsed.success) {
1733
+ error("INVALID_SCHEMA");
1734
+ return failure();
1735
+ }
1736
+ if (parsed.data.general) {
1737
+ const general = parsed.data.general;
1738
+ parsed.data.general = Object.fromEntries(Object.keys(input.general).map((key) => [key, general[key]]));
1739
+ }
1740
+ const p = deepFreeze(parsed.data);
1741
+ if (!(p.target.platform === "macos" && p.target.version === "6.10.0") && !(p.target.platform === "ios" && p.target.version === "5.21.0")) error("UNKNOWN_TARGET");
1742
+ const tunnels = p.tunnels ?? [];
1743
+ const resources = [
1744
+ ...p.nodes,
1745
+ ...tunnels,
1746
+ ...p.groups
1747
+ ];
1748
+ if (resources.length > 1e3) error("RESOURCE_LIMIT");
1749
+ const ids = new Set(resources.map((r) => r.id));
1750
+ if (ids.size !== resources.length) error("DUPLICATE_RESOURCE");
1751
+ if (Object.keys(p.names ?? {}).some((id) => !ids.has(id))) error("UNKNOWN_NAME_MAPPING");
1752
+ const bindings = resources.map((r) => ({
1753
+ id: r.id,
1754
+ nativeName: p.names?.[r.id] ?? r.id
2066
1755
  }));
2067
- if (program.fallback.type === "reject") rules.push(singAction(program.fallback));
2068
- else routing.final = actionTag(program.fallback);
2069
- const config = {
2070
- log: { level: "warn" },
2071
- outbounds,
2072
- route: routing
1756
+ if (bindings.some((b) => !nativeNameSchema.safeParse(b.nativeName).success || isReservedNativeName(b.nativeName, "surge"))) error("INVALID_NATIVE_NAME");
1757
+ if (new Set(bindings.map((b) => b.nativeName)).size !== bindings.length) error("DUPLICATE_NATIVE_NAME");
1758
+ if (new Set(tunnels.map((t) => t.sectionName)).size !== tunnels.length) error("DUPLICATE_TUNNEL_SECTION");
1759
+ if (p.target.platform === "ios" && [
1760
+ "bypass-system",
1761
+ "replica",
1762
+ "tls-provider",
1763
+ "bypass-tun",
1764
+ "external-controller-access"
1765
+ ].some((k) => Object.hasOwn(p.general ?? {}, k))) error("PLATFORM_OPTION_UNSUPPORTED");
1766
+ if (new Set((p.hosts ?? []).map((h) => h.pattern.toLowerCase())).size !== (p.hosts ?? []).length) error("DUPLICATE_HOST_PATTERN");
1767
+ const checkPolicy = (action) => {
1768
+ if ("ref" in action && !ids.has(action.ref)) error("MISSING_REFERENCE");
2073
1769
  };
2074
- if (standalone) {
2075
- const listener = program.listener;
2076
- config.inbounds = [{
2077
- type: "mixed",
2078
- tag: "pl-listener",
2079
- listen: "127.0.0.1",
2080
- listen_port: listener.port
2081
- }];
2082
- config.dns = {
2083
- servers: [modern ? {
2084
- type: "udp",
2085
- tag: DNS,
2086
- server: listener.resolver,
2087
- server_port: 53,
2088
- detour: DIRECT
2089
- } : {
2090
- tag: DNS,
2091
- address: `udp://${isIP(listener.resolver) === 6 ? `[${listener.resolver}]` : listener.resolver}`,
2092
- detour: DIRECT
2093
- }],
2094
- final: DNS,
2095
- strategy: "prefer_ipv4"
2096
- };
2097
- if (modern) routing.default_domain_resolver = {
2098
- server: DNS,
2099
- strategy: "prefer_ipv4"
2100
- };
1770
+ const edges = new Map(resources.map((r) => [r.id, []]));
1771
+ const proxyIds = new Set([...p.nodes, ...tunnels].map((n) => n.id));
1772
+ for (const node of p.nodes) {
1773
+ if (node.type === "vless") error("PROTOCOL_UNSUPPORTED");
1774
+ validateProxyOptions(node, {
1775
+ id: "profile",
1776
+ engine: "surge"
1777
+ }, diagnostics);
1778
+ if (node.via) {
1779
+ checkPolicy({ ref: node.via });
1780
+ edges.get(node.id).push(node.via);
1781
+ }
2101
1782
  }
2102
- if (program.endpoints?.length) {
2103
- config.endpoints = program.endpoints.map((endpoint) => ({
2104
- type: "tailscale",
2105
- tag: endpoint.id,
2106
- hostname: endpoint.hostname,
2107
- state_directory: endpoint.stateDirectory,
2108
- accept_routes: endpoint.acceptRoutes,
2109
- domain_resolver: { server: `pl-ts-dns-${endpoint.id}` },
2110
- ...endpoint.authKey ? { auth_key: secret(endpoint.authKey) } : {},
2111
- ...endpoint.exitNode ? { exit_node: endpoint.exitNode } : {},
2112
- ...endpoint.exitNodeAllowLanAccess !== void 0 ? { exit_node_allow_lan_access: endpoint.exitNodeAllowLanAccess } : {}
2113
- }));
2114
- const dns = config.dns;
2115
- for (const endpoint of program.endpoints) dns.servers.push({
2116
- type: "udp",
2117
- tag: `pl-ts-dns-${endpoint.id}`,
2118
- server: endpoint.bootstrapResolver,
2119
- server_port: 53,
2120
- detour: DIRECT
2121
- });
1783
+ for (const group of p.groups) {
1784
+ if (group.type === "smart" && (group.url !== void 0 || group.intervalSeconds !== void 0 || group.timeoutSeconds !== void 0)) error("GROUP_OPTION_UNSUPPORTED");
1785
+ for (const member of group.members) {
1786
+ checkPolicy(member);
1787
+ if (group.type === "smart" && (!("ref" in member) || !proxyIds.has(member.ref))) error("SMART_MEMBER_UNSUPPORTED");
1788
+ if ("ref" in member) edges.get(group.id).push(member.ref);
1789
+ }
1790
+ }
1791
+ const active = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set();
1792
+ const visit = (id) => {
1793
+ if (active.has(id)) {
1794
+ error("RESOURCE_CYCLE");
1795
+ return;
1796
+ }
1797
+ if (visited.has(id)) return;
1798
+ active.add(id);
1799
+ for (const next of edges.get(id) ?? []) visit(next);
1800
+ active.delete(id);
1801
+ visited.add(id);
1802
+ };
1803
+ if (resources.length <= 1e3) for (const id of ids) visit(id);
1804
+ const formats = /* @__PURE__ */ new Map();
1805
+ const checkCondition = (c, depth) => {
1806
+ if (depth > 10) {
1807
+ error("LOGICAL_DEPTH_EXCEEDED");
1808
+ return;
1809
+ }
1810
+ if (c.noResolve !== void 0 && ![
1811
+ "ipCidr",
1812
+ "ipCidr6",
1813
+ "ruleSet"
1814
+ ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
1815
+ if (c.extendedMatching !== void 0 && ![
1816
+ "domain",
1817
+ "domainSuffix",
1818
+ "ruleSet"
1819
+ ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
1820
+ if (p.target.platform === "ios" && ["processName", "macAddress"].includes(c.type)) error("PLATFORM_RULE_UNSUPPORTED");
1821
+ if (c.type === "all" || c.type === "any") for (const child of c.conditions) checkCondition(child, depth + 1);
1822
+ if (c.type === "not") checkCondition(c.condition, depth + 1);
1823
+ if (c.type === "ruleSet") {
1824
+ if (c.builtin && c.format !== "rule-set") error("BUILTIN_RULESET_FORMAT");
1825
+ if (c.url) {
1826
+ if (formats.has(c.url) && formats.get(c.url) !== c.format) error("RULESET_FORMAT_CONFLICT");
1827
+ formats.set(c.url, c.format);
1828
+ }
1829
+ }
1830
+ };
1831
+ for (const rule of p.rules) {
1832
+ checkPolicy(rule.then);
1833
+ checkCondition(rule.when, 0);
2122
1834
  }
2123
- return config;
1835
+ checkPolicy(p.fallback);
1836
+ if (diagnostics.some((d) => d.severity === "error")) return failure();
1837
+ if (formats.size) diagnostics.push({
1838
+ severity: "warning",
1839
+ code: "EXTERNAL_RULESET_UNVERIFIED",
1840
+ path: "rules",
1841
+ message: "External rule sets are resolved by the client, not by the compiler."
1842
+ });
1843
+ const result = deepFreeze({
1844
+ ok: true,
1845
+ artifactKind: "surge-profile",
1846
+ diagnostics,
1847
+ bindings
1848
+ });
1849
+ plans.set(result, p);
1850
+ return result;
2124
1851
  }
2125
- function surgeCondition(condition) {
2126
- switch (condition.type) {
2127
- case "ruleSet": return surgeCondition(condition.when);
2128
- case "nativeRuleSet": return `${condition.format === "domain-set" ? "DOMAIN-SET" : "RULE-SET"},${condition.url}`;
1852
+ function conditionOptions(c) {
1853
+ return [...c.noResolve ? ["no-resolve"] : [], ...c.extendedMatching ? ["extended-matching"] : []];
1854
+ }
1855
+ function conditionText(c) {
1856
+ switch (c.type) {
2129
1857
  case "all":
2130
- case "any": return `${condition.type === "all" ? "AND" : "OR"},(${condition.conditions.map((c) => `(${surgeCondition(c)})`).join(",")})`;
2131
- case "not": return `NOT,((${surgeCondition(condition.condition)}))`;
2132
- case "domain": return `DOMAIN,${condition.value}`;
2133
- case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
2134
- case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value},no-resolve`;
2135
- case "sourceIp": return `SRC-IP,${condition.value}`;
2136
- case "network": return `PROTOCOL,${condition.value.toUpperCase()}`;
1858
+ case "any": return `${c.type === "all" ? "AND" : "OR"},(${c.conditions.map((x) => `(${[conditionText(x), ...conditionOptions(x)].join(",")})`).join(",")})`;
1859
+ case "not": return `NOT,((${[conditionText(c.condition), ...conditionOptions(c.condition)].join(",")}))`;
2137
1860
  case "port":
2138
- case "sourcePort": return `${condition.type === "port" ? "DEST-PORT" : "SRC-PORT"},${condition.from === condition.to ? condition.from : `${condition.from}-${condition.to}`}`;
1861
+ case "sourcePort": return `${c.type === "port" ? "DEST-PORT" : "SRC-PORT"},${c.from}${c.to === void 0 || c.to === c.from ? "" : `-${c.to}`}`;
1862
+ case "network": return `PROTOCOL,${c.value.toUpperCase()}`;
1863
+ case "ruleSet": return `${c.format === "rule-set" ? "RULE-SET" : "DOMAIN-SET"},${c.url ?? c.builtin}`;
1864
+ default: return `${{
1865
+ domain: "DOMAIN",
1866
+ domainSuffix: "DOMAIN-SUFFIX",
1867
+ ipCidr: "IP-CIDR",
1868
+ ipCidr6: "IP-CIDR6",
1869
+ sourceIp: "SRC-IP",
1870
+ processName: "PROCESS-NAME",
1871
+ macAddress: "MAC-ADDRESS"
1872
+ }[c.type]},${c.value}`;
2139
1873
  }
2140
1874
  }
2141
- function surge(plan, secret) {
2142
- const policy = (action) => action.type === "route" ? action.to : action.type === "direct" ? "DIRECT" : "REJECT";
2143
- const lines = ["# Generated by proxylang; see manifest for source mapping and preconditions."];
2144
- if (plan.target.mode === "standalone") lines.push("[General]", "loglevel = warning", "allow-wifi-access = false", `http-listen = 127.0.0.1:${plan.program.listener.port}`, `dns-server = ${plan.program.listener.resolver}`, "");
2145
- lines.push("[Proxy]");
2146
- for (const node of plan.program.nodes) lines.push(surgeProxy(node, secret));
1875
+ function renderProfile(compilation, read) {
1876
+ const p = plans.get(compilation);
1877
+ if (!p) throw new RenderError("COMPILATION_FAILED");
1878
+ const name = (id) => p.names?.[id] ?? id;
1879
+ const action = (value) => "ref" in value ? name(value.ref) : value.builtin;
1880
+ const credential = (token, kind) => {
1881
+ const value = read(token);
1882
+ if (!(kind === "key" ? key.safeParse(value).success : kind === "control" ? /^[A-Za-z0-9_.+%-]+$/.test(value) : /^[A-Za-z0-9_-]+$/.test(value))) throw new RenderError("SURGE_VALUE_UNREPRESENTABLE");
1883
+ return value;
1884
+ };
1885
+ const lines = [];
1886
+ if (p.managed) {
1887
+ const address = new URL(p.managed.url);
1888
+ for (const [k, v] of Object.entries(p.managed.query ?? {})) address.searchParams.set(k, typeof v === "string" ? v : read(v));
1889
+ lines.push(`#!MANAGED-CONFIG ${address.href} interval=${p.managed.intervalSeconds} strict=${p.managed.strict}`, "");
1890
+ }
1891
+ lines.push("[General]");
1892
+ for (const [k, v] of Object.entries(p.general ?? {})) {
1893
+ const value = Array.isArray(v) ? v.join(", ") : typeof v === "object" ? `${credential(v.password, "control")}@${v.listen}` : String(v);
1894
+ lines.push(`${k} = ${value}`);
1895
+ }
1896
+ lines.push("", "[Host]");
1897
+ for (const h of p.hosts ?? []) lines.push(`${h.pattern} = ${[...h.address ? [h.address] : [], ...h.server ? [`server:${h.server}`] : []].join(", ")}`);
1898
+ lines.push("", "[Proxy]");
1899
+ for (const n of p.nodes) lines.push(surgeProxy(n, read, name));
1900
+ for (const t of p.tunnels ?? []) lines.push(`${name(t.id)} = ${t.type}, section-name=${t.sectionName}`);
1901
+ for (const t of p.tunnels ?? []) {
1902
+ lines.push("", `[${t.type === "tailscale" ? "Tailscale" : "WireGuard"} ${t.sectionName}]`);
1903
+ if (t.type === "tailscale") {
1904
+ lines.push(`auth-key = ${credential(t.authKey, "tailscale")}`, `hostname = ${t.hostname}`);
1905
+ if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
1906
+ if (t.autoAddMagicDnsRule !== void 0) lines.push(`auto-add-magic-dns-rule = ${t.autoAddMagicDnsRule}`);
1907
+ if (t.idleKeepalive !== void 0) lines.push(`idle-keepalive = ${t.idleKeepalive}`);
1908
+ } else {
1909
+ lines.push(`private-key = ${credential(t.privateKey, "key")}`, `self-ip = ${t.selfIp}`);
1910
+ if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
1911
+ if (t.mtu !== void 0) lines.push(`mtu = ${t.mtu}`);
1912
+ for (const peer of t.peers) {
1913
+ const values = [`public-key = ${peer.publicKey}`];
1914
+ if (peer.presharedKey) values.push(`preshared-key = ${credential(peer.presharedKey, "key")}`);
1915
+ values.push(`allowed-ips = "${peer.allowedIps.join(", ")}"`, `endpoint = ${peer.endpoint}`);
1916
+ if (peer.persistentKeepalive !== void 0) values.push(`keepalive = ${peer.persistentKeepalive}`);
1917
+ lines.push(`peer = (${values.join(", ")})`);
1918
+ }
1919
+ }
1920
+ }
2147
1921
  lines.push("", "[Proxy Group]");
2148
- for (const group of plan.program.groups) lines.push(surgeGroup(group));
1922
+ for (const g of p.groups) lines.push(`${name(g.id)} = ${[
1923
+ g.type,
1924
+ ...g.members.map(action),
1925
+ ...g.url ? [`url=${g.url}`] : [],
1926
+ ...g.intervalSeconds !== void 0 ? [`interval=${g.intervalSeconds}`] : [],
1927
+ ...g.timeoutSeconds !== void 0 ? [`timeout=${g.timeoutSeconds}`] : []
1928
+ ].join(", ")}`);
2149
1929
  lines.push("", "[Rule]");
2150
- for (const rule of plan.rules) {
2151
- lines.push(`# ${rule.id}`);
2152
- if (rule.when.type === "ipCidr") {
2153
- const condition = surgeCondition(rule.when).replace(/,no-resolve$/, "");
2154
- lines.push(`${condition},${policy(rule.then)},no-resolve`);
2155
- } else lines.push(`${surgeCondition(rule.when)},${policy(rule.then)}${rule.when.type === "nativeRuleSet" && rule.when.intervalSeconds !== void 0 ? `,update-interval=${rule.when.intervalSeconds}` : ""}`);
2156
- }
2157
- lines.push(`FINAL,${policy(plan.program.fallback)}`);
2158
- return lines.join("\n") + "\n";
1930
+ for (const r of p.rules) lines.push([
1931
+ conditionText(r.when),
1932
+ action(r.then),
1933
+ ...conditionOptions(r.when)
1934
+ ].join(","));
1935
+ lines.push(`FINAL,${action(p.fallback)}`, "");
1936
+ return deepFreeze({
1937
+ artifactKind: "surge-profile",
1938
+ content: lines.join("\n")
1939
+ });
1940
+ }
1941
+ function renderSurgeProfile(compilation, resolveSecret) {
1942
+ return renderProfile(compilation, secretReader(resolveSecret));
1943
+ }
1944
+ function renderSurgeProfiles(compilations, resolveSecret) {
1945
+ if (compilations.some((c) => !plans.has(c))) throw new RenderError("COMPILATION_FAILED");
1946
+ const read = secretReader(resolveSecret);
1947
+ return deepFreeze(compilations.map((c) => renderProfile(c, read)));
2159
1948
  }
2160
1949
  //#endregion
2161
- //#region src/host.ts
2162
- const buildHints = {
2163
- INVALID_OUTPUT_DIRECTORY: "提供非空输出目录路径",
2164
- OUTPUT_LOCKED: "确认没有构建正在运行;检查并处理遗留锁后重试,不要删除仍在使用的锁",
2165
- SECRET_MISSING: "在构建环境提供配置引用的非空秘密变量",
2166
- SECRET_RESOLUTION_FAILED: "检查秘密解析器;原始异常不会进入构建报告",
2167
- PUBLISHED_CLEANUP_FAILED: "活动指针已经切换;检查残留锁和临时文件,不要假设发布失败",
2168
- FAILED_CLEANUP_REQUIRED: "旧活动指针保留;检查本次残留产物和锁后重试"
1950
+ //#region src/surge-definitions.ts
1951
+ var ProfileDefinitionError = class extends Error {
1952
+ code;
1953
+ constructor(code) {
1954
+ super(code);
1955
+ this.code = code;
1956
+ this.name = "ProfileDefinitionError";
1957
+ }
2169
1958
  };
2170
- function outputFailure(error) {
2171
- const code = error && typeof error === "object" ? Object.getOwnPropertyDescriptor(error, "code")?.value : void 0;
2172
- if (code === "EACCES" || code === "EPERM") return {
2173
- reason: "ACCESS_DENIED",
2174
- hint: "检查输出目录的写入和遍历权限"
2175
- };
2176
- if (code === "ENOSPC" || code === "EDQUOT") return {
2177
- reason: "NO_SPACE",
2178
- hint: "释放磁盘空间或调整存储配额后重试"
2179
- };
2180
- if (code === "EROFS") return {
2181
- reason: "READ_ONLY",
2182
- hint: "选择可写的本地输出目录"
2183
- };
2184
- if ([
2185
- "ENOTDIR",
2186
- "EISDIR",
2187
- "EEXIST",
2188
- "UNSAFE_DIRECTORY"
2189
- ].includes(code)) return {
2190
- reason: "INVALID_DIRECTORY",
2191
- hint: "检查输出根、generations 和 active.json 的文件类型;输出目录不能是符号链接"
1959
+ const fail$1 = (code) => {
1960
+ throw new ProfileDefinitionError(code);
1961
+ };
1962
+ /** Inspect descriptors before any caller spreads or reads input fields. Shared DAGs are legal. */
1963
+ function inspectDefinition(root) {
1964
+ let edges = 0;
1965
+ let objects = 0;
1966
+ const visiting = /* @__PURE__ */ new Set();
1967
+ const heights = /* @__PURE__ */ new Map();
1968
+ function visit(value, depth) {
1969
+ if (depth > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
1970
+ if (value === null || typeof value !== "object") {
1971
+ if (![
1972
+ "undefined",
1973
+ "string",
1974
+ "number",
1975
+ "boolean"
1976
+ ].includes(typeof value) && value !== null) fail$1("DEFINITION_NOT_DATA");
1977
+ return 0;
1978
+ }
1979
+ if (visiting.has(value)) fail$1("DEFINITION_CYCLE");
1980
+ const cached = heights.get(value);
1981
+ if (cached !== void 0) {
1982
+ if (depth + cached > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
1983
+ return cached;
1984
+ }
1985
+ if (++objects > 2e4) fail$1("DEFINITION_OBJECT_BUDGET_EXCEEDED");
1986
+ const proto = Object.getPrototypeOf(value);
1987
+ if (proto !== Object.prototype && proto !== null && !(Array.isArray(value) && proto === Array.prototype)) fail$1("DEFINITION_NOT_DATA");
1988
+ if (Array.isArray(value) && value.length > 1e5) fail$1("DEFINITION_EDGE_BUDGET_EXCEEDED");
1989
+ visiting.add(value);
1990
+ let height = 0;
1991
+ for (const key of Reflect.ownKeys(value)) {
1992
+ if (++edges > 1e5) fail$1("DEFINITION_EDGE_BUDGET_EXCEEDED");
1993
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
1994
+ if (typeof key !== "string" || !("value" in descriptor) || !descriptor.enumerable && !(Array.isArray(value) && key === "length")) fail$1("DEFINITION_NOT_DATA");
1995
+ height = Math.max(height, 1 + visit(descriptor.value, depth + 1));
1996
+ }
1997
+ visiting.delete(value);
1998
+ heights.set(value, height);
1999
+ return height;
2000
+ }
2001
+ visit(root, 0);
2002
+ }
2003
+ /** Count output occurrences, not identities, before allocating each copied value. */
2004
+ function snapshot(input) {
2005
+ let remaining = 1e5;
2006
+ function copy(value, depth) {
2007
+ if (--remaining < 0) fail$1("DEFINITION_OUTPUT_BUDGET_EXCEEDED");
2008
+ if (depth > 64) fail$1("DEFINITION_DEPTH_EXCEEDED");
2009
+ if (value === null || typeof value !== "object") return value;
2010
+ if (Array.isArray(value)) {
2011
+ const output = [];
2012
+ for (const item of value) output.push(copy(item, depth + 1));
2013
+ return output;
2014
+ }
2015
+ const output = {};
2016
+ for (const [key, item] of Object.entries(value)) Object.defineProperty(output, key, {
2017
+ value: copy(item, depth + 1),
2018
+ enumerable: true,
2019
+ writable: true,
2020
+ configurable: true
2021
+ });
2022
+ return output;
2023
+ }
2024
+ return copy(input, 0);
2025
+ }
2026
+ function snapshotDefinition(input) {
2027
+ inspectDefinition(input);
2028
+ return snapshot(input);
2029
+ }
2030
+ function exactDefinition(value, keys) {
2031
+ if (!value || typeof value !== "object" || Array.isArray(value)) fail$1("DEFINITION_NOT_DATA");
2032
+ if (Object.keys(value).some((key) => !keys.includes(key))) fail$1("DEFINITION_UNKNOWN_FIELD");
2033
+ }
2034
+ const outbound = {
2035
+ direct: Object.freeze({ builtin: "DIRECT" }),
2036
+ reject: Object.freeze({ builtin: "REJECT" }),
2037
+ rejectDrop: Object.freeze({ builtin: "REJECT-DROP" }),
2038
+ rejectNoDrop: Object.freeze({ builtin: "REJECT-NO-DROP" }),
2039
+ rejectTinyGif: Object.freeze({ builtin: "REJECT-TINYGIF" })
2040
+ };
2041
+ function defineProxyGroup(input) {
2042
+ inspectDefinition(input);
2043
+ exactDefinition(input, [
2044
+ "id",
2045
+ "name",
2046
+ "algorithm",
2047
+ "members",
2048
+ "url",
2049
+ "intervalSeconds",
2050
+ "timeoutSeconds"
2051
+ ]);
2052
+ if (!input.algorithm || ![
2053
+ "select",
2054
+ "surge-smart",
2055
+ "urltest"
2056
+ ].includes(input.algorithm.type)) fail$1("UNSUPPORTED_GROUP_ALGORITHM");
2057
+ exactDefinition(input.algorithm, input.algorithm.type === "urltest" ? [
2058
+ "type",
2059
+ "url",
2060
+ "intervalSeconds",
2061
+ "toleranceMs"
2062
+ ] : ["type"]);
2063
+ if (!Array.isArray(input.members)) fail$1("INVALID_GROUP_DEFINITION");
2064
+ return {
2065
+ ...input,
2066
+ type: "proxy-group",
2067
+ algorithm: { ...input.algorithm },
2068
+ members: [...input.members]
2192
2069
  };
2070
+ }
2071
+ function defineRoute(input) {
2072
+ inspectDefinition(input);
2073
+ exactDefinition(input, ["when", "to"]);
2193
2074
  return {
2194
- reason: "IO_ERROR",
2195
- hint: "检查输出目录及文件系统状态,旧活动配置在发布前失败时保持不变"
2075
+ ...input,
2076
+ type: "route"
2196
2077
  };
2197
2078
  }
2198
- async function directory(path) {
2199
- await mkdir(path, {
2200
- recursive: true,
2201
- mode: 448
2079
+ function defineRoutes(input) {
2080
+ inspectDefinition(input);
2081
+ exactDefinition(input, ["when", "to"]);
2082
+ if (!Array.isArray(input.when)) fail$1("INVALID_ROUTE_DEFINITION");
2083
+ return input.when.map((when) => ({
2084
+ type: "route",
2085
+ when,
2086
+ to: input.to
2087
+ }));
2088
+ }
2089
+ function selectProxies(nodes, query = {}) {
2090
+ inspectDefinition({
2091
+ nodes,
2092
+ query
2202
2093
  });
2203
- const stat = await lstat(path);
2204
- if (!stat.isDirectory() || stat.isSymbolicLink()) throw Object.assign(/* @__PURE__ */ new Error("UNSAFE_DIRECTORY"), { code: "UNSAFE_DIRECTORY" });
2094
+ exactDefinition(query, [
2095
+ "ids",
2096
+ "regions",
2097
+ "providers",
2098
+ "tags"
2099
+ ]);
2100
+ if (!Array.isArray(nodes) || nodes.some((node) => !node || typeof node !== "object")) fail$1("DEFINITION_NOT_DATA");
2101
+ for (const values of Object.values(query)) if (values !== void 0 && !Array.isArray(values)) fail$1("DEFINITION_NOT_DATA");
2102
+ return nodes.filter((node) => (!query.ids || query.ids.includes(node.id)) && (!query.regions || node.region !== void 0 && query.regions.includes(node.region)) && (!query.providers || node.provider !== void 0 && query.providers.includes(node.provider)) && (!query.tags || query.tags.every((tag) => node.tags?.includes(tag))));
2205
2103
  }
2206
- /** All targets publish together by one active.json rename. Config files never go to stdout. */
2207
- async function buildToDirectory(compilation, output, resolveSecret = (token) => process.env[token.name]) {
2208
- if (!compilation.ok) return {
2209
- published: false,
2210
- exitCode: 1,
2211
- code: "COMPILATION_FAILED"
2104
+ function defineSurgeProfile(input) {
2105
+ inspectDefinition(input);
2106
+ exactDefinition(input, [
2107
+ "target",
2108
+ "managed",
2109
+ "general",
2110
+ "hosts",
2111
+ "nodes",
2112
+ "tunnels",
2113
+ "names",
2114
+ "groups",
2115
+ "routes",
2116
+ "fallback"
2117
+ ]);
2118
+ if (!Array.isArray(input.nodes) || !Array.isArray(input.groups) || !Array.isArray(input.routes) || input.tunnels !== void 0 && !Array.isArray(input.tunnels)) fail$1("DEFINITION_NOT_DATA");
2119
+ const registry = /* @__PURE__ */ new Map();
2120
+ const names = Object.assign(Object.create(null), input.names);
2121
+ for (const resource of [
2122
+ ...input.nodes,
2123
+ ...input.tunnels ?? [],
2124
+ ...input.groups
2125
+ ]) {
2126
+ if (!resource || typeof resource !== "object" || typeof resource.id !== "string") fail$1("INVALID_RESOURCE_DEFINITION");
2127
+ if (registry.has(resource.id)) fail$1("DUPLICATE_RESOURCE_ID");
2128
+ registry.set(resource.id, resource);
2129
+ const name = resource.type === "proxy-group" ? resource.name : "label" in resource ? resource.label ?? resource.id : resource.id;
2130
+ if (resource.type === "proxy-group" && names[resource.id] !== void 0 && names[resource.id] !== name) fail$1("GROUP_NAME_CONFLICT");
2131
+ Object.defineProperty(names, resource.id, {
2132
+ value: names[resource.id] ?? name,
2133
+ enumerable: true,
2134
+ configurable: true,
2135
+ writable: true
2136
+ });
2137
+ }
2138
+ function lower(destination) {
2139
+ if (!destination || typeof destination !== "object") fail$1("INVALID_DESTINATION");
2140
+ if ("builtin" in destination) {
2141
+ exactDefinition(destination, ["builtin"]);
2142
+ if (!Object.values(outbound).some((value) => value.builtin === destination.builtin)) fail$1("INVALID_DESTINATION");
2143
+ return { builtin: destination.builtin };
2144
+ }
2145
+ if (registry.get(destination.id) !== destination) fail$1("UNREGISTERED_DESTINATION_INSTANCE");
2146
+ return { ref: destination.id };
2147
+ }
2148
+ const groups = input.groups.map((definition) => {
2149
+ exactDefinition(definition, [
2150
+ "type",
2151
+ "id",
2152
+ "name",
2153
+ "algorithm",
2154
+ "members",
2155
+ "url",
2156
+ "intervalSeconds",
2157
+ "timeoutSeconds"
2158
+ ]);
2159
+ if (definition.type !== "proxy-group") fail$1("INVALID_GROUP_DEFINITION");
2160
+ if (!definition.algorithm || !["select", "surge-smart"].includes(definition.algorithm.type)) fail$1("UNSUPPORTED_GROUP_ALGORITHM");
2161
+ exactDefinition(definition.algorithm, ["type"]);
2162
+ if (!Array.isArray(definition.members)) fail$1("INVALID_GROUP_DEFINITION");
2163
+ const { id, url, intervalSeconds, timeoutSeconds } = definition;
2164
+ return {
2165
+ id,
2166
+ type: definition.algorithm.type === "select" ? "select" : "smart",
2167
+ members: definition.members.map(lower),
2168
+ ...url === void 0 ? {} : { url },
2169
+ ...intervalSeconds === void 0 ? {} : { intervalSeconds },
2170
+ ...timeoutSeconds === void 0 ? {} : { timeoutSeconds }
2171
+ };
2172
+ });
2173
+ const rules = input.routes.map((definition) => {
2174
+ exactDefinition(definition, [
2175
+ "type",
2176
+ "when",
2177
+ "to"
2178
+ ]);
2179
+ if (definition.type !== "route") fail$1("INVALID_ROUTE_DEFINITION");
2180
+ return {
2181
+ when: definition.when,
2182
+ then: lower(definition.to)
2183
+ };
2184
+ });
2185
+ const { routes: _routes, groups: _groups, fallback, ...rest } = input;
2186
+ return snapshot({
2187
+ ...rest,
2188
+ names,
2189
+ groups,
2190
+ rules,
2191
+ fallback: lower(fallback)
2192
+ });
2193
+ }
2194
+ function condition(value) {
2195
+ inspectDefinition(value);
2196
+ return value;
2197
+ }
2198
+ function atom(type) {
2199
+ return (value, options = {}) => {
2200
+ inspectDefinition(options);
2201
+ return condition({
2202
+ ...options,
2203
+ type,
2204
+ value
2205
+ });
2212
2206
  };
2213
- if (typeof output !== "string" || !output.trim()) return {
2214
- published: false,
2215
- exitCode: 1,
2216
- code: "INVALID_OUTPUT_DIRECTORY",
2217
- hint: buildHints.INVALID_OUTPUT_DIRECTORY
2207
+ }
2208
+ const surgeMatch = {
2209
+ domain: atom("domain"),
2210
+ domainSuffix: atom("domainSuffix"),
2211
+ ipCidr: atom("ipCidr"),
2212
+ ipCidr6: atom("ipCidr6"),
2213
+ sourceIp: atom("sourceIp"),
2214
+ processName: atom("processName"),
2215
+ macAddress: atom("macAddress"),
2216
+ network: (value, options = {}) => {
2217
+ inspectDefinition(options);
2218
+ return condition({
2219
+ ...options,
2220
+ type: "network",
2221
+ value
2222
+ });
2223
+ },
2224
+ port: (from, to, options = {}) => {
2225
+ inspectDefinition(options);
2226
+ return condition({
2227
+ ...options,
2228
+ type: "port",
2229
+ from,
2230
+ ...to === void 0 ? {} : { to }
2231
+ });
2232
+ },
2233
+ sourcePort: (from, to, options = {}) => {
2234
+ inspectDefinition(options);
2235
+ return condition({
2236
+ ...options,
2237
+ type: "sourcePort",
2238
+ from,
2239
+ ...to === void 0 ? {} : { to }
2240
+ });
2241
+ },
2242
+ all: (conditions, options = {}) => {
2243
+ inspectDefinition({
2244
+ conditions,
2245
+ options
2246
+ });
2247
+ return condition({
2248
+ ...options,
2249
+ type: "all",
2250
+ conditions: [...conditions]
2251
+ });
2252
+ },
2253
+ any: (conditions, options = {}) => {
2254
+ inspectDefinition({
2255
+ conditions,
2256
+ options
2257
+ });
2258
+ return condition({
2259
+ ...options,
2260
+ type: "any",
2261
+ conditions: [...conditions]
2262
+ });
2263
+ },
2264
+ not: (value, options = {}) => {
2265
+ inspectDefinition({
2266
+ value,
2267
+ options
2268
+ });
2269
+ return condition({
2270
+ ...options,
2271
+ type: "not",
2272
+ condition: value
2273
+ });
2274
+ },
2275
+ ruleSet: (options) => {
2276
+ inspectDefinition(options);
2277
+ return condition({
2278
+ ...options,
2279
+ type: "ruleSet"
2280
+ });
2281
+ }
2282
+ };
2283
+ //#endregion
2284
+ //#region src/profile.ts
2285
+ const fail = (code) => {
2286
+ throw new ProfileDefinitionError(code);
2287
+ };
2288
+ /** Keep aliases across nodes, groups and destinations; reject accessors before cloning. */
2289
+ function snapshotProfile(input) {
2290
+ inspectDefinition(input);
2291
+ return deepFreeze(structuredClone(input));
2292
+ }
2293
+ function surgeConfig(input) {
2294
+ inspectDefinition(input);
2295
+ exactDefinition(input, [
2296
+ "managed",
2297
+ "general",
2298
+ "hosts",
2299
+ "names"
2300
+ ]);
2301
+ return snapshotProfile(input);
2302
+ }
2303
+ function defineProfile(input) {
2304
+ inspectDefinition(input);
2305
+ exactDefinition(input, [
2306
+ "target",
2307
+ "nodes",
2308
+ "groups",
2309
+ "routes",
2310
+ "fallback",
2311
+ "endpoints",
2312
+ "surge",
2313
+ "singBox"
2314
+ ]);
2315
+ exactDefinition(input.target, [
2316
+ "engine",
2317
+ "platform",
2318
+ "version"
2319
+ ]);
2320
+ if (input.surge !== void 0) exactDefinition(input.surge, [
2321
+ "managed",
2322
+ "general",
2323
+ "hosts",
2324
+ "names"
2325
+ ]);
2326
+ if (input.singBox !== void 0) {
2327
+ exactDefinition(input.singBox, ["mode", "listener"]);
2328
+ if (!["fragment", "standalone"].includes(input.singBox.mode)) fail("INVALID_PROFILE_DEFINITION");
2329
+ if (input.singBox.listener !== void 0) exactDefinition(input.singBox.listener, ["port", "resolver"]);
2330
+ }
2331
+ if (!Array.isArray(input.nodes) || !Array.isArray(input.groups) || !Array.isArray(input.routes) || input.endpoints !== void 0 && !Array.isArray(input.endpoints)) fail("INVALID_PROFILE_DEFINITION");
2332
+ return snapshotProfile(input);
2333
+ }
2334
+ function surgeCondition$1(condition, depth = 0) {
2335
+ if (depth > 10) return fail("LOGICAL_DEPTH_EXCEEDED");
2336
+ if (condition.type === "nativeRuleSet" || condition.type === "ruleSet" && "when" in condition) {
2337
+ const parsed = matchSchema.safeParse(condition);
2338
+ if (!parsed.success) return fail("PROFILE_CONDITION_UNSUPPORTED");
2339
+ const value = parsed.data;
2340
+ if (value.type === "ruleSet") return surgeCondition$1(value.when, depth);
2341
+ if (value.type !== "nativeRuleSet" || value.engine !== "surge" || value.intervalSeconds !== void 0) return fail("PROFILE_CONDITION_UNSUPPORTED");
2342
+ return {
2343
+ type: "ruleSet",
2344
+ format: value.format,
2345
+ url: value.url
2346
+ };
2347
+ }
2348
+ if (condition.type === "all" || condition.type === "any") {
2349
+ if (!Array.isArray(condition.conditions)) return fail("PROFILE_CONDITION_UNSUPPORTED");
2350
+ if (condition.conditions.length === 1) {
2351
+ exactDefinition(condition, ["type", "conditions"]);
2352
+ return surgeCondition$1(condition.conditions[0], depth + 1);
2353
+ }
2354
+ return {
2355
+ ...condition,
2356
+ conditions: condition.conditions.map((child) => surgeCondition$1(child, depth + 1))
2357
+ };
2358
+ }
2359
+ if (condition.type === "not") return {
2360
+ ...condition,
2361
+ condition: surgeCondition$1(condition.condition, depth + 1)
2218
2362
  };
2219
- const root = resolve(output);
2220
- if (compilation.plans.some((plan) => plan.program.endpoints?.some((endpoint) => pathsOverlap(root, endpoint.stateDirectory)))) return {
2221
- published: false,
2222
- exitCode: 1,
2223
- code: "ENDPOINT_STATE_OVERLAP"
2363
+ if (condition.type === "ipCidr" && isIP(condition.value.split("/")[0]) === 6) return {
2364
+ ...condition,
2365
+ type: "ipCidr6"
2224
2366
  };
2225
- const lock = join(root, ".proxylang-lock");
2226
- const id = randomUUID();
2227
- const relativeGeneration = `generations/${id}`;
2228
- const generation = join(root, relativeGeneration);
2229
- const pointer = join(root, `.active-${id}.json`);
2230
- let locked = false;
2231
- let created = false;
2232
- let published = false;
2233
- let code = "BUILD_FAILED";
2234
- let cleanupFailed = false;
2235
- let detail = {};
2367
+ return condition;
2368
+ }
2369
+ /** No secrets or I/O. All engine adaptations retain strict validation. */
2370
+ function compileProfile(input) {
2236
2371
  try {
2237
- await directory(root);
2238
- try {
2239
- await mkdir(lock, { mode: 448 });
2240
- locked = true;
2241
- } catch (error) {
2242
- if (error.code === "EEXIST") return {
2243
- published: false,
2244
- exitCode: 1,
2245
- code: "OUTPUT_LOCKED",
2246
- hint: buildHints.OUTPUT_LOCKED
2372
+ const profile = defineProfile(input);
2373
+ snapshotDefinition(profile.routes.map((route) => route.when));
2374
+ if (profile.target.engine === "surge") {
2375
+ if (profile.singBox !== void 0) fail("PROFILE_EXTENSION_UNSUPPORTED");
2376
+ if (profile.endpoints?.some((endpoint) => endpoint.type === "sing-box-tailscale")) fail("PROFILE_ENDPOINT_UNSUPPORTED");
2377
+ const compilation = compileSurgeProfile(defineSurgeProfile({
2378
+ target: profile.target,
2379
+ ...profile.surge,
2380
+ nodes: profile.nodes,
2381
+ tunnels: profile.endpoints,
2382
+ groups: profile.groups,
2383
+ routes: profile.routes.map((route) => ({
2384
+ ...route,
2385
+ when: surgeCondition$1(route.when)
2386
+ })),
2387
+ fallback: profile.fallback
2388
+ }));
2389
+ return {
2390
+ engine: "surge",
2391
+ ok: compilation.ok,
2392
+ compilation
2393
+ };
2394
+ }
2395
+ if (profile.target.engine !== "sing-box") return fail("PROFILE_TARGET_UNSUPPORTED");
2396
+ if (profile.surge !== void 0) fail("PROFILE_EXTENSION_UNSUPPORTED");
2397
+ if (profile.endpoints?.some((endpoint) => endpoint.type !== "sing-box-tailscale")) fail("PROFILE_ENDPOINT_UNSUPPORTED");
2398
+ const registry = /* @__PURE__ */ new Map();
2399
+ for (const resource of [
2400
+ ...profile.nodes,
2401
+ ...profile.groups,
2402
+ ...profile.endpoints ?? []
2403
+ ]) {
2404
+ if (!resource || typeof resource.id !== "string") fail("INVALID_RESOURCE_DEFINITION");
2405
+ if (registry.has(resource.id)) fail("DUPLICATE_RESOURCE_ID");
2406
+ registry.set(resource.id, resource);
2407
+ }
2408
+ const lower = (destination) => {
2409
+ if (!destination || typeof destination !== "object") return fail("INVALID_DESTINATION");
2410
+ if ("builtin" in destination) {
2411
+ exactDefinition(destination, ["builtin"]);
2412
+ if (destination.builtin === "DIRECT") return { type: "direct" };
2413
+ if (destination.builtin === "REJECT") return { type: "reject" };
2414
+ return fail("PROFILE_DESTINATION_UNSUPPORTED");
2415
+ }
2416
+ if (registry.get(destination.id) !== destination) fail("UNREGISTERED_DESTINATION_INSTANCE");
2417
+ return {
2418
+ type: "route",
2419
+ to: destination.id
2420
+ };
2421
+ };
2422
+ const groups = profile.groups.map((definition) => {
2423
+ exactDefinition(definition, [
2424
+ "type",
2425
+ "id",
2426
+ "name",
2427
+ "algorithm",
2428
+ "members",
2429
+ "url",
2430
+ "intervalSeconds",
2431
+ "timeoutSeconds"
2432
+ ]);
2433
+ if (definition.type !== "proxy-group" || typeof definition.name !== "string" || !definition.name.trim()) fail("INVALID_GROUP_DEFINITION");
2434
+ if (definition.url !== void 0 || definition.intervalSeconds !== void 0 || definition.timeoutSeconds !== void 0) fail("PROFILE_GROUP_OPTIONS_UNSUPPORTED");
2435
+ exactDefinition(definition.algorithm, definition.algorithm.type === "urltest" ? [
2436
+ "type",
2437
+ "url",
2438
+ "intervalSeconds",
2439
+ "toleranceMs"
2440
+ ] : ["type"]);
2441
+ const members = definition.members.map((member) => {
2442
+ const action = lower(member);
2443
+ if (action.type !== "route") return fail("PROFILE_GROUP_MEMBER_UNSUPPORTED");
2444
+ return action.to;
2445
+ });
2446
+ return {
2447
+ ...definition.algorithm,
2448
+ id: definition.id,
2449
+ members
2247
2450
  };
2248
- throw error;
2249
- }
2250
- const artifacts = render(compilation, resolveSecret);
2251
- await directory(join(root, "generations"));
2252
- await mkdir(generation, { mode: 448 });
2253
- created = true;
2254
- for (const artifact of artifacts) await writeFile(join(generation, artifact.filename), artifact.content, {
2255
- encoding: "utf8",
2256
- mode: 384,
2257
- flag: "wx"
2258
2451
  });
2259
- const manifest = {
2260
- schemaVersion: 1,
2261
- targets: compilation.plans.map((plan) => ({
2262
- target: plan.target,
2263
- sourceMap: plan.sourceMap,
2264
- strategySelections: plan.strategySelections,
2265
- preconditions: plan.preconditions,
2266
- nativeValidation: plan.nativeValidation
2267
- })),
2268
- diagnostics: compilation.diagnostics,
2269
- cases: compilation.cases,
2270
- artifacts: artifacts.map((artifact) => ({
2271
- target: artifact.target,
2272
- filename: artifact.filename
2273
- }))
2274
- };
2275
- await writeFile(join(generation, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n", {
2276
- mode: 384,
2277
- flag: "wx"
2452
+ const routing = profile.routes.map((route, index) => {
2453
+ exactDefinition(route, [
2454
+ "type",
2455
+ "when",
2456
+ "to"
2457
+ ]);
2458
+ if (route.type !== "route") fail("INVALID_ROUTE_DEFINITION");
2459
+ return {
2460
+ type: "rule",
2461
+ id: `route-${index + 1}`,
2462
+ when: route.when,
2463
+ then: lower(route.to)
2464
+ };
2278
2465
  });
2279
- const active = {
2280
- schemaVersion: 1,
2281
- generation: relativeGeneration,
2282
- manifest: `${relativeGeneration}/manifest.json`,
2283
- artifacts: Object.fromEntries(artifacts.map((artifact) => [artifact.target, `${relativeGeneration}/${artifact.filename}`]))
2466
+ const compilation = compile(snapshotDefinition({
2467
+ programs: { profile: {
2468
+ engine: "sing-box",
2469
+ nodes: profile.nodes,
2470
+ endpoints: profile.endpoints,
2471
+ groups,
2472
+ routing,
2473
+ fallback: lower(profile.fallback),
2474
+ ...profile.singBox?.listener ? { listener: profile.singBox.listener } : {}
2475
+ } },
2476
+ targets: [{
2477
+ ...profile.target,
2478
+ id: "profile",
2479
+ program: "profile",
2480
+ mode: profile.singBox?.mode ?? "fragment"
2481
+ }]
2482
+ }));
2483
+ return {
2484
+ engine: "sing-box",
2485
+ ok: compilation.ok,
2486
+ compilation
2284
2487
  };
2285
- await writeFile(pointer, JSON.stringify(active, null, 2) + "\n", {
2286
- mode: 384,
2287
- flag: "wx"
2288
- });
2289
- await rename(pointer, join(root, "active.json"));
2290
- published = true;
2291
- code = "PUBLISHED";
2292
2488
  } catch (error) {
2293
- code = error instanceof RenderError ? error.code : "OUTPUT_FAILED";
2294
- detail = error instanceof RenderError ? { hint: buildHints[code] } : outputFailure(error);
2295
- } finally {
2296
- if (locked) {
2297
- try {
2298
- await rm(pointer, { force: true });
2299
- } catch {
2300
- cleanupFailed = true;
2301
- }
2302
- if (created && !published) try {
2303
- await rm(generation, { recursive: true });
2304
- } catch {
2305
- cleanupFailed = true;
2306
- }
2307
- try {
2308
- await rm(lock, { recursive: true });
2309
- } catch {
2310
- cleanupFailed = true;
2311
- }
2312
- }
2489
+ return {
2490
+ engine: "invalid",
2491
+ ok: false,
2492
+ code: error instanceof ProfileDefinitionError ? error.code : "INVALID_PROFILE_DEFINITION"
2493
+ };
2313
2494
  }
2314
- const resultCode = cleanupFailed ? published ? "PUBLISHED_CLEANUP_FAILED" : "FAILED_CLEANUP_REQUIRED" : code;
2315
- return {
2316
- published,
2317
- exitCode: published ? cleanupFailed ? 2 : 0 : 1,
2318
- code: resultCode,
2319
- ...detail,
2320
- ...buildHints[resultCode] ? { hint: buildHints[resultCode] } : {},
2321
- ...published ? {
2322
- active: join(root, "active.json"),
2323
- generation
2324
- } : {}
2325
- };
2326
2495
  }
2327
2496
  //#endregion
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;
2497
+ //#region src/proxy-builder.ts
2498
+ /** Fluent construction is separate from the plain-data node consumed by the compiler. */
2499
+ function proxyBuilder(node) {
2500
+ assertData(node);
2501
+ const copy = deepFreeze(structuredClone(node));
2502
+ const fork = (patch) => proxyBuilder({
2503
+ ...copy,
2504
+ ...patch
2505
+ });
2506
+ return Object.freeze({
2507
+ via: (id) => fork({ via: id }),
2508
+ label: (text) => fork({ label: text }),
2509
+ tcpFastOpen: (enabled) => fork({ tcpFastOpen: enabled }),
2510
+ build: () => deepFreeze(structuredClone(copy))
2511
+ });
2360
2512
  }
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
2513
+ //#endregion
2514
+ //#region src/dsl.ts
2515
+ const ruleSet = (definition) => ({
2516
+ ...definition,
2517
+ type: "ruleSet"
2518
+ });
2519
+ const match = {
2520
+ ruleSet: (set) => set,
2521
+ domain: (value) => ({
2522
+ type: "domain",
2523
+ value
2494
2524
  }),
2495
- z.strictObject({
2496
- type: z.enum(["all", "any"]),
2497
- conditions: z.array(conditionSchema).min(2).max(100),
2498
- ...options
2525
+ domainSuffix: (value) => ({
2526
+ type: "domainSuffix",
2527
+ value
2499
2528
  }),
2500
- z.strictObject({
2501
- type: z.literal("not"),
2502
- condition: conditionSchema,
2503
- ...options
2529
+ ipCidr: (value) => ({
2530
+ type: "ipCidr",
2531
+ value
2504
2532
  }),
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()
2533
+ sourceIp: (value) => ({
2534
+ type: "sourceIp",
2535
+ value
2524
2536
  }),
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
+ port: (from, to = from) => ({
2538
+ type: "port",
2539
+ from,
2540
+ to
2541
+ }),
2542
+ sourcePort: (from, to = from) => ({
2543
+ type: "sourcePort",
2544
+ from,
2545
+ to
2546
+ }),
2547
+ network: (value) => ({
2548
+ type: "network",
2549
+ value
2550
+ }),
2551
+ all: (...conditions) => ({
2552
+ type: "all",
2553
+ conditions
2554
+ }),
2555
+ any: (...conditions) => ({
2556
+ type: "any",
2557
+ conditions
2558
+ }),
2559
+ not: (condition) => ({
2560
+ type: "not",
2561
+ condition
2562
+ })
2563
+ };
2564
+ const direct = () => ({ type: "direct" });
2565
+ const reject = () => ({ type: "reject" });
2566
+ const route = (to) => ({
2567
+ type: "route",
2568
+ to
2537
2569
  });
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: []
2570
+ /** An exit parameter declared by policy.exits and resolved by use.bindings. */
2571
+ const slot = (name) => ({
2572
+ type: "slot",
2573
+ name
2574
+ });
2575
+ const secret = (name) => ({
2576
+ type: "env",
2577
+ name
2578
+ });
2579
+ const rule = (id, when, then) => ({
2580
+ type: "rule",
2581
+ id,
2582
+ when,
2583
+ then
2584
+ });
2585
+ const block = (id, rules, when) => ({
2586
+ type: "block",
2587
+ id,
2588
+ rules,
2589
+ ...when ? { when } : {}
2590
+ });
2591
+ const policy = (definition) => ({
2592
+ type: "policy",
2593
+ ...definition
2594
+ });
2595
+ const use = (definition, options) => ({
2596
+ type: "use",
2597
+ id: options.id,
2598
+ policy: definition,
2599
+ bindings: options.bindings
2600
+ });
2601
+ const sequence = (...parts) => parts.flatMap((part) => Array.isArray(part) ? part : [part]);
2602
+ const defineConfig = (config) => config;
2603
+ /** Filtering is stable: catalogue order determines initial selector order. */
2604
+ function selectNodes(nodes, query = {}) {
2605
+ return nodes.filter((node) => (!query.regions || node.region !== void 0 && query.regions.includes(node.region)) && (!query.providers || node.provider !== void 0 && query.providers.includes(node.provider)) && (!query.tags || query.tags.every((tag) => node.tags?.includes(tag)))).map((node) => node.id);
2606
+ }
2607
+ /** A shared strategy declares an algorithm or explicitly selects native implementations. */
2608
+ const strategy = (definition) => ({
2609
+ type: "strategy",
2610
+ ...definition
2611
+ });
2612
+ const group = {
2613
+ auto: () => ({ type: "auto" }),
2614
+ select: () => ({ type: "select" }),
2615
+ urltest: (options) => ({
2616
+ type: "urltest",
2617
+ ...options
2618
+ })
2619
+ };
2620
+ const surge$1 = {
2621
+ config: surgeConfig,
2622
+ match: surgeMatch,
2623
+ smart: () => ({ type: "surge-smart" }),
2624
+ ruleSet: (options) => ({
2625
+ format: "rule-set",
2626
+ ...options,
2627
+ type: "nativeRuleSet",
2628
+ engine: "surge"
2629
+ })
2630
+ };
2631
+ const mihomo = { ruleProvider: (options) => ({
2632
+ ...options,
2633
+ type: "nativeRuleSet",
2634
+ engine: "mihomo"
2635
+ }) };
2636
+ /** Protocol constructors keep credentials and options specific to their protocol. */
2637
+ function nodeConstructor(type) {
2638
+ return (options) => ({
2639
+ ...options,
2640
+ type
2552
2641
  });
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);
2642
+ }
2643
+ const proxy = {
2644
+ builder: proxyBuilder,
2645
+ http: nodeConstructor("http"),
2646
+ trojan: nodeConstructor("trojan"),
2647
+ anytls: nodeConstructor("anytls"),
2648
+ shadowsocks: nodeConstructor("shadowsocks"),
2649
+ vmess: nodeConstructor("vmess"),
2650
+ vless: nodeConstructor("vless")
2651
+ };
2652
+ const singbox$1 = {
2653
+ ruleSet: (options) => ({
2654
+ ...options,
2655
+ type: "nativeRuleSet",
2656
+ engine: "sing-box"
2657
+ }),
2658
+ tailscale: (options) => ({
2659
+ ...options,
2660
+ type: "sing-box-tailscale"
2661
+ })
2662
+ };
2663
+ //#endregion
2664
+ //#region src/render.ts
2665
+ const DIRECT = "pl-direct";
2666
+ const DNS = "pl-dns";
2667
+ const actionTag = (action) => action.type === "route" ? action.to : action.type === "direct" ? DIRECT : "pl-reject";
2668
+ /** Secret resolution is once per token per batch, including across providers. */
2669
+ function render(compilation, resolveSecret) {
2670
+ if (!compilation.ok) throw new RenderError("COMPILATION_FAILED");
2671
+ const secret = secretReader(resolveSecret);
2672
+ return compilation.plans.map((plan) => ({
2673
+ target: plan.target.id,
2674
+ filename: `${plan.target.id}.${plan.target.engine === "surge" ? "conf" : plan.target.engine === "sing-box" ? "json" : "yaml"}`,
2675
+ content: plan.target.engine === "surge" ? surge(plan, secret) : plan.target.engine === "sing-box" ? JSON.stringify(singbox(plan, secret), null, 2) + "\n" : stringify(clashConfig(plan, secret))
2676
+ }));
2677
+ }
2678
+ function singCondition(condition) {
2679
+ switch (condition.type) {
2680
+ case "ruleSet": return singCondition(condition.when);
2681
+ case "nativeRuleSet": return { rule_set: [condition.id] };
2682
+ case "all":
2683
+ case "any": return {
2684
+ type: "logical",
2685
+ mode: condition.type === "all" ? "and" : "or",
2686
+ rules: condition.conditions.map(singCondition)
2687
+ };
2688
+ case "not": return {
2689
+ type: "logical",
2690
+ mode: "and",
2691
+ rules: [singCondition(condition.condition)],
2692
+ invert: true
2693
+ };
2694
+ case "domain": return { domain: [condition.value] };
2695
+ case "domainSuffix": return { domain_suffix: [condition.value] };
2696
+ case "ipCidr": return { ip_cidr: [condition.value] };
2697
+ case "sourceIp": return { source_ip_cidr: [condition.value] };
2698
+ case "network": return { network: [condition.value] };
2699
+ case "port":
2700
+ case "sourcePort": {
2701
+ const key = condition.type === "port" ? "port" : "source_port";
2702
+ return condition.from === condition.to ? { [key]: [condition.from] } : { [`${key}_range`]: [`${condition.from}:${condition.to}`] };
2617
2703
  }
2618
2704
  }
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);
2705
+ }
2706
+ function singAction(action) {
2707
+ return action.type === "reject" ? {
2708
+ action: "reject",
2709
+ method: "default",
2710
+ no_drop: true
2711
+ } : {
2712
+ action: "route",
2713
+ outbound: actionTag(action)
2630
2714
  };
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
- }
2715
+ }
2716
+ function singbox(plan, secret) {
2717
+ const { program, target } = plan;
2718
+ const modern = target.version === "1.12.0";
2719
+ const standalone = target.mode === "standalone";
2720
+ const outbounds = [{
2721
+ type: "direct",
2722
+ tag: DIRECT,
2723
+ ...!modern && standalone ? { domain_strategy: "prefer_ipv4" } : {}
2724
+ }];
2725
+ for (const node of program.nodes) outbounds.push(singboxProxy(node, secret));
2726
+ for (const group of program.groups) outbounds.push(singboxGroup(group));
2727
+ const rules = plan.rules.map((rule) => ({
2728
+ ...singCondition(rule.when),
2729
+ ...singAction(rule.then)
2730
+ }));
2731
+ const routing = { rules };
2732
+ if (plan.nativeRuleSets.length) routing.rule_set = plan.nativeRuleSets.map((r) => ({
2733
+ type: "remote",
2734
+ tag: r.id,
2735
+ url: r.url,
2736
+ format: r.format,
2737
+ update_interval: `${r.intervalSeconds}s`,
2738
+ download_detour: DIRECT
2739
+ }));
2740
+ if (program.fallback.type === "reject") rules.push(singAction(program.fallback));
2741
+ else routing.final = actionTag(program.fallback);
2742
+ const config = {
2743
+ log: { level: "warn" },
2744
+ outbounds,
2745
+ route: routing
2658
2746
  };
2659
- for (const rule of p.rules) {
2660
- checkPolicy(rule.then);
2661
- checkCondition(rule.when, 0);
2747
+ if (standalone) {
2748
+ const listener = program.listener;
2749
+ config.inbounds = [{
2750
+ type: "mixed",
2751
+ tag: "pl-listener",
2752
+ listen: "127.0.0.1",
2753
+ listen_port: listener.port
2754
+ }];
2755
+ config.dns = {
2756
+ servers: [modern ? {
2757
+ type: "udp",
2758
+ tag: DNS,
2759
+ server: listener.resolver,
2760
+ server_port: 53,
2761
+ detour: DIRECT
2762
+ } : {
2763
+ tag: DNS,
2764
+ address: `udp://${isIP(listener.resolver) === 6 ? `[${listener.resolver}]` : listener.resolver}`,
2765
+ detour: DIRECT
2766
+ }],
2767
+ final: DNS,
2768
+ strategy: "prefer_ipv4"
2769
+ };
2770
+ if (modern) routing.default_domain_resolver = {
2771
+ server: DNS,
2772
+ strategy: "prefer_ipv4"
2773
+ };
2662
2774
  }
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;
2775
+ if (program.endpoints?.length) {
2776
+ config.endpoints = program.endpoints.map((endpoint) => ({
2777
+ type: "tailscale",
2778
+ tag: endpoint.id,
2779
+ hostname: endpoint.hostname,
2780
+ state_directory: endpoint.stateDirectory,
2781
+ accept_routes: endpoint.acceptRoutes,
2782
+ domain_resolver: { server: `pl-ts-dns-${endpoint.id}` },
2783
+ ...endpoint.authKey ? { auth_key: secret(endpoint.authKey) } : {},
2784
+ ...endpoint.exitNode ? { exit_node: endpoint.exitNode } : {},
2785
+ ...endpoint.exitNodeAllowLanAccess !== void 0 ? { exit_node_allow_lan_access: endpoint.exitNodeAllowLanAccess } : {}
2786
+ }));
2787
+ const dns = config.dns;
2788
+ for (const endpoint of program.endpoints) dns.servers.push({
2789
+ type: "udp",
2790
+ tag: `pl-ts-dns-${endpoint.id}`,
2791
+ server: endpoint.bootstrapResolver,
2792
+ server_port: 53,
2793
+ detour: DIRECT
2794
+ });
2795
+ }
2796
+ return config;
2679
2797
  }
2680
- function conditionOptions(c) {
2681
- return [...c.noResolve ? ["no-resolve"] : [], ...c.extendedMatching ? ["extended-matching"] : []];
2798
+ function surgeCondition(condition) {
2799
+ switch (condition.type) {
2800
+ case "ruleSet": return surgeCondition(condition.when);
2801
+ case "nativeRuleSet": return `${condition.format === "domain-set" ? "DOMAIN-SET" : "RULE-SET"},${condition.url}`;
2802
+ case "all":
2803
+ case "any": return `${condition.type === "all" ? "AND" : "OR"},(${condition.conditions.map((c) => `(${surgeCondition(c)})`).join(",")})`;
2804
+ case "not": return `NOT,((${surgeCondition(condition.condition)}))`;
2805
+ case "domain": return `DOMAIN,${condition.value}`;
2806
+ case "domainSuffix": return `DOMAIN-SUFFIX,${condition.value}`;
2807
+ case "ipCidr": return `${condition.value.includes(":") ? "IP-CIDR6" : "IP-CIDR"},${condition.value},no-resolve`;
2808
+ case "sourceIp": return `SRC-IP,${condition.value}`;
2809
+ case "network": return `PROTOCOL,${condition.value.toUpperCase()}`;
2810
+ case "port":
2811
+ case "sourcePort": return `${condition.type === "port" ? "DEST-PORT" : "SRC-PORT"},${condition.from === condition.to ? condition.from : `${condition.from}-${condition.to}`}`;
2812
+ }
2813
+ }
2814
+ function surge(plan, secret) {
2815
+ const policy = (action) => action.type === "route" ? action.to : action.type === "direct" ? "DIRECT" : "REJECT";
2816
+ const lines = ["# Generated by proxylang; see manifest for source mapping and preconditions."];
2817
+ if (plan.target.mode === "standalone") lines.push("[General]", "loglevel = warning", "allow-wifi-access = false", `http-listen = 127.0.0.1:${plan.program.listener.port}`, `dns-server = ${plan.program.listener.resolver}`, "");
2818
+ lines.push("[Proxy]");
2819
+ for (const node of plan.program.nodes) lines.push(surgeProxy(node, secret));
2820
+ lines.push("", "[Proxy Group]");
2821
+ for (const group of plan.program.groups) lines.push(surgeGroup(group));
2822
+ lines.push("", "[Rule]");
2823
+ for (const rule of plan.rules) {
2824
+ lines.push(`# ${rule.id}`);
2825
+ if (rule.when.type === "ipCidr") {
2826
+ const condition = surgeCondition(rule.when).replace(/,no-resolve$/, "");
2827
+ lines.push(`${condition},${policy(rule.then)},no-resolve`);
2828
+ } else lines.push(`${surgeCondition(rule.when)},${policy(rule.then)}${rule.when.type === "nativeRuleSet" && rule.when.intervalSeconds !== void 0 ? `,update-interval=${rule.when.intervalSeconds}` : ""}`);
2829
+ }
2830
+ lines.push(`FINAL,${policy(plan.program.fallback)}`);
2831
+ return lines.join("\n") + "\n";
2832
+ }
2833
+ //#endregion
2834
+ //#region src/host.ts
2835
+ const buildHints = {
2836
+ INVALID_OUTPUT_DIRECTORY: "提供非空输出目录路径",
2837
+ OUTPUT_LOCKED: "确认没有构建正在运行;检查并处理遗留锁后重试,不要删除仍在使用的锁",
2838
+ SECRET_MISSING: "在构建环境提供配置引用的非空秘密变量",
2839
+ SECRET_RESOLUTION_FAILED: "检查秘密解析器;原始异常不会进入构建报告",
2840
+ PUBLISHED_CLEANUP_FAILED: "活动指针已经切换;检查残留锁和临时文件,不要假设发布失败",
2841
+ FAILED_CLEANUP_REQUIRED: "旧活动指针保留;检查本次残留产物和锁后重试"
2842
+ };
2843
+ function outputFailure(error) {
2844
+ const code = error && typeof error === "object" ? Object.getOwnPropertyDescriptor(error, "code")?.value : void 0;
2845
+ if (code === "EACCES" || code === "EPERM") return {
2846
+ reason: "ACCESS_DENIED",
2847
+ hint: "检查输出目录的写入和遍历权限"
2848
+ };
2849
+ if (code === "ENOSPC" || code === "EDQUOT") return {
2850
+ reason: "NO_SPACE",
2851
+ hint: "释放磁盘空间或调整存储配额后重试"
2852
+ };
2853
+ if (code === "EROFS") return {
2854
+ reason: "READ_ONLY",
2855
+ hint: "选择可写的本地输出目录"
2856
+ };
2857
+ if ([
2858
+ "ENOTDIR",
2859
+ "EISDIR",
2860
+ "EEXIST",
2861
+ "UNSAFE_DIRECTORY"
2862
+ ].includes(code)) return {
2863
+ reason: "INVALID_DIRECTORY",
2864
+ hint: "检查输出根、generations 和 active.json 的文件类型;输出目录不能是符号链接"
2865
+ };
2866
+ return {
2867
+ reason: "IO_ERROR",
2868
+ hint: "检查输出目录及文件系统状态,旧活动配置在发布前失败时保持不变"
2869
+ };
2682
2870
  }
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
- }
2871
+ async function directory(path) {
2872
+ await mkdir(path, {
2873
+ recursive: true,
2874
+ mode: 448
2875
+ });
2876
+ const stat = await lstat(path);
2877
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw Object.assign(/* @__PURE__ */ new Error("UNSAFE_DIRECTORY"), { code: "UNSAFE_DIRECTORY" });
2702
2878
  }
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;
2879
+ /** All targets publish together by one active.json rename. Config files never go to stdout. */
2880
+ async function buildToDirectory(compilation, output, resolveSecret = (token) => process.env[token.name]) {
2881
+ if (!compilation.ok) return {
2882
+ published: false,
2883
+ exitCode: 1,
2884
+ code: "COMPILATION_FAILED"
2712
2885
  };
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(", ")})`);
2886
+ if (typeof output !== "string" || !output.trim()) return {
2887
+ published: false,
2888
+ exitCode: 1,
2889
+ code: "INVALID_OUTPUT_DIRECTORY",
2890
+ hint: buildHints.INVALID_OUTPUT_DIRECTORY
2891
+ };
2892
+ const root = resolve(output);
2893
+ if (compilation.plans.some((plan) => plan.program.endpoints?.some((endpoint) => pathsOverlap(root, endpoint.stateDirectory)))) return {
2894
+ published: false,
2895
+ exitCode: 1,
2896
+ code: "ENDPOINT_STATE_OVERLAP"
2897
+ };
2898
+ const lock = join(root, ".proxylang-lock");
2899
+ const id = randomUUID();
2900
+ const relativeGeneration = `generations/${id}`;
2901
+ const generation = join(root, relativeGeneration);
2902
+ const pointer = join(root, `.active-${id}.json`);
2903
+ let locked = false;
2904
+ let created = false;
2905
+ let published = false;
2906
+ let code = "BUILD_FAILED";
2907
+ let cleanupFailed = false;
2908
+ let detail = {};
2909
+ try {
2910
+ await directory(root);
2911
+ try {
2912
+ await mkdir(lock, { mode: 448 });
2913
+ locked = true;
2914
+ } catch (error) {
2915
+ if (error.code === "EEXIST") return {
2916
+ published: false,
2917
+ exitCode: 1,
2918
+ code: "OUTPUT_LOCKED",
2919
+ hint: buildHints.OUTPUT_LOCKED
2920
+ };
2921
+ throw error;
2922
+ }
2923
+ const artifacts = render(compilation, resolveSecret);
2924
+ await directory(join(root, "generations"));
2925
+ await mkdir(generation, { mode: 448 });
2926
+ created = true;
2927
+ for (const artifact of artifacts) await writeFile(join(generation, artifact.filename), artifact.content, {
2928
+ encoding: "utf8",
2929
+ mode: 384,
2930
+ flag: "wx"
2931
+ });
2932
+ const manifest = {
2933
+ schemaVersion: 1,
2934
+ targets: compilation.plans.map((plan) => ({
2935
+ target: plan.target,
2936
+ sourceMap: plan.sourceMap,
2937
+ strategySelections: plan.strategySelections,
2938
+ preconditions: plan.preconditions,
2939
+ nativeValidation: plan.nativeValidation
2940
+ })),
2941
+ diagnostics: compilation.diagnostics,
2942
+ cases: compilation.cases,
2943
+ artifacts: artifacts.map((artifact) => ({
2944
+ target: artifact.target,
2945
+ filename: artifact.filename
2946
+ }))
2947
+ };
2948
+ await writeFile(join(generation, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n", {
2949
+ mode: 384,
2950
+ flag: "wx"
2951
+ });
2952
+ const active = {
2953
+ schemaVersion: 1,
2954
+ generation: relativeGeneration,
2955
+ manifest: `${relativeGeneration}/manifest.json`,
2956
+ artifacts: Object.fromEntries(artifacts.map((artifact) => [artifact.target, `${relativeGeneration}/${artifact.filename}`]))
2957
+ };
2958
+ await writeFile(pointer, JSON.stringify(active, null, 2) + "\n", {
2959
+ mode: 384,
2960
+ flag: "wx"
2961
+ });
2962
+ await rename(pointer, join(root, "active.json"));
2963
+ published = true;
2964
+ code = "PUBLISHED";
2965
+ } catch (error) {
2966
+ code = error instanceof RenderError ? error.code : "OUTPUT_FAILED";
2967
+ detail = error instanceof RenderError ? { hint: buildHints[code] } : outputFailure(error);
2968
+ } finally {
2969
+ if (locked) {
2970
+ try {
2971
+ await rm(pointer, { force: true });
2972
+ } catch {
2973
+ cleanupFailed = true;
2974
+ }
2975
+ if (created && !published) try {
2976
+ await rm(generation, { recursive: true });
2977
+ } catch {
2978
+ cleanupFailed = true;
2979
+ }
2980
+ try {
2981
+ await rm(lock, { recursive: true });
2982
+ } catch {
2983
+ cleanupFailed = true;
2746
2984
  }
2747
2985
  }
2748
2986
  }
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)));
2987
+ const resultCode = cleanupFailed ? published ? "PUBLISHED_CLEANUP_FAILED" : "FAILED_CLEANUP_REQUIRED" : code;
2988
+ return {
2989
+ published,
2990
+ exitCode: published ? cleanupFailed ? 2 : 0 : 1,
2991
+ code: resultCode,
2992
+ ...detail,
2993
+ ...buildHints[resultCode] ? { hint: buildHints[resultCode] } : {},
2994
+ ...published ? {
2995
+ active: join(root, "active.json"),
2996
+ generation
2997
+ } : {}
2998
+ };
2776
2999
  }
2777
3000
  //#endregion
2778
3001
  //#region src/surge-publish.ts
@@ -2784,7 +3007,7 @@ var SurgePublishError = class extends Error {
2784
3007
  }
2785
3008
  };
2786
3009
  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");
3010
+ if (!files.size || files.size > 16 || [...files.keys()].some((name) => !/^[a-z0-9][a-z0-9-]*\.(?:conf|json)$/.test(name))) throw new Error("INVALID_PROFILE_FILENAMES");
2788
3011
  const root = resolve(surgeDirectory);
2789
3012
  const generations = join(root, ".generations");
2790
3013
  const id = randomUUID();
@@ -2916,7 +3139,7 @@ async function buildSurgeProfilesToDirectory(profiles, output, resolveSecret = (
2916
3139
  }
2917
3140
  }
2918
3141
  //#endregion
2919
- //#region src/surge-build.ts
3142
+ //#region src/build-core.ts
2920
3143
  function record(value, keys) {
2921
3144
  if (!value || typeof value !== "object" || Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
2922
3145
  for (const key of Reflect.ownKeys(value)) {
@@ -2925,7 +3148,7 @@ function record(value, keys) {
2925
3148
  }
2926
3149
  }
2927
3150
  /** Capture data and callback references before application preflight can change its source. */
2928
- function defineSurgeBuild(input) {
3151
+ function captureBuild(input, snapshot) {
2929
3152
  try {
2930
3153
  record(input, [
2931
3154
  "profiles",
@@ -2935,7 +3158,7 @@ function defineSurgeBuild(input) {
2935
3158
  record(input.profiles);
2936
3159
  for (const callback of [input.preflight, input.resolveSecret]) if (callback !== void 0 && typeof callback !== "function") throw new Error();
2937
3160
  return Object.freeze({
2938
- profiles: deepFreeze(snapshotDefinition(input.profiles)),
3161
+ profiles: deepFreeze(snapshot(input.profiles)),
2939
3162
  ...input.preflight === void 0 ? {} : { preflight: input.preflight },
2940
3163
  ...input.resolveSecret === void 0 ? {} : { resolveSecret: input.resolveSecret }
2941
3164
  });
@@ -2943,7 +3166,7 @@ function defineSurgeBuild(input) {
2943
3166
  throw new ProfileDefinitionError("INVALID_BUILD_DEFINITION");
2944
3167
  }
2945
3168
  }
2946
- function surgeBuildFailure(code, validation = false, profileCount = 0) {
3169
+ function profileBuildFailure(code, validation = false, profileCount = 0) {
2947
3170
  return {
2948
3171
  published: false,
2949
3172
  exitCode: 1,
@@ -2954,23 +3177,23 @@ function surgeBuildFailure(code, validation = false, profileCount = 0) {
2954
3177
  };
2955
3178
  }
2956
3179
  /** Pure orchestration result; the CLI owns stdout and process exit status. */
2957
- async function runSurgeBuild(input, output, options = {}) {
3180
+ async function executeBuild(input, output, options, capture, publish) {
2958
3181
  let validation;
2959
3182
  try {
2960
3183
  record(options, ["validation"]);
2961
3184
  if (options.validation !== void 0 && typeof options.validation !== "boolean") throw new Error();
2962
3185
  validation = options.validation ?? false;
2963
3186
  } catch {
2964
- return surgeBuildFailure("INVALID_BUILD_OPTIONS");
3187
+ return profileBuildFailure("INVALID_BUILD_OPTIONS");
2965
3188
  }
2966
3189
  let definition;
2967
3190
  try {
2968
- definition = defineSurgeBuild(input);
3191
+ definition = capture(input);
2969
3192
  } catch {
2970
- return surgeBuildFailure("INVALID_BUILD_DEFINITION", validation);
3193
+ return profileBuildFailure("INVALID_BUILD_DEFINITION", validation);
2971
3194
  }
2972
3195
  const profileCount = Object.keys(definition.profiles).length;
2973
- const failure = (code) => surgeBuildFailure(code, validation, profileCount);
3196
+ const failure = (code) => profileBuildFailure(code, validation, profileCount);
2974
3197
  if (typeof output !== "string" || !output.trim()) return failure("INVALID_OUTPUT_DIRECTORY");
2975
3198
  if (validation && !definition.resolveSecret) return failure("VALIDATION_RESOLVER_REQUIRED");
2976
3199
  let codes;
@@ -2990,11 +3213,77 @@ async function runSurgeBuild(input, output, options = {}) {
2990
3213
  const context = Object.freeze({ validation });
2991
3214
  const resolver = definition.resolveSecret;
2992
3215
  return {
2993
- ...await buildSurgeProfilesToDirectory(definition.profiles, output, resolver ? (token) => resolver(token, context) : (token) => process.env[token.name]),
3216
+ ...await publish(definition.profiles, output, resolver ? (token) => resolver(token, context) : (token) => process.env[token.name]),
2994
3217
  warnings,
2995
3218
  validation,
2996
3219
  profileCount
2997
3220
  };
2998
3221
  }
2999
3222
  //#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 };
3223
+ //#region src/surge-build.ts
3224
+ const surgeBuildFailure = profileBuildFailure;
3225
+ function defineSurgeBuild(input) {
3226
+ return captureBuild(input, snapshotDefinition);
3227
+ }
3228
+ function runSurgeBuild(input, output, options = {}) {
3229
+ return executeBuild(input, output, options, defineSurgeBuild, buildSurgeProfilesToDirectory);
3230
+ }
3231
+ //#endregion
3232
+ //#region src/profile-build.ts
3233
+ function defineBuild(input) {
3234
+ return captureBuild(input, snapshotProfile);
3235
+ }
3236
+ async function publish(profiles, output, resolver) {
3237
+ try {
3238
+ const entries = Object.entries(profiles);
3239
+ if (!entries.length || entries.length > 16 || entries.some(([id]) => !/^[a-z0-9][a-z0-9-]*$/.test(id))) return {
3240
+ published: false,
3241
+ exitCode: 1,
3242
+ code: "INVALID_PROFILE_FILENAMES"
3243
+ };
3244
+ const compiled = entries.map(([, profile]) => compileProfile(profile));
3245
+ const invalid = compiled.find((profile) => !profile.ok);
3246
+ if (invalid) return {
3247
+ published: false,
3248
+ exitCode: 1,
3249
+ code: invalid.engine === "invalid" ? invalid.code : "COMPILATION_FAILED"
3250
+ };
3251
+ if (compiled.some((profile) => profile.engine === "sing-box" && profile.compilation.plans.some((plan) => plan.program.endpoints?.some((endpoint) => pathsOverlap(resolve(output), endpoint.stateDirectory))))) return {
3252
+ published: false,
3253
+ exitCode: 1,
3254
+ code: "ENDPOINT_STATE_OVERLAP"
3255
+ };
3256
+ const read = secretReader(resolver);
3257
+ const files = /* @__PURE__ */ new Map();
3258
+ for (const [index, profile] of compiled.entries()) {
3259
+ if (profile.engine === "invalid") throw new Error();
3260
+ const artifacts = profile.engine === "surge" ? renderSurgeProfiles([profile.compilation], read) : render(profile.compilation, read);
3261
+ files.set(`${entries[index][0]}.${profile.engine === "surge" ? "conf" : "json"}`, artifacts[0].content);
3262
+ }
3263
+ await publishProfiles(files, output);
3264
+ return {
3265
+ published: true,
3266
+ exitCode: 0,
3267
+ code: "PUBLISHED",
3268
+ active: join(resolve(output), "out")
3269
+ };
3270
+ } catch (error) {
3271
+ if (error instanceof SurgePublishError) return {
3272
+ published: error.published,
3273
+ exitCode: error.published ? 2 : 1,
3274
+ code: error.message,
3275
+ ...error.published ? { active: join(resolve(output), "out") } : {},
3276
+ ...error.message === "PUBLISH_RECOVERY_REQUIRED" ? { hint: "out may be absent; preserve the lock, backup, generation and temporary pointer for manual recovery" } : {}
3277
+ };
3278
+ return {
3279
+ published: false,
3280
+ exitCode: 1,
3281
+ code: error instanceof RenderError ? error.code : "BUILD_FAILED"
3282
+ };
3283
+ }
3284
+ }
3285
+ function runBuild(input, output, options = {}) {
3286
+ return executeBuild(input, output, options, defineBuild, publish);
3287
+ }
3288
+ //#endregion
3289
+ export { deepFreeze as $, defineProfile as A, renderSurgeProfiles as B, sequence as C, surge$1 as D, strategy as E, defineSurgeProfile as F, isReservedNativeName as G, compile as H, outbound as I, RenderError as J, nativeNameSchema as K, selectProxies as L, defineProxyGroup as M, defineRoute as N, use as O, defineRoutes as P, assertData as Q, compileSurgeProfile as R, selectNodes as S, slot as T, explain as U, secretReader as V, compileStrategyGroups as W, validateProxyOptions as X, surgeProxy as Y, StaticRuleSetUnknownError as Z, reject as _, surgeBuildFailure as a, ruleSet as b, render as c, direct as d, idSchema as et, group as f, proxy as g, policy as h, runSurgeBuild as i, ProfileDefinitionError as j, compileProfile as k, block as l, mihomo as m, runBuild as n, requestSchema as nt, buildSurgeProfilesToDirectory as o, match as p, targetCatalog as q, defineSurgeBuild as r, buildToDirectory as s, defineBuild as t, nodeSchema as tt, defineConfig as u, route as v, singbox$1 as w, secret as x, rule as y, renderSurgeProfile as z };