proxylang 0.11.0 → 0.13.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/dist/cli.js CHANGED
@@ -1,228 +1,269 @@
1
1
  #!/usr/bin/env node
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-BVhtmxFG.js";
3
- import { lstat, open, stat } from "node:fs/promises";
4
- import { resolve } from "node:path";
2
+ import { C as definitionDiagnostic, i as targetCatalog } from "./build-B_eJXR4E.js";
5
3
  import { pathToFileURL } from "node:url";
4
+ import { resolve } from "node:path";
5
+ import { lstat, open, stat } from "node:fs/promises";
6
6
  import { constants } from "node:fs";
7
- import { tsImport } from "tsx/esm/api";
7
+ import { register } from "tsx/esm/api";
8
+ import { register as register$1 } from "tsx/cjs/api";
8
9
  //#region src/cli.ts
9
- const print = (value) => process.stdout.write(JSON.stringify(value, null, 2) + "\n");
10
- const failure = (code) => {
10
+ let json = false;
11
+ function print(value, text) {
12
+ process.stdout.write(json ? JSON.stringify(value, null, 2) + "\n" : (text ?? human(value)) + "\n");
13
+ }
14
+ function human(value) {
15
+ if (!value || typeof value !== "object") return String(value);
16
+ if ("explanation" in value) {
17
+ const r = value;
18
+ const e = r.explanation;
19
+ return `${r.profile}: ${e.outcome}${e.exit ? " → " + e.exit : ""}${e.needs ? " needs: " + e.needs.kind + (e.needs.kind === "ruleSet" ? " " + e.needs.id : "") : ""}\n${e.trace.map((t) => ` routes[${t.index}]: ${t.matched === null ? "unknown" : t.matched ? "hit" : "miss"}${t.origin ? ` ${t.origin.file}:${t.origin.line}:${t.origin.column}` : ""}`).join("\n")}`;
20
+ }
21
+ if ("diagnostics" in value) return value.diagnostics.map((d) => `${d.code} ${d.path}`).join("\n");
22
+ if ("profiles" in value) return humanCheck(value);
23
+ if ("check" in value) {
24
+ const result = value;
25
+ return `${humanCheck(result.check)}\n${result.code}${result.secretName ? " " + result.secretName : ""}${result.hint ? "\n" + result.hint : ""}`;
26
+ }
27
+ if ("targets" in value) return value.targets.map((t) => `${t.engine} ${t.platform} ${t.version} ${t.modes.join("/")} ${t.artifact}`).join("\n");
28
+ const r = value;
29
+ return [
30
+ r.code,
31
+ r.reason,
32
+ r.hint,
33
+ r.paths?.join(", "),
34
+ r.origin ? `${r.origin.file}:${r.origin.line}:${r.origin.column}` : void 0
35
+ ].filter(Boolean).join(" ");
36
+ }
37
+ function humanCheck(check) {
38
+ return check.profiles.map((p) => `${p.ok ? "✓" : "✗"} ${p.key} ${p.target.engine} ${p.target.platform} ${p.target.version}${p.selections.flatMap((s) => s.kind === "algorithm" ? [` auto: ${s.group}→${s.algorithm}`] : s.kind === "ruleSet" ? [` ruleSets: ${s.ruleSet}→${s.branch} (${s.nativeName})`] : []).join("")}\n${p.diagnostics.map((d) => ` ${d.severity} ${d.code} ${d.path}${d.origin ? ` ${d.origin.file}:${d.origin.line}:${d.origin.column}` : ""}`).join("\n")}`).join("\n") + `\ncases: ${check.cases.filter((c) => c.ok).length} passed, ${check.cases.filter((c) => !c.ok).length} failed\n${check.cases.map((c) => ` ${c.ok ? "✓" : "✗"} ${c.profile} "${c.name}": expected ${c.expected}, ${c.actual ? "got " + c.actual : c.outcome}${c.needs ? " needs: " + c.needs.kind + (c.needs.kind === "ruleSet" ? " " + c.needs.id : "") : ""}${c.route ? ` at routes[${c.route.index}]${c.route.origin ? ` ${c.route.origin.file}:${c.route.origin.line}:${c.route.origin.column}` : ""}` : ""}`).join("\n")}\n${check.code}`;
39
+ }
40
+ function failure(code, detail = {}) {
11
41
  print({
12
42
  ok: false,
13
- code
43
+ code,
44
+ ...detail
14
45
  });
15
46
  return 1;
16
- };
17
- const usages = {
18
- targets: ["proxylang targets"],
19
- check: ["proxylang check"],
20
- explain: ["proxylang explain --target ID --request JSON", "proxylang explain --target ID --request-file FILE"],
21
- build: ["proxylang build [--validation]"]
22
- };
23
- async function readRequestFile(path) {
24
- const limit = 1048576;
25
- const file = await open(resolve(path), constants.O_RDONLY | constants.O_NONBLOCK);
26
- try {
27
- const stat = await file.stat();
28
- if (!stat.isFile()) throw new Error("REQUEST_FILE_READ_FAILED");
29
- if (stat.size > limit) throw new Error("REQUEST_FILE_TOO_LARGE");
30
- const buffer = Buffer.alloc(1048577);
31
- let size = 0;
32
- while (size < buffer.length) {
33
- const read = await file.read(buffer, size, buffer.length - size, null);
34
- if (!read.bytesRead) break;
35
- size += read.bytesRead;
36
- }
37
- if (size > limit) throw new Error("REQUEST_FILE_TOO_LARGE");
38
- return new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, size));
39
- } finally {
40
- await file.close();
41
- }
42
47
  }
