sing-box-kit 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,160 @@
1
1
  import { compile } from "json-schema-to-typescript";
2
+ import type { JSONSchema } from "json-schema-to-typescript";
3
+ import {
4
+ factoryCatalog,
5
+ inputDefinition,
6
+ inputProperty,
7
+ rootSettings,
8
+ ruleActionSchemas,
9
+ ruleMatchSchema,
10
+ schemaShape,
11
+ sectionSettings,
12
+ tagReference,
13
+ targetSchema,
14
+ } from "../src/input-schema";
15
+ import type { Target } from "../src/resource";
16
+ import { definitionName } from "../src/schema";
17
+ import type { SchemaNode } from "../src/schema";
2
18
 
3
19
  const schema = await Bun.file(new URL("../schema/sing-box.json", import.meta.url)).json();
4
20
  const types = await compile({ ...schema, title: "SingBoxConfig" }, "SingBoxConfig", {
5
21
  additionalProperties: false,
6
22
  });
7
23
  await Bun.write(new URL("../src/generated/sing-box.ts", import.meta.url), types);
24
+
25
+ const definitions: Record<string, unknown> = {};
26
+ const imports = new Set<string>();
27
+ const projections = new Map<string, string>();
28
+
29
+ function typedReference(reference: string): { tsType: string } {
30
+ const entry = tagReference(reference);
31
+ const type = entry.type;
32
+ imports.add(type);
33
+ return { tsType: "allowString" in entry ? `${type} | string` : type };
34
+ }
35
+
36
+ function transform(value: unknown): unknown {
37
+ if (Array.isArray(value)) return value.map(transform);
38
+ if (!value || typeof value !== "object") return value;
39
+ const node = value as SchemaNode;
40
+ const annotation = node["x-tag-reference"];
41
+ if (typeof annotation === "string") return typedReference(annotation);
42
+ if (node.propertyNames && typeof node.additionalProperties === "object") {
43
+ const keys = schemaShape(node.propertyNames).enum;
44
+ if (keys?.every((key) => typeof key === "string")) {
45
+ const field = transform(node.additionalProperties);
46
+ return {
47
+ type: "object",
48
+ properties: Object.fromEntries(keys.map((key) => [key, field])),
49
+ additionalProperties: false,
50
+ };
51
+ }
52
+ }
53
+ const name = definitionName(node);
54
+ if (name) {
55
+ if (!Object.hasOwn(definitions, name)) {
56
+ definitions[name] = {};
57
+ definitions[name] = transform(inputDefinition(name));
58
+ }
59
+ return node;
60
+ }
61
+ return Object.fromEntries(
62
+ Object.entries(value).map(([key, item]) => [
63
+ key,
64
+ key === "properties"
65
+ ? Object.fromEntries(
66
+ Object.entries(node.properties!).map(([property, schema]) => [
67
+ property,
68
+ transform(inputProperty(property, schema)),
69
+ ]),
70
+ )
71
+ : transform(item),
72
+ ]),
73
+ );
74
+ }
75
+
76
+ function object(properties: Record<string, unknown>) {
77
+ return {
78
+ type: "object",
79
+ properties,
80
+ required: Object.keys(properties),
81
+ additionalProperties: false,
82
+ };
83
+ }
84
+
85
+ function projection(name: string, schema: SchemaNode) {
86
+ const key = JSON.stringify(schema);
87
+ let definition = projections.get(key);
88
+ if (!definition) {
89
+ projections.set(key, name);
90
+ definitions[name] = transform(schema);
91
+ definition = name;
92
+ }
93
+ return { $ref: `#/$defs/${definition}` };
94
+ }
95
+
96
+ function factoryTypes(target: Target) {
97
+ return object(
98
+ Object.fromEntries(
99
+ Array.from(factoryCatalog(target), ([kind, branches]) => {
100
+ const name =
101
+ targetSchema[target] +
102
+ kind
103
+ .split("-")
104
+ .map((word) => word[0]!.toUpperCase() + word.slice(1))
105
+ .join("");
106
+ const first = branches[0]!;
107
+ const groups: Record<string, unknown> = {
108
+ options: projection(
109
+ `${name}Options`,
110
+ branches.length > 1
111
+ ? { oneOf: branches.map((branch) => branch.options) }
112
+ : first.options,
113
+ ),
114
+ };
115
+ for (const group of ["listen", "dial", "tls"] as const) {
116
+ const settings = first[group];
117
+ if (settings)
118
+ groups[group] = definitionName(settings)
119
+ ? transform(settings)
120
+ : projection(`${name}${group[0]!.toUpperCase()}${group.slice(1)}`, settings);
121
+ }
122
+ return [kind, object(groups)];
123
+ }),
124
+ ),
125
+ );
126
+ }
127
+
128
+ const factories = Object.fromEntries(
129
+ (Object.keys(targetSchema) as Target[]).map((target) => [target, factoryTypes(target)]),
130
+ );
131
+ const sbkit = {
132
+ ...object({
133
+ factories: object(factories),
134
+ root: object(
135
+ Object.fromEntries(
136
+ Object.entries(rootSettings).map(([key, value]) => [key, transform(value)]),
137
+ ),
138
+ ),
139
+ sections: object({
140
+ route: projection("RouteSettings", sectionSettings.route),
141
+ dns: projection("DnsSettings", sectionSettings.dns),
142
+ }),
143
+ matches: object({
144
+ route: projection("RouteMatchFields", ruleMatchSchema.route),
145
+ dns: projection("DnsMatchFields", ruleMatchSchema.dns),
146
+ }),
147
+ actions: object({
148
+ route: projection("RouteActionInput", { oneOf: [...ruleActionSchemas("route").values()] }),
149
+ dns: projection("DnsActionInput", { oneOf: [...ruleActionSchemas("dns").values()] }),
150
+ }),
151
+ }),
152
+ $defs: definitions,
153
+ } as JSONSchema;
154
+
155
+ const sbkitTypes = await compile(sbkit, "SBKitInputs", {
156
+ additionalProperties: false,
157
+ bannerComment: `/* Generated by scripts/generate-schema.ts. */
158
+ import type { ${[...imports].sort().join(", ")} } from "../resource";`,
159
+ });
160
+ await Bun.write(new URL("../src/generated/sbkit-inputs.ts", import.meta.url), sbkitTypes);
package/src/compile.ts CHANGED
@@ -1,11 +1,10 @@
1
1
  import { isIP } from "node:net";
