proxylang 0.8.0 → 0.9.1

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/README.md CHANGED
@@ -405,6 +405,8 @@ DEMO_PASSWORD=example-only DEMO_UUID=11111111-2222-4333-8444-555555555555 \
405
405
 
406
406
  支持域名、IP、端口、网络类型与逻辑条件,节点协议包括 Trojan、HTTP、AnyTLS、Shadowsocks、VMess、VLESS,具体能力按目标版本检查。未知版本和影响路由行为的不支持项报错;可省略的展示信息报 warning,可用 `warningsAsErrors` 提升为错误。
407
407
 
408
+ 需要额外匹配 TLS SNI 和 HTTP Host 时,使用 `match.domainSuffix("example.com", { includeSniffed: true })`。原域名仍参与匹配;Surge 编译为 `extended-matching`。其他引擎的嗅探通常优先使用识别域名,不能等价为多来源 OR,因此拒绝此选项的 `true`。它不改变连接目的地址。详见[匹配语义](docs/feature/target-compilation/domain-sources.md)。
409
+
408
410
  Stash 当前拒绝来源 IP/端口、端口范围和组级 URLTest。完整配置的节点地址暂限 IP,独立 Surge 节点片段支持域名。HTTP、VMess、VLESS 及经过它们的代理链按 TCP-only 检查;AnyTLS 目前仅在 Surge 放行 UDP。远程节点订阅、MAC/进程匹配和 TUN 尚未实现。完整限制见 [SDK 细则](docs/implementation-v0.md)和 [Mihomo / Stash 转换边界](docs/engineering/clash-backends/README.md)。
409
411
 
410
412
  配置文件是可信的 TypeScript 代码;构建产物包含密码,旧构建也会保留。凭据与产物管理见[构建契约](docs/feature/artifact-publication/use-case/publish-generation.md)。
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { K as requestSchema, L as targetCatalog, M as compile, N as explain, V as StaticRuleSetUnknownError, i as buildToDirectory, n as defineBuild, r as runBuild, t as checkBuild } from "./profile-build-DuHp9nQt.js";
2
+ import { K as requestSchema, L as targetCatalog, M as compile, N as explain, V as StaticRuleSetUnknownError, Z as definitionDiagnostic, i as buildToDirectory, n as defineBuild, r as runBuild, t as checkBuild } from "./profile-build-Cyrem-0-.js";
3
3
  import { lstat, open, stat } from "node:fs/promises";
4
4
  import { resolve } from "node:path";
5
5
  import { pathToFileURL } from "node:url";
@@ -41,6 +41,17 @@ async function readRequestFile(path) {
41
41
  }
42
42
  }