48
+ const usage = [
49
+ "proxylang check [--json]",
50
+ "proxylang build [--validation] [--json]",
51
+ "proxylang explain --profile KEY (--request JSON | --request-file FILE) [--json]",
52
+ "proxylang targets [--json]"
53
+ ];
43
54
  function loadFailure(cause) {
44
55
  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
- }
55
- let code;
56
- let name;
56
+ if (diagnostic) return failure("CONFIG_LOAD_FAILED", {
57
+ reason: "INVALID_CONFIGURATION",
58
+ ...diagnostic,
59
+ code: "CONFIG_LOAD_FAILED",
60
+ hint: diagnostic.code
61
+ });
62
+ let code, name;
57
63
  try {
58
64
  if (cause && typeof cause === "object") {
59
65
  code = Object.getOwnPropertyDescriptor(cause, "code")?.value;
60
66
  name = Object.getOwnPropertyDescriptor(cause, "name")?.value;
61
- if (cause instanceof SyntaxError) name = "SyntaxError";
62
67
  }
63
68
  } catch {}
64
- print({
65
- ok: false,
66
- code: "CONFIG_LOAD_FAILED",
67
- ...code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND" || code === "ENOENT" ? {
68
- reason: "MODULE_NOT_FOUND",
69
- hint: "检查配置文件和 import 路径,并安装所需依赖"
70
- } : code === "EACCES" || code === "EPERM" ? {
71
- reason: "ACCESS_DENIED",
72
- hint: "检查配置及导入文件的读取权限"
73
- } : name === "TransformError" || name === "SyntaxError" ? {
74
- reason: "INVALID_SYNTAX",
75
- hint: "使用 TypeScript 检查配置与导入文件的语法"
76
- } : {
77
- reason: "EXECUTION_FAILED",
78
- hint: "检查默认导出、导入依赖和配置顶层执行逻辑"
69
+ return failure("CONFIG_LOAD_FAILED", { reason: [
70
+ "ERR_MODULE_NOT_FOUND",
71
+ "MODULE_NOT_FOUND",
72
+ "ENOENT"
73
+ ].includes(code) ? "MODULE_NOT_FOUND" : ["EACCES", "EPERM"].includes(code) ? "ACCESS_DENIED" : ["TransformError", "SyntaxError"].includes(name) ? "INVALID_SYNTAX" : "EXECUTION_FAILED" });
74
+ }
75
+ async function requestFile(path) {
76
+ let file;
77
+ try {
78
+ file = await open(path, constants.O_RDONLY | constants.O_NONBLOCK);
79
+ const info = await file.stat();
80
+ if (!info.isFile()) return { code: "REQUEST_FILE_READ_FAILED" };
81
+ const max = 1048576;
82
+ if (info.size > max) return { code: "REQUEST_FILE_TOO_LARGE" };
83
+ const buffer = Buffer.alloc(1048577);
84
+ let length = 0;
85
+ while (length < buffer.length) {
86
+ const { bytesRead } = await file.read(buffer, length, buffer.length - length, null);
87
+ if (!bytesRead) break;
88
+ length += bytesRead;
79
89
  }
80
- });
81
- return 1;
90
+ if (length > max) return { code: "REQUEST_FILE_TOO_LARGE" };
91
+ return { text: new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, length)) };
92
+ } catch {
93
+ return { code: "REQUEST_FILE_READ_FAILED" };
94
+ } finally {
95
+ await file?.close();
96
+ }
97
+ }
98
+ function usedRuleSets(profile) {
99
+ const used = /* @__PURE__ */ new Map();
100
+ const visit = (c) => {
101
+ if (c.type === "all" || c.type === "any") c.conditions.forEach(visit);
102
+ else if (c.type === "not") visit(c.condition);
103
+ else if (c.type === "ruleSetSource" || c.type === "ruleSet") used.set(c.id, c);
104
+ };
105
+ profile.routes.forEach((r) => visit(r.when));
106
+ return used;
82
107
  }
