proxylang 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -28,7 +28,7 @@ npm install --save-exact proxylang@0.3.0
28
28
  npx proxylang --help
29
29
  ```
30
30
 
31
- 将下面的 Usage 示例保存为 `proxy.config.ts`,即可执行 `npx proxylang check proxy.config.ts`。
31
+ 将下面的 Usage 示例保存为 `proxylang.config.ts`,即可执行 `npx proxylang check`。
32
32
 
33
33
  若要运行仓库里的完整示例,另需 **Vite+ 1.3.0**:
34
34
 
@@ -39,15 +39,16 @@ vp install --frozen-lockfile
39
39
  vp run build
40
40
 
41
41
  # 检查现成的四客户端示例,不读取密码
42
- vp exec node dist/cli.js check examples/clients.ts
42
+ cd examples/clients
43
+ vp exec node ../../dist/cli.js check
43
44
 
44
45
  # 用测试密码生成配置,不会启动代理
45
- DEMO_PASSWORD=example-only vp exec node dist/cli.js build examples/clients.ts --out out/clients
46
+ DEMO_PASSWORD=example-only vp exec node ../../dist/cli.js build
46
47
  ```
47
48
 
48
49
  仓库开发统一使用 Vite+:`vp run dev` 监听构建,`vp run check` 检查源码,`vp run verify` 完成源码与隔离安装包验收。`vp add` / `vp remove` 管理依赖,提交更新后的 `package-lock.json`。
49
50
 
50
- [四客户端示例](examples/clients.ts)展示完整配置;下面从规则开始,逐步写出自己的版本。
51
+ [四客户端示例](examples/clients/proxylang.config.ts)展示完整配置;下面从规则开始,逐步写出自己的版本。
51
52
 
52
53
  ## 直接组合设备配置
53
54
 