43
43
  function loadFailure(cause) {
44
+ const diagnostic = definitionDiagnostic(cause);
45
+ if (diagnostic) {
46
+ print({
47
+ ok: false,
48
+ code: "CONFIG_LOAD_FAILED",
49
+ reason: "INVALID_CONFIGURATION",
50
+ diagnostic,
51
+ hint: "检查配置字段与库定义约束"
52
+ });
53
+ return 1;
54
+ }
44
55
  let code;
45
56
  let name;
46
57
  try {
package/dist/index.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { z } from "zod";
2
2
  //#region src/types.d.ts
3
- export type DomainSource = "destination" | "tlsSni" | "httpHost";
4
3
  export type Network = "tcp" | "udp";
5
4
  export type NamedRuleSet = {
6
5
  readonly type: "ruleSet";
@@ -16,7 +15,7 @@ export type NativeRuleSet = {
16
15
  readonly format: "rule-set" | "domain-set";
17
16
  readonly intervalSeconds?: number;
18
17
  readonly noResolve?: boolean;
19
- readonly sources?: readonly DomainSource[];
18
+ readonly includeSniffed?: boolean;
20
19
  } | {
21
20
  readonly engine: "sing-box";
22
21
  readonly format: "source" | "binary";
@@ -29,7 +28,7 @@ export type NativeRuleSet = {
29
28
  });
30
29
  export type Match = NamedRuleSet | NativeRuleSet | {
31
30
  readonly type: "domain" | "domainSuffix";
32
- readonly sources?: readonly DomainSource[];
31
+ readonly includeSniffed?: boolean;
33
32
  readonly value: string;
34
33
  } | {
35
34
  readonly type: "ipCidr";
@@ -439,32 +438,38 @@ declare const groupSchema: z.ZodObject<{
439
438
  timeoutSeconds: z.ZodOptional<z.ZodNumber>;
440
439
  }, z.core.$strict>;
441
440
  type SurgeGroup = z.infer<typeof groupSchema>;
442
- type ConditionOptions = {
443
- readonly noResolve?: boolean;
444
- readonly sources?: readonly DomainSource[];
441
+ type NoSniff = {
442
+ readonly includeSniffed?: never;
445
443
  };
446
- type SurgeCondition = ConditionOptions & ({
447
- readonly type: "domain" | "domainSuffix" | "ipCidr" | "ipCidr6" | "sourceIp" | "processName" | "macAddress";
444
+ type SurgeCondition = {
445
+ readonly noResolve?: boolean;
446
+ } & ({
447
+ readonly type: "domain" | "domainSuffix";
448
448
  readonly value: string;
449
- } | {
449
+ readonly includeSniffed?: boolean;
450
+ } | (NoSniff & {
451
+ readonly type: "ipCidr" | "ipCidr6" | "sourceIp" | "processName" | "macAddress";
452
+ readonly value: string;
453
+ }) | (NoSniff & {
450
454
  readonly type: "port" | "sourcePort";
451
455
  readonly from: number;
452
456
  readonly to?: number;
453
- } | {
457
+ }) | (NoSniff & {
454
458
  readonly type: "network";
455
459
  readonly value: "tcp" | "udp";
456
- } | {
460
+ }) | (NoSniff & {
457
461
  readonly type: "all" | "any";
458
462
  readonly conditions: readonly SurgeCondition[];
459
- } | {
463
+ }) | (NoSniff & {
460
464
  readonly type: "not";
461
465
  readonly condition: SurgeCondition;
462
- } | {
466
+ }) | {
463
467
  readonly type: "ruleSet";
464
468
  readonly format: "rule-set" | "domain-set";
465
469
  readonly url?: string;
466
470
  readonly builtin?: "LAN" | "SYSTEM";
467
471
  readonly intervalSeconds?: number;
472
+ readonly includeSniffed?: boolean;
468
473
  });
469
474
  type SurgeRule = {
470
475
  readonly when: SurgeCondition;
@@ -621,7 +626,8 @@ type RouteDefinition = {
621
626
  };
622
627
  export declare class ProfileDefinitionError extends Error {
623
628
  readonly code: string;
624
- constructor(code: string);
629
+ readonly paths?: readonly string[];
630
+ constructor(code: string, paths?: readonly string[]);
625
631
  }
626
632
  export declare const outbound: {
627
633
  direct: Readonly<{
@@ -655,12 +661,10 @@ type ProfileCondition = Exclude<Match | SurgeCondition, {
655
661
  readonly type: "all" | "any";
656
662
  readonly conditions: readonly ProfileCondition[];
657
663
  readonly noResolve?: boolean;
658
- readonly sources?: readonly DomainSource[];
659
664
  } | {
660
665
  readonly type: "not";
661
666
  readonly condition: ProfileCondition;
662
667
  readonly noResolve?: boolean;
663
- readonly sources?: readonly DomainSource[];
664
668
  };
665
669
  type ProfileDestination = string | ProxyNode | ProxyGroupDefinition | SurgeTunnel | TailscaleEndpoint | {
666
670
  readonly builtin: "DIRECT" | "REJECT" | "REJECT-DROP" | "REJECT-NO-DROP" | "REJECT-TINYGIF";
@@ -710,6 +714,7 @@ type ProfileCompilation = {
710
714
  readonly engine: "invalid";
711
715
  readonly ok: false;
712
716
  readonly code: string;
717
+ readonly paths?: readonly string[];
713
718
  };
714
719
  declare function surgeConfig(input: SurgeConfig): SurgeConfig;
715
720
  export declare function defineProfile(input: ProfileDefinition | Profile): Profile;
@@ -733,7 +738,7 @@ export declare function dnsRule(pattern: string, server: string): DnsRule;
733
738
  export declare function dnsRule(patterns: readonly string[], server: string): DnsRule[];
734
739
  export declare const ruleSet: (definition: Omit<NamedRuleSet, "type">) => NamedRuleSet;
735
740
  type DomainOptions = {
736
- readonly sources?: readonly DomainSource[];
741
+ readonly includeSniffed?: boolean;
737
742
  };
738
743
  type IpOptions = {
739
744
  readonly noResolve?: boolean;
@@ -745,12 +750,12 @@ export declare const match: {
745
750
  };
746
751
  ruleSet: (set: NamedRuleSet) => NamedRuleSet;
747
752
  domain: (value: string, opts?: DomainOptions) => {
748
- sources?: readonly DomainSource[];
753
+ includeSniffed?: boolean;
749
754
  type: "domain";
750
755
  value: string;
751
756
  };
752
757
  domainSuffix: (value: string, opts?: DomainOptions) => {
753
- sources?: readonly DomainSource[];
758
+ includeSniffed?: boolean;
754
759
  type: "domainSuffix";
755
760
  value: string;
756
761
  };
@@ -844,55 +849,55 @@ export declare const surge: {
844
849
  match: {
845
850
  domain: (value: string, options?: {
846
851
  readonly noResolve?: boolean;
847
- readonly sources?: readonly DomainSource[];
848
- }) => SurgeCondition;
852
+ readonly includeSniffed?: boolean;
853
+ } | undefined) => SurgeCondition;
849
854
  domainSuffix: (value: string, options?: {
850
855
  readonly noResolve?: boolean;
851
- readonly sources?: readonly DomainSource[];
852
- }) => SurgeCondition;
856
+ readonly includeSniffed?: boolean;
857
+ } | undefined) => SurgeCondition;
853
858
  ipCidr: (value: string, options?: {
854
859
  readonly noResolve?: boolean;
855
- readonly sources?: readonly DomainSource[];
856
- }) => SurgeCondition;
860
+ readonly includeSniffed?: never;
861
+ } | undefined) => SurgeCondition;
857
862
  ipCidr6: (value: string, options?: {
858
863
  readonly noResolve?: boolean;
859
- readonly sources?: readonly DomainSource[];
860
- }) => SurgeCondition;
864
+ readonly includeSniffed?: never;
865
+ } | undefined) => SurgeCondition;
861
866
  sourceIp: (value: string, options?: {
862
867
  readonly noResolve?: boolean;
863
- readonly sources?: readonly DomainSource[];
864
- }) => SurgeCondition;
868
+ readonly includeSniffed?: never;
869
+ } | undefined) => SurgeCondition;
865
870
  processName: (value: string, options?: {
866
871
  readonly noResolve?: boolean;
867
- readonly sources?: readonly DomainSource[];
868
- }) => SurgeCondition;
872
+ readonly includeSniffed?: never;
873
+ } | undefined) => SurgeCondition;
869
874
  macAddress: (value: string, options?: {
870
875
  readonly noResolve?: boolean;
871
- readonly sources?: readonly DomainSource[];
872
- }) => SurgeCondition;
876
+ readonly includeSniffed?: never;
877
+ } | undefined) => SurgeCondition;
873
878
  network: (value: "tcp" | "udp", options?: {
874
879
  readonly noResolve?: boolean;
875
- readonly sources?: readonly DomainSource[];
880
+ readonly includeSniffed?: never;
876
881
  }) => SurgeCondition;
877
882
  port: (from: number, to?: number, options?: {
878
883
  readonly noResolve?: boolean;
879
- readonly sources?: readonly DomainSource[];
884
+ readonly includeSniffed?: never;
880
885
  }) => SurgeCondition;
