proxylang 0.1.2 → 0.1.4

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.
package/dist/index.js CHANGED
@@ -1,7 +1,12 @@
1
- import { A as slot, C as route, D as selectNodes, E as secret, F as deepFreeze, I as idSchema, L as nodeSchema, M as surge, N as use, O as sequence, P as assertData, S as reject, T as ruleSet, _ as group, a as explain, b as policy, c as nativeNameSchema, d as surgeProxy, f as validateProxyOptions, g as direct, h as defineConfig, i as compile, j as strategy, k as singbox, l as targetCatalog, m as block, n as render, o as compileStrategyGroups, p as StaticRuleSetUnknownError, r as secretReader, s as isReservedNativeName, t as buildToDirectory, u as RenderError, v as match, w as rule, x as proxy, y as mihomo } from "./host-BvBQxdmA.js";
1
+ import { A as slot, C as route, D as selectNodes, E as secret, F as deepFreeze, I as idSchema, L as nodeSchema, M as surge, N as use, O as sequence, P as assertData, S as reject, T as ruleSet, _ as group, a as explain, b as policy, c as nativeNameSchema, d as surgeProxy, f as validateProxyOptions, g as direct, h as defineConfig, i as compile, j as strategy, k as singbox, l as targetCatalog, m as block, n as render, o as compileStrategyGroups, p as StaticRuleSetUnknownError, r as secretReader, s as isReservedNativeName, t as buildToDirectory, u as RenderError, v as match, w as rule, x as proxy, y as mihomo } from "./host-BPBSZ-jw.js";
2
2
  import { z } from "zod";
3
+ import { isIP } from "node:net";
4
+ import ipaddr from "ipaddr.js";
5
+ import { lstat, mkdir, readlink, rename, rm, symlink, writeFile } from "node:fs/promises";
6
+ import { join, resolve } from "node:path";
7
+ import { randomUUID } from "node:crypto";
3
8
  //#region src/proxy-fragments.ts