2
+ import type { SBKitInputs } from "./generated/sbkit-inputs";
3
+ import { rootSettings, sectionSettings } from "./input-schema";
2
4
  import type { SingBoxConfig } from "./generated/sing-box";
3
- import { copyJson, expandFields, fieldsFrom, ref, resourceData } from "./resource";
5
+ import { copyJson, fieldsFrom, resourceData } from "./resource";
4
6
  import type {
5
7
  DnsServer,
6
- Egress,
7
- Fields,
8
- ReadonlyJson,
9
8
  Resolve,
10
9
  Resource,
11
10
  ResourceData,
@@ -15,12 +14,10 @@ import type {
15
14
  import { checkDnsRules, expandRule } from "./rules";
16
15
  import type { RuleValue } from "./rules";
17
16
  import { fail, validateConfig } from "./schema";
18
- import { expandResolver, isEmptyDirect } from "./settings";
19
- import type { DomainResolver } from "./settings";
17
+ import { expandInput, isEmptyDirect } from "./settings";
18
+ import type { Fields, ReadonlyJson } from "./type-utils";
20
19
 
21
- export interface CompileInput {
22
- readonly log?: ReadonlyJson<NonNullable<SingBoxConfig["log"]>>;
23
- readonly experimental?: ReadonlyJson<NonNullable<SingBoxConfig["experimental"]>>;
20
+ export interface CompileInput extends Partial<ReadonlyJson<SBKitInputs["root"]>> {
24
21
  readonly inbounds?: readonly Resource<"inbounds">[];
25
22
  readonly outbounds?: readonly Resource<"outbounds">[];
26
23
  readonly endpoints?: readonly Resource<"endpoints">[];
@@ -31,15 +28,11 @@ export interface CompileInput {
31
28
  readonly route?: {
32
29
  readonly rules?: readonly RuleValue<"route">[];
33
30
  readonly rule_set?: readonly Resource<"route.rule_set">[];
34
- readonly final?: Egress;
35
- readonly default_domain_resolver?: DomainResolver;
36
- readonly default_http_client?: TaggedHttpClient;
37
- };
31
+ } & ReadonlyJson<SBKitInputs["sections"]["route"]>;
38
32
  readonly dns?: {
39
33
  readonly rules?: readonly RuleValue<"dns">[];
40
34
  readonly servers?: readonly DnsServer[];
41
- readonly final?: DnsServer;
42
- };
35
+ } & ReadonlyJson<SBKitInputs["sections"]["dns"]>;
43
36
  }
44
37
 
45
38
  type TopLevelTarget = Exclude<Target, "dns.servers" | "route.rule_set">;
@@ -52,14 +45,8 @@ const topLevelLists = [
52
45
  "certificate_providers",
53
46
  "network_namespaces",
54
47
  ] as const satisfies readonly TopLevelTarget[];
55
- const routeKeys = [
56
- "rules",
57
- "rule_set",
58
- "final",
59
- "default_domain_resolver",
60
- "default_http_client",
61
- ] as const;
62
- const dnsKeys = ["rules", "servers", "final"] as const;
48
+ const routeKeys = ["rules", "rule_set", ...Object.keys(sectionSettings.route.properties!)];
49
+ const dnsKeys = ["rules", "servers", ...Object.keys(sectionSettings.dns.properties!)];
63
50
 
64
51
  interface Registered {
65
52
  readonly value: Resource;
@@ -108,8 +95,7 @@ function checkCycles(resources: Iterable<Registered>): void {
108
95
  */
109
96
  export function compile(input: CompileInput): SingBoxConfig {
110
97
  const fields = fieldsFrom(input, "config", [
111
- "log",
112
- "experimental",
98
+ ...Object.keys(rootSettings),
113
99
  ...topLevelLists,
114
100
  "route",
115
101
  "dns",
@@ -220,53 +206,43 @@ export function compile(input: CompileInput): SingBoxConfig {
220
206
  ) {
221
207
  fail(`${path}.domain_resolver`, "hostname requires a per-server resolver or detour");
222
208
  }
223
- return expandFields(data.fields, data.references ?? {}, path, resolveFrom(entry));
209
+ const expand = data.expand ?? copyJson;
210
+ return expand(data.fields, path, resolveFrom(entry)) as Fields;
224
211
  });
225
212
  }
226
213
 
227
214
  const resolve = resolveFrom();
228
215
  const output: Fields = {};
229
- for (const key of ["log", "experimental"] as const) {
230
- if (fields[key] !== undefined) output[key] = copyJson(fields[key], key);
216
+ for (const [key, schema] of Object.entries(rootSettings)) {
217
+ if (fields[key] !== undefined) output[key] = expandInput(schema, fields[key], key, resolve);
231
218
  }
232
219
  for (const target of topLevelLists) {
233
220
  const values = emitList(target);
234
221
  if (values !== undefined) output[target] = values;
235
222
  }
236
223
  if (route) {
237
- output.route = expandFields(
238
- route,
239
- {
240
- rule_set: () => emitList("route.rule_set"),
241
- final: ref("egress"),
242
- default_domain_resolver: expandResolver,
243
- default_http_client: ref("http-client"),
244
- rules: (values, path) =>
245
- array(values, path).map((value, index) =>
246
- expandRule(value, "route", `${path}[${index}]`, resolve),
247
- ),
248
- },
249
- "route",
250
- resolve,
251
- );
224
+ const { rules, rule_set, ...settings } = route;
225
+ const result = expandInput(sectionSettings.route, settings, "route", resolve) as Fields;
226
+ if (rule_set !== undefined) result.rule_set = emitList("route.rule_set");
227
+ if (rules !== undefined) {
228
+ result.rules = array(rules, "route.rules").map((value, index) =>
229
+ expandRule(value, "route", `route.rules[${index}]`, resolve),
230
+ );
231
+ }
232
+ output.route = result;
252
233
  }
253
234
  if (dns) {
254
- output.dns = expandFields(
255
- dns,
256
- {
257
- servers: () => emitList("dns.servers"),
258
- final: ref("dns-server"),
259
- rules: (values, path) => {
260
- const rules = array(values, path).map((value, index) =>
261
- expandRule(value, "dns", `${path}[${index}]`, resolve),
262
- );
263
- checkDnsRules(rules, path);
264
- return rules;
265
- },
266
- },
267
- "dns",
268
- resolve,
269
- );
235
+ const { rules, servers, ...settings } = dns;
236
+ const result = expandInput(sectionSettings.dns, settings, "dns", resolve) as Fields;
237
+ if (servers !== undefined) result.servers = emitList("dns.servers");
238
+ if (rules !== undefined) {
239
+ const compiled = array(rules, "dns.rules").map((value, index) =>
240
+ expandRule(value, "dns", `dns.rules[${index}]`, resolve),
241
+ );
242
+ checkDnsRules(compiled, "dns.rules");
243
+ result.rules = compiled;
244
+ }
245
+ output.dns = result;
270
246
  }
271
247
  checkCycles(registrations.values());
272
248
  return validateConfig(output);