881
886
  sourcePort: (from: number, to?: number, options?: {
882
887
  readonly noResolve?: boolean;
883
- readonly sources?: readonly DomainSource[];
888
+ readonly includeSniffed?: never;
884
889
  }) => SurgeCondition;
885
890
  all: (conditions: readonly SurgeCondition[], options?: {
886
891
  readonly noResolve?: boolean;
887
- readonly sources?: readonly DomainSource[];
892
+ readonly includeSniffed?: never;
888
893
  }) => SurgeCondition;
889
894
  any: (conditions: readonly SurgeCondition[], options?: {
890
895
  readonly noResolve?: boolean;
891
- readonly sources?: readonly DomainSource[];
896
+ readonly includeSniffed?: never;
892
897
  }) => SurgeCondition;
893
898
  not: (value: SurgeCondition, options?: {
894
899
  readonly noResolve?: boolean;
895
- readonly sources?: readonly DomainSource[];
900
+ readonly includeSniffed?: never;
896
901
  }) => SurgeCondition;
897
902
  ruleSet: (options: Omit<Extract<SurgeCondition, {
898
903
  type: "ruleSet";
@@ -916,7 +921,7 @@ export declare const surge: {
916
921
  readonly format: "rule-set" | "domain-set";
917
922
  readonly intervalSeconds?: number;
918
923
  readonly noResolve?: boolean;
919
- readonly sources?: readonly DomainSource[];
924
+ readonly includeSniffed?: boolean;
920
925
  };
921
926
  };
922
927
  };