4
- const inputSchema = z.strictObject({
9
+ const inputSchema$1 = z.strictObject({
5
10
  target: z.strictObject({
6
11
  engine: z.string(),
7
12
  platform: z.string(),
@@ -15,7 +20,7 @@ const inputSchema = z.strictObject({
15
20
  kind: z.enum(["proxy", "group"])
16
21
  })).max(1e3).optional()
17
22
  });
18
- const plans = /* @__PURE__ */ new WeakMap();
23
+ const plans$1 = /* @__PURE__ */ new WeakMap();
19
24
  function compileProxyNodes(input) {
20
25
  const diagnostics = [];
21
26
  const error = (code, path, message) => diagnostics.push({
@@ -37,7 +42,7 @@ function compileProxyNodes(input) {
37
42
  error("INVALID_INPUT_GRAPH", "$", "输入必须是有限纯数据,不接受 builder 或访问器");
38
43
  return failure();
39
44
  }
40
- const parsed = inputSchema.safeParse(input);
45
+ const parsed = inputSchema$1.safeParse(input);
41
46
  if (!parsed.success) {
42
47
  error("INVALID_SCHEMA", "$", "节点、名字或外部声明不符合严格 schema");
43
48
  return failure();
@@ -108,14 +113,14 @@ function compileProxyNodes(input) {
108
113
  bindings,
109
114
  requirements
110
115
  });
111
- plans.set(compilation, deepFreeze({
116
+ plans$1.set(compilation, deepFreeze({
112
117
  nodes,
113
118
  names: Object.fromEntries(symbols.map((s) => [s.id, s.nativeName]))
114
119
  }));
115
120
  return compilation;
116
121
  }
117
122
  function renderProxyNodes(compilation, resolveSecret) {
118
- const plan = plans.get(compilation);
123
+ const plan = plans$1.get(compilation);
119
124
  if (!plan) throw new RenderError("COMPILATION_FAILED");
120
125
  const secret = secretReader(resolveSecret);
121
126
  const entries = plan.nodes.map((node) => ({
@@ -129,4 +134,614 @@ function renderProxyNodes(compilation, resolveSecret) {
129
134
  });
130
135
  }
131
136
  //#endregion
132
- export { RenderError, StaticRuleSetUnknownError, block, buildToDirectory, compile, compileProxyNodes, compileStrategyGroups, defineConfig, direct, explain, group, match, mihomo, policy, proxy, reject, render, renderProxyNodes, route, rule, ruleSet, secret, selectNodes, sequence, singbox, slot, strategy, surge, targetCatalog, use };
137
+ //#region src/surge-profile.ts
138
+ const builtin = z.enum([
139
+ "DIRECT",
140
+ "REJECT",
141
+ "REJECT-DROP",
142
+ "REJECT-NO-DROP",
143
+ "REJECT-TINYGIF"
144
+ ]);
145
+ const policy$1 = z.union([z.strictObject({ ref: idSchema }), z.strictObject({ builtin })]);
146
+ const token = z.strictObject({
147
+ type: z.literal("env"),
148
+ name: z.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/)
149
+ });
150
+ const safe = z.string().min(1).max(4096).refine((v) => v.trim() === v && !/[\p{C}\p{Zl}\p{Zp},=()#;"'\\]/u.test(v));
151
+ 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])?$/);
152
+ const hostPattern = safe.refine((v) => /^[a-zA-Z0-9*?._-]+$/.test(v));
153
+ const ip = safe.refine((v) => isIP(v) !== 0 && !v.includes("%"));
154
+ const cidr = (version) => safe.refine((v) => {
155
+ try {
156
+ const [address] = ipaddr.parseCIDR(v);
157
+ return (!version || (address.kind() === "ipv4" ? 4 : 6) === version) && !v.includes("%");
158
+ } catch {
159
+ return false;
160
+ }
161
+ });
162
+ const port = z.number().int().min(1).max(65535);
163
+ function addressPort(value, allowHost, portRequired) {
164
+ if (!portRequired && isIP(value)) return true;
165
+ const match = /^(\[[^\]]+\]|[^:]+):(\d+)$/.exec(value);
166
+ if (!match || Number(match[2]) < 1 || Number(match[2]) > 65535) return false;
167
+ const host = match[1];
168
+ return host.startsWith("[") ? isIP(host.slice(1, -1)) === 6 : isIP(host) === 4 || allowHost && domain.safeParse(host).success;
169
+ }
170
+ const listener = safe.refine((v) => addressPort(v, false, false));
171
+ const endpoint = safe.refine((v) => addressPort(v, true, true));
172
+ const dns = safe.refine((v) => v === "system" || addressPort(v, false, false));
173
+ const url = z.string().min(1).max(4096).refine((v) => {
174
+ try {
175
+ const u = new URL(v);
176
+ return /^https?:\/\//.test(v) && !u.username && !u.password && !u.hash && !/[\s\p{C},()\\"']/u.test(v);
177
+ } catch {
178
+ return false;
179
+ }
180
+ });
181
+ const encryptedDns = z.string().max(4096).refine((v) => {
182
+ try {
183
+ const u = new URL(v);
184
+ return [
185
+ "https:",
186
+ "h3:",
187
+ "quic:",
188
+ "tls:",
189
+ "tcp:"
190
+ ].includes(u.protocol) && !!u.hostname && !u.username && !u.password && !u.hash && !/[\s\p{C},()\\"']/u.test(v);
191
+ } catch {
192
+ return false;
193
+ }
194
+ });
195
+ const list = (item) => z.array(item).min(1).max(1e3);
196
+ const control = z.strictObject({
197
+ password: token,
198
+ listen: safe.refine((v) => addressPort(v, false, true))
199
+ });
200
+ const generalSchema = z.strictObject({
201
+ loglevel: z.enum([
202
+ "verbose",
203
+ "info",
204
+ "notify",
205
+ "warning"
206
+ ]).optional(),
207
+ "dns-server": list(dns).optional(),
208
+ "encrypted-dns-server": list(encryptedDns).optional(),
209
+ "show-error-page-for-reject": z.boolean().optional(),
210
+ "exclude-simple-hostnames": z.boolean().optional(),
211
+ "internet-test-url": url.optional(),
212
+ "skip-proxy": list(z.union([
213
+ hostPattern,
214
+ ip,
215
+ cidr()
216
+ ])).optional(),
217
+ ipv6: z.boolean().optional(),
218
+ "ipv6-vif": z.enum([
219
+ "auto",
220
+ "always",
221
+ "disabled"
222
+ ]).optional(),
223
+ "bypass-system": z.boolean().optional(),
224
+ replica: z.boolean().optional(),
225
+ "tls-provider": z.enum(["default", "openssl"]).optional(),
226
+ "bypass-tun": list(cidr()).optional(),
227
+ "always-real-ip": list(hostPattern).optional(),
228
+ "http-api": control.optional(),
229
+ "http-api-web-dashboard": z.boolean().optional(),
230
+ "external-controller-access": control.optional(),
231
+ "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(),
232
+ "http-listen": listener.optional(),
233
+ "socks5-listen": listener.optional(),
234
+ "proxy-restricted-to-lan": z.boolean().optional()
235
+ });
236
+ const hostSchema = z.strictObject({
237
+ pattern: hostPattern,
238
+ address: z.union([ip, domain]).optional(),
239
+ server: z.union([dns, encryptedDns]).optional()
240
+ }).refine((v) => v.address !== void 0 || v.server !== void 0);
241
+ 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);
242
+ const sectionName = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,127}$/);
243
+ const tunnelSchema = z.discriminatedUnion("type", [z.strictObject({
244
+ type: z.literal("tailscale"),
245
+ id: idSchema,
246
+ sectionName,
247
+ authKey: token,
248
+ hostname: domain,
249
+ dnsServer: list(dns).optional(),
250
+ autoAddMagicDnsRule: z.boolean().optional(),
251
+ idleKeepalive: z.number().int().min(-1).max(2147483647).optional()
252
+ }), z.strictObject({
253
+ type: z.literal("wireguard"),
254
+ id: idSchema,
255
+ sectionName,
256
+ privateKey: token,
257
+ selfIp: ip.refine((v) => isIP(v) === 4),
258
+ dnsServer: list(dns).optional(),
259
+ mtu: z.number().int().min(576).max(9e3).optional(),
260
+ peers: list(z.strictObject({
261
+ publicKey: key,
262
+ endpoint,
263
+ allowedIps: list(cidr()),
264
+ presharedKey: token.optional(),
265
+ persistentKeepalive: z.number().int().min(0).max(65535).optional()
266
+ }))
267
+ })]);
268
+ const groupSchema = z.strictObject({
269
+ id: idSchema,
270
+ type: z.enum(["select", "smart"]),
271
+ members: list(policy$1),
272
+ url: url.optional(),
273
+ intervalSeconds: z.number().int().positive().max(2147483647).optional(),
274
+ timeoutSeconds: z.number().int().positive().max(3600).optional()
275
+ });
276
+ const options = {
277
+ noResolve: z.boolean().optional(),
278
+ extendedMatching: z.boolean().optional()
279
+ };
280
+ const atom = (type, value) => z.strictObject({
281
+ type: z.literal(type),
282
+ value,
283
+ ...options
284
+ });
285
+ const conditionSchema = z.lazy(() => z.union([
286
+ atom("domain", domain),
287
+ atom("domainSuffix", domain),
288
+ atom("ipCidr", cidr(4)),
289
+ atom("ipCidr6", cidr(6)),
290
+ atom("sourceIp", z.union([ip, cidr()])),
291
+ atom("processName", safe),
292
+ atom("macAddress", z.string().regex(/^(?:[\da-fA-F]{2}:){5}[\da-fA-F]{2}$/)),
293
+ z.strictObject({
294
+ type: z.enum(["port", "sourcePort"]),
295
+ from: port,
296
+ to: port.optional(),
297
+ ...options
298
+ }).refine((v) => v.to === void 0 || v.to >= v.from),
299
+ z.strictObject({
300
+ type: z.literal("network"),
301
+ value: z.enum(["tcp", "udp"]),
302
+ ...options
303
+ }),
304
+ z.strictObject({
305
+ type: z.enum(["all", "any"]),
306
+ conditions: z.array(conditionSchema).min(2).max(100),
307
+ ...options
308
+ }),
309
+ z.strictObject({
310
+ type: z.literal("not"),
311
+ condition: conditionSchema,
312
+ ...options
313
+ }),
314
+ z.strictObject({
315
+ type: z.literal("ruleSet"),
316
+ format: z.enum(["rule-set", "domain-set"]),
317
+ url: url.optional(),
318
+ builtin: z.enum(["LAN", "SYSTEM"]).optional(),
319
+ ...options
320
+ }).refine((v) => v.url !== void 0 !== (v.builtin !== void 0))
321
+ ]));
322
+ const managedSchema = z.strictObject({
323
+ url: url.refine((v) => !new URL(v).search && !v.includes("?")),
324
+ 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(),
325
+ intervalSeconds: z.number().int().min(60).max(2147483647),
326
+ strict: z.boolean()
327
+ });
328
+ const inputSchema = z.strictObject({
329
+ target: z.strictObject({
330
+ engine: z.literal("surge"),
331
+ platform: z.enum(["macos", "ios"]),
332
+ version: z.string()
333
+ }),
334
+ managed: managedSchema.optional(),
335
+ general: generalSchema.optional(),
336
+ hosts: z.array(hostSchema).max(2e3).optional(),
337
+ nodes: z.array(nodeSchema).max(1e3),
338
+ tunnels: z.array(tunnelSchema).max(1e3).optional(),
339
+ groups: z.array(groupSchema).max(1e3),
340
+ rules: z.array(z.strictObject({
341
+ when: conditionSchema,
342
+ then: policy$1
343
+ })).max(1e4),
344
+ fallback: policy$1,
345
+ names: z.record(idSchema, nativeNameSchema).optional()
346
+ });
347
+ const plans = /* @__PURE__ */ new WeakMap();
348
+ function compileSurgeProfile(input) {
349
+ const diagnostics = [];
350
+ const error = (code) => diagnostics.push({
351
+ severity: "error",
352
+ code,
353
+ path: "$",
354
+ message: code
355
+ });
356
+ const failure = () => deepFreeze({
357
+ ok: false,
358
+ artifactKind: "surge-profile",
359
+ diagnostics,
360
+ bindings: []
361
+ });
362
+ try {
363
+ assertData(input);
364
+ } catch {
365
+ error("INVALID_INPUT_GRAPH");
366
+ return failure();
367
+ }
368
+ const parsed = inputSchema.safeParse(input);
369
+ if (!parsed.success) {
370
+ error("INVALID_SCHEMA");
371
+ return failure();
372
+ }
373
+ if (parsed.data.general) {
374
+ const general = parsed.data.general;
375
+ parsed.data.general = Object.fromEntries(Object.keys(input.general).map((key) => [key, general[key]]));
376
+ }
377
+ const p = deepFreeze(parsed.data);
378
+ if (!(p.target.platform === "macos" && p.target.version === "6.10.0") && !(p.target.platform === "ios" && p.target.version === "5.21.0")) error("UNKNOWN_TARGET");
379
+ const tunnels = p.tunnels ?? [];
380
+ const resources = [
381
+ ...p.nodes,
382
+ ...tunnels,
383
+ ...p.groups
384
+ ];
385
+ if (resources.length > 1e3) error("RESOURCE_LIMIT");
386
+ const ids = new Set(resources.map((r) => r.id));
387
+ if (ids.size !== resources.length) error("DUPLICATE_RESOURCE");
388
+ if (Object.keys(p.names ?? {}).some((id) => !ids.has(id))) error("UNKNOWN_NAME_MAPPING");
389
+ const bindings = resources.map((r) => ({
390
+ id: r.id,
391
+ nativeName: p.names?.[r.id] ?? r.id
392
+ }));
393
+ if (bindings.some((b) => !nativeNameSchema.safeParse(b.nativeName).success || isReservedNativeName(b.nativeName, "surge"))) error("INVALID_NATIVE_NAME");
394
+ if (new Set(bindings.map((b) => b.nativeName)).size !== bindings.length) error("DUPLICATE_NATIVE_NAME");
395
+ if (new Set(tunnels.map((t) => t.sectionName)).size !== tunnels.length) error("DUPLICATE_TUNNEL_SECTION");
396
+ if (p.target.platform === "ios" && [
397
+ "bypass-system",
398
+ "replica",
399
+ "tls-provider",
400
+ "bypass-tun",
401
+ "external-controller-access"
402
+ ].some((k) => Object.hasOwn(p.general ?? {}, k))) error("PLATFORM_OPTION_UNSUPPORTED");
403
+ if (new Set((p.hosts ?? []).map((h) => h.pattern.toLowerCase())).size !== (p.hosts ?? []).length) error("DUPLICATE_HOST_PATTERN");
404
+ const checkPolicy = (action) => {
405
+ if ("ref" in action && !ids.has(action.ref)) error("MISSING_REFERENCE");
406
+ };
407
+ const edges = new Map(resources.map((r) => [r.id, []]));
408
+ const proxyIds = new Set([...p.nodes, ...tunnels].map((n) => n.id));
409
+ for (const node of p.nodes) {
410
+ if (node.type === "vless") error("PROTOCOL_UNSUPPORTED");
411
+ validateProxyOptions(node, {
412
+ id: "profile",
413
+ engine: "surge"
414
+ }, diagnostics);
415
+ if (node.via) {
416
+ checkPolicy({ ref: node.via });
417
+ edges.get(node.id).push(node.via);
418
+ }
419
+ }
420
+ for (const group of p.groups) {
421
+ if (group.type === "smart" && (group.url !== void 0 || group.intervalSeconds !== void 0 || group.timeoutSeconds !== void 0)) error("GROUP_OPTION_UNSUPPORTED");
422
+ for (const member of group.members) {
423
+ checkPolicy(member);
424
+ if (group.type === "smart" && (!("ref" in member) || !proxyIds.has(member.ref))) error("SMART_MEMBER_UNSUPPORTED");
425
+ if ("ref" in member) edges.get(group.id).push(member.ref);
426
+ }
427
+ }
428
+ const active = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set();
429
+ const visit = (id) => {
430
+ if (active.has(id)) {
431
+ error("RESOURCE_CYCLE");
432
+ return;
433
+ }
434
+ if (visited.has(id)) return;
435
+ active.add(id);
436
+ for (const next of edges.get(id) ?? []) visit(next);
437
+ active.delete(id);
438
+ visited.add(id);
439
+ };
440
+ if (resources.length <= 1e3) for (const id of ids) visit(id);
441
+ const formats = /* @__PURE__ */ new Map();
442
+ const checkCondition = (c, depth) => {
443
+ if (depth > 10) {
444
+ error("LOGICAL_DEPTH_EXCEEDED");
445
+ return;
446
+ }
447
+ if (c.noResolve !== void 0 && ![
448
+ "ipCidr",
449
+ "ipCidr6",
450
+ "ruleSet"
451
+ ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
452
+ if (c.extendedMatching !== void 0 && ![
453
+ "domain",
454
+ "domainSuffix",
455
+ "ruleSet"
456
+ ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
457
+ if (p.target.platform === "ios" && ["processName", "macAddress"].includes(c.type)) error("PLATFORM_RULE_UNSUPPORTED");
458
+ if (c.type === "all" || c.type === "any") for (const child of c.conditions) checkCondition(child, depth + 1);
459
+ if (c.type === "not") checkCondition(c.condition, depth + 1);
460
+ if (c.type === "ruleSet") {
461
+ if (c.builtin && c.format !== "rule-set") error("BUILTIN_RULESET_FORMAT");
462
+ if (c.url) {
463
+ if (formats.has(c.url) && formats.get(c.url) !== c.format) error("RULESET_FORMAT_CONFLICT");
464
+ formats.set(c.url, c.format);
465
+ }
466
+ }
467
+ };
468
+ for (const rule of p.rules) {
469
+ checkPolicy(rule.then);
470
+ checkCondition(rule.when, 0);
471
+ }
472
+ checkPolicy(p.fallback);
473
+ if (diagnostics.some((d) => d.severity === "error")) return failure();
474
+ if (formats.size) diagnostics.push({
475
+ severity: "warning",
476
+ code: "EXTERNAL_RULESET_UNVERIFIED",
477
+ path: "rules",
478
+ message: "External rule sets are resolved by the client, not by the compiler."
479
+ });
480
+ const result = deepFreeze({
481
+ ok: true,
482
+ artifactKind: "surge-profile",
483
+ diagnostics,
484
+ bindings
485
+ });
486
+ plans.set(result, p);
487
+ return result;
488
+ }
489
+ function conditionOptions(c) {
490
+ return [...c.noResolve ? ["no-resolve"] : [], ...c.extendedMatching ? ["extended-matching"] : []];
491
+ }
492
+ function conditionText(c) {
493
+ switch (c.type) {
494
+ case "all":
495
+ case "any": return `${c.type === "all" ? "AND" : "OR"},(${c.conditions.map((x) => `(${[conditionText(x), ...conditionOptions(x)].join(",")})`).join(",")})`;
496
+ case "not": return `NOT,((${[conditionText(c.condition), ...conditionOptions(c.condition)].join(",")}))`;
497
+ case "port":
498
+ case "sourcePort": return `${c.type === "port" ? "DEST-PORT" : "SRC-PORT"},${c.from}${c.to === void 0 || c.to === c.from ? "" : `-${c.to}`}`;
499
+ case "network": return `PROTOCOL,${c.value.toUpperCase()}`;
500
+ case "ruleSet": return `${c.format === "rule-set" ? "RULE-SET" : "DOMAIN-SET"},${c.url ?? c.builtin}`;
501
+ default: return `${{
502
+ domain: "DOMAIN",
503
+ domainSuffix: "DOMAIN-SUFFIX",
504
+ ipCidr: "IP-CIDR",
505
+ ipCidr6: "IP-CIDR6",
506
+ sourceIp: "SRC-IP",
507
+ processName: "PROCESS-NAME",
508
+ macAddress: "MAC-ADDRESS"
509
+ }[c.type]},${c.value}`;
510
+ }
511
+ }
512
+ function renderProfile(compilation, read) {
513
+ const p = plans.get(compilation);
514
+ if (!p) throw new RenderError("COMPILATION_FAILED");
515
+ const name = (id) => p.names?.[id] ?? id;
516
+ const action = (value) => "ref" in value ? name(value.ref) : value.builtin;
517
+ const credential = (token, kind) => {
518
+ const value = read(token);
519
+ 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");
520
+ return value;
521
+ };
522
+ const lines = [];
523
+ if (p.managed) {
524
+ const address = new URL(p.managed.url);
525
+ for (const [k, v] of Object.entries(p.managed.query ?? {})) address.searchParams.set(k, typeof v === "string" ? v : read(v));
526
+ lines.push(`#!MANAGED-CONFIG ${address.href} interval=${p.managed.intervalSeconds} strict=${p.managed.strict}`, "");
527
+ }
528
+ lines.push("[General]");
529
+ for (const [k, v] of Object.entries(p.general ?? {})) {
530
+ const value = Array.isArray(v) ? v.join(", ") : typeof v === "object" ? `${credential(v.password, "control")}@${v.listen}` : String(v);
531
+ lines.push(`${k} = ${value}`);
532
+ }
533
+ lines.push("", "[Host]");
534
+ for (const h of p.hosts ?? []) lines.push(`${h.pattern} = ${[...h.address ? [h.address] : [], ...h.server ? [`server:${h.server}`] : []].join(", ")}`);
535
+ lines.push("", "[Proxy]");
536
+ for (const n of p.nodes) lines.push(surgeProxy(n, read, name));
537
+ for (const t of p.tunnels ?? []) lines.push(`${name(t.id)} = ${t.type}, section-name=${t.sectionName}`);
538
+ for (const t of p.tunnels ?? []) {
539
+ lines.push("", `[${t.type === "tailscale" ? "Tailscale" : "WireGuard"} ${t.sectionName}]`);
540
+ if (t.type === "tailscale") {
541
+ lines.push(`auth-key = ${credential(t.authKey, "tailscale")}`, `hostname = ${t.hostname}`);
542
+ if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
543
+ if (t.autoAddMagicDnsRule !== void 0) lines.push(`auto-add-magic-dns-rule = ${t.autoAddMagicDnsRule}`);
544
+ if (t.idleKeepalive !== void 0) lines.push(`idle-keepalive = ${t.idleKeepalive}`);
545
+ } else {
546
+ lines.push(`private-key = ${credential(t.privateKey, "key")}`, `self-ip = ${t.selfIp}`);
547
+ if (t.dnsServer) lines.push(`dns-server = ${t.dnsServer.join(", ")}`);
548
+ if (t.mtu !== void 0) lines.push(`mtu = ${t.mtu}`);
549
+ for (const peer of t.peers) {
550
+ const values = [`public-key = ${peer.publicKey}`];
551
+ if (peer.presharedKey) values.push(`preshared-key = ${credential(peer.presharedKey, "key")}`);
552
+ values.push(`allowed-ips = "${peer.allowedIps.join(", ")}"`, `endpoint = ${peer.endpoint}`);
553
+ if (peer.persistentKeepalive !== void 0) values.push(`keepalive = ${peer.persistentKeepalive}`);
554
+ lines.push(`peer = (${values.join(", ")})`);
555
+ }
556
+ }
557
+ }
558
+ lines.push("", "[Proxy Group]");
559
+ for (const g of p.groups) lines.push(`${name(g.id)} = ${[
560
+ g.type,
561
+ ...g.members.map(action),
562
+ ...g.url ? [`url=${g.url}`] : [],
563
+ ...g.intervalSeconds !== void 0 ? [`interval=${g.intervalSeconds}`] : [],
564
+ ...g.timeoutSeconds !== void 0 ? [`timeout=${g.timeoutSeconds}`] : []
565
+ ].join(", ")}`);
566
+ lines.push("", "[Rule]");
567
+ for (const r of p.rules) lines.push([
568
+ conditionText(r.when),
569
+ action(r.then),
570
+ ...conditionOptions(r.when)
571
+ ].join(","));
572
+ lines.push(`FINAL,${action(p.fallback)}`, "");
573
+ return deepFreeze({
574
+ artifactKind: "surge-profile",
575
+ content: lines.join("\n")
576
+ });
577
+ }
578
+ function renderSurgeProfile(compilation, resolveSecret) {
579
+ return renderProfile(compilation, secretReader(resolveSecret));
580
+ }
581
+ function renderSurgeProfiles(compilations, resolveSecret) {
582
+ if (compilations.some((c) => !plans.has(c))) throw new RenderError("COMPILATION_FAILED");
583
+ const read = secretReader(resolveSecret);
584
+ return deepFreeze(compilations.map((c) => renderProfile(c, read)));
585
+ }
586
+ //#endregion
587
+ //#region src/surge-compose.ts
588
+ /** Bind shared names only for included resources; explicit input mappings remain compiler-checked. */
589
+ function surgeProfile(input, names = {}) {
590
+ const bindings = {};
591
+ for (const node of input.nodes) bindings[node.id] = names[node.id] ?? node.label ?? node.id;
592
+ for (const resource of [...input.tunnels ?? [], ...input.groups]) bindings[resource.id] = names[resource.id] ?? resource.id;
593
+ return {
594
+ ...input,
595
+ names: {
596
+ ...bindings,
597
+ ...input.names
598
+ }
599
+ };
600
+ }
601
+ /** Stable queries produce native-profile policy references without consumer mapping code. */
602
+ function surgeMembers(nodes, query = {}) {
603
+ return selectNodes(nodes, query).map((ref) => ({ ref }));
604
+ }
605
+ //#endregion
606
+ //#region src/surge-publish.ts
607
+ var SurgePublishError = class extends Error {
608
+ published;
609
+ constructor(message, published) {
610
+ super(message);
611
+ this.published = published;
612
+ }
613
+ };
614
+ async function publishProfiles(files, surgeDirectory, io = { rename }) {
615
+ 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");
616
+ const root = resolve(surgeDirectory);
617
+ const generations = join(root, ".generations");
618
+ const id = randomUUID();
619
+ const generation = join(generations, id);
620
+ const pointer = join(root, `.out-${id}`);
621
+ const output = join(root, "out");
622
+ const backup = join(generations, `legacy-${id}`);
623
+ const lock = join(root, ".build-lock");
624
+ const remove = io.rm ?? rm;
625
+ let failure;
626
+ let locked = false, created = false, committed = false, movedLegacy = false, recoveryFailed = false;
627
+ async function directory(path) {
628
+ await mkdir(path, {
629
+ recursive: true,
630
+ mode: 448
631
+ });
632
+ const stat = await lstat(path);
633
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
634
+ }
635
+ try {
636
+ await directory(root);
637
+ try {
638
+ await mkdir(lock, { mode: 448 });
639
+ locked = true;
640
+ } catch (error) {
641
+ if (error.code === "EEXIST") throw new Error("OUTPUT_LOCKED");
642
+ throw error;
643
+ }
644
+ await directory(generations);
645
+ let previous;
646
+ try {
647
+ previous = await lstat(output);
648
+ } catch (error) {
649
+ if (error.code !== "ENOENT") throw error;
650
+ }
651
+ if (previous?.isSymbolicLink()) {
652
+ const target = await readlink(output);
653
+ if (!/^\.generations\/(?:legacy-)?[a-f0-9-]{36}$/.test(target)) throw new Error("UNMANAGED_OUTPUT_LINK");
654
+ const stat = await lstat(join(root, target));
655
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
656
+ } else if (previous && !previous.isDirectory()) throw new Error("UNSAFE_OUTPUT_DIRECTORY");
657
+ await mkdir(generation, { mode: 448 });
658
+ created = true;
659
+ for (const [name, content] of files) await writeFile(join(generation, name), content, {
660
+ mode: 384,
661
+ flag: "wx"
662
+ });
663
+ await symlink(`.generations/${id}`, pointer, "dir");
664
+ if (previous?.isDirectory()) {
665
+ await io.rename(output, backup);
666
+ movedLegacy = true;
667
+ }
668
+ try {
669
+ await io.rename(pointer, output);
670
+ committed = true;
671
+ } catch (error) {
672
+ if (movedLegacy) try {
673
+ await io.rename(backup, output);
674
+ movedLegacy = false;
675
+ } catch {
676
+ recoveryFailed = true;
677
+ throw new Error("PUBLISH_RECOVERY_REQUIRED");
678
+ }
679
+ throw error;
680
+ }
681
+ } catch (error) {
682
+ const code = error instanceof Error && /^(?:INVALID_PROFILE_FILENAMES|OUTPUT_LOCKED|UNMANAGED_OUTPUT_LINK|UNSAFE_OUTPUT_DIRECTORY|PUBLISH_RECOVERY_REQUIRED)$/.test(error.message) ? error.message : "PROFILE_PUBLISH_FAILED";
683
+ failure = new Error(code);
684
+ } finally {
685
+ if (!recoveryFailed) try {
686
+ await remove(pointer, { force: true });
687
+ if (created && !committed) await remove(generation, {
688
+ recursive: true,
689
+ force: true
690
+ });
691
+ if (locked) await remove(lock, {
692
+ recursive: true,
693
+ force: true
694
+ });
695
+ } catch {
696
+ failure ??= /* @__PURE__ */ new Error("PROFILE_PUBLISH_CLEANUP_FAILED");
697
+ }
698
+ }
699
+ if (failure) throw new SurgePublishError(failure.message === "PROFILE_PUBLISH_CLEANUP_FAILED" ? committed ? "PUBLISHED_CLEANUP_FAILED" : "FAILED_CLEANUP_REQUIRED" : failure.message, committed);
700
+ }
701
+ //#endregion
702
+ //#region src/surge-host.ts
703
+ /** Complete-profile batches use the out symlink protocol; the Program host remains unchanged. */
704
+ async function buildSurgeProfilesToDirectory(profiles, output, resolveSecret = (token) => process.env[token.name]) {
705
+ if (typeof output !== "string" || !output.trim()) return {
706
+ published: false,
707
+ exitCode: 1,
708
+ code: "INVALID_OUTPUT_DIRECTORY"
709
+ };
710
+ try {
711
+ const entries = Object.entries(profiles);
712
+ if (!entries.length || entries.length > 16 || entries.some(([id]) => !/^[a-z0-9][a-z0-9-]*$/.test(id))) return {
713
+ published: false,
714
+ exitCode: 1,
715
+ code: "INVALID_PROFILE_FILENAMES"
716
+ };
717
+ const compiled = entries.map(([, input]) => compileSurgeProfile(input));
718
+ if (compiled.some((profile) => !profile.ok)) return {
719
+ published: false,
720
+ exitCode: 1,
721
+ code: "COMPILATION_FAILED"
722
+ };
723
+ const artifacts = renderSurgeProfiles(compiled, resolveSecret);
724
+ await publishProfiles(new Map(entries.map(([id], i) => [`${id}.conf`, artifacts[i].content])), output);
725
+ return {
726
+ published: true,
727
+ exitCode: 0,
728
+ code: "PUBLISHED",
729
+ active: join(resolve(output), "out")
730
+ };
731
+ } catch (error) {
732
+ if (error instanceof SurgePublishError) return {
733
+ published: error.published,
734
+ exitCode: error.published ? 2 : 1,
735
+ code: error.message,
736
+ ...error.published ? { active: join(resolve(output), "out") } : {},
737
+ ...error.message === "PUBLISH_RECOVERY_REQUIRED" ? { hint: "out may be absent; preserve the lock, backup, generation and temporary pointer for manual recovery" } : {}
738
+ };
739
+ return {
740
+ published: false,
741
+ exitCode: 1,
742
+ code: error instanceof RenderError ? error.code : "BUILD_FAILED"
743
+ };
744
+ }
745
+ }
746
+ //#endregion
747
+ export { RenderError, StaticRuleSetUnknownError, block, buildSurgeProfilesToDirectory, buildToDirectory, compile, compileProxyNodes, compileStrategyGroups, compileSurgeProfile, defineConfig, direct, explain, group, match, mihomo, policy, proxy, reject, render, renderProxyNodes, renderSurgeProfile, renderSurgeProfiles, route, rule, ruleSet, secret, selectNodes, sequence, singbox, slot, strategy, surge, surgeMembers, surgeProfile, targetCatalog, use };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proxylang",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "description": "Composable routing policies in TypeScript with explicit platform targets",
5
5
  "homepage": "https://github.com/CorrectRoadH/proxylang#readme",
6
6
  "bugs": {