83
108
  async function main(args) {
109
+ json = args.includes("--json");
84
110
  const root = process.cwd();
85
- const [command, ...rest] = args;
86
- if (command === "targets" && args.length === 1) {
87
- print(targetCatalog);
111
+ const command = args[0];
112
+ const rest = args.slice(1);
113
+ const options = /* @__PURE__ */ new Map();
114
+ const flags = /* @__PURE__ */ new Set();
115
+ if (!command || (command === "--help" || command === "-h") && args.length === 1) {
116
+ process.stdout.write(usage.join("\n") + "\n");
88
117
  return 0;
89
118
  }
90
- const help = (value) => value === "--help" || value === "-h";
91
- if (!command || help(command) && args.length === 1 || Object.hasOwn(usages, command) && help(rest[0]) && rest.length === 1) {
92
- print({
93
- usage: command && Object.hasOwn(usages, command) ? usages[command] : Object.values(usages).flat(),
94
- configFile: "proxylang.config.ts",
95
- trustedConfig: true
96
- });
119
+ if ([
120
+ "check",
121
+ "build",
122
+ "explain",
123
+ "targets"
124
+ ].includes(command) && rest.length === 1 && ["--help", "-h"].includes(rest[0])) {
125
+ process.stdout.write(usage.filter((v) => v.startsWith(`proxylang ${command}`)).join("\n") + "\n");
97
126
  return 0;
98
127
  }
99
128
  if (![
100
129
  "check",
130
+ "build",
101
131
  "explain",
102
- "build"
132
+ "targets"
103
133
  ].includes(command)) return failure("INVALID_ARGUMENTS");
104
- const options = /* @__PURE__ */ new Map();
105
- let validation = false;
106
- if (command === "build") {
107
- if (rest.length === 1 && rest[0] === "--validation" || rest.length === 2 && rest[0] === "--" && rest[1] === "--validation") validation = true;
108
- else if (rest.length) return failure("INVALID_ARGUMENTS");
109
- } else if (command === "check") {
110
- if (rest.length) return failure("INVALID_ARGUMENTS");
111
- } else {
112
- for (let i = 0; i < rest.length; i += 2) {
113
- const key = rest[i];
114
- const value = rest[i + 1];
115
- if (![
116
- "--target",
117
- "--request",
118
- "--request-file"
119
- ].includes(key) || !value?.trim() || value.startsWith("--") || options.has(key)) return failure("INVALID_ARGUMENTS");
120
- options.set(key, value);
121
- }
122
- if (!options.has("--target") || options.has("--request") === options.has("--request-file")) return failure("INVALID_ARGUMENTS");
134
+ for (let i = 0; i < rest.length; i++) {
135
+ const option = rest[i];
136
+ if (option === "--json" || command === "build" && option === "--validation") {
137
+ if (flags.has(option)) return failure("INVALID_ARGUMENTS");
138
+ flags.add(option);
139
+ } else if (command === "explain" && [
140
+ "--profile",
141
+ "--request",
142
+ "--request-file"
143
+ ].includes(option)) {
144
+ const value = rest[++i];
145
+ if (!value?.trim() || value.startsWith("--") || options.has(option)) return failure("INVALID_ARGUMENTS");
146
+ options.set(option, value);
147
+ } else return failure("INVALID_ARGUMENTS");
148
+ }
149
+ if (command === "explain" && (!options.has("--profile") || options.has("--request") === options.has("--request-file"))) return failure("INVALID_ARGUMENTS");
150
+ if (command === "targets") {
151
+ print({ targets: targetCatalog.flatMap((t) => t.platforms.map((platform) => ({
152
+ engine: t.engine,
153
+ platform,
154
+ version: t.version,
155
+ modes: t.engine === "surge" ? ["standalone"] : t.engine === "stash" ? ["fragment"] : ["standalone", "fragment"],
156
+ artifact: t.engine === "surge" ? ".conf" : t.engine === "sing-box" ? ".json" : ".yaml"
157
+ }))) });
158
+ return 0;
123
159
  }
124
160
  const file = resolve(root, "proxylang.config.ts");
125
- let found = false;
126
161
  try {
127
162
  const info = await lstat(file);
128
- found = true;
129
163
  if (!(info.isSymbolicLink() ? (await stat(file)).isFile() : info.isFile())) return loadFailure({ code: "INVALID_CONFIG_FILE" });
130
- } catch (cause) {
131
- if (!found && cause && typeof cause === "object" && Object.getOwnPropertyDescriptor(cause, "code")?.value === "ENOENT") return failure("CONFIG_NOT_FOUND");
132
- return loadFailure(cause);
164
+ } catch (e) {
165
+ if (e && typeof e === "object" && Object.getOwnPropertyDescriptor(e, "code")?.value === "ENOENT") return failure("CONFIG_NOT_FOUND");
166
+ return loadFailure(e);
133
167
  }
134
- let config;
168
+ const loader = register({ namespace: "proxylang-config" });
169
+ const cjsLoader = register$1({ namespace: "proxylang-config" });
170
+ const log = console.log, info = console.info;
171
+ console.log = (...args) => console.error(...args);
172
+ console.info = (...args) => console.error(...args);
135
173
  try {
136
- const loaded = await tsImport(pathToFileURL(resolve(file)).href, import.meta.url);
137
- config = loaded.default?.__esModule === true ? loaded.default.default : loaded.default;
138
- } catch (cause) {
139
- return loadFailure(cause);
140
- }
141
- if (config && typeof config === "object" ? Object.getOwnPropertyDescriptor(config, "profiles") : void 0) {
174
+ let sdk = await loader.import("./index.js", import.meta.url);
175
+ let loaded;
176
+ try {
177
+ loaded = await loader.import(pathToFileURL(file).href, import.meta.url);
178
+ } catch (e) {
179
+ return loadFailure(e);
180
+ }
181
+ const config = loaded.default?.__esModule === true ? loaded.default.default : loaded.default;
142
182
  let definition;
143
183
  try {
144
- definition = defineBuild(config);
145
- if (definition.outDir !== void 0) definition = {
146
- ...definition,
147
- outDir: resolve(root, definition.outDir)
148
- };
184
+ definition = sdk.defineBuild(config);
149
185
  } catch {
150
- return failure("INVALID_BUILD_DEFINITION");
186
+ sdk = cjsLoader.require("./index.js", import.meta.url);
187
+ try {
188
+ definition = sdk.defineBuild(config);
189
+ } catch {
190
+ return failure("INVALID_BUILD_DEFINITION");
191
+ }
192
+ }
193
+ if (definition.outDir !== void 0) definition = sdk.defineBuild({
194
+ ...definition,
195
+ outDir: resolve(root, definition.outDir)
196
+ });
197
+ const { checkBuild, runBuild } = sdk;
198
+ if (command === "check") {
199
+ const checked = checkBuild(definition);
200
+ print(checked);
201
+ return checked.ok ? 0 : 1;
151
202
  }
152
- if (command !== "build") {
203
+ if (command === "explain") {
153
204
  const checked = checkBuild(definition);
154
- if (!checked.ok || command === "check") {
205
+ if (checked.code === "CHECK_FAILED") {
155
206
  print(checked);
156
- return checked.ok ? 0 : 1;
207
+ return 1;
208
+ }
209
+ if (!Object.hasOwn(definition.profiles, options.get("--profile"))) return failure("UNKNOWN_PROFILE");
210
+ const profileKey = options.get("--profile");
211
+ const profile = definition.profiles[profileKey];
212
+ let content = options.get("--request");
213
+ if (content === void 0) {
214
+ const read = await requestFile(resolve(root, options.get("--request-file")));
215
+ if ("code" in read) return failure(read.code);
216
+ content = read.text;
217
+ }
218
+ let input;
219
+ try {
220
+ input = JSON.parse(content);
221
+ } catch {
222
+ return failure("INVALID_REQUEST");
223
+ }
224
+ if (!input || typeof input !== "object" || Array.isArray(input)) return failure("INVALID_REQUEST");
225
+ const { ruleSets, ...request } = input;
226
+ const assume = {
227
+ hit: [],
228
+ miss: []
229
+ };
230
+ if (ruleSets !== void 0) {
231
+ if (!ruleSets || typeof ruleSets !== "object" || Array.isArray(ruleSets)) return failure("INVALID_REQUEST", { paths: ["ruleSets"] });
232
+ const used = usedRuleSets(profile);
233
+ for (const [id, hit] of Object.entries(ruleSets)) {
234
+ if (typeof hit !== "boolean") return failure("INVALID_REQUEST", { paths: ["ruleSets"] });
235
+ const ref = used.get(id);
236
+ if (!ref) return failure("ASSUMPTION_UNKNOWN_RULESET", { paths: ["ruleSets"] });
237
+ assume[hit ? "hit" : "miss"].push(ref);
238
+ }
239
+ }
240
+ try {
241
+ const result = sdk.explainProfile(profile, request, assume);
242
+ if (!result.ok) return failure(result.diagnostics[0]?.code ?? "INVALID_ASSUMPTIONS", { paths: ["ruleSets"] });
243
+ print({
244
+ ...result,
245
+ profile: profileKey
246
+ });
247
+ return result.ok ? 0 : 1;
248
+ } catch (e) {
249
+ const d = definitionDiagnostic(e);
250
+ return failure("INVALID_REQUEST", d?.paths ? { paths: d.paths } : {});
157
251
  }
158
- return failure("EXPLAIN_PROFILE_UNSUPPORTED");
159
252
  }
160
- if (definition.outDir === void 0) return failure("OUTPUT_DIRECTORY_REQUIRED");
161
- const built = await runBuild(definition, definition.outDir, { validation });
253
+ const built = await runBuild(definition, { validation: flags.has("--validation") });
162
254
  print(built);
163
255
  return built.exitCode;
256
+ } finally {
257
+ console.log = log;
258
+ console.info = info;
259
+ cjsLoader.unregister();
260
+ await loader.unregister();
164
261
  }
165
- if (validation) return failure("VALIDATION_PROFILE_REQUIRED");
166
- const result = compile(config);
167
- if (!result.ok) {
168
- print({
169
- ok: false,
170
- diagnostics: result.diagnostics,
171
- cases: result.cases
172
- });
173
- return 1;
174
- }
175
- if (command === "check") {
176
- print({
177
- ok: true,
178
- diagnostics: result.diagnostics,
179
- cases: result.cases,
180
- targets: result.plans.map((plan) => ({
181
- target: plan.target,
182
- rules: plan.rules.length,
183
- sourceMap: plan.sourceMap,
184
- strategySelections: plan.strategySelections,
185
- preconditions: plan.preconditions,
186
- nativeValidation: plan.nativeValidation
187
- }))
188
- });
189
- return 0;
190
- }
191
- if (command === "explain") {
192
- let source = options.get("--request");
193
- if (options.has("--request-file")) try {
194
- source = await readRequestFile(resolve(root, options.get("--request-file")));
195
- } catch (cause) {
196
- return failure(cause instanceof Error && cause.message === "REQUEST_FILE_TOO_LARGE" ? "REQUEST_FILE_TOO_LARGE" : "REQUEST_FILE_READ_FAILED");
197
- }
198
- let request;
199
- try {
200
- request = JSON.parse(source);
201
- } catch {
202
- return failure("INVALID_REQUEST");
203
- }
204
- const parsed = requestSchema.safeParse(request);
205
- if (!parsed.success) return failure("INVALID_REQUEST");
206
- if (!result.plans.some((plan) => plan.target.id === options.get("--target"))) return failure("UNKNOWN_TARGET");
207
- print({
208
- ...explain(result, options.get("--target"), parsed.data),
209
- diagnostics: result.diagnostics
210
- });
211
- return 0;
212
- }
213
- const outDir = Object.getOwnPropertyDescriptor(config, "outDir")?.value;
214
- if (outDir === void 0) return failure("OUTPUT_DIRECTORY_REQUIRED");
215
- const built = await buildToDirectory(result, resolve(root, outDir));
216
- print({
217
- ...built,
218
- diagnostics: result.diagnostics
219
- });
220
- return built.exitCode;
221
262
  }
222
263
  try {
223
264
  process.exitCode = await main(process.argv.slice(2));
224
- } catch (cause) {
225
- process.exitCode = failure(cause instanceof StaticRuleSetUnknownError ? cause.message : "UNEXPECTED_FAILURE");
265
+ } catch {
266
+ process.exitCode = failure("UNEXPECTED_FAILURE");
226
267
  }
227
268
  //#endregion
228
269
  export {};