@@ -1026,11 +1031,18 @@ type Artifact = {
1026
1031
  /** Secret resolution is once per token per batch, including across providers. */
1027
1032
  export declare function render(compilation: Compilation, resolveSecret: (token: Secret) => string | undefined): readonly Artifact[];
1028
1033
  //#endregion
1034
+ //#region src/secrets.d.ts
1035
+ type SecretFailure = {
1036
+ readonly secretName?: string;
1037
+ readonly secretReason?: "MISSING" | "RESOLUTION_FAILED";
1038
+ };
1039
+ //#endregion
1029
1040
  //#region src/host.d.ts
1030
- type BuildResult = {
1041
+ type BuildResult = SecretFailure & {
1031
1042
  readonly published: boolean;
1032
1043
  readonly exitCode: 0 | 1 | 2;
1033
1044
  readonly code: string;
1045
+ readonly paths?: readonly string[];
1034
1046
  readonly active?: string;
1035
1047
  readonly generation?: string;
1036
1048
  readonly reason?: "ACCESS_DENIED" | "NO_SPACE" | "READ_ONLY" | "INVALID_DIRECTORY" | "IO_ERROR";
@@ -1120,6 +1132,7 @@ type ProfileCheckResult = {
1120
1132
  readonly engine: "surge" | "sing-box" | "invalid";
1121
1133
  readonly ok: boolean;
1122
1134
  readonly code?: string;
1135
+ readonly paths?: readonly string[];
1123
1136
  readonly diagnostics: readonly Diagnostic[];
1124
1137
  }[];
1125
1138
  };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as outbound, A as renderSurgeProfiles, B as validateProxyOptions, C as strategy, D as defineProfile, E as compileProfile, F as isReservedNativeName, G as nodeSchema, H as assertData, I as nativeNameSchema, J as defineProxyGroup, L as targetCatalog, M as compile, N as explain, O as compileSurgeProfile, P as compileStrategyGroups, Q as inspectDefinition, R as RenderError, S as slot, T as use, U as deepFreeze, V as StaticRuleSetUnknownError, W as idSchema, X as defineRoutes, Y as defineRoute, Z as exactDefinition, _ as rule, a as render, b as sequence, c as direct, d as match, f as mihomo, g as route, h as reject, i as buildToDirectory, j as secretReader, k as renderSurgeProfile, l as dnsRule, m as proxy, n as defineBuild, o as block, p as policy, q as ProfileDefinitionError, r as runBuild, s as defineConfig, t as checkBuild, u as group, v as ruleSet, w as surge, x as singbox, y as secret, z as surgeProxy } from "./profile-build-DuHp9nQt.js";
1
+ import { $ as inspectDefinition, A as renderSurgeProfiles, B as validateProxyOptions, C as strategy, D as defineProfile, E as compileProfile, F as isReservedNativeName, G as nodeSchema, H as assertData, I as nativeNameSchema, J as defineProxyGroup, L as targetCatalog, M as compile, N as explain, O as compileSurgeProfile, P as compileStrategyGroups, Q as exactDefinition, R as RenderError, S as slot, T as use, U as deepFreeze, V as StaticRuleSetUnknownError, W as idSchema, X as defineRoutes, Y as defineRoute, _ as rule, a as render, b as sequence, c as direct, d as match, et as outbound, f as mihomo, g as route, h as reject, i as buildToDirectory, j as secretReader, k as renderSurgeProfile, l as dnsRule, m as proxy, n as defineBuild, o as block, p as policy, q as ProfileDefinitionError, r as runBuild, s as defineConfig, t as checkBuild, u as group, v as ruleSet, w as surge, x as singbox, y as secret, z as surgeProxy } from "./profile-build-Cyrem-0-.js";
2
2
  import { z } from "zod";
3
3
  import { createHash } from "node:crypto";
4
4
  //#region src/proxy-fragments.ts
@@ -1,30 +1,14 @@
1
- import { z } from "zod";
2
1
  import { isIP } from "node:net";
2
+ import { z } from "zod";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import ipaddr from "ipaddr.js";
5
5
  import { stringify } from "yaml";
6
6
  import { lstat, mkdir, readlink, rename, rm, symlink, writeFile } from "node:fs/promises";
7
7
  import { join, resolve } from "node:path";
8
- //#region src/domain-sources.ts
9
- const order = [
10
- "destination",
11
- "tlsSni",
12
- "httpHost"
13
- ];
14
- const domainSourcesSchema = z.array(z.enum(order)).min(1).max(3).refine((sources) => new Set(sources).size === sources.length);
15
- function supportsDomainSources(sources, engine) {
16
- return sources === void 0 || sources.length === 1 && sources[0] === "destination" || engine === "surge" && sources.length === 3;
17
- }
18
- function extendedDomainSources(sources) {
19
- return sources?.length === 3;
20
- }
21
- /** Identity only: preserve author snapshots and all non-source options. */
8
+ //#region src/match-identity.ts
9
+ /** Identity only: preserve explicit false in author snapshots. */
22
10
  function domainIdentityFields(value) {
23
- return Object.entries(value).map(([key, field]) => {
24
- if (key !== "sources" || field === void 0) return [key, field];
25
- const sources = field;
26
- return [key, sources.length === 1 && sources[0] === "destination" ? void 0 : order.filter((source) => sources.includes(source))];
27
- }).filter(([, field]) => field !== void 0).sort(([a], [b]) => a.localeCompare(b));
11
+ return Object.entries(value).filter(([key, field]) => field !== void 0 && !(key === "includeSniffed" && field === false)).sort(([a], [b]) => a.localeCompare(b));
28
12
  }
29
13
  //#endregion
30
14
  //#region src/dns.ts
@@ -74,12 +58,75 @@ function dnsCondition(rule) {
74
58
  }
75
59
  //#endregion
76
60
  //#region src/surge-definitions.ts
61
+ const definitionCodes = /* @__PURE__ */ new Set([
62
+ "DEFINITION_CYCLE",
63
+ "DEFINITION_DEPTH_EXCEEDED",
64
+ "DEFINITION_EDGE_BUDGET_EXCEEDED",
65
+ "DEFINITION_NOT_DATA",
66
+ "DEFINITION_OBJECT_BUDGET_EXCEEDED",
67
+ "DEFINITION_OUTPUT_BUDGET_EXCEEDED",
68
+ "DEFINITION_UNKNOWN_FIELD",
69
+ "DNS_HOSTS_CONFLICT",
70
+ "DNS_RULE_CONFLICT",
71
+ "DUPLICATE_RESOURCE_ID",
72
+ "GROUP_NAME_CONFLICT",
73
+ "INVALID_BUILD_DEFINITION",
74
+ "INVALID_DESTINATION",
75
+ "INVALID_DNS_RULE",
76
+ "INVALID_DNS_RULES",
77
+ "INVALID_GROUP_DEFINITION",
78
+ "INVALID_MATCH_OPTIONS",
79
+ "INVALID_NATIVE_RULESET",
80
+ "INVALID_PROFILE_DEFINITION",
81
+ "INVALID_RESOURCE_DEFINITION",
82
+ "INVALID_ROUTE_DEFINITION",
83
+ "INVALID_SECRETS_DEFINITION",
84
+ "INVALID_SURGE_GENERAL",
85
+ "INVALID_SURGE_HOSTS",
86
+ "LOGICAL_DEPTH_EXCEEDED",
87
+ "PROFILE_CONDITION_UNSUPPORTED",
88
+ "PROFILE_DESTINATION_UNSUPPORTED",
89
+ "PROFILE_ENDPOINT_UNSUPPORTED",
90
+ "PROFILE_EXTENSION_UNSUPPORTED",
91
+ "PROFILE_GROUP_MEMBER_UNSUPPORTED",
92
+ "PROFILE_GROUP_OPTIONS_UNSUPPORTED",
93
+ "PROFILE_TARGET_UNSUPPORTED",
94
+ "RULESET_COMPOSITION_UNSUPPORTED",
95
+ "UNKNOWN_DESTINATION_ID",
96
+ "UNREGISTERED_DESTINATION_INSTANCE",
97
+ "UNSUPPORTED_GROUP_ALGORITHM"
98
+ ]);
99
+ function validDiagnosticPath(path) {
100
+ return typeof path === "string" && /^(dns|surge\.hosts)\[\d{1,4}\]$/.test(path);
101
+ }
102
+ function definitionDiagnostic(error) {
103
+ try {
104
+ if (!error || typeof error !== "object") return;
105
+ const name = Object.getOwnPropertyDescriptor(error, "name")?.value;
106
+ const code = Object.getOwnPropertyDescriptor(error, "code")?.value;
107
+ if (name !== "ProfileDefinitionError" || typeof code !== "string" || !definitionCodes.has(code)) return;
108
+ const paths = Object.getOwnPropertyDescriptor(error, "paths")?.value;
109
+ if (code === "DNS_HOSTS_CONFLICT" && Array.isArray(paths) && Object.getOwnPropertyDescriptor(paths, "length")?.value === 2) {
110
+ const first = Object.getOwnPropertyDescriptor(paths, "0")?.value;
111
+ const second = Object.getOwnPropertyDescriptor(paths, "1")?.value;
112
+ if (validDiagnosticPath(first) && validDiagnosticPath(second)) return {
113
+ code,
114
+ paths: [first, second]
115
+ };
116
+ }
117
+ return { code };
118
+ } catch {
119
+ return;
120
+ }
121
+ }
77
122
  var ProfileDefinitionError = class extends Error {
78
123
  code;
79
- constructor(code) {
124
+ paths;
125
+ constructor(code, paths) {
80
126
  super(code);
81
127
  this.code = code;
82
128
  this.name = "ProfileDefinitionError";
129
+ if (paths?.length === 2 && paths.every(validDiagnosticPath)) this.paths = Object.freeze([...paths]);
83
130
  }
84
131
  };
85
132
  const fail$1 = (code) => {
@@ -308,11 +355,28 @@ function lowerSurgeProfile(input) {
308
355
  }
309
356
  function condition(value) {
310
357
  inspectDefinition(value);
358
+ exactDefinition(value, [
359
+ "type",
360
+ "noResolve",
361
+ ...value.type === "ruleSet" ? [
362
+ "format",
363
+ "url",
364
+ "builtin",
365
+ "intervalSeconds"
366
+ ] : value.type === "all" || value.type === "any" ? ["conditions"] : value.type === "not" ? ["condition"] : value.type === "port" || value.type === "sourcePort" ? ["from", "to"] : ["value"],
367
+ ...[
368
+ "domain",
369
+ "domainSuffix",
370
+ "ruleSet"
371
+ ].includes(value.type) ? ["includeSniffed"] : []
372
+ ]);
373
+ if (value.includeSniffed !== void 0 && typeof value.includeSniffed !== "boolean") throw new ProfileDefinitionError("INVALID_MATCH_OPTIONS");
311
374
  return value;
312
375
  }
313
376
  function atom$2(type) {
314
- return (value, options = {}) => {
315
- inspectDefinition(options);
377
+ return (value, options) => {
378
+ inspectDefinition(options ?? {});
379
+ exactDefinition(options ?? {}, ["noResolve", ...["domain", "domainSuffix"].includes(type) ? ["includeSniffed"] : []]);
316
380
  return condition({
317
381
  ...options,
318
382
  type,
@@ -437,7 +501,7 @@ const nativeRuleSetSchema = z.discriminatedUnion("engine", [
437
501
  format: z.enum(["rule-set", "domain-set"]),
438
502
  intervalSeconds: updateInterval.optional(),
439
503
  noResolve: z.boolean().optional(),
440
- sources: domainSourcesSchema.optional()
504
+ includeSniffed: z.boolean().optional()
441
505
  }),
442
506
  z.strictObject({
443
507
  ...remoteBase,
@@ -467,12 +531,12 @@ const matchSchema = z.lazy(() => z.discriminatedUnion("type", [
467
531
  z.strictObject({
468
532
  type: z.literal("domain"),
469
533
  value: domain$1,
470
- sources: domainSourcesSchema.optional()
534
+ includeSniffed: z.boolean().optional()
471
535
  }),
472
536
  z.strictObject({
473
537
  type: z.literal("domainSuffix"),
474
538
  value: domain$1,
475
- sources: domainSourcesSchema.optional()
539
+ includeSniffed: z.boolean().optional()
476
540
  }),
477
541
  z.strictObject({
478
542
  type: z.literal("ipCidr"),
@@ -1013,7 +1077,11 @@ function evaluate(condition, request) {
1013
1077
  switch (condition.type) {
1014
1078
  case "domain":
1015
1079
  case "domainSuffix": {
1016
- const domains = (condition.sources ?? ["destination"]).map((source) => source === "destination" ? request.domain : request[source]);
1080
+ const domains = condition.includeSniffed ? [
1081
+ request.domain,
1082
+ request.tlsSni,
1083
+ request.httpHost
1084
+ ] : [request.domain];
1017
1085
  present = domains.some((value) => value !== void 0);
1018
1086
  matched = domains.some((value) => value !== void 0 && (value === condition.value || condition.type === "domainSuffix" && value.endsWith(`.${condition.value}`)));
1019
1087
  break;
@@ -1812,7 +1880,7 @@ function compile(input) {
1812
1880
  for (const rule of rules) if (logicalDepth(rule.when) > 10) error("LOGICAL_DEPTH", rule.id, "Surge 逻辑条件最多嵌套 10 层", target.id);
1813
1881
  }
1814
1882
  const checkOptions = (condition) => {
1815
- if ("sources" in condition && !supportsDomainSources(condition.sources, target.engine) || condition.type === "ipCidr" && condition.noResolve !== void 0 && target.engine === "sing-box") error("MATCH_OPTION_UNSUPPORTED", path, "目标无法等价实现显式匹配选项", target.id);
1883
+ if ("includeSniffed" in condition && condition.includeSniffed === true && target.engine !== "surge" || condition.type === "ipCidr" && condition.noResolve !== void 0 && target.engine === "sing-box") error("MATCH_OPTION_UNSUPPORTED", path, "目标无法等价实现显式匹配选项", target.id);
1816
1884
  if (condition.type === "all" || condition.type === "any") condition.conditions.forEach(checkOptions);
1817
1885
  else if (condition.type === "not") checkOptions(condition.condition);
1818
1886
  else if (condition.type === "ruleSet") checkOptions(condition.when);
@@ -1905,6 +1973,18 @@ function explain(compilation, target, request) {
1905
1973
  }
1906
1974
  //#endregion
1907
1975
  //#region src/secrets.ts
1976
+ const failures = /* @__PURE__ */ new WeakMap();
1977
+ function secretFailure(error) {
1978
+ return error !== null && typeof error === "object" ? failures.get(error) ?? {} : {};
1979
+ }
1980
+ function failure(code, name, reason) {
1981
+ const error = new RenderError(code);
1982
+ if (/^[A-Z][A-Z0-9_]{0,127}$/.test(name)) failures.set(error, Object.freeze({
1983
+ secretName: name,
1984
+ secretReason: reason
1985
+ }));
1986
+ return error;
1987
+ }
1908
1988
  /** One reader per rendering batch; exceptions and missing values never disclose credentials. */
1909
1989
  function secretReader(resolveSecret) {
1910
1990
  const values = /* @__PURE__ */ new Map();
@@ -1913,10 +1993,11 @@ function secretReader(resolveSecret) {
1913
1993
  let value;
1914
1994
  try {
1915
1995
  value = resolveSecret(token);
1916
- } catch {
1917
- throw new RenderError("SECRET_RESOLUTION_FAILED");
1996
+ } catch (error) {
1997
+ const nested = secretFailure(error);
1998
+ throw failure("SECRET_RESOLUTION_FAILED", token.name, nested.secretName === token.name && nested.secretReason === "MISSING" ? "MISSING" : "RESOLUTION_FAILED");
1918
1999
  }
1919
- if (typeof value !== "string" || value.length === 0) throw new RenderError("SECRET_MISSING");
2000
+ if (typeof value !== "string" || value.length === 0) throw failure("SECRET_MISSING", token.name, "MISSING");
1920
2001
  values.set(token.name, value);
1921
2002
  return value;
1922
2003
  };
@@ -2063,14 +2144,15 @@ const groupSchema = z.strictObject({
2063
2144
  intervalSeconds: z.number().int().positive().max(2147483647).optional(),
2064
2145
  timeoutSeconds: z.number().int().positive().max(3600).optional()
2065
2146
  });
2066
- const options$1 = {
2067
- noResolve: z.boolean().optional(),
2068
- sources: domainSourcesSchema.optional()
2147
+ const options$1 = { noResolve: z.boolean().optional() };
2148
+ const domainOptions = {
2149
+ ...options$1,
2150
+ includeSniffed: z.boolean().optional()
2069
2151
  };
2070
2152
  const atom = (type, value) => z.strictObject({
2071
2153
  type: z.literal(type),
2072
2154
  value,
2073
- ...options$1
2155
+ ...["domain", "domainSuffix"].includes(type) ? domainOptions : options$1
2074
2156
  });
2075
2157
  const conditionSchema = z.lazy(() => z.union([
2076
2158
  atom("domain", domain),
@@ -2107,7 +2189,7 @@ const conditionSchema = z.lazy(() => z.union([
2107
2189
  url: url.optional(),
2108
2190
  builtin: z.enum(["LAN", "SYSTEM"]).optional(),
2109
2191
  intervalSeconds: z.number().int().min(60).max(2147483647).optional(),
2110
- ...options$1
2192
+ ...domainOptions
2111
2193
  }).refine((v) => v.url !== void 0 !== (v.builtin !== void 0))
2112
2194
  ]));
2113
2195
  const managedSchema = z.strictObject({
@@ -2240,12 +2322,11 @@ function compileSurgeProfile(input) {
2240
2322
  "ipCidr6",
2241
2323
  "ruleSet"
2242
2324
  ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
2243
- if (c.sources !== void 0 && ![
2325
+ if (c.includeSniffed !== void 0 && ![
2244
2326
  "domain",
2245
2327
  "domainSuffix",
2246
2328
  "ruleSet"
2247
2329
  ].includes(c.type)) error("RULE_OPTION_UNSUPPORTED");
2248
- if (c.sources !== void 0 && !supportsDomainSources(c.sources, "surge")) error("MATCH_OPTION_UNSUPPORTED");
2249
2330
  if (p.target.platform === "ios" && ["processName", "macAddress"].includes(c.type)) error("PLATFORM_RULE_UNSUPPORTED");
2250
2331
  if (c.type === "all" || c.type === "any") for (const child of c.conditions) checkCondition(child, depth + 1);
2251
2332
  if (c.type === "not") checkCondition(c.condition, depth + 1);
@@ -2284,7 +2365,7 @@ function compileSurgeProfile(input) {
2284
2365
  function conditionOptions(c) {
2285
2366
  return [
2286
2367
  ...c.noResolve ? ["no-resolve"] : [],
2287
- ...extendedDomainSources(c.sources) ? ["extended-matching"] : [],
2368
+ ..."includeSniffed" in c && c.includeSniffed ? ["extended-matching"] : [],
2288
2369
  ...c.type === "ruleSet" && c.intervalSeconds !== void 0 ? [`update-interval=${c.intervalSeconds}`] : []
2289
2370
  ];
2290
2371
  }
@@ -2490,7 +2571,15 @@ function defineProfile(input) {
2490
2571
  ...input.surge.hosts === void 0 ? {} : { hosts: flatten(input.surge.hosts) }
2491
2572
  };
2492
2573
  }
2493
- if (dns?.length && surge?.hosts?.length) fail("DNS_HOSTS_CONFLICT");
2574
+ if (dns?.length && surge?.hosts?.length) {
2575
+ if (dns.length + surge.hosts.length > 2e3) fail("INVALID_SURGE_HOSTS");
2576
+ const patterns = new Map(dns.map((entry, index) => [entry.pattern.toLowerCase(), index]));
2577
+ for (const [index, host] of surge.hosts.entries()) {
2578
+ if (typeof host?.pattern !== "string") fail("INVALID_SURGE_HOSTS");
2579
+ const dnsIndex = patterns.get(host.pattern.toLowerCase());
2580
+ if (dnsIndex !== void 0) throw new ProfileDefinitionError("DNS_HOSTS_CONFLICT", [`dns[${dnsIndex}]`, `surge.hosts[${index}]`]);
2581
+ }
2582
+ }
2494
2583
  const { dns: _dns, surge: _surge, proxies: _proxies, groups: _groups, routes: _routes, ...rest } = input;
2495
2584
  return snapshotProfile({
2496
2585
  ...rest,
@@ -2523,7 +2612,7 @@ function surgeCondition$1(condition, depth = 0) {
2523
2612
  url: value.url,
2524
2613
  ...value.intervalSeconds !== void 0 ? { intervalSeconds: value.intervalSeconds } : {},
2525
2614
  ...value.noResolve !== void 0 ? { noResolve: value.noResolve } : {},
2526
- ...value.sources !== void 0 ? { sources: value.sources } : {}
2615
+ ...value.includeSniffed !== void 0 ? { includeSniffed: value.includeSniffed } : {}
2527
2616
  };
2528
2617
  }
2529
2618
  if (condition.type === "all" || condition.type === "any") {
@@ -2552,6 +2641,25 @@ function compileProfile(input) {
2552
2641
  try {
2553
2642
  const profile = defineProfile(input);
2554
2643
  snapshotDefinition(profile.routes.map((route) => route.when));
2644
+ const ruleSets = [];
2645
+ const collectRuleSets = (condition) => {
2646
+ if (condition.type === "nativeRuleSet" || condition.type === "ruleSet" && "when" in condition) {
2647
+ const parsed = matchSchema.safeParse(condition);
2648
+ if (!parsed.success) return fail("PROFILE_CONDITION_UNSUPPORTED");
2649
+ ruleSets.push({
2650
+ type: "rule",
2651
+ id: `ruleset-${ruleSets.length}`,
2652
+ when: parsed.data,
2653
+ then: { type: "direct" }
2654
+ });
2655
+ } else if (condition.type === "all" || condition.type === "any") condition.conditions.forEach(collectRuleSets);
2656
+ else if (condition.type === "not") collectRuleSets(condition.condition);
2657
+ };
2658
+ profile.routes.forEach((route) => collectRuleSets(route.when));
2659
+ const ruleSetDiagnostics = [];
2660
+ validateRuleSets(ruleSets, profile.target.engine, ruleSetDiagnostics, "routes");
2661
+ const ruleSetError = ruleSetDiagnostics.find((diagnostic) => diagnostic.severity === "error");
2662
+ if (ruleSetError) return fail(ruleSetError.code);
2555
2663
  const nodes = profile.proxies.filter((proxy) => !isEndpoint(proxy));
2556
2664
  const endpoints = profile.proxies.filter(isEndpoint);
2557
2665
  if (profile.target.engine === "surge") {
@@ -2560,7 +2668,7 @@ function compileProfile(input) {
2560
2668
  const compilation = compileSurgeProfile(lowerSurgeProfile({
2561
2669
  target: profile.target,
2562
2670
  ...profile.surge,
2563
- ...profile.dns?.length ? { hosts: profile.dns } : {},
2671
+ ...profile.dns?.length ? { hosts: [...profile.dns, ...profile.surge?.hosts ?? []] } : {},
2564
2672
  nodes,
2565
2673
  tunnels: endpoints,
2566
2674
  groups: profile.groups,
@@ -2677,7 +2785,8 @@ function compileProfile(input) {
2677
2785
  return {
2678
2786
  engine: "invalid",
2679
2787
  ok: false,
2680
- code: error instanceof ProfileDefinitionError ? error.code : "INVALID_PROFILE_DEFINITION"
2788
+ code: error instanceof ProfileDefinitionError ? error.code : "INVALID_PROFILE_DEFINITION",
2789
+ ...error instanceof ProfileDefinitionError && error.paths ? { paths: error.paths } : {}
2681
2790
  };
2682
2791
  }
2683
2792
  }
@@ -2715,15 +2824,18 @@ function dnsRule(pattern, server) {
2715
2824
  if (!checked.success) throw new ProfileDefinitionError("INVALID_DNS_RULE");
2716
2825
  return batch ? checked.data : checked.data[0];
2717
2826
  }
2718
- const ruleSet = (definition) => ({
2719
- ...definition,
2720
- type: "ruleSet"
2721
- });
2827
+ const ruleSet = (definition) => {
2828
+ inspectDefinition(definition);
2829
+ exactDefinition(definition, ["id", "when"]);
2830
+ return snapshotDefinition({
2831
+ ...definition,
2832
+ type: "ruleSet"
2833
+ });
2834
+ };
2722
2835
  function options(value, keys) {
2723
2836
  inspectDefinition(value);
2724
2837
  exactDefinition(value, keys);
2725
- if ("sources" in value && value.sources !== void 0 && !domainSourcesSchema.safeParse(value.sources).success) throw new ProfileDefinitionError("INVALID_DOMAIN_SOURCES");
2726
- if (Object.entries(value).some(([key, v]) => key !== "sources" && v !== void 0 && typeof v !== "boolean")) throw new ProfileDefinitionError("INVALID_MATCH_OPTIONS");
2838
+ if (Object.values(value).some((v) => v !== void 0 && typeof v !== "boolean")) throw new ProfileDefinitionError("INVALID_MATCH_OPTIONS");
2727
2839
  return snapshotDefinition(value);
2728
2840
  }
2729
2841
  const match = {
@@ -2738,12 +2850,12 @@ const match = {
2738
2850
  domain: (value, opts = {}) => ({
2739
2851
  type: "domain",
2740
2852
  value,
2741
- ...options(opts, ["sources"])
2853
+ ...options(opts, ["includeSniffed"])
2742
2854
  }),
2743
2855
  domainSuffix: (value, opts = {}) => ({
2744
2856
  type: "domainSuffix",
2745
2857
  value,
2746
- ...options(opts, ["sources"])
2858
+ ...options(opts, ["includeSniffed"])
2747
2859
  }),
2748
2860
  ipCidr: (value, opts = {}) => ({
2749
2861
  type: "ipCidr",
@@ -2791,7 +2903,7 @@ function nativeConstructor(engine) {
2791
2903
  "format",
2792
2904
  "intervalSeconds",
2793
2905
  "noResolve",
2794
- "sources",
2906
+ "includeSniffed",
2795
2907
  "behavior",
2796
2908
  "to"
2797
2909
  ]);
@@ -2802,7 +2914,7 @@ function nativeConstructor(engine) {
2802
2914
  "url",
2803
2915
  "format",
2804
2916
  "intervalSeconds",
2805
- ...engine === "surge" ? ["noResolve", "sources"] : engine === "mihomo" ? ["behavior"] : []
2917
+ ...engine === "surge" ? ["noResolve", "includeSniffed"] : engine === "mihomo" ? ["behavior"] : []
2806
2918
  ]);
2807
2919
  const parsed = nativeRuleSetSchema.safeParse({
2808
2920
  ...engine === "surge" ? { format: "rule-set" } : {},
@@ -3102,7 +3214,7 @@ function surgeOptions(condition) {
3102
3214
  return [
3103
3215
  ...condition.type === "ipCidr" && condition.noResolve !== false ? ["no-resolve"] : [],
3104
3216
  ...condition.type === "nativeRuleSet" && condition.engine === "surge" && condition.noResolve ? ["no-resolve"] : [],
3105
- ..."sources" in condition && extendedDomainSources(condition.sources) ? ["extended-matching"] : []
3217
+ ..."includeSniffed" in condition && condition.includeSniffed ? ["extended-matching"] : []
3106
3218
  ].map((value) => `,${value}`).join("");
3107
3219
  }
3108
3220
  function surgeCondition(condition) {
@@ -3272,7 +3384,10 @@ async function buildToDirectory(compilation, output, resolveSecret = (token) =>
3272
3384
  code = "PUBLISHED";
3273
3385
  } catch (error) {
3274
3386
  code = error instanceof RenderError ? error.code : "OUTPUT_FAILED";
3275
- detail = error instanceof RenderError ? { hint: buildHints[code] } : outputFailure(error);
3387
+ detail = error instanceof RenderError ? {
3388
+ hint: buildHints[code],
3389
+ ...secretFailure(error)
3390
+ } : outputFailure(error);
3276
3391
  } finally {
3277
3392
  if (locked) {
3278
3393
  try {
@@ -3407,7 +3522,8 @@ function compileBatch(profiles, output) {
3407
3522
  const entries = Object.entries(profiles);
3408
3523
  const compiled = [];
3409
3524
  let outputDirectoryChecked = false;
3410
- const result = (code) => ({
3525
+ const result = (code, paths) => ({
3526
+ ...paths ? { paths } : {},
3411
3527
  ok: code === "CHECKED",
3412
3528
  code,
3413
3529
  entries,
@@ -3417,7 +3533,7 @@ function compileBatch(profiles, output) {
3417
3533
  if (!entries.length || entries.length > 16 || entries.some(([id]) => !/^[a-z0-9][a-z0-9-]*$/.test(id))) return result("INVALID_PROFILE_FILENAMES");
3418
3534
  compiled.push(...entries.map(([, profile]) => compileProfile(profile)));
3419
3535
  const invalid = compiled.find((profile) => !profile.ok);
3420
- if (invalid) return result(invalid.engine === "invalid" ? invalid.code : "COMPILATION_FAILED");
3536
+ if (invalid) return result(invalid.engine === "invalid" ? invalid.code : "COMPILATION_FAILED", invalid.engine === "invalid" ? invalid.paths : void 0);
3421
3537
  if (output !== void 0) {
3422
3538
  outputDirectoryChecked = true;
3423
3539
  if (compiled.some((profile) => profile.engine === "sing-box" && profile.compilation.plans.some((plan) => plan.program.endpoints?.some((endpoint) => pathsOverlap(output, endpoint.stateDirectory))))) return result("ENDPOINT_STATE_OVERLAP");
@@ -3450,6 +3566,7 @@ function checkBuild(input) {
3450
3566
  ok: profile.ok,
3451
3567
  ...profile.engine === "invalid" ? {
3452
3568
  code: profile.code,
3569
+ ...profile.paths ? { paths: profile.paths } : {},
3453
3570
  diagnostics: []
3454
3571
  } : { diagnostics: profile.compilation.diagnostics }
3455
3572
  }))
@@ -3461,7 +3578,8 @@ async function publish(profiles, output, readSecret) {
3461
3578
  if (!checked.ok) return {
3462
3579
  published: false,
3463
3580
  exitCode: 1,
3464
- code: checked.code
3581
+ code: checked.code,
3582
+ ...checked.paths ? { paths: checked.paths } : {}
3465
3583
  };
3466
3584
  const { entries, compiled } = checked;
3467
3585
  const read = secretReader(readSecret);
@@ -3489,7 +3607,8 @@ async function publish(profiles, output, readSecret) {
3489
3607
  return {
3490
3608
  published: false,
3491
3609
  exitCode: 1,
3492
- code: error instanceof RenderError ? error.code : "BUILD_FAILED"
3610
+ code: error instanceof RenderError ? error.code : "BUILD_FAILED",
3611
+ ...secretFailure(error)
3493
3612
  };
3494
3613
  }
3495
3614
  }
@@ -3578,4 +3697,4 @@ async function runBuild(input, output, options = {}) {
3578
3697
  };
3579
3698
  }
3580
3699
  //#endregion
3581
- export { outbound as $, renderSurgeProfiles as A, validateProxyOptions as B, strategy as C, defineProfile as D, compileProfile as E, isReservedNativeName as F, nodeSchema as G, assertData as H, nativeNameSchema as I, defineProxyGroup as J, requestSchema as K, targetCatalog as L, compile as M, explain as N, compileSurgeProfile as O, compileStrategyGroups as P, inspectDefinition as Q, RenderError as R, slot as S, use as T, deepFreeze as U, StaticRuleSetUnknownError as V, idSchema as W, defineRoutes as X, defineRoute as Y, exactDefinition as Z, rule as _, render as a, sequence as b, direct as c, match as d, mihomo as f, route as g, reject as h, buildToDirectory as i, secretReader as j, renderSurgeProfile as k, dnsRule as l, proxy as m, defineBuild as n, block as o, policy as p, ProfileDefinitionError as q, runBuild as r, defineConfig as s, checkBuild as t, group as u, ruleSet as v, surge$1 as w, singbox$1 as x, secret as y, surgeProxy as z };
3700
+ export { inspectDefinition as $, renderSurgeProfiles as A, validateProxyOptions as B, strategy as C, defineProfile as D, compileProfile as E, isReservedNativeName as F, nodeSchema as G, assertData as H, nativeNameSchema as I, defineProxyGroup as J, requestSchema as K, targetCatalog as L, compile as M, explain as N, compileSurgeProfile as O, compileStrategyGroups as P, exactDefinition as Q, RenderError as R, slot as S, use as T, deepFreeze as U, StaticRuleSetUnknownError as V, idSchema as W, defineRoutes as X, defineRoute as Y, definitionDiagnostic as Z, rule as _, render as a, sequence as b, direct as c, match as d, outbound as et, mihomo as f, route as g, reject as h, buildToDirectory as i, secretReader as j, renderSurgeProfile as k, dnsRule as l, proxy as m, defineBuild as n, block as o, policy as p, ProfileDefinitionError as q, runBuild as r, defineConfig as s, checkBuild as t, group as u, ruleSet as v, surge$1 as w, singbox$1 as x, secret as y, surgeProxy as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proxylang",
3
- "version": "0.8.0",
3
+ "version": "0.9.1",
4
4
  "description": "Composable routing policies in TypeScript with explicit platform targets",
5
5
  "homepage": "https://github.com/CorrectRoadH/proxylang#readme",
6
6
  "bugs": {