@@ -82,7 +83,7 @@ const laptop = defineProfile({
82
83
 
83
84
  ## Usage
84
85
 
85
- 将下面三个 TypeScript 代码块按顺序保存为项目中的 `proxy.config.ts`。
86
+ 将下面三个 TypeScript 代码块按顺序保存为项目中的 `proxylang.config.ts`。
86
87
 
87
88
  ### 1. 组合规则,给出口留一个位置
88
89
 
@@ -200,6 +201,7 @@ const program = (engine: Engine): Program => ({
200
201
  });
201
202
 
202
203
  export default defineConfig({
204
+ outDir: "out",
203
205
  programs: {
204
206
  desktop: program("surge"),
205
207
  backup: program("sing-box"),
@@ -225,14 +227,14 @@ export default defineConfig({
225
227
 
226
228
  ```sh
227
229
  # 检查所有目标和请求案例
228
- npx proxylang check proxy.config.ts
230
+ npx proxylang check
229
231
 
230
232
  # 查看请求命中了哪条规则,以及规则来自哪个模板
231
- npx proxylang explain proxy.config.ts --target backup \
233
+ npx proxylang explain --target backup \
232
234
  --request '{"network":"tcp","domain":"github.com","port":443}'
233
235
 
234
236
  # 用测试密码构建;实际使用时由环境提供真实凭据
235
- PROXY_PASSWORD=example-only npx proxylang build proxy.config.ts --out out
237
+ PROXY_PASSWORD=example-only npx proxylang build
236
238
  ```
237
239
 
238
240
  `explain` 展示条件匹配与逻辑出口,不模拟节点测速或网络连通性。`build` 生成原生配置,整批成功后更新 `out/active.json`,其中列出各目标文件路径;一个目标失败不会替换上一批结果。
@@ -246,7 +248,7 @@ PROXY_PASSWORD=example-only npx proxylang build proxy.config.ts --out out
246
248
  把请求元数据保存为 UTF-8 JSON,避免 shell 转义:
247
249
 
248
250
  ```sh
249
- npx proxylang explain proxy.config.ts --target backup --request-file request.json
251
+ npx proxylang explain --target backup --request-file request.json
250
252
  npx proxylang build --help
251
253
  ```
252
254
 
@@ -276,7 +278,7 @@ const mediaRule = rule("media", match.all(match.network("tcp"), media), direct()
276
278
 
277
279
  Surge 顶层引用可设置 `intervalSeconds`;嵌套逻辑使用客户端默认更新间隔,显式间隔暂报不支持。sing-box 与 Mihomo 的更新间隔是必填项,嵌套组合仍引用独立声明的资源。Stash 原生外部规则入口尚未实现。
278
280
 
279
- 完整的三平台组合与构建示例见 [examples/rule-sets.ts](examples/rule-sets.ts)。示例 URL 仅展示语法,实际使用时替换为自己的规则源。更完整的平台逃生舱边界见[设计说明](docs/engineering/composable-rule-sets/README.md)。
281
+ 完整的三平台组合与构建示例见 [examples/rule-sets/proxylang.config.ts](examples/rule-sets/proxylang.config.ts)。示例 URL 仅展示语法,实际使用时替换为自己的规则源。更完整的平台逃生舱边界见[设计说明](docs/engineering/composable-rule-sets/README.md)。
280
282
 
281
283
  ## 定义代理节点
282
284
 
@@ -383,12 +385,13 @@ const backup: Program = {
383
385
 
384
386
  构建只生成配置,不加入 tailnet、不创建身份目录、不启用 MagicDNS。状态目录应由单个运行实例独占,并独立于构建产物;端点暂不能放进策略组或作为 `via`。这是本机显式代理配置,尚不是 TUN 网关或已验收的整机备份。
385
387
 
386
- [完整节点与 Tailscale 示例](examples/proxies.ts)包含五个构建目标和共用规则,可直接检查:
388
+ [完整节点与 Tailscale 示例](examples/proxies/proxylang.config.ts)包含五个构建目标和共用规则,可直接检查:
387
389
 
388
390
  ```sh
389
- vp exec node dist/cli.js check examples/proxies.ts
391
+ cd examples/proxies
392
+ vp exec node ../../dist/cli.js check
390
393
  DEMO_PASSWORD=example-only DEMO_UUID=11111111-2222-4333-8444-555555555555 \
391
- vp exec node dist/cli.js build examples/proxies.ts --out out/proxies
394
+ vp exec node ../../dist/cli.js build
392
395
  ```
393
396
 
394
397
  ## 当前支持
@@ -408,9 +411,9 @@ Stash 当前拒绝来源 IP/端口、端口范围和组级 URLTest。完整配
408
411
 
409
412
  ## 更多示例与文档
410
413
 
411
- - [代理协议与 Tailscale](examples/proxies.ts):SS/VMess/VLESS 节点和独立家庭网络端点。
412
- - [四客户端共用规则](examples/clients.ts):同一个 policy,不同平台策略。
414
+ - [代理协议与 Tailscale](examples/proxies/proxylang.config.ts):SS/VMess/VLESS 节点和独立家庭网络端点。
415
+ - [四客户端共用规则](examples/clients/proxylang.config.ts):同一个 policy,不同平台策略。
413
416
  - [家庭与开发环境规则](examples/policies.ts):规则模块、守卫与出口绑定。
414
- - [多设备配置与请求案例](examples/home.ts):节点筛选、代理链和路由回归案例。
417
+ - [多设备配置与请求案例](examples/home/proxylang.config.ts):节点筛选、代理链和路由回归案例。
415
418
  - [设计与使用文档](docs/README.md):规则组合、平台机制、CLI 与构建边界。
416
419
  - [开发工作流](docs/engineering/development/README.md):Concord 管理 Feature 与 Use Case,`vp` 负责构建和测试。
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
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 profileBuildFailure, r as runBuild } from "./profile-build-Cokl8MBF.js";
3
- import { open } from "node:fs/promises";
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-DX7t23HZ.js";
3
+ import { lstat, open, stat } from "node:fs/promises";
4
4
  import { resolve } from "node:path";
5
5
  import { pathToFileURL } from "node:url";
6
6
  import { constants } from "node:fs";
@@ -15,11 +15,10 @@ const failure = (code) => {
15
15
  return 1;
16
16
  };
17
17
  const usages = {
18
- "profile-build": ["proxylang profile-build config.ts --out DIRECTORY [--validation]"],
19
18
  targets: ["proxylang targets"],
20
- check: ["proxylang check config.ts"],
21
- explain: ["proxylang explain config.ts --target ID --request JSON", "proxylang explain config.ts --target ID --request-file FILE"],
22
- build: ["proxylang build config.ts --out DIRECTORY"]
19
+ check: ["proxylang check"],
20
+ explain: ["proxylang explain --target ID --request JSON", "proxylang explain --target ID --request-file FILE"],
21
+ build: ["proxylang build [--validation]"]
23
22
  };
24
23
  async function readRequestFile(path) {
25
24
  const limit = 1048576;
@@ -71,39 +70,56 @@ function loadFailure(cause) {
71
70
  return 1;
72
71
  }
73
72
  async function main(args) {
74
- const [command, file, ...rest] = args;
73
+ const root = process.cwd();
74
+ const [command, ...rest] = args;
75
75
  if (command === "targets" && args.length === 1) {
76
76
  print(targetCatalog);
77
77
  return 0;
78
78
  }
79
79
  const help = (value) => value === "--help" || value === "-h";
80
- if (!command || help(command) && args.length === 1 || Object.hasOwn(usages, command) && help(file) && args.length === 2) {
80
+ if (!command || help(command) && args.length === 1 || Object.hasOwn(usages, command) && help(rest[0]) && rest.length === 1) {
81
81
  print({
82
82
  usage: command && Object.hasOwn(usages, command) ? usages[command] : Object.values(usages).flat(),
83
+ configFile: "proxylang.config.ts",
83
84
  trustedConfig: true
84
85
  });
85
86
  return 0;
86
87
  }
87
- if (command === "profile-build") return profileBuildCommand(file, rest);
88
88
  if (![
89
89
  "check",
90
90
  "explain",
91
91
  "build"
92
- ].includes(command) || !file?.trim() || help(file)) return failure("INVALID_ARGUMENTS");
92
+ ].includes(command)) return failure("INVALID_ARGUMENTS");
93
93
  const options = /* @__PURE__ */ new Map();
94
- for (let i = 0; i < rest.length; i += 2) {
95
- const key = rest[i];
96
- const value = rest[i + 1];
97
- if (!key.startsWith("--") || !value?.trim() || options.has(key)) return failure("INVALID_ARGUMENTS");
98
- options.set(key, value);
94
+ let validation = false;
95
+ if (command === "build") {
96
+ if (rest.length === 1 && rest[0] === "--validation" || rest.length === 2 && rest[0] === "--" && rest[1] === "--validation") validation = true;
97
+ else if (rest.length) return failure("INVALID_ARGUMENTS");
98
+ } else if (command === "check") {
99
+ if (rest.length) return failure("INVALID_ARGUMENTS");
100
+ } else {
101
+ for (let i = 0; i < rest.length; i += 2) {
102
+ const key = rest[i];
103
+ const value = rest[i + 1];
104
+ if (![
105
+ "--target",
106
+ "--request",
107
+ "--request-file"
108
+ ].includes(key) || !value?.trim() || value.startsWith("--") || options.has(key)) return failure("INVALID_ARGUMENTS");
109
+ options.set(key, value);
110
+ }
111
+ if (!options.has("--target") || options.has("--request") === options.has("--request-file")) return failure("INVALID_ARGUMENTS");
112
+ }
113
+ const file = resolve(root, "proxylang.config.ts");
114
+ let found = false;
115
+ try {
116
+ const info = await lstat(file);
117
+ found = true;
118
+ if (!(info.isSymbolicLink() ? (await stat(file)).isFile() : info.isFile())) return loadFailure({ code: "INVALID_CONFIG_FILE" });
119
+ } catch (cause) {
120
+ if (!found && cause && typeof cause === "object" && Object.getOwnPropertyDescriptor(cause, "code")?.value === "ENOENT") return failure("CONFIG_NOT_FOUND");
121
+ return loadFailure(cause);
99
122
  }
100
- const allowed = command === "check" ? [] : command === "build" ? ["--out"] : [
101
- "--target",
102
- "--request",
103
- "--request-file"
104
- ];
105
- const required = command === "check" ? [] : command === "build" ? ["--out"] : ["--target"];
106
- if ([...options.keys()].some((key) => !allowed.includes(key)) || required.some((key) => !options.has(key)) || command === "explain" && options.has("--request") === options.has("--request-file")) return failure("INVALID_ARGUMENTS");
107
123
  let config;
108
124
  try {
109
125
  const loaded = await tsImport(pathToFileURL(resolve(file)).href, import.meta.url);
@@ -111,6 +127,31 @@ async function main(args) {
111
127
  } catch (cause) {
112
128
  return loadFailure(cause);
113
129
  }
130
+ if (config && typeof config === "object" ? Object.getOwnPropertyDescriptor(config, "profiles") : void 0) {
131
+ let definition;
132
+ try {
133
+ definition = defineBuild(config);
134
+ if (definition.outDir !== void 0) definition = {
135
+ ...definition,
136
+ outDir: resolve(root, definition.outDir)
137
+ };
138
+ } catch {
139
+ return failure("INVALID_BUILD_DEFINITION");
140
+ }
141
+ if (command !== "build") {
142
+ const checked = checkBuild(definition);
143
+ if (!checked.ok || command === "check") {
144
+ print(checked);
145
+ return checked.ok ? 0 : 1;
146
+ }
147
+ return failure("EXPLAIN_PROFILE_UNSUPPORTED");
148
+ }
149
+ if (definition.outDir === void 0) return failure("OUTPUT_DIRECTORY_REQUIRED");
150
+ const built = await runBuild(definition, definition.outDir, { validation });
151
+ print(built);
152
+ return built.exitCode;
153
+ }
154
+ if (validation) return failure("VALIDATION_PROFILE_REQUIRED");
114
155
  const result = compile(config);
115
156
  if (!result.ok) {
116
157
  print({
@@ -139,7 +180,7 @@ async function main(args) {
139
180
  if (command === "explain") {
140
181
  let source = options.get("--request");
141
182
  if (options.has("--request-file")) try {
142
- source = await readRequestFile(options.get("--request-file"));
183
+ source = await readRequestFile(resolve(root, options.get("--request-file")));
143
184
  } catch (cause) {
144
185
  return failure(cause instanceof Error && cause.message === "REQUEST_FILE_TOO_LARGE" ? "REQUEST_FILE_TOO_LARGE" : "REQUEST_FILE_READ_FAILED");
145
186
  }
@@ -158,46 +199,15 @@ async function main(args) {
158
199
  });
159
200
  return 0;
160
201
  }
161
- const built = await buildToDirectory(result, options.get("--out"));
202
+ const outDir = Object.getOwnPropertyDescriptor(config, "outDir")?.value;
203
+ if (outDir === void 0) return failure("OUTPUT_DIRECTORY_REQUIRED");
204
+ const built = await buildToDirectory(result, resolve(root, outDir));
162
205
  print({
163
206
  ...built,
164
207
  diagnostics: result.diagnostics
165
208
  });
166
209
  return built.exitCode;
167
210
  }
168
- async function profileBuildCommand(file, args) {
169
- const invalid = () => {
170
- print(profileBuildFailure("INVALID_ARGUMENTS"));
171
- return 1;
172
- };
173
- if (!file?.trim() || file.startsWith("-")) return invalid();
174
- let output;
175
- let validation = false;
176
- for (let i = 0; i < args.length; i++) {
177
- const arg = args[i];
178
- if (arg === "--out" && output === void 0) {
179
- const value = args[++i];
180
- if (!value?.trim() || value.startsWith("-")) return invalid();
181
- output = value;
182
- } else if (arg === "--validation" && !validation) validation = true;
183
- else if (arg === "--" && output !== void 0 && !validation && i === args.length - 2 && args[i + 1] === "--validation") {
184
- validation = true;
185
- i++;
186
- } else return invalid();
187
- }
188
- if (output === void 0) return invalid();
189
- let config;
190
- try {
191
- const loaded = await tsImport(pathToFileURL(resolve(file)).href, import.meta.url);
192
- config = loaded.default?.__esModule === true ? loaded.default.default : loaded.default;
193
- } catch {
194
- print(profileBuildFailure("PROFILE_DEFINITION_FAILED", validation));
195
- return 1;
196
- }
197
- const result = await runBuild(config, output, { validation });
198
- print(result);
199
- return result.exitCode;
200
- }
201
211
  try {
202
212
  process.exitCode = await main(process.argv.slice(2));
203
213
  } catch (cause) {
package/dist/index.d.ts CHANGED
@@ -281,6 +281,7 @@ export type PolicyCase = {
281
281
  };
282
282
  };
283
283
  export type Config = {
284
+ readonly outDir?: string;
284
285
  readonly programs: Readonly<Record<string, Program>>;
285
286
  readonly targets: readonly Target[];
286
287
  readonly cases?: readonly PolicyCase[];
@@ -1121,10 +1122,25 @@ export declare function compileProxyNodes(input: unknown): ProxyNodeCompilation;
1121
1122
  export declare function renderProxyNodes(compilation: ProxyNodeCompilation, resolveSecret: (token: Secret) => string | undefined): ProxyNodeArtifact;
1122
1123
  //#endregion
1123
1124
  //#region src/profile-build.d.ts
1125
+ type ProfileCheckResult = {
1126
+ readonly ok: boolean;
1127
+ readonly code: string;
1128
+ readonly profileCount: number;
1129
+ readonly outputDirectoryChecked: boolean;
1130
+ readonly profiles: readonly {
1131
+ readonly id: string;
1132
+ readonly engine: "surge" | "sing-box" | "invalid";
1133
+ readonly ok: boolean;
1134
+ readonly code?: string;
1135
+ readonly diagnostics: readonly Diagnostic[];
1136
+ }[];
1137
+ };
1138
+ export declare function checkBuild(input: BuildDefinition): ProfileCheckResult;
1124
1139
  type BuildContext = {
1125
1140
  readonly validation: boolean;
1126
1141
  };
1127
1142
  type BuildDefinition = {
1143
+ readonly outDir?: string;
1128
1144
  readonly profiles: Readonly<Record<string, Profile | ProfileDefinition>>;
1129
1145
  readonly preflight?: () => readonly string[];
1130
1146
  readonly resolveSecret?: (token: Secret, context: BuildContext) => string | undefined;
@@ -1145,4 +1161,4 @@ export declare function runBuild(input: BuildDefinition, output: string, options
1145
1161
  /** Stable identity independent of engine and mutable metadata. */
1146
1162
  export declare function proxyId(provider: string, label: string): string;
1147
1163
  //#endregion
1148
- export type { Artifact, BuildContext, BuildDefinition, BuildResult, CaseResult, Compilation, DeepReadonly, Fragments, Profile, ProfileBuildResult, ProfileCompilation, ProfileCondition, ProfileDefinition, ProfileDestination, ProfileProxy, ProxyBuilder, ProxyGroupDefinition, ProxyNodeArtifact, ProxyNodeCompilation, ProxyNodeInput, RouteDefinition, StrategyGroupCompilation, StrategyGroupInput, SurgeCondition, SurgeConfig, SurgeGeneral, SurgeGroup, SurgeHost, SurgePolicy, SurgeProfileArtifact, SurgeProfileCompilation, SurgeProfileInput, SurgeRule, SurgeTunnel, TargetPlan };
1164
+ export type { Artifact, BuildContext, BuildDefinition, BuildResult, CaseResult, Compilation, DeepReadonly, Fragments, Profile, ProfileBuildResult, ProfileCheckResult, ProfileCompilation, ProfileCondition, ProfileDefinition, ProfileDestination, ProfileProxy, ProxyBuilder, ProxyGroupDefinition, ProxyNodeArtifact, ProxyNodeCompilation, ProxyNodeInput, RouteDefinition, StrategyGroupCompilation, StrategyGroupInput, SurgeCondition, SurgeConfig, SurgeGeneral, SurgeGroup, SurgeHost, SurgePolicy, SurgeProfileArtifact, SurgeProfileCompilation, SurgeProfileInput, SurgeRule, SurgeTunnel, TargetPlan };
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { 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 selectProxies, 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 outbound, _ as ruleSet, a as render, b as sequence, c as direct, d as mihomo, f as policy, g as rule, h as route, i as buildToDirectory, j as secretReader, k as renderSurgeProfile, l as group, m as reject, o as block, p as proxy, q as ProfileDefinitionError, r as runBuild, s as defineConfig, t as defineBuild, u as match, v as secret, w as surge, x as singbox, y as selectNodes, z as surgeProxy } from "./profile-build-Cokl8MBF.js";
1
+ import { 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 selectProxies, 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 outbound, _ as ruleSet, a as render, b as sequence, c as direct, d as mihomo, f as policy, g as rule, h as route, i as buildToDirectory, j as secretReader, k as renderSurgeProfile, l as group, m as reject, n as defineBuild, o as block, p as proxy, q as ProfileDefinitionError, r as runBuild, s as defineConfig, t as checkBuild, u as match, v as secret, w as surge, x as singbox, y as selectNodes, z as surgeProxy } from "./profile-build-DX7t23HZ.js";
2
2
  import { createHash } from "node:crypto";
3
3
  import { z } from "zod";
4
4
  //#region src/proxy-fragments.ts
@@ -137,4 +137,4 @@ function proxyId(provider, label) {
137
137
  return `node-${createHash("sha256").update(JSON.stringify([provider, label])).digest("hex").slice(0, 16)}`;
138
138
  }
139
139
  //#endregion
140
- export { ProfileDefinitionError, RenderError, StaticRuleSetUnknownError, block, buildToDirectory, compile, compileProfile, compileProxyNodes, compileStrategyGroups, compileSurgeProfile, defineBuild, defineConfig, defineProfile, defineProxyGroup, defineRoute, defineRoutes, direct, explain, group, match, mihomo, outbound, policy, proxy, proxyId, reject, render, renderProxyNodes, renderSurgeProfile, renderSurgeProfiles, route, rule, ruleSet, runBuild, secret, selectNodes, selectProxies, sequence, singbox, slot, strategy, surge, targetCatalog, use };
140
+ export { ProfileDefinitionError, RenderError, StaticRuleSetUnknownError, block, buildToDirectory, checkBuild, compile, compileProfile, compileProxyNodes, compileStrategyGroups, compileSurgeProfile, defineBuild, defineConfig, defineProfile, defineProxyGroup, defineRoute, defineRoutes, direct, explain, group, match, mihomo, outbound, policy, proxy, proxyId, reject, render, renderProxyNodes, renderSurgeProfile, renderSurgeProfiles, route, rule, ruleSet, runBuild, secret, selectNodes, selectProxies, sequence, singbox, slot, strategy, surge, targetCatalog, use };
@@ -698,6 +698,7 @@ const requestSchema = z.strictObject({
698
698
  sourcePort: port$1.optional()
699
699
  });
700
700
  const configSchema = z.strictObject({
701
+ outDir: z.string().min(1).refine((value) => value.trim() === value && !value.includes("\0")).optional(),
701
702
  programs: z.record(idSchema, z.strictObject({
702
703
  engine: z.enum([
703
704
  "surge",
@@ -3388,26 +3389,67 @@ async function publishProfiles(files, surgeDirectory, io = { rename }) {
3388
3389
  }
3389
3390
  //#endregion
3390
3391
  //#region src/profile-build.ts
3391
- async function publish(profiles, output, resolver) {
3392
+ function compileBatch(profiles, output) {
3393
+ const entries = Object.entries(profiles);
3394
+ const compiled = [];
3395
+ let outputDirectoryChecked = false;
3396
+ const result = (code) => ({
3397
+ ok: code === "CHECKED",
3398
+ code,
3399
+ entries,
3400
+ compiled,
3401
+ outputDirectoryChecked
3402
+ });
3403
+ if (!entries.length || entries.length > 16 || entries.some(([id]) => !/^[a-z0-9][a-z0-9-]*$/.test(id))) return result("INVALID_PROFILE_FILENAMES");
3404
+ compiled.push(...entries.map(([, profile]) => compileProfile(profile)));
3405
+ const invalid = compiled.find((profile) => !profile.ok);
3406
+ if (invalid) return result(invalid.engine === "invalid" ? invalid.code : "COMPILATION_FAILED");
3407
+ if (output !== void 0) {
3408
+ outputDirectoryChecked = true;
3409
+ if (compiled.some((profile) => profile.engine === "sing-box" && profile.compilation.plans.some((plan) => plan.program.endpoints?.some((endpoint) => pathsOverlap(output, endpoint.stateDirectory))))) return result("ENDPOINT_STATE_OVERLAP");
3410
+ }
3411
+ return result("CHECKED");
3412
+ }
3413
+ function checkBuild(input) {
3414
+ const root = process.cwd();
3415
+ let definition;
3392
3416
  try {
3393
- const entries = Object.entries(profiles);
3394
- if (!entries.length || entries.length > 16 || entries.some(([id]) => !/^[a-z0-9][a-z0-9-]*$/.test(id))) return {
3395
- published: false,
3396
- exitCode: 1,
3397
- code: "INVALID_PROFILE_FILENAMES"
3398
- };
3399
- const compiled = entries.map(([, profile]) => compileProfile(profile));
3400
- const invalid = compiled.find((profile) => !profile.ok);
3401
- if (invalid) return {
3402
- published: false,
3403
- exitCode: 1,
3404
- code: invalid.engine === "invalid" ? invalid.code : "COMPILATION_FAILED"
3417
+ definition = defineBuild(input);
3418
+ } catch {
3419
+ return {
3420
+ ok: false,
3421
+ code: "INVALID_BUILD_DEFINITION",
3422
+ profileCount: 0,
3423
+ outputDirectoryChecked: false,
3424
+ profiles: []
3405
3425
  };
3406
- if (compiled.some((profile) => profile.engine === "sing-box" && profile.compilation.plans.some((plan) => plan.program.endpoints?.some((endpoint) => pathsOverlap(resolve(output), endpoint.stateDirectory))))) return {
3426
+ }
3427
+ const checked = compileBatch(definition.profiles, definition.outDir === void 0 ? void 0 : resolve(root, definition.outDir));
3428
+ return {
3429
+ ok: checked.ok,
3430
+ code: checked.code,
3431
+ profileCount: checked.entries.length,
3432
+ outputDirectoryChecked: checked.outputDirectoryChecked,
3433
+ profiles: checked.compiled.map((profile, index) => ({
3434
+ id: checked.entries[index][0],
3435
+ engine: profile.engine,
3436
+ ok: profile.ok,
3437
+ ...profile.engine === "invalid" ? {
3438
+ code: profile.code,
3439
+ diagnostics: []
3440
+ } : { diagnostics: profile.compilation.diagnostics }
3441
+ }))
3442
+ };
3443
+ }
3444
+ async function publish(profiles, output, resolver) {
3445
+ try {
3446
+ const checked = compileBatch(profiles, output);
3447
+ if (!checked.ok) return {
3407
3448
  published: false,
3408
3449
  exitCode: 1,
3409
- code: "ENDPOINT_STATE_OVERLAP"
3450
+ code: checked.code
3410
3451
  };
3452
+ const { entries, compiled } = checked;
3411
3453
  const read = secretReader(resolver);
3412
3454
  const files = /* @__PURE__ */ new Map();
3413
3455
  for (const [index, profile] of compiled.entries()) {
@@ -3450,11 +3492,14 @@ function defineBuild(input) {
3450
3492
  record(input, [
3451
3493
  "profiles",
3452
3494
  "preflight",
3453
- "resolveSecret"
3495
+ "resolveSecret",
3496
+ "outDir"
3454
3497
  ]);
3498
+ if (input.outDir !== void 0 && (typeof input.outDir !== "string" || !input.outDir.trim() || input.outDir.trim() !== input.outDir || input.outDir.includes("\0"))) throw new Error();
3455
3499
  record(input.profiles);
3456
3500
  for (const callback of [input.preflight, input.resolveSecret]) if (callback !== void 0 && typeof callback !== "function") throw new Error();
3457
3501
  return Object.freeze({
3502
+ ...input.outDir === void 0 ? {} : { outDir: input.outDir },
3458
3503
  profiles: snapshotProfile(input.profiles),
3459
3504
  ...input.preflight === void 0 ? {} : { preflight: input.preflight },
3460
3505
  ...input.resolveSecret === void 0 ? {} : { resolveSecret: input.resolveSecret }
@@ -3475,6 +3520,7 @@ function profileBuildFailure(code, validation = false, profileCount = 0) {
3475
3520
  }
3476
3521
  /** Pure orchestration result; the CLI owns stdout and process exit status. */
3477
3522
  async function runBuild(input, output, options = {}) {
3523
+ const root = process.cwd();
3478
3524
  let validation;
3479
3525
  try {
3480
3526
  record(options, ["validation"]);
@@ -3492,6 +3538,7 @@ async function runBuild(input, output, options = {}) {
3492
3538
  const profileCount = Object.keys(definition.profiles).length;
3493
3539
  const failure = (code) => profileBuildFailure(code, validation, profileCount);
3494
3540
  if (typeof output !== "string" || !output.trim()) return failure("INVALID_OUTPUT_DIRECTORY");
3541
+ output = resolve(root, output);
3495
3542
  if (validation && !definition.resolveSecret) return failure("VALIDATION_RESOLVER_REQUIRED");
3496
3543
  let codes;
3497
3544
  try {
@@ -3517,4 +3564,4 @@ async function runBuild(input, output, options = {}) {
3517
3564
  };
3518
3565
  }
3519
3566
  //#endregion
3520
- export { renderSurgeProfiles as A, validateProxyOptions as B, strategy as C, defineProfile as D, compileProfile as E, isReservedNativeName as F, nodeSchema as G, assertData as H, nativeNameSchema as I, defineProxyGroup as J, requestSchema as K, targetCatalog as L, compile as M, explain as N, compileSurgeProfile as O, compileStrategyGroups as P, selectProxies as Q, RenderError as R, slot as S, use as T, deepFreeze as U, StaticRuleSetUnknownError as V, idSchema as W, defineRoutes as X, defineRoute as Y, outbound as Z, ruleSet as _, render as a, sequence as b, direct as c, mihomo as d, policy as f, rule as g, route as h, buildToDirectory as i, secretReader as j, renderSurgeProfile as k, group as l, reject as m, profileBuildFailure as n, block as o, proxy as p, ProfileDefinitionError as q, runBuild as r, defineConfig as s, defineBuild as t, match as u, secret as v, surge$1 as w, singbox$1 as x, selectNodes as y, surgeProxy as z };
3567
+ export { renderSurgeProfiles as A, validateProxyOptions as B, strategy as C, defineProfile as D, compileProfile as E, isReservedNativeName as F, nodeSchema as G, assertData as H, nativeNameSchema as I, defineProxyGroup as J, requestSchema as K, targetCatalog as L, compile as M, explain as N, compileSurgeProfile as O, compileStrategyGroups as P, selectProxies as Q, RenderError as R, slot as S, use as T, deepFreeze as U, StaticRuleSetUnknownError as V, idSchema as W, defineRoutes as X, defineRoute as Y, outbound as Z, ruleSet as _, render as a, sequence as b, direct as c, mihomo as d, policy as f, rule as g, route as h, buildToDirectory as i, secretReader as j, renderSurgeProfile as k, group as l, reject as m, defineBuild as n, block as o, proxy as p, ProfileDefinitionError as q, runBuild as r, defineConfig as s, checkBuild as t, match as u, secret as v, surge$1 as w, singbox$1 as x, selectNodes as y, surgeProxy as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "proxylang",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Composable routing policies in TypeScript with explicit platform targets",
5
5
  "homepage": "https://github.com/CorrectRoadH/proxylang#readme",
6
6
  "bugs": {
@@ -36,8 +36,8 @@
36
36
  "check": "vp pack && vp check && vp run typecheck && vp test run",
37
37
  "docs:check": "concord check --fresh",
38
38
  "docs:gaps": "concord trace gaps --fresh",
39
- "example:check": "vp exec node dist/cli.js check examples/home.ts",
40
- "example:build": "vp exec node dist/cli.js build examples/home.ts --out out",
39
+ "example:check": "cd examples/home && vp exec node ../../dist/cli.js check",
40
+ "example:build": "cd examples/home && vp exec node ../../dist/cli.js build",
41
41
  "test:package": "vp pack && vp exec node scripts/verify-package.mjs"
42
42
  },
43
43
  "dependencies": {